Detailed interpretation of LangGraph research assistant case
📋 Case Overview
This case shows how to use LangGraph to build an intelligent research assistant system that can:
- Automatically generate multiple professional analysts based on research topics
- Each analyst conducts in-depth interviews on specific subtopics
- Perform multiple interviews in parallel to improve efficiency
- Finally integrate all interviews into a complete research report
Core technical points
- Human-in-the-Loop (Human-in-the-Loop): Users can review and modify the generated analyst team
- Structured Output: Use Pydantic models to ensure consistent data format
- Sub-picture nesting: The interview process is embedded in the main picture as an independent sub-picture
- Parallel Execution (Map-Reduce): Run multiple interviews simultaneously using the
Send()API - Checkpoint mechanism: supports interrupting and resuming the execution process
🗺️ Overall architecture diagram
用户输入研究主题
↓
┌─────────────────────────────────────────┐
│ 第一阶段:生成分析师团队 │
├─────────────────────────────────────────┤
│ create_analysts → human_feedback │
│ ↑ ↓ │
│ └────────────────┘ │
│ (可循环修改直到满意) │
└─────────────────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ 第二阶段:并行执行访谈(Map) │
├─────────────────────────────────────────┤
│ 分析师1 → 访谈子图 → 生成章节 │
│ 分析师2 → 访谈子图 → 生成章节 │
│ 分析师3 → 访谈子图 → 生成章节 │
│ (所有访谈同时进行) │
└─────────────────────────────────────────┘
↓
┌─────────────────────────────────────────┐
│ 第三阶段:汇总报告(Reduce) │
├─────────────────────────────────────────┤
│ write_introduction ┐ │
│ write_report ├→ finalize_report │
│ write_conclusion ┘ │
└─────────────────────────────────────────┘
↓
最终报告📚 Detailed explanation of code segments
Part 1: Define the data structure
class Analyst(BaseModel):
affiliation: str # 所属机构
name: str # 姓名
role: str # 角色
description: str # 描述What it does: This is a Pydantic model that defines the standard format for "analysts".
Why is it important?
- Using a structured data model ensures a consistent format for LLM output
- The
@propertydecorator creates thepersonaproperty, combining all the information into a string - LangGraph can automatically validate data based on this model
Part 2: Generating Analysts (First Figure)
Status definition
class GenerateAnalystsState(TypedDict):
topic: str # 研究主题
max_analysts: int # 最大分析师数量
human_analyst_feedback: str # 用户反馈
analysts: List[Analyst] # 生成的分析师列表Key Concept: State is the core concept in LangGraph. It is like a "shared memory" that transfers data between nodes.
Node function
1. create_analysts node
def create_analysts(state: GenerateAnalystsState):
# 使用 structured_output 确保 LLM 返回符合 Perspectives 格式的数据
structured_llm = llm.with_structured_output(Perspectives)
# 构建系统提示词
system_message = analyst_instructions.format(
topic=topic,
human_analyst_feedback=human_analyst_feedback,
max_analysts=max_analysts
)
# 调用 LLM 生成分析师
analysts = structured_llm.invoke([SystemMessage(...)])
return {"analysts": analysts.analysts}Technical Highlights:
with_structured_output()forces LLM to return JSON conforming to thePerspectivesmodel- Prompt words include topics, user feedback and quantity limits
- The returned dictionary will update the
analystsfield in the status
2. human_feedback node
def human_feedback(state: GenerateAnalystsState):
pass # 空操作节点**Why do we need empty nodes? **
- This is an "interrupt point"
- When execution reaches this point, the graph will pause and wait for user input.
- Users can modify the status through
graph.update_state()
3. should_continue conditional edge
def should_continue(state: GenerateAnalystsState):
human_analyst_feedback = state.get('human_analyst_feedback', None)
if human_analyst_feedback:
return "create_analysts" # 有反馈,重新生成
return END # 无反馈,结束Logic explanation:
- Check if there is
human_analyst_feedbackin the status - If there is → go back to
create_analystsand regenerate - If not → end this phase
Graph construction
builder = StateGraph(GenerateAnalystsState)
builder.add_node("create_analysts", create_analysts)
builder.add_node("human_feedback", human_feedback)
# 边的连接
builder.add_edge(START, "create_analysts")
builder.add_edge("create_analysts", "human_feedback")
builder.add_conditional_edges("human_feedback", should_continue,
["create_analysts", END])
# 编译图
graph = builder.compile(
interrupt_before=['human_feedback'], # 在此节点前中断
checkpointer=memory # 使用内存保存状态
)Key Mechanism:
interrupt_beforecauses the graph to pause beforehuman_feedbackcheckpointersaves execution status and supports recoveryconditional_edgesdetermines the next step based on the function return value
Part Three: Executive Interview (Sub-Picture)
Interview status
class InterviewState(MessagesState):
max_num_turns: int # 最大对话轮数
context: Annotated[list, operator.add] # 检索到的文档
analyst: Analyst # 当前分析师
interview: str # 访谈记录
sections: list # 生成的章节NOTE: context: Annotated[list, operator.add]
Annotatedspecifies how to merge statesoperator.addmeans the new context will be appended to the existing list- This way multiple search results can be accumulated
Core node
1. generate_question - Analyst question
def generate_question(state: InterviewState):
analyst = state["analyst"]
messages = state["messages"]
# 构建系统提示
system_message = question_instructions.format(goals=analyst.persona)
# LLM 根据分析师的角色生成问题
question = llm.invoke([SystemMessage(content=system_message)] + messages)
return {"messages": [question]}Workflow:
- Get the analyst’s persona
- Combine the conversation history to generate the next question
- The question will be appended to the message list
2. search_web and search_wikipedia - Parallel Search
def search_web(state: InterviewState):
# 将对话转换为搜索查询
structured_llm = llm.with_structured_output(SearchQuery)
search_query = structured_llm.invoke([search_instructions] + state['messages'])
# 使用 Tavily 搜索
search_docs = tavily_search.invoke(search_query.search_query)
# 格式化结果
formatted_search_docs = "\n\n---\n\n".join([
f'<Document href="{doc["url"]}"/>\n{doc["content"]}\n</Document>'
for doc in search_docs
])
return {"context": [formatted_search_docs]}Technical Details:
- First use LLM to refine conversations into search queries
- Call external search tools (Tavily/Wikipedia)
- Formatted into documents with source annotations -The returned context will be automatically merged into the state
3. generate_answer - expert answer
def generate_answer(state: InterviewState):
analyst = state["analyst"]
messages = state["messages"]
context = state["context"] # 检索到的所有文档
# 构建包含上下文的提示
system_message = answer_instructions.format(
goals=analyst.persona,
context=context
)
# 生成答案
answer = llm.invoke([SystemMessage(content=system_message)] + messages)
answer.name = "expert" # 标记消息来源
return {"messages": [answer]}RAG Mode:
- Use the retrieved context as a source of knowledge
- LLM answers questions based on these documents
- Include citations in the answer (e.g. [1], [2])
4. route_messages - routing logic
def route_messages(state: InterviewState, name: str = "expert"):
messages = state["messages"]
max_num_turns = state.get('max_num_turns', 2)
# 统计专家回答的次数
num_responses = len([
m for m in messages
if isinstance(m, AIMessage) and m.name == name
])
# 达到上限则保存访谈
if num_responses >= max_num_turns:
return 'save_interview'
# 检查是否包含结束语
last_question = messages[-2]
if "Thank you so much for your help" in last_question.content:
return 'save_interview'
return "ask_question" # 继续提问Control logic:
- Limit the number of interview rounds to prevent infinite loops
- Detection end signal (thank you)
- Decide whether to continue asking questions or end the interview
5. write_section - generate sections
def write_section(state: InterviewState):
interview = state["interview"]
context = state["context"]
analyst = state["analyst"]
system_message = section_writer_instructions.format(
focus=analyst.description
)
section = llm.invoke([
SystemMessage(content=system_message),
HumanMessage(content=f"Use this source to write your section: {context}")
])
return {"sections": [section.content]}Report Generation:
- Based on interviews and retrieved documents
- Generate structured Markdown chapters
- Includes abstract and source citations
Subgraph construction
interview_builder = StateGraph(InterviewState)
# 添加所有节点
interview_builder.add_node("ask_question", generate_question)
interview_builder.add_node("search_web", search_web)
interview_builder.add_node("search_wikipedia", search_wikipedia)
interview_builder.add_node("answer_question", generate_answer)
interview_builder.add_node("save_interview", save_interview)
interview_builder.add_node("write_section", write_section)
# 关键:并行搜索
interview_builder.add_edge(START, "ask_question")
interview_builder.add_edge("ask_question", "search_web")
interview_builder.add_edge("ask_question", "search_wikipedia") # 同时触发
interview_builder.add_edge("search_web", "answer_question")
interview_builder.add_edge("search_wikipedia", "answer_question")
# 条件路由
interview_builder.add_conditional_edges("answer_question", route_messages,
['ask_question', 'save_interview'])
interview_builder.add_edge("save_interview", "write_section")
interview_builder.add_edge("write_section", END)Execution process:
ask_question
├─→ search_web ──┐
└─→ search_wikipedia ──┤
↓
answer_question
↓
┌──────────────┴──────────────┐
↓ ↓
ask_question save_interview
(继续循环) ↓
write_section
↓
ENDPart 4: Main Picture - Map-Reduce Mode
Main state
class ResearchGraphState(TypedDict):
topic: str
max_analysts: int
human_analyst_feedback: str
analysts: List[Analyst]
sections: Annotated[list, operator.add] # 累积所有章节
introduction: str
content: str
conclusion: str
final_report: strinitiate_all_interviews - Map steps
def initiate_all_interviews(state: ResearchGraphState):
human_analyst_feedback = state.get('human_analyst_feedback')
if human_analyst_feedback:
return "create_analysts" # 返回修改分析师
# 关键:使用 Send() API 并行启动多个子图
else:
topic = state["topic"]
return [
Send("conduct_interview", {
"analyst": analyst,
"messages": [HumanMessage(
content=f"So you said you were writing an article on {topic}?"
)]
})
for analyst in state["analysts"]
]The magic of the Send() API:
- Create a separate instance of the interview subgraph for each analyst
- All interviews executed in parallel
- The
sectionsoutput of each subgraph is automatically merged into the main state
Analogy:
- Just like a manager sending multiple employees to different locations for research at the same time
- Each employee works independently and reports the results at the end
- Manager consolidates all reports
Reduce steps
1. write_report - Integrate chapters
def write_report(state: ResearchGraphState):
sections = state["sections"] # 包含所有分析师的章节
topic = state["topic"]
# 将所有章节合并成一个字符串
formatted_str_sections = "\n\n".join([f"{section}" for section in sections])
# LLM 整合成连贯的报告主体
system_message = report_writer_instructions.format(
topic=topic,
context=formatted_str_sections
)
report = llm.invoke([
SystemMessage(content=system_message),
HumanMessage(content="Write a report based upon these memos.")
])
return {"content": report.content}2. write_introduction / write_conclusion
def write_introduction(state: ResearchGraphState):
sections = state["sections"]
formatted_str_sections = "\n\n".join([f"{section}" for section in sections])
instructions = intro_conclusion_instructions.format(
topic=topic,
formatted_str_sections=formatted_str_sections
)
intro = llm.invoke([instructions, HumanMessage(content="Write the report introduction")])
return {"introduction": intro.content}3. finalize_report - Assemble final report
def finalize_report(state: ResearchGraphState):
content = state["content"]
# 清理和分离来源部分
if content.startswith("## Insights"):
content = content.strip("## Insights")
if "## Sources" in content:
content, sources = content.split("\n## Sources\n")
# 组装完整报告
final_report = (
state["introduction"] + "\n\n---\n\n" +
content + "\n\n---\n\n" +
state["conclusion"]
)
if sources:
final_report += "\n\n## Sources\n" + sources
return {"final_report": final_report}Main image construction
builder = StateGraph(ResearchGraphState)
# 第一阶段:生成分析师
builder.add_node("create_analysts", create_analysts)
builder.add_node("human_feedback", human_feedback)
# 第二阶段:执行访谈(子图)
builder.add_node("conduct_interview", interview_builder.compile())
# 第三阶段:生成报告
builder.add_node("write_report", write_report)
builder.add_node("write_introduction", write_introduction)
builder.add_node("write_conclusion", write_conclusion)
builder.add_node("finalize_report", finalize_report)
# 流程控制
builder.add_edge(START, "create_analysts")
builder.add_edge("create_analysts", "human_feedback")
builder.add_conditional_edges("human_feedback", initiate_all_interviews,
["create_analysts", "conduct_interview"])
# 关键:并行生成介绍、结论和主体
builder.add_edge("conduct_interview", "write_report")
builder.add_edge("conduct_interview", "write_introduction")
builder.add_edge("conduct_interview", "write_conclusion")
# 汇总
builder.add_edge(["write_conclusion", "write_report", "write_introduction"],
"finalize_report")
builder.add_edge("finalize_report", END)
# 编译
graph = builder.compile(
interrupt_before=['human_feedback'],
checkpointer=memory
)🔑 Core technology analysis
1. Human-in-the-Loop
Implementation:
graph = builder.compile(interrupt_before=['human_feedback'], checkpointer=memory)Workflow:
- The graph execution is paused before reaching
human_feedback - The user modifies the status through
graph.update_state() - Continue to execute
graph.stream(None, thread)
Practical Application:
# 第一次运行
for event in graph.stream(initial_input, thread):
pass # 在 human_feedback 前停止
# 用户审核并反馈
graph.update_state(thread, {
"human_analyst_feedback": "Add a startup CEO"
}, as_node="human_feedback")
# 继续运行
for event in graph.stream(None, thread):
pass # 重新生成分析师2. Send() API - Dynamic Parallelism
Traditional way vs Send():
Traditional way (static):
builder.add_edge("node_a", "node_b")
builder.add_edge("node_a", "node_c")
# 必须预先知道有多少个节点Send() method (dynamic):
def dynamic_dispatch(state):
return [
Send("subgraph", {"input": item})
for item in state["items"] # 数量在运行时确定
]
builder.add_conditional_edges("dispatcher", dynamic_dispatch)This case application:
- Number of analysts determined by user input and LLM
- Each analyst corresponds to an independent instance of the interview subgraph
- All interviews run simultaneously, greatly improving efficiency
3. Subgraph
**Why use subplots? **
- Encapsulate complex logic (interview process)
- Reusable (each analyst reuses the same process)
- State isolation (each interview has independent message history)
Integration method:
# 子图
interview_graph = interview_builder.compile()
# 嵌入主图
builder.add_node("conduct_interview", interview_graph)Status transfer:
- The main picture passes the initial state to the sub-picture through
Send() - The
sectionsoutput of the sub-image is automatically merged into the main image state
4. Structured output
Pydantic model + with_structured_output():
class Analyst(BaseModel):
name: str
role: str
# ... 其他字段
structured_llm = llm.with_structured_output(Perspectives)
result = structured_llm.invoke(messages) # 自动验证和解析Advantages:
- Ensure consistent data format
- Automatic type checking
- Easy to follow up
5. Checkpointer
Function:
- Save the status of each node after execution
- Support interrupt and resume
- Implement time travel debugging
How to use:
memory = MemorySaver()
graph = builder.compile(checkpointer=memory)
# 使用 thread_id 标识会话
thread = {"configurable": {"thread_id": "1"}}
graph.stream(input, thread)
# 查看当前状态
state = graph.get_state(thread)
# 恢复执行
graph.stream(None, thread)💡 Best Practices and Tips
1. Control LLM output format
Issue: LLM output format is unstable
Solution:
# 定义严格的 Pydantic 模型
class Output(BaseModel):
field1: str = Field(description="详细描述")
field2: int
# 强制结构化输出
structured_llm = llm.with_structured_output(Output)
result = structured_llm.invoke(prompt) # 保证符合 Output 格式2. Loop control
Problem: The dialogue may loop infinitely
Solution:
def route_messages(state):
max_turns = state.get('max_num_turns', 2)
current_turns = count_turns(state['messages'])
if current_turns >= max_turns:
return 'end_node'
if detect_end_signal(state['messages']):
return 'end_node'
return 'continue_node'3. Merge the results of parallel nodes
Using Annotated:
from typing import Annotated
import operator
class State(TypedDict):
results: Annotated[list, operator.add] # 自动追加Effect:
- Node A returns
{"results": [1, 2]} - Node B returns
{"results": [3, 4]} - Final state:
{"results": [1, 2, 3, 4]}
4. Prompt word project
Layering Tips:
# 系统级指令
system_prompt = """You are an expert. Follow these rules:
1. Rule 1
2. Rule 2
"""
# 角色级指令
role_prompt = f"Your role: {analyst.persona}"
# 任务级指令
task_prompt = "Answer this question: ..."
# 组合
llm.invoke([
SystemMessage(content=system_prompt),
SystemMessage(content=role_prompt),
HumanMessage(content=task_prompt)
])🎯 Practical suggestions
For beginners
Understand a single node first
- Starting from
create_analysts - Test each function individually
- Starting from
Build the diagram step by step
- Build the simplest linear graph first -Add conditional edges and loops
Make good use of visualization
pythongraph.get_graph().draw_mermaid_png()Debugging with LangSmith
- View the input and output of each node
- Trace LLM calls
For advanced use
Optimize Parallelism
- Identify nodes that can be parallelized
- Dynamic distribution using
Send()
Cost Control
- Use smaller models for routing
- Cache duplicate LLM calls
Error handling
pythondef safe_node(state): try: return process(state) except Exception as e: return {"error": str(e)}Extended search sources
- Add more search tools
- Integrate local document library
📌 Summary
This case is a comprehensive demonstration of LangGraph, showing:
Architecture design
- Hierarchical structure: main picture + sub-picture
- Clear Responsibilities: Each node only does one thing
- Flexible Control: Conditional Routing + Loop Detection
Technical Points
- Structured Output: Ensure data quality
- Human-machine collaboration: human intervention at key decision points
- Parallel Execution: Improve system efficiency
- Checkpoint mechanism: supports interruption recovery
Application value
- Customizable: Easily adjust analyst type, search source, report format
- Extensible: add new nodes and functions
- Production Level: complete error handling and status management
🚀 Further study suggestions
Modify case
- Change research topic
- Adjust the number and types of analysts
- Use different LLM models
Extended functions
- Add chart generation
- Integrate more data sources
- Implement multi-language support
Optimize performance
- Implement result caching
- Use streaming output
- Add rate limit
In-depth principles
- Study the message passing mechanism of LangGraph
- Understand the atomicity of status updates
- Learn advanced routing strategies
🎤 In-depth understanding: the core role of the Interview subgraph in the system
Interview sub-picture is the "heart" of the entire research assistant system, which is responsible for the most critical knowledge acquisition task. From a system architecture perspective, it plays three roles:
First, it is the engine of knowledge production. By simulating the "analyst-expert" dialogue mode, the Interview subgraph transforms abstract research topics into concrete and in-depth knowledge content. This multi-round dialogue mechanism (ask_question → search → answer → ask_question) realizes progressive knowledge mining. Each round of dialogue builds on the previous round and ultimately forms valuable research chapters.
Secondly, it is the basic unit of parallelization architecture. Through the Send() API, the system can start multiple Interview instances at the same time, and each instance runs independently without interfering with each other. This design allowed interviews with the 3 analysts to be completed within the same time frame rather than being performed serially. The state-isolated nature of subgraphs ensures that each analyst has an independent conversation history and context, avoiding information confusion.
Finally, it is a Map phase implementation of the Map-Reduce pattern. Each Interview subgraph receives an analyst as input and outputs a structured research section. These chapters are automatically aggregated into the main graph state through Annotated[list, operator.add], providing raw materials for the subsequent Reduce stages (write_report, write_introduction, write_conclusion). This clear input and output interface allows subgraphs to be seamlessly integrated into larger systems.
From a technical implementation point of view, the Interview subgraph also shows several important modes of LangGraph: RAG retrieval enhancement (providing factual basis for answers through search_web and search_wikipedia), loop control (preventing infinite conversations through route_messages), message role management (distinguishing the speeches of analysts and experts). The combination of these modes makes Interview not just a simple question and answer process, but a complete, controllable, and high-quality knowledge production pipeline.
Final words: The power of LangGraph is that it allows you to build complex AI systems like building blocks. Although this research assistant example is complex, each component is simple. Once you master these basic building blocks, the application possibilities are endless!