AI research agent helps builders understand the setup flow, source requirements, and production checks before implementation.
LangGraph is a graph-based orchestration library built on top of LangChain that lets you model agent logic as explicit nodes and edges. Unlike simple chain-based pipelines, it supports cycles, conditional branching, and persistent state — making it well-suited for research agents that need to plan, search, evaluate results, and decide whether to keep digging. This LangGraph research agent tutorial walks through building a working multi-step research agent from scratch, covering the core concepts you need before writing a single line of code.
What You Will Build
The agent in this tutorial accepts a research question, breaks it into sub-queries, retrieves information using a search tool, evaluates whether the results are sufficient, and either returns a synthesized answer or loops back to refine its search. This loop-until-done pattern is where LangGraph’s graph model earns its keep over a linear chain.
Prerequisites
- Python 3.10 or later
- Basic familiarity with LangChain concepts (LLMs, tools, prompts)
- An OpenAI API key or a compatible LLM provider
- LangGraph installed:
pip install langgraph langchain-openai
Core Concepts Before You Start
State
Every LangGraph application revolves around a shared state object — a typed dictionary that flows through every node. Nodes read from it, write to it, and pass it along. For a research agent, state typically holds the original question, accumulated search results, a list of sub-queries, and a flag indicating whether the answer is complete.
Nodes
Nodes are plain Python functions (or runnables) that accept the current state and return a partial update. LangGraph merges the returned dict back into state automatically. Keep each node focused on one responsibility: planning, searching, evaluating, or synthesizing.
Edges and Conditional Edges
Edges connect nodes in sequence. Conditional edges let you route to different nodes based on the current state — for example, looping back to the search node if the evaluator decides the results are insufficient, or proceeding to synthesis if they are good enough.
Step 1 — Define the State Schema
Start by defining a typed state class using Python’s TypedDict:
from typing import TypedDict, List, Optional
class ResearchState(TypedDict):
question: str
sub_queries: List[str]
search_results: List[str]
answer: Optional[str]
sufficient: bool
iterations: int
The sufficient flag and iterations counter are what allow the graph to decide whether to loop or exit. Setting a hard cap on iterations prevents runaway loops in production.
Step 2 — Build the Nodes
Planner Node
The planner takes the original question and generates a list of focused sub-queries using an LLM. Keep the prompt tight — ask for three to five distinct search angles rather than an open-ended list.
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="gpt-4o-mini")
def planner(state: ResearchState) -> dict:
prompt = f"Break this research question into 3 focused search queries:n{state['question']}"
response = llm.invoke(prompt)
queries = [line.strip() for line in response.content.split("n") if line.strip()]
return {"sub_queries": queries, "iterations": state.get("iterations", 0)}
Search Node
The search node iterates over sub-queries and calls a retrieval tool. In this example, a simple wrapper around a web search API or a vector store retriever works. LangGraph does not prescribe a specific tool — use whatever fits your stack.
def searcher(state: ResearchState) -> dict:
results = []
for query in state["sub_queries"]:
# Replace with your actual search tool call
result = my_search_tool.run(query)
results.append(result)
return {"search_results": results}
Evaluator Node
The evaluator asks the LLM whether the accumulated results are sufficient to answer the original question. This is the decision point that drives the loop.
def evaluator(state: ResearchState) -> dict:
context = "n".join(state["search_results"])
prompt = (
f"Question: {state['question']}n"
f"Results so far:n{context}n"
"Are these results sufficient to give a complete answer? Reply YES or NO."
)
response = llm.invoke(prompt)
sufficient = "YES" in response.content.upper()
return {"sufficient": sufficient, "iterations": state["iterations"] + 1}
Synthesizer Node
When the evaluator is satisfied, the synthesizer composes the final answer from accumulated results.
def synthesizer(state: ResearchState) -> dict:
context = "n".join(state["search_results"])
prompt = f"Answer this question using the research below:n{state['question']}nn{context}"
response = llm.invoke(prompt)
return {"answer": response.content}
Step 3 — Assemble the Graph
With nodes defined, wire them together using StateGraph:
from langgraph.graph import StateGraph, END
builder = StateGraph(ResearchState)
builder.add_node("planner", planner)
builder.add_node("searcher", searcher)
builder.add_node("evaluator", evaluator)
builder.add_node("synthesizer", synthesizer)
builder.set_entry_point("planner")
builder.add_edge("planner", "searcher")
builder.add_edge("searcher", "evaluator")
def route_after_eval(state: ResearchState) -> str:
if state["sufficient"] or state["iterations"] >= 3:
return "synthesizer"
return "searcher"
builder.add_conditional_edges("evaluator", route_after_eval)
builder.add_edge("synthesizer", END)
graph = builder.compile()
The conditional edge after the evaluator is the loop mechanism. If results are insufficient and the iteration cap has not been reached, the graph routes back to the searcher. The planner only runs once; subsequent loops reuse the existing sub-queries or you can modify the searcher to refine them based on what was missing.
Step 4 — Run the Agent
initial_state = {
"question": "What are the main approaches to reducing hallucinations in large language models?",
"sub_queries": [],
"search_results": [],
"answer": None,
"sufficient": False,
"iterations": 0,
}
result = graph.invoke(initial_state)
print(result["answer"])
LangGraph’s invoke runs the graph synchronously. For streaming intermediate steps — useful for debugging or building a UI — use graph.stream(initial_state) instead, which yields state snapshots after each node.
Extending the Agent
- Persistent memory: LangGraph supports checkpointers that save state between runs, enabling long-running or resumable research sessions. Current documentation covers SQLite and in-memory checkpointers; verify available backends in the latest release.
- Human-in-the-loop: You can interrupt the graph at any node to request human approval before continuing — useful when the agent is about to make an expensive API call or take an irreversible action.
- Parallel search: LangGraph supports branching to multiple nodes simultaneously, so sub-queries can be dispatched in parallel rather than sequentially.
- Tool binding: Rather than calling tools directly inside nodes, you can bind tools to the LLM using LangChain’s tool-calling interface and let the model decide which tool to invoke at each step.
What to Check Before Production
This tutorial uses a minimal setup to illustrate the pattern. Before deploying a research agent in a real environment, verify a few things. LangGraph’s API surface is actively evolving — check the official documentation at langchain-ai.github.io/langgraph for the current node and edge APIs, as method signatures may have changed since this was written. Evaluate your LLM’s tool-calling reliability on your specific domain before trusting the evaluator’s YES/NO judgment in automated pipelines. Set conservative iteration caps and add timeouts around external tool calls to avoid runaway costs. If your agent accesses external APIs or user data, review the terms of service for each tool and any applicable data handling requirements.
What to Check Before Production
The code samples above are illustrative and based on LangGraph’s publicly documented patterns. Exact import paths, class names, and method signatures should be verified against the current LangGraph release before use. The library is under active development, and breaking changes between minor versions are possible. Teams evaluating LangGraph for production workloads should review the project’s changelog on GitHub and test against a pinned version. Enterprise-specific features such as managed deployment, observability integrations, or access controls are not covered here — consult current LangGraph documentation and LangChain’s commercial offerings for those requirements.