Write the agent loop (~15 min)
agent_loop.py defines two tools (get_temperature, c_to_f) and their schemas, but run_agent is a stub.
Implement run_agent(prompt, client=None, max_turns=10) -> str so that:
- It calls
client.messages.createwith the model,max_tokens,tools=TOOLSand the runningmessages. - While the model wants tools, it runs every
tool_useblock throughHANDLERSand calls the model again with the results. - When the model is done, it returns the final text (the text blocks joined).
- If a tool raises, or the model asks for an unknown tool, the loop must not crash. Send that
tool_resultback withis_error: Trueand a useful message so the model can recover. - If the model is still calling tools after
max_turnsmodel calls, raiseRuntimeError.
Tool results go back as strings. Think about what the API expects when the model asks for several tools in a single turn.
Try it: python -m agent_loop
Check it: pytest tests/test_agent_loop.py