Your First Agent Loop
After this lesson, you will be able to:
- Read a tool as an ordinary Python function with a name and inputs
- Follow a hand trace of an agent run and predict what the program will print
- Read the loop: choose an action, use a tool, write the result down, repeat
- Explain why a step limit is part of every agent loop
- Say which part of the code a real language model would replace
#From Paper to Program
Last lesson's agent ran in rounds: think, act, observe. A program can do the same with a loop. In words, it looks like this:
- Start with an empty notebook.
- Ask the brain, "Given the goal and the notebook, what do you do next?"
- If the brain says it is finished, stop and give the answer.
- Otherwise use the tool the brain named, with the inputs it gave.
- Write the tool's result in the notebook.
- If you have used up the step limit, stop. Otherwise go back to step 2.
That is the whole shape. Every agent you will meet, however large, repeats this shape. What changes is how clever the brain is and how many tools it has.
In this lesson the brain is not a language model. It is a small function of plain rules that looks at the notebook and picks the next action. That is honest, and it is useful: you can see exactly why each choice was made. In the real version a language model makes the choice by reading text.
In one sentence: an agent is a loop that asks the brain for an action, uses a tool, writes down the result, and stops when the brain says it is done or the step limit is reached.
#Tools Are Just Functions
The prices are made up for the exercise, so the numbers carry no meaning outside it.
price for an item that is not in the list, it does not crash. It sends back a short message that starts with "error". The agent reads that message like any other observation, and the brain can react to it.In one sentence: a tool is a plain function, and a good tool answers a bad request with a short error message instead of crashing.
#Hand Trace Before Code
Here is the job. The goal is: "Find the cost of 3 notebooks and 2 pens, and say whether it fits a budget of 100." Before you look at any code, work out what the loop will do. The brain follows these rules: look up any price it does not yet know, then use the calculator, then answer.
| Round | Notebook so far | Brain chooses | Tool result |
|---|---|---|---|
| 1 | empty | price(notebook) | 30 |
| 2 | notebook = 30 | price(pen) | 10 |
| 3 | notebook = 30, pen = 10 | total(30, 3, 10, 2) | 30 x 3 + 10 x 2 = 110 |
| 4 | all three results | finish | no tool used |
At round 4 the cost is 110 and the budget is 100, so the answer says the order is 10 over. Count: 4 rounds and 3 tool calls.
Using the table, what will the final answer say?
In one sentence: trace the rounds on paper first, because then the program's output is something you predicted and not something you hope for.
#Run the Loop
run_agent. In run_agent the three comments THINK, ACT and OBSERVE mark the same three parts you traced by hand. The notebook is a list that grows by one entry per round, and max_steps is the step limit.Press Run. The output should match your trace.
Tests · Run the script. It should print four lines: price(notebook) -> 30, price(pen) -> 10, total(30, 3, 10, 2) -> 110, then 'Total is 110. That is 10 over the budget of 100.' and finally 'All checks passed'. With max_steps=2 you should see only the two price lines followed by the stop message. The brain here is a few fixed rules, a stand-in for a language model.
Do: Run the cell once. Then change the budget to 120 and run it again. Last, callrun_agent(goal, max_steps=2).Notice: With the larger budget the same four rounds happen and only the last sentence changes. With a step limit of 2 the loop stops before the calculator is used and prints the stop message.Why: The notebook is what lets the brain choose a different next step each round. The step limit is what stops the loop even when the goal is not met. The brain here is fixed rules, not a trained model.
result = f"error: no tool called {name}" would catch it. The error goes in the notebook like any other result. That is how real agents recover from a mistyped tool name.In one sentence: the whole agent is one short program, and the three marked comments are the same think, act, observe you traced on paper.
#A Real Brain in the Same Loop
brain function. Instead of rules, it sends the goal, the notebook and a description of the tools to a language model. The model replies in a form a program can read, a tool call, which is the name of one tool and the inputs to give it. The loop then runs that tool and sends the result back to the model.The picture below shows one such exchange. It uses made-up sample data and fixed scripts, not a live model.
Do: Pick the Code Executor scenario. Press Step and read each stage's panel before moving on.Notice: The model never runs the tool itself. It writes a tool call, the program runs it, and the result goes back to the model as a new message. Then the model writes the final answer.Why: This is the same think, act, observe loop with the brain replaced by a model. Drawn stand-in with sample data, not a live model.
claude-sonnet-5-5. Model names change often, so check the provider's documentation for a current one before you run it.# Copy to Colab (needs the anthropic package and a secret key; it cannot run in the browser)
# The same two tools and the same loop, with a language model as the brain.
import anthropic
client = anthropic.Anthropic() # reads the key from the ANTHROPIC_API_KEY setting
MODEL = "claude-sonnet-5-5" # model names change, check the docs for the current one
PRICES = {"notebook": 30, "pen": 10, "ruler": 15}
def price(item):
return PRICES.get(item, f"error: no item called {item}")
def total(price_a, qty_a, price_b, qty_b):
return price_a * qty_a + price_b * qty_b
TOOLS = {"price": price, "total": total}
tool_descriptions = [
{
"name": "price",
"description": "Look up the price of one item by name.",
"input_schema": {
"type": "object",
"properties": {"item": {"type": "string"}},
"required": ["item"],
},
},
{
"name": "total",
"description": "Cost of two order lines: price_a * qty_a + price_b * qty_b.",
"input_schema": {
"type": "object",
"properties": {
"price_a": {"type": "number"}, "qty_a": {"type": "number"},
"price_b": {"type": "number"}, "qty_b": {"type": "number"},
},
"required": ["price_a", "qty_a", "price_b", "qty_b"],
},
},
]
goal = "Find the cost of 3 notebooks and 2 pens, and say whether it fits a budget of 100."
messages = [{"role": "user", "content": goal}]
for step in range(1, 7): # the step limit
reply = client.messages.create(
model=MODEL, max_tokens=1024, tools=tool_descriptions, messages=messages
)
messages.append({"role": "assistant", "content": reply.content})
if reply.stop_reason != "tool_use": # the model is finished
print(reply.content[0].text)
break
results = []
for block in reply.content:
if block.type == "tool_use":
output = TOOLS[block.name](**block.input) # ACT: run the tool
results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(output)})
messages.append({"role": "user", "content": results}) # OBSERVE: send the result back
else:
print("stopped: step limit reached before the goal was met")Compare the two versions. The tools are identical. The loop is the same shape with the same step limit. Only the line that decides the next action moved from rules to a model.
In one sentence: a real agent keeps the same loop and the same tools and swaps the rule-based brain for a language model.
#When the Loop Goes Wrong
Because the loop is now code, you can see exactly where it can go wrong, and where to guard it.
- No step limit. Delete
max_stepsand a confused brain could loop for ever. Every real agent has one, and a good one tells the user it stopped. - A tool crashes. A tool that raises an error would end the run with nothing. Return an error message as the result instead.
- The notebook is ignored. If the brain did not read the notebook, it would ask for the same price again and again. The notebook only helps if the brain reads it each round.
- Too much power. The tools here only read prices. A tool that sends money or deletes files needs a person to approve each use, because the loop will use whatever tools you give it.
In one sentence: guard every agent with a step limit, polite tool errors and a printed trace of each round.
#Where to Go Next
You can now read an agent loop and run one. Pick the next lesson that matches your goal.
- Next, the standard story: Agent Fundamentals, which covers the loop, the spectrum from chatbot to agent, and the reasoning-then-acting pattern.
- How a model asks for a tool: Tool Use and Function Calling, which explains tool descriptions and tool calls in detail.
- Go back a step: AI Agents: Start Here if the five parts still feel new.
- Python first: if the code in this lesson felt fast, start with Python Setup and the Python track from the beginning.
In one sentence: read Agent Fundamentals next, and keep this lesson's cell open to try each new idea in it.
A named recipe in code: you give it inputs and it gives back a result.
A function an agent is allowed to use, such as a price lookup or a calculator.
A lookup table in Python, with names on the left and values on the right.
The list of every action and result so far, which the brain reads before choosing again.
The name of one tool and the inputs to give it, written by the brain in a form a program can read.
A number that stops the loop after that many rounds, even if the goal is not met.
A simple piece of code used in place of a real model so the loop can be seen and tested.
#Key Takeaways
- An agent loop asks the brain for an action, uses a tool, writes the result in the notebook and repeats
- A tool is an ordinary function, and a good tool returns a short error message instead of crashing
- Trace the rounds on paper first, then run the code and compare
- A step limit stops the loop even when the goal is not met, so every agent needs one
- A real agent swaps only the brain for a language model; the tools and the loop stay the same
#Quick Check
In the loop, what does the notebook let the brain do?