AI Agents by HandAll problemsAbout

All problems › Agent problem · easy · ~15 min

Write the tool-use loop

agent loop tool results

Solve it in your browser →

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:

  1. It calls client.messages.create with the model, max_tokens, tools=TOOLS and the running messages.
  2. While the model wants tools, it runs every tool_use block through HANDLERS and calls the model again with the results.
  3. When the model is done, it returns the final text (the text blocks joined).
  4. If a tool raises, or the model asks for an unknown tool, the loop must not crash. Send that tool_result back with is_error: True and a useful message so the model can recover.
  5. If the model is still calling tools after max_turns model calls, raise RuntimeError.

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

Starter code and hidden tests open in the editor. Nothing to install.