Part 1: Prefix, Hybrid Retrieval, and Offloading
Build the project’s prefix, retrieval, and execution layers by assembling tested components into shared files. You’ll verify cache stability, history and retrieval budgets, quote grounding, edge ordering, and sandbox limits while learning why isolation matters for code generated from untrusted context.
We'll cover the following...
In the last lesson, we wrote the project’s specification: six files, a 1,063-token fixed prefix, a 16,000-token working budget with a cap for each part, the cache breakpoint, and the trust boundaries. None of the project files exists yet.
In this lesson, we’ll write three of them: context_prefix.py, retrieval.py, and runner.py. Each one assembles pieces we built and tested in earlier chapters. The new work is the assembly. Moving tested code into a shared file can break it in ways the earlier tests never checked, so after each file we’ll rerun the check that proved the original, now against the assembled file and the budget from the specification.
Write the prefix file
Every request depends on the exact bytes before the cache breakpoint, so context_prefix.py comes first. It holds three rules from Chapter 3 and one from Chapter 5:
Fixed prefix: We always send the same six tools and the same system prompt, in the same order.
Masking with
tool_choice: We pick the tool mode from the state machine, so the tools block itself never changes.Dynamic content after the breakpoint: We put retrieved notes, memory, history, and the question in the messages.
Compaction: We archive old turns and summarize them once the history passes its threshold, applying the Write and Compress moves from Chapter 1.
Here’s the file.
In the code above:
Line 9: We list the tool names from the six project tools.
Lines 12–18: We define
tool_choice(). It asksnext_state()from Lesson 3.4 for the mode. A known next tool becomes a forced choice, after a check that the tool exists. Otherwise the mode isrequiredorauto.Lines 21–25: We define
build_request(). It compacts the history withcompact_session()from Lesson 5.2, then puts the context, the history, and the question in the user message. The tools and the system prompt never change.Lines 28–29: We define
prefix_of(), which renders the part of the request that gets cached.
Check that the prefix holds
The cache ...