Module 04: Projects

Understand LLMs4 projects0 of 4 complete

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

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:

Setup:

bash
uv init prompt-makeover --bare --python 3.13 && cd prompt-makeover

Nothing 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:

  1. Create tasks.py with five tasks. Each task is a dict with: name, weak_prompt (the prompt as it arrived — deliberately bad), cases (a list of promptlab.Case objects with id, input, expected, tags), scorer (a Case, output -> float function), signals (the strings a competent prompt must contain for the fake to produce the contract output) and answer/fallback functions for its fake model. The five tasks and their starter data:

    • triage — support-ticket triage, output contract CATEGORY | URGENCY with categories billing|technical|account|shipping|other and urgencies low|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-case DEV_SET and triage_scorer from s1_dev_loop.py — they are already labelled and tagged. Signals: the category list and the literal | separator format; fake: FakeTriager from fake_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 — expected null handling 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 exactly NOT 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: each input is <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 (the ablation.py trick from 04.6), else NOT IN DOCUMENT or an ungrounded guess.

    For tasks 2–5 write the fake as a small class following FakeTriager's pattern: it inspects the rendered prompt (plus system) 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.

  2. Baseline every task. For each task, run run(cases, weak_prompt, fake, scorer, name="weak", model="fake") and print the result with markdown_table([result]). Expect low scores — that is the point. Record each in a Changelog("changelog.jsonl").

  3. 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's PROMPT_V4-style prompt is your reference. Run compare(weak_run, new_run); keep it only if it improves without regressing, and record the changelog entry.

  4. 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.

  5. 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).

  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:

bash
uv run python makeover.py    # or however you wired the five tasks

Expected 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):

text
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.75

And 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.md links each choice to the lesson section that justifies it.
  • Each task has a hold-out result reported separately from the dev score.
  • MAKEOVER.md states 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 signals list 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

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 promptlib contract end to end: PromptSpec front matter, the loader, PromptRegistry.render with alias/version resolution, RenderedPrompt hashes, PromptRecorder and diff_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:

bash
uv init prompt-ab --bare --python 3.13 && cd prompt-ab
uv add jinja2 pydantic pyyaml pytest
# or: pip install jinja2 pydantic pyyaml pytest

Copy 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:

  1. Prove the library works. Run the appendix demo (PYTHONPATH=. python -m examples.triage_demo if you copied it, or write a five-line script): registry = PromptRegistry("prompts").load(), then registry.render("support.ticket-triage", ticket_text="My invoice is wrong", plan_tier="pro"). Confirm resolved_from == "alias:production" and inspect content_hash/variables_hash. Run diff_versions(registry, "support.ticket-triage", "1.0.0", "1.1.0") and read the diff — v1.1.0 adds churn_risk.

  2. Build the dataset. Create dataset.py with 12–20 labelled tickets for support.ticket-triage as promptlab.Case objects (id, input = ticket text, expected = the expected JSON fields as a string, tags like edge, billing, critical). Reuse the triage tickets from 04.1's triage_data.py and 04.9's DEV_SET as raw material, adapting labels to the library prompt's contract (category, priority, needs_human, summary, plus churn_risk for v1.1.0). Tag 2–3 cases critical. Keep a holdout list of 3 cases you never tune against.

  3. Write the scorer. triage_score(case, output) -> float in [0, 1]: parse the JSON (reuse parse_output from 04.1's triage_loop.py), then score per expected field — 0.2 per correct field among category, 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.

  4. Write ab_test.py (offline arm). For each variant (version="1.0.0" and version="1.1.0"): render every dataset case via registry.render, run the model callable repeats=3 times per case, score with triage_score. Copy promptlab.py from 04.9 into the project and feed it (system, rendered.text, case) triples — or write a 40-line equivalent if you prefer the library's RenderedPrompt shape throughout. The model is a fake for the keyless run: adapt FakeTriager so it reads signals from the rendered prompt (v1.1.0's extra churn_risk field and rules are signals too — the fake should only emit churn_risk when the prompt asks for it). Report per-variant: overall mean, pass rate with Wilson interval, per-tag slices, and compare(variant_a, variant_b) for the paired McNemar result. Print a verdict: winner, tie/noise, or regression.

  5. Add the online arm. Implement assign_variant(unit_id, ["control", "control", "treatment"], salt) exactly as in 04.10, 8.2, then a function serve(unit_id, ticket_text) that renders the assigned variant, calls the model, and returns (variant, RenderedPrompt, output). Log every call through PromptRecorder("logs/ab_calls.jsonl").record(rendered, variant=..., unit_id=...). Verify stickiness: the same unit_id must always get the same variant across 100 simulated calls, and the split over 10,000 synthetic IDs should be near the configured ratio.

  6. Add the regression gate. gate.py (or a --gate flag): after the offline comparison, fail (exit 1) if the candidate variant's overall score is more than 0.02 below control or any critical-tagged case regresses vs control — the same two-gate shape as 04.9, 3.3. Snapshot both variants' per-case outputs with save_snapshot and show diff_snapshots so a reviewer sees which answers changed, not just the score.

  7. 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.

  8. 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:

bash
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):

text
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:

  • promptlib loads the shipped prompts, pytest passes, and diff_versions produces a readable diff between 1.0.0 and 1.1.0.
  • ab_test.py compares both variants over the dataset with repeats ≥ 3, prints means, Wilson intervals, per-tag slices and a McNemar verdict, and states plainly whether the result is significant.
  • assign_variant is demonstrably sticky and near the configured split; calls are logged via PromptRecorder with variant and unit_id.
  • The regression gate exits non-zero when you deliberately regress a critical case, and zero on the shipped pair.
  • AB.md includes 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:

  • render raises "missing required variable". The front matter declares ticket_text as required — pass it as a keyword: registry.render("support.ticket-triage", ticket_text=..., plan_tier=...). Undeclared variables are rejected too; check spec.variables.
  • YAML parsed version as 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_risk contract 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

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 ContextSource priorities, required flags 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:

bash
uv init context-packer --bare --python 3.13 && cd context-packer

Standard library only. Copy context_builder.py and ablation.py from 04.6 (each is printed in full) into the folder.

Milestones and deliverables:

  1. 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 are required.
  2. Sources with provenance (sources.py). Write each source as a ContextSource. Every document carries id, source, date and authority attributes (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).
  3. Pack at three budgets (pack_demo.py). Run ContextBuilder(budget_tokens=B).pack(sources, reserve_tokens=R) at a generous, a tight and a draconian budget. Print packed.report() for each. Write down at which budget each source is truncated and then dropped, and whether that is the order you would choose.
  4. 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.
  5. Ablation (my_ablation.py). Adapt ablation.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.
  6. 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.py shows a different drop pattern at each of the three budgets, and required sources are never dropped.
  • layout_check.py passes: 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.md states 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): lower priority numbers are kept first, cacheable=True sources render in the stable prefix, and position orders 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.py does) 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)

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 ConversationManager API: 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:

bash
uv init context-manager --bare --python 3.13 && cd context-manager

Standard 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:

  1. Run the demo and the retention harness. python demo_manager.py and python 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.

  2. 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 a FACT_PATTERNS list, and open tasks (sentences containing to-do markers or "?"), staying under summary_allowance. Keyed version: call a provider with the same prompt — illustrative glue is in 04.7, 11.4. Run retention_test.py against both and compare which facts survive.

  3. Build the retention suite. Extend retention_test.py into retention_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?

  4. Add tool-result management. Give the demo a kb_search tool whose result is added via add_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). Verify group_turns never orphans a tool result from its call.

  5. 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).

  6. Decide server-side versus yours. Write a short COMPACTION.md comparing your manager against the provider features in 04.7, Part 4 — OpenAI context_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:

bash
python demo_manager.py          # same shape as the lesson's real output
python retention_suite.py       # your pass matrix

Expected shape (illustrative — depends on your summarizer and budgets):

text
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-only

Done when:

  • demo_manager.py runs unchanged and you can explain every line of its drop log.
  • retention_suite.py produces 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.md states, 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 large max_output may still compact. The lesson's run A uses context_window=100_000 for a reason.
  • Compaction never fires. _compact only runs when projected tokens exceed compaction_ratio * input_budget, and only if a summarizer is set. Check both, and check keep_recent isn't eating all your turns.
  • The summary itself busts the budget. summary_allowance caps it — but _summary_message truncates by characters, so keep the allowance conservative.
  • Tool results orphaned. add_tool_result must follow its add_assistant(tool_calls=...) in the same turn — group_turns binds them; inserting a user message between call and result breaks the pairing.
Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close