ステップ 4 / 13 - 約 35 分
Lab 03 - Context assembly and caching
Time: about 35 minutes. You will: lay out every request so the prompt cache keeps working, give the model fresh facts each turn without breaking it, and see what each conversation costs.
Why
An always-on assistant sends its whole context on every request: the tools, the persona, the rules, and the conversation so far. Without care, you pay full price for all of it every time. With care, almost all of it is read from the prompt cache at a fraction of the price, and the answers start sooner. The difference comes down to one property: the start of every request must be byte-for-byte the same as the start of the one before.
Concepts
What the cache sees
The API reads a request in a fixed order and caches it from the start:
図のソース
flowchart LR
T[tools] --> S[system] --> M1[message 1] --> M2[message 2] --> MN[... new message]
style T fill:#2d6a4f,color:#fff
style S fill:#2d6a4f,color:#fff
style M1 fill:#2d6a4f,color:#fff
style M2 fill:#2d6a4f,color:#fffA request reuses the cache only for a prefix that is exactly the same as in an earlier request. From the first changed block on, everything is processed (and billed) again: a change in the tools invalidates the system prompt and the messages too, and a change in the system prompt invalidates the messages. So:
| Keep stable (front of the request) | Put at the end (new each turn) |
|---|---|
| Tool list, in a fixed order | The new user message |
| Persona and rules | The current time, the channel |
| Earlier messages, exactly as they were | Anything that changes per turn |
Things that silently break the cache: a timestamp or a counter in the system prompt, tools built in a different order, JSON with keys in a random order, or editing an earlier message.
Two more facts matter for an always-on assistant. A cached prefix lives for 5 minutes and every hit refreshes it, so after a longer pause the next message writes the cache again. And a prompt shorter than the model's minimum (512 tokens on Claude Opus 5.5) is not cached at all, with no error; Steward's tools and system prompt are well above that.
Where per-turn facts go
A study coach needs today's date in almost every answer. Putting it in the system prompt would
change the first block of every request: a cache miss every time. Instead, src/context/turn-context.ts
adds a small block at the front of each user message:
<turn-context>
local time: Sunday, November 22, 2026 at 10:15 AM (America/New_York)
channel: terminal
</turn-context>That block becomes part of the history like any other text, so every earlier request stays
unchanged. The current_time tool from lab 01 is still there for a long turn where the time
matters to the minute.
What a request costs
The API reports four token counts, each priced differently (Pricing):
| Usage field | Meaning | Price (Claude Opus 5.5, per million) |
|---|---|---|
input_tokens |
Not cached | $4.00 |
cache_creation_input_tokens |
Written to the cache (5-minute cache) | $5.00 (1.25x input) |
cache_read_input_tokens |
Read from the cache | $0.20 (0.05x input) |
output_tokens |
Generated, including thinking | $20.00 |
The three input counts add up to the size of the request. Prices live in
config/steward.example.json (pricing), so you can update them without touching code. Check
the current price list before you rely on the numbers: cache reads are 0.1x the input price on
most models. Claude Haiku 5.5 charges more for a request whose prompt (all three input counts) is
over 100,000 tokens; its longContext entry in the price table holds those rates, and costOf()
uses them for the whole request. A turn can make several requests, and a fallback model may
answer one of them (lab 01), so the usage keeps a requests list and each request is priced at
the model that served it (costOfTurn()).
The persona file is your CLAUDE.md
config/persona.md and config/rules.md do for Steward what a project's CLAUDE.md does for
Claude Code: standing instructions loaded into every request. The same advice applies to both:
keep them short, concrete, and stable (prompting best practices).
Build
src/context/system-prompt.ts- three text blocks: identity, persona, rules. No dates, no ids, nothing that changes between turns.src/context/turn-context.ts-turnContextBlock()anduserContent().src/app.ts- the tool list is built once, in a fixed order, and the per-turn context is wired into the assistant.src/core/anthropic-model.ts-buildRequestParams()setscache_control: { type: 'ephemeral' }at the top level: the API caches the longest stable prefix automatically.src/context/usage.ts-costOf(),totalCost(), andcacheHitRate().src/core/turn-loop.ts-addUsage()also recordscontextTokens: the size of the latest request, which is how full the context window is.
Run
pnpm steward chatHave a short conversation (four or five messages), then type /usage. The output looks like
this (illustrative numbers):
model calls 6, input 1840, output 912, cache read 41210, cache write 6230
cache hit rate 84% of input tokens
cost $0.06
context 8920 tokens in the last request (compaction at 150000)
spent today $0.06 of $5.00 daily limitCheck the math with the Opus 5.5 prices above, in dollars:
(1,840 x 4 + 912 x 20 + 41,210 x 0.20 + 6,230 x 5) / 1,000,000 = about 0.065 (shown rounded to
$0.06). The hit rate is
41,210 / (1,840 + 41,210 + 6,230) = 84%. The last line is the daily spending cap from lab 12.
Your numbers will differ. The cache hit rate should climb with every turn. pnpm steward usage
prints the same report for every session (without the daily line).
Break it
Put the time in the system prompt. In src/context/system-prompt.ts, add it to the identity
line:
const identity = `Your name is ${config.assistant.name}. Now: ${new Date().toISOString()}.`;Run pnpm lab 03: the test "puts the time in the user message, never in the system prompt"
fails. Steward builds the system prompt once when the process starts (createApp in
src/app.ts), so in one chat the cost is small: the cache misses once after every restart.
Now make it miss on every request, the way an app does when it rebuilds its prompt per call.
In runTurnFor() in src/core/assistant.ts, add one line to the runTurn({...}) input:
system: [...this.deps.system, { type: 'text', text: `Now: ${new Date().toISOString()}` }],Chat for a few turns and check /usage: cache reads drop and cache writes jump, because the
system prompt of every request is new. Undo both changes.
Check
pnpm lab 03The checkpoint proves: across turns, system and tools are identical and each request's
messages start with all messages of the request before; the time is in the user message and not
in the system prompt; tools go out in a fixed order with caching on; cost and cache-hit math is
right; and the context size of the latest request is recorded.
Exercises
- Add a daily cost line to the banner of
steward chat(hint:totalCost()over the turns whosetsis today). - Add the learner's exam date from config to the turn context only when it is within 14 days. Why is that safe for the cache, while the same line in the system prompt would not be?
Claude API docs
- Prompt caching - automatic caching, what invalidates a prefix, and the usage fields.
- Pricing - input, cache write, cache read, and output prices per model.
- Context windows - what
contextTokensmeasures against. - Prompting best practices - writing a persona and rules that stay stable.
- Effective context engineering - choosing what goes into each request.
Exam connection
CCA-F - Context Management & Reliability (prompt caching, what invalidates it, context budgets) and Prompt Engineering & Structured Output (system prompt design). Practice both on CertLabPro. Related: caching and cost tracking are part of Operational Efficiency and Optimization on the AWS Certified Generative AI Developer - Professional (AIP-C01) exam.
Previous: Lab 02 - Next: Lab 04 - Tools