IamBishal

Chapter 9 · Part III: Context, models and testing

Context engineering basics: what goes in the window and why it matters

Measure what fills an agent's context window on each call, cap large tool results without losing their path or URL, and compare loading a whole messy handbook against list_docs and read_doc tools on Grace Lin's policy questions. Also covers why order and noise affect answer quality, and where retrieval fits.

40 min read · from Agentic AI Foundations

Grace Lin, Kestrel's People Partner, runs onboarding, so new starters bring their policy questions to her. This week a new support hire asked which delivery promise applies when a trade customer's order arrives late. Grace puts the question to a small sibling of the operations agent that answers from the internal docs instead of the shipment API. What comes back depends on what was in the context window when the model answered: which pages, how much of each, in what order, and whether the retired shipping page sat next to the current one. The stance this chapter takes is a design caution, not a measured result: when an agent's answer is wrong, inspect its input before you reach for a different model.

By the end of this chapter you will be able to:

  • List what fills the window on every call and measure each part's token share.
  • Explain why length, position and noise change answer quality.
  • Cap or summarise large tool results without losing the path or URL they came from.
  • Compare two designs on Grace's questions: the whole handbook in the prompt, or list_docs and read_doc tools, and say where retrieval fits.

You need tokens and the context window (Chapter 2), the model client and max output tokens (Chapter 3), delimiters and the six-section prompt layout (Chapter 4), the agent loop, its run budget and step log (Chapter 7) and tool output shaping (Chapter 8). The budget inspector and the truncation helper go straight into Sam Adeyemi's research assistant in the capstone, where keeping provenance is what makes citations possible.

1. What the model sees on every step

Context engineering is deciding what goes into the context window on each model call (instructions, tools, history, tool results), in what order and at what size. It overlaps with writing a good prompt but goes further: in an agent the system prompt's share shrinks as the run goes on, because the other inputs grow while it stays the same.

The model keeps nothing between steps. Chapter 7's loop sends the whole package again every time, and whatever is not in it, the model cannot see, even if your code still holds it in a variable.

The package has four components, each with a different owner:

  • System prompt. We write it, keep it in a versioned file and lay it out in Chapter 4's six sections. It does not change during a run.
  • Tool definitions. Fixed per run (Chapters 6 and 8). Names, descriptions and input schemas go out with every request, whether the model uses them or not.
  • History. The user's question, the assistant's earlier messages and its tool calls. It grows on every step.
  • Tool results. Everything the tools have returned so far, re-sent on later steps. Its size is decided by the data, not by our code, which makes it the hardest component to predict.

When we measure, a fifth line appears: overhead, the cost of a near-empty request. It is a measurement artefact rather than something you design, and it stays flat.

Chapter 2 established that the window is a hard limit shared by input and output, so the max output tokens you set on each call take part of it too. Window sizes for specific models belong in configuration, next to the model ID.

The model keeps nothing between steps, so all four parts are sent again on every call.

History appears in this chapter only as a component to measure. Chapter 10 (pending) covers keeping it under control.

2. Why more context can make answers worse

Fitting in the window doesn't mean the model reads everything in it equally well. Anthropic's essay on context engineering describes longer contexts as a performance gradient, not a hard cliff: models stay highly capable as input grows, but they may become less precise at pulling out specific facts and at long-range reasoning.

Position matters too. In the paper "Lost in the Middle: How Language Models Use Long Contexts", in a 20-document question-answering setting, GPT-3.5-Turbo (16K) scored 75.7% when the document containing the answer came first and 54.1% when it came tenth.

The same paper reports that GPT-3.5-Turbo's multi-document question-answering performance can drop by more than 20%. In the worst case, results with 20 and 30 documents fell below the closed-book baseline of 56.1%, the score with no documents at all. In that worst case, adding documents did worse than giving the model nothing.

It also states that extended-context models are not necessarily better at using their input context. A larger window lets you include more; it doesn't mean the model makes good use of what you include. These results come from the models the paper tested on a research task. Treat them as evidence of a pattern, not as predictions for the model in your .env.

Then there is noise: content that looks relevant but is wrong, stale or duplicated. Kestrel's retired shipping page uses the same vocabulary as the current policy, yet it promises 4 working days where the current page promises 3. Kestrel at least labels it in its title; many real folders don't. My analysis, not a measured result, is that every conflicting page in the window is something the model can wrongly anchor on, and it cannot tell which page was retired unless something in the context says so. Leave out what the task does not need.

Ordering helps, within limits. As of November 2026, Anthropic's prompting guide advises putting long documents near the top of the prompt, above the query, instructions and examples, and says this improves performance across all models. The paper tested a related change, repeating the query before and after the data: it gave near-perfect results on a synthetic key-value lookup task but only minimally changed the trends in multi-document question answering. Better ordering helps the model find facts in clean data. It does not take the stale page out of the context.

That advice pulls against Chapter 4's layout, which puts <data> fourth, below the instructions. This chapter keeps the recorded layout and treats documents-first as an experiment (Exercise 2); the default changes only through a recorded decision backed by measurements.

Delimiters still matter, for clarity rather than defence. Anthropic's guide says XML tags help its models parse prompts that mix instructions, context, examples and variable inputs, and its essay says the exact formatting of prompts is likely becoming less important as models become more capable. My reading: what you include matters more than how you format it. Defending against prompt injection is a separate problem, covered in Books 6–8.

3. Measuring each component: the context budget inspector

A total token count tells you the window is filling. It does not tell you what to cut. A bloated system prompt calls for editing a versioned file, too many tool definitions call for a smaller tool set, and a large tool result calls for a cap. So we measure, and plan, per component.

A context budget per component plans how one request's window is spent. In this book a budget is a limit the code enforces, so it holds exactly two limits: the cap on each tool result, enforced by the tool registry inside the loop, and the output reserve (max output tokens), enforced by the provider, which never generates past it. Next to them sit two ceilings, one each for the system prompt and for the tool definitions. Ceilings are not limits: the inspector reports a component that passes one, and nothing stops. History gets whatever is left, and the inspector's headroom shows how much that is. None of this replaces Chapter 7's run budget (steps, tokens and wall time so far; money joins it in the capstone), which is still what stops a run. A component's share is its tokens divided by the request's total input tokens.

ch09-context-engineering/ch09/context_budget.py (excerpt)
class ContextBudget(BaseModel):
    window: int  # configured per model, next to the model ID
    output_reserve: int  # enforced by the provider: max output tokens per call
    tool_result_max_chars: int  # enforced by the loop: cap per tool result
    system_ceiling: int | None = None  # tokens; warning only
    tools_ceiling: int | None = None  # tokens; warning only

The chapter's defaults are a 16,000-character cap per tool result, a 2,000-token system-prompt ceiling and a 3,000-token tools ceiling. They are design choices in .env.example, not facts about any model. The cap is in characters because the loop must apply it to every result without a network call.

Tool definitions are the component people forget. As of November 2026, Anthropic's tool definition docs say that when you pass tools, the API builds a special system prompt from the tool definitions, the tool configuration and your own system prompt; with no tools and tool choice none, that tool-use system prompt adds 0 tokens. Anthropic reports that adding Jira's tools alone uses about 17K tokens, and that it has seen tool definitions consume 134K tokens before optimisation.

Counting tokens per component

Chapter 2 called the provider's count endpoint directly as a preview; now it moves behind the model client. As of November 2026, Anthropic's count endpoint is POST /v1/messages/count_tokens. Counts are model-specific, so the adapter sends the same model ID as inference. The endpoint is stateless: to find one component's tokens, count the request with it and without it, and subtract.

ch09-context-engineering/ch09/model_client.py (excerpt)
class ModelClient(Protocol):
    def complete(
        self,
        system: str,
        messages: Sequence[Message],
        max_tokens: int,
        tools: Sequence[ToolDefinition] = (),
        tool_choice: ToolChoice | None = None,
        timeout: float | None = None,  # Chapter 7: seconds for this call only
    ) -> ModelResponse: ...

    # New in Chapter 9
    provider_counts: bool  # False when count_tokens is a local estimate

    def count_tokens(
        self,
        system: str,
        messages: Sequence[Message],
        tools: Sequence[ToolDefinition] = (),
        timeout: float | None = None,
    ) -> int: ...

The inspector counts five requests. Three never change during a run, so it makes them once (count_fixed); the other two it makes on every step:

ch09-context-engineering/ch09/inspector.py (excerpt)
def count_fixed(
    client: ModelClient,
    system: str,
    tools: Sequence[ToolDefinition],
    timeout: float | None = None,
) -> FixedCounts:
    return FixedCounts(
        base=client.count_tokens("", PLACEHOLDER, (), timeout),
        with_system=client.count_tokens(system, PLACEHOLDER, (), timeout),
        with_tools=client.count_tokens(system, PLACEHOLDER, tools, timeout),
    )


def inspect_request(
    client: ModelClient,
    system: str,
    tools: Sequence[ToolDefinition],
    messages: Sequence[Message],
    fixed: FixedCounts,
    budget: ContextBudget,
    timeout: float | None = None,
) -> ContextReport:
    blanked = client.count_tokens(system, blank_tool_results(messages), tools, timeout)
    full = client.count_tokens(system, messages, tools, timeout)
    raw: dict[Component, int] = {
        "overhead": fixed.base,
        "system": fixed.with_system - fixed.base,
        "tools": fixed.with_tools - fixed.with_system,
        "history": blanked - fixed.with_tools,
        "tool_results": full - blanked,
    }
    return build_report(raw, full, budget, client.provider_counts)

blank_tool_results returns a copy of the messages with every tool result's content emptied. Blanking rather than removing matters: drop a result and its tool call has no answer, so the request is invalid. build_report computes shares, compares each component with its ceiling and works out headroom: the window minus the input minus the output reserve. Negative headroom means the request no longer fits, so the inspector logs a warning. What happens next depends on the provider; if it rejects the call, the loop reports model_error.

The five values add up to full by construction, but each is the difference between two separate counts. Request framing doesn't split neatly along our component lines, so treat the figures as approximate at the boundaries. The placeholder message, for example, is counted in overhead, so history comes out a token or two low.

Hooking it into the loop

In run_agent, the inspector is an optional argument. When it is set, the loop measures the exact request it is about to send, then rechecks the run budget and shrinks the model call's timeout to the time left, because counting took some. The ContextReport goes into the step's model-call record (StepRecord.context):

ch09-context-engineering/ch09/agent.py (excerpt)
        started, context = clock(), None
        if inspector is not None:  # the request about to go out; its time counts too
            timeout = min(limits.timeout_seconds, tracker.remaining_seconds())
            context = measure(inspector, system, tools, messages, timeout)
            cause = tracker.check(MIN_CALL_TOKENS, MIN_CALL_SECONDS)  # measuring took time
            if cause is not None:
                break
        call_limits = CallLimits(  # shrink this call to what the run has left
            max_output_tokens=min(limits.max_output_tokens, tracker.remaining_tokens()),
            timeout_seconds=min(limits.timeout_seconds, tracker.remaining_seconds()),
        )
        sent = len(messages)
        try:
            response = client.complete(
                system,
                list(messages),  # a copy: later appends must not change this request
                call_limits.max_output_tokens,
                tools,
                timeout=call_limits.timeout_seconds,
            )

measure catches a failed count, logs it and returns None: measuring must never end a run. A component over its ceiling logs a warning, and the run continues under Chapter 7's limits. Counting costs network calls and wall time, so switch the hook on in development and eval runs, or on a sample of steps. In production, every real call already reports its input usage at no extra cost, which is enough to watch the trend.

Here is Chapter 8's operations agent, with its v2 tools and prompt, chasing Chapter 7's four orders with the inspector on. The fake model scripts the replies and its own in=/out= usage, which are invented, so don't compare them with the table; the table measures the real requests, tool results from the mock API included.

text
$ uv run python -m ch09.inspect_ops --fake chased
[fake model: scripted replies; tool results from the mock API]
step 1  tool_call 4x get_delivery_status (1 ERR) in=1210   out=96    8 ms
step 2  tool_call 1x list_shipments          in=1830   out=58    5 ms
step 3  finished  -                          in=4120   out=162   0 ms
stopped: finished  steps 3/8  tokens 7476/60000  time 0.0/90 s
step         overhead         system          tools        history   tool_results   total  headroom
1              1 (0%)      263 (18%)     1169 (80%)        35 (2%)         0 (0%)    1468     97508
2              1 (0%)      263 (15%)     1169 (66%)        94 (5%)      238 (13%)    1765     97211
3              1 (0%)      263 (11%)     1169 (49%)       113 (5%)      841 (35%)    2387     96589
[local estimates; window 100000, output reserve 1024]

Read down the columns, not across the rows. overhead, system and tools stay flat. history grows a little on every step, because questions and tool calls are short. tool_results jumps when the agent lists a page of late Northline Freight shipments, and it is the component that grows fastest. In this short run, though, the five tool definitions stay the largest: on step one they are four-fifths of the request, which is easy to miss when you only read your prompt file.

With your own key, compare each step's reported input_tokens with the report's total_input. A sharp gap with provider counts means the inspector counted a different request from the one sent. With local estimates, use the gap to tune CHARS_PER_TOKEN.

4. Capping tool results without losing where they came from

Chapter 8 shaped outputs inside individual tools, and that is still the first line of defence. But a document tool can return a 40-page manual, and the capstone's web search will return pages we never wrote. Every tool result needs a size limit. The hard part is applying it without losing track of what the content is.

Provenance of a tool result is the record of three things: where the content came from (a file path or a URL), which part of it the model is seeing, and whether it was cut or summarised. Once a result is truncated or summarised, its sentences are detached from their document. If two capped policies sit side by side in the history, neither the model nor our code can tell which file a sentence came from, so there is nothing to check a citation against.

The envelope

ch09-context-engineering/ch09/truncate.py (excerpt)
Kind = Literal["file", "url", "tool"]  # "tool": identifiable, never citable
MARKER_ROOM = 64  # space kept for the truncation marker


class ProvenancedResult(BaseModel):
    origin: str  # file path, URL, or tool call
    kind: Kind
    total_chars: int
    shown: list[tuple[int, int]]  # half-open character ranges of the original
    truncated: bool = False
    summarised: bool = False
    fetched_at: datetime | None = None  # set for URLs
    content: str

    def render(self) -> str:
        """Header line from our code, then the content as data (Chapter 4's tag rule)."""
        ranges = ", ".join(f"{start}-{end}" for start, end in self.shown)
        parts = [
            f"origin: {header_safe(self.origin)}",  # URLs and tool arguments come from outside
            f"kind: {self.kind}",
            f"shown: {ranges} of {self.total_chars} chars",
        ]
        if self.fetched_at:
            parts.append(f"fetched: {self.fetched_at.isoformat()}")
        parts += [
            f for f, on in (("truncated", self.truncated), ("summarised", self.summarised)) if on
        ]
        return f"[{' | '.join(parts)}]\n<data>{escape(self.content, quote=False)}</data>"


def header_safe(text: str) -> str:
    """Remove the header's own delimiters, so an origin cannot imitate another field."""
    return " ".join(text.translate(str.maketrans("[]|", "()/")).split())


def cap_result(
    text: str,
    *,
    origin: str,
    kind: Kind,
    max_chars: int,
    offset: int = 0,
    head_share: float = 0.7,
    fetched_at: datetime | None = None,
) -> ProvenancedResult:
    """Bound the content to max_chars, marker included. The header line is extra."""
    if max_chars < 4 * MARKER_ROOM:
        raise ValueError(f"max_chars={max_chars} is too small; use at least {4 * MARKER_ROOM}")
    total = len(text)
    meta = dict(origin=origin, kind=kind, total_chars=total, fetched_at=fetched_at)
    if offset > 0:  # paging: one window from offset, no tail
        if offset >= total:
            raise ValueError(f"offset {offset} is past the end ({total} chars)")
        end = min(offset + max_chars, total)
        return ProvenancedResult(
            **meta, shown=[(offset, end)], truncated=True, content=text[offset:end]
        )
    if total <= max_chars:
        return ProvenancedResult(**meta, shown=[(0, total)], content=text)
    keep = max_chars - MARKER_ROOM
    head_end = int(keep * head_share)
    tail_start = total - (keep - head_end)
    content = (
        text[:head_end]
        + f"\n[truncated: chars {head_end}-{tail_start} omitted]\n"
        + text[tail_start:]
    )
    return ProvenancedResult(
        **meta, shown=[(0, head_end), (tail_start, total)], truncated=True, content=content
    )

render puts one header line from our code above the content, and the content itself goes inside <data> tags with tag characters escaped. That is Chapter 4's rule, which Chapters 7 and 8 already applied to every result; this path replaces the registry's as_data() and its fixed backstop. The header is new, and it sits outside the tags because our code writes it. An origin can come from outside (a URL, a tool's arguments), so render strips the header's own delimiters from it first. max_chars bounds the content, marker included, so a rendered result is slightly longer than the cap. A cap too small to hold the marker fails loudly instead of producing nonsense.

With no offset, the helper keeps the head and the tail. That rests on an assumption: for policy pages, I assume scope sits near the top and exceptions or effective dates near the bottom. When the clause you need is in the middle, the marker says text is missing and gives its range, and read_doc can pass the start of that range as offset. Here is the current shipping policy read with a deliberately tiny 300-character cap, then the page from the marker:

text
$ uv run python -m ch09.demo_cap
[origin: shipping-policy.md | kind: file | shown: 0-165, 654-725 of 725 chars | truncated]
<data># Shipping policy (v3, effective 1 March 2025)

&gt; Kestrel Outfitters is a fictional company; this document is synthetic.

- Orders placed before 14:00 on a working d
[truncated: chars 165-654 omitted]
r performance is reviewed every quarter by Operations (Tomasz Wójcik).
</data>
[origin: shipping-policy.md | kind: file | shown: 165-465 of 725 chars | truncated]
True

The delivery promise Grace needs is exactly in the omitted middle; the second read, from offset 165, contains it (the True). head_share is a setting to tune per source: web pages may open with navigation, so the capstone may want a smaller head share for URLs. Head and tail suits prose, never tables: cutting rows out of a CSV export silently changes any count taken from it, so page or filter tabular data instead.

Whichever path it takes, the origin stays in the header inside the result.

One rendering path

Chapter 8's registry.py keeps its per-field hints and validation messages; the one change is the last step of dispatch, which now hands every successful output to a single function:

ch09-context-engineering/ch09/registry.py (excerpt)
        content, is_error = render_tool_result(  # new in Chapter 9: header, cap, <data>
            call.name, call.arguments, output, self.max_result_chars
        )
        return ToolResult(tool_call_id=call.id, content=content, is_error=is_error)
ch09-context-engineering/ch09/results.py (excerpt)
def render_tool_result(name: str, args: dict, output: object, max_chars: int) -> tuple[str, bool]:
    """Called once per successful tool call by the registry. Returns (content, is_error)."""
    if isinstance(output, ProvenancedResult):  # the tool set its own origin
        try:
            return enforce_cap(output, max_chars).render(), False
        except ValueError as exc:
            return str(exc), True
    origin = f"{name}({json.dumps(args, sort_keys=True)})"
    text = output if isinstance(output, str) else json.dumps(output, default=str)
    if not isinstance(output, str) and len(text) > max_chars:
        # Shaped JSON from Chapter 8's tools: never cut it mid-structure.
        return (
            f"{name} returned {len(text)} chars of JSON, over the {max_chars}-char cap. "
            f"If {name} takes paging or filter arguments, call it again asking for less; "
            "otherwise say the result was too large to read."
        ), True
    return cap_result(text, origin=origin, kind="tool", max_chars=max_chars).render(), False

An envelope a tool built itself still passes through enforce_cap. A tool that forgot to cap a 200K-character page gets cut to the cap, keeping its origin, kind and fetched_at, with the header showing which range survived. A summary or a multi-range result can't be re-sliced honestly, so it becomes an error result instead. Plain strings get a tool-kind envelope whose origin is the tool name and arguments: identifiable, but never citable. Structured JSON is never cut by characters, because a cut produces invalid JSON; the error tells the model to ask for less if the tool takes paging or filter arguments, and otherwise to say the result was too large. That second branch matters for list_docs, which has no arguments to narrow: a folder of a few hundred documents would push its listing past the cap, and it would then need Chapter 8's paging.

When to summarise instead

Some results are so far over the cap that head and tail would show almost nothing. For those, a tool can opt in to summarise_result; the loop never calls it on its own. Its prompt is a versioned file, summarise_v1.md, a single-purpose helper prompt rather than an agent prompt, so it skips the six-section layout.

ch09-context-engineering/ch09/summarise.py (excerpt)
def summarise_result(
    client: ModelClient,
    text: str,
    *,
    origin: str,
    kind: Kind,
    max_chars: int,
    max_input_chars: int,
    max_tokens: int,
    timeout: float | None = None,  # pass what the run has left (Chapter 7)
    fetched_at: datetime | None = None,
) -> tuple[ProvenancedResult, Usage | None]:
    """Returns (result, usage); the caller adds usage to the run budget.
    Falls back to cap_result instead of failing."""
    fallback = cap_result(
        text, origin=origin, kind=kind, max_chars=max_chars, fetched_at=fetched_at
    )
    if len(text) > max_input_chars:  # too large for the summarising call itself
        return fallback, None
    try:
        reply = client.complete(
            load_prompt("summarise", 1).body,
            [Message(role="user", content=f"<data>\n{escape(text, quote=False)}\n</data>")],
            max_tokens,
            timeout=timeout,
        )
    except ModelError as exc:  # Chapter 3's errors, after the SDK's retries
        logger.warning("summary of %s failed (%s); falling back to a cap", origin, exc.kind)
        return fallback, None
    if reply.stop_reason != "finished":  # cut off or odd: not a complete summary
        logger.warning("summary of %s ended with %s; falling back", origin, reply.stop_reason)
        return fallback, reply.usage
    if len(reply.text) > max_chars:  # complete but over the cap: the registry would refuse it
        logger.warning("summary of %s is over the %d-char cap; falling back", origin, max_chars)
        return fallback, reply.usage
    result = ProvenancedResult(
        origin=origin,
        kind=kind,
        total_chars=len(text),
        fetched_at=fetched_at,
        shown=[(0, len(text))],  # the range summarised; none of it verbatim
        summarised=True,
        content=reply.text,
    )
    return result, reply.usage

The origin passes through unchanged, and summarised=True tells the model and our code that none of the content is the source's own wording. The extra call costs money, latency and tokens, so its usage goes back to the caller for the run budget, and its timeout should be what the run has left. A failed call, a cut-off summary or one longer than the cap is logged and falls back to a capped result. When exact wording matters, as it does for Grace's policy questions, prefer truncation plus paging. Summarising one result is not compaction, which works on the whole conversation history; Chapter 10 (pending) covers it.

5. Grace's policy questions: the whole handbook or two small tools

Grace's questions come from onboarding: what an over-limit training claim needs, how long trade customers have to return items and, from new support hires, which delivery promise applies to a late trade order. Every answer lives under .kestrel/docs/, which is messy on purpose: shipping-policy-v2-OUTDATED.md still sits next to the current page.

The chapter folder holds these questions. Each names the file that answers it, phrases a correct answer must contain and, where the retired page disagrees, phrases only that page contains. Chapter 13 (pending) turns questions like these into golden tasks with a fuller format.

ch09-context-engineering/ch09/questions.py (excerpt)
    PolicyQuestion(
        id="trade-late-delivery",
        question="A trade customer's standard order arrived late. What was the delivery "
        "promise, and when does a delivery count as late?",
        expected_path="shipping-policy.md",
        expected_facts=["3 working days", "after its promised date"],
        stale_facts=["4 working days"],
    ),

Grading is deliberately simple:

ch09-context-engineering/ch09/grade.py (excerpt)
def quotes_stale(q: PolicyQuestion, answer: str) -> bool:
    """Relying on the retired page, not merely naming it as superseded."""
    text = answer.lower()
    return any(f.lower() in text for f in q.stale_facts)


def is_correct(q: PolicyQuestion, answer: str, read_paths: set[str] | None = None) -> bool:
    """read_paths: the docs the run actually read (variant B). A path the model only saw in
    list_docs does not count. None means every doc was in the context (variant A)."""
    text = answer.lower()
    return (
        q.expected_path in answer
        and (read_paths is None or q.expected_path in read_paths)
        and all(f.lower() in text for f in q.expected_facts)
        and not quotes_stale(q, answer)
    )

A correct answer names the right path, contains the required phrases and carries nothing from the retired page. In variant B the path must also be one the run actually read: a model that names shipping-policy.md because list_docs printed it, without opening it, is not citing anything. Naming the retired file to say it is superseded is fine; repeating its 4 working days is not. Two of the tests pin that down:

ch09-context-engineering/tests/test_compare.py (excerpt)
def test_naming_a_path_the_run_never_read_is_not_correct():
    answer = "3 working days, late after its promised date. Source: shipping-policy.md"
    assert not is_correct(TRADE, answer, read_paths=set())


def test_relying_on_the_retired_page_is_caught_but_naming_it_is_not():
    assert quotes_stale(TRADE, "Standard delivery takes 4 working days.")
    assert not quotes_stale(TRADE, "shipping-policy-v2-OUTDATED.md is superseded; ignore it.")

Phrase matching still misses paraphrases and accepts a right phrase in a wrong sentence. It is good enough to compare two designs on the same questions, not to certify an agent.

Variant A: the whole handbook in the system prompt

The first variant puts every document into the <data> section of a six-section prompt, handbook_v1.md. Each document gets its own tag carrying its path, and tag characters are escaped. Each question costs one model call with no tools.

ch09-context-engineering/ch09/handbook_compare.py (excerpt)
from ch09.settings import Settings


def render_handbook(root: Path) -> str:
    """Every doc, each wrapped in a tag that carries its path, tag characters escaped."""
    return "\n".join(
        f'<doc path="{escape(path)}">\n'
        f"{escape((root / path).read_text(encoding='utf-8'), quote=False)}\n</doc>"
        for path in sorted(doc_paths(root))
    )

Variant B: two read-only tools and the agent loop

The second variant's prompt, docs_agent_v1.md, holds instructions only. list_docs returns the path, title and length in characters of every document; read_doc(path, offset=0) returns one document through cap_result. Each question runs through run_agent with the run budget unchanged and the inspector on.

ch09-context-engineering/ch09/doc_tools.py (excerpt)
LIST_DOCS_DESCRIPTION = (
    "List every internal Kestrel document (handbook pages and policies). Returns the path, "
    "title and length in characters of each. Call this first: read_doc only accepts paths "
    "that appear in this list."
)
READ_DOC_DESCRIPTION = (
    "Read one internal document by a path returned by list_docs. Long documents are "
    "truncated: the header shows which character ranges you are seeing, and a marker names "
    "the omitted range. Pass offset to read from that position."
)


class ListDocsInput(BaseModel):
    model_config = ConfigDict(extra="forbid")


class ReadDocInput(BaseModel):
    model_config = ConfigDict(extra="forbid")
    path: str = Field(max_length=200, description="A path exactly as list_docs returned it.")
    offset: int = Field(0, ge=0, description="Character position to start reading from.")


def doc_paths(root: Path) -> set[str]:
    """Docs-relative paths: the only form list_docs returns and read_doc accepts."""
    return {p.relative_to(root).as_posix() for p in root.rglob("*.md") if p.name != "README.md"}


def list_docs(root: Path, args: ListDocsInput) -> list[dict[str, object]]:
    docs = []
    for path in sorted(doc_paths(root)):
        text = (root / path).read_text(encoding="utf-8")
        title = text.splitlines()[0].removeprefix("# ") if text else path
        docs.append({"path": path, "title": title, "chars": len(text)})
    return docs


def read_doc(root: Path, max_chars: int, args: ReadDocInput) -> ProvenancedResult:
    if args.path not in doc_paths(root):  # also keeps reads inside the docs folder
        raise ToolError(f"Unknown doc path {args.path!r}. Call list_docs and use a path from it.")
    text = (root / args.path).read_text(encoding="utf-8")
    try:
        return cap_result(
            text, origin=args.path, kind="file", max_chars=max_chars, offset=args.offset
        )
    except ValueError as exc:  # an offset past the end: tell the model the length
        raise ToolError(str(exc)) from exc

Chapter 8's rules show up in the details: the descriptions say when to call each tool, read_doc accepts only a path list_docs would return, and its errors tell the model how to recover. Lengths are in characters, the same unit as offset and the header, so the model can page without converting. The membership check also keeps reads inside the docs folder, because a path like ../.env is never in the set; the file sandbox proper comes in Chapters 14 and 15 (pending). One detail does a lot of work: the retired page's own title says it was superseded, and list_docs shows that title to the model before it opens anything.

Variant A pays for every page on one call. Variant B pays per step but reads only what it needs.

What the measurements show

The comparison script runs both variants over the same questions with the same settings. With the fake model the replies are scripted (variant B always lists, reads the expected document, then answers), so correctness means nothing yet. Two columns still do. input tokens estimates the real requests each design sends. stale sent checks those requests for a phrase only the retired page contains:

ch09-context-engineering/ch09/handbook_compare.py (excerpt)
def stale_sent(q: PolicyQuestion, texts: list[str]) -> bool | None:
    """Did a phrase only the retired page contains reach the model? None: nothing to check."""
    if not q.stale_facts:
        return None
    return any(f in t for f in q.stale_facts for t in texts)


def request_texts(messages: list[Message]) -> list[str]:
    """Everything a run sent besides the system prompt: messages and tool results."""
    return [m.content for m in messages] + [r.content for m in messages for r in m.tool_results]
text
$ uv run python -m ch09.handbook_compare --fake
handbook: 4 docs, 2102 chars
[fake model: scripted replies; token counts are local estimates of the real requests]
question              variant  steps  input tokens  stale sent
trade-late-delivery   A        1      811           yes
trade-late-delivery   B        3      2077          no
training-over-limit   A        1      803           -
training-over-limit   B        3      2015          -
trade-returns         A        1      796           -
trade-returns         B        3      1977          -

That is not the result the usual advice predicts. Kestrel's folder is four short policy files, so sending all of it costs less than three steps, each of which re-sends the instructions, both tool definitions and everything read so far. What variant A pays instead shows in the last column: the retired page's 4 working days reaches the model on the trade question, and only the model's attention to a title keeps it out of the answer. In variant B the model sees that title in a short listing and never opens the page, so the wording never arrives, at the price of extra steps.

A real handbook, with manuals and wiki pages, is far larger. --crossover grows a copy of the folder with synthetic filler pages of about 1,700 characters each and reruns the trade question:

text
$ uv run python -m ch09.handbook_compare --fake --crossover
[fake model: scripted replies; token counts are local estimates]
filler pages  docs chars  A tokens  B tokens
0             2102        811       2077
2             5592        1699      2161
4             9082        2588      2243
8             16062       4365      2411
32            57942       15027     3407

Variant A grows with every page it carries; variant B grows only by one list_docs line per page. Here they cross between two and four filler pages, at well under 10,000 characters of documents. With your own key the script adds correct and stale columns, and the steps become an observation: a real model may open a second document, or answer without reading, which fails the grader.

My recommendation follows the measurement. Small, stable, curated text that every call needs can sit in the system prompt; for today's folder, leaving the retired page out of the prompt would be the cheapest fix, while someone knows which pages are retired. Content that is large, messy, growing or only sometimes relevant should come in through tools. Neither variant can fix a question no document answers; both prompts keep Chapter 4's don't-know rule.

6. Trade-offs and failure modes

Each of these failures can break an agent without raising an error.

Tool definitions creep. Every tool is sent with every request and is one more choice to get wrong. As of November 2026, Anthropic reports that the most common tool-use failures are wrong tool selection and incorrect parameters, especially when tool names are similar, and says that too many or overlapping tools can distract agents from efficient strategies. Before adding a tool, run the inspector with and without it.

Tokens are money and time. Multiply each step's input by the input price in settings (Chapter 2) and the tool-results column becomes the growing line on the bill. Provider-side caching of repeated input is a further lever, left to your provider's docs.

The cap cuts the answer. Head and tail can miss a clause in the middle, as the demo showed. Worse, a model may answer from the visible part as if it were whole and never page. Keep the marker explicit, and page from its offset rather than raising the cap.

Provenance gets dropped downstream. A logging helper or retry wrapper that rebuilds a result from content alone silently loses the origin. Run the provenance tests against any new code that touches tool results.

Where retrieval fits. Retrieval means fetching relevant content into the context on demand, with the tool itself finding what is relevant. read_doc is a plain file read, not retrieval: the model names a path and gets that file. A retrieval tool would plug into this loop the same way, as a tool whose results arrive capped and carrying their origin. Indexed search, ranking and chunking belong to Book 2: Context, Memory and Retrieval.

7. Exercises

Run the live parts against the Kestrel mock API with your key in .env, and the test parts without a key.

Exercise 1: measure. Run inspect_ops with your key and the v2 tools, then with Chapter 8's first-draft set (tools_v1.py, copied from its folder). Keep the prompt, question and model ID fixed. Report how the tool-definition and tool-result shares changed. Hint: the fixed counts already isolate the tool definitions.

Exercise 2: order. In a copy of handbook_v1.md (as handbook_v2.md), move the data section above the task section and rerun Grace's questions live. Compare is_correct and quotes_stale. With documents this short, expect little or no difference; repeat it on a grown folder (grow_folder), running each order several times, because Chapter 2 showed that output varies between runs.

Exercise 3: noise. Point --docs at a scratch copy of the docs folder with a second stale copy of one policy, titled like a current one. Check whether variant B still opens the current file. If it doesn't, improve what list_docs returns, for example an updated date per entry, and leave the system prompt alone.

Exercise 4: growth. Replace the synthetic filler in grow_folder with longer, realistic pages (a product manual, a wiki page that half-answers a question) and rerun --crossover, then the graded run with your key.

Exercise 5: provenance. Write a fake-model test that summarises a URL-origin result with fetched_at set and fails if any provenance field is lost. Add a logging wrapper that rebuilds the result from content alone and confirm the test catches it.

8. Summary and what comes next

Context engineering is deciding what the model sees on each call, and in an agent that decision is remade on every step. The inspector gives each component a measured share, using provider counts where an endpoint exists and a flagged estimate where it doesn't. The context budget per component enforces two limits, the tool-result cap and the output reserve, and sets ceilings that only warn. The run budget is still what stops a run.

Length, position and noise reduce answer quality gradually; leaving out what the task does not need helps most. Every capped or summarised result keeps its origin in a header, and the registry checks the cap even for envelopes that tools build themselves. In the capstone, citations are checked against those origins.

Grace's questions made the handbook choice something to measure rather than argue about. At four pages the whole handbook is the cheaper design, but it sends the retired page's wording with every question, and a few pages more tip the cost to the tools.

The conversation, tool results included, still grows unchecked: each result is capped, never their sum. Chapter 10 (pending) deals with it, so long runs stay inside the budget this chapter defined.

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.