Why Break Your Own Agent
Real models sometimes ask for a tool with the wrong input, name a tool that
does not exist, run out of output space mid-sentence, decline a request, or
fail to answer at all because the service is busy. Code that coordinates
several agents has to cope with every one of these, so later lessons need a
way to make them happen on demand. In this lesson you add kit/faults.py,
which wraps any model and makes it misbehave on a fixed schedule, and you
write your first automated tests of an agent with pytest.
The faults are simulations: they produce the same shapes of failure a real model or API can produce, so you can test what your code does with them. They say nothing about how often a real model fails.
Five Kinds of Misbehaviour
| Fault | What the wrapped model does | Where the real-world shape comes from |
|---|---|---|
wrong_arguments | Every tool request loses its input | A model filling in a tool's input incorrectly |
unknown_tool | Every tool request names cancel_order, which does not exist | A model naming a tool it was not given |
truncated | The answer stops halfway, with stop reason max_tokens | Output running out of space (S19) |
refusal | No content, with stop reason refusal | A model declining a request |
overloaded | Raises ModelOverloaded instead of answering | A temporary service error such as "overloaded" |
The first four come back as normal responses, so the agent loop handles them as it handles any reply. The fifth is an exception: the request never got an answer, so there is nothing for the loop to append.
Why a Schedule, Not Randomness
A schedule maps a call number to a fault: {1: "wrong_arguments"} breaks
the first model call and no other. The same schedule therefore breaks the same
call on every run, so a test that uses it always gives the same result.
Random faults would make a test pass on one run and fail on the next, and a
test you cannot trust is worse than none. Later, when you want to explore
many combinations, you can still generate schedules; each one stays
repeatable.
Exercise: Break the Agent on Schedule
Goal: save kit/faults.py, run the order agent from lesson 4 under each
fault, then write tests that pin the behaviour down.
Starting state: the kit modules from lessons 3 and 4 (build-the-agent-loop) and the course environment active. Check:
python -c "from kit.loop import run_agent; from kit.shop import shop_tools; print('kit ready')"
Effects: adds kit/faults.py (kept) and an exercise folder with two
Python files and a shop.sqlite3 file. Every run takes well under a second.
-
Save this as
kit/faults.pyin your practice folder:"""Scripted models that misbehave on a fixed schedule, to test how your code copes. FaultyModel wraps any model and, on the calls named in its schedule, changes the reply or raises an error. A schedule maps a call number (1 is the first call) to a fault, so a test that uses one gets the same result every time. """ from kit.messages import text FAULTS = ("wrong_arguments", "unknown_tool", "truncated", "refusal", "overloaded") class ModelOverloaded(Exception): """Stands in for a temporary service error, such as an HTTP 529 'overloaded' response.""" class FaultyModel: def __init__(self, model, schedule): unknown = set(schedule.values()) - set(FAULTS) if unknown: raise ValueError(f"unknown faults {sorted(unknown)}; choose from {FAULTS}") self.model = model self.schedule = dict(schedule) self.name = model.name self.calls = 0 def create(self, **request): self.calls += 1 fault = self.schedule.get(self.calls) if fault == "overloaded": # the request never reaches the wrapped model raise ModelOverloaded(f"{self.name} is overloaded (call {self.calls}); try again later") response = self.model.create(**request) if fault == "wrong_arguments": # every tool request loses its input for block in response["content"]: if block["type"] == "tool_use": block["input"] = {} elif fault == "unknown_tool": # every tool request names a tool that does not exist for block in response["content"]: if block["type"] == "tool_use": block["name"] = "cancel_order" elif fault == "truncated": # the answer stops halfway, as when output runs out words = " ".join(b["text"] for b in response["content"] if b["type"] == "text").split() response["content"] = [text(" ".join(words[: len(words) // 2]))] response["stop_reason"] = "max_tokens" elif fault == "refusal": # the model declines and says nothing response["content"] = [] response["stop_reason"] = "refusal" return response -
Create the exercise folder and move into it:
mkdir -p ~/multi-agent-practice/faulty-models cd ~/multi-agent-practice/faulty-modelsSave this as
faulty_runs.pyin it:"""Run lesson 4's order agent while a scripted model misbehaves on schedule.""" import json import sys from pathlib import Path from kit.faults import FaultyModel, ModelOverloaded from kit.loop import run_agent from kit.messages import blocks_of from kit.scripted import ScriptedModel, call, say from kit.shop import create_shop, shop_tools SYSTEM = "You answer questions about Quillfield Cycles orders. Use the tools; never guess a status." SCHEDULES = { "none": {}, "wrong_arguments": {1: "wrong_arguments"}, "unknown_tool": {1: "unknown_tool"}, "truncated": {2: "truncated"}, "refusal": {1: "refusal"}, "overloaded": {1: "overloaded"}, } def order_rule(messages): """The same decisions as lesson 4: look the order up, then answer from the result.""" last = messages[-1] if isinstance(last["content"], str): return [call("order_status", order_id=last["content"].split()[-1])] result = blocks_of(last, "tool_result")[0] if result["is_error"]: return say(f"I could not look that order up ({result['content']}).") status = json.loads(result["content"]) return say(f"Order {status['order_id']} is {status['status']} (placed {status['placed_on']}).") def run_with(schedule, task="Where is order A-1003"): """Run the order agent once with a fault schedule; return its AgentResult.""" tools = shop_tools(create_shop(Path("shop.sqlite3"))) model = FaultyModel(ScriptedModel(rule=order_rule), schedule) return run_agent(model, system=SYSTEM, task=task, tools=tools, max_steps=4) def main(): name = sys.argv[1] if len(sys.argv) > 1 else "none" try: result = run_with(SCHEDULES[name]) except ModelOverloaded as error: print(f"{name}: the run raised {type(error).__name__}: {error}") return print(f"{name}: stop_reason={result.stop_reason} steps={result.steps} text={result.text!r}") for message in result.messages: for block in blocks_of(message, "tool_result"): if block["is_error"]: print(f" error result: {block['content']}") if __name__ == "__main__": main() -
For each schedule in
SCHEDULES, predict the stop reason, the number of model calls and the final text. Then run all six:for name in none wrong_arguments unknown_tool truncated refusal overloaded; do python faulty_runs.py "$name" donePowerShell:
foreach ($name in "none", "wrong_arguments", "unknown_tool", "truncated", "refusal", "overloaded") { python faulty_runs.py $name }Output (exact):
none: stop_reason=end_turn steps=2 text='Order A-1003 is shipped (placed 2026-10-12).' wrong_arguments: stop_reason=end_turn steps=2 text="I could not look that order up (invalid input: missing required field 'order_id')." error result: invalid input: missing required field 'order_id' unknown_tool: stop_reason=end_turn steps=2 text="I could not look that order up (unknown tool 'cancel_order'; available: order_status, order_details)." error result: unknown tool 'cancel_order'; available: order_status, order_details truncated: stop_reason=max_tokens steps=2 text='Order A-1003 is' refusal: stop_reason=refusal steps=1 text='' overloaded: the run raised ModelOverloaded: scripted is overloaded (call 1); try again later -
Save this as
test_order_agent.pyin the same folder:"""Tests for the order agent under scripted faults.""" import pytest from faulty_runs import run_with from kit.faults import ModelOverloaded def test_answers_when_nothing_goes_wrong(): result = run_with({}) assert result.stop_reason == "end_turn" assert result.text == "Order A-1003 is shipped (placed 2026-10-12)." def test_wrong_arguments_reach_the_model_as_an_error(): result = run_with({1: "wrong_arguments"}) tool_result = result.messages[2]["content"][0] assert tool_result["is_error"] assert tool_result["content"] == "invalid input: missing required field 'order_id'" assert result.stop_reason == "end_turn" and result.steps == 2 def test_an_overloaded_model_error_escapes_the_loop(): with pytest.raises(ModelOverloaded): run_with({1: "overloaded"})Run the tests:
python -m pytest -q -p no:cacheproviderOutput (illustrative: the time varies):
... [100%] 3 passed in 0.03s -
Now change the schedule in
test_wrong_arguments_reach_the_model_as_an_errorfrom{1: "wrong_arguments"}to{2: "wrong_arguments"}. Predict whether the test still passes, then run pytest again.
Success: the six runs match the output above, the three tests pass, and the edited test fails while the other two still pass. That shows each fault reaching the loop in a different way, and tests that detect a change in behaviour exactly.
How the Faults Work
FaultyModel has the same create method as ScriptedModel, so the loop
cannot tell them apart; this is what lets you swap in a faulty model without
changing any other code.
self.calls += 1
fault = self.schedule.get(self.calls)
if fault == "overloaded": # the request never reaches the wrapped model
raise ModelOverloaded(...)
response = self.model.create(**request)
(Excerpt from create in kit/faults.py; the error message is shortened.)
The wrapper counts its own calls and looks the number up in the schedule. For
overloaded it raises before calling the wrapped model, as a real service
error happens before any answer exists; a later successful attempt therefore
still gets the scripted model's first reply. For the other faults it calls the
wrapped model and then changes the response: emptying tool inputs, renaming
tools, cutting the text in half with stop reason max_tokens, or replacing
everything with an empty refusal. The constructor rejects a misspelt fault
name with ValueError: unknown faults ['refused']; choose from ..., so a typo
in a schedule cannot silently test nothing.
Reading the Six Runs
- wrong_arguments and unknown_tool: the loop's validation turned the
bad request into an error result, and the scripted rule answered from it.
Both runs end with
end_turnafter two calls, so the stop reason alone hides the failure; the error result and the final text reveal it. - truncated: the run ends with stop reason
max_tokensand half an answer. Code that used the text without checking the stop reason would pass a broken sentence on to the next agent. - refusal: one call, no text, stop reason
refusal. There is nothing to pass on; the caller must decide what happens next. - overloaded: the loop does not catch it, so the exception reaches your code. That is deliberate: a temporary error is worth retrying, but deciding how often, and at which level, belongs to the code around the loop (lesson 24).
How the Tests Work
pytest finds files named test_*.py, runs every function whose name starts
with test_, and reports each assert that fails (S29).
run_with(schedule)runs the whole agent once, so each test checks real behaviour, not a copy of it.test_wrong_arguments_reach_the_model_as_an_errorchecks the exact error text the model received, not just that the run ended: as the runs showed, the stop reason is the same with and without the fault.pytest.raises(ModelOverloaded)passes only if the code inside raises that exception, which pins down that the loop lets it escape.-qshows one character per test (.passed,Ffailed);-p no:cacheproviderstops pytest writing a cache folder into the exercise.
When you moved the fault to call 2, the second call carried no tool request,
so the fault had nothing to change and the test failed at
assert tool_result["is_error"]:
.F. [100%]
=================================== FAILURES ===================================
_______________ test_wrong_arguments_reach_the_model_as_an_error _______________
def test_wrong_arguments_reach_the_model_as_an_error():
result = run_with({2: "wrong_arguments"})
tool_result = result.messages[2]["content"][0]
> assert tool_result["is_error"]
E assert False
test_order_agent.py:17: AssertionError
=========================== short test summary info ============================
FAILED test_order_agent.py::test_wrong_arguments_reach_the_model_as_an_error
1 failed, 2 passed in 0.08s
The > marks the failing line and E explains it. Change the schedule back
to {1: "wrong_arguments"} before continuing.
When It Goes Wrong
| What you see | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'faulty_runs' | pytest run from another folder | Run it inside faulty-models |
ValueError: unknown faults [...] | A misspelt fault name | Use one of the five names |
| A fault seems to do nothing | It is scheduled on a call where it has nothing to change | Check which call carries the tool request or the answer |
no tests ran | The file or functions do not start with test | Rename them |
Your Turn: A Refusal Test
Add a test named test_a_refusal_stops_the_run that runs the agent with a
refusal on the first call and checks the stop reason, the number of model
calls and the final text. Run pytest and confirm four tests pass.
Reset and Clean Up
Keep kit/faults.py. Remove the exercise folder:
cd ~/multi-agent-practice
case "$PWD" in */multi-agent-practice) rm -rf faulty-models ;; *) echo "not in the practice folder" ;; esac
PowerShell:
cd ~/multi-agent-practice
if ((Get-Location).Path -like "*multi-agent-practice") { Remove-Item -Recurse -Force faulty-models }
Check Your Understanding
- Why does
FaultyModelraiseoverloadedbefore calling the wrapped model, and what would go wrong if it called it first? - A colleague's test checks only
result.stop_reason == "end_turn"after awrong_argumentsfault. What does that test fail to detect? - Why is a fault schedule better for tests than a 10 per cent chance of failure on every call?
Answer and Reasoning
Your turn.
def test_a_refusal_stops_the_run():
result = run_with({1: "refusal"})
assert result.stop_reason == "refusal"
assert result.steps == 1 and result.text == ""
The run stops after one model call because refusal is not tool_use, and
the refused reply has no text. pytest then reports 4 passed.
Understanding check.
- A real overload error means the request got no answer at all. Raising first keeps the wrapped script in step: when the caller retries, the scripted model gives its first reply, as a real model would on a successful retry. Calling it first would use up a reply that nobody saw.
- Whether the fault had any effect. The run ends with
end_turnwith or without the fault, so the test passes even if the error never reached the model. Check the error result or the final text. - A schedule breaks the same call on every run, so the test's result never changes unless the code does. A random failure makes the same test pass or fail by chance, and a failure you cannot reproduce is very hard to fix.
References
- S19: Claude documentation, Tool use overview: stop reasons a reply can end with.
- S20: Claude documentation, Handle tool calls: returning tool errors with
is_error. - S29: pytest documentation: test discovery, assertions and
pytest.raises.