Module 04: Projects
Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.
Four projects: one starter and three stretches (the long-conversation manager is optional). The core loops run keylessly on the deterministic fakes and harnesses the lessons build — promptlab.py, FakeTriager, ContractModel-style signal stubs, ContextBuilder with a fake model, ConversationManager with a stub summarizer. A fake "model" in this module is a small Python function that reads the rendered prompt for instruction signals and answers accordingly: it proves your measurement loop works, and it responds to prompt content, so before/after comparisons are meaningful inside the simulation. What it cannot do is predict GPT, Claude or Gemini — for that you need a real model call, either with provider keys in .env or the free local stand-in from lesson 03.1, Part 12. Each project says where the keyless line ends and the real-model stretch begins.
The projects reuse code printed in full in the lessons, so do them after the lessons they cite. First time with uv? See lesson 03.1, Part 4. The starter project needs only the standard library; the A/B harness needs jinja2, pydantic, pyyaml and pytest (the promptlib packages from 04.10, whose Setup gives the versions the samples were checked against).
Starter: Prompt makeover#
Goal: Take five deliberately weak prompts spanning five task types, rewrite each using the module's anatomy, structure and system-prompt techniques, and prove each change helped — or didn't — on a small labelled set, with a changelog entry per prompt.
What you'll practise:
- Auditing a prompt against the seven building blocks and the one-page checklist (lesson 04.1, 2.8) and rewriting it in six steps (04.1, 7.2)
- Choosing zero-shot versus few-shot and formatting examples (lesson 04.2, Parts 1–3)
- Deciding whether reasoning prompts earn their tokens for the task (lesson 04.3, Part 6)
- Separating instructions from data with tags and delimiters (lesson 04.4, Part 4) and ordering long context question-last (04.4, Part 5)
- Writing a minimal system prompt where the task is a standing assistant (lesson 04.5, Parts 1–2)
- Measuring honestly: dev set, scorer, one change at a time, changelog, hold-out check (lesson 04.9, Parts 1.2–1.3, 1.5, 1.6)
- Using
promptlab.py'srun,compare,Changelogandmarkdown_table(04.9, 1.4)
Setup:
uv init prompt-makeover --bare --python 3.13 && cd prompt-makeoverNothing to install — promptlab.py is pure standard library. Copy promptlab.py, fake_model.py and s1_dev_loop.py from lesson 04.9 into the project folder (each is printed in full there). No .env file is needed.
Steps:
-
Create
tasks.pywith five tasks. Each task is a dict with:name,weak_prompt(the prompt as it arrived — deliberately bad),cases(a list ofpromptlab.Caseobjects withid,input,expected,tags),scorer(aCase, output -> floatfunction),signals(the strings a competent prompt must contain for the fake to produce the contract output) andanswer/fallbackfunctions for its fake model. The five tasks and their starter data:triage— support-ticket triage, output contractCATEGORY | URGENCYwith categoriesbilling|technical|account|shipping|otherand urgencieslow|normal|high|urgent. Weak prompt:"You are a helpful assistant. Read this ticket and tell me what kind of problem it is and how urgent it seems. Ticket: {input}". Reuse the 12-caseDEV_SETandtriage_scorerfroms1_dev_loop.py— they are already labelled and tagged. Signals: the category list and the literal|separator format; fake:FakeTriagerfromfake_model.py.invoice_extract— extract{"invoice_number", "total", "currency", "due_date"}as JSON from short invoice texts. Weak prompt:"Get the details from this invoice: {input}". Provide 5 inline cases (invent realistic invoices: one clean, one with VAT and no due date, one in euros with a comma decimal, one that is not an invoice — expectednullhandling per the improved prompt's rule, one with a thousands separator). Signals: the JSON field names and"Reply with ONLY a JSON object"; fake returns the case's expected JSON when all signals are present, else prose like"I found an invoice for ...".meeting_summary— summarise meeting notes as exactly 3 bullets: decisions, action items with owners, open questions; no invented facts. Weak prompt:"Summarise this meeting: {input}". Provide 4 inline cases (a standup transcript, a planning meeting with two decisions, a 1:1 with only action items, notes that are already bullet points). Signals: "3 bullets" (or equivalent explicit count) and the section requirements; fake emits three labelled bullets when signalled, else a paragraph.tone_rewrite— rewrite a formal message into a friendly tone, preserve every fact, stay under 60 words. Weak prompt:"Make this friendlier: {input}". Provide 5 inline cases (a refund decline, a shipping delay apology, a feature-request reply, an invoice reminder, a praise reply). Signals: the word limit and the fact-preservation rule; fake returns a compliant rewrite when signalled (lower-case opener, under the cap, keeps the key nouns), else echoes the input unchanged.grounded_qa— answer a question using only the provided document; cite[DOC-1]; if the document doesn't contain the answer, reply exactlyNOT IN DOCUMENT. Weak prompt:"Here is a document and a question. Document: {input}"— note it never separates document from question or states the abstention rule. Provide 5 inline cases: eachinputis<document>...</document>\nQuestion: ...with two answerable and three unanswerable questions over a small invented policy doc (refund windows, shipping times, plan names). Signals: the citation format and the abstention string; fake answers with the expected sentence plus[DOC-1]when signalled and the expected keywords appear in the input (theablation.pytrick from 04.6), elseNOT IN DOCUMENTor an ungrounded guess.
For tasks 2–5 write the fake as a small class following
FakeTriager's pattern: it inspects the rendered prompt (plussystem) for the signal strings; when all are present it returns the case's correct output, otherwise a plausible-but-wrong one. Keep each fake under ~30 lines. The point is not cleverness — it is that the fake can only satisfy the contract when the prompt states it, so your improved prompt's score reflects the contract being explicit. -
Baseline every task. For each task, run
run(cases, weak_prompt, fake, scorer, name="weak", model="fake")and print the result withmarkdown_table([result]). Expect low scores — that is the point. Record each in aChangelog("changelog.jsonl"). -
Rewrite prompt 1 (triage) properly. Apply the six-step rewrite from 04.1, 7.2: one goal, context with the label definitions and policy facts,
<ticket>-fenced input, explicit edge-case rules (empty ticket, multi-intent), exact output format, success criteria. This is the worked example — the lesson'sPROMPT_V4-style prompt is your reference. Runcompare(weak_run, new_run); keep it only if it improves without regressing, and record the changelog entry. -
Rewrite prompts 2–5 one at a time. For each, decide deliberately: does this task need examples (few-shot per 04.2)? Does it need reasoning shown (04.3, Part 6)? What markup separates instructions from data (04.4)? Does it need a system prompt (04.5)? Change one thing at a time, re-run
compare, and write a changelog entry per kept change with the score before and after. If a change regresses, revert it — the changelog records the attempt too. -
Hold-out check. For each task, hold back 2 cases you never iterated on (or write 2 new ones at the end), run the final prompt on them, and report the score separately. A prompt that aces the dev set and fails the hold-out has memorised, not generalised (04.9, 1.6).
-
Write
MAKEOVER.md. For each of the five prompts: the weak version, the final version, a table of every change and which lesson section justifies it, the dev-set score before and after, the hold-out score, and one paragraph on what the fake could and could not tell you.
Verify it, and what you should see:
uv run python makeover.py # or however you wired the five tasksExpected shape of the output (scores are illustrative — they depend on your fake's signals and cases, but weak prompts should score far below improved ones):
tasks: 5
triage weak 0.58 -> final 1.00 (dev) hold-out 1.00
invoice_extract weak 0.20 -> final 0.90 (dev) hold-out 0.75
meeting_summary weak 0.30 -> final 0.95 (dev) hold-out 1.00
tone_rewrite weak 0.40 -> final 0.85 (dev) hold-out 0.80
grounded_qa weak 0.35 -> final 0.90 (dev) hold-out 0.75And changelog.jsonl has one JSON line per kept change with score_before, score_after, prompt_hash and your change/notes text. compare() returns a Comparison with a McNemar p-value; print it with print_comparison from s1_dev_loop.py — expect several "noise" verdicts on small sets, which is honest, not a bug.
Done when:
- All five weak prompts have a rewritten version, a dev-set before/after score and a changelog entry per kept change.
- Every rewrite demonstrably uses at least three of: the seven-block anatomy, explicit output contract, instruction/data separation, edge-case rules, examples, or a system prompt — and
MAKEOVER.mdlinks each choice to the lesson section that justifies it. - Each task has a hold-out result reported separately from the dev score.
MAKEOVER.mdstates plainly what the fakes measured (contract explicitness) and what they could not (real model behaviour), and names the one thing you'd test on a real model first.
Stretch ideas: Swap one fake for a real provider call — openai_model/anthropic_model/gemini_model/openrouter_model factories are in 04.9, 1.8; needs keys or the local stand-in. Add a sixth task that is a poor fit for prompting (ambiguous subjective judgement) and document why the loop can't fix it (04.9, 2.3). Port your best prompt to a second "model" by writing a second fake with different habits and re-running the migration checklist (04.9, 4.3).
Common problems:
- The fake ignores your prompt. Check that your
signalslist matches what your improved prompt actually says — the fake is literal; if it can't find the contract strings, it falls back. This is the simulation working as designed, not a bug. - Scores don't move. Your scorer may be too lenient (everything passes) or the weak prompt accidentally satisfies the signals. Tighten the scorer or the signals and re-run — and check
failing_cases()to see which cases fail and why. - McNemar says "noise" on a big-looking improvement. Small dev sets can't prove small effects (04.9, 1.7). Keep the change if the mechanism is sound, say so honestly in
MAKEOVER.md, and grow the set before shipping. - You changed five things at once. That's the anti-pattern the whole lesson warns about. Revert to one-change-at-a-time; the changelog exists precisely so you can attribute results.
Stretch: Prompt A/B harness#
Goal: Build a versioned prompt library (the promptlib package from lesson 04.10) plus a script that A/B tests prompt variants on a labelled dataset — with repeats for variance, a paired statistical comparison, deterministic online bucketing, and a regression gate that can fail CI.
What you'll practise:
- The
promptlibcontract end to end:PromptSpecfront matter, the loader,PromptRegistry.renderwith alias/version resolution,RenderedPrompthashes,PromptRecorderanddiff_versions(lesson 04.10, Part 5, 5.2, 5.4, 5.5, 5.7) - Prompt-plus-model as one unit, aliases and rollback (04.10, 4.2–4.4)
- Offline A/B on a dev set and deterministic sticky bucketing for online assignment (04.10, 8.1–8.2)
- Honest comparison statistics: repeats, per-case means, Wilson intervals, McNemar's paired test (lesson 04.9, 1.4, 1.7)
- Regression gates: score threshold plus zero-tolerance on critical-tagged cases, snapshot diffs (04.9, Part 3)
- Sample-size warnings and the hold-out rule (04.10, 8.4)
Setup:
uv init prompt-ab --bare --python 3.13 && cd prompt-ab
uv add jinja2 pydantic pyyaml pytest
# or: pip install jinja2 pydantic pyyaml pytestCopy the whole promptlib package and the prompts/ tree verbatim from the 04.10 appendix (promptlib/__init__.py, spec.py, loader.py, registry.py, recorder.py, diffutil.py, prompts/aliases.yaml, the four *.md prompt files, tests/test_promptlib.py, pytest.ini). Then python -m pytest tests/ -q — expect 15 passed. The library ships support.ticket-triage v1.0.0 and v1.1.0 already; that's your A/B pair.
Steps:
-
Prove the library works. Run the appendix demo (
PYTHONPATH=. python -m examples.triage_demoif you copied it, or write a five-line script):registry = PromptRegistry("prompts").load(), thenregistry.render("support.ticket-triage", ticket_text="My invoice is wrong", plan_tier="pro"). Confirmresolved_from == "alias:production"and inspectcontent_hash/variables_hash. Rundiff_versions(registry, "support.ticket-triage", "1.0.0", "1.1.0")and read the diff — v1.1.0 addschurn_risk. -
Build the dataset. Create
dataset.pywith 12–20 labelled tickets forsupport.ticket-triageaspromptlab.Caseobjects (id,input= ticket text,expected= the expected JSON fields as a string,tagslikeedge,billing,critical). Reuse the triage tickets from 04.1'striage_data.pyand 04.9'sDEV_SETas raw material, adapting labels to the library prompt's contract (category,priority,needs_human,summary, pluschurn_riskfor v1.1.0). Tag 2–3 casescritical. Keep aholdoutlist of 3 cases you never tune against. -
Write the scorer.
triage_score(case, output) -> floatin [0, 1]: parse the JSON (reuseparse_outputfrom 04.1'striage_loop.py), then score per expected field — 0.2 per correct field amongcategory,priority,needs_human,churn_risk, plus 0.2 for valid JSON and a summary under 25 words. Return 0.0 on unparseable output. Write it so a partial contract scores partially — that's what makes A/B differences visible. -
Write
ab_test.py(offline arm). For each variant (version="1.0.0"andversion="1.1.0"): render every dataset case viaregistry.render, run the model callablerepeats=3times per case, score withtriage_score. Copypromptlab.pyfrom 04.9 into the project and feed it(system, rendered.text, case)triples — or write a 40-line equivalent if you prefer the library'sRenderedPromptshape throughout. The model is a fake for the keyless run: adaptFakeTriagerso it reads signals from the rendered prompt (v1.1.0's extrachurn_riskfield and rules are signals too — the fake should only emitchurn_riskwhen the prompt asks for it). Report per-variant: overall mean, pass rate with Wilson interval, per-tag slices, andcompare(variant_a, variant_b)for the paired McNemar result. Print a verdict:winner,tie/noise, orregression. -
Add the online arm. Implement
assign_variant(unit_id, ["control", "control", "treatment"], salt)exactly as in 04.10, 8.2, then a functionserve(unit_id, ticket_text)that renders the assigned variant, calls the model, and returns(variant, RenderedPrompt, output). Log every call throughPromptRecorder("logs/ab_calls.jsonl").record(rendered, variant=..., unit_id=...). Verify stickiness: the sameunit_idmust always get the same variant across 100 simulated calls, and the split over 10,000 synthetic IDs should be near the configured ratio. -
Add the regression gate.
gate.py(or a--gateflag): after the offline comparison, fail (exit 1) if the candidate variant's overall score is more than 0.02 below control or anycritical-tagged case regresses vs control — the same two-gate shape as 04.9, 3.3. Snapshot both variants' per-case outputs withsave_snapshotand showdiff_snapshotsso a reviewer sees which answers changed, not just the score. -
Run the hold-out. Score the winning variant on the 3 hold-out cases once, at the end, and report it separately. If the winner was chosen on dev and loses on hold-out, say so — that is the honest A/B outcome, and 04.10, 8.4 explains why small samples lie.
-
Write
AB.md. Document: the two variants and their diff, the dataset and scorer, N repeats used, the comparison table, the McNemar verdict, the bucketing proof, the gate behaviour (including a deliberate gate failure you triggered by flipping an alias), and what you'd measure differently with real traffic.
Verify it, and what you should see:
python -m pytest tests/ -q # 15 passed (the library's own suite)
python ab_test.py # offline comparison + gate
python -c "from ab_test import assign_variant; print({assign_variant(f'u{i}', ['control','control','treatment']) for i in range(1000)})"Expected shape (illustrative — your fake's signals decide the scores):
variant 1.0.0 overall 0.72 pass 58% (CI 41–74%) critical: 2/3
variant 1.1.0 overall 0.88 pass 75% (CI 56–88%) critical: 3/3
compare: mean +0.16 | improved ['c04','c07','c11'] | regressed [] | McNemar p=0.25 (noise on this set size)
verdict: candidate ahead but NOT significant — grow the dataset or repeats before shipping
gate: PASS (no critical regressions; delta within tolerance)The McNemar "noise" verdict on a small set is the lesson, not a failure: 04.9, 1.7 shows you need ~6 discordant cases all favouring one side for p < 0.05. Your AB.md should say exactly that.
Done when:
promptlibloads the shipped prompts,pytestpasses, anddiff_versionsproduces a readable diff between 1.0.0 and 1.1.0.ab_test.pycompares both variants over the dataset withrepeats ≥ 3, prints means, Wilson intervals, per-tag slices and a McNemar verdict, and states plainly whether the result is significant.assign_variantis demonstrably sticky and near the configured split; calls are logged viaPromptRecorderwithvariantandunit_id.- The regression gate exits non-zero when you deliberately regress a critical case, and zero on the shipped pair.
AB.mdincludes the hold-out result and an honest statement of what the fake could and could not measure.
Stretch ideas: Add a third variant (ticket-triage.v3.md with version: 1.2.0 in its front matter) that you author — bump aliases.yaml staging to it and re-run the whole pipeline. Swap the fake for a real provider: render via registry.render, map RenderedPrompt to each provider's request shape (04.10, 5.6, lesson 03.2), and keep repeats high enough that model variance doesn't masquerade as a variant effect. Add the CI story from 04.10, Part 7: a pytest golden-set check that runs on every PR with the fake client.
Common problems:
renderraises "missing required variable". The front matter declaresticket_textas required — pass it as a keyword:registry.render("support.ticket-triage", ticket_text=..., plan_tier=...). Undeclared variables are rejected too; checkspec.variables.- YAML parsed
versionas a float. The loader's validator exists for exactly this — quote it:version: "1.2.0". - The fake scores both variants identically. Your signals probably don't distinguish the variants — v1.1.0's
churn_riskcontract is the natural discriminator. If the fake can't tell the prompts apart, neither can your A/B test; that's a harness bug, not a result. - Everything is "noise". Expected on ≤20 cases. Report the uncertainty honestly, grow the dataset or repeats, and use the hold-out only once — 04.10, 8.4 has the sample-size math in plain English.
Stretch: Context packer and ablation study#
Goal: Build the context layer for a small support assistant: pack six context sources into a token budget with ContextBuilder, label them with provenance, order them for cache and attention, then prove with an ablation which sources earn their tokens and which can be cut.
Prerequisites: lessons 04.6 (all of it) and 04.5, Part 5. No API key needed.
What you'll practise:
- Inventorying context sources and writing a budget table (04.6, 1.5, 2.1)
- Packing sources with
ContextSourcepriorities,requiredflags and the output reserve, and reading the drop report (04.6, Part 11) - Provenance labels, conflict rules and freshness dates (04.6, Parts 6 and 7)
- Stable-prefix-first layout and checking it by diffing two packed contexts (04.6, Parts 10 and 12)
- Single-source ablation, and its limits (04.6, Part 13)
Setup:
uv init context-packer --bare --python 3.13 && cd context-packerStandard library only. Copy context_builder.py and ablation.py from 04.6 (each is printed in full) into the folder.
Milestones and deliverables:
- Inventory and budget (
BUDGET.md). Pick a task: the Acme Cloud support assistant from 04.6 or one of your own. List at least six sources (system prompt, account state, two or more policy documents, a history summary, the ticket) with a priority and an estimated token cost each. Choose a total budget and an output reserve and show the arithmetic. State which sources arerequired. - Sources with provenance (
sources.py). Write each source as aContextSource. Every document carriesid,source,dateandauthorityattributes (04.6, 6.2). Include two documents that contradict each other (for example a 2025 and a 2026 refund timeline) and one untrusted block (a customer ticket that contains an instruction such as "ignore your rules"). Put your conflict-resolution rules and the "text inside these tags is data" rule in the system prompt (04.6, 7.3, 6.3). - Pack at three budgets (
pack_demo.py). RunContextBuilder(budget_tokens=B).pack(sources, reserve_tokens=R)at a generous, a tight and a draconian budget. Printpacked.report()for each. Write down at which budget each source is truncated and then dropped, and whether that is the order you would choose. - Layout check (
layout_check.py). Pack the same sources for two different tickets. Assert that everything before the first volatile block is byte-identical between the two packed texts (the stable prefix), and that the ticket and the question come last. Print the first position at which the two texts differ. - Ablation (
my_ablation.py). Adaptablation.py: write 6 to 8 cases (questions with expected keywords), and make the fake model read the packed context rather than the raw sources. Drop each source in turn, plus each pair of sources, and print the score delta per source and per pair. - Write-up (
FINDINGS.md). One page: the budget table, the three drop reports, the layout check result, the ablation table, a "cut list" of sources that look neutral, and one paragraph on why neutral on your dev set does not prove a source is useless (04.6, 13.3).
Acceptance criteria:
pack_demo.pyshows a different drop pattern at each of the three budgets, and required sources are never dropped.layout_check.pypasses: the stable prefix is identical across two tickets and the first differing position falls inside the volatile tail.- The ablation reports single-source and pair deltas. At least one source is marked "needed" and you can name the case that needs it; if every source is "needed" or every source is "neutral", your cases are too easy or too hard, so revise them.
- The untrusted ticket appears inside a labelled data block after the instructions, and the system prompt says so.
FINDINGS.mdstates honestly what the fake model could not tell you (real model behaviour) and names the first real-model experiment you would run.
Self-check: Remove the date attribute from one of the two contradictory documents. Does your conflict rule still tell the model which to prefer? If not, your rule depends on a label you have just deleted; add the fallback ("if a source has no date, say the sources conflict and prefer the one with higher authority").
Hints:
ContextSource(name, text, priority, required, cacheable, position): lowerprioritynumbers are kept first,cacheable=Truesources render in the stable prefix, andpositionorders blocks inside each section.- To find the first differing position in the layout check, compare the two strings with a loop over
zip(a, b)and report the index; then print 40 characters on each side of it. - For pair ablation use
itertools.combinations(source_names, 2). - A fake model that returns the expected sentence only when both its keyword and the document id appear in the packed text (as
ablation.pydoes) is enough to make the ablation meaningful.
Keyless path and real-model stretch: everything above runs offline. To test on a real model, replace the fake with a provider call such as the sketch at the bottom of ablation.py, run each ablation arm at least five times, and report the spread, not a single score.
Common problems:
- Nothing is ever dropped. Your budget is too large for your sources; shrink it until the drop report shows at least one
x. - Every source looks neutral. The fake model may be answering from a keyword that appears in several sources; make the expected fact appear in exactly one source per case.
- The layout check fails on the first line. A volatile value (a timestamp or user id) has leaked into the system prompt; move it into a trailing volatile source (04.6, 10.1).
Stretch (optional): Long-conversation manager#
Goal: Extend lesson 04.7's ConversationManager from a stub-summarized demo into something you could defend in review: a real summarization strategy, a fact- and constraint-retention test suite, tool-result lifecycle handling, and a report of what the manager drops and why.
What you'll practise:
- The full
ConversationManagerAPI:add_user/add_assistant/add_tool_result/set_state,render()→(messages, RenderStats),input_budget,drop_log, pinned facts and importance carry-forward (lesson 04.7, 11.1–11A.2) - Writing summarization prompts that preserve goal, constraints, decisions, verbatim facts and open tasks (04.7, Part 3)
- Retention testing: plant a fact or constraint early, probe late, vary the management policy (04.7, 12.1–12.2)
- Provider compaction features versus rolling your own (04.7, Part 4) and tool-result lifecycle (04.7, Part 5)
- Graceful limit handling: pre-flight counting, compaction thresholds, the shedding order, telling the user (04.7, Part 10)
- Keeping instructions alive and caches warm (04.7, Parts 8–9)
Setup:
uv init context-manager --bare --python 3.13 && cd context-managerStandard library only for the core. Optionally uv add tiktoken for real token counts (the built-in chars_per_token estimator works fine). Copy conversation_manager.py, demo_manager.py and retention_test.py from 04.7 — each is printed in full.
Steps:
-
Run the demo and the retention harness.
python demo_manager.pyandpython retention_test.py; read the drop log and the four probe outcomes (A–D) until you can explain why run B loses the fact and runs C and D keep it. -
Replace the stub summarizer. Write
llm_summarizer(previous, turns)that renders the 04.7, 3.2 rolling-summary prompt over the victim turns. Keyless version: a smarter deterministic summarizer that extracts user questions, decisions (sentences containing "decided"/"approved"/"will"), verbatim facts matching aFACT_PATTERNSlist, and open tasks (sentences containing to-do markers or "?"), staying undersummary_allowance. Keyed version: call a provider with the same prompt — illustrative glue is in 04.7, 11.4. Runretention_test.pyagainst both and compare which facts survive. -
Build the retention suite. Extend
retention_test.pyintoretention_suite.py: a table of(fact_planted_at_turn, probed_at_turn, importance)cases — at least 6 covering early/middle/late planting, high/low importance, and one constraint probe ("never offer discounts over 10 percent" planted early, then tempting turns, then check the sent context still carries it — 04.7, 12.2). For each case run the manager at 2–3(context_window, compaction_ratio, protect_importance)settings and report a pass matrix: did the probe find the fact in the rendered messages? -
Add tool-result management. Give the demo a
kb_searchtool whose result is added viaadd_tool_result. After compaction fires, old tool results should be replaced by a stub[cleared: kb_search, N tokens — re-fetch if needed]while call/result pairing stays intact (04.7, 5.2–5.4). Verifygroup_turnsnever orphans a tool result from its call. -
Instrument the report. Add a
report()that prints: tokens used vs budget per turn, compactions fired, drops by reason (summarized,over_budget,orphaned_leading_turn), pinned-fact growth, and the stable-prefix versus volatile-tail split (04.7, 9.1). Identify the turn where your layout stops being cache-friendly and apply one fix (e.g. move the summary into the pinned block only when it changes). -
Decide server-side versus yours. Write a short
COMPACTION.mdcomparing your manager against the provider features in 04.7, Part 4 — OpenAIcontext_management/responses.compact, Anthropic compaction/context-editing/memory tool, Gemini and OpenRouter equivalents — noting what's GA versus beta as of November 2026 and which parts of your manager each feature replaces (and which it doesn't: pinning, importance, your drop log).
Verify it, and what you should see:
python demo_manager.py # same shape as the lesson's real output
python retention_suite.py # your pass matrixExpected shape (illustrative — depends on your summarizer and budgets):
retention suite: 6 fact probes x 3 policies
protect_importance=0.0 naive summary : 1/6 facts survive verbatim
protect_importance=0.8 carry-forward : 5/6
pinned_facts explicit : 6/6
constraint probe 'no discounts >10%': survives in pinned block, lost in summary-onlyDone when:
demo_manager.pyruns unchanged and you can explain every line of its drop log.retention_suite.pyproduces a pass matrix over at least 6 probes and 2 policies, including one constraint probe.- Tool results are stubbed after compaction without orphaning call/result pairs.
report()shows the per-turn budget breakdown and names the cache-unfriendly turn.COMPACTION.mdstates, per provider, which compaction feature exists as of November 2026, its maturity, and what your manager still has to do itself.
Stretch ideas: Wire render() output through the provider glue in 04.7, 11.4 against the local stand-in for a real end-to-end chat. Implement hierarchical summarization (summaries of summaries) for a 50+ turn conversation. Add a memory layer per 04.7, Part 6: a JSON notes file the manager reads at session start and writes back at session end, with a test that secrets/PII never land in it.
Common problems:
- The probe fails even with a huge window. Check
input_budget:context_window - max_output - safety_margin— a "huge" window with a largemax_outputmay still compact. The lesson's run A usescontext_window=100_000for a reason. - Compaction never fires.
_compactonly runs when projected tokens exceedcompaction_ratio * input_budget, and only if asummarizeris set. Check both, and checkkeep_recentisn't eating all your turns. - The summary itself busts the budget.
summary_allowancecaps it — but_summary_messagetruncates by characters, so keep the allowance conservative. - Tool results orphaned.
add_tool_resultmust follow itsadd_assistant(tool_calls=...)in the same turn —group_turnsbinds them; inserting a user message between call and result breaks the pairing.