Agent-Loop ohne echtes Modell testen: Skript-Fake-LLM und fünf pytest-Tests
Wer das Verhalten seines Agent-Loops prüfen will, braucht dafür kein echtes Sprachmodell. Ein geskripteter Fake-LLM erlaubt reproduzierbare Tests, etwa mit pytest.

Veröffentlicht am 29. Nov. • Bearbeitet am 29. Nov. • KI-unterstützt
Deine Agent-Schleife hat gerade "Lass mich die Bestellung A1 nachschlagen." als endgültige Antwort zurückgegeben. Das Nachschlagen wurde nie ausgeführt, und der Nutzer erhielt ein Versprechen statt einer Antwort. Das Modell hat seinen Teil erledigt: Seine Antwort enthielt diesen Satz und einen tool_use-Block Seite an Seite, mit stop_reason auf tool_use gesetzt. Die Tool-Use-Dokumentation von Anthropic zeigt exakt diese Struktur in einer Beispielantwort. Deine Schleife hat den Text gelesen, festgestellt, dass er nicht leer ist, und ihn zurückgegeben.
Kein Modell-Upgrade behebt das. Der Fehler steckt in etwa zehn Zeilen deines eigenen Python-Codes, und du kannst diese zehn Zeilen testen, ohne einen API-Schlüssel, einen Netzwerkaufruf oder ein einziges ausgegebenes Token.
Eine Agent-Schleife ist klein. Das Modell um einen Zug bitten, die von ihm angeforderten Tools ausführen, die Ergebnisse zurücksenden, stoppen, wenn es antwortet oder wenn die Geduld erschöpft ist. Kleiner Code versteht trotzdem drei klassische Fehler. Hier sind sie in einer illustrativen Schleife:
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 Enter fullscreen mode Exit fullscreen mode Fehler 1 gibt dem Modell einen Zug weniger als konfiguriert, sodass ein Lauf, der in seinem letzten erlaubten Zug abgeschlossen worden wäre, stattdessen scheitert. Fehler 2 ist die Eröffnungsszene: Text, der zusammen mit einem offenen Tool-Aufruf mitgeschickt wird, wird als endgültige Antwort behandelt. Fehler 3 schluckt ein Tool-Versagen.
Die Dokumentation ist ausdrücklich: Du fügst "für jeden tool_use-Block in diesem Content einen tool_result-Block hinzu, selbst wenn das Tool fehlgeschlagen ist", und markierst Fehlschläge mit is_error: true, woraufhin "Claude das Tool möglicherweise erneut mit einem neuen tool_use-Block aufruft, begrenze also, wie viele Wiederholungen deine Schleife erlaubt." Lässt du das Ergebnis weg, ist die nächste Anfrage fehlerhaft; dieselbe Seite listet einen Fehler auf, den du erhalten kannst: "tool_use ids were found without tool_result blocks immediately after".
Keiner dieser Fälle braucht ein echtes Modell zur Reproduktion. Jeder erfordert nur, dass das Modell zu einem bestimmten Zeitpunkt etwas Bestimmtes sagt. Das ist ein Skript.
Das Fake-Modell ist ein Skript: jeder Zug, den es spielt, wurde im Voraus notiert.
Alistair Cockburns Original-Paper zu Ports and Adapters formuliert das Ziel so: Eine Anwendung solle "gleichermaßen von Nutzern, Programmen, automatisierten Tests oder Batch-Skripten gesteuert werden können" und "isoliert von ihren letztlichen Laufzeitgeräten und Datenbanken entwickelt und getestet werden können." Ein LLM-Anbieter ist eines dieser Laufzeitgeräte. Also bekommt die Schleife ein eigenes Vokabular und spricht mit dem Modell über eine einzige Methode:
# 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:... Enter fullscreen mode Exit fullscreen mode Nichts darin weiß etwas von einem Anbieter-SDK oder HTTP. Stop hat drei Werte, weil die Schleife sich nur um drei Ausgänge kümmert: Das Modell will Tools, das Modell ist fertig, oder die Antwort wurde abgeschnitten.
Die Schleife hängt nur von diesem Port ab und von nichts anderem:
# 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 ) Enter fullscreen mode Exit fullscreen mode Jeder Aufruf bekommt ein Ergebnis, Fehlschläge eingeschlossen. Eine Antwort zählt nur, wenn das Modell sagt, dass es fertig ist, und nichts mehr anfordert. Das Limit zählt Modell-Züge, und die Schleife fordert exakt max_turns davon an.
Das Fake implementiert denselben Port. Es gibt die geplanten Züge in Reihenfolge zurück und behält eine Kopie der jeweils gesehenen Historie, sodass Tests prüfen können, was das Modell erhalten hätte:
# 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 ) Enter fullscreen mode Exit fullscreen mode Der AssertionError ist entscheidend. Fordert die Schleife einen Zug an, den das Skript nie vorgesehen hat, fällt der Test lautstark durch, statt zu hängen oder eine Antwort zu erfinden.
Pydantic AI liefert dieselbe Idee mit. Dessen Test-Guide bietet TestModel und FunctionModel für Unit-Tests mit "keinerlei Modell-Anfragen und jedes Mal demselben Ergebnis" und empfiehlt, ALLOW_MODEL_REQUESTS=False zu setzen, damit versehentlich nichts ein echtes Modell erreicht. Wenn du dieses Framework nutzt, verwende diese Werkzeuge. Wenn deine Schleife eigener Code ist, geben dir zwanzig Zeilen Fake dieselbe Kontrolle.
Jeder Test treibt die Schleife durch genau ein Tor: ein fehlgeschlagenes Tool, der letzte erlaubte Zug, ein offener Aufruf.
Jeder Test ist eine kurze Geschichte, die der Schleife erzählt wird. Führe sie mit python -m pytest aus, was außerdem das aktuelle Verzeichnis auf sys.path legt, sodass agent aus dem Projekt-Stammverzeichnis importiert wird.
# 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, ) Enter fullscreen mode Exit fullscreen mode Der erste Test ist der Wiederholungspfad: Tool-Aufruf, Tool-Fehler, Wiederholung, endgültiger Text. Die letzte Assertion ist die, die Fehler 3 aufdeckt. Sie prüft, was das Modell in seinem zweiten Zug gelesen hätte, und das muss der Fehler sein, als solcher markiert.
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 Enter fullscreen mode Exit fullscreen mode Das Paar nagelt das Limit von beiden Seiten fest. range(max_turns - 1) lässt den ersten Test scheitern. range(max_turns + 1) lässt den zweiten scheitern, weil die Schleife einen vierten Zug anfordert und das Fake einen AssertionError statt der erwarteten LoopLimit-Ausnahme wirft.
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?" ) Enter fullscreen mode Exit fullscreen mode Der Test mit dem offenen Tool-Aufruf ist die Eröffnungsszene, in einen Regressionstest verwandelt. Der Test zur Abschneidung deckt einen Fall ab, vor dem die Referenz zu den Stop-Gründen warnt: Eine Antwort, die das Limit von max_tokens erreicht, wird an Ihrer Grenze abgeschnitten, und wenn der Schnitt innerhalb eines Tool-Aufrufs landet, müssen Sie mit einem höheren Limit erneut versuchen. In beiden Fällen ist es keine Antwort.
Keiner dieser Tests öffnet einen Socket. Das Fake ist eine Liste und ein pop.
Der Produktionscode benötigt die andere Seite des Ports. Für die Anthropic Messages API bildet der Adapter Domain-Einträge auf Messages ab und die Antwort zurück auf einen 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 ] } Enter fullscreen mode Exit fullscreen mode Die Stop-Gründe stammen aus derselben Kurzreferenztabelle. Alles, wofür die Schleife keine Regel hat, etwa refusal oder pause_turn, löst eine Exception aus, statt geraten zu werden.
Eine Einschränkung: Dieser Entwurf rekonstruiert Assistant-Turns nur aus Text und Tool-Aufrufen, während die Dokumentation sagt, den Antwortinhalt unverändert zurückzusenden. Wenn Sie Thinking oder serverseitige Tools aktivieren, bewahren Sie die rohen Blöcke neben dem ModelTurn auf, damit der Adapter sie wiedergeben kann.
Da der Adapter keine Schleifenlogik enthält, gehen seine Tests um das Mapping. Eine Handvoll aufgezeichneter Antworten deckt sie ab.
Aufgezeichnete Kassetten sind die übliche Alternative. VCR.py speichert echten HTTP-Traffic beim ersten Lauf und spielt ihn später wieder ab, und sein none-Aufzeichnungsmodus "garantiert, dass keine neuen HTTP-Anfragen gestellt werden". Das passt gut zum Adapter: Es belegt, dass Ihr Mapping mit dem übereinstimmt, was der Anbieter tatsächlich sendet.
Für die Schleife kann eine Kassette nur ein Gespräch wiedergeben, das wirklich stattgefunden hat. Um eines zu bekommen, in dem die Bestelldatenbank abläuft, das Modell mit denselben Argumenten erneut versucht und dann antwortet, müssten Sie das echte Modell und das echte Tool genau das tun lassen, während Sie aufzeichnen. Ein Skript erlaubt es Ihnen, dieses Gespräch heute zu schreiben, plus diejenigen, die die Produktion noch nicht hervorgebracht hat: zwei Tool-Aufrufe in einem Turn, ein unbekannter Tool-Name, eine abgeschnittene Antwort im letzten erlaubten Turn.
Teilen Sie die Arbeit entlang des Ports auf. Skripte für die Schleife, Kassetten oder ein kleiner Live-Smoke-Test für den Adapter, und Evals für die Frage, ob die Antworten des Modells gut sind. Wie es der Pydantic-AI-Leitfaden formuliert, sagen Unit-Tests Ihnen "nicht, ob die Antworten des Modells gut sind; dafür sind Evals da".
Das Fake in diesem Beitrag funktioniert, weil die Schleife den Anbieter nie importiert: Sie spricht mit einem Port, und der Anbieter ist einer von zwei Adaptern. Das ist die Kernidee der Hexagonalen Architektur in Python. Das Buch handelt nicht von Agenten. Es baut einen asynchronen FastAPI- und SQLAlchemy-2-Dienst auf fünf Arten auf (hexagonal, Clean, Onion, geschichtet und als Vertical Slices), vergleicht sie dann, und dieselbe Gewohnheit, den Kern von Datenbank und Framework getrennt zu halten, ist es, die diese Schleife testbar gemacht hat. Jedes Listing läuft aus dem kostenlosen Begleit-Repo.
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
Posted on Nov 29 • Edited on Nov 29 • AI-assisted
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.
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 Enter fullscreen mode Exit fullscreen mode 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.
The fake model is a script: every turn it plays is one you wrote down in advance.
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:... Enter fullscreen mode Exit fullscreen mode 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 ) Enter fullscreen mode Exit fullscreen mode 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.
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 ) Enter fullscreen mode Exit fullscreen mode 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.
Each test drives the loop through one gate: a failed tool, the last allowed turn, a pending call.
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, ) Enter fullscreen mode Exit fullscreen mode 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 Enter fullscreen mode Exit fullscreen mode 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?" ) Enter fullscreen mode Exit fullscreen mode 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.
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 ] } Enter fullscreen mode Exit fullscreen mode 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.
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."
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.