Building an agent loop
Under every agent framework is a simple loop. Build it yourself once and you'll understand — and debug — any agent.
Learning objectives
- Implement a bounded agent loop with error handling and tracing
- Distinguish working, scratchpad and long-term memory
- Manage context in long tasks
- Explain planning, sub-agents and skills
- Evaluate when to use a framework
- Reduce context by clearing old tool results
- Describe compaction, structured note-taking and just-in-time retrieval
Setup: the client, three tools and their Python functions (runs automatically when you press Run on any cell)
Python · setupimport anthropic, json
client = anthropic.Anthropic() # the real SDK reads ANTHROPIC_API_KEY from the environment
MODEL = "YOUR-MODEL-NAME" # copy a current model name from your provider's docs
ORDERS = {"GFY-10422": {"status": "dispatched", "eta": "Thursday"},
"GFY-10423": {"status": "delayed", "eta": "unknown"}}
REFUNDS = [] # a pretend ledger, so we can check what really happened
def get_order_status(order_id): # a real system would query a database
if order_id not in ORDERS:
return {"error": "Order not found. Check the format GFY-#####."}
return {"order_id": order_id, **ORDERS[order_id]}
def issue_refund(order_id, amount):
REFUNDS.append((order_id, amount))
return {"order_id": order_id, "refunded": amount}
def escalate_to_human(summary):
return {"ticket": "H-501", "status": "a person will reply within one hour"}
tools = [
{"name": "get_order_status",
"description": "Look up the delivery status of a customer order. Use when the customer asks where their order is.",
"input_schema": {"type": "object",
"properties": {"order_id": {"type": "string", "description": "Order number, e.g. GFY-10422"}},
"required": ["order_id"]}},
{"name": "issue_refund",
"description": "Refund money to the customer for an order. Use only when policy allows a refund.",
"input_schema": {"type": "object",
"properties": {"order_id": {"type": "string"},
"amount": {"type": "number", "description": "Amount in pounds"}},
"required": ["order_id", "amount"]}},
{"name": "escalate_to_human",
"description": "Hand the conversation to a member of staff. Use for policy exceptions, complaints or uncertainty.",
"input_schema": {"type": "object",
"properties": {"summary": {"type": "string", "description": "What the customer wants and what has been done"}},
"required": ["summary"]}},
]
TOOL_FUNCS = {"get_order_status": get_order_status, "issue_refund": issue_refund,
"escalate_to_human": escalate_to_human} # name -> Python functionEvery code block in this course is a live cell: press Run and it runs in your browser, and you can edit it and run it again. A real LLM needs a secret API key, and a key must never sit in a web page. So on these pages the cells talk to a small pretend model built into the page. It can ask for tools, read their results and reply, which is everything an agent loop needs. The code is what you'd write for the real thing (it uses Anthropic's Python SDK; OpenAI, Google and Microsoft SDKs follow the same pattern with different field names). The pretend model's decisions come from simple word-matching rules, not real AI, so it is far more predictable than a real model. To use a real one, copy the code into a notebook such as Google Colab and add your own key (see Python for AI, Module 5).
4.1 The agent loop
At its core, an agent is a loop: the model looks at the goal and everything so far, chooses an action (usually a tool call), your code executes it, the result is added to the context, and the loop repeats — until the model produces a final answer or a limit is hit. The setup cell above holds three tools from Module 2 (order status, refund, escalate) and a small table of pretend orders.
Python · a minimal, bounded agent loopdef run_agent(goal, max_steps=10):
messages = [{"role": "user", "content": goal}]
for step in range(max_steps):
r = client.messages.create(model=MODEL, max_tokens=1000, tools=tools,
system="You are a careful support agent. "
"Use tools to check facts. Stop and ask if unsure.",
messages=messages)
messages.append({"role": "assistant", "content": r.content})
if r.stop_reason != "tool_use": # the model gave a final answer
return "".join(b.text for b in r.content if b.type == "text")
results = []
for call in (b for b in r.content if b.type == "tool_use"):
try:
out = TOOL_FUNCS[call.name](**call.input)
except Exception as e: # errors go back to the model
out = {"error": str(e)}
print(f"step {step} [{r.usage.input_tokens} tokens sent]: {call.name}({call.input}) -> {out}") # trace
results.append({"type": "tool_result", "tool_use_id": call.id,
"content": json.dumps(out)})
messages.append({"role": "user", "content": results})
return "Stopped: step limit reached. Escalating to a human."
print(run_agent("Where's my order GFY-10422?"))
Three details matter: a step limit, errors returned to the model so it can recover, and a trace of every action. One tool call was enough for that question. Now give it a goal that needs a decision in the middle:
Python · the same code, two different pathsprint(run_agent("Where is order GFY-10423? If it is delayed, refund the £3.95 delivery charge."))
print()
print(run_agent("Where is order GFY-10422? If it is delayed, refund the £3.95 delivery charge."))
Same request, different order, different path. For the delayed order the agent took two steps, checking the status and then refunding; for the one that was on its way it stopped after the check. No if statement in your code made that choice: the model read the tool result and decided. That is what "dynamically directs its own process" means, and it is also exactly what you must be able to trust before letting it near a real refund button (Module 5).
Python · an error, and the step limitprint(run_agent("Where is order GFY-99999?"))
print()
print(run_agent("Where is order GFY-10423? If it is delayed, refund the £3.95 delivery charge.", max_steps=1))
The unknown order did not crash anything: the tool's error went back as a result and the model reported it. And with max_steps=1 the loop ran out of turns before the agent could answer, so the code stopped it and handed over. A limit that hands over with a clear message is far better than an agent that keeps trying.
4.2 State, memory and context
| Kind | What it holds | How |
|---|---|---|
| Working memory | The current task: goal, steps, tool results | The conversation context itself |
| Scratchpad / plan | A to-do list or notes the agent updates | A file or state object the agent reads and writes via tools |
| Long-term memory | Facts and preferences across sessions | A database or retrieval index, read and written deliberately |
Long tasks fill the context window. Techniques include summarising or trimming old tool results, storing details in files and re-reading them when needed, and handing sub-tasks to sub-agents with their own fresh context.
4.3 Planning
Asking an agent to write a short plan first — and update it as it goes — tends to improve long, multi-step work. Reasoning models do much of this internally. Either way, keep plans visible in traces so humans can understand what the agent intended.
4.4 Multi-agent systems
Some systems split work across several agents — for example an orchestrator that hands research, coding and review to specialised sub-agents, each with its own instructions, tools and context. This can help with large tasks and parallelism, but multiplies cost and makes failures harder to trace. Use it when a single agent demonstrably struggles, not by default.
4.5 Reusable skills and instructions
Agents perform better with good instructions about how to do recurring tasks. Several platforms now support packaged, reusable instructions — for example Anthropic's agent Skills, which an agent loads only when relevant. Treat them like code: version, review and test them.
4.6 Frameworks
You can build agents directly on a model API (as above) or use frameworks and platforms such as the OpenAI Agents SDK, Microsoft's agent frameworks, Google's Agent Development Kit, Amazon Bedrock's agent services, or open-source libraries. Frameworks speed up common plumbing — tool registration, tracing, hand-offs — but understand the underlying loop first so you can debug it.
4.7 Watching the context grow
Look back at the traces: each line shows how many tokens were sent on that step, and the second step always sends more than the first, because it carries the first tool call and its result. Our tools return one short line. Real tools return search results, files and web pages, and the context fills quickly. The simplest remedy is to clear out old tool results once the agent has used them:
Python · clearing old tool resultsdef size(messages): # a rough token count: about 4 characters per token
return len(json.dumps(messages, default=str)) // 4
def clear_old_results(messages, keep_last=1):
"""Replace the content of all but the most recent tool results with a short marker."""
positions = [i for i, m in enumerate(messages)
if m["role"] == "user" and isinstance(m["content"], list)]
for i in positions[:-keep_last]:
for block in messages[i]["content"]:
block["content"] = "[older tool result cleared]"
return messages
# a conversation after four steps, each tool returning a long page of text
page = "Delivery terms and conditions, paragraph after paragraph... " * 60
history = [{"role": "user", "content": "Find out which courier lost order GFY-10423 and summarise their policy."}]
for n in range(1, 5):
history.append({"role": "assistant", "content": [{"type": "tool_use", "id": f"t{n}", "name": "fetch_page",
"input": {"url": f"https://example.com/page{n}"}}]})
history.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": f"t{n}", "content": page}]})
print("before:", f"{size(history):,} tokens")
print("after: ", f"{size(clear_old_results(history)):,} tokens")
About 70% of the context disappeared, and the agent still has the page it fetched most recently plus the record that it made the earlier calls. If it needs an old page again it can fetch it again. Several model APIs now offer this kind of clearing as a built-in option.
4.8 Context engineering
Choosing what goes into the context on each step has acquired a name: context engineering. Anthropic's guidance describes the aim as finding the smallest set of high-signal tokens that gets the job done, on the grounds that a model's attention is a limited budget and every irrelevant token spends some of it. Where prompt engineering asks "what should my instructions say?", context engineering asks "of everything the agent could see right now, what should it see?". Three techniques carry most of the weight on long tasks:
| Technique | What happens | Good for |
|---|---|---|
| Compaction | When the context is nearly full, the conversation is summarised and the task continues from the summary | Long back-and-forth work where the thread matters more than the detail |
| Structured note-taking | The agent keeps a notes or to-do file outside the context and re-reads it when needed | Multi-hour tasks with milestones; surviving a compaction without losing the plan |
| Sub-agents | A sub-agent explores in its own fresh context and returns only a short summary | Research and search, where most of what is read turns out not to matter |
A related habit is just-in-time retrieval: instead of loading every document up front, give the agent lightweight references (file names, links, IDs) and tools to open them when needed, much as a person keeps a filing system instead of memorising its contents.
A classic failure is the agent calling the same tool with the same arguments again and again. Write is_stuck(calls, limit=3), which returns True when any identical (name, arguments) pair appears limit times or more.
Your turnimport json
healthy = [("get_order_status", {"order_id": "GFY-10423"}), ("issue_refund", {"order_id": "GFY-10423", "amount": 3.95})]
looping = [("get_order_status", {"order_id": "GFY-99999"})] * 4 + [("escalate_to_human", {"summary": "stuck"})]
def is_stuck(calls, limit=3):
... # True if the same (name, arguments) pair appears limit times or more
print("healthy:", is_stuck(healthy))
print("looping:", is_stuck(looping))Show a solution
import json
healthy = [("get_order_status", {"order_id": "GFY-10423"}), ("issue_refund", {"order_id": "GFY-10423", "amount": 3.95})]
looping = [("get_order_status", {"order_id": "GFY-99999"})] * 4 + [("escalate_to_human", {"summary": "stuck"})]
from collections import Counter
def is_stuck(calls, limit=3):
counts = Counter((name, json.dumps(args, sort_keys=True)) for name, args in calls)
return any(n >= limit for n in counts.values())
print("healthy:", is_stuck(healthy))
print("looping:", is_stuck(looping))Clearing everything but the newest result is aggressive. Using clear_old_results and size from section 4.7, build the four-page history again and compare the size when you keep the last one, two and three results.
Your turn# build() should return a fresh four-page history each time (clearing changes the list it is given)
# then print size(clear_old_results(build(), keep_last=k)) for k = 3, 2, 1Show a solution
def build():
page = "Delivery terms and conditions, paragraph after paragraph... " * 60
h = [{"role": "user", "content": "Summarise the courier's policy."}]
for n in range(1, 5):
h.append({"role": "assistant", "content": [{"type": "tool_use", "id": f"t{n}", "name": "fetch_page", "input": {}}]})
h.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": f"t{n}", "content": page}]})
return h
print("nothing cleared:", f"{size(build()):,} tokens")
for keep in (3, 2, 1):
print(f"keep last {keep}: {size(clear_old_results(build(), keep_last=keep)):,} tokens")Key takeaways
- The loop: decide → act → observe → repeat, until done or a limit.
- Step limits, errors returned to the model and traces are essential.
- Use files, summaries and sub-agents to manage context.
- Multi-agent systems add power and cost — use when one agent struggles.
- Learn the loop before relying on a framework.
- The model, not your code, chooses the path: the same loop took one step or two depending on a tool result.
- Context engineering: give the agent the smallest set of high-signal tokens it needs at each step.