Interview question: "Write the loop every agent is built on: the model can call tools, and your code keeps the conversation going until it answers."
The model never runs a tool. When it needs one, its reply has stop_reason set to "tool_use" and a tool_use block with the tool's name and input. Your code runs the tool, appends the model's turn to messages, then a user turn with a tool_result for each request, and calls the model again. Any other stop reason means the model answered in text, so you return it. A cap on the number of rounds stops a model that never finishes.
The same loop with another tool: asked "Do I need an umbrella in Oslo?", a weather agent gets a tool_use for get_weather with {"city": "Oslo"}, sends back "rain" as a tool_result, and its second call answers "Yes, take one." Each tool_use needs its tool_result in the very next message, or the API refuses the request.
This lesson's script asks two questions. The first is answered after two tool calls. The second keeps asking about order 7 and hits the cap:
Tool: order_status {'order_id': 4} -> shipped
Tool: order_status {'order_id': 7} -> paid
Order 4 has shipped. Order 7 is paid but hasn't shipped yet.
Tool: order_status {'order_id': 7} -> paid
Tool: order_status {'order_id': 7} -> paid
Tool: order_status {'order_id': 7} -> paid
Tool: order_status {'order_id': 7} -> paid
Tool: order_status {'order_id': 7} -> paid
Stopped after 5 rounds without an answer.
Your task: ask_model, run_tools and the give-up line are already written. In run_agent, loop 5 rounds at most: call the model, return its text when it wants no tool, and otherwise add its turn and the tool results to messages.
Assignment
Follow the Coding Tutorial to write the tool loop in run_agent.
Hint
The text answer is in reply.content[0].text. Append the assistant turn with reply.content, then the user turn with run_tools(reply): always both, in that order.
Free plan: 30 tutor messages. PRO is unlimited.
