Module 08F: Projects
Starter projects are guided step by step and suit freshers. Stretch projects are open-ended, add production concerns, and suit experienced readers.
The LangChain and LangGraph track: four more projects#
Lessons 08F.4 to 08F.17 add four projects (08F.P1 to 08F.P4, all in this file) that use the two frameworks instead of your own loop: two starters (a create_agent desk agent with a middleware stack; an agentic RAG assistant) and two stretches (a LangGraph support workflow with a durable checkpointer, approvals, time travel and a subgraph; an optional multi-agent research desk with local tracing and an evaluation dataset). They are built only from the APIs those lessons teach, and they reuse the lessons' keyless approach: scripted fake chat models, a keyless embedding model, plain-Python graph nodes and in-memory or local SQLite persistence, so every "Done when" checklist can be finished with no API key and no LangSmith account. Provider variants (a real chat model, real embeddings, LangSmith datasets and experiments, Studio) are labelled illustrative: they were written from the official documentation and package source and were not run when this module was written.
The honesty note from the projects of Module 08A applies with one change of emphasis. A scripted model always makes the call you scripted, so your tests prove your code: which tools run, what a guard blocks, what an approval pauses, what a checkpoint remembers. They cannot tell you whether a real model picks the right tool, writes a good brief or follows your prompt; that is an evaluation question, and the last project shows the mechanics of asking it (08F.8, 12.4). Every output block below is labelled illustrative unless it says it comes from a lesson.
Rule: raw tool loop first. These projects assume you have already built a loop by hand (lesson 08A.2 and the starter projects of Module 08A). The frameworks only make sense once you know what they replace.
Setup shared by all four. You need Python 3.11 or newer and uv. Each project names its own folder and its own uv add line, and every install command lists package names only: there are no == pins, because the lockfile uv writes records what resolved, and each lesson's Versions line says what its samples were checked against (langchain 1.5.0, langgraph 1.2.22 and friends, as of November 2026). These packages release several times a week; when a name here does not match what you see, trust the lesson's Versions line, the API reference and the changelog, and fix the project, not the package.
Files you copy from the lessons. Copy each exactly as printed:
- From 08F.8:
fakes.py(FakeToolCallingModel,RecordingModel,StreamingFakeModel; 1.3), andsupport_desk.pyas a reference to read, not to copy (Part 11) - From 08F.9:
corpus.py(HANDBOOK),hash_embeddings.py(BagOfWordsEmbeddings),kb_common.py,rag_fakes.py(RecordingFakeModel),kb.pyandtest_kb.py(Part 15) - From 08F.12:
refund_flow.py,refund_demo.pyandtest_refund_flow.py(Part 11) - From 11A.5:
trace_recorder.py(Recorder), from the Setup section at the top of the lesson
One name collides: 08F.8 and 11A.5 each print a fakes.py. Keep the 08F.8 one, which is a superset of the 11A.5 one. 08F.9's helper is rag_fakes.py on purpose, so both can live in one folder.
Starter: Service-desk agent with create_agent and middleware#
Goal: Build a hire-desk agent for the fictional Meridian Cycles bike-share (the company from the first starter project of Module 08A): four tools, the customer's identity taken from run-time context and never from the model, and a deliberately ordered middleware stack that redacts email addresses, caps the loop, turns tool failures into messages the model can read, asks a human before any cancellation, and falls back to a second model when the first is down. You test every guard with scripted fake models, so the whole project runs with no key. It is the LangChain counterpart of the loop you wrote by hand in 08A.2: create_agent is that loop as a compiled graph, and middleware is where your policy goes.
What you'll practise:
- What
create_agentreturns and what it does not do for you: no step budget, no approval, no memory without a checkpointer (lesson 08F.8, 1.1, 1.4) - Tool design in LangChain:
@tool(parse_docstring=True), names and descriptions the model reads, andToolRuntime[Context]so identity comes from your auth layer (lesson 08F.8, 2.2, 3.2) - The four remedies for tool failure, and composing
ToolErrorMiddlewareoutsideToolRetryMiddleware(lesson 08F.8, 4.2, 4.4, 4.5) - The six middleware hooks, writing your own with decorators, and which hook fits which job (lesson 08F.8, 8.2, 8.3, 8.4)
- Human approval with
HumanInTheLoopMiddleware, theapprove/edit/rejectdecisions and why a checkpointer and athread_idare required (lesson 08F.8, 8.9) - PII redaction, call limits, model fallback and retry, and the middleware order (lesson 08F.8, 8.11, 8.12, 8.10, 8.6)
- Testing an agent without a key: scripted models,
RecordingModel, and asserting on what the system did rather than on what the fake said (lesson 08F.8, Part 12)
Setup:
uv init langchain-agents --bare --python 3.13 && cd langchain-agents # first time only
uv add langchain python-dotenv
uv add --dev pytestCopy fakes.py from 08F.8, 1.3 next to your files. No .env, no keys. Read support_desk.py in 08F.8, Part 11 first: your project has the same shape on different data, so write your own rather than pasting it, and use the lesson's file as the answer key when you are stuck.
Steps:
- Create the data. Make
desk_data.pywith aBOOKINGSdict (five or six bookings, ids such asBK-1001, each with acustomer_id, ahub, adate, astatusofconfirmedorcancelledand aprice), anAVAILABILITYdict (hub then date then number of bikes free), a smallFAQdict (cancel,helmet,deposit), and an emptyCANCELLATIONSlist that the cancel tool appends to so tests can see what really happened. Put two bookings under one customer and at least one under another, so privacy tests have something to protect. - Write the context and the tools. In
desk_tools.pydefineContextas a dataclass (customer_id,customer_name) and four tools with@tool(parse_docstring=True):check_availability(hub, date),search_faq(query),get_booking(booking_id, runtime: ToolRuntime[Context])andcancel_booking(booking_id, runtime: ToolRuntime[Context]). Write each docstring as the description the model reads: what it does, when to use it, and when not to (08F.8, 2.2). RaiseToolExceptionwith a curated message for failures, and use one message for "no such booking" and "someone else's booking" so the tool cannot be used to probe which ids exist.cancel_bookingre-checks its preconditions (the booking is yours and stillconfirmed) after approval, because the world can change while a human decides. - Assemble the agent. In
desk_agent.pywritebuild_agent(model, *, fallback_model=None)that returnscreate_agent(model, tools=[...], middleware=[...], context_schema=Context, checkpointer=InMemorySaver(), name="hire_desk"). Order the middleware as 08F.8, 8.6 and the lesson'sbuild_agentdo:PIIMiddleware("email", strategy="redact")first, thenModelCallLimitMiddleware(run_limit=8, exit_behavior="end"), thenToolCallLimitMiddleware(tool_name="cancel_booking", run_limit=1), then a@dynamic_promptfunction that greets the customer byrequest.runtime.context.customer_name(9.1), then your two custom hooks (steps 4 and 5), thenToolErrorMiddleware(on_error=...)outsideToolRetryMiddleware(max_retries=2, tools=["search_faq"], on_failure="error"), andHumanInTheLoopMiddlewarelast, withcancel_bookingallowedapprove,editandrejectand the three read tools set toFalse. Youron_errorfunction returns the message forToolExceptionand a generic "internal error, offer to escalate" string for anything else, so internals never reach the model. - Add an input guardrail. Write a
@before_agent(can_jump_to=["end"])function in the style of 08F.8, 8.14 that ends the run with a fixedAIMessagewhen the last human message asks for something outside hire-desk topics or contains an obvious injection phrase. Withoutcan_jump_tothe jump has no edge, so declare it. - Add an audit and policy hook. Write a
@wrap_tool_callfunction that appends(tool name, arguments)to anAUDITlist before callinghandler(request), and that refuses acancel_bookingfor a booking whose date is less than 24 hours away by returning aToolMessage(status="error")with the sametool_call_idinstead of calling the handler (08F.8, 8.4). Then check when it fires: the approval pause comes from a model-side hook that runs before the tool node, so work out from 08F.8, 8.2 and a test whether a human is asked to approve a cancellation that your policy will refuse anyway, and move the check (into the tool body, or into a hook that runs before the pause) if that is wasteful. - Script the scenarios. In
run_desk.pybuild a freshFakeToolCallingModelper scenario (the script is an iterator and is consumed once) with acalls(*items)helper like the lesson's. Four scenarios: (a) look up a booking, then cancel it, pausing for approval and resuming withCommand(resume={"decisions": [{"type": "approve"}]}); (b) ask about another customer's booking; (c) a message containing an email address, usingRecordingModelto show what the model actually received; (d) the injection phrase. Invoke withconfig={"configurable": {"thread_id": ...}},context=Context(...)andversion="v2", which returns an object with.interruptsand.value. - Test every guard. Write
test_desk.pyin the style of 08F.8, 12.2, onecalls()-scripted test per rule: another customer's booking is not readable (and the error text names no other customer); a cancellation waits for a human and nothing is recorded until approval; an approved cancellation is recorded once; a rejected one never is; aneditdecision with a different booking id cancels the edited one (check what your tool does with it, and decide whether the wrapper should re-validate); the email is redacted before the model sees it; an endless model (a generator of tool calls) is stopped byModelCallLimitMiddleware; the late-cancellation refusal never reaches the tool body. Test the negatives first: they are the rules that must hold. - Prove the fallback and the retry order. Following 08F.8, 8.10, add
ModelFallbackMiddleware(fallback_model)whenfallback_modelis given, with aDownModelsubclass ofFakeToolCallingModelthat raisesConnectionErrorin_generate, and assert the backup answers. Then count attempts on a dead primary withModelRetryMiddlewarelisted before and after the fallback middleware, and write one sentence on why the order changes the count. - Live mode (optional, needs a key). Illustrative:
uv add langchain-openai, putOPENAI_API_KEYin.env, callload_dotenv()and pass"openai:gpt-6-luna"tobuild_agent(the model ids are the course defaults from 02.9; check them before you run, because model ids change). The same call works for the other providers by changing the string (08F.5, 2.1). Compare the real trajectory with your script: did it look the booking up before cancelling? Did it ask for the same tools in the same order? Note one difference.
Verify it, and what you should see:
uv run python run_desk.py
uv run pytest -q(a) paused for approval: cancel_booking {'booking_id': 'BK-1001'} | cancellations so far: []
after approve: cancellations: ['BK-1001']
(b) tool message (error): No booking 'BK-2001' found for this customer. Ask the customer to check the number.
(c) the model received: Please email me at [REDACTED_EMAIL]
(d) ended by the input guardrail: I can only help with Meridian Cycles hire questions.pytest should finish with every test passing. The point of the scripted run is its shape: the pause happens before the side effect, the redaction happens before the model, and the guard ends the run before any model call.
Done when:
run_desk.pyruns the four scenarios keylessly and the approval pause resumes throughCommand(resume=...)on the samethread_id.test_desk.pypasses and contains a test for each of: privacy, approval wait, approval once, rejection, redaction, loop cap, late-cancellation refusal and fallback.- Your middleware list is in a deliberate order that you can explain in one sentence per entry, and the retry-versus-fallback ordering test is written down.
- No tool returns raw exception text to the model, and
cancel_bookingis never retried. - Your notes record one thing a live model did differently from your script (or "not tested live" if you have no key).
Stretch ideas:
- Add
SummarizationMiddleware(model=..., trigger={"tokens": 3000}, keep=("messages", 12))assupport_desk.pydoes, and write a test that feeds a long scripted history and checks that a summary appears (08F.8, 8.8). - Choose a cheaper model for short chats with a
wrap_model_callhook that callsrequest.override(model=...)(08F.8, 9.2), and test which model each call used. - Return a typed final answer with
response_formatand check the structured response (08F.8, 7.7; strategies per provider in 08F.6, Part 10). - Bring in tools from an MCP server through
langchain.mcp(the garden server from the MCP project works) and gate its tools by annotations (08F.8, Part 6). - Hosted, needs keys: run the same agent on a real model and turn tracing on (08F.4, 5.7) to see the loop as a trace.
Common problems:
StopIterationor "script exhausted": the agent made more model calls than you scripted, or you reused a consumed iterator. Build a fresh model per scenario and read the failure as a test result (08F.13, Part 9 has the same advice).ValidationErrorwhen you call a tool directly:tool.invoke(...)does not inject aToolRuntime. Test through the agent, or calltool.func(...)with a stand-in runtime object (08F.8, 12.1).- A guard's jump is ignored: the hook returned
jump_tobut was not declared withcan_jump_to=[...](08F.8, 8.3). - The approval never pauses: the agent has no checkpointer, the call has no
thread_id, or the tool name ininterrupt_ondoes not match the tool's name. - The loop never stops on its own: the default recursion limit is 10,007 steps, not a budget (08F.8, 7.5). A tool limit with the default
exit_behavior="continue"only makes the tool refuse politely, so pair it withModelCallLimitMiddlewareor useexit_behavior="end". - Redaction does not apply to tool results or model output:
apply_to_outputandapply_to_tool_resultsare off by default (08F.8, 8.11). - Retries multiply side effects:
ToolRetryMiddlewarecalls the tool again, so restrict it withtools=[...]to read-only tools (08F.8, 4.5).
Starter: Agentic RAG assistant#
Goal: Turn the Module 07 idea of retrieval-augmented generation into LangChain objects and then into an agent: ingest a folder of Markdown into an in-memory vector store with the indexing API (so re-running ingest is free and edits replace the old text), expose retrieval as a tool that respects the caller's role and carries its sources as an artifact, bound the loop with a retrieval budget, compare the agentic shape with a two-step one, and measure retrieval with a small golden set. Everything runs with the keyless bag-of-words embedding model and scripted chat models from lesson 08F.9.
What you'll practise:
- The RAG pipeline as LangChain components, and where each stage lives (lesson 08F.9, 1.1, 1.3)
- Loading and splitting: a tiny
BaseLoader,RecursiveCharacterTextSplitterwithchunk_size,chunk_overlapandadd_start_index(lesson 08F.9, 2.2, 3.1) - The
Embeddingsinterface andInMemoryVectorStore, including the filter-as-a-function trick (lesson 08F.9, 4.1, 5.1) - Incremental ingest with
index(...), a record manager and the four cleanup modes, including the blind spot of"incremental"(lesson 08F.9, 11.2, 11.3) - Retrieval as a tool:
@tool(response_format="content_and_artifact"), per-user filters throughToolRuntime, andToolCallLimitMiddlewareas a budget (lesson 08F.9, 8.1, 8.3, 8.4) - Two-step RAG as
@dynamic_promptmiddleware versus agentic RAG, and how to choose (lesson 08F.9, 7.2, Part 9) - A keyless retrieval harness with hit rate and mean reciprocal rank, and reading the misses (lesson 08F.9, 12.2), with the theory in Module 06, lesson 10
- The security rules for retrieved text (lesson 08F.9, 13.1)
Setup:
uv init langchain-rag --bare --python 3.13 && cd langchain-rag # first time only
uv add langchain langchain-text-splitters numpy python-dotenv pytest
uv add langchain-classic rank-bm25 greenlet # only for the hybrid retriever in step 7; do not add langchain-community (sunset 22 May 2026, repository archived)Copy corpus.py, hash_embeddings.py, kb_common.py, rag_fakes.py, kb.py and test_kb.py from 08F.9 exactly as printed (each is shown where it is first needed; Part 15 lists which sit beside kb.py). No .env, no keys. numpy is needed because InMemoryVectorStore imports it the first time you search (08F.9, 5.1).
Steps:
- Run the lesson's module unchanged. Run
uv run pytest -q. The six tests intest_kb.pyshould pass before you touch anything: a second ingest changes nothing, an edit leaves one version of a chunk, a deleted file leaves the index undercleanup="full"and stays under"incremental", sources come back as an artifact, and a customer cannot retrieve the internal document. If any fail, fix your copy before you extend it. - Grow the handbook. Write
make_handbook.pythat writes the fiveHANDBOOKfiles plus three of your own into ahandbook/folder:repairs.md(turnaround and cost),sizing.md(how to choose a tent size) andstaff-escalation.md(discount authority limits: an internal document). Addstaff-escalation.mdtoINTERNAL_SOURCESinkb.py. Keep each file short, with##headings so the splitter has structure. - Ingest from the folder, twice. Write
ingest.pythat builds a store withnew_store(BagOfWordsEmbeddings()), createsInMemoryRecordManager(namespace="handbook/bag-of-words/v1")(callcreate_schema()), and runsbuild_index(Path("handbook"), store, records)two times. The first run reports additions; the second should report zero additions and zero deletions and skip every chunk. Edit one sentence inreturns.md, run it again, and confirm one chunk added and one deleted. The counts depend on your chunking, so compare shapes (all skipped; one added, one deleted), not the lesson's numbers for its five-file corpus. - Script four agentic trajectories. Using
make_agent(model, store)fromkb.pyand aRecordingFakeModelfromrag_fakes.pywith scriptedAIMessages, writetest_agentic.pywith: (a) onesearch_handbookcall, then a cited answer; (b) two searches (a rephrase) then an answer; (c) an empty result: build a second store from only the internal file, query it with acustomercontext, and check that the tool returns "No matching handbook text." and that the scripted answer says it does not know (a vector store otherwise always returns its nearestkchunks, relevant or not, so deciding to abstain is the model's job and the prompt's, not the retriever's); (d) a model that never stops searching, whichToolCallLimitMiddleware(tool_name="search_handbook", run_limit=3, exit_behavior="end")must stop. Assert on messages and artifacts, not on the scripted wording: the tool message starts with[returns.md], itsartifactholds theDocuments, and for (d) the count of tool calls equals the limit. - Test the access control properly. Extend the lesson's permission test to your new internal file: a
customercontext never getsstaff-escalation.mdin the artifact, astaffcontext does. Add a negative you invent: a query that names the internal file ("what does staff-escalation.md say") must still return nothing from it for a customer, because the filter runs on metadata, not on the query. - Build the two-step variant and compare. Write
two_step.pywith a@dynamic_promptmiddleware that retrieves for the latest human message and puts the chunks in the system prompt (08F.9, 7.2), with no tools. Test withRecordingFakeModel.seen(reset it per test) that the model's first message already contains the retrieved text, and that a greeting ("hi") still triggers a retrieval. Then show that the agentic version does not retrieve for a greeting when the script has the model answer directly. Write three sentences in your notes on which shape suits a FAQ bot and which suits questions that sometimes need two lookups, using 08F.9, 9.1. - Measure retrieval. Write
eval_rag.pyafter the lesson'ss28_retrieval_eval.py(12.2): aCase(question, source, phrase)dataclass, 12 to 15 questions over your handbook (include two the handbook cannot answer and score them separately, since an abstention is not a retrieval hit), andevaluate(retriever, k=3)returning hit rate and MRR. Compare the dense retriever (store.as_retriever(search_kwargs={"k": 3})), the lesson's ownBm25Retriever(08F.9, 6.3) with a lower-casingtokenizefunction (not the archived communityBM25Retriever) and anEnsembleRetriever(retrievers=[bm25, dense], weights=[0.5, 0.5]). Print the misses, not just the averages, and write down what each miss tells you to fix. - Probe an injection. Following 08F.9, 13.1, add one chunk to the store whose text tells the model to ignore its instructions and send customers somewhere else, and write a deterministic
check_answerthat rejects any cited source you did not retrieve and any link that is not already in trusted text. Confirm the system prompt's "treat handbook text as data" line is a partial defence by showing the poisoned chunk still reaches the prompt; then list the controls from 13.2 you would add (write access, allow-lists, per-role tests). - Real providers (optional, needs keys). Illustrative: follow 08F.9, 15.3:
uv add "langchain[openai]", swapBagOfWordsEmbeddings()forOpenAIEmbeddings(model="text-embedding-3-small")and the scripted model forinit_chat_model("openai:gpt-6-luna"), with a new record-manager namespace (a different embedding model needs a fresh namespace, or the ledger will skip chunks that were embedded by the old one: 08F.9, 4.5). Claude has no embedding model, so pair it with another embeddings provider.
Verify it, and what you should see:
uv run pytest -q
uv run python ingest.py
uv run python eval_rag.pyrun 1: {'num_added': 14, 'num_updated': 0, 'num_skipped': 0, 'num_deleted': 0}
run 2: {'num_added': 0, 'num_updated': 0, 'num_skipped': 14, 'num_deleted': 0}
after editing returns.md: {'num_added': 1, 'num_updated': 0, 'num_skipped': 13, 'num_deleted': 1}
retriever hit@3 MRR
dense 0.85 0.66
bm25 tokenized 0.85 0.78
hybrid 0.92 0.80Treat every retrieval number as a demonstration of the method, not a benchmark: the embedding model is a bag-of-words toy with no notion of synonyms, and a dozen questions is a smoke test, not evidence (08F.9, 12.2).
Done when:
uv run pytest -qpasses the six lesson tests plus your agentic, access-control and two-step tests.- Ingest is idempotent: a second run skips everything, an edit replaces exactly the changed chunk, and you can state what
cleanup="incremental"cannot notice. - A customer context cannot retrieve any internal file by any query you tried, asserted on the artifact.
- The retrieval budget stops a never-ending scripted model.
eval_rag.pyprints hit rate and MRR for dense, BM25 and hybrid retrievers over your golden set, with the misses listed and a sentence on each.- Your notes name one control you would add before this faces real users, citing the lesson section.
Stretch ideas:
- Add
multi_query_searchor a reranker (theOverlapRerankerpattern) and measure whether hit rate or MRR moves (08F.9, 10.2, 10.3). - Replace the in-memory record manager with
SQLRecordManageron a SQLite file and rerun ingest across two processes (08F.9, 11.4). - Cache embeddings with
CacheBackedEmbeddingsand show the second ingest embeds nothing (08F.9, 4.4). - Put the golden set in LangSmith as a dataset and run it as an experiment (08F.9, 12.3; needs an account, so illustrative).
- Add a structured final answer (
answer,sources,confident) withresponse_format(08F.6, Part 10) and check that every listed source was retrieved.
Common problems:
ModuleNotFoundError: numpy:InMemoryVectorStoreneeds it on first search, andlangchaindoes not install it.- The edit left two copies of a chunk: you indexed whole documents instead of the split chunks, or
source_id_keyis wrong (08F.9, 11.5). Split before you index. - A deleted file still answers questions:
cleanup="incremental"cannot see a source that is no longer in the batch; use"full"when the folder is the whole corpus, and read the data-loss warning in 11.3 first. - Everything is skipped after you changed the embedding model: the record manager remembers content hashes, not vectors. Use a new namespace.
- The BM25 retriever looks useless: its default tokenizer splits on whitespace, so punctuation and case defeat it. Pass a
preprocess_func(08F.9, 6.3). - The agent tests pass but retrieval quality is bad: the fake model's words and the toy embedding say nothing about real quality. Evaluate with a golden set, ideally against the real embedding model, as a CI threshold.
- The agent searches forever on a real model:
exit_behavior="continue"only blocks the tool; use"end"or add a model-call limit.
Stretch: LangGraph support workflow with persistence, approvals and a subgraph#
Goal: Take the refund workflow from lesson 08F.12 (a cached policy lookup, an approval pause with a typed answer, a retried and time-limited payment call with an idempotency key, and an error handler that routes failures to a person) and turn it into a support workflow you could run for real: add a triage subgraph with a private state key, swap the in-memory checkpointer for a durable SQLite one and prove that a paused case survives a restart, fork a thread from an old checkpoint, and remember a customer preference in the Store. It uses no model at all: nodes are plain Python, the payment gateway is the lesson's FakeGateway, so every check runs with no key. It is deliberately open-ended: the steps give the shape and the traps, and you design the details.
What you'll practise:
- Graph design with
StateGraph, reducers,Commandrouting and conditional edges, and drawing the result (lesson 08F.10, Part 5, Part 6, 10.4, 13.1) - Subgraphs added as nodes, shared versus private keys, the shared-reducer trap and
subgraphs=Truestreaming (lesson 08F.13, 2.2, 2.3) - Interrupts:
interrupt()withresponse_schema,Command(resume=...), the restart-from-the-first-line rule and idempotent side effects (lesson 08F.12, 1.6, 2.4, Part 4) - Failure handling:
RetryPolicy,TimeoutPolicy,CachePolicyand node error handlers (lesson 08F.12, 7.2, 7.5, Part 8, Part 9) - Durable checkpointers:
AsyncSqliteSaver, thread ids, durability modes and the at-least-once rule (lesson 08F.11, 5.2, 4.1, 4.3) - Reading and rewriting history:
get_state,get_state_history, replay and fork, and interrupts that fire again (lesson 08F.11, 2.7, 3.1, 3.2) - Long-term memory in the
Store, reached throughRuntime, and whycontextmust be passed again on resume (lesson 08F.11, 7.7, 08F.12, 6.2) - Testing graphs with no model: a node alone, a path through the graph, the topology (lesson 08F.10, 13.3)
Setup:
uv init langgraph-workflow --bare --python 3.13 && cd langgraph-workflow # first time only
uv add langchain langgraph-checkpoint-sqlite
uv add --dev pytestlangchain brings langgraph, langgraph-checkpoint and langgraph-prebuilt; langgraph-checkpoint-sqlite adds the SQLite savers and SqliteStore (08F.11, Setup). Copy refund_flow.py, refund_demo.py and test_refund_flow.py from 08F.12, Part 11 exactly as printed. No .env, no keys, no model.
Steps:
- Baseline. Run
uv run python refund_demo.pyanduv run pytest -q. The demo's five cases (an auto-approved small refund, a paused big refund the manager approves with a smaller amount, a decline, lost acknowledgements that the idempotency key makes harmless, and a gateway that is down or hangs and routes toneeds_manual_refund) and the five tests are real output in the lesson; yours should match their shape. Read 11.1's design notes before changing anything, and draw the graph withgraph.get_graph().draw_mermaid()(local, no network;draw_mermaid_png()sends your graph structure to a web service by default). - Add a triage subgraph. Create
triage.pywith its own smallStateGraphand aTypedDictstate holdingbody(the customer's message),category,priorityand a private keymatched_rule, built from two or three plain-Python nodes (a rule-based classifier standing in for a model: 08F.6 shows the realwith_structured_outputshape, illustrative until you have a key). Addbody,categoryandpriorityto the parent'sStateinrefund_flow.py, add the compiled subgraph withbuilder.add_node("triage", triage_graph)ahead ofload_policy, and route after it with a conditional edge:category == "refund"goes on toload_policy, anything else goes toclosewith statusrouted_elsewhere. Do not putlog(the parent's append-reducer list) in the subgraph's schema: a shared key with an append reducer duplicates entries (08F.13, 2.3). Instead, let a parent node write the triage result into the log. Then write the experiment as a test: addlogto the subgraph's schema on a scratch copy, predict what the parent'slogwill hold, run it, and note the result. - Prove what the subgraph hides and shows. Test that the parent's final state does not contain
matched_rule, that a plainstream_mode="updates"showstriageas one node, and thatstream(..., stream_mode="updates", subgraphs=True)also shows the inner nodes under atriage:<id>namespace (08F.13, 2.2). Also test the topology: the drawn edges include both routes out oftriage. - Make the checkpointer durable. Change
build_graphto takecheckpointer(and keepInMemorySaveras the default for tests). The nodes are async, so useAsyncSqliteSaver:async with AsyncSqliteSaver.from_conn_string("cases.sqlite") as saver:(08F.11, 5.2). The syncSqliteSaverraisesNotImplementedErrorwith an async graph, and reading state from an async graph uses the async twins (aget_state,aget_state_history). Passdurability="sync"on the refund calls: approvals and irreversible side effects are the case the lesson names for it (08F.11, 4.1). Note that the policy cache is not persisted: only the checkpointer is. - Survive a restart. Write
case_cli.pywith two commands:start <order> <tier> <amount>(runs the case and prints the interrupt payload if it pauses, then exits) andresume <order> <approved> <amount>(opens the same SQLite file in a new process, rebuilds the graph and resumes withCommand(resume={"approved": ..., "amount": ...})on the samethread_id). A big refund started by one process must be finishable by another. Intest_restart.py, approximate the two processes in one test by building two graphs from the same file under atmp_path(the lesson's SQLite samples prove the same thing across two real processes, 08F.11, 4.1 and 5.2) and assert that the second graph seesnext == ("ask_manager",)and finishes with the samestatusas the in-memory run. - Add the
Storeand run-time context. DefineContext(a dataclass withcustomer_id), compile withcontext_schema=Contextand astore=InMemoryStore(), and makecloseread the item with keycontactin the namespace(customer_id, "prefs")throughruntime.store(declareruntime: Runtime[Context]on the node) and log "notify by email" or "notify by phone" accordingly (08F.11, 7.7). Write the preference from a small helper outside the graph, as an application would. Then reproduce the documented bug on purpose: resume the paused big refund withoutcontext=and see whatruntime.contextis, and fix it by routing every call, first call or resume, through one function that rebuilds the context (08F.12, 6.2). Namespaces should include the customer id so one customer can never read another's preference; add a test for that. - Fork a thread. On the in-memory build (as 08F.11, 3.1 does), finish a case, list
get_state_history, and print each snapshot'snextbefore choosing one (do not assume which checkpoint is "beforeissue_refund"). Replay from it withinvoke(None, snapshot.config)and fork withupdate_state(snapshot.config, {...})theninvoke(None, fork_config). Predict first, from theFakeGatewaycode, what happens togateway.callsand togateway.refundswhen you replay a checkpoint beforeissue_refund, and what happens if you fork with a differentapproved_amount(readrefund()closely: it deduplicates on the key), then run it and explain any surprise. Remember that a replay of a checkpoint beforeask_managermakes the interrupt fire again (08F.11, 3.2). Repeating this on the SQLite build needs the async counterpart ofupdate_state; the lessons only show the sync form, so look it up in the API reference rather than guessing. - Test it without a model. Write
test_workflow.pyin the three kinds of 08F.10, 13.3: the triage nodes alone; a path through the whole graph for each of the lesson's five cases plus the two triage routes; and the topology. Keep the lesson's negatives: an invalid manager answer (a negative amount) is refused and the pause survives; lost acknowledgements do not double-refund; a gateway that is down ends inneeds_manual_refundwith no money moved. - Write the ops note. One page: what each node's retry and timeout policy is and why, what the idempotency key is derived from, what a restart loses (the cache) and keeps (the checkpoint), what
durability="sync"costs, what theStoreholds and who can read it, and which of 08F.11's pre-flight checklist items you did not do.
Verify it, and what you should see:
uv run python refund_demo.py # the five lesson cases still behave
uv run python case_cli.py start A-9 standard 480 # pauses and prints the manager payload
uv run python case_cli.py resume A-9 true 300 # a new process finishes the case
uv run pytest -q$ uv run python case_cli.py start A-9 standard 480
paused: {'question': 'Approve this refund?', 'order_id': 'A-9', 'requested': 480.0, 'limit': 100.0}
$ uv run python case_cli.py resume A-9 true 300
status=refunded | log: triage: refund | policy loaded for tier standard | above the limit: manager needed | manager approved 300.00 | refunded 300.00 | case closed with status refundedDone when:
- A paused big refund started in one process is resumed to completion by another, from the SQLite file alone.
- The triage subgraph is a node of the parent with a private key that never reaches the parent's state, and a test shows both that and the
subgraphs=Truestream. - You can show, with a test, the shared-reducer duplication on a scratch copy and the fix in the real graph.
- Replay and fork are demonstrated on a finished thread, with your written prediction of the gateway counts beside what actually happened.
- The
Storepreference is read throughRuntime, a cross-customer read returns nothing, and the resume-without-context bug is reproduced and fixed. - The tests need no model and cover the five lesson cases, both triage routes, the restart and the topology.
Stretch ideas:
- Swap
InMemoryStoreforSqliteStore.from_conn_string(...)and note what the lesson says was and was not verified about it (08F.11, 7.5). - Illustrative, needs a Postgres server: repeat step 4 with
PostgresSaverorAsyncPostgresSaver(08F.11, 5.3) and keep the checkpointer and store in the same database. - Rewrite the payment step as a Functional API
@taskinside an@entrypointand compare resume behaviour (08F.14, Part 3, 4.1). - Add a second approval tier (two sequential approvals above a higher limit) and test the resume map when two interrupts are pending (08F.12, 3.5).
- Drain gracefully on
SIGTERMwithRunControl(08F.12, 10.1) and show a half-run case resumes. - Hosted, needs a free LangSmith account: put the graph behind
langgraph devwith alanggraph.jsonand open it in Studio (11A.5, Part 5).
Common problems:
NotImplementedError: The SqliteSaver does not support async methods: an async graph needsAsyncSqliteSaver, opened withasync with(08F.11, 5.2).- The refund happened twice: the idempotency key is built from something that changes between attempts. Derive it from durable state (the order id), as the lesson does (08F.12, 7.4).
- A side effect ran again after the manager answered: it sits before
interrupt()in the node, and the node restarts from its first line on resume (08F.12, 1.6). - After the approval, the node crashed with
AttributeErroronruntime.context:context=is not saved in the checkpoint; pass it on every call including the resume. - The parent's list is doubled after the subgraph ran: a shared key with an append reducer (08F.13, 2.3).
- An error handler's dict return never reaches
close: a handler that should route must returnCommand(goto=...)(08F.12, 7.5). get_state_historydoes not list threads: it needs athread_id; list threads with.list(None)(oralist(None)) on the saver, passingNone, not{}(08F.11, 2.7).- You changed a node and old threads misbehave: check which graph changes are safe while threads exist (08F.10, 14.1) and 08F.11, 4.6.
Stretch (optional): Multi-agent research desk with tracing and an eval dataset#
Goal: Build a small research desk the LangChain way, then make it observable and measurable: a supervisor create_agent whose tools are two specialist subagents, wrapped as a node inside an outer StateGraph with a deterministic intake, a quality gate that checks every cited URL really exists, and a human publish approval; run it with local tracing so you can read the run as a tree with no LangSmith account; and score it against a small evaluation dataset with plain-function evaluators and a trajectory evaluator. It is the framework counterpart of the pure-Python orchestrator project above, built on 08F.13 and 11A.5 rather than on 08D.3's from-scratch code, and it is open-ended on purpose.
What you'll practise:
- Deciding whether multi-agent earns its place, and which of the five official patterns fits (lesson 08F.13, 1.1, 1.4, Part 8) alongside 08D.3's decision table
- Subagents as tools: what the supervisor sees and does not see, and names that show up in traces (lesson 08F.13, 3.1, 3.2, 3.5)
- A custom workflow around a team with a bounded loop, a deterministic gate and a human approval (lesson 08F.13, Part 6), and interrupts through nested agents (3.8)
- Bounding every loop:
ModelCallLimitMiddleware,ToolCallLimitMiddlewareand the recursion limit that is not a budget (lesson 08F.8, 7.5, 8.12) - Tracing: run names, tags, metadata and
thread_id,tracing_context, and reading a run tree through the recording client (lesson 11A.5, 2.4, 2.5, 2.7) - Datasets, reference outputs and evaluators as plain functions, including trajectory-match modes (lesson 11A.5, 3.1, 3.3, 3.4)
- Testing a multi-agent graph without a model: the path, a valid history, isolation and budgets (lesson 08F.13, Part 9, 11A.5, Part 4)
Setup:
uv init langgraph-research --bare --python 3.13 && cd langgraph-research # first time only
uv add langchain langgraph langsmith
uv add --dev pytest
uv add openevals agentevalsCopy fakes.py from 08F.8, 1.3 (you need FakeToolCallingModel and RecordingModel) and trace_recorder.py from the Setup section of 11A.5. For the corpus, reuse the shape of the first starter project's research_data.py ({url: {"title": ..., "text": ...}}, the Meridian Cycles pages), so the tools here can be plain functions over it. No .env, no keys, no LangSmith account: the recorder is a real langsmith.Client whose HTTP session stores requests and answers with a fake success, so nothing leaves your machine (11A.5, 2.4).
Steps:
- Write the two specialists. In
desk.pymake shared toolssearch_pages(query)andread_page(url)over the corpus (descriptions that say when not to use them;ToolExceptionwith an actionable message for an unknown URL). Buildpricing_agentandsafety_agentwithcreate_agent, each with a uniquename=, its own system prompt that asks for a final message containing the evidence (the supervisor only sees that message), and its own budget:ModelCallLimitMiddleware(run_limit=6, exit_behavior="end")plusToolCallLimitMiddleware(tool_name="read_page", run_limit=3). Each gets a fresh scriptedFakeToolCallingModel. - Write the supervisor. Wrap each specialist in a
@tool("ask_pricing", description=...)or@tool("ask_safety", description=...)function whose description says "pass a complete, self-contained question" and whose body callsagent.invoke({"messages": [{"role": "user", "content": question}]})["messages"][-1].text(08F.13, 3.1). Buildresearch_team = create_agent(model, tools=[ask_pricing, ask_safety], name="research_team", system_prompt=...). Script the supervisor to call both tools in one reply, so the tool node runs them as parallel delegation (08F.13, 3.6). - Wrap it in a workflow. Build the outer
StateGraphof 08F.13, Part 6: aDeskState(MessagesState)withtopic,attemptsandstatus;intake(an empty topic goes straight toENDwith a status, before any model call);research_teamadded as a node so LangGraph can see it;quality_gate, which this time checks something real: parse aSources:line from the final answer and require every URL to exist in your corpus, looping back with a nudge message at most twice; andpublish_review, aninterruptthat carries the draft. Compile with oneInMemorySaveron the outermost graph and always pass athread_idon the outer call, or the pause cannot be found again (08F.13, 3.8). Because the scripted models are one-shot iterators, put the whole build inbuild_desk(scripts)and call it once per run. - Write the scenario scripts. In
scenarios.pydefine scripts as data:good(both specialists, a real URL cited),no_sources(first answer lacksSources:, the gate loops once, the second has it),invented_url(cites a URL that is not in the corpus, which the gate must reject until attempts run out),wrong_specialist(the supervisor asks onlyask_safetyfor a pricing question) andendless(a specialist that keeps callingread_page). Use unique tool-call ids across a script (08F.13, Part 9). - Trace it, locally. Run
goodinsidels.tracing_context(enabled=True, client=Recorder().client)with a config carryingrun_name="research-desk",tags=["research", "dev"],metadata={"app_version": "0.1"}and thethread_id, thenrec.print_tree()(11A.5, 2.4). Write down what you see: the outer nodes (intake,research_team,quality_gate,publish_review), the innermodelandtoolsnodes of the team, and whether the specialist runs appear nested under theask_pricingandask_safetytool runs. Do not assume: print it and record the answer, and if they do not nest, read 08F.7, 4.1 on how config is inherited and decide whether your wrapper should pass it on. Assert in a test that the tags and metadata reach the tool runs, and that a run withtracing_context(enabled=False)sends nothing (11A.5, 2.7). - Write the eval dataset. In
dataset.pywrite 8 to 10 examples in LangSmith's shape:{"inputs": {"topic": ..., "scenario": ...}, "outputs": {"specialists": [...], "sources": [...]}}, whereoutputsare reference outputs the target never sees. Include questions that need only one specialist, one that needs both, one the corpus cannot answer, and an empty topic. Because the models are scripted, each example's inputs name the scenario script to run: be honest in your notes that this dataset tests your workflow and evaluators, not a model. - Write the target and the evaluators.
target(inputs)builds a fresh desk, runs it on a freshthread_idper example (otherwise examples share state through the checkpointer: 11A.5, 3.4), and returns an outputs dict (answer,sources,specialists_called,model_calls,status). Write evaluators as plain functions takinginputs,outputsandreference_outputs(11A.5, 3.3):cites_real_sources(bool),called_expected_specialists(set comparison),within_budget(model calls under a cap) andno_unrequested_publish(status neverpublishedbefore approval). Addcreate_trajectory_match_evaluator(trajectory_match_mode="superset")fromagentevalsover the supervisor's tool calls, building the reference and the actual trajectory in the OpenAI-style message dicts the lesson uses. Unit-test the evaluators on hand-made runs first, before any experiment exists. - Run a local experiment. Write
eval_research.pythat loops over the dataset, callstarget, applies every evaluator and prints a per-example table and a pass rate per metric. Run it for thegoodscripts, then again with thewrong_specialistandinvented_urlvariants swapped in, and show the metrics fall where they should. That before-and-after is whatclient.evaluatedoes server-side, with the experiments compared side by side. - Test the multi-agent wiring. In
test_desk.pywrite the four assertions of 08F.13, Part 9: the path (the supervisor's tool calls equal the expected list, not its wording), a valid history (every AI tool call has aToolMessagewith the same id), isolation (aRecordingModelon a specialist saw only the supervisor's brief, and the unused specialist's model was never called), and budgets (theendlessscript stops through the middleware limit and the run still ends with a message, not an exception). Add the approval test: the run pauses atpublish_reviewthrough the nested agents, andCommand(resume="yes")on the same thread finishes it. - Hosted variant (optional, needs a key and an account). Illustrative: put the dataset in LangSmith with
client.create_dataset(...)andclient.create_examples(...), then runclient.evaluate(target, data="research-desk-v1", evaluators=[...], experiment_prefix="desk-baseline", max_concurrency=4)(11A.5, 3.2, 3.4); swap the scripted models for real ones and add an LLM-as-judge evaluator (3.6). Do not add raw production inputs to a dataset without masking them: datasets keep what you put in them. Know thatupload_results=Falseis not an offline mode (3.5). - Decide honestly. Write a note applying 08F.13's decision table and the four taxes of 08D.3 to this task: would one agent with two tools and a better prompt do the job? Compare lines of code, number of model calls per run (your traces count them) and how readable the trace is, against the pure-Python orchestrator project.
Verify it, and what you should see:
uv run python run_desk.py # a scripted run with a printed trace tree and the approval pause
uv run python eval_research.py # the local experiment table, baseline then the worse variants
uv run pytest -qresearch-desk [chain] tags=['dev', 'research']
intake [chain]
research_team [chain]
model [chain]
tools [chain]
ask_pricing [tool]
ask_safety [tool]
model [chain]
quality_gate [chain]
publish_review [chain]
metric good wrong_specialist invented_url
cites_real_sources 1.00 1.00 0.00
called_expected_specialists 1.00 0.00 1.00
within_budget 1.00 1.00 1.00Done when:
- The desk runs end to end on scripts: intake, a supervisor delegating to two named specialists, a gate that rejects an invented URL, a human approval that pauses through the nested agents and resumes on the same thread.
- Every loop is bounded, and the
endlessscript ends in a clean message through a middleware limit, not through the recursion limit. - A printed run tree shows your outer nodes, and your notes say honestly whether the specialist runs nested under the tool runs and what you did about it.
- The dataset has reference outputs the target never sees, the evaluators are plain functions with their own unit tests, and the experiment table moves in the right direction when you swap in a worse script.
- The four multi-agent assertions (path, history, isolation, budgets) pass, plus the approval test.
- Your decision note answers whether this task needed multi-agent at all, with numbers from your own traces.
Stretch ideas:
- Replace the supervisor with the router of 08F.13, 5.1 (
Sendto specialist nodes, then a synthesis node) and compare the traces and the eval table. Handle the empty-classification case explicitly. - Add a critic as a verifier node with a bounded loop back, giving it different evidence from the drafter (08F.13, Part 8).
- Give one specialist
checkpointer=Trueand show it remembers per thread, then show what two parallel calls to it do (08F.13, 2.6, 3.7). - Stream the desk with
subgraphs=Trueand render a live timeline of which agent is working (08F.14, 9.1). - Read the archived
langgraph-supervisorpackage's example in 08F.13, 7.2 and port it to your desk using the migration table in 7.3. Do not build new work on it. - Hosted, needs keys: run the hosted variant of step 10 and compare the real model's pass rates with your scripted ones: that gap is what the evaluation is for.
Common problems:
StopIterationpartway through a run: the graph made more model calls than you scripted (the gate looped, or a specialist retried). Count the calls your scenario should make, and build fresh models per run.- A dangling tool call error or odd history: a tool call without a matching
ToolMessageid, or two calls with the same id in one script. Use unique ids and assert on valid history. - The nested approval never reaches you: a subagent has its own
checkpointer=, or the outer call has nothread_id. One checkpointer on the outermost graph (08F.13, 3.8). - The supervisor ignores the specialist's evidence: it sees only the specialist's final message; make the specialist's prompt put the evidence there (08F.13, 3.2).
get_state(subgraphs=True)finds nothing for a specialist: it is called inside a tool, so the graph cannot see it; call it from a node if you need its state (08F.13, 2.7).- One failing parallel branch loses the others' results: a super-step is transactional; turn failures into results inside the node (08F.13, 5.4).
- Tracing sends nothing, or everything: the environment variable is read once and cached, and
tracing_contextbeats it in both directions (11A.5, 2.2, 2.7). - Examples leak state into each other during an experiment: they share a
thread_id; use a fresh one per example. - False economy: you added agents to feel advanced. Re-read 08D.3, 1.2 and your own decision note.
Module 08F projects complete. Next: Module 09: Voice & Multimodal Apps.