Hands-on exercises (repo package)¶
Complete these alongside the matching core module. Numbered src.* exercises hit the teaching package; the others are the module labs (no extra library required). Grow the production path in capstone-starter/ (own requirements.txt, mock model, no Poetry) — especially EX-13 and the five gates.
EX-01 — Templates (src.prompts)¶
-
Render
email_replywith a real email snippet. -
Add a new template
bug_triageinsrc/prompts.py+ a unit test. -
Log three outputs at different temperatures (API optional).
Check: pytest tests/test_prompts.py -v
EX-02 — Security (src.security)¶
-
Run
sanitize_user_texton three injection strings; all should flag. -
Redact a paragraph containing email + phone.
-
Wire
prepare_user_messagebefore any mock “LLM call” function.
Check: pytest tests/test_security.py -v
EX-03 — Structured extract (Module 03 lab)¶
No extra package code — use the Module 03 lab:
-
Pydantic model for an invoice (or your domain).
-
Two few-shot edge cases.
-
parse_success_rateon ≥20 raw strings (model or hand-crafted). -
Justify CoT yes/no in one paragraph.
Check: pytest tests/test_prompts.py -v plus your parser tests.
EX-04 — Golden evals (src.evals)¶
-
Open
tests/fixtures/invoice_golden.jsonl. -
Write a
predict(text) -> dictheuristic (regex is fine). -
Use
run_suiteand print accuracy; improve until ≥ 0.66 on the fixture.
Check: pytest tests/test_evals.py -v
EX-05 — Memory budget (src.context_memory)¶
-
Fill
SessionMemorywith 15 turns; setmax_recent=5. -
Assert
build_messageslength stays bounded. -
Use
fit_budgetto drop low-priority history under a tight budget.
Check: pytest tests/test_context_memory.py -v
EX-06 — Fine-tune or not (Module 06 lab)¶
-
One-page decision memo: why FT vs RAG/tools.
-
30 train + 10 held-out instruction rows, no PII.
-
Baseline score on the 10 (API or local). GPU LoRA is optional.
EX-07 — Tiny RAG (src.rag)¶
-
Chunk two short notes (company handbook style).
-
Ask an answerable and unanswerable query.
-
Validate citations with
validate_citations.
Check: pytest tests/test_rag.py -v
EX-08 — MCP policy (Module 08 lab)¶
-
Read modelcontextprotocol.io.
-
In dev only, list tools from a reviewed filesystem/git server.
-
Write
mcp-policy.md: allowed servers per env, approval-required tools, pin/update process. - Run
pytest tests/test_mcp_prod.py -vand extend one case (e.g. extra write tool blocked in CI).
EX-09 — Hybrid retrieval (Module 09 lab)¶
-
20 questions with
must_haveids (include keyword/ID and multi-hop). -
Dense-only vs
rrfhybrid Hit@5 and MRR. -
Log intermediate queries for 5 multi-hop items.
Check: pytest tests/test_rag.py -v
EX-10 — Cost controls (src.cost)¶
-
Route
classifyvscomplex_reasonwithModelRouter. -
Cache one payload; assert second
gethits. -
Enforce a $1.00 user budget with
UsageLedger.
Check: pytest tests/test_cost.py -v
EX-11 — Agent loop (src.agents)¶
-
Implement tools
add(a,b)andecho(text). -
Script an LLM stub that calls
addthenfinal. -
Confirm repeated identical tool calls abort.
Check: pytest tests/test_agents.py -v
EX-12 — Multi-agent vs single (Module 12 lab)¶
-
Researcher → writer → critic with max 2 critique rounds.
-
Structured payloads; reject invalid JSON.
-
On 10 tasks, compare success and cost to a single
src.agents.Agent.
EX-13 — Production endpoint (Module 13 lab)¶
-
FastAPI
/healthz+/v1/generatewithrequest_id. -
Timeout + fallback (stubs OK).
-
Dockerfile; 5-case PR eval subset.
EX-14 — Audit log (src.audit)¶
-
Record three tool events with hashed inputs.
-
Write JSONL to a temp path via
AuditLog. -
Ensure raw secrets never appear in the log file.
Check: pytest tests/test_audit.py -v
EX-15 — Vertical refuse path (Module 15 lab)¶
-
One-page policy: allowed / refused / escalate.
-
10-case eval with ≥3 must-refuse.
-
policy_check+ audit event on refuse.
EX-16 — Jobs or hybrid route (Module 16 lab)¶
-
POST /jobs→ worker (in-memory queue is fine). -
Server-side
data_classrouting to two stub endpoints. -
request_idin API log and worker log.
EX-17 — Local SLM vs mini (Module 17 lab)¶
- Run a 3B–8B-class local model on 20 golden tasks.
- Score vs a cloud mini model.
- Escalate on schema fail; record which tasks the SLM owns.
- Print
recommend_local_setup(HardwareBudget(ram_gb=...))for your machine; the model in step 1 should fit that row (no swap).
Check: pytest tests/test_local_agents.py -v
EX-18 — Leaf patterns (Module 18 lab)¶
Apply three of: Subroutine (validated output), Tool Gate (split messages), Rejection Sampler (max_trials), Consensus (n=5 + entropy), Adaptive Retriever. Name the failure each one fixes.
EX-19 — Orchestration shape (Module 19 lab)¶
Apply three of: Map-Reduce, Router, Planner, ReAct, Memory, Duet to one workflow. See the Module 19 lab for the combo rule.
EX-20 — Failure detectors (src.reliability)¶
- Build a two-step trajectory with identical
searchargs; assertrunaway_loop. - Propose a tool not in
known_tools; asserttool_hallucination. - Trip
CircuitBreaker(fail_max=2)and assertallowis false until cooldown.
Check: pytest tests/test_reliability.py -v
EX-21 — Sandbox (src.sandbox)¶
- Register a read tool and a write tool with
requires_approval=True. - Deny without grant; deny without human; allow after approval.
WorktreeExecutor: edit a copy; assert the source file is unchanged.
Check: pytest tests/test_sandbox.py -v
EX-22 — Trajectory evals (src.agent_evals)¶
- Score a clean success vs a looping success; composite must drop on the loop.
dashboardon both; notebudget_violations.regression_deltawith a worsened candidate; assertok is False.
Check: pytest tests/test_agent_evals.py -v
EX-23 — Prompt drift (src.drift)¶
- Pin a
PromptConfig; change onlytools; assertkind == "changed". - Drop the id from live; assert
missing. eval_regressionwithparse_rate0.92 → 0.70; gate fails.
Check: pytest tests/test_drift.py -v
EX-24 — Local-first (src.local_agents)¶
TokenBudget(10)refusesallow(11).- Router:
classify→ local;plan+ schema fail → strong. run_local_firstwith a tiny budget; abort reason mentions budget.
Check: pytest tests/test_local_agents.py -v
EX-25 — Durable graph (src.durable)¶
- Child evidence raises parent score on
HypothesisTree. DurableStoreround-tripsphase_donefrom JSONL.- Coordinator pauses on
ask_human; denial must not run the next phase;MergeGateblocks failed tests.
Check: pytest tests/test_durable.py -v
EX-26 — Orchestrator pick (src.orchestrators)¶
- Compare custom / LangGraph / CrewAI / MCP hosts; write when you’d pick each.
- Two
CostEvents; writer USD > researcher. TraceRecorderexport includesagenton every span.
Check: pytest tests/test_orchestrators.py -v
EX-27 — Harness (src.harness)¶
verifier_required=Truewith noverifycallable →stopped == "no_verifier".- Propose
tool="bash"against a spec that only listswrite_note; notes includedenied:. - First artifact
"draft", second"REFUND …"; report isverifiedin two steps, not atstep_cap. - Two context windows: persist
progress.jsonafter a failed draft;load_progressin session 2 and verify.
Check: pytest tests/test_harness.py -v
Track stretch¶
| Track | Stretch exercise |
|---|---|
| Stock | Replace TinyRAG bag-of-words with real embeddings; keep citation tests |
| Hybrid | Export a tiny MLP from PyTorch; serve predict via FastAPI sketch |
| Agentic plugin | Run Agent over read_file / list_files tools on this repo (read-only); add worktree + merge gate + trajectory eval |