Test the Agent with a Fake Model
An agent loop is ordinary code: it calls a model, runs the tools the reply asks for, sends the results back and decides when to stop. That code can be tested like any other code, as long as the test controls what the model says. This page shows how to replace the model with a scripted stand-in, so a test runs in a moment, gives the same verdict every time, and checks both what the agent did on the way and what it handed over at the end.
Why a test should not call a live model
The obvious way to test an agent is to run it against the real model and look at the answer. It works once, but it makes a poor automated test, for three reasons.
- The reply varies. A model samples its words, so the same messages can produce a different reply, a different tool call or a different number of steps on the next run. Some providers accept a
seedparameter, but the reference describes it as a best effort and states that determinism is not guaranteed. - It costs money. Every run is billed in tokens, and a suite runs many times a day.
- It is slow. Each step is a network call that takes seconds, and an agent makes several of them per run.
The first reason is the decisive one. When a test that calls a live model fails, there are two suspects: your change to the code, or a different choice by the model. The test cannot tell you which. A test is useful when a failure points at one cause, and that requires every input to be fixed, including the replies of the model.
| Aspect | Live model | Scripted fake model |
|---|---|---|
| Same replies on every run | Not guaranteed | Always |
| Cost of a run | Tokens billed | Nothing |
| Time of a run | Seconds per step | No network wait |
| Needs an API key | Yes | No |
| A failure means | The code or the model changed | The code changed |
True or false?
Passing a fixed seed to a live model makes a test that calls it fully repeatable.
False. Where a provider supports a seed, it is a best effort: the reference says determinism is not guaranteed, and the backend behind the model can change.
If a test that calls a live model fails, the failure alone does not say whether the code broke.
True. The model may simply have chosen differently on this run, so the same code can pass one run and fail the next.
Tests with pytest
A test is a function that runs a piece of code and asserts on what comes back. With pytest, the most widely used test runner for Python, that is all a test needs to be: a plain function whose name starts with test, using the plain assert statement. No base class and no special assertion methods are required.
Here is a small function that turns the arguments of a tool call, which arrive as a JSON string, into a dictionary, with two tests for it. In a real project the function lives in its own module and the test file imports it.
import json
import pytest
def parse_arguments(raw):
data = json.loads(raw)
if not isinstance(data, dict):
raise ValueError("arguments must be a JSON object")
return data
def test_parses_an_object():
assert parse_arguments('{"order_id": "1042"}') == {"order_id": "1042"}
def test_rejects_a_list():
with pytest.raises(ValueError, match="JSON object"):
parse_arguments("[1, 2]")The second test uses pytest.raises, which passes only if the code inside the with block raises the given exception. Its match argument adds a check on the message: pytest looks for that pattern in the text of the exception with re.search().
One command finds and runs every test. pytest looks in the current directory and its subdirectories for files named test_*.py or *_test.py, and in them for functions whose names start with test (and for such methods inside classes whose names start with Test). The -q flag keeps the output short: one dot per passing test, an F per failing one, then a count.
$ pytest -q
.. [100%]
2 passed in 0.02sWhen an assertion fails, pytest prints the values on both sides of the comparison, so assert result == expected shows what result actually was. It does this by rewriting the assert statements of the test files it collects before they run.
True or false?
pytest only runs tests written as methods of a class that inherits from a test base class.
False. A plain function named test_... in a file named test_*.py is collected and run; a class is optional and only needs a name starting with Test.
A file called checks.py with a function test_loop in it is not collected when you run pytest with no arguments.
True. By default pytest looks only in files named test_*.py or *_test.py.
The model as a dependency
A test can only replace the model if the loop lets it. A loop that builds its own client inside the function always talks to the real service, and the test has no way in. The fix is to make the model a dependency: something the loop receives from outside, as a parameter, instead of creating it itself.
-def run_agent(task, tools, max_steps=10):
- client = OpenAI()
+def run_agent(task, tools, model, max_steps=10):
messages = [{"role": "user", "content": task}]
while True:
- reply = client.chat.completions.create(
- model=MODEL_NAME, messages=messages, tools=SCHEMAS)
+ reply = model.create(messages, SCHEMAS)
...The loop now asks for one thing: an object with a create(messages, tools) method that returns a reply. In normal use the program passes a thin wrapper around the real chat client, which forwards the call to the provider. In a test, the test passes a stand-in with the same method. The loop never knows which one it got.
This works because the loop only reads attributes of the reply: reply.choices[0].message.tool_calls, function.name, function.arguments, finish_reason. The reply objects of the openai package are Pydantic models with those attributes, and any other object with the same attributes is read the same way.
- run_agent the agent loop
- Client wrapper calls the live model
- FakeModel returns prepared replies
- run_agent to Client wrapper: when the program runs
- run_agent to FakeModel: in a test
A scripted fake model
A fake model is a stand-in that holds a list of replies written in advance and hands them out in order, one per call. It does two jobs. It plays the model's part, including tool calls, so the loop has something to act on. And it keeps a copy of every request it received, so the test can check afterwards exactly what the loop sent.
import copy
import json
from types import SimpleNamespace as NS
class FakeModel:
def __init__(self, replies):
self.replies = list(replies)
self.requests = []
def create(self, messages, tools):
self.requests.append(copy.deepcopy(messages))
if not self.replies:
raise AssertionError("the loop called the model more times than scripted")
return self.replies.pop(0)
def tool_call(call_id, name, arguments):
if not isinstance(arguments, str):
arguments = json.dumps(arguments)
return NS(id=call_id, type="function",
function=NS(name=name, arguments=arguments))
def reply(content=None, tool_calls=None):
message = NS(role="assistant", content=content, tool_calls=tool_calls)
finish_reason = "tool_calls" if tool_calls else "stop"
return NS(choices=[NS(index=0, finish_reason=finish_reason, message=message)])Three details make this fake trustworthy.
- It copies each request. The loop keeps appending to the same
messageslist. Storing the list itself would leave the test with several references to its final state;copy.deepcopyfreezes what was sent at each call. - It fails when the script runs out. If the loop calls the model more often than the test planned, that is a bug in the loop, and the fake raises instead of returning something harmless.
- It imitates the real reply shape. In Chat Completions, a tool call's
argumentsis a JSON-encoded string, not a dictionary, andfinish_reasonistool_callswhen the model called a tool andstopwhen it finished.tool_callaccepts a dictionary for the common case and a raw string when a test needs arguments that are broken.
The standard library offers a ready-made alternative: a unittest.mock.Mock whose side_effect is a list returns the next item on each call and records every call in call_args_list. A small class like the one above does the same job and is easier to read in a test that fails.
True or false?
Appending the messages list itself, without copying it, to the requests of the fake is enough to see what the loop sent at each call.
False. All the stored entries would point to the same list, which keeps growing, so every one of them would show the final transcript.
A fake that raises when its replies run out catches a loop that calls the model once too often.
True. The extra call has no prepared reply, so the test fails at that call instead of carrying on with a made-up answer.
Checking the path as well as the result
A run of an agent has two things worth checking. The result is what the run hands back at the end: the answer and the reason it stopped. The path is the sequence of steps that led there: which tools were called, with which arguments, in which order, and what the loop sent back to the model each time. A loop can reach the right answer by the wrong path, for example by sending a tool result with the wrong tool_call_id that a real model happens to tolerate today. Asserting on the path catches that.
Here is a scripted run with one tool call. Each arrow is one step, and the fake model's replies are the two the test prepared.
- Agent loop
- FakeModel
- lookup_order
- Agent loop to FakeModel: request 1: the task
- FakeModel to Agent loop: call lookup_order 1042
- Agent loop to lookup_order: order_id = 1042
- lookup_order to Agent loop: status: shipped
- Agent loop to FakeModel: request 2: + tool result
- FakeModel to Agent loop: text answer, stop
The test writes that script, runs the loop, and then asserts on both halves. The tool is a small function that records its own calls, so the test can see how the loop used it. (The tool registry is reduced here to names and functions.)
from agent import run_agent
from fakes import FakeModel, reply, tool_call
def test_looks_up_the_order_then_answers():
looked_up = []
def lookup_order(order_id):
looked_up.append(order_id)
return {"order_id": order_id, "status": "shipped"}
fake = FakeModel([
reply(tool_calls=[tool_call("call_1", "lookup_order", {"order_id": "1042"})]),
reply(content="Order 1042 has shipped."),
])
result = run_agent("Where is order 1042?",
tools={"lookup_order": lookup_order}, model=fake)
assert result.stop_reason == "answered"
assert result.answer == "Order 1042 has shipped."
assert looked_up == ["1042"]
assert len(fake.requests) == 2
sent_back = fake.requests[1][-1]
assert sent_back["role"] == "tool"
assert sent_back["tool_call_id"] == "call_1"
assert "shipped" in sent_back["content"]Each assertion on the path pins one step. looked_up proves the tool ran once, with the argument parsed from the JSON string. len(fake.requests) proves the loop called the model exactly twice and then stopped. The last message of the second request proves the result went back as a tool message, paired with the id of the call it answers. Checking that the content contains a word, instead of comparing the whole string, keeps the test from breaking when the tool's output format changes in a way that does not matter.
Order matters too. A model can ask for several tools in one reply, and the loop has to send back a result for each of them. A test scripts a reply with two calls and checks that both results come back in the second request, each with its own id, in the order of the calls:
fake = FakeModel([
reply(tool_calls=[
tool_call("call_1", "lookup_order", {"order_id": "1042"}),
tool_call("call_2", "lookup_order", {"order_id": "1043"}),
]),
reply(content="Both orders have shipped."),
])
run_agent("Where are orders 1042 and 1043?", tools=TOOLS, model=fake)
results = [m for m in fake.requests[1] if m["role"] == "tool"]
assert [m["tool_call_id"] for m in results] == ["call_1", "call_2"]True or false?
With a fake model, an assertion on which tools were called checks the loop code, not the judgement of a model.
True. The test itself wrote which tools the fake asks for, so the assertion checks that the loop carried out those requests correctly.
If the final answer is right, assertions on the path add nothing.
False. A loop can produce the scripted answer while sending a result with the wrong id, running a tool twice or skipping one; only the path shows that.
Scripting the rare cases
A live model behaves well most of the time, which is exactly why its rare mistakes are hard to test: you cannot make it call a tool that does not exist whenever you want to. A fake model makes that call on every run. The cases worth scripting are the ones the loop has code for but a real model seldom triggers.
| Case | What the fake replies | What the test asserts |
|---|---|---|
| Unknown tool | A call to a name not in the registry | An error result goes back with that call's id, and the run continues |
| Invalid arguments | Arguments that are not valid JSON, or miss a required field | The tool never runs; an error result says what was wrong |
| A result that never comes | One tool call after another, never an answer | The run stops at the step limit with no answer and its stop reason |
The first two cases differ only in the reply the fake gives, so one test can cover them. The decorator @pytest.mark.parametrize runs the same test function once for each tuple of values in its list; here the tuples are an unknown tool name, arguments that are not valid JSON, and arguments that lack order_id. Each run checks that the bad call comes back to the model as a tool message with an error, instead of crashing the run.
import pytest
@pytest.mark.parametrize("name, arguments, expected", [
("cancel_everything", "{}", "unknown tool"),
("lookup_order", '{"order_id": 10', "not valid JSON"),
("lookup_order", '{"order": "1042"}', "order_id"),
])
def test_a_bad_call_becomes_an_error_result(name, arguments, expected):
fake = FakeModel([
reply(tool_calls=[tool_call("call_1", name, arguments)]),
reply(content="I could not do that."),
])
result = run_agent("Help me", tools=TOOLS, model=fake)
error = fake.requests[1][-1]
assert error["role"] == "tool"
assert error["tool_call_id"] == "call_1"
assert expected in error["content"]
assert result.stop_reason == "answered"The expected texts are the loop's own error messages, so these tests also pin down what the model is told when it makes a mistake.
The third case scripts a model that keeps working and never answers. Each reply asks for a different order, so the loop does not stop the run early as a repeated call. The script holds exactly as many replies as the step limit allows: three. If the loop ignored its limit, it would ask for a fourth reply, and the fake would fail the test.
def test_step_limit_ends_a_run_that_never_answers():
fake = FakeModel([
reply(tool_calls=[tool_call(f"call_{n}", "lookup_order", {"order_id": str(n)})])
for n in range(1, 4)
])
result = run_agent("Where is my order?", tools=TOOLS, model=fake, max_steps=3)
assert result.stop_reason == "max_steps"
assert result.answer is None
assert len(fake.requests) == 3True or false?
To test how a loop handles a tool name that does not exist, you have to wait until a real model produces one.
False. A scripted reply can call any name, so the case runs on every test run instead of by chance.
In a scripted invalid-arguments case, the arguments can be a string that is not valid JSON at all.
True. Arguments arrive as a JSON string generated by the model, and the API reference warns it is not always valid JSON, so this is a realistic case to script.
What a fake model cannot show
Every reply in these tests was written by the person who wrote the test. A green suite therefore proves that the code around the model is right: it parses tool calls, runs the right functions, pairs each result with its call, rejects bad requests and stops when it should. It proves nothing about whether a real model, given the same task, would choose the right tool, pass the right arguments or write a good answer. The fake never decides anything.
How well a real model decides is measured differently: by running the agent against the real model on a set of realistic tasks, several times each because the replies vary, and scoring the outcomes. That practice is called evaluation, and it is a separate subject. The two complement each other: the fake-model suite runs on every change in a moment and says the code works, and evaluation says whether the agent, with a particular model and prompt, does its job well.
| Question | Tests with a fake model | Evaluating real runs |
|---|---|---|
| Does the loop run the tool the reply names? | Yes | Indirectly |
| Does it stop at the step limit? | Yes | Only if a run happens to hit it |
| Does the model pick the right tool? | No | Yes |
| Is the final answer good? | No | Yes |
| Same verdict on every run? | Yes | No, so tasks are run several times |
True or false?
When every fake-model test passes, the agent is known to give good answers to customers.
False. The tests replay answers the test author wrote; the quality of a real model's decisions is measured by evaluating real runs.
A fake-model test can still fail after a change to the system prompt alone.
True. It fails if a test asserts on the messages sent to the model, since the system prompt is part of every request; the replies of the fake stay the same.