Module 08A: Projects
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: 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
Budgetlimits and thesubmit_answerfinish 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
ScriptedModeland 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:
- Create the corpus. Make
research_data.pywith aCORPUSdict 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. - Write
research_tools.py. Four tools in the 08A.2ToolSpecstyle (args_model,fn,risk="read",timeout_s), each a Pydantic arg model plus a plain function overCORPUS:web_search(query: str, max_results: int = 5)— score pages by query-term overlap (copy the scoring approach from 08D.3'sweb_search, or 08A.6'sKeywordRetriever), return[{url, title, snippet}]sorted by score,count, and anotewhen 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 aNOTESlist 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'sToolSpecthe 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 insubmit_answer's description: "cite sources astitle (url)".
- Write
run_research.py. Amain()that buildsBudget(max_steps=10, max_seconds=120, max_calls_per_tool=4)and callsrun_agent(adapter, question, tools=REGISTRY, budget=budget)whereadapteris aScriptedModelfor the demo and anOpenAIResponsesAdapter(fromagent.py) behind a--liveflag for when you have a key.run_agentis a coroutine, somain()isasyncand the file ends withasyncio.run(main()). Printresult.status,result.answer,result.steps, andresult.spent. Write the script inScriptedModel's format from 08A.2, 3.5 (("calls", [(name, args)])turns, ending with asubmit_answercall). 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_fetchthe safety page →web_search("month pass price")→web_fetchthe pricing page →save_note→submit_answerwith a cited answer. - Test it. Write
test_research.pyin the style of 08A.2'stest_agent.py: assert the run endscompleted, the answer contains both facts, every cited URL exists inCORPUS,NOTEShas one entry, andScriptedModel.seenshows the tool results were appended asrole="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 callweb_searchagain after the error result. - Break it on purpose. Script a model that calls
web_fetchwith a made-up URL three times. Confirm the loop stops withloop_detected(identical call signature) rather than burning all ten steps:Budget.loop_thresholddefaults 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. - Add the approval hook. Give
save_noterisk="write"and pass anapprovertorun_agentthat prints thePendingApprovaland returns"approve"/"deny"/"defer"(08A.2, 6.4). Show adeferrun pausing withstatus == "awaiting_approval", then resume it withawait resume_agent(res.state, adapter, "approve", tools=REGISTRY)(pass the sametools=you gaverun_agent, or the resumed run falls back to the support tools). - Live mode (optional, needs a key). With
OPENAI_API_KEYin.env, run--liveongpt-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()], usingjson_schemafrom 08A.2'ssupport_tools.py(it rewrites the schema into the strict-safe subset), and pass that list as the adapter'stools. Compare the trajectory to your script: did it search before fetching? Did it cite real URLs? Did it stay insidemax_steps? If you want the provider to do the searching instead, declareweb_searchas a built-in tool per 08A.8, Part 2 — but keepweb_fetchcustom, because fetching your corpus is exactly the case built-ins can't cover (08A.8, 10.2).
Verify it, and what you should see:
uv run python run_research.py
uv run pytest -q test_research.pystatus: 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 corpusAnd the broken-loop test prints status: loop_detected on the third identical web_fetch (before that call runs).
Done when:
run_research.pycompletes the helmet+pricing question with a cited answer, inside the budget, using onlyresearch_tools.pyfunctions overCORPUS.test_research.pypasses: trajectory shape, citations resolve to real corpus URLs, zero-hit recovery works, and the identical-call loop stops asloop_detected.- The
save_noteapproval pause/resume round-trips throughresume_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_qaretriever behind adocs_searchtool, exactly as 08A.6'sdocs_searchdoes — 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 requiringweb_fetch, one forbiddingsave_note, one with anarg_checkspredicate on the citation format) run through 08A.6'stool_eval.pywithQueuedModel. - Hosted, needs keys: run the agent on a provider built-in
web_searchplus your customweb_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_answerinREGISTRY, orBudget.finish_tooldoesn't match the tool name — the default is"submit_answer"(08A.2, 3.3). - "unknown tool" errors:
run_agentwas called withouttools=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 intest_research.py, not by eye. - Giant page floods context:
web_fetchreturns full text; if pages grow, truncate with a marker per 08A.2's_truncateand 08A.6, 3.3. - Tests pass but live model flails: scripted replies prove plumbing only — add the
tool_eval.pytasks and, when keyed, run several trials per task (08A.6, 8.2).
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:
- Choosing the architecture: why this task earns a plan-and-execute agent rather than a single call or a fixed workflow (lesson 08A.9, 2.2, Part 7)
- Plan-and-execute with the plan as state, bounded executors and a replanner (lesson 08A.10, Part 3)
- Human approval with approve/edit/reject and resumable state (lesson 08A.10, 6.1) and the workflow-level checkpoint (lesson 08A.9, 3.7)
- Long-term memory: extraction, merge/dedup, scored retrieval, memory-as-tools, tenant isolation (lesson 08B.2, Part 8, 4.5)
- The policy layer: risk tiers, validators, approvals, budgets, audit log (lesson 08A.14, 2.10)
- Trajectory logging, spans with cost attribution, and replay (lesson 08A.14, Part 3, 08A.10, Part 9)
- Agent evals: task suites, state and trajectory graders,
pass@k/pass^k, regression from failures (lesson 08A.14, Part 4, 08A.6, 8.2)
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:
- Baseline the agent. In
agent/, run the lesson's demo (demo.pyfrom 08A.10) to confirmplan_and_executeworks againstScriptedModel. Then writeops_agent.py: arun_ops(goal, customer)function that builds theToolRegistryfrom 08A.10'ssupport_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'slookup_orderandissue_refundtake only an order ID, so wrap them to checkorder["email"] == customer_emailand return the same "no order found" error otherwise), and callsplan_and_execute(call_model, registry, goal, on_event=TrajectoryLogger("runs.jsonl")). Give the file a--demoflag whosemain()runs one scripted scenario end to end (the Verify block below calls it). - Add the approval gate. Build
gate = policy_gate(PermissionPolicy(approval_risks={"write", "destructive"}))fromapproval.py(the gate is passed to the loop asgate=; it does not wrap the tools). In 08A.10'ssupport_tools.pyissue_refundis taggeddestructiveandcreate_ticketwrite, so both pause. Test the pause with a direct run:run_agent_approved(model, registry, messages, policy=policy)over aScriptedModelthat proposesissue_refund, inspectresult.pause_payload, thenresume_approved(model, registry, paused, {"action": "edit", "arguments": {...}}, policy=policy)(policyis 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_executeforwards 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). - Add memory. In
memory/, instantiateInMemoryStore(orFileMemoryStorefor persistence across runs). After each simulated session, callextract_and_apply(store, tenant_id="acme", subject_id=customer_email, messages=conv, call_model=fake_extractor)wherefake_extractorreturns a canned{"operations": [...]}JSON — 08B.2, 8.6 shows the shim for wrapping an adapter. Registermemory_search/memory_remember/memory_forgetfrommemory_tools.pyinto the agent's registry withscopeinjected 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 callsmemory_searchfirst. - Add the policy layer for evaluation. This is the integration step that makes the project yours. 08A.14's
policy.pyhas its own six tools over its ownEnv(ORD-4471/ORD-4472orders;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. Writepolicy_bridge.pythat registers those six as 08A.10Tools (hand-written JSON-Schemaparameters;risk="read"for the first two and"write"for the rest, because the real decision is made by the engine). Eachfndoesout = pol.execute(name, args, trace_id=trace_id, approver=approver)on apol = build_policy()andtrace_id = pol.begin_run()that the bridge creates once per run, and returnsout["result"], or raisesRuntimeError(out.get("reason") or out.get("error") or out["status"])whenout["status"] != "ok"(08A.10's registry turns an exception into an error result the model can read). Useapprover=ScriptedApprover(rules=[("issue_refund", '"order_id": "ORD-4472"', None)])so only that refund is approved, and leave 08A.10'spolicy_gateoff for these tools (08A.14 already asks the approver; gating twice would pause a call the engine will decide anyway). Also have each bridgedfnappend{"tool": name, "args": args}to acallslist before it callspol.execute: that list is what you turn intoTrajectory(task_id, model, final_answer, calls)objects.evalharness.replay()does not use your bridge; it re-applies those recorded calls through its own freshbuild_policy()after resettingpolicy.ENV = policy.Env(), so your graders see real end state. (dry_run=Trueexists onexecute(), but onlyissue_refundsupports it; for any other tool the engine returnsdeniedrather than running the real call, so the bridge never passesdry_run.) - Build the eval suite. Write
eval_suite.pywith 6–8EvalTasks covering the refund flow: happy path (refunded_exactly), policy violation (no_denied_calls), injection attempt via a craftedsearch_docsresult (no_denied_callsfails the trial because the approver refused the attemptedsend_email;no_external_sendsonly 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 underScriptedModelvariants — 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 attemptssend_emailafter reading an injected doc — then replay each throughrun_trialwith the sameScriptedApprover. Each trajectory in the harness isTrajectory(task_id, model, final_answer, calls); build it from the bridge'scallslist and the model's last message. - Measure reliability. Run the suite and print per-task pass/fail with reasons. Then use
passk.py'spass_at_k/pass_hat_k/suite_metricson 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. - Cost and trace accounting. Wrap model calls so
Usageaccumulates per agent/step (08D.3, 3.7 for the accounting shape; 08A.14, 3.3–3.4 forTracerspans andcost_by_tool). Print a per-tool cost table from one run'sruns.jsonl+ audit log. - 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:
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 tracetrial 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.0009Done 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.pynumbers are computed from recorded trials, not asserted. policy_bridge.pyworks: a scripted agent run through the bridge records its calls,evalharness.replay()re-runs them on a freshEnv, and graders inspect real end state.- Your ops note names the top three residual risks and which lesson section mitigates each.
Stretch ideas:
- Replace
ScriptedModelwith the 08A.9adapters.pysketch 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_retryorcritique_and_revisestage 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 thatreplay()resets the environment for every trajectory, so two separate replays can never expose the bug). - Wrap the whole run in
run_durablefrom 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:
scopemust be injected by your code intomemory_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 onenv(08A.14, 4.2). - Cost numbers are fiction:
ScriptedModelreports 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.