Sub topic 5
Writing the agent loop yourself
This chapter assumes you can call the chat completions API, define a tool schema as in the previous chapter, and read JSON in Python. You should also know that a tool call is returned as data and that your code runs the function.
What an agent loop is
An agent loop repeats one cycle. Send the conversation to the model. If the reply asks for tool calls, run them, append the results to the conversation, and send it again. Stop when the model replies with plain text.
The model never runs anything. It only asks. Your code owns the loop, which makes the loop easy to write and easy to get wrong.
A complete loop
This version adds a Python function for the tool, a dispatch table, and a step limit.
import json
from openai import OpenAI
client = OpenAI()
def get_weather(city: str) -> str:
# A stub. A real tool would call a weather API.
return json.dumps({"city": city, "temp_c": 18, "sky": "cloudy"})
TOOLS_BY_NAME = {"get_weather": get_weather}
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
def run_agent(question: str, max_steps: int = 5) -> str:
messages = [{"role": "user", "content": question}]
for _ in range(max_steps):
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
)
message = response.choices[0].message
if not message.tool_calls:
return message.content
messages.append(message) # the assistant turn that holds the tool calls
for call in message.tool_calls:
try:
args = json.loads(call.function.arguments)
result = TOOLS_BY_NAME[call.function.name](**args)
except Exception as err:
result = f"Error: {err}" # let the model see the failure
messages.append(
{
"role": "tool",
"tool_call_id": call.id,
"content": result,
}
)
raise RuntimeError(f"No final answer after {max_steps} steps")
print(run_agent("Is it warmer in Paris than a 15 degree day?"))Details that break loops
- Append the assistant message first. The API rejects a
toolmessage unless the assistant message with the matching tool call comes before it. - Answer every tool call. Each
tool_call_idneeds its owntoolmessage, even when a call fails. - Arguments are a JSON string. Parse them with
json.loads. The model can produce invalid JSON or the wrong argument names, so catch those errors. - Return strings. The
contentof a tool message is text. Serialize dictionaries withjson.dumps. - Cap the steps. Without
max_steps, a confused model can call tools forever and run up your bill. - Parallel calls. One reply can contain several tool calls. Loop over all of them, as the code above does.
Why this matters for the framework decision
The loop is about 25 lines. Frameworks wrap this same cycle, usually adding retries, argument validation, streaming, and tracing. Writing it once yourself shows you what they hide. It also helps you judge whether you need that help.
Exercise
In the loop above, a reply contains two tool calls, and your code answers only the first with a tool message before sending the next request. What happens, and how do you fix it?
Show answer
The API returns an error, because every tool_call_id in the assistant message must have a matching tool message. Fix it by looping over all of message.tool_calls and appending one tool message per call, even if a call failed (put the error text in content).
Exercise
Why does the loop catch exceptions from a tool and send the error text back instead of raising?
Show answer
The model can read the error and correct itself, for example by fixing a bad argument. Raising would end the whole run for a failure the model could recover from. The max_steps limit still stops repeated failures.