Your agent loop just returned "Let me look up order A1." as its final answer. The lookup never ran, and the user got a promise instead of an answer. The model did its part: its response carried that sentence and a tool_use block side by side, with stop_reason set to tool_use. Anthropic's tool-use docs show that same shape in an example response. Your loop read the text, saw it was not empty, and returned it.

No model upgrade fixes that. The bug is in about ten lines of your own Python, and you can test those ten lines without an API key, a network call or a single token spent.

The bugs live in the loop

An agent loop is small. Ask the model for a turn, run the tools it asked for, send the results back, stop when it answers or when you run out of patience. Small code still hides three classic bugs. Here they are in one illustrative loop:

for _ in range(max_turns - 1): # 1. off by one turn = llm.next_turn(history) if turn.text: # 2. preamble wins return turn.text for c in turn.calls: try: history.append(run(c)) except Exception: continue # 3. error dropped 

Bug 1 gives the model one turn fewer than you configured, so a run that would have finished on its last allowed turn fails instead. Bug 2 is the opening scene: text that rides along with a pending tool call gets treated as the final answer. Bug 3 swallows a tool failure. The docs are explicit that you add "one tool_result block for each tool_use block in that content, even if the tool failed", and that you mark failures with is_error: true, after which "Claude might then call the tool again with a new tool_use block, so limit how many retries your loop allows." Skip the result and the next request is malformed; the same page lists an error you can get: "tool_use ids were found without tool_result blocks immediately after".

None of these needs a real model to reproduce. Each needs the model to say a specific thing at a specific moment. That is a script.

A puppeteer's hand holding a scroll of cues, with strings running down to a small robot at a desk
The fake model is a script: every turn it plays is one you wrote down in advance.

Put the model behind a port

Alistair Cockburn's original Ports and Adapters paper states the goal as letting an application "equally be driven by users, programs, automated test or batch scripts" and be "developed and tested in isolation from its eventual run-time devices and databases." An LLM provider is one of those run-time devices. So the loop gets its own vocabulary and talks to the model through one method:

# agent/ports.py from dataclasses import dataclass from typing import Literal, Protocol Stop = Literal["tool_use", "end_turn", "truncated"] @dataclass(frozen=True) class UserText: text: str @dataclass(frozen=True) class ToolCall: id: str name: str args: dict @dataclass(frozen=True) class ToolResult: call_id: str content: str is_error: bool = False @dataclass(frozen=True) class ModelTurn: stop: Stop text: str = "" calls: tuple[ToolCall, ...] = () Entry = UserText | ModelTurn | tuple[ToolResult, ...] class LLMPort(Protocol): def next_turn(self, history: list[Entry]) -> ModelTurn: ... 

Nothing in there knows about a provider SDK or HTTP. Stop has three values because the loop only cares about three outcomes: the model wants tools, the model is done, or the reply was cut off.

The loop depends on that port and nothing else:

# agent/loop.py from collections.abc import Callable from agent.ports import ( Entry, LLMPort, ToolCall, ToolResult, UserText, ) Tool = Callable[[dict], str] class LoopLimit(Exception): ... class Truncated(Exception): ... def run_agent( llm: LLMPort, tools: dict[str, Tool], prompt: str, max_turns: int = 5, ) -> str: history: list[Entry] = [UserText(prompt)] for _ in range(max_turns): turn = llm.next_turn(history) history.append(turn) if turn.stop == "truncated": raise Truncated(turn.text) if turn.stop == "end_turn" and not turn.calls: return turn.text history.append( tuple(_run(tools, c) for c in turn.calls) ) raise LoopLimit(f"no answer in {max_turns} turns") def _run(tools: dict[str, Tool], c: ToolCall) -> ToolResult: tool = tools.get(c.name) if tool is None: return ToolResult(c.id, f"unknown tool {c.name}", True) try: return ToolResult(c.id, tool(c.args)) except Exception as exc: msg = f"{type(exc).__name__}: {exc}" return ToolResult(c.id, msg, True) 

Every call gets a result, failures included. An answer counts only when the model says it is done and asks for nothing. The cap counts model turns, and the loop asks for exactly max_turns of them.

A fake that follows a script

The fake implements the same port. It hands back the turns you planned, in order, and keeps a copy of the history it saw each time so tests can check what the model would have received:

# tests/fakes.py from agent.ports import Entry, ModelTurn, ToolCall class ScriptedLLM: def __init__(self, *turns: ModelTurn) -> None: self._turns = list(turns) self.seen: list[list[Entry]] = [] def next_turn(self, history: list[Entry]) -> ModelTurn: self.seen.append(list(history)) if not self._turns: raise AssertionError("loop asked past the script") return self._turns.pop(0) def call(name: str, cid: str = "c1", **args) -> ModelTurn: tc = ToolCall(cid, name, args) return ModelTurn("tool_use", calls=(tc,)) def say(text: str) -> ModelTurn: return ModelTurn("end_turn", text=text) 

The AssertionError matters. If the loop asks for a turn the script never planned, the test fails loudly instead of hanging or inventing a reply.

Pydantic AI ships the same idea. Its testing guide offers TestModel and FunctionModel for unit tests with "no model requests and the same result every run", and suggests setting ALLOW_MODEL_REQUESTS=False so nothing reaches a real model by accident. If you are on that framework, use those. If your loop is your own code, twenty lines of fake give you the same control.

A circular track with three burnt-orange gates on it and a small robot runner, viewed from above
Each test drives the loop through one gate: a failed tool, the last allowed turn, a pending call.

Five tests, four loop bugs

Each test is a short story told to the loop. Run them with python -m pytest, which also puts the current directory on sys.path, so agent imports from the project root.

# tests/test_loop.py import pytest from agent.loop import LoopLimit, Truncated, run_agent from agent.ports import ModelTurn, ToolCall, ToolResult from fakes import ScriptedLLM, call, say def flaky(fails: int, value: str): n = {"calls": 0} def tool(args: dict) -> str: n["calls"] += 1 if n["calls"] <= fails: raise TimeoutError("orders db timed out") return value return tool def test_tool_error_goes_back_to_the_model(): llm = ScriptedLLM( call("lookup_order", id="A1"), call("lookup_order", cid="c2", id="A1"), say("Order A1 shipped."), ) tools = {"lookup_order": flaky(1, "shipped")} answer = run_agent(llm, tools, "Where is A1?") assert answer == "Order A1 shipped." err = ToolResult( "c1", "TimeoutError: orders db timed out", True ) assert llm.seen[1][-1] == (err,) 

The first test is the retry path: tool call, tool error, retry, final text. The last assertion is the one that catches bug 3. It checks what the model would have read on its second turn, and that has to be the error, flagged as one.

def test_answer_on_the_last_allowed_turn(): llm = ScriptedLLM( call("ping"), call("ping", cid="c2"), say("done"), ) tools = {"ping": lambda a: "pong"} assert run_agent(llm, tools, "go", max_turns=3) == "done" def test_cap_stops_after_exactly_max_turns(): llm = ScriptedLLM( *[call("ping", cid=f"c{i}") for i in range(3)] ) with pytest.raises(LoopLimit): run_agent(llm, {"ping": lambda a: "pong"}, "go", max_turns=3) assert len(llm.seen) == 3 

The pair pins the cap from both sides. range(max_turns - 1) fails the first test. range(max_turns + 1) fails the second, because the loop asks for a fourth turn and the fake raises AssertionError instead of the expected LoopLimit.

def test_text_beside_a_tool_call_is_not_the_answer(): pending = ModelTurn( "tool_use", text="Let me look up order A1.", calls=(ToolCall("c1", "lookup_order", {"id": "A1"}),), ) llm = ScriptedLLM(pending, say("Order A1 shipped.")) tools = {"lookup_order": lambda a: "shipped"} answer = run_agent(llm, tools, "Where is A1?") assert answer == "Order A1 shipped." def test_cut_off_reply_is_not_an_answer(): llm = ScriptedLLM(ModelTurn("truncated", text="A1 has")) with pytest.raises(Truncated): run_agent(llm, {}, "Where is A1?") 

The pending-call test is the opening scene, turned into a regression test. The truncation test covers a case the stop-reason reference warns about: a reply that hits max_tokens is cut off at your limit, and if the cut lands inside a tool call you have to retry with a higher limit. Either way it is not an answer.

None of these tests opens a socket. The fake is a list and a pop.

The real adapter is thin

Production code needs the other side of the port. For the Anthropic Messages API, the adapter maps domain entries to messages and the response back to a ModelTurn:

# adapters/anthropic_llm.py import anthropic from agent.ports import Entry, ModelTurn, ToolCall, UserText _STOPS = { "end_turn": "end_turn", "stop_sequence": "end_turn", "tool_use": "tool_use", "max_tokens": "truncated", "model_context_window_exceeded": "truncated", } class UnsupportedStop(Exception): ... class AnthropicLLM: def __init__(self, model: str, tools: list[dict]): self._client = anthropic.Anthropic() self._model = model self._tools = tools def next_turn(self, history: list[Entry]) -> ModelTurn: resp = self._client.messages.create( model=self._model, max_tokens=2048, tools=self._tools, messages=[_to_message(e) for e in history], ) stop = _STOPS.get(resp.stop_reason) if stop is None: raise UnsupportedStop(resp.stop_reason) text = "".join( b.text for b in resp.content if b.type == "text" ) calls = tuple( ToolCall(b.id, b.name, b.input) for b in resp.content if b.type == "tool_use" ) return ModelTurn(stop, text, calls) def _to_message(e: Entry) -> dict: if isinstance(e, UserText): return {"role": "user", "content": e.text} if isinstance(e, ModelTurn): blocks = [] if e.text: blocks.append({"type": "text", "text": e.text}) blocks += [ {"type": "tool_use", "id": c.id, "name": c.name, "input": c.args} for c in e.calls ] return {"role": "assistant", "content": blocks} return {"role": "user", "content": [ {"type": "tool_result", "tool_use_id": r.call_id, "content": r.content, "is_error": r.is_error} for r in e ]} 

The stop reasons come from the same quick-reference table. Anything the loop has no rule for, such as refusal or pause_turn, raises instead of being guessed at. One limit: this sketch rebuilds assistant turns from text and tool calls only, while the docs say to send the response content back unchanged. If you turn on thinking or server tools, keep the raw blocks next to the ModelTurn so the adapter can replay them.

Because the adapter holds no loop logic, its tests are about mapping. A handful of recorded responses covers them.

Scripts versus cassettes

Recorded cassettes are the usual alternative. VCR.py saves real HTTP traffic on the first run and replays it later, and its none record mode "guarantees that no new HTTP requests will be made." That is a good fit for the adapter: it proves your mapping matches what the provider actually sends.

For the loop, a cassette can only replay a conversation that really happened. To get one where the orders database times out, the model retries with the same arguments, and then answers, you would need the real model and the real tool to do exactly that while you record. A script lets you write that conversation today, plus the ones production has not produced yet: two tool calls in one turn, an unknown tool name, a cut-off reply on the last allowed turn.

Split the work along the port. Scripts for the loop, cassettes or a small live smoke test for the adapter, and evals for whether the model's answers are any good. As the Pydantic AI guide puts it, unit tests "don't tell you whether the model's answers are good; that is what evals are for."

If this was useful

The fake in this post works because the loop never imports the provider: it talks to a port, and the provider is one of two adapters. That is the core idea of Hexagonal Architecture in Python. The book isn't about agents. It builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice), then compares them, and the same habit of keeping the core apart from the database and the framework is what made this loop testable. Every listing runs from the free companion repo.

Hexagonal Architecture in Python by Gabriel Anhaia