Write the loop that runs a tool-calling agent
An AI agent is a loop: ask the model what to do, run the tool it asks for, show it the result, repeat until it gives a final answer. Most agent bugs live in this loop, not in the model.
Write run_agent(model, tools, question, max_steps=5).
- model(messages) returns either {"tool": name, "args": {...}} or {"final": text}.
- tools is a dict mapping tool names to Python functions.
- Start with messages = [{"role": "user", "content": question}].
- Each step: call model(messages). If it returned "final", return that text. Otherwise run tools[name](**args), then append {"role": "assistant", "content": str(call)} and {"role": "tool", "content": str(result)} to messages and loop.
- If the model asks for a tool that does not exist, append {"role": "tool", "content": "error: unknown tool NAME"} (with the real name) instead of crashing, and keep going.
- If max_steps model calls pass with no final answer, return "stopped: max steps".
def run_agent(model, tools, question, max_steps=5)Understand the idea
A tool-calling agent is just a loop around a model. Each turn the model either asks for a tool or gives a final answer. If it asks for a tool, you run it, write both the request and the result into the message list, and ask again. Like a manager asking an assistant to look things up until the manager can answer. Two safety rules: an unknown tool name becomes an error message the model can read, not a crash, and a step limit stops endless loops. Worked trace with max_steps = 3: call 1 returns a tool call for add(2, 3), result 5, so 2 messages are appended (assistant then tool). Call 2 returns a final answer, so you return it after 2 model calls. If instead all 3 calls ask for tools, you return 'stopped: max steps'. Rule: count model calls, not tool runs; check 'final' first; append the call then its result. Every agent framework, from coding agents to browser agents, is built on this loop.