Sub topic 10
Fake streaming replies and tool calls
This chapter assumes you can write pytest tests, you know Python generators (yield), and you have read the earlier chapters on the narrow client seam and the scripted fake. It extends that fake to two shapes of reply that a single canned string can't represent.
Why one string is not enough
A plain complete() call returns one string. Two common features break that model.
- Streaming. The client yields many small chunks. Your code must join them, forward them to a UI, and survive a failure halfway through.
- Tool calls. The model replies with a request to run a function. Your code runs it, sends the result back, and calls the model again.
Both are still deterministic once you script them. The seam stays narrow, and the fake grows to match.
Fake a streaming reply
Add a second method to the seam that returns an iterator of text chunks.
from typing import Callable, Iterator, Optional, Protocol
class StreamingClient(Protocol):
def stream(self, prompt: str) -> Iterator[str]: ...
def collect_answer(
client: StreamingClient,
prompt: str,
on_chunk: Optional[Callable[[str], None]] = None,
) -> str:
parts = []
for chunk in client.stream(prompt):
parts.append(chunk)
if on_chunk:
on_chunk(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.
import pytest
class FakeStreamClient:
def __init__(self, chunks, fail_after=None, error=None):
self._chunks = list(chunks)
self._fail_after = fail_after
self._error = error or ConnectionError("stream dropped")
self.prompts = []
def stream(self, prompt: str) -> Iterator[str]:
self.prompts.append(prompt) # recorded when stream() is called
def generate():
for i, chunk in enumerate(self._chunks):
if self._fail_after is not None and i == self._fail_after:
raise self._error
yield chunk
return generate()
def test_chunks_are_joined_and_forwarded():
client = FakeStreamClient(["Hel", "lo, wor", "ld"])
seen = []
assert collect_answer(client, "hi", on_chunk=seen.append) == "Hello, world"
assert seen == ["Hel", "lo, wor", "ld"]
def test_failure_mid_stream_surfaces_after_partial_output():
client = FakeStreamClient(["Hel", "lo", " never sent"], fail_after=2)
seen = []
with pytest.raises(ConnectionError):
collect_answer(client, "hi", on_chunk=seen.append)
assert seen == ["Hel", "lo"]Split chunks inside words, as the first test does. Real providers cut text at arbitrary token boundaries, so code that assumes whole words will fail on real traffic.
Fake a tool-call loop
Here the client returns either a string (the final answer) or a ToolCall. The agent loop runs the requested tool and calls the client again.
from dataclasses import dataclass
@dataclass
class ToolCall:
name: str
arguments: dict
def run_agent(client, tools, question, max_steps=3):
messages = [{"role": "user", "content": question}]
for _ in range(max_steps):
reply = client.complete(messages)
if isinstance(reply, str):
return reply
result = tools[reply.name](**reply.arguments)
messages.append(
{"role": "tool", "name": reply.name, "content": str(result)}
)
raise RuntimeError("too many tool steps")
class FakeAgentClient:
def __init__(self, replies):
self._replies = list(replies)
self.calls = []
def complete(self, messages):
self.calls.append(list(messages)) # snapshot: the loop mutates the list
return self._replies.pop(0)
def test_tool_result_is_sent_back_to_the_model():
client = FakeAgentClient([ToolCall("add", {"a": 8, "b": 10}), "The sum is 18."])
tools = {"add": lambda a, b: a + b}
assert run_agent(client, tools, "8 + 10?") == "The sum is 18."
assert client.calls[1][-1] == {"role": "tool", "name": "add", "content": "18"}
def test_endless_tool_requests_are_stopped():
client = FakeAgentClient([ToolCall("add", {"a": 1, "b": 1})] * 3)
with pytest.raises(RuntimeError):
run_agent(client, {"add": lambda a, b: a + b}, "loop")The fake copies messages on every call. Without the copy, every entry in calls would point at the same list, and the first call would appear to contain the tool result.
What this does not prove
Useful extra cases to script: a ToolCall naming an unknown tool, arguments that fail validation, a tool that raises, and a stream that ends with zero chunks.
Exercise
In FakeAgentClient, why does complete store list(messages) instead of messages?
Show answer
The agent loop appends to the same messages list after every call. Storing the list itself would make every entry in calls reflect the final state, so a test could not check what the model was sent at each step. Copying captures a snapshot of each call.
Exercise
Using FakeStreamClient, write a test that a stream with no chunks makes collect_answer return an empty string.
Show answer
def testemptystream(): client = FakeStreamClient([]) assert collect_answer(client, "hi") == ""