Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 39 ยท Getting Started

Your First Agent Loop

Write a complete agent loop in plain Python: a model stand-in that picks actions, a tool dispatcher, a message history, a step limit and a readable trace.

Time to build one. In this lesson you write the smallest complete agent: a loop that asks a "model" what to do, runs the chosen tool, feeds the result back, and stops when the model says it is done. You need no framework. Understanding this 30-line core makes every framework easier to read, because they are all variations on it.

The question our agent will answer is: "What is the population density of Norland?" It cannot know the answer by itself. It must look up two facts with a tool and then compute with a second tool.

The model here is a scripted stand-in called fake_llm. It reads the conversation and returns a JSON action, as a real model would when asked for structured output. Replacing it with an API call changes one function, not the loop.

The shape of the loop

flowchart TD
  S["messages = [goal]"] --> L{"step < max_steps?"}
  L -- no --> X["stop: limit reached"]
  L -- yes --> M["call model(messages)"]
  M --> P{"action type"}
  P -- "final" --> E["return answer"]
  P -- "tool" --> T["run tool(args)"]
  T --> R["append result to messages"]
  R --> L

One iteration: ask, check the type of action, execute, remember, repeat.

Four pieces, each simple on its own:

  1. A tool registry: a dictionary from tool name to a Python function.
  2. A model function that returns an action.
  3. A message list that records everything that happened.
  4. A loop with a hard limit.

A complete agent

Python Stand-in: a complete agent loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Trace it step by step. The loop never "knows" the plan. It only follows what the model returns. Each iteration adds two messages: the assistant's action and the tool's result, so by the third call the model can see everything that has happened.

What the real version looks like

With a real provider the shape is identical. Only the model call and the way actions are encoded differ (real APIs return structured tool-call objects rather than free JSON text, which the next chapter covers). This sketch is read-only:

Python
# Read-only sketch with a real SDK-style client
def run_agent(goal, max_steps=8):
    messages = [{"role": "user", "content": goal}]
    for _ in range(max_steps):
        reply = client.messages.create(model=MODEL, tools=TOOL_SPECS,
                                       max_tokens=1000, messages=messages)
        messages.append({"role": "assistant", "content": reply.content})
        calls = [b for b in reply.content if b.type == "tool_use"]
        if not calls:
            return reply.content[0].text          # no tool requested: final answer
        results = [{"type": "tool_result", "tool_use_id": c.id,
                    "content": str(TOOLS[c.name](**c.input))} for c in calls]
        messages.append({"role": "user", "content": results})
    raise RuntimeError("step limit reached")

Compare it with the runnable version: same registry, same transcript, same limit.

Making the trace readable

When an agent misbehaves, the first thing you want is a clear record of each step. A small logging helper pays for itself immediately. The next example adds a trace with step numbers and timing placeholders, and shows what happens when the model asks for a tool that does not exist.

Python Add a trace and survive an unknown tool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the unknown tool did not crash the program. Instead the error became an observation: text the model can read and react to. Turning failures into observations is one of the most useful habits in agent design, and tool errors and retries builds on it.

Common first-agent mistakes

  • No step limit. The first time a model repeats the same action forever, you will pay for it.
  • Trusting the model's output. json.loads raises on malformed text, and the keys may be missing. See structured outputs.
  • Forgetting to append the tool result. The model then repeats the same request, because from its view nothing happened.
  • Printing nothing. Without a trace you cannot tell a good run from a lucky one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What are the four basic pieces of the minimal agent in this lesson?

    Those four pieces are enough for a working agent. Everything else refines one of them.
  2. 2. Why is the tool result appended to the messages?

    The model is stateless. It only learns the result of an action if it is in the next request.
  3. 3. The model asks for a tool named teleport that does not exist. What is a good response?

    An error observation keeps the loop alive and gives the model the information it needs to try again.
  4. 4. What does the step limit protect against?

    A hard cap guarantees the run ends even if the model keeps asking for more actions.

Summary

  • An agent core is a tool registry, a model function, a message list and a bounded loop.
  • Each turn: ask the model, validate the action, run the tool, append the observation.
  • Errors become observations, not crashes, so the model can recover.
  • A readable trace is the main debugging tool for agents.
  • Real SDKs change the encoding of actions, not the structure of the loop.

Next: Use Cases and Limits of Agents