The Agent Loop Is Forty Lines. The Guards Around It Are the Engineering
A framework-free agent loop in Python, written as a state machine with five explicit exits: validated tool calls, errors returned as observations, step, token and time budgets, and stall detection, all tested with a scripted model and the real SDK.

An agent that works in a demo usually fails in production for a reason that has nothing to do with the model. A tool raises an exception and the whole request dies with a stack trace. The model asks for the same search four hundred times because nothing told it to stop. A response is cut off at the token limit and the half-sentence is shown to the user as the answer. None of these is a prompt problem. They are control-flow problems, and control flow is ordinary code.
That is the reason to build an AI agent from scratch at least once: a framework hides exactly the part that fails. What follows is a complete tool-using agent in 159 lines of Python with no agent framework. The agent loop itself is 44 of them, and nearly everything else is a guard. Every listing is taken from code that was run; the test suite is described near the end.
What it takes to build an AI agent from scratch
A language model is a function from a sequence of tokens to the next tokens; how that works internally does not matter here. It cannot call anything. What providers call tool use is a convention: you describe functions in the request, and the model may answer with a structured request to call one instead of with prose. Your code decides whether to run it, runs it, and sends the result back as another message. The model then continues from a longer transcript.
An agent is that exchange repeated until the model stops asking. Anthropic's engineering guidance defines agents as systems where the model dynamically directs its own process and tool use, in contrast to workflows, where code fixes the path in advance. Stripped of a framework, LLM agent architecture comes down to three parts, and only one of them is the model:
- a transcript, the only state the model ever sees;
- a tool registry, the complete list of things the model can cause to happen;
- a loop, which owns every decision about when to call the model again and when to stop.
Reliability is decided in the loop, so its contract with the model is worth making explicit before the loop is written.
The contract: one turn, reduced to what the loop needs
Provider responses differ in shape, but a loop needs only four facts from each turn: why the model stopped, any text, any tool calls, and how many tokens were spent.
@dataclass(frozen=True) class ToolCall: id: str name: str arguments: dict[str, Any] @dataclass(frozen=True) class ModelTurn: """One model response, reduced to what the loop needs.""" stop: str # "final" | "tool_calls" | "truncated" | "refused" text: str = "" tool_calls: tuple[ToolCall, ...] = () input_tokens: int = 0 output_tokens: int = 0 class Model(Protocol): def complete(self, transcript: list[dict], tools: list[dict]) -> ModelTurn: ...
stop has four values, not two. A model can finish (final), ask for tools (tool_calls), be cut off by an output or context limit (truncated), or decline (refused). Treating everything that is not a tool call as an answer is the first common bug: a truncated response looks like text, and it is not an answer.
A tool is a function plus the two things the model needs in order to call it correctly, a description and a JSON Schema for its arguments, and one thing the loop needs, a timeout:
@dataclass class Tool: name: str description: str schema: dict[str, Any] fn: Callable[..., Any] timeout_s: float = 5.0 def spec(self) -> dict: return {"name": self.name, "description": self.description, "input_schema": self.schema}
The schema does two jobs. It is sent to the model as documentation, and it is enforced by your code on every call. Only the second one is a guarantee.
Figure 1. The loop as a state machine: one guard before each model call, three around each tool call, and every way out named.
The loop, with five exits
Here is the whole loop. Read it for the return statements in the while body; there are five, and each one is a distinct outcome the caller can act on.
def run_agent(model: Model, tools: list[Tool], task: str, budget: Budget | None = None, max_repeats: int = 2) -> Outcome: budget = budget or Budget() registry = {t.name: t for t in tools} specs = [t.spec() for t in tools] transcript: list[dict] = [{"role": "user", "content": task}] seen: dict[str, int] = {} def done(status: str, answer: str = "", detail: str = "") -> Outcome: return Outcome(status, answer, transcript, budget.steps, budget.tokens, detail) while True: if (reason := budget.exhausted()) is not None: return done("budget_exhausted", detail=reason) turn = model.complete(transcript, specs) budget.steps += 1 budget.tokens += turn.input_tokens + turn.output_tokens # Record only the calls the loop is about to answer: a cut-off turn can carry half a call. calls = turn.tool_calls if turn.stop == "tool_calls" else () transcript.append({"role": "assistant", "content": turn.text, "tool_calls": [vars(c) for c in calls]}) if turn.stop == "final": return done("completed", turn.text) if turn.stop == "refused": return done("refused", turn.text) if not calls: # "truncated", an unknown stop value, or a tool turn without calls: never an answer return done("truncated", turn.text) observations = [] for call in calls: key = fingerprint(call) seen[key] = seen.get(key, 0) + 1 if seen[key] > max_repeats: # Close the pending calls so the transcript stays well-formed, then stop. observations.append({"tool_call_id": call.id, "name": call.name, "is_error": True, "content": "Not executed: identical call repeated."}) continue observations.append(execute(registry.get(call.name), call)) transcript.append({"role": "tool", "content": observations}) if any(count > max_repeats for count in seen.values()): return done("stalled", detail="identical tool call repeated")
Three details in it are easy to get wrong.
The budget is checked before each model call, not after it. A check placed after the call would throw away a response that has already been paid for, possibly the final answer. The price of checking first is that the token and time limits are thresholds, not hard caps: the call that crosses a limit still completes, so in the test suite a 200-token budget ends the run at 240 tokens. Only the step limit is exact.
The transcript is appended to and never rewritten, and every tool call in it has an answer. Providers reject a conversation in which a tool call has no matching result, so even on the stall exit the loop writes an observation for the call it refused to run. The same rule applies in the other direction: a response cut off at the output limit can end in half a tool call, so the assistant entry records calls only when the stop is tool_calls, and any other turn that is not final or refused ends the run as truncated. A transcript that is always well-formed can be resumed, replayed and inspected; one that is well-formed only on the happy path cannot.
The loop returns an Outcome with a status, never a bare string. "The agent ran out of budget" and "the agent answered" must not be the same type, because the caller has to do different things with them: show an answer, or show a failure and perhaps hand over to a person.
Errors are observations, not exceptions
When a tool fails, there are two readers for the failure. One is your logging. The other is the model, which can often recover if it is told what went wrong: it can fix an argument, try a different tool, or tell the user it could not complete the task. An exception that unwinds the loop removes the second reader.
def execute(tool: Tool | None, call: ToolCall) -> dict: """Run one tool call. Every failure becomes an observation the model can read.""" def observation(content: str, is_error: bool) -> dict: if len(content) > MAX_OBSERVATION_CHARS: # errors are capped too: a validation message can echo a huge argument content = content[:MAX_OBSERVATION_CHARS] + f"\n[truncated {len(content) - MAX_OBSERVATION_CHARS} characters]" return {"tool_call_id": call.id, "name": call.name, "content": content, "is_error": is_error} if tool is None: return observation(f"Unknown tool '{call.name}'.", True) errors = sorted(Draft202012Validator(tool.schema).iter_errors(call.arguments), key=lambda e: [str(p) for p in e.path]) if errors: problems = "; ".join(f"{'/'.join(map(str, e.path)) or '(root)'}: {e.message}" for e in errors[:3]) return observation(f"Invalid arguments: {problems}", True) future = _pool.submit(tool.fn, **call.arguments) try: result = future.result(timeout=tool.timeout_s) except FutureTimeout: if future.cancel(): # still queued behind busy workers, so it never ran return observation(f"Not started within {tool.timeout_s:g}s: no worker was free. The call was not executed.", True) return observation(f"Timed out after {tool.timeout_s:g}s. The call may or may not have completed.", True) except Exception as exc: # the tool's own failure is data for the model, not a crash of the loop return observation(f"{type(exc).__name__}: {exc}", True) text = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False, default=str) return observation(text, False)
Five failure paths return the same shape as a success, with is_error set: an unknown tool name, arguments that fail the schema, a call that never got a worker thread, a timeout, and an exception from the tool itself. The validation message names the offending path and the rule that failed, because that is what lets the model correct the call on the next step. In the test suite, a model that sends "1042" where an integer is required receives id: '1042' is not of type 'integer', and its next call is valid.
The cap inside the observation helper matters as much as the error handling. A tool that returns 300 kB of JSON would consume the context window in one step, so every observation is cut at 4,000 characters and says how much was removed. Errors pass through the same cap because a schema message quotes the offending value, and the model chose that value. The exception path deserves a second look as well: it hands str(exc) to the model, and from there the text can reach the user, so a tool should raise messages that are fit to be read there and keep connection strings and SQL out of them.
Tool output is also untrusted input: anything a tool returns, such as a web page, an email body or a database field, enters the transcript and can contain instructions addressed to the model. This loop does not defend against that; treating tool output as data rather than as instructions needs separate controls, in the same way that injection defences in conventional applications are separate from input parsing.
Figure 2. Two tool calls in one turn. The timeout is reported to the model next to the successful result.
The timeout message is deliberately worded: the call may or may not have completed. A timeout tells you that you stopped waiting, not that the work stopped. Python cannot kill a running thread, so the function may still finish after the loop has moved on. For a read this is harmless. The one case the loop can be sure about is a call that was still queued when its time ran out: future.cancel() succeeds only if the function never started, and the observation then says the call was not executed. For a tool that sends a payment or an email it is the most dangerous state in the system, and the only sound answer is to make the operation safe to repeat with an idempotency key rather than to hope the timeout was accurate.
Budgets and stall detection
A loop driven by a probabilistic component needs a bound that does not depend on that component behaving. There are three independent ones here:
@dataclass class Budget: max_steps: int = 8 max_tokens: int = 50_000 max_seconds: float = 60.0 steps: int = 0 tokens: int = 0 started: float = field(default_factory=time.monotonic) def exhausted(self) -> str | None: if self.steps >= self.max_steps: return "steps" if self.tokens >= self.max_tokens: return "tokens" if time.monotonic() - self.started >= self.max_seconds: return "time" return None
Steps bound the number of model calls, tokens bound spend, and wall-clock time bounds how long a user or a worker waits. They are separate because they fail separately: ten steps with large tool results can exceed a token budget that a hundred small steps would not. A Budget carries its own counters and starts its clock when it is constructed, so each run needs a new one. The time limit is also only checked between steps. One slow model call can overshoot it, and the adapter shown later inherits the SDK's default read timeout, 600 seconds in version 2.8.0, which is worth lowering to fit the budget.
A budget alone turns an infinite loop into an expensive finite one. The cheaper signal is repetition. Each call is reduced to a fingerprint, the tool name plus its canonicalised arguments, and the loop counts them:
def fingerprint(call: ToolCall) -> str: return call.name + ":" + json.dumps(call.arguments, sort_keys=True, ensure_ascii=False)
With max_repeats=2, a model that issues an identical call a third time is stopped at step three with the status stalled, where a step budget of fifty would have let it run fifty times. The count is per run, not per consecutive step, so a tool that is legitimately polled with identical arguments needs a higher max_repeats. And it catches only the simplest loop shape, exact repetition. Alternating between two calls, or drifting through slightly different arguments, needs detection on progress rather than on calls, and the budget remains the backstop for those.
The same contract on a real SDK
Nothing above is specific to a provider. An adapter translates the neutral transcript into the provider's message format and the provider's response into a ModelTurn. This one targets the Anthropic Messages API:
STOP = {"end_turn": "final", "stop_sequence": "final", "tool_use": "tool_calls", "max_tokens": "truncated", "model_context_window_exceeded": "truncated", "refusal": "refused"} def to_messages(transcript: list[dict]) -> list[dict]: """Translate the loop's neutral transcript into Messages API content blocks.""" messages = [] for entry in transcript: if entry["role"] == "user": messages.append({"role": "user", "content": entry["content"]}) elif entry["role"] == "assistant": blocks = [{"type": "text", "text": entry["content"]}] if entry["content"] else [] blocks += [{"type": "tool_use", "id": c["id"], "name": c["name"], "input": c["arguments"]} for c in entry["tool_calls"]] messages.append({"role": "assistant", "content": blocks}) else: # tool observations go back in ONE user message, one tool_result block per call messages.append({"role": "user", "content": [ {"type": "tool_result", "tool_use_id": o["tool_call_id"], "content": o["content"], "is_error": o["is_error"]} for o in entry["content"]]}) return messages class AnthropicModel: def __init__(self, client: anthropic.Anthropic | None = None, model: str | None = None, system: str = "", max_tokens: int = 1024): self.client = client or anthropic.Anthropic() self.model = model or os.environ["AGENT_MODEL"] # a model ID is configuration, never a literal self.system, self.max_tokens = system, max_tokens def complete(self, transcript: list[dict], tools: list[dict]) -> ModelTurn: response = self.client.messages.create( model=self.model, max_tokens=self.max_tokens, system=self.system or anthropic.omit, messages=to_messages(transcript), tools=tools, ) text = "".join(b.text for b in response.content if b.type == "text") calls = tuple(ToolCall(b.id, b.name, dict(b.input)) for b in response.content if b.type == "tool_use") return ModelTurn( stop=STOP.get(response.stop_reason or "", "truncated"), text=text, tool_calls=calls, input_tokens=response.usage.input_tokens, output_tokens=response.usage.output_tokens, )
Three points are specific to this API. Tool results are sent in a user message as tool_result blocks, each carrying the tool_use_id it answers. The documentation requires that message to follow the assistant's tool-use message directly, with nothing in between, which is why the loop gathers all observations of a turn into one transcript entry.
The set of stop reasons is also wider than end_turn and tool_use. Version 2.8.0 of the SDK types stop_reason as one of seven values, and the adapter maps them like this:
SDK stop_reason | ModelTurn.stop | Loop outcome |
|---|---|---|
end_turn, stop_sequence | final | completed |
tool_use | tool_calls | tools run, loop continues |
max_tokens, model_context_window_exceeded | truncated | truncated |
refusal | refused | refused |
pause_turn, or any value not in the table | truncated | truncated |
The last row is the fail-closed default: a stop reason added by a future API version is not reported as a completed answer. pause_turn falls there on purpose. It belongs to server-side tools, which this loop does not use, and continuing such a turn means sending the assistant content back unchanged.
That points at the third limit. to_messages rebuilds assistant turns from text and tool_use blocks only, so any other block type in a response is dropped. A feature whose blocks must be returned to the API as they were received needs an adapter that stores the raw content, not this neutral transcript.
The model identifier is read from the environment, because model names change faster than loops do. An empty system prompt is omitted from the request with the SDK's omit sentinel instead of being sent as an empty string.
Testing an agent without a model
The loop is deterministic given the model's turns, so the model can be replaced by a script:
class Scripted: """A model that replays a fixed list of turns: deterministic, free, and enough to test the loop.""" def __init__(self, turns): self.turns, self.calls = list(turns), 0 def complete(self, transcript, tools): self.calls += 1 return self.turns.pop(0) if len(self.turns) > 1 else self.turns[0]
With that, each exit becomes an ordinary unit test that runs in milliseconds and costs nothing:
def test_step_budget_stops_a_model_that_never_finishes(): turns = [call("get_order", f"c{i}", id=1042 + i) for i in range(50)] outcome = run_agent(Scripted(turns), [get_order], "loop", Budget(max_steps=5)) assert (outcome.status, outcome.detail, outcome.steps) == ("budget_exhausted", "steps", 5) def test_token_budget_is_checked_before_the_next_model_call(): model = Scripted([call("get_order", id=1042)]) outcome = run_agent(model, [get_order], "loop", Budget(max_tokens=200), max_repeats=99) assert (outcome.status, outcome.detail, model.calls) == ("budget_exhausted", "tokens", 2) def test_identical_repeated_call_is_detected_as_a_stall(): model = Scripted([call("get_order", id=1042)]) outcome = run_agent(model, [get_order], "loop", Budget(max_steps=50)) assert (outcome.status, outcome.steps) == ("stalled", 3) assert observations(outcome)[-1]["content"] == "Not executed: identical call repeated."
The first asserts that the run stops after exactly five model calls. The second shows the threshold behaviour described earlier: two calls are made and paid for before the 200-token limit is seen. The third stops at step three, with the refused call closed in the transcript.
The suite has fourteen tests. Twelve drive the loop with the scripted model: completion after a tool call, recovery from invalid arguments, the tool failures that must not crash the run, the step, token and time budgets, the stall, the pairing of every tool call with exactly one observation, truncated and refused turns, a cut-off turn carrying half a tool call, the cap on error observations, and a call that never got a worker. The other two run the real Anthropic SDK against a local HTTP transport, with no network and no API key. One asserts the request body the SDK actually sends, including the tool_result block; the other feeds max_tokens, pause_turn and an invented stop reason through the adapter and expects truncated each time. The transport has to be an httpx2.MockTransport: this SDK version builds on httpx2, and its client constructor rejects an httpx.Client with a TypeError.
Verification. All fourteen tests pass on Python 3.13.18 with anthropic 2.8.0, jsonschema 4.26.0 and pytest 9.2.0 (run on 11 November 2026). Not verified: the loop was not run against a live model, so nothing here is a claim about how any particular model behaves, and the mock transport accepts any request, so the tests prove what the SDK sends and not that the API accepts it. Scripted tests verify the loop; model behaviour needs an evaluation set of its own, and skipping that step is one of the patterns behind AI projects that fail in production.
What this loop leaves out
It is a correct core, not a platform. Before it carries production traffic it needs decisions on at least these:
| Concern | What the loop does today | What production needs |
|---|---|---|
| Side effects | Runs any registered tool | A policy layer: which caller may trigger which tool, and which calls need a person's approval |
| Model call failures | An SDK exception leaves run_agent and the transcript goes with it | Catch, persist the transcript, retry with backoff |
| Ambiguous timeouts | Reports them honestly | Idempotency keys on every tool that changes state |
| Concurrency | Tools run one after another | Parallel execution for independent reads, with a per-turn limit |
| Durability | State lives in memory | Persisting the transcript after each step so a restart can resume |
| Context growth | Truncates single observations | Eviction or summarising of old tool results before the window fills |
| Observability | Returns the transcript | A trace per step: model, tokens, tool, duration, outcome |
| Cost | Counts tokens | Per-tenant budgets and provider cache-aware accounting |
The thread pool deserves one more caution. It bounds how long the loop waits, not how much work is in flight, so a tool that hangs forever occupies a worker forever. The pool is also shared by every run in the process and has eight workers; once eight calls hang, every later call is reported as not started. Tools that call the network should carry their own client-side timeout as well, and anything truly untrusted belongs in a separate process.
Common mistakes
Letting the model's stop decide everything. If the only exit is "the model returned text", the system has no exit at all when the model misbehaves.
Raising on tool failure. It converts a recoverable step into a failed request and hides from the model the one thing it needed to know.
Trusting the schema because the model was given it. A schema in the request is advice. Validation in your code is enforcement. Provider-side strict modes constrain the shape of the arguments; they do not replace checking at the boundary you own.
One number for the budget. A step cap without a token cap is defeated by large observations; a token cap without a time cap is defeated by a slow tool.
Rewriting history. Editing earlier transcript entries to "clean up" produces conversations that providers reject and that nobody can replay.
Engineering verdict
Write this loop yourself when the agent is part of a product you operate: you get five named outcomes, tests that need no model, and a transcript you fully understand. The cost is that every item in the table above becomes your work.
Use a framework or a provider's agent SDK when you need what they have already built, such as durable execution, tracing or hosted tools, and when you have read enough of their loop to know where its exits are. The questions to ask of any agent runtime are the ones this article answers for its own: what are the exits, what happens when a tool fails, what bounds the run, and can it be tested without a model?
And do not build an agent where the path is known in advance. If you can write the steps down, write them as code and let the model handle only the steps that need judgement. The loop is for the cases where you cannot.
References
Related Articles
AI & Machine Learning28 min read
Large Language Model Architecture: How LLMs Actually Work
A technical deep dive into LLM architecture: tokenization, embeddings, transformer blocks, attention mechanisms, and why these systems behave the way they do—including hallucinations and limitations.
Security Engineering16 min read
Protecting Against Injection Attacks: SQL, NoSQL, and XSS
Prevent SQL injection, NoSQL injection, and XSS attacks with validated code patterns. Covers parameterized queries, input sanitization, and CSP configuration.
Under the Hood · No. 01Backend Design10 min read
Idempotency Keys Are a Contract, Not a Header: Designing Retry-Safe Operations
A retry is only safe if the server has promised what happens the second time. This issue designs that promise end to end, from the key table to queue consumers and external calls.