Sam Adeyemi wants a research assistant that can answer questions like "which carriers had the most late deliveries last quarter, and what do public sources say about their service?" Before anyone builds it, someone has to answer two plainer questions. What will one question cost? And if the assistant gets it right once, can you trust it to get it right the next time?
Chapter 1 defined an agent as a program in which a model chooses tools in a loop and decides when to stop, inside limits that code enforces. Agent or workflow, every model call has a price, a size limit and some variability in what comes back, and an agent pays for them on every step.
You don't need any machine learning background. Treat the model as a backend dependency with inputs, outputs, limits and a price, whose behaviour you predict before you build on it.
By the end of the chapter you should be able to:
- Count the tokens in a page of Kestrel's internal docs (the returns policy, a small stand-in for a handbook page) and price them from configured rates.
- Explain why input and output share one context window, and refuse a request that won't fit before sending it.
- Explain how temperature changes output variability, see it on a toy sampler, and observe run-to-run variation by sending one prompt several times.
- Explain what a reasoning model adds in tokens and latency (latency you measure with a key), and detect an answer cut short by a token limit.
1. Before you start
The code is in books-code/agentic-ai-foundations/ch02-how-llms-work/. Like Chapter 1's folder, it keeps its code in a package named after the chapter and runs from its own folder with uv run python -m ...; the book's pyproject.toml one level up pins the packages.
Chapter 1's uv run kestrel up also writes seeded files under .kestrel/, including the internal docs in .kestrel/docs/. This chapter needs only the files; --no-serve writes them without starting the mock API:
uv run kestrel up --no-serveThe page used throughout is .kestrel/docs/returns-policy.md, which Maya Okafor's support team checks when a customer asks whether an item can go back. Every reader gets the same file:
# Returns policy
> Kestrel Outfitters is a fictional company; this document is synthetic.
- Consumers may return unused items within 30 days of delivery for a full refund; trade customers within 14 days, unless their contract says otherwise.
- Damaged or wrong items: Kestrel pays return shipping and refunds within 5 working days of receiving the item.
- Refunds go back to the original payment method. Support (Maya Okafor's team) can approve refunds up to USD 500; above that, Finance approves.2. Tokens: the unit the model reads, writes and bills
A language model reads tokens, not characters or words. A token is a piece of text, often part of a word, and it is the unit for both the size limit and the price of a call. Before the model sees anything, a tokenizer splits your text into tokens and maps each one to a numeric ID. The model then produces its response one token at a time, and the IDs are turned back into text on the way out, so a token is not a word. To picture it, a tokenizer might keep a common word such as "the" whole and split an invented product name such as "Ridgeline" into "Ridge" and "line". That split is only an illustration; each tokenizer has its own vocabulary.
flowchart LR A["Policy text<br/>(returns-policy.md)"] --> B["Tokenizer"] B --> C["Token IDs"] C --> D["Model"] D --> E["Output tokens"] E -->|"each new token is<br/>fed back in"| D E --> F["Response text"]
Token counts belong to a specific model's tokenizer. Anthropic's token counting documentation says the endpoint counts under the tokenizer of the model you pass, and, as of November 2026, that Claude 4.7 and later models use a newer tokenizer that produces approximately 30 percent more tokens for the same text. The same page can produce a different count on another model without a single character changing, so re-count whenever you change models.
There are two ways to get a count from the provider. Before a call, the count_tokens endpoint reports how many input tokens a request would use. After a call, the response's usage field reports the input and output tokens it consumed. The documentation calls the pre-call figure an estimate that can differ from actual usage by a small amount, so treat it as a sizing figure and treat usage as the billed one. Counting costs nothing per call but has its own requests-per-minute limit, so each count is one extra request.
Without a key you get neither, so the estimator falls back to a placeholder that no provider promises: four characters per token. The real ratio depends on the content and on the tokenizer. The code prints it next to the provider's count, and without one it labels every figure built on it as an estimate.
3. Counting the tokens in a Kestrel policy page
Anything that can change lives in a Settings record that from_env() reads from environment variables. Prices are Decimal, never binary floats, and the key is a SecretStr that may be missing, in which case the code runs in fallback mode.
class Settings(BaseModel):
model: str # a current model from your provider
api_key: SecretStr | None # None: counting falls back to the labelled estimate
input_price_per_mtok: Decimal # USD per million input tokens
output_price_per_mtok: Decimal # USD per million output tokens
context_window_tokens: int # from your provider's docs for this model
docs_dir: Path # Markdown docs written by `uv run kestrel up`
model_timeout_s: float.env.example holds the values that go stale (model, prices, window size) under a Last checked date with their sources. Copy it to .env, which git ignores, and check each value.
The counter reads the page from disk, then asks the provider to count it:
def load_page(settings: Settings, page: str) -> str:
path = settings.docs_dir / page
if not path.is_file():
raise FileNotFoundError(f"{path} not found; run `uv run kestrel up` first")
return path.read_text(encoding="utf-8")
def count_text(
settings: Settings, page: str, text: str, client: anthropic.Anthropic | None = None
) -> TokenCount:
heuristic = math.ceil(len(text) / CHARS_PER_TOKEN)
if client is None and settings.api_key is None:
return TokenCount(
page=page, characters=len(text), heuristic_tokens=heuristic, counted_tokens=None
)
client = client or make_client(settings)
try:
result = client.messages.count_tokens(
model=settings.model,
messages=[{"role": "user", "content": text}],
)
except anthropic.APIError as exc:
raise TokenCountError(f"count_tokens failed for {page}: {exc}") from exc
return TokenCount(
page=page,
characters=len(text),
heuristic_tokens=heuristic,
counted_tokens=result.input_tokens,
)make_client builds the SDK client with the settings' timeout and max_retries=2, written in the code (Chapter 3 makes it a setting), so one call can become up to three requests. A provider error becomes a TokenCountError that names the page. Without a key, counted_tokens stays None on purpose, so a guess can never pass for a count. The file's main() prints the counts, a fit check against --max-tokens (default 1,024) and two costs; the next two sections explain the last three lines:
cp .env.example .env
uv run --env-file .env python -m ch02.tokens returns-policy.mdWithout a key, it prints (example output from 16 November 2026, using the .env.example values):
page: returns-policy.md
characters: 500
heuristic tokens: 125
counted tokens: - (ESTIMATE: no API key)
fits the window: True (max_tokens 1024) (ESTIMATE: no API key)
input cost (USD): 0.0000125 (ESTIMATE: no API key)
worst case (USD): 0.0005245 (ESTIMATE: no API key)The prices behind those two cost lines are the per-million rates in .env.example, copied on 16 November 2026 from Anthropic's pricing page, where they apply to prompts up to 100,000 tokens. Above that tier this model is not billed at the standard rate, and estimate_cost charges one flat rate, so it would misprice such a prompt; re-check the pricing page before sizing long documents.
With a key, a model line names the configured model, counted tokens shows the provider's figure and the labels disappear. The book shows no live output, so you will see the gap from the heuristic only with your own key; it is why this chapter never sizes a budget from the heuristic alone. The page is a small stand-in: the four policy pages in .kestrel/docs/ (leaving out its README) come to 527 heuristic tokens, far less than a real handbook, but the method is the same.
The tests run without a key or network. A small FakeClient in conftest.py stands in for the SDK client: it returns chosen counts and responses from JSON fixtures, written by hand in the shape the Messages API returns, and records every request. Chapter 3 replaces it with the book's fake model. Such tests check our arithmetic, labelling and handling of the provider's answer, never the tokenizer itself.
4. From token counts to money
Providers price input and output tokens separately, per million tokens. The output rate is usually the higher one; for the configured model above it is five times the input rate. Copy the current rates for your model from the provider's official pricing page into .env, not from a blog post. At a 5x ratio, one output token costs as much as five input tokens. So padding an answer is expensive: if a call only needs a ticket category, asking for a paragraph of explanation buys more of the dearer tokens. It doesn't make input cheap. A 50,000-token prompt costs as much as a 10,000-token answer, and in the agent run sketched below, input ends up the larger share.
cost = input_tokens × input price per million / 1,000,000
+ output_tokens × output price per million / 1,000,000cost.py implements exactly this, with no price as a literal:
"""Token-based cost from configured prices. No price appears as a literal."""
from decimal import Decimal
from pydantic import BaseModel
from ch02.settings import Settings
PER_MILLION = Decimal(1_000_000)
class CostEstimate(BaseModel):
input_tokens: int
output_tokens: int
input_cost: Decimal
output_cost: Decimal
@property
def total(self) -> Decimal:
return self.input_cost + self.output_cost
def estimate_cost(input_tokens: int, output_tokens: int, settings: Settings) -> CostEstimate:
return CostEstimate(
input_tokens=input_tokens,
output_tokens=output_tokens,
input_cost=input_tokens * settings.input_price_per_mtok / PER_MILLION,
output_cost=output_tokens * settings.output_price_per_mtok / PER_MILLION,
)An int times a Decimal is a Decimal, and so is the division, so small amounts stay exact across thousands of calls. In tests/test_cost.py, a million tokens of each must cost exactly the configured prices, which catches a misplaced division, and a thousand small calls must add up to exactly one big one, which binary floats don't guarantee.
Back in the counter's output, the worst case adds every output token max_tokens allows: USD 0.0005245 against 0.0000125, about 42 times the input cost at this run's 1,024 max_tokens.
That figure is tiny, but an agent rarely makes one call. Anthropic's context-window documentation describes each request's input as all previous conversation history plus the new message, so step five pays again for everything sent in steps one to four. The table sketches one of Sam's questions as a five-step run. The token figures are assumptions for illustration: a 2,000-token start, and each later call 1,500 tokens longer than the one before (the previous reply plus a new tool result), with 300 output tokens per call. The prices are the .env.example rates, USD 0.10 per million input and 0.50 per million output tokens, from the pricing page on 16 November 2026; they show the method, not current prices:
| Step | Input tokens this call | Cumulative input | Cumulative output | Cumulative cost (USD) |
|---|---|---|---|---|
| 1 | 2,000 | 2,000 | 300 | 0.00035 |
| 2 | 3,500 | 5,500 | 600 | 0.00085 |
| 3 | 5,000 | 10,500 | 900 | 0.0015 |
| 4 | 6,500 | 17,000 | 1,200 | 0.0023 |
| 5 | 8,000 | 25,000 | 1,500 | 0.00325 |
run_cost_table(2_000, 1_500, 300, steps=5, settings=settings) in cost.py builds every row by calling estimate_cost on the running totals, and a test checks the input column:
def run_cost_table(
start: int, new_per_step: int, output_per_step: int, steps: int, settings: Settings
) -> list[CostEstimate]:
"""Cumulative cost after each step of a run that resends its whole history every call."""
rows: list[CostEstimate] = []
total_in = total_out = 0
for step in range(steps):
total_in += start + step * new_per_step # this call's input
total_out += output_per_step
rows.append(estimate_cost(total_in, total_out, settings))
return rowsThe last row is estimate_cost(25_000, 1_500, settings): USD 0.0025 for input and 0.00075 for output. Input is three quarters of the bill, although each input token is the cheap kind, because the history is paid for again on every step: 25,000 input tokens instead of 10,000 if each call held only the first step's context. An eval that runs the question five times pays about USD 0.016, and real questions can take more steps. Prompt caching, where a provider reuses the processed start of a repeated prompt, lowers the price of resent input, though not the space it takes. For work that can wait, the same pricing page (checked November 2026) lists a Batch API at half the standard rates. Chapter 7 explains the loop that produces this pattern, and Chapter 13 defines evals.
Chapter 1 called the limits that code sets on a run the run budget; Chapter 7 enforces steps, tokens and time, and Chapter 16 adds money. This chapter supplies the method behind a money check's two figures: priced usage after each call, and the worst case from counted input and max_tokens before it. Telling the model to "keep costs down" is not a budget; a budget is code that refuses the next call.
5. The context window: one limit shared by input and output
A context window is the maximum number of tokens one model call can handle, counting input and generated output together. The input includes the instructions sent with every request (Chapter 3 names them the system prompt), any tool definitions (Chapter 6), the conversation history and the new content. The model keeps nothing between calls, which is why the history in the cost table kept growing.
You can count the input side. The output side is the space you reserve with max_tokens, the request parameter that caps how many tokens the model may generate. Every token of policy text you add is a token the answer can't use. Prompt caching doesn't change this: cached input still occupies the window. Window sizes differ between models and change, so settings read the size from CONTEXT_WINDOW_TOKENS.
What happens when a request doesn't fit
There are two ways to overflow, and the API treats them differently. These rules come from the same context-window documentation (checked in November 2026); other providers may differ.
The input side is strict. If the input alone goes past the window, the API returns a 400 invalid_request_error with the message "prompt is too long", on every model. An agent partway through a run has just lost a step.
The output side depends on the model. On Claude 4.5 models and newer, the API accepts a request whose input plus max_tokens exceeds the window; if generation then reaches the window's limit, it stops and reports model_context_window_exceeded as its stop_reason. Earlier models reject the same request with a validation error. stop_reason, which Chapter 3 covers, is the response field that says why generation ended; an answer that stopped at a limit may be cut off mid-sentence. tokens.py keeps both limit values in one set, LIMIT_STOPS, which the later scripts reuse.
Checking the fit before you call
With the input size counted, our own code can check a request before it goes out:
class WindowCheck(BaseModel):
input_tokens: int
max_tokens: int
context_window: int
input_fits: bool # False: rejected on every model ("prompt is too long")
fits: bool # False: rejected on older models, may be cut short on newer ones
output_headroom: int # the largest max_tokens that still fits, never negativedef check_fits(input_tokens: int, max_tokens: int, context_window: int) -> WindowCheck:
"""Compare counted input plus planned output with the configured window."""
if input_tokens < 0:
raise ValueError("input_tokens must not be negative")
if max_tokens <= 0 or context_window <= 0:
raise ValueError("max_tokens and context_window must be positive")
return WindowCheck(
input_tokens=input_tokens,
max_tokens=max_tokens,
context_window=context_window,
input_fits=input_tokens <= context_window,
fits=input_tokens + max_tokens <= context_window,
output_headroom=max(context_window - input_tokens, 0),
)output_headroom is the largest max_tokens that would still fit, which matters once reasoning tokens share the output side. input_fits=False means rejection on every model. fits=False with input_fits=True means rejection on models before Claude 4.5 and a possibly truncated answer on newer ones. The scripts here refuse both. That is a policy, not a mirror of the API, and it refuses some requests a newer model would have answered in full, because a model often stops well short of max_tokens. In a loop I'd still take that trade: a local refusal costs one counting request and no model call, while a truncated answer costs money and a step, and the next step builds on half an answer. The check is only as exact as the count. count_tokens is an estimate that can differ from billed usage by a small amount, so a request right at the edge can pass and still overflow. Leave a margin below the window, sized by comparing counted tokens with billed usage on your own requests.
tests/test_window.py covers both cases with a 10,000-token test window. Run the chapter's tests from ch02-how-llms-work/ with uv run pytest -q; no key is needed, and the expected result is 23 passed, 1 deselected (the deselected test is the live one). The book's later loops don't repeat this refusal: they rely on the provider's 400 or limit stop, and Chapter 9 adds token counting with an inspector that warns when headroom runs low. It tells you a request doesn't fit, not what to leave out. Choosing what goes into the window is Chapter 9's subject, and keeping a long run inside it with trimming and compaction is Chapter 10's.
6. Why the same prompt gives different answers
Generation is a sequence of single-token choices. Before each new token, the model scores every token in its vocabulary by how likely it is to come next. A sampler picks one according to its settings, appends it and asks for the next. Each pick becomes input for every later pick, so if two runs diverge early the answers can drift apart in wording, length and sometimes substance.
Temperature is the best-known sampling setting. In the usual formulation, the sampler divides each score by the temperature before turning the scores into probabilities. A temperature below 1 stretches the gaps between scores, so the top token wins more often (nearly always at a low value such as 0.2) and output becomes more repeatable. A temperature above 1 shrinks the gaps, so lower-ranked tokens get picked more often. Lower is not the same as fixed: output can still vary between runs at the lowest setting, so don't rely on it for exact repeats. Top-p keeps the smallest set of tokens whose combined probability reaches p, and top-k keeps the k most likely tokens; the sampler then picks only from that set. With the temperature 1.0 probabilities printed below, a top-k of 2 keeps "within" and "up", and so does a top-p of 0.8 (0.63 + 0.23 = 0.86). The toy sampler varies only temperature.
You can watch temperature without any model. temperature.py is a toy sampler over four invented scores for the word after "Consumers may return unused items":
# Made-up scores for the word after "Consumers may return unused items"; not from any model.
SCORES = {"within": 3.0, "up": 2.0, "for": 1.0, "before": 0.5}
def probabilities(scores: dict[str, float], temperature: float) -> dict[str, float]:
"""Divide each score by the temperature, then turn the scores into probabilities."""
if temperature <= 0:
raise ValueError("temperature must be positive")
scaled = {token: score / temperature for token, score in scores.items()}
top = max(scaled.values())
weights = {token: math.exp(value - top) for token, value in scaled.items()}
total = sum(weights.values())
return {token: weight / total for token, weight in weights.items()}
def sample(scores: dict[str, float], temperature: float, picks: int, seed: int = 0) -> Counter:
"""Pick the next token `picks` times; a fixed seed makes the toy repeatable."""
probs = probabilities(scores, temperature)
rng = random.Random(seed)
return Counter(rng.choices(list(probs), weights=list(probs.values()), k=picks))uv run python -m ch02.temperature prints each token's probability and, in brackets, its wins in 100 seeded picks:
temperature 0.2: within 0.99 (99) up 0.01 (1) for 0.00 (0) before 0.00 (0)
temperature 1.0: within 0.63 (57) up 0.23 (22) for 0.09 (15) before 0.05 (6)
temperature 2.0: within 0.44 (28) up 0.27 (35) for 0.16 (19) before 0.13 (18)At 0.2 the toy is nearly repeatable. At 2.0 "within" is still the most likely word, yet "up" won more of these 100 picks: at a high temperature, luck can outweigh the ranking. The tests check the shape, not the luck: probabilities add up to 1, and the top token's share falls as temperature rises.
On a real model, whether you can set these at all depends on the provider and the model. The configured model's migration guide says to omit temperature, top_p and top_k, and the pinned SDK's messages.create parameters have no field for any of them (both checked November 2026). For another model, check your provider's documentation. Either way, don't count on exact repeats; your code has to live with variation.
Whether variation matters depends on the task. A call that routes Maya's tickets should put the same ticket in the same queue every time; a draft reply can vary in wording as long as the facts stay correct. Either way, code checks what comes back; Chapter 5, Structured outputs, shows how. Variability also changes what counts as evidence: a single passing run may have been the lucky one. So the capstone's evals run each task several times and report a pass rate; Chapter 13 defines them.
7. Running the variability demo
sampling_demo.py sends one identical request several times, the page plus "In one sentence: how many days does a consumer have to return an unused item?" It counts the prompt and checks the fit first, caps the run count, and reports what came back and what it cost.
def prompt_for(page_text: str) -> str:
return f"{page_text}\n\n{QUESTION}"
def run_demo(
client: anthropic.Anthropic, settings: Settings, page_text: str, runs: int, max_tokens: int
) -> SamplingReport:
prompt = prompt_for(page_text)
counted = count_text(settings, PAGE, prompt, client).counted_tokens
require_fit(counted, max_tokens, settings.context_window_tokens)
answers: list[str] = []
truncated = input_tokens = output_tokens = 0
for _ in range(min(runs, MAX_RUNS)):
response = client.messages.create( # same request every time, nothing else varies
model=settings.model,
max_tokens=max_tokens,
messages=[{"role": "user", "content": prompt}],
timeout=settings.model_timeout_s,
)
input_tokens += response.usage.input_tokens
output_tokens += response.usage.output_tokens # truncated runs are still billed
if response.stop_reason in LIMIT_STOPS:
truncated += 1
continue
answers.append("".join(b.text for b in response.content if b.type == "text").strip())
return SamplingReport(
runs=min(runs, MAX_RUNS),
answers=answers,
distinct=len(set(answers)),
truncated=truncated,
cost=estimate_cost(input_tokens, output_tokens, settings),
)require_fit, in tokens.py, raises before anything is sent if there is no provider count or the request doesn't fit. Answers that stopped at a limit count as truncated, not as variants, and their tokens still count toward the cost. main() takes max_tokens from SAMPLING_MAX_TOKENS in .env (default 1,024, which leaves room for any thinking) and prints the counts, each answer with how often it appeared, the tokens and the cost.
The request sends no thinking setting, but adaptive thinking is on by default for this model, so a response can start with thinking blocks anyway. Those tokens are billed as output and count against max_tokens, so some variation in cost, and an occasional limit stop, may come from reasoning rather than sampling.
It is also why Chapter 3's model client turns thinking off by default (a MODEL_THINKING setting of off): its small output caps would otherwise risk truncated or empty replies on calls that need no reasoning.
With a key, run uv run --env-file .env python -m ch02.sampling_demo --runs 5. The fake responses below show two wordings among four complete answers; a real model may give one wording or several, and the count can change between runs. Either is normal, and you can't tune it here, which is why the toy sampler exists. A different return window is a defect.
Without a key, the tests feed five fixture responses through run_demo: three identical answers, one differently worded, and one that spent most of its 256 tokens on a thinking block and stopped at max_tokens mid-sentence.
def test_counts_variants_and_truncation_and_bills_every_run(settings, fake_client):
client = fake_client(count=200, responses="sampling_responses.json")
page = load_page(settings, "returns-policy.md")
report = run_demo(client, settings, page, runs=5, max_tokens=256)
assert report.runs == 5
assert report.truncated == 1 # stopped at max_tokens: not a variant
assert report.distinct == 2 # two wordings of the same fact
assert all("30 days" in answer for answer in report.answers)
assert report.cost.output_tokens == 16 + 20 + 16 + 256 + 16 # truncated run billed too
assert report.cost.input_tokens == 5 * 180The test asserts that every answer states the fact and every run is billed, never the exact wording; a test that expects exact model text fails intermittently.
8. Reasoning models: paying for tokens before the answer
A reasoning model generates intermediate reasoning tokens before it writes its answer, trading latency and token cost for what is usually expected to be better results on multi-step problems. Anthropic's API calls these thinking tokens and returns them in thinking blocks.
As of November 2026, the context-window documentation says thinking tokens are a subset of max_tokens, are billed as output tokens and count toward rate limits. So reasoning adds the dearer kind of token before the answer begins. A short reply can hide far more billed output, and if max_tokens is tight, reasoning can use up the allowance before the answer starts.
It also adds latency: output is produced one token at a time, reasoning included, so every reasoning token comes before the first word of the answer. Suppose a call writes 900 reasoning tokens and a 50-token answer (assumed figures): it generates about nineteen times the tokens of the answer alone, and waits for all of them. At the .env.example rate of USD 0.50 per million output tokens, estimate_cost puts the 950 at an estimated USD 0.000475, against 0.000025 for the answer alone. The three test fixtures below (fixture data, 230 input tokens each) show the same shape: low effort bills 62 output tokens, USD 0.000054 in total; high effort 940, 890 of them thinking, USD 0.000493; the truncated run 2,000 thinking tokens and no answer, USD 0.001023.
Usage is also hard to predict: the same page says that with adaptive thinking the model decides its thinking allocation per request, so usage varies from one request to the next.
How you control reasoning is itself a fast-moving fact. In November 2026, Anthropic's extended thinking page says the older manual mode, thinking set to enabled with a budget_tokens figure, is deprecated, and Claude 4.7 and later models reject it with a 400 error. The configured model's migration guide says adaptive thinking is on by default for this model; the effort setting in output_config steers it: at a lower effort the model thinks less and can skip thinking on simple requests.
Comparing two effort levels
reasoning.py asks one multi-step question about the returns policy at each effort level you name:
QUESTION = (
"A trade customer received a damaged tent 10 days ago and an unused stove 20 days ago. "
"The refund for the tent alone would be USD 640. Using only the policy above: which "
"items can go back, who pays return shipping, and who must approve the refund?"
)The policy answers it in three steps: the damaged tent goes back with Kestrel paying return shipping; the unused stove is outside the trade customer's 14 days (unless their contract says otherwise, which a careful answer may mention); the tent's USD 640 refund is above Support's USD 500 limit, so Finance approves it. A model without reasoning may well get this right too, so expect the comparison to show mostly the cost side.
def ask(
client: anthropic.Anthropic,
settings: Settings,
page_text: str,
effort: Effort,
max_tokens: int,
) -> ReasoningRun:
prompt = f"{page_text}\n\n{QUESTION}"
counted = count_text(settings, PAGE, prompt, client).counted_tokens
require_fit(counted, max_tokens, settings.context_window_tokens)
started = time.monotonic()
response = client.messages.create(
model=settings.model,
max_tokens=max_tokens, # must hold the reasoning tokens and the answer
thinking={"type": "adaptive"}, # the model decides whether and how much to reason
output_config={"effort": effort},
messages=[{"role": "user", "content": prompt}],
timeout=settings.model_timeout_s,
)
details = response.usage.output_tokens_details
return ReasoningRun(
effort=effort,
answer="".join(b.text for b in response.content if b.type == "text"),
thinking_blocks=sum(1 for b in response.content if b.type == "thinking"),
output_tokens=response.usage.output_tokens,
thinking_tokens=details.thinking_tokens if details else None,
latency_s=time.monotonic() - started,
stop_reason=response.stop_reason,
truncated=response.stop_reason in LIMIT_STOPS,
cost=estimate_cost(response.usage.input_tokens, response.usage.output_tokens, settings),
)usage.output_tokens covers the reasoning and the answer, and it is the figure the cost uses. output_tokens_details.thinking_tokens reports how many of those billed tokens were reasoning, when the response includes it (same extended thinking page). truncated is set when stop_reason is in LIMIT_STOPS; treat it as a failure, not a short answer.
main() takes max_tokens from REASONING_MAX_TOKENS (default 16,000, so that high effort has room to reason and still answer). It and SAMPLING_MAX_TOKENS sit in .env.example as script-local options, not Settings fields, because only one script reads each; Chapter 3 replaces them with a MAX_OUTPUT_TOKENS setting. With a key, run uv run --env-file .env python -m ch02.reasoning --efforts low high and compare output tokens, thinking tokens, latency and cost.total. If high-effort calls time out, raise MODEL_TIMEOUT_S in .env.
The offline tests replay three fixture responses: a low-effort answer with no thinking, a high-effort answer with a thinking block, and one that spent all 2,000 tokens of its allowance on thinking and stopped at max_tokens. Two more tests check that thinking and effort go into the request and that the truncated run comes back flagged, with an empty answer.
from ch02.cost import PER_MILLION
from ch02.reasoning import ask
from ch02.tokens import load_page
def run(settings, fake_client, fixture, effort="high"):
client = fake_client(count=230, responses=fixture)
page = load_page(settings, "returns-policy.md")
return client, ask(client, settings, page, effort, max_tokens=2_000)
def test_reasoning_tokens_are_billed_as_output(settings, fake_client):
_, result = run(settings, fake_client, "reasoning_high.json")
assert result.thinking_blocks == 1
assert result.thinking_tokens == 890
assert result.output_tokens > result.thinking_tokens # the answer is the small part
price = settings.output_price_per_mtok
assert result.cost.output_cost == result.output_tokens * price / PER_MILLION
assert "Finance" in result.answer
assert result.truncated is FalseDon't mistake effort for a budget either: effort shapes how much the model reasons, and the model decides the rest. Only the run budget, enforced by your code, can stop a run.
When is reasoning worth paying for? This is my judgment, not a measured result. Sam's question can justify it: plan which late-shipment counts to request per carrier (code does the counting; Chapter 14 specifies the tool and Chapter 15 builds it), then weigh them against public sources. Its steps depend on each other. Extracting one field from a support ticket is usually poor value. I would start at a low effort and raise it only where evals show it helps; Chapter 11 weighs capability against latency and cost when choosing a model. When reasoning is on, pass its max_tokens to check_fits, because the output side has to hold the reasoning as well as the answer.
9. Exercises
Run these inside ch02-how-llms-work/. Without a key, use the heuristic figure and label results as estimates.
Exercise 1: price all the docs. Extend the counter to loop over sorted(settings.docs_dir.glob("*.md")), skipping README.md and passing each file name to load_page. Report per-page counts, the total (expected without a key: 527 heuristic tokens) and its input cost from estimate_cost. Check that the pages sum to the total, and that changing the price in .env changes the cost; if it doesn't, you hard-coded it.
Exercise 2: find the output headroom. Set CONTEXT_WINDOW_TOKENS in .env to a small test value such as 2,000. In a Python shell, work out the largest max_tokens that still fits alongside the returns policy (125 heuristic tokens) plus a 500-token instruction, and confirm that check_fits passes with it (expected: 1,375). Raise it and confirm that fits turns false while input_fits stays true. Finish with one sentence on what happens when the input alone is larger than the window (expected: a 400 "prompt is too long" on every model).
Exercise 3: measure variability. Add a temperature of 0.5 to the toy sampler and predict the top word's probability before you run it (expected: about 0.86, between 0.99 and 0.63). With a key, also repeat the sampling demo twice with --runs 5, record the distinct and truncated counts and the cost, and write two sentences on what this means for testing.
Exercise 4 (optional; needs a key). Run ch02.reasoning with --efforts low high. Record output tokens, thinking tokens, latency and cost.total for each, and check each answer against the three-step answer above. If truncated is true, raise REASONING_MAX_TOKENS in .env and run again. Whether the higher effort earns its cost is your call; one run of each tells you little.
10. Chapter summary and what comes next
Counts depend on the model's tokenizer, and the provider's count beats any rule of thumb. Cost is tokens multiplied by configured prices. Output is the dearer side per token, but because every step resends the whole history, input can make up most of a multi-step run's bill. Input and output share one hard limit per call.
Sampling makes outputs vary. Temperature changes how much, as the toy sampler shows, but the configured model's guide says to omit it and the pinned SDK has no field for it, so this book's code sends none. Reasoning models spend extra output tokens and time before they answer, and the amount changes from one request to the next.
Two ideas carry into the capstone: the per-question budget uses this chapter's method, priced usage after each call and the worst case before it, though Chapter 11's models.toml becomes its price source; and the evals repeat each task because a single run proves little.
Chapter 3, Talking to models, covers the request this chapter only previewed (messages, roles, the system prompt, stop_reason and streaming) behind a model client that tests can replace with scripted responses.
