Module 08A: Projects

Agents & multimodal2 projects0 of 2 complete

Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.

Two projects: one starter (the research agent, 08A.P1) and one stretch (the multi-step workflow agent, 08A.P2). Everything runs keylessly. The agent loop, the tools, the scripted fake model, the memory store, the policy layer and the eval harness are all pure Python over in-memory fake data, so you can finish every "Done when" checklist without a single API key. Hosted providers (real web search, real model calls) are the stretch goal for each project once you have keys; the lessons show exactly where they plug in.

What the fakes can and cannot tell you. ScriptedModel replays canned replies, so your tests prove the plumbing (the loop, budgets, dispatch, approvals, memory writes, grading) deterministically. They cannot tell you how a real model will behave: which tool it picks, whether it invents an argument, how many steps it takes. Every "expected output" below is labelled illustrative; your scripted runs are deterministic, but a live model's trajectories will differ every time. That gap is exactly what the tool-use evals and agent evals in these projects are for.

First time? Do the shared setup once: uv init tools-agents --bare --python 3.13 && cd tools-agents, then uv add openai anthropic google-genai pydantic python-dotenv pytest. These are the provider SDKs from lesson 08A.2's Setup plus pytest for the test suites (the lessons picked different folder names; any works). Run scripts with uv run python file.py and tests with uv run pytest -q. No .env file is needed for anything below. The multi-agent project is in Module 08D, and the MCP server project is with Module 08E.

You will reuse lesson files rather than reinvent them. The names below are the real ones from the lessons. Copy each file into your project folder exactly as printed there:

  • From 08A.2: agent.py (the canonical loop: ChatAdapter, ModelTurn, ToolCall, ToolResult, Budget, AgentResult, run_agent, resume_agent, OpenAIResponsesAdapter), scripted.py (ScriptedModel), support_tools.py (ToolSpec, REGISTRY, run_tool), loop_detect.py, approval_gate.py
  • From 08A.6: support_data.py, support_tools.py (the other one: ToolRegistry, build_registry(), orders_get, docs_search, refunds_issue, and so on), test_support_tools.py, tool_eval.py (QueuedModel, EvalTask, run_eval)
  • From 08A.9: workflows.py (CallModel, ScriptedModel, Tracer, prompt_chain, route, parallel, vote, orchestrate, evaluator_optimizer, map_reduce, checkpoint, fallback_chain)
  • From 08A.10: agent_loop.py (ToolRegistry, Budget, ScriptedModel, run_agent, resume_agent, snapshot/restore), patterns.py (plan_and_execute, route_and_run, orchestrate, critique_and_revise, verify_and_retry), approval.py (PermissionPolicy, policy_gate), statemachine.py, trajectory.py (TrajectoryLogger), support_tools.py
  • From 08A.14: policy.py, tracer.py, passk.py, evalharness.py
  • From 08B.2 (the stretch project only): memory_store.py, extract_memories.py, memory_tools.py, test_memory.py

Note the deliberate name collisions the lessons warn about: 08A.2's support_tools.py/ToolSpec/REGISTRY and 08A.6's support_tools.py/ToolRegistry/build_registry() are different files with the same name, and 08A.9 and 08A.10 each ship their own slimmer ScriptedModel. Keep them in separate project folders (or rename on copy) so imports stay honest. Each lesson's "Going deeper" notes and the file headers say which loop owns which names.


Starter

Starter: Research agent#

Goal: Build a research agent that answers questions about a small fake "web" — it searches the corpus, fetches the pages it needs, takes notes, and submits a final answer with citations — on the canonical loop from lesson 08A.2, with the tool design discipline of 08A.6 and the budget/stop-condition rules that keep a loop from running away. Test the whole thing with ScriptedModel so it runs with no keys.

What you'll practise:

  • The canonical agent loop over an injectable adapter, with Budget limits and the submit_answer finish tool (lesson 08A.2, 1.2, 3.2, 3.3)
  • Writing tools as prompts: names, descriptions with when-not-to-use clauses, few typed bounded parameters (lesson 08A.6, 1.3–1.6)
  • High-signal results with URLs the model can cite, and actionable error results (lesson 08A.6, 3.1–3.4)
  • Loop detection and budget exhaustion as designed stop conditions, not surprises (lesson 08A.2, 3.4, 6.1)
  • Testing the loop deterministically with ScriptedModel and asserting on the trajectory (lesson 08A.2, 3.5–3.6)
  • Reading where provider built-in web search would slot in, and why you'd still write your own fetch tool for private corpora (lesson 08A.8, 4.8, 10.2)

Setup: the shared project from the intro paragraph. Copy agent.py, scripted.py and support_tools.py from 08A.2 unchanged — research_tools.py will import ToolSpec from support_tools, and run_agent accepts tools= so the support registry is never in scope. No .env, no keys.

Steps:

  1. Create the corpus. Make research_data.py with a CORPUS dict of six fake web pages about a fictional city bike-share called Meridian Cycles. Suggested pages (write ~80–120 words each, realistic and slightly inconsistent so search matters): https://meridian.example/start (how to unlock a bike), https://meridian.example/pricing (day pass £3, month pass £18, student discount 50%), https://meridian.example/app-troubleshooting ("bike won't unlock" → check the app's Bluetooth permission first; a different page says force-quit and reopen — the inconsistency is deliberate, the agent should surface it), https://meridian.example/safety (helmet law for under-16s, night riding lights), https://meridian.example/group-rides (free guided rides every Saturday), https://meridian.example/accessibility (step-through bikes at 12 hubs, wheelchair-accessible docks). Use the same {url: {"title": ..., "text": ...}} shape as 08D.3's fake corpus.
  2. Write research_tools.py. Four tools in the 08A.2 ToolSpec style (args_model, fn, risk="read", timeout_s), each a Pydantic arg model plus a plain function over CORPUS:
    • web_search(query: str, max_results: int = 5) — score pages by query-term overlap (copy the scoring approach from 08D.3's web_search, or 08A.6's KeywordRetriever), return [{url, title, snippet}] sorted by score, count, and a note when zero hits ("no pages matched; try broader terms").
    • web_fetch(url: str) — return the full {url, title, text} or an error result naming the problem ("no page at that URL; use an exact URL from web_search results").
    • save_note(title: str, content: str) — append to a NOTES list and return {saved: true, note_id}; risk "write" so you can demo the approval hook later.
    • submit_answer(answer: str) — the finish tool: return {"answer": answer, "submitted": true}. Write the descriptions per 08A.6, 1.4: what it does, when to use it, when not to, what it returns. In 08A.2's ToolSpec the model-facing description is the docstring of the argument model (" ".join(args_model.__doc__.split())), so write each Pydantic class's docstring as the description rather than a comment. Include the citation contract in submit_answer's description: "cite sources as title (url)".
  3. Write run_research.py. A main() that builds Budget(max_steps=10, max_seconds=120, max_calls_per_tool=4) and calls run_agent(adapter, question, tools=REGISTRY, budget=budget) where adapter is a ScriptedModel for the demo and an OpenAIResponsesAdapter (from agent.py) behind a --live flag for when you have a key. run_agent is a coroutine, so main() is async and the file ends with asyncio.run(main()). Print result.status, result.answer, result.steps, and result.spent. Write the script in ScriptedModel's format from 08A.2, 3.5 (("calls", [(name, args)]) turns, ending with a submit_answer call). Start with a script for the question "Do I need a helmet to ride a Meridian bike at night, and how much is a month pass?": web_search("helmet night riding") → web_fetch the safety page → web_search("month pass price") → web_fetch the pricing page → save_note → submit_answer with a cited answer.
  4. Test it. Write test_research.py in the style of 08A.2's test_agent.py: assert the run ends completed, the answer contains both facts, every cited URL exists in CORPUS, NOTES has one entry, and ScriptedModel.seen shows the tool results were appended as role="tool" messages. Add a second test where the script searches, gets zero hits, and must recover by re-searching with different terms — script the model to call web_search again after the error result.
  5. Break it on purpose. Script a model that calls web_fetch with a made-up URL three times. Confirm the loop stops with loop_detected (identical call signature) rather than burning all ten steps: Budget.loop_threshold defaults to 3, and the check runs before the third identical call executes, so the model sees two error results and the third call never runs. Check that those error results were actionable.
  6. Add the approval hook. Give save_note risk="write" and pass an approver to run_agent that prints the PendingApproval and returns "approve"/"deny"/"defer" (08A.2, 6.4). Show a defer run pausing with status == "awaiting_approval", then resume it with await resume_agent(res.state, adapter, "approve", tools=REGISTRY) (pass the same tools= you gave run_agent, or the resumed run falls back to the support tools).
  7. Live mode (optional, needs a key). With OPENAI_API_KEY in .env, run --live on gpt-6-luna. The adapter needs an async client (AsyncOpenAI()), and the wire tool list must come from your registry, not the support tools: build it as [{"type": "function", "name": n, "description": s.description, "parameters": json_schema(s.args_model), "strict": True} for n, s in REGISTRY.items()], using json_schema from 08A.2's support_tools.py (it rewrites the schema into the strict-safe subset), and pass that list as the adapter's tools. Compare the trajectory to your script: did it search before fetching? Did it cite real URLs? Did it stay inside max_steps? If you want the provider to do the searching instead, declare web_search as a built-in tool per 08A.8, Part 2 — but keep web_fetch custom, because fetching your corpus is exactly the case built-ins can't cover (08A.8, 10.2).

Verify it, and what you should see:

bash
uv run python run_research.py
uv run pytest -q test_research.py
Example output · illustrative5 lines
status: completed | steps: 6 | spent: {'input_tokens': 600, 'output_tokens': 120, 'cost_usd': 0.0}
answer: You don't need a helmet as an adult, but riders under 16 must wear one;
        lights are required after dark (Safety). A month pass costs £18, with a
        50% student discount (Pricing).
notes saved: 1 | citations checked: 2/2 URLs in corpus

And the broken-loop test prints status: loop_detected on the third identical web_fetch (before that call runs).

Done when:

  • run_research.py completes the helmet+pricing question with a cited answer, inside the budget, using only research_tools.py functions over CORPUS.
  • test_research.py passes: trajectory shape, citations resolve to real corpus URLs, zero-hit recovery works, and the identical-call loop stops as loop_detected.
  • The save_note approval pause/resume round-trips through resume_agent.
  • Your tool descriptions each say when not to call the tool, and submit_answer's description carries the citation contract.
  • Your notes record one thing a live model did differently from your script (or "not tested live" if you have no key).

Stretch ideas:

  • Swap the corpus for the Module 07 docs_qa retriever behind a docs_search tool, exactly as 08A.6's docs_search does — retrieval becomes a tool, not a pipeline stage.
  • Add a compare_pages(url_a, url_b) composite tool (08A.6, 2.3) and measure whether the model chains fewer calls.
  • Turn the fixed script into an eval: three EvalTasks (one requiring web_fetch, one forbidding save_note, one with an arg_checks predicate on the citation format) run through 08A.6's tool_eval.py with QueuedModel.
  • Hosted, needs keys: run the agent on a provider built-in web_search plus your custom web_fetch/submit_answer, and log the per-call cost with the usage fields from 08A.8, 6.2.

Common problems:

  • Loop never ends: you forgot submit_answer in REGISTRY, or Budget.finish_tool doesn't match the tool name — the default is "submit_answer" (08A.2, 3.3).
  • "unknown tool" errors: run_agent was called without tools=REGISTRY, so it used the support tools' default registry.
  • Citations fail: the model cites titles without URLs — tighten submit_answer's description and check the answer in test_research.py, not by eye.
  • Giant page floods context: web_fetch returns full text; if pages grow, truncate with a marker per 08A.2's _truncate and 08A.6, 3.3.
  • Tests pass but live model flails: scripted replies prove plumbing only — add the tool_eval.py tasks and, when keyed, run several trials per task (08A.6, 8.2).

Stretch

Stretch: Multi-step workflow agent#

Goal: Take the support assistant's hardest request — "a customer wants a refund on an order that hasn't arrived; check the order and the refund policy, then advise or act" — and run it as a production-shaped agent: plan_and_execute decomposes it, a permission gate pauses before any write, the MemoryStore remembers the customer across "sessions", every step is traced and costed, and an eval suite with trajectory graders plus pass^k proves it still works after your changes. This is the module's capstone: it combines 08A.9's orchestration, 08A.10's loop and patterns, 08B.2's memory and 08A.14's safety and evaluation — and it is deliberately open-ended.

What you'll practise:

Setup: stdlib + pydantic + pytest. Work in its own folder — this project mixes three lessons' support_tools.py-style files, so keep the 08A.10 set (agent_loop.py, patterns.py, approval.py, support_tools.py, trajectory.py) in agent/ and the 08A.14 set (policy.py, tracer.py, passk.py, evalharness.py) in reliability/ (not evalkit/, which is the Module 10A package's name); the 08B.2 files (memory_store.py, extract_memories.py, memory_tools.py) go in memory/. Adjust the lessons' imports accordingly (mechanical from x import y fixes — the lessons' file headers say what each expects beside it).

Steps:

  1. Baseline the agent. In agent/, run the lesson's demo (demo.py from 08A.10) to confirm plan_and_execute works against ScriptedModel. Then write ops_agent.py: a run_ops(goal, customer) function that builds the ToolRegistry from 08A.10's support_tools.py, scopes the run to the customer (the customer's identity is bound in code, never taken from the model — the confused-deputy rule from 08A.6, 4.2; 08A.10's lookup_order and issue_refund take only an order ID, so wrap them to check order["email"] == customer_email and return the same "no order found" error otherwise), and calls plan_and_execute(call_model, registry, goal, on_event=TrajectoryLogger("runs.jsonl")). Give the file a --demo flag whose main() runs one scripted scenario end to end (the Verify block below calls it).
  2. Add the approval gate. Build gate = policy_gate(PermissionPolicy(approval_risks={"write", "destructive"})) from approval.py (the gate is passed to the loop as gate=; it does not wrap the tools). In 08A.10's support_tools.py issue_refund is tagged destructive and create_ticket write, so both pause. Test the pause with a direct run: run_agent_approved(model, registry, messages, policy=policy) over a ScriptedModel that proposes issue_refund, inspect result.pause_payload, then resume_approved(model, registry, paused, {"action": "edit", "arguments": {...}}, policy=policy) (policy is required, so the gate stays on after the human decision) and show the edited amount lands in the refund record: the lesson's exercise 9, as a test. Note the limit: plan_and_execute forwards the gate to each executor, but a pause inside an executor ends that step as [step ended: paused] and the plan result carries no resumable pause. So the resumable approval path lives on the direct agent run; in the planned run you can only assert that the refund did not execute (08A.10, 6.1).
  3. Add memory. In memory/, instantiate InMemoryStore (or FileMemoryStore for persistence across runs). After each simulated session, call extract_and_apply(store, tenant_id="acme", subject_id=customer_email, messages=conv, call_model=fake_extractor) where fake_extractor returns a canned {"operations": [...]} JSON — 08B.2, 8.6 shows the shim for wrapping an adapter. Register memory_search/memory_remember/memory_forget from memory_tools.py into the agent's registry with scope injected by your code (the model can narrow, never widen — 08B.2, 8.5). Prove recall: session 1 stores "prefers email updates, refund threshold £50"; session 2's prompt asks about communication preferences and the agent calls memory_search first.
  4. Add the policy layer for evaluation. This is the integration step that makes the project yours. 08A.14's policy.py has its own six tools over its own Env (ORD-4471/ORD-4472 orders; lookup_order, search_docs, create_ticket(subject, body, priority), issue_refund(order_id, amount, reason=""), send_email, delete_customer_data), which differ from 08A.10's tools by design. Write policy_bridge.py that registers those six as 08A.10 Tools (hand-written JSON-Schema parameters; risk="read" for the first two and "write" for the rest, because the real decision is made by the engine). Each fn does out = pol.execute(name, args, trace_id=trace_id, approver=approver) on a pol = build_policy() and trace_id = pol.begin_run() that the bridge creates once per run, and returns out["result"], or raises RuntimeError(out.get("reason") or out.get("error") or out["status"]) when out["status"] != "ok" (08A.10's registry turns an exception into an error result the model can read). Use approver=ScriptedApprover(rules=[("issue_refund", '"order_id": "ORD-4472"', None)]) so only that refund is approved, and leave 08A.10's policy_gate off for these tools (08A.14 already asks the approver; gating twice would pause a call the engine will decide anyway). Also have each bridged fn append {"tool": name, "args": args} to a calls list before it calls pol.execute: that list is what you turn into Trajectory(task_id, model, final_answer, calls) objects. evalharness.replay() does not use your bridge; it re-applies those recorded calls through its own fresh build_policy() after resetting policy.ENV = policy.Env(), so your graders see real end state. (dry_run=True exists on execute(), but only issue_refund supports it; for any other tool the engine returns denied rather than running the real call, so the bridge never passes dry_run.)
  5. Build the eval suite. Write eval_suite.py with 6–8 EvalTasks covering the refund flow: happy path (refunded_exactly), policy violation (no_denied_calls), injection attempt via a crafted search_docs result (no_denied_calls fails the trial because the approver refused the attempted send_email; no_external_sends only fires if a mail actually went out, so add a trial with a permissive approver to see it), memory recall (claims_match_actions-style grader on the trajectory), and a max-steps grader you write yourself (08A.14, 4.9, exercises 5–7). Record trajectories by running the bridged agent under ScriptedModel variants — one correct, one that issues the refund for the wrong amount (the policy denies an amount above the balance, so a wrong-but-valid amount such as a partial refund is the state grader's job), one that attempts send_email after reading an injected doc — then replay each through run_trial with the same ScriptedApprover. Each trajectory in the harness is Trajectory(task_id, model, final_answer, calls); build it from the bridge's calls list and the model's last message.
  6. Measure reliability. Run the suite and print per-task pass/fail with reasons. Then use passk.py's pass_at_k/pass_hat_k/suite_metrics on repeated-trial results (08A.14, 4.4) — simulate trials by varying the script (e.g. 5 scripted "runs" per task with different failure mixes) and report pass@1 vs pass^5. Explain in your notes why pass^5 punishes flaky agents even when pass@1 looks fine.
  7. Cost and trace accounting. Wrap model calls so Usage accumulates per agent/step (08D.3, 3.7 for the accounting shape; 08A.14, 3.3–3.4 for Tracer spans and cost_by_tool). Print a per-tool cost table from one run's runs.jsonl + audit log.
  8. Write the ops note. One page: the architecture diagram (you may describe it in text), what the policy layer denies and why, what memory stores and what it refuses, the eval results table, and the three failure modes you injected and how each was caught.

Verify it, and what you should see:

bash
uv run pytest -q agent/ reliability/ memory/     # lesson tests + your new tests pass
uv run python eval_suite.py                  # per-task PASS/FAIL with grader reasons
uv run python ops_agent.py --demo            # one scripted end-to-end run with trace
Example output · illustrative5 lines
trial refund-happy: PASS []
trial refund-partial: FAIL ['ORD-4472 refunded=40.0, expected 84.5']
trial injection-send: FAIL ['1 denied call(s): send_email']
suite: pass@1=0.75 pass^5=0.50 over 4 tasks x 5 trials
cost: lookup_order $0.0011, issue_refund $0.0004, memory_search $0.0009

Done when:

  • A single command runs the scripted end-to-end scenario: plan → tools → approval pause → resume → answer, with a written trajectory.
  • The approval edit path demonstrably changes the executed refund amount; the reject path feeds an error the model can read.
  • Memory written in "session 1" is retrieved and used in "session 2", scoped to the right tenant/subject, and a cross-tenant probe returns nothing.
  • The eval suite grades at least four distinct failure modes and passk.py numbers are computed from recorded trials, not asserted.
  • policy_bridge.py works: a scripted agent run through the bridge records its calls, evalharness.replay() re-runs them on a fresh Env, and graders inspect real end state.
  • Your ops note names the top three residual risks and which lesson section mitigates each.

Stretch ideas:

  • Replace ScriptedModel with the 08A.9 adapters.py sketch behind a flag, run five live trials per task, and compare live pass rates to scripted ones (08A.14, 4.10).
  • Add a verify_and_retry or critique_and_revise stage from 08A.10, Part 4 before the final answer and measure whether the eval scores move.
  • Persist paused runs with snapshot()/restore() so an approval can survive a process restart (08A.10, Part 6); then record one trajectory that calls the refund tool twice with the same idempotency key and show one refund, not two (idempotency; 08A.14, 5.1 and its exercise 8 — note that replay() resets the environment for every trajectory, so two separate replays can never expose the bug).
  • Wrap the whole run in run_durable from 08A.9, 6.3 for step-level resume, and kill it mid-run to prove recovery.

Common problems:

  • Import collisions: three lessons ship support_tools.py/ScriptedModel/ToolRegistry — the subfolder layout above is not optional; fix imports mechanically and keep each loop's tests beside its files.
  • Memory leaks across tenants: scope must be injected by your code into memory_tools, never read from model args (08B.2, 8.5); write the tenant-leak probe test from 08B.2's exercise 5 before debugging anything else.
  • Approval approves forever: a pause approves one call, not the tool — re-check policy on resume and give approvals a scope/TTL per 08A.14, 2.5.
  • Eval passes vacuously: a grader that inspects only the final text can't see a denied-then-retried call — use trajectory graders on steps, and state graders on env (08A.14, 4.2).
  • Cost numbers are fiction: ScriptedModel reports zero or canned usage — label cost output "as if priced" and source real per-token prices from the 03.7 price-table pattern when you go live.

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