Sub topic 5
Writing the agent loop yourself
This chapter assumes you can call a chat completions API, read and write JSON, and write Python functions and classes. You should also know how the SDK returns a tool call as data, as in the previous chapter. Here you will write the loop that turns a single tool call into a working agent.
What an agent loop is
An agent loop is a while loop around model calls. On each pass, the model either answers the user or asks your code to run one or more tools. If it asks for tools, your code runs them, appends the results to the conversation, and calls the model again. The loop ends when the model replies with plain text and no tool calls.
The model never runs anything itself. It only emits a structured request such as "call get_weather with {"city": "Paris"}". Your program is the executor, and it decides what is allowed to run.
The message protocol
The loop depends on the shape of the message list. With the OpenAI-style Chat Completions API, a tool round trip adds two kinds of messages:
- An assistant message that carries a
tool_callslist. Each call has anid, a functionname, andargumentsas a JSON string. - One
toolmessage per call. Each has atool_call_idmatching the call'sid, and acontentstring with the result.
You must append the assistant message exactly as the model returned it, before the tool messages. If you leave it out, or a tool_call_id has no match, the API rejects the request. Other providers use different field names, but the pattern is the same: the model's request goes into the history, then the results go in, then you call again.
A complete loop
The example below defines two tools, a registry that maps names to Python functions, and the loop. Both tools use fake data so the example runs without any other service.
import json
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
MODEL = "gpt-4o-mini"
MAX_STEPS = 5
def get_weather(city: str) -> dict:
fake = {"Paris": 18, "Tokyo": 24}
if city not in fake:
raise ValueError(f"No weather data for {city}")
return {"city": city, "temp_c": fake[city]}
def add(a: float, b: float) -> dict:
return {"result": a + b}
REGISTRY = {"get_weather": get_weather, "add": add}
TOOLS = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current temperature in Celsius for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
},
{
"type": "function",
"function": {
"name": "add",
"description": "Add two numbers.",
"parameters": {
"type": "object",
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
"required": ["a", "b"],
},
},
},
]
def run_tool(name: str, raw_arguments: str) -> str:
"""Run one tool and always return a string, even on failure."""
func = REGISTRY.get(name)
if func is None:
return json.dumps({"error": f"Unknown tool: {name}"})
try:
args = json.loads(raw_arguments)
return json.dumps(func(**args))
except Exception as err: # report the problem to the model instead of crashing
return json.dumps({"error": f"{type(err).__name__}: {err}"})
def run_agent(question: str) -> str:
messages = [
{"role": "system", "content": "Use the tools when they help. Be concise."},
{"role": "user", "content": question},
]
for step in range(MAX_STEPS):
response = client.chat.completions.create(
model=MODEL, messages=messages, tools=TOOLS
)
message = response.choices[0].message
if not message.tool_calls:
return message.content
messages.append(message) # the assistant message with tool_calls
for call in message.tool_calls:
result = run_tool(call.function.name, call.function.arguments)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": result}
)
return "Stopped: the step limit was reached before the model gave an answer."
print(run_agent("What is the temperature in Paris plus the temperature in Tokyo?"))For that question, the model will usually request both get_weather calls in a single reply, then call add on the next pass, then answer in text. That is three model calls. The loop handles this without special code because it iterates over every entry in message.tool_calls.
Design decisions inside the loop
Stop conditions
The natural stop is a reply with no tool_calls. Never rely on it alone. A model can keep requesting tools forever, for example when a tool keeps failing and the model keeps retrying with the same arguments. MAX_STEPS is a hard cap. Choose a value from the task: 3 to 5 for simple lookups, more for research-style tasks. When the cap is hit, return something explicit, or raise an exception, so the caller knows the answer is not complete.
Errors go back to the model
run_tool catches exceptions and returns them as the tool result. That lets the model see "No weather data for Atlantis" and respond sensibly, perhaps by telling the user or trying another city. Crashing the loop on every bad tool argument would make the agent brittle.
Do not return raw stack traces. They can leak file paths or secrets and they waste tokens. A short error type and message is enough.
Validate arguments
The arguments field is a JSON string written by the model. It can be malformed, miss a required field, or have the wrong type. Calling func(**args) directly means a wrong key raises a TypeError, which the example catches. For stricter checking, validate with Pydantic, as you did for structured output:
import json
from pydantic import BaseModel, ValidationError
class WeatherArgs(BaseModel):
city: str
def get_weather_checked(raw_arguments: str) -> str:
try:
args = WeatherArgs.model_validate_json(raw_arguments)
except ValidationError as err:
return json.dumps({"error": f"Invalid arguments: {err.errors()[0]['msg']}"})
return json.dumps({"city": args.city, "temp_c": 18})
print(get_weather_checked('{"city": "Paris"}'))
print(get_weather_checked('{"town": "Paris"}'))Pydantic can also generate the JSON schema for the parameters field with WeatherArgs.model_json_schema(). That removes the duplicated definition between your function signature and your tool list. This is one of the first conveniences frameworks add, and you can see how little code it takes by hand.
Security of the registry
The registry is an allowlist. Only names you put in REGISTRY can run. Never use eval, getattr on arbitrary modules, or shell execution driven by model text. Treat every argument as untrusted input, because the model may be echoing text from a web page or a user. Tools that write data, send messages, or spend money should require a confirmation step in your code, outside the model's control.
Parallel and independent calls
Models can return several tool calls in one reply. The example runs them in order, which is simple and predictable. If the tools are slow network calls and are independent, you can run them concurrently with concurrent.futures.ThreadPoolExecutor or asyncio.gather. Keep the order of the appended tool messages the same as the order of the calls, to make logs easier to read. Do not run concurrently if tools have side effects that depend on each other.
Context growth
Every pass resends the whole message list, so cost and latency rise with each step. Large tool results make this worse. Common mitigations:
- Truncate or summarize big results before returning them.
- Return only the fields the model needs.
- Drop or compress old tool messages once they are no longer relevant. Keep the pairing rule in mind: if you remove an assistant message with
tool_calls, remove its matchingtoolmessages too.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| API error about a missing tool response | The assistant message has `tool_calls`, but one call has no matching `tool` message | Append one `tool` message for every call `id` |
| API error about an unexpected `tool` message | The assistant message with `tool_calls` was not appended first | Append `message` before the results |
| `json.JSONDecodeError` | The model produced invalid JSON in `arguments` | Catch it and return an error string as the tool result |
| Loop never ends | The model repeats a failing call | Keep `MAX_STEPS`, and make error messages specific |
| `TypeError` on a tool call | The model used a wrong or extra argument name | Validate with Pydantic and return the message |
| Tool result is not accepted | `content` was a dict, not a string | Serialize with `json.dumps` |
What you have written, and what it lacks
In about 60 lines you have a working agent. It still lacks several things you may need later:
- Retries with backoff when the API returns rate-limit or server errors.
- Timeouts for each tool.
- Logging of every request and tool call, which the later chapter on observability returns to.
- Conversation memory across user turns.
- Provider portability. The message and tool schema shapes above are specific to Chat Completions.
Each of these is a reason people adopt a framework, and each can also be added by hand when you need it. That trade-off is the subject of the chapters that follow.
Exercise
In the loop above, the model asks for get_weather with the city "Atlantis", and the function raises a ValueError. What should the loop do, and why does it not just stop with an exception?
Show answer
The loop should catch the exception in run_tool, return a short JSON error string as the content of the tool message for that call id, and call the model again. The model then sees the error and can explain it to the user or try something else. Crashing would end the whole agent run over a recoverable problem. The step limit still protects against the model retrying the same failing call forever.
Exercise
A request fails because the assistant message contains two tool calls but the history has only one matching tool message. Write the fix as a change to the loop body.
Show answer
Make sure the inner for call in message.tool_calls: loop appends a tool message for every call, each with "tool_call_id": call.id. Do not break or return inside that loop, and do not skip a call when its tool fails. A failed call still gets a tool message containing the error text.