Tool-calling agent loop
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Write run_agent(client, tools, task, max_steps=10): the loop at the heart of every tool-calling agent. It sends the user's task to a chat model together with the tools it may use, runs the tools the model asks for, sends their results back, and repeats until the model gives a final answer, which run_agent returns.
The starter code makes one model call and returns whatever comes back. That works only when the model answers straight away.
The model API
The client is a scripted stand-in for a real chat API (OpenAI-style messages), so every run is deterministic and needs no API key. It rejects bad requests the way a real API does, with an APIError.
response = client.chat(messages, tools=[tool.schema for tool in tools])
response.content # str | None: the model's text
response.tool_calls # list[ToolCall], empty when the model is done
response.message # the assistant message to append to `messages`
call.id, call.name, call.arguments # a ToolCall; arguments is a dict
tool.name, tool.schema # a Tool; tool(**arguments) runs itMessages are dicts. The conversation starts with {"role": "user", "content": task}, and each tool result is sent as:
{"role": "tool", "tool_call_id": call.id, "content": "<the result, as a string>"}Part 1: the loop
- Pass every tool's schema on every call.
- When the reply has tool calls, append the reply (
response.message), run each tool with its arguments, append one tool message per call, and call the model again. - The model has no memory between calls: send the whole conversation each time.
- When the reply has no tool calls, return its
content.
Part 2: tools fail
A failing tool must not crash the agent. Turn the failure into a tool result that says what went wrong, so the model can recover:
- The tool raises an exception: send its message back.
- The model asks for a tool that doesn't exist: say so, and name the tool.
- The model passes wrong arguments (calling the tool raises a
TypeError): send the error back, so the model can fix its call. - A tool returns something that isn't a string, like a dict: tool results must be strings, so serialize it.
Part 3: limits and edge cases
- The model can ask for several tools in one reply. Every one of them needs a result before the next model call.
- A reply can have both text and tool calls ("Let me check..."). It isn't the final answer: run the tools.
max_stepsis the most model calls one run may make. If the model still wants tools after that many calls, raiseMaxStepsExceeded(already defined, no import needed).
Note
Run plays the scenarios in tests.json, which you can edit: each one scripts the model's replies and the tools' results. Submit runs all the hidden scenarios. The Trace tab shows every request your code sent and every tool it ran.
Follow-up questions interviewers ask
- The conversation grows with every step. How do you keep it inside the context window, and what does that cost per call?
- Two tool calls in one turn are independent. How would you run them in parallel, and what changes in the loop?
- A tool sends emails or moves money. Where do you add a human approval step?
- The model keeps calling the same tool with the same arguments. How do you detect the loop and stop it earlier than
max_steps? - How would you stream the final answer to the user while keeping this loop?
The approach
An agent is a for loop around a chat call. The model never runs anything itself: it only asks for tool calls, and your code decides what runs and what the model sees next. Each turn:
- Call the model with the whole conversation and every tool schema.
- Append its reply to the conversation, whatever it contains.
- No tool calls: the reply is the answer. Return it.
- Otherwise run each call and append one
toolmessage per call, linked bytool_call_id.
The loop is bounded by max_steps, and falling out of it raises MaxStepsExceeded.
Why the conversation has this shape
Chat APIs are stateless: the model only knows what is in messages on this call. That is why you append the assistant message before its tool results. Each tool message points at a call id the assistant message announced, and a real API returns a 400 if a result has no matching call, or if a call has no result by the next request. The Trace tab shows the conversation growing by one assistant message and one tool message per call, on every step.
Errors are results, not exceptions
run_tool never raises. A missing tool, bad arguments and a crashing tool all become text such as Error: TypeError: get_weather() got an unexpected keyword argument 'location'. That is the point: the model reads the error, and in the bad-arguments scenario it fixes its own call on the next turn. If the exception escaped instead, one bad call would end the whole run.
Catch Exception, not BaseException, so KeyboardInterrupt and the like still stop the program. Results that aren't strings go through json.dumps, which the model reads more reliably than Python's repr.
Limits
for _ in range(max_steps) counts model calls, the expensive part. A model that keeps asking for tools can't run up an unbounded bill, and raising instead of returning None lets the caller tell "gave up" apart from a real answer.
The traps
- Returning when
contentis set. A reply can say "Let me check..." and ask for a tool at the same time. Decide bytool_calls, never bycontent. - Calling the model after one tool result. In a parallel turn, every call needs its result first.
- Rebuilding
messageseach turn. Anything you drop, the model has forgotten. - Different tools on each call. Keep the schema list the same on every step.
Complexity
Each step resends the whole conversation, so the input tokens of step k grow with k, and a run of n steps costs O(n²) input tokens in total. That is why production agents cap steps, trim or summarize old tool results, and use prompt caching for the stable prefix.
Reference solution
import json
def run_agent(client, tools, task, max_steps=10):
tools_by_name = {tool.name: tool for tool in tools}
schemas = [tool.schema for tool in tools]
messages = [{"role": "user", "content": task}]
for _ in range(max_steps):
response = client.chat(messages, tools=schemas)
messages.append(response.message)
if not response.tool_calls:
return response.content
# Every call in this turn gets a result before the model is called again.
for call in response.tool_calls:
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": run_tool(tools_by_name, call),
})
raise MaxStepsExceeded(f"No final answer after {max_steps} model calls")
def run_tool(tools_by_name, call):
"""A tool's result as text. Failures become text too, so the model can recover."""
tool = tools_by_name.get(call.name)
if tool is None:
available = ", ".join(tools_by_name)
return f"Error: there is no tool named '{call.name}'. Available tools: {available}"
try:
result = tool(**call.arguments)
except Exception as error:
return f"Error: {type(error).__name__}: {error}"
return result if isinstance(result, str) else json.dumps(result)