Velamuvi AIAcademy
LangGraph

Lesson 11 of 11 · Advanced

Project: Research Agent

Build a research agent in LangGraph: a planner, parallel workers with Send, a reducer, a writer, a citation check and human review, checkpointed and streamed.

  • 8 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Combine planning, parallel workers, writing, checking and human review in one graph
  • Plan sub-questions with structured output and cap the fan-out
  • Run research workers in parallel with Send and collect findings with a reducer
  • Check citations in code before a person reviews the report
  • Pause for approval, revise with feedback, and resume on the same thread

What you'll build

A research agent that answers a policy question for a (made-up) city council: “Should Riverton build more protected bike lanes?” It must:

  • Break the question into focused sub-questions.
  • Research them in parallel, from a document library, with citations.
  • Write a short report that keeps the citations.
  • Check every citation in code.
  • Pause for a person to approve or request changes, and revise until approved.

It uses nearly every lesson of this course: state and reducers (2), conditional edges (3), model nodes with structured output (4), checkpoints (6), interrupts (7), streaming (8) and Send (10).

The design

NodeKindJob
planModel, structured outputSplit the question into at most 4 sub-questions
researchModel + search tool, run once per sub-question with SendAnswer one sub-question from the library, with a citation
writeModelCombine findings into a report, applying any reviewer feedback
check_citationsCodeFlag citations that aren't in the library
human_reviewInterruptApprove, or send feedback back to write

The flow in plain Python

First, the shape of the run with stand-ins for the model calls, including a writer slip that the citation check catches:

Try it yourselfPython
import re

# The research agent's flow in plain Python, with simple stand-ins for the model calls.
LIBRARY = {
    "safety-2025": "After Riverton added protected bike lanes on Main Street, cyclist injuries there fell by 41% in two years.",
    "costs-2025": "Protected lanes cost Riverton about 1.2 million euros per kilometre, including new kerbs and signals.",
    "shops-survey": "In a survey of 80 Main Street shops, 62% reported the same or higher sales after the lanes opened.",
    "traffic-study": "Car journey times on Main Street rose by about 2 minutes at peak hours after one car lane was removed.",
    "bus-timetable": "Route 4 buses run every 15 minutes in the city centre.",
}
STOP = {"how", "did", "do", "the", "a", "what", "of", "on", "in", "and", "by", "after", "per", "about"}
def words(t):
    return {w[:-1] if len(w) > 3 and w.endswith("s") else w for w in re.findall(r"[a-z]+", t.lower()) if w not in STOP}
def search(q):
    return max(LIBRARY, key=lambda d: len(words(q) & words(LIBRARY[d])))

plan = ["How did protected bike lanes affect cyclist injuries?", "What do protected lanes cost per kilometre?",
        "How did the lanes affect shop sales?", "How did the lanes affect car journey times?"]   # planner stand-in
findings = [f"{LIBRARY[search(q)]} [{search(q)}]" for q in plan]                               # parallel workers
report = " ".join(findings) + " [traffic-2019]"                     # a writer slip: a source nobody found

cited = set(re.findall(r"\[([\w-]+)\]", report))
unknown, unused = sorted(cited - set(LIBRARY)), sorted(set(LIBRARY) - cited)
print(f"Plan: {len(plan)} sub-questions -> {len(findings)} findings")
print("Cited:", sorted(cited))
print("Unknown citations (block the report):", unknown)
print("Library documents not used:", unused)

The report cited traffic-2019, which isn't in the library: the kind of plausible-looking citation models sometimes invent. A set difference finds it instantly.

The LangGraph version

import operator, re
from typing import Annotated, TypedDict
from pydantic import BaseModel, Field
from langchain.chat_models import init_chat_model
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, Send, interrupt

# ---------- A small library of sample documents (about a made-up city) ----------
LIBRARY = {
    "safety-2025": "After Riverton added protected bike lanes on Main Street, cyclist injuries there fell by 41% in two years.",
    "costs-2025": "Protected lanes cost Riverton about 1.2 million euros per kilometre, including new kerbs and signals.",
    "shops-survey": "In a survey of 80 Main Street shops, 62% reported the same or higher sales after the lanes opened.",
    "traffic-study": "Car journey times on Main Street rose by about 2 minutes at peak hours after one car lane was removed.",
    "bus-timetable": "Route 4 buses run every 15 minutes in the city centre.",
}
STOP = {"how", "did", "do", "does", "the", "a", "what", "of", "on", "in", "and", "by", "after", "per", "about"}

def words(text: str) -> set[str]:
    ws = re.findall(r"[a-z]+", text.lower())
    return {w[:-1] if len(w) > 3 and w.endswith("s") else w for w in ws if w not in STOP}   # crude plural fix

def search(query: str, k: int = 2) -> list[str]:            # a stand-in for a real search tool
    scored = sorted(((len(words(query) & words(t)), d) for d, t in LIBRARY.items()), reverse=True)
    return [d for s, d in scored[:k] if s > 0]

model = init_chat_model("anthropic:MODEL_NAME", temperature=0)

class Plan(BaseModel):
    subquestions: list[str] = Field(description="2 to 4 focused questions to research", max_length=4)

# ---------- State ----------
class State(TypedDict):
    question: str
    subquestions: list[str]
    findings: Annotated[list[str], operator.add]
    report: str
    feedback: str
    status: str

# ---------- Nodes ----------
def plan(state: State) -> dict:
    p = model.with_structured_output(Plan).invoke(f"Break this research question into sub-questions: {state['question']}")
    return {"subquestions": p.subquestions[:4]}                     # cap the fan-out in code too

def assign(state: State) -> list[Send]:
    return [Send("research", {"subquestion": q}) for q in state["subquestions"]]

def research(task: dict) -> dict:
    docs = search(task["subquestion"])
    context = "\n".join(f"[{d}] {LIBRARY[d]}" for d in docs)
    answer = model.invoke(f"Using only these documents, answer in one sentence and cite the "
                          f"document ID in brackets.\nQuestion: {task['subquestion']}\n{context}").content
    return {"findings": [answer]}

def write(state: State) -> dict:
    notes = "\n".join(state["findings"])
    report = model.invoke(f"Write a short report answering: {state['question']}\nUse only these findings and keep "
                          f"their citations:\n{notes}\nReviewer feedback: {state.get('feedback') or 'none'}").content
    return {"report": report}

def check_citations(state: State) -> dict:                          # code, not a model
    cited = set(re.findall(r"\[([\w-]+)\]", state["report"]))
    unknown = sorted(cited - set(LIBRARY))
    return {"status": f"citations checked: {len(cited)} sources" + (f", UNKNOWN: {unknown}" if unknown else "")}

def human_review(state: State) -> Command:
    decision = interrupt({"report": state["report"], "status": state["status"]})
    if decision["action"] == "approve":
        return Command(update={"status": "approved"}, goto=END)
    return Command(update={"feedback": decision["feedback"]}, goto="write")   # revise with feedback

# ---------- Graph ----------
builder = StateGraph(State)
for name, fn in [("plan", plan), ("research", research), ("write", write),
                 ("check_citations", check_citations), ("human_review", human_review)]:
    builder.add_node(name, fn)
builder.add_edge(START, "plan")
builder.add_conditional_edges("plan", assign, ["research"])
builder.add_edge("research", "write")
builder.add_edge("write", "check_citations")
builder.add_edge("check_citations", "human_review")
graph = builder.compile(checkpointer=InMemorySaver())

# ---------- Run it ----------
config = {"configurable": {"thread_id": "bike-lanes-report"}}
question = "Should Riverton build more protected bike lanes?"
for step in graph.stream({"question": question, "findings": []}, config, stream_mode="updates"):
    for node, update in step.items():
        if node == "__interrupt__":
            print("PAUSED for review:", update[0].value["status"])
        else:
            print(f"{node}: {update}")

print("\n--- A reviewer asks for a change ---")
for step in graph.stream(Command(resume={"action": "revise", "feedback": "End with a clear recommendation."}),
                         config, stream_mode="updates"):
    for node, update in step.items():
        print("PAUSED for review" if node == "__interrupt__" else f"{node}: {update}")

print("\n--- Approved ---")
final = graph.invoke(Command(resume={"action": "approve"}), config)
print(final["status"])
print(final["report"])
Output
plan: {'subquestions': ['How did protected bike lanes affect cyclist injuries?', 'What do protected lanes cost per kilometre?', 'How did the lanes affect shop sales?', 'How did the lanes affect car journey times?']}
research: {'findings': ['Cyclist injuries on Main Street fell by 41% in two years [safety-2025].']}
research: {'findings': ['Car journeys took about 2 minutes longer at peak hours [traffic-study].']}
research: {'findings': ['They cost about 1.2 million euros per kilometre [costs-2025].']}
research: {'findings': ['62% of shops reported the same or higher sales [shops-survey].']}
write: {'report': 'Protected lanes cut cyclist injuries on Main Street by 41% [safety-2025] and cost about 1.2 million euros per kilometre [costs-2025]. Most shops saw the same or higher sales [shops-survey], while car journeys took about 2 minutes longer at peak hours [traffic-study].'}
check_citations: {'status': 'citations checked: 4 sources'}
PAUSED for review: citations checked: 4 sources

--- A reviewer asks for a change ---
human_review: {'feedback': 'End with a clear recommendation.'}
write: {'report': 'Protected lanes cut cyclist injuries on Main Street by 41% [safety-2025] and cost about 1.2 million euros per kilometre [costs-2025]. Most shops saw the same or higher sales [shops-survey], while car journeys took about 2 minutes longer at peak hours [traffic-study]. Recommendation: build more protected lanes on the busiest cycling streets first, and keep monitoring car journey times.'}
check_citations: {'status': 'citations checked: 4 sources'}
PAUSED for review

--- Approved ---
approved
Protected lanes cut cyclist injuries on Main Street by 41% [safety-2025] and cost about 1.2 million euros per kilometre [costs-2025]. Most shops saw the same or higher sales [shops-survey], while car journeys took about 2 minutes longer at peak hours [traffic-study]. Recommendation: build more protected lanes on the busiest cycling streets first, and keep monitoring car journey times.

How it works

  1. Planning. with_structured_output(Plan) returns a list of sub-questions. The schema allows at most 4, and the node slices to 4 anyway, so a planner that gets carried away can't start 20 workers.
  2. Parallel research. assign returns one Send per sub-question; the four research runs happen in parallel (notice they finished in a different order from the plan). Each searches the library, gets the matching documents and asks the model for a one-sentence answer with a citation. The operator.add reducer collects all four findings.
  3. Writing. write waits for every worker, then turns the findings into a report. Its prompt includes the reviewer's feedback, or “none” on the first draft.
  4. Citation check. Code extracts every [source] and compares it with the library. Its status goes to the reviewer with the report.
  5. Human review. interrupt pauses the thread with the report and status. Resuming with revise returns a Command that stores the feedback and goes back to write; resuming with approve ends the run.
  6. Checkpointing. Every step is saved on the thread bike-lanes-report, which is what makes pausing for review, possibly for days, safe.

Common mistakes

Practice exercise

Write the citation checker that runs before the human review: unknown sources must block the report, and unused sources are worth a look.

Your solutionPython
import re
library = {"safety-2025", "costs-2025", "shops-survey", "traffic-study"}
report = ("Injuries fell by 41% [safety-2025]. Lanes cost 1.2M EUR per km [costs-2025]. "
          "Sales held up [shops-survey]. Residents love them [poll-2024].")

# Find every citation in square brackets with re.findall(r"\[([\w-]+)\]", report).
# Print the sorted list of cited IDs that are NOT in the library, then the sorted list of
# library IDs that were never cited.
Knowledge check

Why does the research agent compile with a checkpointer?

Summary

  • The agent is a graph of plan, parallel research (with Send), write, check_citations and human_review.
  • Structured output plans sub-questions; cap the fan-out in schema and code.
  • A reducer collects parallel findings; code checks citations before people review.
  • interrupt and Command implement approve-or-revise; a checkpointer keeps the thread safe while it waits.
  • Streaming updates show progress at every step.

Course complete

You can now build stateful applications with LangGraph: define state with reducers, route with conditional edges and Command, build tool-calling agents, persist and resume threads with checkpointers, pause for human decisions with interrupt, stream progress and tokens, compose graphs from subgraphs, run multi-agent designs with supervisors and Send, and combine them into a research agent with checks and human review.

Finished reading? Tick it off to track your progress.