So far you asked the model a question and your code decided what happens next. An agent turns that around: you give the model a goal and some tools, and in a loop the model itself picks every next step until the goal is met.
One turn of the loop: your code asks the model for its next move. If the model wants a tool, your code runs it and adds the result to the messages, so the model sees it on the next turn. For another goal, "Is the mug in stock?", a run could take two turns:
turn 1 the model asks for check_stock your code runs it and sends back the result turn 2 the model answers in plain text the loop ends
Who ends the loop? The model does. While it wants a tool, reply.stop_reason is "tool_use". When it has what it needs, it answers in plain text and the stop reason is something else. Nobody knows how many turns a goal needs, so the loop has no count.
An agent decides alone, so you print a trace: the number of each step, the model's thought and the tool it called. For the goal "Find out why order 6 is late and tell the customer." your program must print:
Step 1
Thought: First I need to see the order itself.
Tool: lookup_order {'order_id': 6} -> {'id': 6, 'customer': 'Ben Ortiz', 'ordered': '2026-05-21', 'status': 'cancelled'}
Step 2
Thought: The order isn't late: it was cancelled. I'll see what was in it.
Tool: order_items {'order_id': 6} -> {'items': [{'product_id': 7, 'name': 'Stapler', 'quantity': 1}]}
Step 3
Thought: One stapler. If it is in stock, Ben can simply order it again.
Tool: check_stock {'product_id': 7} -> {'name': 'Stapler', 'stock': 15}
Step 4
Answer: Hi Ben, your order 6 isn't late: it was cancelled, so nothing was sent. The stapler you wanted is in stock (15 left), so you can order it again whenever you like.
Your task: the three tools and run_tools are ready. Store the goal in GOAL and call run_agent with it. In run_agent, write the loop: ask the model, stop when it answers, otherwise run the tool it asked for. Then number the steps and print the model's thoughts.
Assignment
Follow the Coding Tutorial to build the agent loop and print a trace of every step.
Hint
The loop is while True: and its only way out is a break when reply.stop_reason is not "tool_use". One step is one call to the model, so the answer is the last step.
Free plan: 30 tutor messages. PRO is unlimited.
