Chapter 2, How LLMs work, just enough, treated a model call mostly as an idea: tokens in and out, one shared context window, and output that varies with sampling. Its scripts called the SDK directly to count tokens and compare samples. This chapter puts that call behind a small interface of our own and makes it dependable.
By the end you will be able to:
- Send a messages request with a system prompt and read back the content, stop reason and token usage.
- Put the provider behind a
ModelClientinterface whose model name and API key come from the environment. - Stream a reply to the terminal, and say when streaming is worth it.
- Bound every call with a timeout, an output-token cap and retry settings, so a failed model call prints one clear line instead of a traceback.
- Test all of it against a fake model, with no API key set.
The running example stays with Maya Okafor, Kestrel's Support Lead, and ticket T-000407, the late-delivery ticket from Chapter 1. She wants a first draft of the next reply. Nothing here is an agent. This chapter builds one slice: the draft on its own is a single model call, point 2 on Chapter 1's autonomy spectrum. Maya's whole ticket, the order-status check plus a draft a person reviews, still starts at point 3, as Chapter 1 placed it.
The code is in books-code/agentic-ai-foundations/ch03-talking-to-models/, as the ch03 package. It is tested with Python 3.12, anthropic 2.8, pydantic 2.14 and httpx 0.28, plus httpx2 2.16, which the SDK installs and only the adapter and its tests import. Where the chapter describes SDK behaviour, that is as of November 2026 for the pinned version, and the links in the text go to primary sources.
Python you need here, beyond functions and classes: a generator hands back values one at a time with yield, and yield from passes on every value of another iterator. A context manager is what a with block opens and always closes. A typing.Protocol lists the methods an object must have, without a base class.
1. A messages request: roles, the message list and the system prompt
A request to the Messages API has four parts that matter for now: the model, a maximum number of output tokens, a system prompt and a list of messages. Each message has a role, user or assistant, and content. Content can be a plain string, shorthand for one text block, or a list of blocks; in this chapter it is always text.
The API keeps nothing between calls. To ask a follow-up, you append the model's reply as an assistant message and your next question as a user message, then send the whole list again, and every resent message counts against the context window. Chapter 10 manages that history as conversation state. Here the list holds one user message carrying Maya's ticket.
The system prompt is not a message. It is a separate parameter sent with every request, so its tokens count as input on every call, and it sets the model's role, the task, the constraints and the output format. It is not secret either: anyone who can read the code or the request logs can read it, so keep credentials and internal notes out of it. Chapter 4, Prompting for agents, gives it structure.
The prompt and the two ticket helpers live in one small module that every script imports, tests included:
"""The system prompt and the two ticket helpers that every script in this chapter shares."""
import json
import httpx
SYSTEM_PROMPT = (
"You draft replies for a Kestrel Outfitters support representative to review. "
"Be polite and specific. Never promise a refund. "
"Keep the reply under 150 words."
)
def fetch_ticket(base_url: str, ticket_id: str) -> dict:
response = httpx.get(f"{base_url}/tickets/{ticket_id}", timeout=5.0)
response.raise_for_status()
return response.json()
def build_user_text(ticket: dict) -> str:
return (
f"Ticket {ticket['ticket_id']}: {ticket['subject']}\n\n"
f"Messages so far:\n{json.dumps(ticket['messages'], indent=2)}\n\n"
"Draft the next reply to the customer."
)Start the mock with uv run kestrel up from ch03-talking-to-models/, in another terminal. Then curl http://127.0.0.1:8700/tickets/T-000407 shows the seeded ticket: a customer asking where order O-0006066 is, and one holding reply.
Here is the first call, made straight against the SDK so you can see the raw shape. It needs a .env file first. Copy .env.example to .env and add an API key from your provider's console. The model and prices are Chapter 2's examples; check them before you trust the cost line:
# Copy to .env (never committed). Model and prices are examples copied from Chapter 2's
# template (last checked there: 2026-11-16). Check them again before use at
# https://platform.claude.com/docs/en/about-claude/pricing
ANTHROPIC_API_KEY=
# A current model from your provider that supports tool calling.
MODEL=claude-haiku-5-5
# USD per million tokens, from that page.
INPUT_PRICE_PER_MTOK=0.10
OUTPUT_PRICE_PER_MTOK=0.50
# Optional (these are the defaults)
MAX_OUTPUT_TOKENS=400
MODEL_TIMEOUT_S=30
MAX_RETRIES=2
# off sends thinking disabled. Some current models reject that: then set adaptive
# and raise MAX_OUTPUT_TOKENS, because thinking tokens count against it.
MODEL_THINKING=off
KESTREL_URL=http://127.0.0.1:8700The scripts read .env through uv run --env-file .env, and the folder's .gitignore keeps the file out of git. Settings.from_env() reads these variables; the settings section below shows how. With the mock running, run uv run --env-file .env python -m ch03.first_call from the same folder:
"""One raw SDK call, to see the response's shape. The CLI does not use this file."""
import anthropic
from ch03.settings import Settings
from ch03.ticket_prompt import SYSTEM_PROMPT, build_user_text, fetch_ticket
settings = Settings.from_env()
assert settings.api_key is not None, "set ANTHROPIC_API_KEY in .env"
ticket = fetch_ticket(settings.kestrel_url, "T-000407")
client = anthropic.Anthropic(api_key=settings.api_key.get_secret_value())
response = client.messages.create(
model=settings.model, # from .env, never a literal
max_tokens=settings.max_output_tokens,
system=SYSTEM_PROMPT, # a parameter, not a message
messages=[{"role": "user", "content": build_user_text(ticket)}],
# Thinking off unless MODEL_THINKING=adaptive, as in the adapter (see its section).
thinking={"type": "disabled"} if settings.thinking == "off" else anthropic.omit,
)
print(response.content) # a list of blocks, not a string
print(response.stop_reason) # why generation ended
print(response.usage) # token countsThe same create call can also carry tool definitions, which Chapter 6, Tool calling from first principles, covers.
2. Reading the response: content, stop reason and usage
A correct run prints three things: a list of content blocks, the stop reason and a Usage object. Later chapters read the same three fields. Here is the shape, from fake-model output, not a live run: the canned response in tests/test_anthropic_adapter.py (message_json("end_turn")), read by the real SDK and printed by the same three lines:
[TextBlock(citations=None, text='Hello ', type='text'), TextBlock(citations=None, text='Maya.', type='text')]
end_turn
Usage(cache_creation=None, cache_creation_input_tokens=None, cache_read_input_tokens=None, inference_geo=None, input_tokens=100, output_tokens=20, output_tokens_details=None, server_tool_use=None, service_tier=None, speed=None)A live run shows your draft in the text blocks and real counts in Usage.
Content is a list of blocks. While it is all text, response.content[0].text looks fine. Once tools are in the request, the list can hold a tool call before, after or instead of the text, and code that indexes the first element breaks. Filter by block type and join the text blocks instead, as the adapter does below.
Stop reason says why generation ended. In the pinned SDK the field can be end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal or model_context_window_exceeded.
The stop-reason docs say what each means: max_tokens means the reply reached your limit, so it was cut off and is not a finished answer, and a reply that fills the context window should be treated as truncated too.
The adapter maps them to four neutral values, so nothing outside it depends on one provider's vocabulary:
| Provider value | Neutral StopReason | What the CLI does |
|---|---|---|
end_turn, stop_sequence | finished | Prints the draft and the footer |
max_tokens, model_context_window_exceeded | truncated | Adds a [truncated] warning |
tool_use | tool_call | Can't happen yet: this chapter sends no tools |
anything else, such as refusal | other | Adds a [stopped] warning |
The first three cover the glossary's cases: the reply finished naturally, the token limit was hit, or the model asked for a tool. The fourth, other, is this book's addition; it exists so that an unfamiliar value is labelled instead of crashing the CLI or passing silently. A refusal is a normal response, not an error, so the CLI shows a labelled message rather than a traceback; Exercise 1 gives it a value of its own.
A truncated draft must never pass as complete: a representative who skims a reply that ends mid-sentence may still send it.
Usage reports token counts, which the cost calculation needs. Input is reported in three fields, and the prompt caching docs give the total as input_tokens plus cache_creation_input_tokens plus cache_read_input_tokens.
Prompt caching lets a provider reuse an unchanged prefix of a request; this book doesn't use it, but the adapter still sums all three fields and treats a missing one as zero.
To see truncation, set MAX_OUTPUT_TOKENS=20 in .env, run the script again, then put the old value back:
uv run --env-file .env python -m ch03.first_callThe stop reason should read max_tokens, with the text stopping after a few words.
3. Settings from the environment: settings.py
Everything that can change comes from environment variables: the model, the API key, the per-token prices, the output-token cap, the timeout, the retry count, the thinking setting and the Kestrel URL. MODEL, ANTHROPIC_API_KEY, the two price variables and MODEL_TIMEOUT_S have the same names as in Chapter 2's .env.example, so your values carry over. The model and the prices have no defaults in code, so a missing value stops the program before any call is made.
"""Everything that can change lives here, read from environment variables."""
import os
from collections.abc import Mapping
from decimal import Decimal
from typing import Literal
from pydantic import BaseModel, Field, SecretStr
DEFAULT_KESTREL_URL = "http://127.0.0.1:8700" # the single Kestrel mock server
ENV_VARS = { # environment variable -> Settings field
"MODEL": "model",
"ANTHROPIC_API_KEY": "api_key",
"INPUT_PRICE_PER_MTOK": "input_price_per_mtok",
"OUTPUT_PRICE_PER_MTOK": "output_price_per_mtok",
"MAX_OUTPUT_TOKENS": "max_output_tokens",
"MODEL_TIMEOUT_S": "timeout_seconds",
"MAX_RETRIES": "max_retries",
"MODEL_THINKING": "thinking",
"KESTREL_URL": "kestrel_url",
}
class Settings(BaseModel):
model: str # a current model from your provider
api_key: SecretStr | None = None # None: only the fake model can run
input_price_per_mtok: Decimal = Field(gt=0) # USD per million input tokens
output_price_per_mtok: Decimal = Field(gt=0) # USD per million output tokens
max_output_tokens: int = Field(default=400, gt=0)
timeout_seconds: float = Field(default=30.0, gt=0)
max_retries: int = Field(default=2, ge=0)
thinking: Literal["off", "adaptive"] = "off" # off: the adapter disables thinking
kestrel_url: str = DEFAULT_KESTREL_URL
@classmethod
def from_env(cls, env: Mapping[str, str] = os.environ) -> "Settings":
"""Unset or empty variables are left out, so a default or a validation error applies."""
return cls(**{field: env[var] for var, field in ENV_VARS.items() if env.get(var)})from_env() maps each variable to a field and leaves out anything unset or empty, so either a default applies or pydantic reports the field as missing. It takes the mapping as a parameter, so tests pass a plain dictionary and never touch your real environment. The prices must be greater than zero: a placeholder of 0.00 would otherwise print a cost of zero on every call, which looks right and is wrong. SecretStr keeps the key out of reprs and logs; the library code unwraps it in one place, the adapter's constructor, and only the throwaway first_call.py does it too. An empty key leaves api_key as None, which is enough for the fake model and the tests.
Chapter 2's CONTEXT_WINDOW_TOKENS and its local check_fits() are not carried over, so a leftover value in .env is ignored: the check needs a token count from the provider, and the ModelClient has no way to ask for one until Chapter 9. Until then a request goes out unchecked, with the two outcomes Chapter 2 described. If the input plus max_tokens is over the window, a newer model may stop at the window, a limit stop the adapter reports as truncated. If the input alone is too large, the provider rejects it as a bad request, bad_request here. Sampling settings are not part of Settings either. Chapter 2 explained why its demo kept the provider's default sampling, and no such setting is added until a chapter checks the provider's docs.
Without .env, or with a required value missing, the CLI from later in the chapter stops at once and names the missing settings. The key is checked later, in build_client(), because the fake model needs none:
$ uv run python -m ch03.draft_reply T-000407
error: missing or invalid settings: MODEL, INPUT_PRICE_PER_MTOK, OUTPUT_PRICE_PER_MTOK4. A provider-neutral ModelClient
If SDK types leak into the prompting code, the tool code and the agent loop, changing provider means rewriting all three, and every test needs a network connection and a key. The capstone must work with any provider whose model supports tool calling, which is easiest to design in now, while the surface is small. The answer is an interface in the book's own terms, plus one adapter per provider that translates between it and an SDK.
"""The provider-neutral model client: the book's own types and build_client()."""
from collections.abc import Iterator, Sequence
from decimal import Decimal
from typing import Literal, Protocol
from pydantic import BaseModel
from ch03.settings import Settings
StopReason = Literal["finished", "truncated", "tool_call", "other"]
ErrorKind = Literal["timeout", "rate_limited", "auth", "bad_request", "provider_error"]
PER_MILLION = Decimal(1_000_000)
class Message(BaseModel):
role: Literal["user", "assistant"]
content: str
class Usage(BaseModel):
input_tokens: int # all input, cached tokens included
output_tokens: int
class ModelResponse(BaseModel):
text: str
stop_reason: StopReason
usage: Usage
request_id: str | None = None
class ModelError(Exception):
def __init__(self, kind: ErrorKind, message: str, request_id: str | None = None) -> None:
super().__init__(message)
self.kind = kind
self.request_id = request_id
class ModelClient(Protocol):
def complete(
self, system: str, messages: Sequence[Message], max_tokens: int
) -> ModelResponse: ...
def stream(
self, system: str, messages: Sequence[Message], max_tokens: int
) -> Iterator[str | ModelResponse]:
"""Yield text chunks as they arrive, then one final ModelResponse."""
...
def call_cost_usd(usage: Usage, settings: Settings) -> Decimal:
input_cost = usage.input_tokens * settings.input_price_per_mtok / PER_MILLION
output_cost = usage.output_tokens * settings.output_price_per_mtok / PER_MILLION
return input_cost + output_cost
class ConfigError(Exception):
"""The settings can't build a real client; the CLI turns this into one line."""
def build_client(settings: Settings) -> ModelClient:
"""The only place that picks an adapter; the SDK is imported only when it is needed."""
if settings.api_key is None:
raise ConfigError("no API key: set ANTHROPIC_API_KEY in .env (tests use the fake model)")
from ch03.anthropic_adapter import AnthropicAdapter
return AnthropicAdapter(settings)It is a Protocol, not a base class. Any object with matching complete() and stream() methods counts as a ModelClient. A type checker such as mypy would compare the methods if you ran one; Python itself checks nothing at run time. The fake model needs no inheritance and no import from the adapter.
It is small on purpose. Message.content and ModelResponse.text are plain text, the text-only subset of the glossary's message and response that this chapter needs. Chapter 6 extends these types: messages can also carry tool calls and tool results, ModelResponse gains a list of tool calls that defaults to empty, and complete() gains tool arguments whose defaults send no tools. A caller that sends strings and reads .text, like everything in this chapter, keeps working unchanged.
build_client() is the one place that picks an adapter, and it imports the SDK only when it is called, so the tests never load it. Chapter 11, Choosing a model, adds a second, and at that point the function grows a provider setting and a branch; nothing that calls ModelClient changes. Figure 3.1 shows the layers.
5. The adapter: anthropic_adapter.py
Apart from the throwaway first_call.py, the adapter is the only file that imports the SDK. Here is its first part, with complete(); stream() and the error mapping follow in their own sections:
"""The Anthropic adapter: the one library file that imports the SDK."""
from collections.abc import Iterator, Sequence
import anthropic
import httpx2 # the SDK's HTTP library, needed for errors raised mid-stream
from ch03.model_client import Message, ModelError, ModelResponse, StopReason, Usage
from ch03.settings import Settings
_STOP_REASONS: dict[str, StopReason] = {
"end_turn": "finished",
"stop_sequence": "finished",
"max_tokens": "truncated",
"model_context_window_exceeded": "truncated",
"tool_use": "tool_call",
}
CONNECT_TIMEOUT_S = 5.0 # the SDK's own connect default; an unreachable host fails fast
class AnthropicAdapter:
def __init__(
self, settings: Settings, http_client: anthropic.DefaultHttpxClient | None = None
) -> None:
assert settings.api_key is not None
self._model = settings.model
self._client = anthropic.Anthropic(
api_key=settings.api_key.get_secret_value(), # the one place the key is unwrapped
timeout=anthropic.Timeout(settings.timeout_seconds, connect=CONNECT_TIMEOUT_S),
max_retries=settings.max_retries,
http_client=http_client, # None in real use; tests pass a fake transport
)
# Thinking tokens count against max_tokens, and the neutral types carry no
# thinking blocks, so thinking is off unless MODEL_THINKING=adaptive.
self._thinking: dict = (
{"thinking": {"type": "disabled"}} if settings.thinking == "off" else {}
)
def complete(self, system: str, messages: Sequence[Message], max_tokens: int) -> ModelResponse:
try:
response = self._client.messages.create(
model=self._model,
max_tokens=max_tokens,
system=system,
messages=_to_sdk_messages(messages),
**self._thinking,
)
except anthropic.APIError as exc:
raise _to_model_error(exc) from exc
return _to_model_response(response, response._request_id)The constructor is where the key leaves its SecretStr, and the timeout, retry count and thinking setting come from Settings. The optional http_client exists for the adapter's own tests, which swap in a canned transport. Every SDK error is caught at this boundary and re-raised as a ModelError, and raise ... from exc keeps the original chained for debugging.
Each request also sends thinking disabled unless MODEL_THINKING is adaptive. Chapter 2 found that the configured model thinks by default, and thinking tokens count against max_tokens, so with the 400-token cap a reply could come back truncated or empty. The neutral types also carry no thinking blocks. Some current models reject disabling it; with those, set MODEL_THINKING=adaptive and raise MAX_OUTPUT_TOKENS.
Two private helpers translate in each direction:
def _to_sdk_messages(messages: Sequence[Message]) -> list[anthropic.types.MessageParam]:
return [{"role": m.role, "content": m.content} for m in messages]
def _to_model_response(response: anthropic.types.Message, request_id: str | None) -> ModelResponse:
u = response.usage
input_total = (
u.input_tokens + (u.cache_creation_input_tokens or 0) + (u.cache_read_input_tokens or 0)
)
return ModelResponse(
# Join every text block; skip block types this chapter doesn't handle yet.
text="".join(block.text for block in response.content if block.type == "text"),
stop_reason=_STOP_REASONS.get(response.stop_reason or "", "other"),
usage=Usage(input_tokens=input_total, output_tokens=u.output_tokens),
request_id=request_id,
)_to_model_response() joins the text blocks, reports input as the sum of the three input fields, and maps the stop reason. An unrecognised value becomes other, not a guess or a crash. Both methods also keep the request id, which matters when a call goes wrong.
A neutral interface hides what one provider offers and others don't, such as caching controls or reasoning settings. When a chapter needs one, it can extend the interface deliberately, with a fake-model test to match, or accept an adapter-specific path that is no longer portable. What I would avoid is an abstraction designed up front for features nobody uses yet.
6. Putting a price on each call
Chapter 2 estimated the cost of a call before making it. Each response now reports the actual counts, so the CLI prices every call after it returns with call_cost_usd(), the same arithmetic as Chapter 2's estimate_cost() applied to reported usage: tokens times the price per million, divided by a million, for each side.
Money is a Decimal, never a float: a binary float can't represent most decimal fractions exactly, so thousands of tiny per-call costs drift from the true total. The prices in Settings are Decimal too, so the string from .env never passes through a float.
The function charges every input token at one rate. If you use prompt caching, check how your provider prices cached tokens before you trust the figure.
7. Bounding every call: timeout, max output tokens and SDK retries
A call can go wrong in three quiet ways: it can hang, it can run longer than the task needs, or it can turn into several requests without your code knowing. Each has a setting.
Timeout. By default the SDK waits up to 10 minutes for a request, which suits a batch job but not Maya at a terminal. A timed-out request raises APITimeoutError, but by default only after it has been retried twice.
The SDK's timeout option takes a number or a Timeout object, and the SDK sends requests with httpx2, an API-compatible fork of httpx.
uv sync installs httpx2 with the SDK; the pinned httpx serves the Kestrel API.
In the httpx timeout model there are separate connect, read, write and pool timeouts, and the read timeout is the longest wait for the next chunk of data. The SDK's default keeps the connect limit at 5 seconds inside its 10 minutes.
The adapter keeps that split. MODEL_TIMEOUT_S sets the read, write and pool limits, and CONNECT_TIMEOUT_S, a fixed constant in the adapter rather than a setting, keeps the SDK's 5-second connect default, so an unreachable host fails fast instead of waiting out the read limit.
A non-streaming call receives nothing until the reply is complete, so the read limit acts roughly as a per-attempt limit. A stream that keeps delivering chunks can run well past it. For a true wall-clock limit on a stream, check time.monotonic() while reading; Exercise 2 builds that. The timeout is set once, on the client; Chapter 7 adds a per-call timeout that the agent loop shrinks to fit the run's time budget.
Max output tokens. This is a hard ceiling on how many tokens the model generates in one response, sent with each request as max_tokens. It bounds latency and the output side of the cost, and, as Chapter 2 explained, it shares the context window with the input. A short support draft needs a few hundred tokens, hence the default of 400.
SDK retries. By default the Python SDK retries twice, with a short exponential backoff, on connection errors and on 408, 409, 429 and 5xx responses. So one messages.create() call can become three HTTP requests.
Each retry is a full request, which lengthens the slow path; the adapter's tests check exactly that count. Wrap the call in your own retry loop and the attempts multiply: three tries around three tries is nine requests. Chapter 5's bounded retry is a different thing: a loop on content that sends a new request when the output fails validation, and each attempt keeps the SDK's own retries.
Exponential backoff means waiting longer after each failed attempt; jitter adds a random amount so clients that failed together don't retry together. MAX_RETRIES sets the adapter's retry count, which for this adapter is the SDK's, so each call has exactly one retry layer. Chapter 7 lowers the default to 1, because inside a loop every step multiplies these retries.
For a complete() call, the worst case is roughly timeout_seconds times one plus max_retries, plus the backoff: with the defaults, about 90 seconds before Maya sees the error line. Treat it as an estimate: connecting has its own limit, and the read limit restarts whenever data arrives. For an interactive terminal I would lower MAX_RETRIES first, assuming slowness is rarely fixed by a second try. Figure 3.2 traces one call.
8. When the call fails anyway
Once its retries run out, the SDK raises an exception from one of two families. Connection errors, timeouts included, cover requests that got no usable answer. Status errors cover failures the provider returned: authentication, rate limiting, bad requests and server errors. Code above the adapter shouldn't need these class names, so the adapter translates them:
def _to_model_error(exc: anthropic.APIError) -> ModelError:
request_id = getattr(exc, "request_id", None) # only status errors carry one
if isinstance(exc, anthropic.APITimeoutError): # check before its parent class
return ModelError("timeout", "the request timed out", request_id)
if isinstance(exc, anthropic.APIConnectionError):
return ModelError("provider_error", "could not reach the provider", request_id)
if isinstance(exc, (anthropic.AuthenticationError, anthropic.PermissionDeniedError)):
return ModelError("auth", "the API key was rejected", request_id)
if isinstance(exc, anthropic.RateLimitError):
return ModelError("rate_limited", "the provider is rate limiting this key", request_id)
if isinstance(exc, (anthropic.BadRequestError, anthropic.NotFoundError)): # 404: unknown MODEL
return ModelError("bad_request", "the provider rejected the request", request_id)
return ModelError("provider_error", "the provider returned an error", request_id)The adapter also maps a 404 to bad_request. That is a design choice, not documented behaviour: I assume a mistyped MODEL is the likeliest cause, so the CLI message says to check it.
The order of the checks matters. In the pinned SDK, APITimeoutError is a subclass of APIConnectionError, so the timeout check has to come first.
Keep the request id. Successful responses expose a _request_id property, read from the request-id header, so that failing requests can be logged and reported.
Status errors carry the same header as request_id; connection errors have no response, so getattr falls back to None.
The CLI catches ModelError and nothing broader, so a bug in our own code still produces a full traceback. Two habits go with this code. Never log the key: an f-string around get_secret_value() undoes everything SecretStr does. And don't print full prompts by default, because ticket messages can contain customer names, addresses and order details.
9. Streaming Maya's draft to the terminal
Run first_call.py again and the terminal sits blank until the whole reply appears at once: a non-streaming call returns only after the model generates its last token. Streaming delivers the output as it is generated. It doesn't make generation faster; it changes when the reader sees the first words.
On the wire, a streamed response is a series of server-sent events: the server keeps the connection open and writes one named event at a time. The streaming docs give the order: message_start, then each content block as content_block_start, any number of content_block_delta events and content_block_stop, then one or more message_delta events, and finally message_stop. The message_delta events, which update the final message, come after all the text.
That order shapes the code. The adapter yields text as it arrives and builds its ModelResponse only when the stream ends, so the CLI's truncation warning and cost line wait for the final item, as Figure 3.3 shows. Here is stream(), using the SDK's stream helper:
def stream(
self, system: str, messages: Sequence[Message], max_tokens: int
) -> Iterator[str | ModelResponse]:
try:
with self._client.messages.stream(
model=self._model,
max_tokens=max_tokens,
system=system,
messages=_to_sdk_messages(messages),
**self._thinking,
) as stream:
yield from stream.text_stream
final = stream.get_final_message()
request_id = stream.request_id
except anthropic.APIError as exc:
raise _to_model_error(exc) from exc
except httpx2.TimeoutException as exc: # a stall while the body is read
raise ModelError("timeout", "the stream stalled") from exc
except httpx2.TransportError as exc: # the connection dropped partway
raise ModelError("provider_error", "the stream was interrupted") from exc
yield _to_model_response(final, request_id)The with block does the important work. The SDK's helpers documentation says the stream is cancelled when its context manager exits.
If the caller closes this generator early, Python raises GeneratorExit at the paused yield; it is not an ordinary exception, so it passes every except, leaves the with block, and the stream is cancelled on the way out. Ctrl+C therefore releases the connection, as long as the caller closes the generator rather than abandoning it.
Streaming adds a failure mode that complete() doesn't have: an error after some text has already reached the terminal. The CLI marks it [incomplete], prints the error on stderr, skips the footer and exits with status 1. A connection can also drop while the body is being read. An adapter test gives the real SDK a transport that does exactly that, and the httpx2 error reaches the caller unwrapped, so stream() also catches httpx2's timeout and transport errors and turns them into a ModelError.
Streaming helps when three things are true: a person is watching, the output is long enough for the wait to matter, and the text will be displayed rather than processed. When code has to parse the output (Chapter 5, Structured outputs) or act on tool calls (Chapters 6 and 7), streaming only adds code to reassemble the pieces, because a program can't validate half a JSON object. For anything a program consumes, I would default to complete(); the capstone does too, and prints its answer when the run ends.
10. The CLI: draft_reply.py
"""Stream a draft reply to one Kestrel ticket: uv run --env-file .env python -m ch03.draft_reply"""
import argparse
import sys
from contextlib import closing
from pydantic import ValidationError
from ch03.model_client import (
ConfigError,
Message,
ModelClient,
ModelError,
ModelResponse,
build_client,
call_cost_usd,
)
from ch03.settings import ENV_VARS, Settings
from ch03.ticket_prompt import SYSTEM_PROMPT, build_user_text, fetch_ticket
FIELD_TO_VAR = {field: var for var, field in ENV_VARS.items()}
def stream_draft(client: ModelClient, settings: Settings, messages: list[Message]) -> ModelResponse:
final: ModelResponse | None = None
printed = False
with closing(client.stream(SYSTEM_PROMPT, messages, settings.max_output_tokens)) as items:
try:
for item in items:
if isinstance(item, ModelResponse):
final = item
else:
print(item, end="", flush=True)
printed = True
except ModelError:
if printed:
print("\n[incomplete] The stream failed partway. The text above is not a draft.")
raise
print()
if final is None:
raise ModelError("provider_error", "the stream ended without a final response")
return final
def print_footer(response: ModelResponse, settings: Settings) -> None:
if response.stop_reason == "truncated":
print("[truncated] This draft hit the output token limit. Do not send it as is.")
elif response.stop_reason != "finished":
print("[stopped] The model stopped for a reason this client does not handle yet.")
cost = call_cost_usd(response.usage, settings)
print(
f"stop: {response.stop_reason} | in: {response.usage.input_tokens} "
f"| out: {response.usage.output_tokens} | cost: ${cost:.6f}"
)
def friendly_message(err: ModelError, settings: Settings) -> str:
messages = {
"timeout": f"The request timed out (MODEL_TIMEOUT_S={settings.timeout_seconds}, "
f"MAX_RETRIES={settings.max_retries}).",
"rate_limited": "The provider is rate limiting this API key. Try again shortly.",
"auth": "The API key was rejected. Check ANTHROPIC_API_KEY.",
"bad_request": "The provider rejected the request. Check MODEL and MAX_OUTPUT_TOKENS.",
"provider_error": "The provider could not be reached or returned an error.",
}
return messages[err.kind]
def run(client: ModelClient, settings: Settings, ticket: dict, *, stream: bool = True) -> int:
messages = [Message(role="user", content=build_user_text(ticket))]
try:
if stream:
response = stream_draft(client, settings, messages)
else:
response = client.complete(SYSTEM_PROMPT, messages, settings.max_output_tokens)
print(response.text)
except ModelError as err:
print(f"error: {friendly_message(err, settings)}", file=sys.stderr)
if err.request_id:
print(f"request id: {err.request_id}", file=sys.stderr)
return 1
print_footer(response, settings)
return 0
def main() -> None:
parser = argparse.ArgumentParser(description="Draft a reply to one Kestrel ticket.")
parser.add_argument("ticket_id", help="for example T-000407")
parser.add_argument("--no-stream", action="store_true", help="wait for the whole reply")
args = parser.parse_args()
try:
settings = Settings.from_env() # fails fast on missing configuration
except ValidationError as exc:
names = ", ".join(FIELD_TO_VAR[str(e["loc"][0])] for e in exc.errors())
raise SystemExit(f"error: missing or invalid settings: {names}") from None
try:
client = build_client(settings) # no network yet: a missing key is reported first
except ConfigError as exc:
raise SystemExit(f"error: {exc}") from None
ticket = fetch_ticket(settings.kestrel_url, args.ticket_id) # before any model call
try:
code = run(client, settings, ticket, stream=not args.no_stream)
except KeyboardInterrupt:
print("\n[cancelled] The draft was abandoned.", file=sys.stderr)
code = 130
raise SystemExit(code)
if __name__ == "__main__":
main()flush=True is required; without it Python buffers stdout and the text still arrives in one lump. closing() closes the generator even when a ModelError or a Ctrl+C escapes the loop, and closing it releases the SDK stream.
run() takes a client, the settings and a ticket, and returns an exit code. It fetches nothing and never exits the process, which is what makes it testable. main() does the I/O: it loads the settings, turning a validation error into the one-line message shown in the settings section, then builds the client and fetches the ticket, both before any model call. build_client() touches no network, so a missing key is reported first; it raises ConfigError instead of exiting, so code that isn't a CLI can catch it, and a test covers that path. --no-stream calls complete() and prints the same footer.
With the mock running and a key in .env, uv run --env-file .env python -m ch03.draft_reply T-000407 streams the draft in pieces and ends with one footer line. With the made-up numbers the tests use (1,000 input tokens at $2 per million, 200 output tokens at $10 per million) that line reads:
stop: finished | in: 1000 | out: 200 | cost: $0.004000Your draft and counts will differ. Then try the failure paths by editing .env: an invalid ANTHROPIC_API_KEY, then MODEL_TIMEOUT_S=0.01. The lines below show the CLI's messages, not a recorded session; the request id is a placeholder:
error: The API key was rejected. Check ANTHROPIC_API_KEY.
request id: req_...
error: The request timed out (MODEL_TIMEOUT_S=0.01, MAX_RETRIES=2).Both exit with status 1 and no traceback. The timeout line reports the settings rather than claiming retries happened, because with MAX_RETRIES=0 none would. Ctrl+C partway through a stream prints [cancelled] and exits with 130. A truncated or stopped draft still exits with 0: it is labelled on screen, and a person reads every draft before it is sent.
Two expected failures are still unhandled: an unknown ticket ID and a mock that isn't running both end in an httpx traceback. Exercise 3 fixes them.
11. FakeModelClient: tests that need no API key
A test that calls a real model is slow, costs money and needs a key, and its output varies between runs, so an assertion on exact text eventually fails for a reason you can't fix. The fake model is a ModelClient that returns responses you scripted in advance. It replaces Chapter 2's SDK-level FakeClient and recorded fixtures with a fake at the book's own interface.
"""The fake model: scripted replies and errors, every call recorded, no network."""
from collections.abc import Iterator, Sequence
from dataclasses import dataclass
from pydantic import BaseModel
from ch03.model_client import Message, ModelError, ModelResponse, Usage
class ScriptExhausted(AssertionError):
"""The code under test made more model calls than the script allows."""
@dataclass
class FailMidStream:
"""stream() yields partial_text in chunks, then raises error; complete() just raises."""
partial_text: str
error: ModelError
ScriptItem = str | ModelResponse | ModelError | FailMidStream
class Call(BaseModel):
system: str
messages: list[Message]
max_tokens: int
class FakeModelClient:
def __init__(self, script: Sequence[ScriptItem], chunk_size: int = 12) -> None:
self._script = list(script)
self._chunk_size = chunk_size
self.calls: list[Call] = []
def complete(self, system: str, messages: Sequence[Message], max_tokens: int) -> ModelResponse:
item = self._next(system, messages, max_tokens)
if isinstance(item, FailMidStream):
raise item.error
return item
def stream(
self, system: str, messages: Sequence[Message], max_tokens: int
) -> Iterator[str | ModelResponse]:
item = self._next(system, messages, max_tokens)
text = item.partial_text if isinstance(item, FailMidStream) else item.text
for i in range(0, len(text), self._chunk_size):
yield text[i : i + self._chunk_size]
if isinstance(item, FailMidStream):
raise item.error
yield item
def _next(
self, system: str, messages: Sequence[Message], max_tokens: int
) -> ModelResponse | FailMidStream:
self.calls.append(Call(system=system, messages=list(messages), max_tokens=max_tokens))
if not self._script:
raise ScriptExhausted(f"the script ran out at call {len(self.calls)}")
item = self._script.pop(0)
if isinstance(item, ModelError):
raise item
if isinstance(item, str): # shorthand: a finished reply with word counts as usage
words = len(system.split()) + sum(len(m.content.split()) for m in messages)
usage = Usage(input_tokens=words, output_tokens=len(item.split()))
return ModelResponse(text=item, stop_reason="finished", usage=usage)
return itemErrors sit in the script next to responses, so a timeout is as easy to test as a good draft, and FailMidStream covers text followed by a failure. A plain string is shorthand for a finished reply, with word counts standing in for token counts. Every call is recorded as a Call, so a test can check what your code sent as well as how it handled the reply. When the script runs out, the fake raises ScriptExhausted, a subclass of AssertionError, so an unexpected extra call is a plain test failure and the fake never makes up a response.
A fake can drift from the real provider: word counts are not token counts, and the fake never refuses or reports cached tokens. Tests that check cost script an explicit ModelResponse, as the CLI tests below do, and the three live tests, which need your key and were not run for this book, are the check you can run to keep the fake honest.
The CLI tests drive run() directly and build Settings by hand, so they never read .env. The last one fetches the real seeded ticket from the mock, which the folder's conftest.py starts inside the test process if you haven't:
from decimal import Decimal
import pytest
from ch03.draft_reply import run
from ch03.fake_model import FailMidStream, FakeModelClient, ScriptExhausted
from ch03.model_client import ModelError, ModelResponse, StopReason, Usage
from ch03.settings import Settings
from ch03.ticket_prompt import SYSTEM_PROMPT, fetch_ticket
TICKET = {"ticket_id": "T-000407", "subject": "Where is my order?", "messages": []}
# Test values only. Built directly, so no .env file or environment variable is read.
SETTINGS = Settings(
model="fake", input_price_per_mtok=Decimal("2"), output_price_per_mtok=Decimal("10")
)
def reply(text: str, stop: StopReason = "finished") -> ModelResponse:
usage = Usage(input_tokens=1_000, output_tokens=200)
return ModelResponse(text=text, stop_reason=stop, usage=usage)
def test_streamed_draft_prints_text_and_footer(capsys):
fake = FakeModelClient([reply("Thanks for your patience with order O-0006066.")], chunk_size=5)
assert run(fake, SETTINGS, TICKET) == 0
out = capsys.readouterr().out
assert "Thanks for your patience with order O-0006066." in out # chunks reassembled
assert "stop: finished" in out
assert "cost: $0.004000" in out # 1,000 x $2/M + 200 x $10/M
@pytest.mark.parametrize("stop, label", [("truncated", "[truncated]"), ("other", "[stopped]")])
def test_unfinished_replies_are_labelled_not_crashed(capsys, stop, label):
assert run(FakeModelClient([reply("Thanks for", stop)]), SETTINGS, TICKET) == 0
assert label in capsys.readouterr().out
def test_timeout_gives_one_line_and_nonzero_exit(capsys):
code = run(FakeModelClient([ModelError("timeout", "timed out")]), SETTINGS, TICKET)
assert code == 1
assert "timed out" in capsys.readouterr().err
def test_failure_after_some_text_marks_it_incomplete(capsys):
fake = FakeModelClient(
[FailMidStream("Thanks for", ModelError("provider_error", "stream dropped"))]
)
assert run(fake, SETTINGS, TICKET) == 1
out = capsys.readouterr().out
assert "Thanks for" in out
assert "[incomplete]" in out
assert "stop:" not in out # no footer for a failed stream
def test_no_stream_uses_complete(capsys):
assert run(FakeModelClient(["Hi."]), SETTINGS, TICKET, stream=False) == 0
assert "Hi.\nstop: finished" in capsys.readouterr().out
def test_cli_sends_the_system_prompt_and_the_output_cap():
fake = FakeModelClient([reply("Hi.")])
run(fake, SETTINGS, TICKET)
assert fake.calls[0].system == SYSTEM_PROMPT
assert fake.calls[0].max_tokens == SETTINGS.max_output_tokens
assert "Never promise a refund." in SYSTEM_PROMPT
def test_an_extra_call_fails_the_test():
fake = FakeModelClient([])
with pytest.raises(ScriptExhausted):
fake.complete(SYSTEM_PROMPT, [], 10)
def test_a_seeded_ticket_reaches_the_model(kestrel_url):
ticket = fetch_ticket(kestrel_url, "T-000407") # Chapter 1's late-delivery ticket
fake = FakeModelClient([reply("Hi.")])
assert run(fake, SETTINGS, ticket) == 0
assert "O-0006066" in fake.calls[0].messages[0].contenttest_cli_sends_the_system_prompt_and_the_output_cap checks that the CLI sends the shared prompt, with its refund rule, and the configured cap. Whether the model follows the rule is a separate question. Scripted responses test how your code handles a reply; judging the replies themselves takes golden tasks and evals, which Chapter 13, Testing your first agent, covers.
The fake model never runs the adapter, and the adapter holds the riskiest logic: the stop-reason map, the input sum, the order of the error checks. tests/test_anthropic_adapter.py tests it offline by giving the real SDK a fake HTTP transport, httpx2.MockTransport, that answers with canned responses. Two of its tests:
def test_a_timeout_is_a_timeout_not_a_connection_error():
def handler(request):
raise httpx2.ReadTimeout("slow", request=request)
with pytest.raises(ModelError) as info:
adapter_for(handler).complete("sys", MESSAGES, 50)
assert info.value.kind == "timeout"
def test_sdk_retries_are_bounded_by_settings():
calls = []
def handler(request):
calls.append(request)
return httpx2.Response(429, json={}, headers={"retry-after-ms": "1"})
with pytest.raises(ModelError):
adapter_for(handler, SETTINGS.model_copy(update={"max_retries": 2})).complete(
"sys", MESSAGES, 50
)
assert len(calls) == 3 # one call, two retriesFrom this chapter's folder, run uv run pytest -q with no key set. All tests pass and three are deselected; those tests in tests/test_live.py call the real provider and run with uv run --env-file .env pytest -m live.
12. Exercises
After each exercise, run uv run pytest with no key set to confirm the existing tests still pass.
-
Give refusals their own stop reason. Add
"refused"toStopReason, maprefusalto it in_STOP_REASONS, and makeprint_footer()print a distinct[refused]line. Keepotherfor values the adapter still doesn't recognise. Expected result: a new CLI test that scriptsreply("...", "refused")finds[refused], and a new case in the adapter's stop-reason test passes. Common mistake: forgetting the CLI, which leaves the new value labelled[stopped]. -
Put a wall-clock limit on streaming. Add a
stream_deadline_secondsfield toSettings, read fromSTREAM_DEADLINE_S. Instream_draft(), check the time after each chunk; when time is up, close the generator, print[incomplete]and return 1. Pass in aclockfunction so a test can fake time. A check made when a chunk arrives can't fire during a stall, which only the read limit bounds. Expected result: a test with a fake clock andchunk_size=1shows[incomplete]and no footer. -
Handle a missing ticket. Make
main()catch thehttpx.HTTPErrorthatfetch_ticket()raises, print one line and exit with status 1. An unknown ID raiseshttpx.HTTPStatusError; a stopped mock raises a connection error, whose line should suggestuv run kestrel up. Expected result:uv run --env-file .env python -m ch03.draft_reply T-999999prints one line.
13. Summary
Settings come from environment variables and fail fast. A small ModelClient Protocol sits in front of one adapter, the CLI's only path to the SDK. Stop reasons arrive as four neutral values, streaming is for a person watching, and each call is bounded by a timeout, an output cap and the SDK's retries; what gets past them is one ModelError. Cost is priced in Decimal, and a fake model and a mock transport keep every test offline.
Chapter 4, Prompting for agents, gives the thin system prompt its structure. Tools come in Chapter 6, the agent loop in Chapter 7, conversation state in Chapter 10, a second adapter in Chapter 11, Choosing a model, and retries you write yourself in Chapter 16.
