Single logo
  • Courses
  • Blog
  • About
Join free on SkoolJoin free on Skool

Learning path · 6 steps

Agents with LangChain and LangGraph
  1. 1
    What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  2. 2
    Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  3. 3
    LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  4. 4
    Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  5. 5
    Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  6. 6
    A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Agents and MCP

Learning path: Agents with LangChain and LangGraph · Step 6 of 6

A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read

A research agent reads three notes (mrr, ndcg, hit-rate) and writes a cited answer whose last sentence cites [hybrid-search], a note it never opened. Without a check, nothing stops it. A check node compares cited with read, sends the draft back with a fix line, draft 2 cites [hit-rate], problems is [] and the graph ends; max_drafts=2 stops a model that never learns.

Chaand Sheikh

·27 November 2026Agents and MCP

What you will learn

  • Build a research agent as a LangGraph graph: plan, search, read and write nodes
  • Keep the text the agent actually read in state, and check every citation against it
  • Send a bad draft back with a conditional edge and a fix line in the prompt
  • Cap the loop with max_drafts so a model that never fixes its draft still stops

Before you start

  • LangGraph Nodes, Edges and State
  • RAG Prompt Assembly and Citations

A research agent plans, searches, reads and writes an answer with citations. The dangerous part is the citations: a model can cite something it never opened, and the reader can't tell. In this article we build the agent in LangGraph, watch it cite a note it never read, and then add a check node that sends the draft back.

It runs with a stand-in test model and scripted replies, so no key is needed. Put a key in .env and the same graph calls a real model.

The researcher and the editor

Think about how a good report with footnotes gets written. A junior researcher breaks the question into smaller ones, pulls books from the library, reads them, and writes a short report with a footnote on every claim. Then an editor checks each footnote against the books on the desk. If a footnote points to a book nobody opened, the report goes back with a note: fix this.

A citation is a promise. It says "I read this". Something has to check that promise.

The job, as a graph

Plan, search, read, write, check plansearchread writecheckEND cited but not read, drafts < max state.notes = what was actually read cited vs read
One node per step. The check node is the editor; the red edge is the "fix this" note.

The library is six short notes on retrieval metrics: chunking, faithfulness, hit-rate, hybrid-search, mrr and ndcg. Watch the hybrid-search note: it's in the corpus, but the agent never reads it.

Two tools: search and read

"""Two plain-function tools over the local corpus: search and read."""
import re
from pathlib import Path

CORPUS = Path(__file__).with_name("corpus")
STOP = {"what", "does", "do", "is", "a", "an", "the", "when", "how", "i", "my", "to", "of", "and", "should"}


def words(text):
    return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if w not in STOP}


def search(query, k=1):
    """doc ids whose text shares the most words with the query (best first)"""
    q = words(query)
    scored = [(len(q & words(p.read_text("utf-8"))), p.stem) for p in CORPUS.glob("*.md")]
    return [doc for score, doc in sorted(scored, reverse=True)[:k] if score > 0]


def read(doc_id):
    """the full text of one document"""
    return (CORPUS / f"{doc_id}.md").read_text("utf-8")

Versions are pinned in the project: langgraph 1.2.18 and langchain-core 1.7. search scores each note by the words it shares with the query and keeps the best k. There's no vector store here, so every step is easy to follow; ask it "What does MRR measure?" and it returns the mrr note. read returns the full text of one note.

One switch for the model

def get_model(replies):
    """replies = the test model's scripted answers, in call order"""
    if os.getenv("OPENAI_API_KEY"):
        from langchain_openai import ChatOpenAI
        return ChatOpenAI(model=os.getenv("MODEL", "gpt-4o-mini"), temperature=0)
    return GenericFakeChatModel(messages=iter(AIMessage(r) for r in replies))

get_model in models.py is one switch: a real chat model with a key, a test model with scripted replies without one. The scripted replies are the plan (three search questions as a JSON list) and two drafts. Draft 1 cites hybrid-search, the trap. Draft 2 cites hit-rate instead. GenericFakeChatModel hands them back in order, one per call.

The state and the nodes

"""A research agent in LangGraph: plan, search, read, write, check the citations."""
import json
import re
from typing import TypedDict

from langgraph.graph import END, START, StateGraph

from tools import read, search


class Research(TypedDict, total=False):
    question: str
    plan: list[str]
    notes: dict[str, str]          # doc id -> text we actually read
    answer: str
    problems: list[str]            # cited but never read
    drafts: int


def cited(answer):
    return re.findall(r"\[([a-z0-9-]+)\]", answer)


def build_graph(model, check=True, max_drafts=2):
    def plan(state: Research) -> dict:
        prompt = ("Split this question into 2-4 short search questions. "
                  "Reply with a JSON list only.\n" + state["question"])
        return {"plan": json.loads(model.invoke(prompt).content), "drafts": 0}

    def find(state: Research) -> dict:
        found = [doc for q in state["plan"] for doc in search(q)]
        return {"notes": {doc: "" for doc in dict.fromkeys(found)}}

    def read_all(state: Research) -> dict:
        return {"notes": {doc: read(doc) for doc in state["notes"]}}

    def write(state: Research) -> dict:
        notes = "\n\n".join(f"[{doc}]\n{text}" for doc, text in state["notes"].items())
        fix = (f"\nLast time you cited {state['problems']}, which are not in the notes. "
               "Cite only the notes." if state.get("problems") else "")
        prompt = (f"Answer using only these notes. Cite each claim like [doc-id].{fix}\n\n"
                  f"{notes}\n\nQuestion: {state['question']}")
        return {"answer": model.invoke(prompt).content, "drafts": state["drafts"] + 1}

    def check_cites(state: Research) -> dict:
        return {"problems": [c for c in cited(state["answer"]) if c not in state["notes"]]}

    def route(state: Research) -> str:
        return "write" if state["problems"] and state["drafts"] < max_drafts else END

The two fields that matter are notes, the doc id and the text we actually read, and problems, anything cited but never read.

  • plan asks the model for a JSON list of search questions and starts the draft counter at 0.
  • find runs one search per sub-question; read_all fills the notes with the real text.
  • write says "answer using only these notes, cite each claim like [doc-id]". If there were problems last time, it adds a fix line: Last time you cited ..., which are not in the notes. Cite only the notes.
  • check_cites lists every citation that isn't in the notes.
  • route goes back to write while there are problems and the drafts are below max_drafts; otherwise it ends.

First attempt: no check

01_without_check.py builds the same graph with check=False, so it ends right after write:

python 01_without_check.py
plan: ['What does MRR measure?', 'What does nDCG measure?', 'When is hit rate enough?']
read: ['mrr', 'ndcg', 'hit-rate']
answer: Use MRR when people read the top result: it scores one over the position of the first good document [mrr]. Use nDCG when several documents matter and you have graded labels [ndcg]. Hybrid search will also fix your ranking [hybrid-search].
cited but never read: ['hybrid-search']

MRR and nDCG are explained well, with the right citations. But the last sentence cites hybrid-search, and that note was never read. Nothing in the graph stopped it, and a reader who trusts that citation is misled.

The fix: a check node and a loop

    g = StateGraph(Research)
    for name, fn in (("plan", plan), ("search", find), ("read", read_all), ("write", write)):
        g.add_node(name, fn)
    g.add_edge(START, "plan")
    g.add_edge("plan", "search")
    g.add_edge("search", "read")
    g.add_edge("read", "write")
    if check:
        g.add_node("check", check_cites)
        g.add_edge("write", "check")
        g.add_conditional_edges("check", route, ["write", END])
    else:
        g.add_edge("write", END)
    return g.compile()

Plain edges connect plan to write in a straight line. With the check on, write always goes to check, and the conditional edge after check picks write again or the end. max_drafts caps the loop, so a model that keeps getting it wrong can't run forever.

python 02_research_agent.py
plan    {'plan': ['What does MRR measure?', 'What does nDCG measure?', 'When is hit rate enough?'], 'drafts': 0}
search  {'notes': ['mrr', 'ndcg', 'hit-rate']}
read    {'notes': ['mrr', 'ndcg', 'hit-rate']}
write   {'answer': 'Use MRR when people read the top result: it scores one over the position of the first good document [mrr]. Use nDCG when several documents matter and you have graded labels [ndcg]. Hybrid search will also fix your ranking [hybrid-search].', 'drafts': 1}
check   {'problems': ['hybrid-search']}
write   {'answer': 'Use MRR when people read the top result: it scores one over the position of the first good document [mrr]. Use nDCG when several documents matter and you have graded labels [ndcg]. Hit rate is enough when one good document is all the generator needs [hit-rate].', 'drafts': 2}
check   {'problems': []}

One line per node (notes shown as ids). Draft 1, and check finds the problem, hybrid-search. Route sends it back to write, with the fix line in the prompt. Draft 2 cites hit-rate instead, check says problems is an empty list, and route ends the graph. The loop ran write twice, and the final answer cites only notes that were read.

Proof it holds

It isn't tied to one question. python demo.py ask "What is chunking?" reads the chunking note and answers from it with problems: []. And the project's five tests pass. The one that matters most gives the graph a model that never fixes its draft:

def test_the_loop_stops_after_max_drafts():
    state = build_graph(get_model([PLAN, DRAFT_1, DRAFT_1])).invoke({"question": QUESTION})
    assert state["drafts"] == 2 and state["problems"] == ["hybrid-search"]

The graph still stops after two drafts, with the problem still listed. So the loop can't run forever, and whatever calls the agent can see that the answer still has a problem.

Common mistakes

  • Trusting citations because they look right. [hybrid-search] was neatly formatted and completely unsupported.
  • Not keeping what was read. Without notes in state, there's nothing to check citations against.
  • A retry with the same prompt. The fix line tells the model what was wrong; without it, the second draft may repeat the first.
  • A loop with no cap. max_drafts turns "forever" into "two tries, then report the problem".
  • Hiding a failed check. When the cap is hit, keep problems in the final state so the caller can act on it.

Quick recap

Node or edgeJob
planSplit the question into search questions (JSON list)
search, readFind one note per sub-question, keep its real text in notes
writeAnswer from the notes only, cite each claim, apply the fix line
checkList citations that are not in notes
route (conditional edge)Back to write while problems remain and drafts < max_drafts

The same idea, checking each claim against its source, is how you score answers offline: see RAG Generation Metrics.

Try it yourself

Run python demo.py ask with a question of your own. Then set max_drafts to 1 and run the agent again: what does the final state say? Finally, put your key in .env and run the same graph with a real model.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in the learning path Agents with LangChain and LangGraph · step 6 of 6

Previous
Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Related posts

Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It

A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.

What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table

LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.

Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph

A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.

LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways

Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.

On this page

  • The researcher and the editor
  • The job, as a graph
  • Two tools: search and read
  • One switch for the model
  • The state and the nodes
  • First attempt: no check
  • The fix: a check node and a loop
  • Proof it holds
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

Become an AI Engineer: LLMs, RAG, Agents and MCP

Build real AI systems in Python: LLM APIs, RAG, evals, agents and MCP.View on Udemy ↗: Become an AI Engineer: LLMs, RAG, Agents and MCP (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.