Back to all articlesAI & Agents

Build an AI Agent Loop From Scratch (Part 1)

Most explanations of AI agents stop at a diagram: a box labelled LLM, an arrow to a box labelled Tools, and a loop drawn around them. That picture is not wrong, but it hides every decision that actually matters. What exactly is in the context at step 4? What happens when the model asks for a tool that does not exist? How do you stop an agent that has decided to keep going forever? Those questions are where real agents succeed or fail.

This tutorial builds the smallest agent loop that is still honest. No framework, no SDK, no API key required. By the end you will have a loop that runs, calls tools, recovers from malformed decisions, respects a step budget, and produces a trace you can inspect. Every later part of this series extends this exact file, so read the code rather than skimming it.

What you’ll build

A research-agent with a single entry point, AgentLoop.run(goal), that returns a final answer. Part 1 gives it four capabilities:

  • A typed message model so the context has explicit structure instead of concatenated strings.
  • A tool registry where tools are the only place side effects are allowed.
  • A decision cycle that turns a model response into either a tool call or a final answer.
  • Stop conditions and error recovery so a confused model cannot hang or crash the process.

The code is deliberately dependency-free. The LLM is an injectable interface, and the default implementation is a deterministic scripted stand-in. That means you can run and test the entire loop offline, then swap in a real HTTP client later without changing the loop.

Prerequisites

  • Python 3.10 or newer (the code uses str | None union syntax and dataclasses).
  • No third-party packages. Everything uses the standard library.
  • Familiarity with JSON and basic Python. You do not need to know any agent framework.
  • This is Part 1 of the series; there is no prior code to fetch. Part 2 replaces the ad-hoc tool functions here with validated contracts, and Part 3 adds a context budget.

A note on scope: the calculate tool below uses eval with a restricted character set. That is a teaching shortcut, not a security boundary. Part 11 replaces it with a real sandbox. Keeping the insecure version visible is intentional — it gives us a concrete failure mode to fix later instead of pretending the problem away.

The anatomy of a loop, not a diagram

An agent loop is a state machine with one state: a list of messages. Each iteration does three things:

  1. Observe — hand the current message list to the model, together with the tool specifications.
  2. Decide — parse the response into a structured decision: call a tool, or finish.
  3. Act — if it is a tool call, execute it and append the result as a new message; if it is final, return.

The critical design choice is that the model never executes anything. It emits a description of an action; the loop owns execution. This single boundary is what makes permissions, logging, retries, and budgets implementable — all of which live on the loop side, not inside the prompt.

The second choice is that tool results go back into the message list. This is why the loop converges: each step sees what the previous action produced, so the model can correct itself. If you discard results, you do not have an agent; you have a one-shot classifier with extra steps.

Here is the message model. Note that role="tool" carries a name, because with several tools the model must know which call a result belongs to.

from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable
import json
@dataclass
class Message:
role: str # "system" | "user" | "assistant" | "tool"
content: str
name: str | None = None # tool name, required when role == "tool"
@dataclass
class ToolResult:
ok: bool
data: str
error: str | None = None
def to_message(self, name: str) -> Message:
payload = self.data if self.ok else "ERROR: " + (self.error or "unknown")
return Message(role="tool", content=payload, name=name)

ToolResult is doing more work than it looks. Every tool, success or failure, returns the same shape. That uniformity is what lets the loop handle errors generically — it never needs to know which tool failed or why. Notice also that failures become content, not exceptions: an error string is appended to the history so the model can read it and adapt. Swallowing the error would hide it; raising it would kill the run.

Tools as the only side effects

A tool here is a name, a description, a JSON Schema for its arguments, and one callable. The spec() method produces the description sent to the model. Keep these two things in sync: a vague description causes wrong calls more often than a weak model does.

@dataclass
class Tool:
name: str
description: str
parameters: dict[str, Any] # JSON Schema
_fn: Callable[[dict], ToolResult]
def spec(self) -> dict:
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
},
}
def run(self, args: dict) -> ToolResult:
return self._fn(args)

Two concrete tools for our research agent. The search tool is a deterministic stand-in for a retrieval backend; the calculator evaluates arithmetic. Both return ToolResult, never raw values, and neither prints or mutates global state.

def _search(args: dict) -> ToolResult:
query = str(args.get("query", "")).lower()
corpus = {
"agent loop": "An agent loop repeats: observe, decide, act, observe.",
"token budget": "Context windows are finite; budget them explicitly.",
"stop condition": "A step limit is a stop condition, not a strategy.",
}
hits = [v for key, v in corpus.items() if key in query]
return ToolResult(ok=True, data=json.dumps(hits or ["no matches"]))
def _calculate(args: dict) -> ToolResult:
expr = str(args.get("expression", ""))
allowed = set("0123456789+-*/(). ")
if not expr or not set(expr) <= allowed:
return ToolResult(ok=False, data="", error="illegal characters in expression")
try:
value = eval(expr, {"__builtins__": {}}, {})
except Exception as exc:
return ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc))
return ToolResult(ok=True, data=str(value))
def build_tools() -> list[Tool]:
return [
Tool(
name="search",
description="Search the local research corpus. Returns a JSON list of matching passages.",
parameters={
"type": "object",
"properties": {"query": {"type": "string", "description": "keywords to look for"}},
"required": ["query"],
},
_fn=_search,
),
Tool(
name="calculate",
description="Evaluate a pure arithmetic expression. No variables, no functions.",
parameters={
"type": "object",
"properties": {"expression": {"type": "string", "description": "e.g. 17 * (3 + 4)"}},
"required": ["expression"],
},
_fn=_calculate,
),
]

The character whitelist in _calculate is the whole safety story for now, and it is thin. It blocks __import__ and attribute access, but it does not bound runtime: an expression like 9**9**9 is legal characters and will happily burn CPU. We will replace this with a proper parser and a timeout in Part 11. The point of showing it now is to make the limitation measurable rather than abstract.

The loop itself

The LLM is an interface with one method, complete(messages, tools). It returns a plain dict, which we treat as a decision. Defining a narrow interface is what makes the loop testable: the tests below inject a scripted model and assert on loop behaviour, with no network and no nondeterminism.

class LLMClient:
def complete(self, messages: list[Message], tools: list[dict]) -> dict:
raise NotImplementedError
class ScriptedLLM(LLMClient):
"""Replays a fixed list of decisions. Used for offline tests and demos."""
def __init__(self, script: list[dict]):
self.script = list(script)
self.calls: list[list[Message]] = []
def complete(self, messages: list[Message], tools: list[dict]) -> dict:
self.calls.append(list(messages))
if not self.script:
return {"type": "final", "content": "no scripted decision left"}
return self.script.pop(0)

Two decision shapes are supported: {"type": "tool", "name": ..., "arguments": {...}} and {"type": "final", "content": ...}. A real client would parse a model’s function-calling response into exactly this shape. Keeping the loop dependent on the shape, not on any vendor’s response format, is what lets you change providers without touching control flow.

Now the loop. Read the guards carefully; they are the substance of the tutorial.

SYSTEM = (
"You are a research agent. Use the provided tools to gather evidence, "
"then answer with a final decision. Do not claim facts you did not retrieve."
)
class AgentLoop:
def __init__(self, llm: LLMClient, tools: list[Tool], max_steps: int = 8):
self.llm = llm
self.tools = {t.name: t for t in tools}
self.specs = [t.spec() for t in tools]
self.max_steps = max_steps
self.trace: list[dict] = []
def run(self, goal: str) -> str:
history = [
Message(role="system", content=SYSTEM),
Message(role="user", content=goal),
]
for step in range(self.max_steps):
decision = self.llm.complete(history, self.specs)
self.trace.append({"step": step, "decision": decision})
kind = decision.get("type")
if kind == "final":
return str(decision.get("content", ""))
if kind != "tool":
return "aborted: malformed decision " + repr(decision)
name = str(decision.get("name", ""))
args = decision.get("arguments", {})
if not isinstance(args, dict):
args = {}
tool = self.tools.get(name)
if tool is None:
# Do not crash. Turn the mistake into context so the model can recover.
result = ToolResult(ok=False, data="", error="unknown tool: " + name)
else:
try:
result = tool.run(args)
except Exception as exc:
# A tool raising is a bug, not a reason to end the run.
result = ToolResult(ok=False, data="", error=type(exc).__name__ + ": " + str(exc))
history.append(result.to_message(name))
return "aborted: step limit reached"

Four decisions here are worth stating explicitly, because each is a place where naive implementations break:

  • max_steps is a hard ceiling. Without it, a model that keeps requesting tools runs until something external times out. Eight is a starting value; production agents usually set a token budget as well (Part 3).
  • Unknown tools become error messages, not exceptions. The model is then told, in its own context, that it asked for something that does not exist. In practice a single such message is often enough for it to pick a valid tool on the next step.
  • Tool exceptions are caught and converted with the same mechanism. A broken tool degrades one step instead of killing the process.
  • Every decision is recorded in trace before being acted on. This gives you a replayable record. Part 9 turns this into structured tracing; Part 10 uses it as an evaluation fixture.

The loop does not append an assistant message for tool calls. Many implementations do. Omitting it is a deliberate simplification for Part 1: the decision is already in trace, and skipping it avoids duplicating large argument payloads into the context. Part 3 revisits this when we start budgeting tokens.

A runnable end-to-end example

This script runs with no network and no key. It uses a scripted model that first searches, then answers.

def demo() -> None:
script = [
{"type": "tool", "name": "search", "arguments": {"query": "agent loop"}},
{"type": "final", "content": "An agent loop repeats: observe, decide, act, observe."},
]
agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=5)
answer = agent.run("Explain the agent loop in one sentence.")
print("ANSWER:", answer)
print("TRACE:", json.dumps(agent.trace, indent=2))
if __name__ == "__main__":
demo()

Expected output (abridged):

ANSWER: An agent loop repeats: observe, decide, act, observe.
TRACE: [
{"step": 0, "decision": {"type": "tool", "name": "search", "arguments": {"query": "agent loop"}}},
{"step": 1, "decision": {"type": "final", "content": "An agent loop repeats: observe, decide, act, observe."}}
]

Notice that step 1 sees the search result appended by step 0. That is the feedback path: the second decision is made against a history containing the tool’s output. If you want proof, inspect agent.llm.calls[1] — it contains the role="tool" message with the retrieved passage. This is the mechanism behind self-correction, and it costs nothing more than appending to a list.

Wiring a real model without touching the loop

A scripted model proves control flow, but production needs a real one. The entire integration should live inside an LLMClient subclass — if you find yourself editing AgentLoop to accommodate a provider, the abstraction is leaking. The job of this adapter is to translate a vendor-specific HTTP response into the two decision shapes the loop already understands.

import urllib.request
class HTTPClient(LLMClient):
"""Minimal adapter for an OpenAI-compatible chat endpoint."""
def __init__(self, base_url: str, api_key: str, model: str, timeout: float = 20.0):
self.base_url, self.api_key, self.model, self.timeout = base_url, api_key, model, timeout
def complete(self, messages: list[Message], tools: list[dict]) -> dict:
payload = {
"model": self.model,
"messages": [{"role": m.role, "content": m.content,
**({"name": m.name} if m.name else {})} for m in messages],
"tools": tools,
"tool_choice": "auto",
}
req = urllib.request.Request(
self.base_url.rstrip("/") + "/chat/completions",
data=json.dumps(payload).encode("utf-8"),
headers={"Content-Type": "application/json",
"Authorization": "Bearer " + self.api_key},
method="POST",
)
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
body = json.load(resp)
choice = body["choices"][0]["message"]
calls = choice.get("tool_calls") or []
if not calls:
return {"type": "final", "content": choice.get("content") or ""}
call = calls[0]["function"]
try:
args = json.loads(call.get("arguments") or "{}")
except json.JSONDecodeError:
args = {}
return {"type": "tool", "name": call["name"], "arguments": args}

Three details in that adapter are easy to get wrong and worth naming. First, tool_choice: "auto" lets the model answer directly when no tool is needed; forcing a tool call would make simple questions loop pointlessly. Second, arguments arrives as a JSON string, not an object — every provider does this, and forgetting to parse it produces a subtly broken agent that always calls tools with empty arguments. Third, a malformed arguments string is caught and downgraded to {}; the loop then executes the tool with defaults rather than aborting. For a schema-validating version of this exact check, see Part 2.

The timeout parameter is the first line of defence against a hung request, but note what it does not do: it does not retry, and it does not distinguish a 429 (rate limit, retry after a pause) from a 401 (bad key, never retry). Classifying those failures is precisely what Part 2 adds. Right now a timeout raises out of complete and is not caught by the loop — AgentLoop.run guards tool.run, not llm.complete. That is a real gap, not an oversight in the prose: wrap self.llm.complete in a try/except before shipping this file.

Tracing how context actually grows

The loop is simple enough that we can account for its cost exactly. Take a run with two tool calls and assume roughly four characters per token. The context handed to the model at each step is:

Step Messages in history Approx. tokens Why it grew
0 system (42) + user (18) ~15 initial state
1 + tool result 1 ~95 search returned a passage
2 + tool result 2 ~180 second call, longer output
3 + final decision ~200 answer is produced

Every earlier message is resent in full on every call. So a five-step run does not cost five times one call — it costs 1 + 2 + 3 + 4 + 5 = 15 message-units of input. Input token spend is quadratic in the number of steps, not linear. This is the single most common reason an agent that works in a demo becomes expensive in production, and it is invisible until you measure it.

Two consequences follow. Shortening tool outputs pays off twice, because each result is re-read on every subsequent step. And appending large blobs early is disproportionately costly. Part 3 introduces a ContextBudget that caps this growth and compresses old turns; the measurements above are the baseline it has to beat. If you cannot state your token spend per step as concretely as this table, you do not yet control your agent’s cost.

Failure modes and how to handle them

Failure What actually happens Handling in this loop What Part 1 does not solve yet
Model requests a nonexistent tool self.tools.get(name) returns None Append an ERROR: unknown tool message, continue A model that repeats the mistake burns all steps
Tool raises an exception Exception propagates out of tool.run Catch, convert to ToolResult(ok=False), continue No retry, no circuit breaker (Part 2)
Malformed decision (missing type, wrong arguments type) Parser cannot classify Return an abort string immediately No schema validation of arguments (Part 2)
Infinite tool requests Loop keeps iterating max_steps ceiling returns an abort No token or cost budget (Part 3)
Context grows unbounded Each step appends a message None yet No summarisation or pruning (Part 3, Part 4)
Arithmetic tool abused (9**9**9) Character whitelist allows it, CPU spikes None No sandbox or timeout (Part 11)

The pattern is consistent: convert failures into data the loop can reason about, and keep a hard bound on iteration. What this table also shows is that Part 1 is a skeleton. Six of the eight real production concerns are explicitly deferred. A tutorial that claims otherwise would be lying about the difficulty.

Trade-offs

Decision Alternative Why we chose it Cost
Model emits structured decisions, loop executes Let the model call functions directly One place to enforce permissions, logging, budgets Requires parsing and a stable decision schema
Tool errors become messages Raise and abort The model can recover in the next step A stuck model can loop on the same error
Fixed max_steps No limit, rely on model to stop Guarantees termination Legitimate long tasks get truncated
Scripted LLM behind an interface Call a real API in tests Deterministic, offline, fast Does not exercise real response parsing
Skip assistant message for tool calls Append every turn Smaller context, simpler history Some providers expect full turn structure
Dependency-free standard library Use an agent framework Every line is visible and editable You must build the missing pieces yourself

The last row is the real trade-off of this whole series. Frameworks give you retries, tracing, and memory on day one, but they also decide those things for you. Building from scratch costs time; the return is that you can explain every behaviour in your system. For a production agent, that is usually worth it.

Testing it

These tests need only python3. Save the code above as agent_loop.py and the following as test_agent_loop.py, then run python3 -m unittest test_agent_loop -v.

import unittest
from agent_loop import AgentLoop, ScriptedLLM, ToolResult, _calculate, build_tools
class TestAgentLoop(unittest.TestCase):
def test_normal_path_returns_final_answer(self):
script = [
{"type": "tool", "name": "search", "arguments": {"query": "agent loop"}},
{"type": "final", "content": "done"},
]
agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=5)
self.assertEqual(agent.run("q"), "done")
self.assertEqual(len(agent.llm.calls), 2)
self.assertTrue(any(m.role == "tool" for m in agent.llm.calls[1]))
def test_unknown_tool_does_not_crash(self):
script = [
{"type": "tool", "name": "ghost", "arguments": {}},
{"type": "final", "content": "recovered"},
]
agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=5)
self.assertEqual(agent.run("q"), "recovered")
self.assertIn("unknown tool", agent.llm.calls[1][-1].content)
def test_step_limit_is_enforced(self):
script = [{"type": "tool", "name": "search", "arguments": {"query": "loop"}}] * 20
agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=3)
self.assertEqual(agent.run("q"), "aborted: step limit reached")
self.assertEqual(len(agent.trace), 3)
def test_malformed_arguments_are_normalised(self):
script = [
{"type": "tool", "name": "calculate", "arguments": "not-a-dict"},
{"type": "final", "content": "handled"},
]
agent = AgentLoop(ScriptedLLM(script), build_tools(), max_steps=5)
self.assertEqual(agent.run("q"), "handled")
def test_calculator_rejects_attribute_access(self):
self.assertFalse(_calculate({"expression": "__import__('os')"}).ok)
self.assertTrue(_calculate({"expression": "17 * (3 + 4)"}).ok)
self.assertEqual(_calculate({"expression": "17 * (3 + 4)"}).data, "119")
if __name__ == "__main__":
unittest.main()

Five tests, each targeting one guard from the failure table. If test_unknown_tool_does_not_crash fails, the recovery path is broken. If test_step_limit_is_enforced fails, you have a potential infinite loop. These are the two properties I would refuse to ship without.

Exercises

  1. Add a finish tool. Instead of a final decision type, model finishing as a tool called finish that takes an answer string. Modify run so that calling it ends the loop, and update the tests. Which design is easier to constrain with a schema?
  2. Introduce a retry counter. If the same tool is called three times with identical arguments and the history has not otherwise changed, abort with a specific message. Where in the loop do you need to keep state, and what does this do to the trace structure?
  3. Swap in a real client. Write an LLMClient subclass that calls an HTTP chat endpoint and parses its function-calling response into our two decision shapes. Keep AgentLoop unchanged — if you have to edit it, your interface boundary is in the wrong place.

Exercise 3 is the one that proves the architecture. The loop should not care which model produced the decision.

What’s next

You now have a loop that terminates, calls tools, and recovers from bad decisions. It also has obvious gaps: tool arguments are unvalidated, errors are unstructured strings, and a tool that fails transiently is never retried.

Part 2, Agent tool contracts and structured errors, replaces the loose Tool dataclass with validated contracts: argument schemas checked before execution, typed error categories, a retry policy that distinguishes transient from permanent failures, and idempotency keys so a retry cannot duplicate a side effect. The AgentLoop from this file stays intact — we extend it, not rewrite it. That is the point of building the boundary first.

Get Ball — Ball

Get Ball

Reading in English? Switch language in the menu.