What an Agent Is: the Loop in a Few Lines
In most programs that use a language model, the code decides everything: it sends a prompt, reads the reply and moves on to its next line. An agent hands one decision to the model: what to do next. This page explains what that means, which parts an agent is made of, how a short loop of ordinary Python gives a model that freedom, and how to tell whether a task needs it at all.
A model that chooses its next step
Picture a customer who writes: "My order 1042 has not arrived. Can I still cancel it?" To answer well, someone has to look up the order, perhaps read the cancellation rules, perhaps look up a second order the customer mentions, and only then write a reply. Which of these steps are needed, and in which order, depends on what each lookup turns up.
With tool calling, a model can ask your code to run a function, such as one that looks up an order, and read the result. An agent is a program that lets the model keep doing this: the model decides which tool to use next, sees the result, decides again, and stops when it judges the task done. The program does not know in advance how many steps there will be. Anthropic's engineering guide puts it this way: agents are "systems where LLMs dynamically direct their own processes and tool usage, maintaining control over how they accomplish tasks", and they are "typically just LLMs using tools based on environmental feedback in a loop".
The word that matters is feedback. Each tool result is a piece of ground truth from outside the model: the real status of the order, the real text of the rule. The model looks at it before it chooses the next step, so its later steps can depend on facts it did not have at the start.
The four parts of an agent
Every agent, however large, has the same four parts:
- The model reads the conversation so far and writes the next reply: either an answer, or a request to call one or more tools.
- The instructions are the system prompt: what the agent is for, what it may do and how it should behave.
- The tools are functions in your code, each described to the model by a name, a description and a JSON schema of its arguments.
- The code around them runs the loop: it calls the model, carries out the tool calls the model asks for and sends the results back.
The split of work is strict. The model never runs anything; it can only ask. Your code is the only part that touches files, data or the outside world, so it decides what is actually done with each request.
- Your code: runs the loop
- Model: decides
- Instructions
- Tools: functions
True or false?
When the model asks for a tool, the API provider runs the function and sends the result to your program.
False. The model only returns the name of a tool and its arguments. Your own code runs the function and decides what to send back.
Two agents with the same model and the same tools can behave differently because of their instructions alone.
True. The system prompt is part of what the model reads before every step, so it shapes which tools it chooses and when it decides it is done.
The agent loop
A single tool call is already a small cycle. You send a request with the tools the model may use, and the model answers with a tool call. Your code runs the function, then sends a second request that carries the result. The reply to that second request may be the final answer, or it may ask for more tools. An agent simply keeps going: as long as a reply asks for tools, it runs them and asks again.
- Call the model whole message list
- Tool calls in reply? none: return the answer
- Run every call one or several
- Append the results one tool message each
- Call the model to Tool calls in reply?
- Tool calls in reply? to Run every call: yes
- Run every call to Append the results
- Append the results to Call the model
The stop condition is in the reply itself. A reply that asks for tools carries a tool_calls list; a reply that answers carries text and no tool_calls. So the loop does not need to understand the task: it only checks whether the latest reply asks for a tool. Here is the whole loop with the openai package and the Chat Completions API, which many providers and local model servers also offer:
import json
import os
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY, and OPENAI_BASE_URL if set
MODEL = os.environ["MODEL"]
def get_order(order_id: str) -> str:
orders = {"1042": "shipped on Monday, not yet delivered"}
return orders.get(order_id, "no order with this id")
TOOLS = [{
"type": "function",
"function": {
"name": "get_order",
"description": "Look up the status of an order by its id.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}]
FUNCTIONS = {"get_order": get_order}
def run_agent(task: str) -> str:
messages = [
{"role": "system", "content": "You answer customers about their orders."},
{"role": "user", "content": task},
]
while True:
response = client.chat.completions.create(
model=MODEL, messages=messages, tools=TOOLS
)
message = response.choices[0].message
messages.append(message)
if not message.tool_calls:
return message.content
for call in message.tool_calls:
args = json.loads(call.function.arguments)
result = FUNCTIONS[call.function.name](**args)
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": result}
)A few details of this code carry the mechanism:
- The reply is appended before its results. The assistant message with its
tool_callsgoes into the list first, then one tool message per call. The order matters because each tool message names the call it answers throughtool_call_id, and that call lives in the assistant message. - Every call in the reply is run. A reply can hold zero, one or several tool calls (OpenAI's guide advises to "assume there are several"), and many providers let a model ask for several at once by default. A loop that runs only the first call leaves the others unanswered.
- The arguments are a string.
call.function.argumentsis JSON text the model wrote, so the code parses it withjson.loads. The model "does not always generate valid JSON", and it may name a tool that does not exist, so real code catches these failures instead of crashing. - A tool result is text. The content of a tool message is a string. Even a function that returns nothing needs one: a short text that says whether the action succeeded.
This loop ends only when the model stops asking for tools. Real agents also put a limit on the number of steps, enforced in code, so that a model that keeps asking cannot run forever.
True or false?
If a reply asks for two tools, the loop can run both and send both results back before calling the model again.
True. The loop appends one tool message per call, each with its own tool_call_id, and only then makes the next model call.
call.function.arguments is a Python dictionary that can be passed straight to the function.
False. It is a string of JSON generated by the model. It has to be parsed first, and it may be invalid or hold parameters the schema does not define.
The loop needs code that understands the task to know when the agent is finished.
False. The loop only checks whether the latest reply has tool calls. Deciding that the task is done is left to the model.
The transcript is the whole state of a run
The list called messages in the loop is the transcript of the run: the system prompt, the task, every reply of the model and every tool result, in order. It is more than a log. The Chat Completions API keeps nothing between requests, so the transcript is the only place where the run exists. In OpenAI's words: "you store the transcript and send the accumulated messages array on each request."
Two consequences follow. First, the model knows of its earlier steps only what the list holds: if a tool result is missing from it, then for the model that lookup never happened. Second, every call sends the whole list again, so each request is larger than the one before. Here is the transcript of a short run of two calls, with the call that first sends each message:
| # | Role | What it holds | First sent with |
|---|---|---|---|
| 1 | system | You answer customers about their orders. | call 1 |
| 2 | user | Where is my order 1042? | call 1 |
| 3 | assistant | tool_calls: get_order(order_id="1042") | call 2 |
| 4 | tool | shipped on Monday, not yet delivered | call 2 |
| 5 | assistant | Your order shipped on Monday and is on its way. | returned, not sent |
- Call 1 2 messages
- Call 2 4 messages
- Call 3 6 messages
- Call 4 8 messages
The chart follows the same run as if the model kept asking for one more lookup. Each step adds one tool call and one result, so the list grows by two messages per step. Each call is billed for its input, so a long run pays again and again for everything it has already read, and the list can approach the size of the model's context window. The tool definitions are sent with every call too, and they also count as input tokens.
True or false?
After the first call, the model remembers the system prompt, so later calls can leave it out of the list.
False. The API keeps no state between requests. Whatever is not in the list sent with a call does not exist for the model during that call.
Two runs of the same agent share nothing through the model: each starts from its own message list.
True. The transcript is created when the run starts and is the only state of that run. A new run with a new list starts with no knowledge of the old one.
Workflow or agent
Many useful programs call a model several times and still are not agents. Anthropic draws the line by who chooses the path. In a workflow, model calls follow "predefined code paths": the programmer wrote the steps and their order, and the model fills in each step. In an agent, the model chooses which step comes next.
- Classify the message
- Look up the order
- Draft a reply
- Send it
- Classify the message to Look up the order
- Look up the order to Draft a reply
- Draft a reply to Send it
- Model decides
- Look up an order
- Read a help page
- Answer
- Model decides to Look up an order
- Look up an order to Model decides: result
- Model decides to Read a help page
- Read a help page to Model decides: result
- Model decides to Answer: when done
The freedom of an agent has a price, in three forms:
- Time. Each step is a full model call, and the calls run one after another, because each depends on the result before it.
- Cost. More calls, each sending a longer transcript, means more input tokens per task.
- Compounding mistakes. A wrong choice early on, such as looking up the wrong order, becomes the ground the next steps stand on. The more steps a run takes, the more chances it has to go wrong, and nothing in a fixed path checks a choice the programmer never wrote.
The last point is easy to underestimate. Suppose, purely as an illustration, that each step of a run goes right with a fixed probability and steps fail independently. The chance that every step of an \(n\)-step run goes right is that probability to the power \(n\):
chance every step goes right (%) against steps in a run
- 99% per step
- 95% per step
Real steps are not independent, and a good agent can notice a bad result and correct course. The shape still holds: a choice that is reliable on its own becomes much less reliable when twenty of them must all go right. Anthropic sums up the trade: workflows "offer predictability and consistency for well-defined tasks", while agents fit when "flexibility and model-driven decision-making are needed".
True or false?
A program that makes four model calls in a fixed order is an agent, because it uses the model more than once.
False. The number of calls does not decide it. When the code fixes the path, it is a workflow; it becomes an agent only when the model chooses the next step.
For the same task, an agent usually takes longer and costs more than a workflow that does the job.
True. An agent spends model calls on choosing its steps, one call after another, and each call resends the growing transcript.
When a task needs an agent
The question to ask of a task is whether you can write down its steps before you see the input. If you can, the code can follow them, and a workflow or even a single model call will be faster, cheaper and easier to test. If the number and the order of the steps depend on what earlier steps discover, no fixed path covers every case, and that is where an agent earns its cost. Anthropic describes these as "open-ended problems where it's difficult or impossible to predict the required number of steps, and where you can't hardcode a fixed path."
| Task | Steps known in advance? | Simplest solution that works |
|---|---|---|
| Translate a customer message into English | Yes: one step | One model call |
| Sort each message into a category, then draft a reply from that category's template | Yes: the same steps every time | A workflow |
| Answer any customer question, looking up orders and help pages as needed | No: they depend on what each lookup shows | An agent |
So the advice is to start simple and add complexity only when it pays. Anthropic's guide recommends "finding the simplest solution possible, and only increasing complexity when needed. This might mean not building agentic systems at all." Try one well-prompted call first; if the task has fixed stages, chain them in code; reach for an agent when a fixed path keeps failing because the task really is open-ended. When you do build one, the loop above is the core of it: a few lines of your own code, which you can read, debug and change, rather than a framework that hides the prompts and replies from you.
True or false?
Summarising every support ticket of the day into one paragraph is a task that calls for an agent.
False. The steps are known in advance: collect the tickets, summarise them. A single call or a short workflow does it with less time, cost and risk.
A task whose next step depends on what the previous lookup returned is a good candidate for an agent.
True. When the path cannot be written down before the run, letting the model choose each step from the results is what an agent is for.