Module 08F: Projects

Agents & multimodal4 projects0 of 4 complete

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

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), and support_desk.py as 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.py and test_kb.py (Part 15)
  • From 08F.12: refund_flow.py, refund_demo.py and test_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

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_agent returns 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, and ToolRuntime[Context] so identity comes from your auth layer (lesson 08F.8, 2.2, 3.2)
  • The four remedies for tool failure, and composing ToolErrorMiddleware outside ToolRetryMiddleware (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, the approve/edit/reject decisions and why a checkpointer and a thread_id are 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:

bash
uv init langchain-agents --bare --python 3.13 && cd langchain-agents   # first time only
uv add langchain python-dotenv
uv add --dev pytest

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

  1. Create the data. Make desk_data.py with a BOOKINGS dict (five or six bookings, ids such as BK-1001, each with a customer_id, a hub, a date, a status of confirmed or cancelled and a price), an AVAILABILITY dict (hub then date then number of bikes free), a small FAQ dict (cancel, helmet, deposit), and an empty CANCELLATIONS list 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.
  2. Write the context and the tools. In desk_tools.py define Context as 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]) and cancel_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). Raise ToolException with 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_booking re-checks its preconditions (the booking is yours and still confirmed) after approval, because the world can change while a human decides.
  3. Assemble the agent. In desk_agent.py write build_agent(model, *, fallback_model=None) that returns create_agent(model, tools=[...], middleware=[...], context_schema=Context, checkpointer=InMemorySaver(), name="hire_desk"). Order the middleware as 08F.8, 8.6 and the lesson's build_agent do: PIIMiddleware("email", strategy="redact") first, then ModelCallLimitMiddleware(run_limit=8, exit_behavior="end"), then ToolCallLimitMiddleware(tool_name="cancel_booking", run_limit=1), then a @dynamic_prompt function that greets the customer by request.runtime.context.customer_name (9.1), then your two custom hooks (steps 4 and 5), then ToolErrorMiddleware(on_error=...) outside ToolRetryMiddleware(max_retries=2, tools=["search_faq"], on_failure="error"), and HumanInTheLoopMiddleware last, with cancel_booking allowed approve, edit and reject and the three read tools set to False. Your on_error function returns the message for ToolException and a generic "internal error, offer to escalate" string for anything else, so internals never reach the model.
  4. 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 fixed AIMessage when the last human message asks for something outside hire-desk topics or contains an obvious injection phrase. Without can_jump_to the jump has no edge, so declare it.
  5. Add an audit and policy hook. Write a @wrap_tool_call function that appends (tool name, arguments) to an AUDIT list before calling handler(request), and that refuses a cancel_booking for a booking whose date is less than 24 hours away by returning a ToolMessage(status="error") with the same tool_call_id instead 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.
  6. Script the scenarios. In run_desk.py build a fresh FakeToolCallingModel per scenario (the script is an iterator and is consumed once) with a calls(*items) helper like the lesson's. Four scenarios: (a) look up a booking, then cancel it, pausing for approval and resuming with Command(resume={"decisions": [{"type": "approve"}]}); (b) ask about another customer's booking; (c) a message containing an email address, using RecordingModel to show what the model actually received; (d) the injection phrase. Invoke with config={"configurable": {"thread_id": ...}}, context=Context(...) and version="v2", which returns an object with .interrupts and .value.
  7. Test every guard. Write test_desk.py in the style of 08F.8, 12.2, one calls()-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; an edit decision 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 by ModelCallLimitMiddleware; the late-cancellation refusal never reaches the tool body. Test the negatives first: they are the rules that must hold.
  8. Prove the fallback and the retry order. Following 08F.8, 8.10, add ModelFallbackMiddleware(fallback_model) when fallback_model is given, with a DownModel subclass of FakeToolCallingModel that raises ConnectionError in _generate, and assert the backup answers. Then count attempts on a dead primary with ModelRetryMiddleware listed before and after the fallback middleware, and write one sentence on why the order changes the count.
  9. Live mode (optional, needs a key). Illustrative: uv add langchain-openai, put OPENAI_API_KEY in .env, call load_dotenv() and pass "openai:gpt-6-luna" to build_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:

bash
uv run python run_desk.py
uv run pytest -q
Example output · illustrative5 lines
(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.py runs the four scenarios keylessly and the approval pause resumes through Command(resume=...) on the same thread_id.
  • test_desk.py passes 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_booking is 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)) as support_desk.py does, 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_call hook that calls request.override(model=...) (08F.8, 9.2), and test which model each call used.
  • Return a typed final answer with response_format and 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:

  • StopIteration or "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).
  • ValidationError when you call a tool directly: tool.invoke(...) does not inject a ToolRuntime. Test through the agent, or call tool.func(...) with a stand-in runtime object (08F.8, 12.1).
  • A guard's jump is ignored: the hook returned jump_to but was not declared with can_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 in interrupt_on does 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 with ModelCallLimitMiddleware or use exit_behavior="end".
  • Redaction does not apply to tool results or model output: apply_to_output and apply_to_tool_results are off by default (08F.8, 8.11).
  • Retries multiply side effects: ToolRetryMiddleware calls the tool again, so restrict it with tools=[...] to read-only tools (08F.8, 4.5).

Starter

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, RecursiveCharacterTextSplitter with chunk_size, chunk_overlap and add_start_index (lesson 08F.9, 2.2, 3.1)
  • The Embeddings interface and InMemoryVectorStore, 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 through ToolRuntime, and ToolCallLimitMiddleware as a budget (lesson 08F.9, 8.1, 8.3, 8.4)
  • Two-step RAG as @dynamic_prompt middleware 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:

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

  1. Run the lesson's module unchanged. Run uv run pytest -q. The six tests in test_kb.py should pass before you touch anything: a second ingest changes nothing, an edit leaves one version of a chunk, a deleted file leaves the index under cleanup="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.
  2. Grow the handbook. Write make_handbook.py that writes the five HANDBOOK files plus three of your own into a handbook/ folder: repairs.md (turnaround and cost), sizing.md (how to choose a tent size) and staff-escalation.md (discount authority limits: an internal document). Add staff-escalation.md to INTERNAL_SOURCES in kb.py. Keep each file short, with ## headings so the splitter has structure.
  3. Ingest from the folder, twice. Write ingest.py that builds a store with new_store(BagOfWordsEmbeddings()), creates InMemoryRecordManager(namespace="handbook/bag-of-words/v1") (call create_schema()), and runs build_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 in returns.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.
  4. Script four agentic trajectories. Using make_agent(model, store) from kb.py and a RecordingFakeModel from rag_fakes.py with scripted AIMessages, write test_agentic.py with: (a) one search_handbook call, 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 a customer context, 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 nearest k chunks, 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, which ToolCallLimitMiddleware(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], its artifact holds the Documents, and for (d) the count of tool calls equals the limit.
  5. Test the access control properly. Extend the lesson's permission test to your new internal file: a customer context never gets staff-escalation.md in the artifact, a staff context 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.
  6. Build the two-step variant and compare. Write two_step.py with a @dynamic_prompt middleware that retrieves for the latest human message and puts the chunks in the system prompt (08F.9, 7.2), with no tools. Test with RecordingFakeModel.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.
  7. Measure retrieval. Write eval_rag.py after the lesson's s28_retrieval_eval.py (12.2): a Case(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), and evaluate(retriever, k=3) returning hit rate and MRR. Compare the dense retriever (store.as_retriever(search_kwargs={"k": 3})), the lesson's own Bm25Retriever (08F.9, 6.3) with a lower-casing tokenize function (not the archived community BM25Retriever) and an EnsembleRetriever(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.
  8. 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_answer that 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).
  9. Real providers (optional, needs keys). Illustrative: follow 08F.9, 15.3: uv add "langchain[openai]", swap BagOfWordsEmbeddings() for OpenAIEmbeddings(model="text-embedding-3-small") and the scripted model for init_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:

bash
uv run pytest -q
uv run python ingest.py
uv run python eval_rag.py
Example output · illustrative8 lines
run 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.80

Treat 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 -q passes 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.py prints 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_search or a reranker (the OverlapReranker pattern) and measure whether hit rate or MRR moves (08F.9, 10.2, 10.3).
  • Replace the in-memory record manager with SQLRecordManager on a SQLite file and rerun ingest across two processes (08F.9, 11.4).
  • Cache embeddings with CacheBackedEmbeddings and 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) with response_format (08F.6, Part 10) and check that every listed source was retrieved.

Common problems:

  • ModuleNotFoundError: numpy: InMemoryVectorStore needs it on first search, and langchain does not install it.
  • The edit left two copies of a chunk: you indexed whole documents instead of the split chunks, or source_id_key is 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

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, Command routing 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=True streaming (lesson 08F.13, 2.2, 2.3)
  • Interrupts: interrupt() with response_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, CachePolicy and 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 through Runtime, and why context must 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:

bash
uv init langgraph-workflow --bare --python 3.13 && cd langgraph-workflow   # first time only
uv add langchain langgraph-checkpoint-sqlite
uv add --dev pytest

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

  1. Baseline. Run uv run python refund_demo.py and uv 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 to needs_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 with graph.get_graph().draw_mermaid() (local, no network; draw_mermaid_png() sends your graph structure to a web service by default).
  2. Add a triage subgraph. Create triage.py with its own small StateGraph and a TypedDict state holding body (the customer's message), category, priority and a private key matched_rule, built from two or three plain-Python nodes (a rule-based classifier standing in for a model: 08F.6 shows the real with_structured_output shape, illustrative until you have a key). Add body, category and priority to the parent's State in refund_flow.py, add the compiled subgraph with builder.add_node("triage", triage_graph) ahead of load_policy, and route after it with a conditional edge: category == "refund" goes on to load_policy, anything else goes to close with status routed_elsewhere. Do not put log (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: add log to the subgraph's schema on a scratch copy, predict what the parent's log will hold, run it, and note the result.
  3. Prove what the subgraph hides and shows. Test that the parent's final state does not contain matched_rule, that a plain stream_mode="updates" shows triage as one node, and that stream(..., stream_mode="updates", subgraphs=True) also shows the inner nodes under a triage:<id> namespace (08F.13, 2.2). Also test the topology: the drawn edges include both routes out of triage.
  4. Make the checkpointer durable. Change build_graph to take checkpointer (and keep InMemorySaver as the default for tests). The nodes are async, so use AsyncSqliteSaver: async with AsyncSqliteSaver.from_conn_string("cases.sqlite") as saver: (08F.11, 5.2). The sync SqliteSaver raises NotImplementedError with an async graph, and reading state from an async graph uses the async twins (aget_state, aget_state_history). Pass durability="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.
  5. Survive a restart. Write case_cli.py with two commands: start <order> <tier> <amount> (runs the case and prints the interrupt payload if it pauses, then exits) and resume <order> <approved> <amount> (opens the same SQLite file in a new process, rebuilds the graph and resumes with Command(resume={"approved": ..., "amount": ...}) on the same thread_id). A big refund started by one process must be finishable by another. In test_restart.py, approximate the two processes in one test by building two graphs from the same file under a tmp_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 sees next == ("ask_manager",) and finishes with the same status as the in-memory run.
  6. Add the Store and run-time context. Define Context (a dataclass with customer_id), compile with context_schema=Context and a store=InMemoryStore(), and make close read the item with key contact in the namespace (customer_id, "prefs") through runtime.store (declare runtime: 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 without context= and see what runtime.context is, 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.
  7. 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's next before choosing one (do not assume which checkpoint is "before issue_refund"). Replay from it with invoke(None, snapshot.config) and fork with update_state(snapshot.config, {...}) then invoke(None, fork_config). Predict first, from the FakeGateway code, what happens to gateway.calls and to gateway.refunds when you replay a checkpoint before issue_refund, and what happens if you fork with a different approved_amount (read refund() closely: it deduplicates on the key), then run it and explain any surprise. Remember that a replay of a checkpoint before ask_manager makes the interrupt fire again (08F.11, 3.2). Repeating this on the SQLite build needs the async counterpart of update_state; the lessons only show the sync form, so look it up in the API reference rather than guessing.
  8. Test it without a model. Write test_workflow.py in 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 in needs_manual_refund with no money moved.
  9. 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 the Store holds 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:

bash
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
Example output · illustrative4 lines
$ 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 refunded

Done 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=True stream.
  • 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 Store preference is read through Runtime, 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 InMemoryStore for SqliteStore.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 PostgresSaver or AsyncPostgresSaver (08F.11, 5.3) and keep the checkpointer and store in the same database.
  • Rewrite the payment step as a Functional API @task inside an @entrypoint and 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 SIGTERM with RunControl (08F.12, 10.1) and show a half-run case resumes.
  • Hosted, needs a free LangSmith account: put the graph behind langgraph dev with a langgraph.json and open it in Studio (11A.5, Part 5).

Common problems:

  • NotImplementedError: The SqliteSaver does not support async methods: an async graph needs AsyncSqliteSaver, opened with async 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 AttributeError on runtime.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 return Command(goto=...) (08F.12, 7.5).
  • get_state_history does not list threads: it needs a thread_id; list threads with .list(None) (or alist(None)) on the saver, passing None, 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)

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, ToolCallLimitMiddleware and 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:

bash
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 agentevals

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

  1. Write the two specialists. In desk.py make shared tools search_pages(query) and read_page(url) over the corpus (descriptions that say when not to use them; ToolException with an actionable message for an unknown URL). Build pricing_agent and safety_agent with create_agent, each with a unique name=, 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") plus ToolCallLimitMiddleware(tool_name="read_page", run_limit=3). Each gets a fresh scripted FakeToolCallingModel.
  2. 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 calls agent.invoke({"messages": [{"role": "user", "content": question}]})["messages"][-1].text (08F.13, 3.1). Build research_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).
  3. Wrap it in a workflow. Build the outer StateGraph of 08F.13, Part 6: a DeskState(MessagesState) with topic, attempts and status; intake (an empty topic goes straight to END with a status, before any model call); research_team added as a node so LangGraph can see it; quality_gate, which this time checks something real: parse a Sources: line from the final answer and require every URL to exist in your corpus, looping back with a nudge message at most twice; and publish_review, an interrupt that carries the draft. Compile with one InMemorySaver on the outermost graph and always pass a thread_id on 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 in build_desk(scripts) and call it once per run.
  4. Write the scenario scripts. In scenarios.py define scripts as data: good (both specialists, a real URL cited), no_sources (first answer lacks Sources:, 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 only ask_safety for a pricing question) and endless (a specialist that keeps calling read_page). Use unique tool-call ids across a script (08F.13, Part 9).
  5. Trace it, locally. Run good inside ls.tracing_context(enabled=True, client=Recorder().client) with a config carrying run_name="research-desk", tags=["research", "dev"], metadata={"app_version": "0.1"} and the thread_id, then rec.print_tree() (11A.5, 2.4). Write down what you see: the outer nodes (intake, research_team, quality_gate, publish_review), the inner model and tools nodes of the team, and whether the specialist runs appear nested under the ask_pricing and ask_safety tool 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 with tracing_context(enabled=False) sends nothing (11A.5, 2.7).
  6. Write the eval dataset. In dataset.py write 8 to 10 examples in LangSmith's shape: {"inputs": {"topic": ..., "scenario": ...}, "outputs": {"specialists": [...], "sources": [...]}}, where outputs are 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.
  7. Write the target and the evaluators. target(inputs) builds a fresh desk, runs it on a fresh thread_id per 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 taking inputs, outputs and reference_outputs (11A.5, 3.3): cites_real_sources (bool), called_expected_specialists (set comparison), within_budget (model calls under a cap) and no_unrequested_publish (status never published before approval). Add create_trajectory_match_evaluator(trajectory_match_mode="superset") from agentevals over 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.
  8. Run a local experiment. Write eval_research.py that loops over the dataset, calls target, applies every evaluator and prints a per-example table and a pass rate per metric. Run it for the good scripts, then again with the wrong_specialist and invented_url variants swapped in, and show the metrics fall where they should. That before-and-after is what client.evaluate does server-side, with the experiments compared side by side.
  9. Test the multi-agent wiring. In test_desk.py write 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 a ToolMessage with the same id), isolation (a RecordingModel on a specialist saw only the supervisor's brief, and the unused specialist's model was never called), and budgets (the endless script stops through the middleware limit and the run still ends with a message, not an exception). Add the approval test: the run pauses at publish_review through the nested agents, and Command(resume="yes") on the same thread finishes it.
  10. Hosted variant (optional, needs a key and an account). Illustrative: put the dataset in LangSmith with client.create_dataset(...) and client.create_examples(...), then run client.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 that upload_results=False is not an offline mode (3.5).
  11. 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:

bash
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 -q
Example output · illustrative15 lines
research-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.00

Done 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 endless script 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 (Send to 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=True and 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=True and render a live timeline of which agent is working (08F.14, 9.1).
  • Read the archived langgraph-supervisor package'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:

  • StopIteration partway 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 ToolMessage id, 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 no thread_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_context beats 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.

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