In Chapter 14, Sam Adeyemi's question, "which carriers had the most late deliveries last quarter, and what do public sources say about their service?", became a folder of design files: a spec, four tool contracts whose bodies raise NotImplementedError, a FinalAnswer schema, a file sandbox, citation checking and five golden tasks. A design answers nothing. This chapter copies that folder forward, writes the missing code and runs the assistant from a terminal.
By the end you will have a research assistant you can check piece by piece:
search_web,read_file,count_rowsandcalculatehave real bodies behind the registry. The file tools reject any path that resolves outside the sandboxed folder, and every argument is validated before a tool runs.- The loop from Chapters 10 and 13 runs the research prompt, collects every location a tool returns, and checks the final answer: shape first, then each citation. A failed answer gets one retry.
- The spec's open question is settled: an answer that still fails after its retry is rejected, and the run prints no answer at all.
- A command-line interface prints the answer, citations, confidence and cost, writes a JSONL trace, and exits with a code that says which of four outcomes happened.
uv run pytestpasses 97 tests with the fake model, including all five golden tasks, with no API key and no network.
Every model message in this chapter is fake-model output, scripted by hand and labelled that way. The counts are real: they come from the seeded exports. With your own key, the same command runs against a real model.
Two things stay out on purpose. Classifying failures, retrying tools and stopping a run on cost belong to Chapter 16. And the assistant stays at point 4 of the autonomy spectrum, as Chapter 14 placed it: four read-only tools and a tight budget.
1. From the Chapter 14 folder to ch15-capstone-build
The capstone uses the same layout as every chapter. ch15-capstone-build/ holds a ch15/ package, conftest.py, tests/ and a README, and it stands alone: it starts as a copy of ch14-capstone-design/, adds Chapter 13's loop pieces and trace and Chapter 10's conversation state, and then changes a few files.
ch15-capstone-build/
├── spec.md, golden_tasks.toml, fixtures/ from Chapter 14 (spec: open questions decided)
├── ch15/
│ ├── tools.py the four tool bodies and the search backends changed
│ ├── registry.py collects the run's citable set changed
│ ├── results.py renders pydantic outputs as JSON changed
│ ├── final.py check_final() and the retry message new
│ ├── agent.py run_agent() with final-answer checking changed (Ch 10, 13)
│ ├── research.py run_research() and the four outcomes new
│ ├── cli.py the command line and its exit codes new
│ ├── trace.py JSONL trace, plus final-check events changed (Ch 13)
│ ├── scripted.py fake-model scripts for golden tasks and demos new
│ ├── golden.py adds grade() changed
│ ├── settings.py adds SEARCH_ENDPOINT and the context policy changed
│ ├── state.py conversation state, trimming, compaction copied (Ch 10)
│ ├── budget.py, fake_model.py, configs.py, the two adapters copied (Ch 13)
│ └── answer.py, citations.py, sandbox.py, prompts.py, pricing.py, ... copied (Ch 14)
└── tests/ 97 tests, no key and no networkanswer.py, citations.py and sandbox.py arrive unchanged. The FinalAnswer schema, check_citations and resolve_in_sandbox were final in Chapter 14, and nothing in the build needed them to move. Start by writing the seeded workspace: uv run kestrel up --no-serve creates .kestrel/exports/, the sandboxed folder.
2. The four tool bodies
The model supplies only the validated arguments. build_registry binds everything else with functools.partial, as Chapter 14 wrote it: the sandbox root for the file tools, and the search backend plus a timeout_s callable for search_web. Errors are raised as ToolError with a message written for the model, and the registry turns each one into an error result, as it has since Chapter 6.
read_file and the file sandbox
Both file tools open files through one helper, so neither can skip the sandbox:
def read_text(root: Path, requested: str) -> tuple[str, str]:
"""(sandbox name, text) of one export, through the sandbox."""
resolved = resolve_in_sandbox(root, requested) # raises SandboxError, a ToolError
try:
return sandbox_name(root, resolved), resolved.read_text(encoding="utf-8")
except UnicodeDecodeError:
raise ToolError(f"{requested!r} is not UTF-8 text. Read one of the CSV exports.") from None
def read_file(args: ReadFileArgs, root: Path) -> ProvenancedResult:
name, text = read_text(root, args.path)
if args.offset >= len(text):
raise ToolError(f"offset {args.offset} is past the end of {name} ({len(text)} chars).")
end = min(args.offset + args.max_chars, len(text))
if end < len(text): # end the page on a whole line, unless one line fills the page
last_newline = text.rfind("\n", args.offset, end)
end = last_newline + 1 if last_newline >= args.offset else end
return ProvenancedResult(
origin=name, # the file's sandbox name: what citable_locations records
kind="file",
total_chars=len(text),
shown=[(args.offset, end)],
truncated=args.offset > 0 or end < len(text),
content=text[args.offset : end],
)resolve_in_sandbox is Chapter 14's: it rejects absolute paths, resolves the path with symlinks followed, and only then checks that the result is inside the root. The page itself ends on a whole line, so a CSV row is never split across two results, and the header the registry adds shows the character range, so the next call knows its offset. The tool returns the file's sandbox name as origin, never an absolute path: that name is what the model will cite and what the citable set records.
Check it before going further. ch15/try_sandbox.py sends five read_file calls a model might make through the registry, exactly as the loop would, and prints the first line of each result:
{'path': '../kestrel.sqlite'} -> ERROR: Path rejected: '../kestrel.sqlite' is outside the sandboxed folder. Use a path relative to it, such as shipments.csv.
{'path': '/etc/passwd'} -> ERROR: Path rejected: '/etc/passwd' is absolute. Use a path relative to the sandboxed folder, such as shipments.csv.
{'path': 'shipmnts.csv'} -> ERROR: No such file: 'shipmnts.csv'. Files in the sandbox: expense_claims.csv, orders.csv, products.csv, shipments.csv, tickets.csv.
{'path': 'shipments.csv', 'max_chars': 50} -> ERROR: Invalid arguments for read_file. max_chars: Input should be greater than or equal to 200; got 50.
{'path': 'shipments.csv', 'max_chars': 200} -> ok: [origin: shipments.csv | kind: file | shown: 0-87 of 2576661 chars | truncated]
citable: ['shipments.csv']Each refusal is an error result written for the model, not an exception, and the run carries on. The fourth call never reaches the tool: the registry's strict input model rejects it and names the field. Only the call that succeeded made shipments.csv citable. tests/test_sandbox.py, copied from Chapter 14, adds a symlink that points out of the folder and a sibling folder whose name starts with the root's name; both are refused.
The sandbox is a path check, not process isolation. It limits which files these two tools open, and nothing else; the Python process still runs with your permissions.
count_rows: every count comes from code
def count_rows(args: CountRowsArgs, root: Path) -> CountRowsResult:
name, text = read_text(root, args.path)
reader = csv.DictReader(io.StringIO(text, newline="")) # quoted newlines stay in one row
if not reader.fieldnames:
raise ToolError(f"{name} is empty: it has no header row to count by.")
asked = [*args.where, args.date_column, args.group_by]
if unknown := sorted({c for c in asked if c} - set(reader.fieldnames)):
raise ToolError(
f"{name} has no column {', '.join(unknown)}. Columns: {', '.join(reader.fieldnames)}."
)
in_file = in_period = matched = 0
groups: Counter[str] = Counter()
for row in reader:
in_file += 1
if args.date_column:
cell = row[args.date_column]
if not cell:
continue # an empty date cell is never inside a range
try:
day = date.fromisoformat(cell[:10])
except ValueError:
raise ToolError(f"{name} record {in_file}: {cell!r} is not an ISO date.") from None
if (args.date_from and day < args.date_from) or (args.date_to and day >= args.date_to):
continue
in_period += 1
if all(row[col] == value for col, value in args.where.items()):
matched += 1
if args.group_by:
groups[row[args.group_by]] += 1
return CountRowsResult(
path=name,
rows_in_file=in_file,
rows_in_period=in_period,
rows_matched=matched,
by_group=dict(sorted(groups.items(), key=lambda kv: (-kv[1], kv[0]))),
)The tool follows Chapter 14's contract to the letter. A column the export doesn't have comes back as an error that lists the real columns, so the model can correct its call. A malformed date names the record instead of escaping as a Python exception, and an empty file is refused because it has no header to count by. The text goes to csv.DictReader through io.StringIO(text, newline=""), which lets the csv module handle line endings itself, so a quoted field that contains a newline stays inside one row. An empty date cell is never inside a range, the same rule ch15.golden.resolve_count uses, so the tool and the test's independent count can't drift apart.
rows_in_period makes the refusal rule checkable. For the carrier question with a run date of 2026-01-15, last quarter is October to December 2025. The seeded export answers with rows_in_period: 4421 and the two largest groups, Harbour Express with 139 late shipments and Swiftway Parcel with 93. Ask about April to June 2026 and the same call returns rows_in_period: 0: the export doesn't cover that quarter, and the prompt's don't-know rule turns that into needs_info, not a count of zero.
search_web behind a search backend
Chapter 14 left one choice open: which search service sits behind SearchBackend. This build doesn't name one. Search services differ in request format, terms and price, and the book can't verify any of them for you. Instead, three backends implement the same one-method interface:
HttpSearchBackendis illustrative. It sendsGET <SEARCH_ENDPOINT>?q=...&count=Nwith the key in anX-API-Keyheader and expects{"results": [{"title", "url", "snippet"}]}. Adapt the request and the parsing to your service's documented API; the tests run it overhttpx.MockTransport.FixtureSearchBackendserves the hand-written results infixtures/search/carriers.json, invented for the book onexample.com. Tests and demos use it, so they never touch the network.UnconfiguredSearchis what a live run gets whenSEARCH_ENDPOINTis empty. The tool stays in the tool set and answers with an error result saying search isn't configured, so the model can still answer from the exports and list the web half undermissing.
def search(self, query: str, max_results: int, timeout_s: float) -> list[SearchResult]:
response = self._client.get(
self._endpoint,
params={"q": query, "count": max_results},
headers=self._headers,
timeout=timeout_s, # per request: SEARCH_TIMEOUT_S or the run's time left, if less
) # httpx.TimeoutException propagates: the registry turns it into a "timed out" result
if response.status_code != 200:
raise ToolError(f"The search service answered HTTP {response.status_code}.")
try:
items = response.json()["results"]
except (ValueError, KeyError, TypeError):
raise ToolError("The search service returned a response without results.") from None
fitted = (fit_result(i) for i in items if isinstance(i, dict))
return [r for r in fitted if r is not None][:max_results]HTTPX raises a TimeoutException after 5 seconds of network inactivity by default, and it distinguishes four timeout types: connect, read, write and pool (HTTPX timeouts, checked November 2026). It also accepts a timeout on an individual request, which is what the backend passes. The value comes from timeout_s(): SEARCH_TIMEOUT_S (10 seconds) or the time left in the run, whichever is smaller. A stalled service therefore fails inside the run's time budget, and the registry turns the timeout into an error result.
fit_result caps titles and snippets and drops any result whose URL is longer than 500 characters. A shortened URL would be a different location, so a result is dropped, never cut. With these caps, ten results still fit under the 16,000-character tool-result cap, and a test keeps it that way.
calculate without eval()
Chapter 14 promised a small recursive-descent parser over Decimal. Each grammar rule is one method:
class _Parser:
"""Recursive descent, one method per grammar rule:
sum := term (('+' | '-') term)* term := factor (('*' | '/') factor)*
factor := ('+' | '-') factor | number | '(' sum ')'"""
def __init__(self, tokens: list[str]) -> None:
self.tokens, self.i = tokens, 0
def peek(self) -> str | None:
return self.tokens[self.i] if self.i < len(self.tokens) else None
def take(self) -> str:
token = self.peek()
if token is None:
raise ToolError("The expression ends too early.")
self.i += 1
return token
def sum(self) -> Decimal:
value = self.term()
while self.peek() in ("+", "-"):
value = value + self.term() if self.take() == "+" else value - self.term()
return value
def term(self) -> Decimal:
value = self.factor()
while self.peek() in ("*", "/"):
value = value * self.factor() if self.take() == "*" else value / self.factor()
return value
def factor(self) -> Decimal:
token = self.take()
if token in ("+", "-"):
value = self.factor()
return value if token == "+" else -value
if token == "(":
value = self.sum()
if self.take() != ")":
raise ToolError("A '(' has no matching ')'.")
return value
if token[0].isdigit():
return Decimal(token)
raise ToolError(f"Unexpected {token!r} in the expression.")
def calculate(args: CalculateArgs) -> CalculateResult:
parser = _Parser(tokenize(args.expression))
try:
value = parser.sum()
except (DivisionByZero, InvalidOperation):
raise ToolError("Division by zero. Check the numbers you passed.") from None
if parser.peek() is not None:
raise ToolError(f"Unexpected {parser.peek()!r} after a complete expression.")
return CalculateResult(expression=args.expression, value=str(value))The tokenizer accepts digits, + - * / and parentheses, and rejects every other character with an error naming it. Names, calls, powers and exponent notation never reach the parser. Decimal keeps (139 - 93) / 93 * 100 free of binary floating-point rounding, and 0.1 + 0.2 comes back as 0.3. The result is a string, so JSON never turns it back into a float.
3. The citable set, collected by the registry
A citation counts only if a tool returned that URL or file path in this run. Chapter 14 wrote citable_locations, which says what one successful output makes citable, and left collecting the set to this chapter. The collection happens in one place, at the end of ToolRegistry.dispatch:
content, is_error = render_tool_result( # new in Chapter 9: header, cap, <data>
call.name, call.arguments, output, self.max_result_chars
)
if not is_error and self._citable_from: # new in Chapter 15: only what the model saw
self.citable |= self._citable_from(call.name, output)
return ToolResult(tool_call_id=call.id, content=content, is_error=is_error)The set grows only after rendering succeeds, so a location enters it only if the model was shown it. Error results never get that far: a path the sandbox refused, a search that timed out or a page that was too large adds nothing. calculate adds nothing either, because a computed rate has no location of its own.
The set lives on the registry, beside the loop, and not in the conversation. That placement matters once compaction exists. Chapter 10's compaction replaces older messages with a summary; if the checker read citable locations back out of the history, a compaction could quietly shrink what the run may cite. Kept apart, the citable set is unaffected by anything compaction does. What compaction can still lose is the model's view of an old URL, which is why the retry message, shown below, lists the whole set.
4. Wiring the loop
The system prompt is Chapter 14's research_assistant_v1.md, unchanged: the six sections in Chapter 4's order, today's date in the data section, and the FinalAnswer JSON Schema generated from the same class that validates the reply. The model ends its turn with one JSON object, as the prompt's output format asks.
Checking the final answer
When the model ends its turn, the loop passes the text to a check. check_final validates the shape with pydantic, exactly as Chapter 5 did, then runs Chapter 14's check_citations against the citable set:
def check_final(text: str, citable: set[str]) -> FinalCheck:
try:
answer = FinalAnswer.model_validate_json(strip_fences(text))
except ValidationError as exc:
return FinalCheck(
None,
[
f"{'.'.join(str(p) for p in e['loc']) or '(root)'}: {e['msg']}"
for e in exc.errors(include_url=False, include_input=False)
],
)
errors = [
f"citations.{e.index}: {e.location!r}: {e.reason}" for e in check_citations(answer, citable)
]
return FinalCheck(answer, errors)Validation comes first because citation checking assumes a well-formed FinalAnswer. The schema's own rules already cover a lot: a claim must cite an existing index, needs_info must start with the NEEDS INFO marker, list what is missing and make no claims, and high confidence needs a file citation on every claim. The citation check then asks the one question validation can't: did a tool return each cited location in this run? Each problem comes back as one line naming the field, such as citations.1: 'https://reviews.example.com/harbour-express-complaints': no tool returned this location in this run. Field paths count from 0, as pydantic's do, so citations.1 is the citation the CLI prints as [2].
The comparison follows Chapter 14's matching rules. A file citation matches after a leading ./ is removed, so ./shipments.csv counts as shipments.csv and exports/shipments.csv doesn't. A URL matches after its scheme and host are lowercased and its fragment dropped; the query string stays, because it can name a different page. Everything else must match exactly.
One retry, then rejected
A model can get the shape right and one detail wrong, so a failed check earns one retry. The retry message lists the problems and every location in the citable set, inside <data> tags with tag characters escaped, and asks for the corrected JSON object only. The retry is an ordinary step: it counts against RUN_MAX_STEPS and is paid from the same token and time budget.
run_agent takes the check and the retry as two optional callables, so the loop knows nothing about citations:
def run_agent(
client: ModelClient,
system: str,
state: ConversationState,
registry: ToolRegistry,
budget: RunBudget,
limits: CallLimits,
policy: ContextPolicy,
check: Callable[[str], FinalCheck] | None = None, # new in Chapter 15
retry: Callable[[FinalCheck], str] | None = None,
max_answer_retries: int = 1,
tracker: BudgetTracker | None = None,
clock: Callable[[], float] = time.monotonic,
recorder: Recorder | None = None,
) -> RunResult:After the tool calls of a step, if the model ended its turn without asking for a tool, the loop runs the check and records the verdict:
verdict = None
if not results and response.stop_reason == "finished" and check is not None:
verdict = check(response.text)
if recorder:
recorder.final_check(index, verdict)What happens if the second answer fails too was the open question Chapter 14 left in spec.md. Here is the end of the loop body:
if results: # new in Chapter 15: a slow tool can end the run before the next call
if tracker.remaining_seconds() < MIN_CALL_SECONDS:
cause = StopCause.TIME_LIMIT
break
continue
final_text = response.text
cause = stop_cause(response, call_limits, limits)
if verdict is None: # not a finished turn, or nothing to check
break
if verdict.accepted:
answer = verdict.answer
break
if retries < max_answer_retries and retry is not None:
retries += 1
state.add_user(retry(verdict)) # the retry is the next step, same budget
continue
answer_errors = verdict.errors # rejected after its retry: no answer
break
else:
cause = StopCause.STEP_LIMITRead it from the top. A step with tool results goes round again, unless the tool round used up the time budget. A step that ended any other way records the stop cause; with no verdict (a cut-off reply, say) the run ends there. An accepted verdict ends the run with an answer. A failed one either earns the retry, by adding the retry message to the conversation and continuing, or ends the run. The else belongs to the for loop: it runs only when every step was used without a break, which is how step_limit is reported.
That ordering settles a corner case. If the first answer fails on the last allowed step, the retry message is added but no step is left to answer it, so the run ends as step_limit, outcome stopped, not rejected. The same happens when the token or time budget runs out before the retry's model call. And every retry costs one more full model call, resending the whole conversation.
The decision: the run ends with StopCause finished, because the model did end its turn, and RunResult.answer is None, with the errors in answer_errors. run_research reports the run as rejected. The rejected text stays in the trace for review, and the command line never prints it as an answer. StopCause keeps its seven recorded values; "rejected" is an outcome of the run, like Chapter 13's trial status, not a new reason for the loop to stop.
Two alternatives looked tempting. The first was for code to write a needs_info answer on the model's behalf. That would blur two different situations: needs_info means the sources don't cover the question, while a rejected answer usually means the evidence was there and the model cited it wrongly. A golden task that expects needs_info, such as the sandbox probe, could then pass on a run that never refused anything. The second was to delete the bad citation and keep the rest. The model wrote its sentences around the citation it chose, so deleting it would leave a claim that looks supported and isn't. Refusing to print costs Sam a re-run. Printing a claim with a missing citation would cost him his trust in every citation the tool prints afterwards.
The run budget
The loop enforces the budget from Chapter 14's spec.md and settings.py defaults: 8 steps, 60,000 tokens and 120 seconds per question, with SEARCH_TIMEOUT_S at 10. The model is never asked to respect any of them. The happy path takes 3 steps and a run with one retry takes 4, which leaves room for a page read and a corrected tool call. As in Chapter 7, the budget is checked before each model call and each call's output cap shrinks to what is left, so the last call can overshoot the token budget by at most that one call. MAX_RETRIES stays at 1 and MODEL_TIMEOUT_S caps each call, shrunk to the time left.
One check is new. After tool calls, the loop looks at the clock before anything else, and a slow tool round ends the run as time_limit before another model call starts. The loop also shares its BudgetTracker with search_web, which is how timeout_s() knows the time left. RUN_MAX_COST_USD is in Settings but not enforced: Chapter 16 adds the money check and its StopCause, cost_limit.
Compaction as a safety net
run_agent is now Chapter 10's loop over a ConversationState, so manage_context runs before every model call with Chapter 10's context policy. With CONTEXT_STRATEGY=compact, it works in this order:
- If the history is at most
COMPACTION_THRESHOLD_TOKENS(24,000), nothing happens. - Above that, the older part of the history is summarised. If the summary call fails, saves nothing or can't be afforded from the run budget, the history is trimmed instead, down to the same 24,000.
- Last, a safety net: if the history is still above
TRIM_TARGET_TOKENS(40,000), it is trimmed down to 40,000. With compaction on, step 2 normally leaves the history well below that; the safety net matters mainly underCONTEXT_STRATEGY=trim, where step 2 is skipped and 40,000 is the only limit.
Every trim and compaction writes a context event to the trace, and both cut only at boundaries where every tool call already has its result: Chapter 10's pairing rule. The rule exists because providers check it. In Anthropic's message format each tool call gets one tool result, matched by its tool_use_id, and all results for one response go back together in the next user message. DeepSeek's Anthropic-compatible API documents the same requirement: the message after tool calls must be a user message with a result for every call, matching ids (DeepSeek docs, checked November 2026). A history cut between a call and its result is therefore not one you can send.
Be honest about its role here: a one-question run under a 60,000-token budget never reaches those thresholds. Chapter 14 expected that too. The policy is a safety net for longer runs, and a test forces it by lowering the threshold. It checks that compaction ran, that every call still has exactly one result, and that the citable set still holds every location, because nothing in it lived in the history.
5. run_research: one question, one outcome
This is where the pieces join. run_research builds one tracker and shares it, builds the registry with citable_from=citable_locations, and binds check and retry to the registry's citable set, read at check time so it includes every result up to that moment:
def outcome_of(run: RunResult) -> Outcome:
if run.cause is not StopCause.FINISHED:
return "stopped" # a budget limit or another stop: never an answer
if run.answer is None:
return "rejected" # the final answer failed its checks twice
return run.answer.status # "answered" (possibly with `missing`) or "needs_info"
def run_research(
question: str,
today: date,
settings: Settings,
client: ModelClient,
backend: SearchBackend,
recorder: Recorder | None = None,
clock: Callable[[], float] = time.monotonic,
) -> ResearchResult:
budget = RunBudget(settings.run_max_steps, settings.run_max_tokens, settings.run_max_seconds)
tracker = BudgetTracker(budget, clock=clock) # shared, so search_web sees the time left
registry = build_registry(
settings.exports_dir,
backend,
lambda: min(settings.search_timeout_s, tracker.remaining_seconds()),
settings.tool_result_max_chars,
citable_from=citable_locations,
)
run = run_agent(
client,
build_system_prompt(today, settings.prompt_version),
ConversationState.start(question),
registry,
budget,
CallLimits(settings.max_output_tokens, settings.timeout_seconds),
settings.context_policy(),
check=lambda text: check_final(text, registry.citable), # read at check time
retry=lambda check: retry_message(check, registry.citable),
tracker=tracker,
recorder=recorder,
)
searches = sum( # calls that returned results; an error result is not counted
c.name == "search_web" and not c.is_error for s in run.steps for c in s.tool_calls
)
price = settings.search_usd_per_query
return ResearchResult(
outcome=outcome_of(run),
run=run,
citable=set(registry.citable),
search_calls=searches,
search_usd=None if price is None else price * searches,
)An answered result may still list gaps in missing, which is how the build gives a partial answer: the cited ranking, plus a note that the web half found nothing. run_research also counts the searches that returned results, so the cost line can price them.
6. A command line with outcomes, exit codes and a cost line
A live run takes the question as an argument, with your settings in .env and your model's price in models.toml:
cd ch15-capstone-build
uv run --env-file .env python -m ch15.cli --today 2026-01-15 \
"Which carriers had the most late deliveries last quarter, and what do public sources say about their service?"--today fixes the date that "last quarter" is measured from, which keeps the seeded data meaningful. --config picks a configuration from Chapter 11's models.toml (default hosted-sdk), so the same command runs through the Anthropic adapter or the OpenAI-compatible one. The loop only sees the provider-neutral model client, and a test runs the carrier script through the OpenAI-compatible adapter over httpx.MockTransport, with hand-written replies in the response format Chapter 11's adapter parses, checking that every tool result goes back with its call's id. Before it spends a token, the CLI checks that settings load, that the sandboxed folder holds CSV exports and that the chosen configuration has its model name and key. Each failure is one line, such as error: not configured (MODEL, ANTHROPIC_API_KEY empty), and exit code 2.
Without a key, --demo NAME runs a fake-model script against the real exports and the search fixture. This is the carrier question:
[demo carriers-late-last-quarter: fake-model replies and token counts, hand-written search
results, an illustrative price; tool results come from the seeded exports]
Question: Which carriers had the most late deliveries last quarter, and what do public sources say about their service?
Today: 2026-01-15
ANSWERED (confidence: medium)
Harbour Express had the most late deliveries in Q4 2025 (139), then Swiftway Parcel (93). Reviews mention missed delivery windows for Harbour Express and slow busy-season deliveries for Swiftway Parcel.
Claims:
1. In Q4 2025, Harbour Express had 139 late deliveries and Swiftway Parcel 93, the two highest. [1]
2. Reviews of Harbour Express mention missed delivery windows on regional routes. [2]
3. Reviews of Swiftway Parcel describe slow regional deliveries in the busy season. [3]
Citations:
[1] shipments.csv (late shipments per carrier, Q4 2025)
[2] https://reviews.example.com/harbour-express (reviews of Harbour Express)
[3] https://reviews.example.com/swiftway-parcel (reviews of Swiftway Parcel)
Missing: -
Run: finished after 3 steps (answer retries: 0, searches: 2)
Tokens: 8,000 in / 460 out
Cost: $0.0103 model (illustrative price) + search unpriced (SEARCH_USD_PER_QUERY not set)
Trace: traces/cli/<time>-carriers-late-last-quarter.jsonlThe banner says what is fake: the model's messages, its token counts, the price and the search results. The counts in the answer are what count_rows returned from the seeded export, and the golden test checks them against an independent count. The cost line multiplies token usage by a price. In a live run, that price comes from your configuration in models.toml, with its date and source page, and searches are priced with SEARCH_USD_PER_QUERY. No price is hard-coded; an unpriced item is printed as unpriced, never as zero.
The exit code tells a script what happened without parsing text:
| Outcome | Printed as | Exit code |
|---|---|---|
answered (possibly with missing) | claims, citations, confidence | 0 |
| needs_info | the NEEDS INFO answer and what is missing | 3 |
| rejected | the errors; the answer stays in the trace | 4 |
stopped (any StopCause but finished) | the StopCause; no answer | 5 |
| bad arguments or configuration | one line | 2 |
7. One run, read from its trace
Every run writes traces/cli/<run id>.jsonl, where the run id is the UTC time plus the demo name (or question); cli takes the place of Chapter 13's eval id, with no trial suffix. The format is Chapter 13's with two new events, context for a trim or compaction and final_check for each final answer the loop checked. One thing moves: run_start and run_end are written by whoever calls run_research with a recorder (here the CLI) rather than by the loop, because only the caller knows the run id, the outcome and the citable set. Tests that call run_research directly pass no recorder and read the ResearchResult instead. As in Chapter 13, steps are numbered from 0 in the trace.
The carrier demo from the command-line section takes three steps. Step 1 (step 0 in the trace) is count_rows on shipments.csv with late = yes, shipped_at from 2025-10-01 to 2026-01-01, grouped by carrier; the registry adds shipments.csv to the citable set. Step 2 is two parallel search_web calls for the top two carriers, and every returned URL joins the set, including a news item the answer never cites. Step 3 is the final answer, accepted on the first check.
The invented-url-rejected demo replays steps 1 and 2, then cites a review page no search returned, twice, at steps 3 and 4 (2 and 3 in the trace). Its trace ends like this (timestamps and the rejected text removed):
{"kind": "final_check", "step": 2, "accepted": false, "errors": ["citations.1: 'https://reviews.example.com/harbour-express-complaints': no tool returned this location in this run; cite only tool results"]}
{"kind": "final_check", "step": 3, "accepted": false, "errors": ["citations.1: 'https://reviews.example.com/harbour-express-complaints': no tool returned this location in this run; cite only tool results"]}
{"kind": "run_end", "outcome": "rejected", "stop_cause": "finished", "steps": 4, "total_tokens": 11960, "answer_retries": 1, "answer_errors": ["citations.1: 'https://reviews.example.com/harbour-express-complaints': no tool returned this location in this run; cite only tool results"], "citable": ["https://news.example.com/2025/11/harbour-express-weekend", "https://reviews.example.com/harbour-express", "https://reviews.example.com/swiftway-parcel", "shipments.csv"], "search_calls": 2, "model_usd": "0.0150", "search_usd": null}From these lines alone, a reviewer can answer "why didn't this print an answer?": the same location failed both checks, and it isn't in citable. The CLI printed REJECTED with that error and exited with code 4. The invented-url-corrected demo differs only in its fourth step, a corrected answer, and exits 0 after one retry.
8. Passing the fake-model tests and the offline golden tasks
Everything runs without a key. ch15/scripted.py holds a fake-model script for each golden task: the tool calls a careful model would make, then a FinalAnswer. The tool results are real, so a script that asks for the wrong count fails against the seeded data. grade() in ch15/golden.py checks one run against its task with deterministic checks only: the outcome, required and forbidden tool calls, the step limit, each expected count next to its group in a claim, and the expected citations.
def research(demo_name: str, exports: Path):
demo = DEMOS[demo_name]
task = TASKS[demo.task_id]
client = FakeModelClient(demo.script())
backend = FixtureSearchBackend(FIXTURE) if demo.search == "fixture" else UnconfiguredSearch()
result = run_research(task.input, task.today, Settings(exports_dir=exports), client, backend)
return task, result
@pytest.mark.parametrize("task_id", sorted(TASKS))
def test_every_golden_task_passes_offline(task_id: str, exports: Path) -> None:
task, result = research(task_id, exports)
assert grade(task, result, exports) == []All five tasks pass: the carrier question, the two exact counts (13 lost by Tallpine Logistics in 2025, and a correct 0 for Northline Freight in October 2025), the uncovered quarter and the sandbox probe, which ends in needs_info after the sandbox refuses ../kestrel.sqlite. The grader is tested too: a rejected run and a claim with a wrong count both fail it. Run the suite from the chapter folder:
uv run pytest -q........................................................................ [ 74%]
......................... [100%]
97 passed in 5.04sBeneath the golden tasks, the tests check each join:
| Layer | What the tests prove |
|---|---|
| Tools | Pages end on a line; count_rows matches every golden count and reports an uncovered period; unknown columns and bad dates are named, quoted newlines stay in one row and an empty file is refused; try_sandbox prints four error results and one success; calculate accepts (139 - 93) / 93 * 100 and rejects powers, names and exponents; the HTTP backend sends its key in a header, drops long URLs, and its timeouts and HTTP errors become error results |
| Citable set | Only successful results add to it; search errors, sandbox refusals and calculate add nothing |
| Final answer | Fenced JSON is accepted; prose fails validation; schema rules and unreturned locations are named by field; the retry message escapes the set inside <data> |
| Loop | One retry fixes an invented URL; a second failure is finished with no answer; the retry needs a step of its own; a slow search ends the run as time_limit; forced compaction keeps every pair and the citable set |
| CLI | Each outcome prints its label and exit code; the trace ends with the outcome, the citable set and the cost; startup problems are one line |
| Second adapter | The carrier script through the OpenAI-compatible adapter ends answered, and every tool call in the request has exactly one result |
An offline pass is deterministic, so a failure points at code or at a script that no longer matches its task, never at sampling. A live run is different: the model's choices vary between runs (Chapter 2), which is why Chapter 16 runs the golden tasks repeatedly as an eval.
9. Where this build is still fragile
Every citation the CLI prints came from a tool in this run. That guarantee is real and narrower than it sounds.
Citation checking proves a location was returned, not that it supports the claim. A genuine review URL can sit next to a sentence the page never says. Chapter 13's model-as-judge grading can catch some of that, at the cost of an extra model call per claim; it would sit on top of the code check, never replace it.
Web evidence is titles and snippets, which is why the prompt caps snippet-only claims at medium confidence. Kestrel's carriers are fictional, so a live search finds nothing about them, or pages about unrelated firms that share a name. Expect a live answer to Sam's question to be the cited ranking with the web half under missing. That is an expectation, not something this book has run; the no-search-partial demo shows the shape of such an answer, with search unconfigured.
The retry message helps the model choose from what the run returned, but a model can repeat a mistake, and then the run is rejected. That is the intended trade: a re-run instead of an unchecked claim.
Failures reach the model unclassified. A search that timed out once and a key that will never work both arrive as error results. Chapter 16 separates them and decides which deserve a retry.
HttpSearchBackend speaks the book's own contract, and live runs through either adapter are left to you: this book shows no live model output. The cost line is an estimate from configured prices, and nothing yet stops a run on cost.
10. Exercises
The first three run offline.
Exercise 1: cite a file the agent never read. Copy invented_url_rejected in ch15/scripted.py into a script whose final answers cite orders.csv as a file. It needs both of its final replies to cite orders.csv: one is answered by the retry message, the second is rejected. Put it in DEMOS and run --demo with it. Expected: exit code 4, and the error names citations.0 and orders.csv (the first citation; field paths count from 0). Then try ./shipments.csv, which the check accepts, and exports/shipments.csv, which it must reject.
Exercise 2: a partial answer in the golden tasks. Add a sixth golden task for the carrier question with expected_status = "answered" and only shipments.csv in its expected citations. Drive it with the no-search-partial script and UnconfiguredSearch, and extend grade(task, result, exports) in ch15/golden.py: add an optional expect_missing: bool field to GoldenTask and append a failure when it is true and result.answer.missing is empty. A common mistake is to forget the field in the model, which extra="forbid" turns into a load error, not a silent pass.
Exercise 3: watch compaction fire. Set COMPACTION_THRESHOLD_TOKENS=300 and COMPACTION_KEEP_UNITS=1, and copy the carrier script with a plain string inserted at index 2, between the search step and the final answer: compaction fires before the third model call, and the summary call takes the next scripted reply. test_forced_compaction_keeps_pairs_and_the_citable_set in tests/test_loop.py does exactly this. If the final answer is used as the summary instead, the run will hit ScriptExhausted. In the trace, find the context event and confirm that run_end.citable matches an uncompacted run's.
Exercise 4 (optional, needs a key). Fill in a priced configuration in models.toml and run the carrier question live, once with search unconfigured and once with a search service you have adapted HttpSearchBackend to. Compare the outcomes, the cost lines and the citable lists.
11. Summary
The research assistant now runs end to end. The four tools have bodies: read_file pages through the sandbox, count_rows does every count in code and reports when a period isn't covered, search_web works behind a backend you choose and offline with a hand-written fixture, and calculate parses arithmetic over Decimal without eval(). The registry collects the citable set from what the model was actually shown, outside the conversation, so compaction can't erase it. The loop checks each final answer, gives one retry, and rejects an answer that still fails rather than printing an unchecked claim. The CLI turns every run into one of four outcomes with its own exit code, a cost line and a trace, and the whole suite passes on the fake model.
The guarantees live in ordinary code: the sandbox, input validation, the counting tool, the citable set, the checks and the run budget. The model chooses the next tool and writes the answer.
Chapter 16, Capstone III, Harden, handles what this build only reports: it classifies failures and adds bounded retries, enforces the cost limit, and turns the golden tasks into an eval you run repeatedly.
