Sub topic 10
Fake streaming replies and tool calls
Earlier chapters used a fake client whose complete method returns one finished string. Many real applications use two other shapes of reply. A streaming reply arrives as many small chunks. A tool call asks your code to run a function and send the result back to the model. This chapter shows how to fake both, and what each one makes you test.
This chapter assumes you have read the chapters on the client seam and the scripted fake. You should be comfortable with pytest, Python generators, dataclasses, and json.loads. The examples use a made-up, simplified client interface. Real SDKs name their events differently, so map the ideas onto your SDK instead of copying the names.
To run the examples, put all the code blocks in one file named test_streaming_tools.py and run pytest.
Why these replies need their own fakes
A single-string fake hides three kinds of behavior:
- Timing and order. Your code sees text in pieces, and the pieces can end anywhere, even in the middle of a word or a JSON key.
- Failure in the middle. A stream can fail after 40 chunks. The code has then already shown partial text to the user.
- Conversation state. In a tool loop, each model call depends on the previous tool results. A fake that ignores the messages it receives cannot catch a bug where you forget to send a result back.
Your tests should cover these cases, and none of them needs a network.
Fake a streaming reply
First, a narrow seam for streaming. The client has one method, stream, which returns an iterator of text chunks. Your code joins the chunks and optionally reports each one, for example to update a terminal.
from typing import Callable, Iterator, Optional, Protocol
class StreamingClient(Protocol):
def stream(self, prompt: str) -> Iterator[str]: ...
def stream_answer(
client: StreamingClient,
prompt: str,
on_text: Optional[Callable[[str], None]] = None,
) -> str:
parts = []
for chunk in client.stream(prompt):
parts.append(chunk)
if on_text is not None:
on_text(chunk)
return "".join(parts)The fake takes a list of chunks. It can also raise an error after a chosen number of chunks, which simulates a dropped connection.
class FakeStreamingClient:
def __init__(self, chunks, error_after=None):
self._chunks = list(chunks)
self._error_after = error_after
self.prompts = []
def stream(self, prompt):
self.prompts.append(prompt)
for index, chunk in enumerate(self._chunks):
if self._error_after is not None and index == self._error_after:
raise ConnectionError("stream dropped")
yield chunkBecause stream contains yield, it is a generator function. Its body does not run until something iterates over it. So self.prompts is filled in only when stream_answer starts reading chunks. A test that calls client.stream("x") and checks client.prompts right away will find it empty. This matches a real SDK, where the request is often sent only when you begin iterating.
Test chunk boundaries and mid-stream failure
The two tests below cover the cases a single-string fake cannot.
import json
import pytest
def chunk_text(text, size):
return [text[i : i + size] for i in range(0, len(text), size)]
def test_chunks_are_joined_and_each_one_is_reported():
client = FakeStreamingClient(["Hel", "lo, ", "wor", "ld"])
seen = []
assert stream_answer(client, "hi", on_text=seen.append) == "Hello, world"
assert seen == ["Hel", "lo, ", "wor", "ld"]
assert client.prompts == ["hi"]
def test_stream_failure_surfaces_after_partial_output():
client = FakeStreamingClient(["Hel", "lo"], error_after=1)
seen = []
with pytest.raises(ConnectionError):
stream_answer(client, "hi", on_text=seen.append)
assert seen == ["Hel"]
@pytest.mark.parametrize("size", [1, 2, 3, 5, 100])
def test_result_does_not_depend_on_chunk_boundaries(size):
reply = '{"total": 42.5}'
client = FakeStreamingClient(chunk_text(reply, size))
assert json.loads(stream_answer(client, "x"))["total"] == 42.5The parametrized test is the most valuable one. Real chunk sizes vary from run to run, so a parser that works with 3-character chunks and fails with 1-character chunks is a real bug. With a fake you can try every boundary on demand.
The failure test pins down a decision that is easy to leave unmade: what should happen to the partial text? Here the error propagates and the caller has seen "Hel" through on_text. If your product should discard partial output, or retry from the start, write that behavior and then test it the same way.
Fake a tool-call loop
A tool-using model does not always return text. A reply can contain tool calls, each with an id, a tool name, and arguments. Your code runs the tool, appends the result to the conversation, and calls the model again. The loop ends when a reply has no tool calls.
Here is the application code. The data classes are simplified stand-ins for your SDK's reply types.
from dataclasses import dataclass, field
from typing import Protocol
@dataclass
class ToolCall:
id: str
name: str
arguments: dict
@dataclass
class Reply:
text: str = ""
tool_calls: list = field(default_factory=list)
class ToolClient(Protocol):
def step(self, messages: list) -> Reply: ...
def run_agent(client, question, tools, max_steps=5):
messages = [{"role": "user", "content": question}]
for _ in range(max_steps):
reply = client.step(list(messages))
if not reply.tool_calls:
return reply.text
messages.append({"role": "assistant", "tool_calls": reply.tool_calls})
for call in reply.tool_calls:
tool = tools.get(call.name)
if tool is None:
result = f"error: unknown tool {call.name}"
else:
try:
result = str(tool(**call.arguments))
except Exception as exc:
result = f"error: {exc}"
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": result}
)
raise RuntimeError("agent did not finish within max_steps")The call client.step(list(messages)) passes a copy of the list. The loop keeps appending to messages, so without the copy a fake that stores what it received would see its earlier snapshots change. The copy keeps each recorded snapshot equal to what the model would have seen at that moment.
The fake is the scripted fake from earlier, adapted to return Reply objects and to keep every message list it receives.
class FakeToolClient:
def __init__(self, replies):
self._replies = list(replies)
self.seen = []
def step(self, messages):
self.seen.append(messages)
if not self._replies:
raise AssertionError("FakeToolClient ran out of scripted replies")
return self._replies.pop(0)What to assert
Do not only check the final text. The final text comes from your script, so asserting on it proves little. Assert on what your code did in between.
def test_agent_runs_the_tool_and_sends_the_result_back():
client = FakeToolClient(
[
Reply(tool_calls=[ToolCall("call_1", "get_weather", {"city": "Oslo"})]),
Reply(text="It is 3 C in Oslo."),
]
)
calls = []
def get_weather(city):
calls.append(city)
return "3 C"
answer = run_agent(client, "Weather in Oslo?", {"get_weather": get_weather})
assert answer == "It is 3 C in Oslo."
assert calls == ["Oslo"]
assert client.seen[1][-1] == {
"role": "tool",
"tool_call_id": "call_1",
"content": "3 C",
}
def test_unknown_tool_is_reported_back_to_the_model():
client = FakeToolClient(
[
Reply(tool_calls=[ToolCall("c1", "delete_all", {})]),
Reply(text="Sorry, I cannot do that."),
]
)
run_agent(client, "go", {})
assert client.seen[1][-1]["content"] == "error: unknown tool delete_all"
def test_tool_exception_becomes_an_error_message():
def broken(city):
raise KeyError(city)
client = FakeToolClient(
[
Reply(tool_calls=[ToolCall("c1", "get_weather", {"city": "Oslo"})]),
Reply(text="done"),
]
)
run_agent(client, "go", {"get_weather": broken})
assert client.seen[1][-1]["content"].startswith("error:")
def test_runaway_tool_loop_is_stopped():
looping = Reply(tool_calls=[ToolCall("c", "ping", {})])
client = FakeToolClient([looping] * 3)
with pytest.raises(RuntimeError):
run_agent(client, "go", {"ping": lambda: "pong"}, max_steps=3)
assert len(client.seen) == 3The first test checks three things: the tool ran with the right arguments, the result went back with the matching tool_call_id, and the second model call saw it. Forgetting the id, or sending the result as the wrong role, is a common bug. A real API rejects it, so the fake test is where you catch it first.
The last two tests show what only a fake can do cheaply. A real model almost never asks for an unknown tool or loops forever, but production eventually does both.
Streamed tool calls
Some APIs stream tool calls too. The tool name arrives first, then the arguments as JSON fragments that are not valid JSON until the last one. Your code has to buffer the fragments and parse once, at the end.
You can fake this with a list of events. The fake does not need to match your SDK's event classes exactly, but it should follow the same order and splitting rules.
def collect_streamed_call(events):
call_id = name = None
buffer = []
for kind, value in events:
if kind == "start":
call_id, name = value
elif kind == "args":
buffer.append(value)
return ToolCall(call_id, name, json.loads("".join(buffer)))
def test_arguments_are_parsed_only_after_all_fragments_arrive():
args = '{"city": "Oslo", "units": "metric"}'
events = [("start", ("c1", "get_weather"))]
events += [("args", piece) for piece in chunk_text(args, 4)]
call = collect_streamed_call(events)
assert call == ToolCall("c1", "get_weather", {"city": "Oslo", "units": "metric"})
def test_truncated_arguments_raise_instead_of_guessing():
events = [("start", ("c1", "get_weather")), ("args", '{"city": "Os')]
with pytest.raises(json.JSONDecodeError):
collect_streamed_call(events)The second test covers a stream that stops early. Decide what the code should do with a half-finished call, then fix that decision in a test. Running a tool on guessed arguments is rarely what you want.
What each behavior needs
| Behavior to test | How the fake produces it | What to assert |
|---|---|---|
| Chunk boundaries | Split one reply at many sizes | Same result for every size |
| Dropped connection | Raise after N chunks | Partial output handling, error type |
| Tool call then answer | Script a `Reply` with `tool_calls`, then a text `Reply` | Tool arguments, result sent back with matching id |
| Bad tool name or arguments | Script a call the tools dict cannot serve | Error text returned to the model |
| Runaway loop | Script the same tool call repeatedly | Step limit raises |
| Truncated tool arguments | End the fragment list early | Parse error, no tool run |
Keep the fakes honest
- Keep the fake as simple as the interface allows. Add timing, such as
time.sleepbetween chunks, only if the code under test has a timeout. Otherwise it only slows the suite. - Do not test the SDK's own streaming code. Your fake replaces the SDK, so the tests cover your parsing, buffering, and loop logic.
- Test one failure per test. A stream that drops and then retries is two behaviors. Script them separately first, then combine them in one test for the retry path.
Exercise
In run_agent, the call is client.step(list(messages)). Suppose you change it to client.step(messages). Which assertion in test_agent_runs_the_tool_and_sends_the_result_back would break, and why?
Show answer
client.seen[1][-1] would break. Without the copy, client.seen[0] and client.seen[1] would be the same list object, so both would end up with the user, assistant, and tool messages. The test still reads seen[1][-1] and might pass, but any check on seen[0], such as "the first call contained only the user message", would fail because that snapshot has been changed by later appends. The copy keeps each snapshot equal to what the model saw at that step.
Exercise
Add a test that checks stream_answer closes nothing and loses no text when the fake yields an empty-string chunk in the middle of the stream. What should the test assert, and does the current code pass it?
Show answer
Use FakeStreamingClient(["a", "", "b"]), pass seen.append as on_text, and assert that the result is "ab" and seen == ["a", "", "b"]. The current code passes, because it joins whatever chunks arrive and reports each one, including empty ones. If you decide the callback should skip empty chunks, change the code to if on_text is not None and chunk: and update the expected seen to ["a", "b"].