Topic 4 of 5 · 5 min read
Building an agent loop in plain code
Goal: Complete a minimal agent loop against a model API that executes tool calls, appends results and stops correctly.
An agent is a loop around a model call, and writing that loop yourself takes under a hundred lines. Doing it once shows you what every framework is doing, and often it is all a small project needs.
Check yourself · 1 of 3
When does a plain agent loop end normally?
The loop
- Send the messages and the tool definitions to the model.
- If the reply contains tool calls, run each tool.
- Append the model's reply and the tool results to the messages.
- Go back to step 1.
- If the reply has no tool calls, it is the final answer. Stop.
- Stop anyway when a turn limit is reached.
A minimal version
def run_agent(task, tools, max_turns=10):
messages = [{"role": "user", "content": task}]
for _ in range(max_turns):
reply = call_model(messages, tool_schemas(tools))
messages.append(reply.as_message())
if not reply.tool_calls:
return reply.text
for call in reply.tool_calls:
try:
result = tools[call.name](**call.arguments)
except Exception as err:
result = f"Tool error: {err}"
messages.append(tool_result(call.id, result))
raise RuntimeError("Turn limit reached without a final answer")
call_model wraps your provider's API. Each provider has its own message and tool-call shapes, so read its API reference for the exact fields. The loop itself is the same everywhere.
What you must add yourself
A framework gives you these for free. In plain code you decide on each:
- A turn limit and a cost cap. Without them a confused agent loops until the bill arrives.
- Error handling. Return tool errors to the model as text so it can recover, and retry network failures with backoff.
- Argument validation. The model can send a wrong type or an invented parameter.
- Permissions. Which tools can run without a human, and which need approval.
- Logging. Write every request, reply and tool result to a file.
- Context management. Long runs fill the context window, so trim or summarise old results.
- Parallel tool calls. A reply can contain several calls. Run them all and return a result for each.
Before and after
Weak loop: it runs only the first tool call in a reply, never appends the model's own message, and has no turn limit. Some providers reject the next request because a tool result has no matching call, and others loop forever.
Fixed loop: append the model's full reply first, run every call, return one result per call, and stop at a limit.
What goes wrong
- Dropping the assistant message. The tool results need the call they answer in the history.
- Treating any text as the end. Stop on "no tool calls", not on the word "done".
- Swallowing errors. If a tool fails and you return nothing, the model guesses.
- Letting arguments run unchecked. A tool that deletes files must validate paths before it runs.
Examples
Spot the missing line
for _ in range(10):
reply = call_model(messages, schemas)
if not reply.tool_calls:
return reply.text
for call in reply.tool_calls:
result = tools[call.name](**call.arguments)
messages.append(tool_result(call.id, result))
The loop never appends reply to messages. The next request contains tool results whose calls are missing from the history, which many APIs reject and others answer badly. It also runs tools with no error handling. Add the assistant message first and wrap the call in try and except.
Where the stop condition goes
An agent ends when the reply has no tool calls, or when max_turns is reached. A team stopped on the text "DONE" instead. The model once wrote "Not done yet, checking the file" and the loop ended early. Stopping on the structure of the reply is safer than stopping on its words.
Key points
- The loop sends messages and tools, runs requested tool calls, appends results and repeats until the reply has no tool calls.
- Always append the model's own message before the tool results so each result matches its call.
- Add a turn limit, a cost cap and logging from the start, because a plain loop has none of them.
- Return tool errors to the model as text so it can recover instead of crashing the run.
- Run every tool call in a reply and return one result for each.
Common mistakes
- Forgetting to append the model's reply before the tool results.
- Stopping when the text contains a keyword instead of when there are no tool calls.
- Shipping without a turn limit or a spending cap.
- Crashing on a tool exception instead of returning the error to the model.
Check yourself · 2 of 3
Why do you append the model's own reply to the messages before the tool results?
Check yourself · 3 of 3
A tool raises an exception in your loop. What is the best handling?
Practice items, not counted towards your mastery.
Start here
- Agent SDK overview (Claude docs) (opens in a new tab)DocsFree
The built-in tools, sessions, hooks and subagents of Anthropic's agent SDK.
- OpenAI Agents SDK (opens in a new tab)DocsFree
Agents, handoffs, guardrails and tracing as the SDK defines them.
- LangGraph overview (opens in a new tab)DocsFree
Graph-based orchestration with durable state, checkpoints and human-in-the-loop.
More for this topic
- OpenAI API reference (opens in a new tab)DocsFree
The raw request and response shapes you call when you skip a framework.
- Building effective agents (Anthropic) (opens in a new tab)ArticleFree
Advice to start with plain API calls and warns that frameworks can hide prompts and responses.