LangGraph是一个用于构建有状态的、多步骤智能体工作流的框架。它通过"图"将LLM调用、工具使用、逻辑判断等节点连接起来,形成可控、可观测的复杂应用程序。
🧠 LangGraph 三大典型应用场景与代码示例
场景一:自主智能体(ReAct模式)
这是最常见的模式,智能体循环进行"思考-行动-观察",直到完成任务。
python
# 简化的自主智能体(ReAct模式)核心结构示例
from langgraph.graph import StateGraph, END
from typing import TypedDict
# 1. 定义贯穿整个工作流的共享状态
class AgentState(TypedDict):
question: str # 用户问题
thought: str # LLM的思考过程
action: str # 决定采取的行动(如调用工具)
action_input: str # 行动的输入参数
observation: str # 执行行动后的观察结果
answer: str # 最终答案
# 2. 定义各个节点(函数)
def llm_decision_node(state: AgentState):
"""LLM决策节点:分析当前状态,决定下一步行动"""
# 这里调用LLM,根据state['question']和state['observation']决定是调用工具还是直接回答
# 模拟决策:如果问题涉及计算,就调用计算器工具
if "calculate" in state['question'].lower():
return {"action": "calculator", "action_input": state['question']}
else:
return {"action": "respond", "answer": "I can answer this directly."}
def tool_node(state: AgentState):
"""工具执行节点:执行具体的工具调用"""
if state['action'] == 'calculator':
# 这里模拟调用一个计算工具,实际可能调用API或本地函数
result = eval(state['action_input'].replace("calculate", "")) # 仅为示例,实际勿用eval
return {"observation": f"The calculation result is {result}"}
return {"observation": "No tool executed"}
def response_node(state: AgentState):
"""响应节点:生成最终回答"""
return {"answer": f"Based on my actions, the final answer is: {state.get('observation', 'N/A')}"}
# 3. 构建图工作流
workflow = StateGraph(AgentState)
workflow.add_node("llm_agent", llm_decision_node)
workflow.add_node("tool", tool_node)
workflow.add_node("respond", response_node)
# 4. 设置边(决定流程走向)
workflow.set_entry_point("llm_agent")
workflow.add_conditional_edges(
"llm_agent",
# 根据LLM决策节点的输出,路由到下一个节点
lambda x: "tool" if x.get("action") == "calculator" else "respond",
{"tool": "tool", "respond": "respond"}
)
workflow.add_edge("tool", "llm_agent") # 执行工具后,返回LLM进行下一步思考
workflow.add_edge("respond", END)
# 5. 编译并运行
app = workflow.compile()
result = app.invoke({"question": "Please calculate 123 + 456"})
print(result["answer"])
这个流程体现了自主智能体典型的"思考-行动"循环,可以用下图概括:
是
否
用户问题
"初始状态"
"LLM决策节点
分析并决定下一步"
"是否需要
调用工具?"
"工具执行节点
执行具体操作"
"响应节点
生成最终答案"
输出结果
场景二:多智能体协作系统
LangGraph可以轻松协调多个各司其职的智能体共同完成任务。
python
# 多智能体协作系统核心架构示例
from langgraph.graph import StateGraph
from typing import TypedDict
class MultiAgentState(TypedDict):
problem: str
specialist_type: str # 当前由哪位专家处理
analysis: str
plan: str
final_answer: str
def planner_agent(state: MultiAgentState):
"""规划智能体:分析问题,决定派发给哪个专家"""
problem = state['problem']
if "code" in problem:
return {"specialist_type": "coder", "plan": "This is a coding task."}
elif "math" in problem:
return {"specialist_type": "mathematician", "plan": "This is a math problem."}
else:
return {"specialist_type": "generalist", "plan": "This is a general question."}
def coder_agent(state: MultiAgentState):
"""编码专家智能体"""
return {"analysis": f"As a coder, I'll solve: {state['problem']}"}
def mathematician_agent(state: MultiAgentState):
"""数学专家智能体"""
return {"analysis": f"As a mathematician, I'll analyze: {state['problem']}"}
def general_agent(state: MultiAgentState):
"""通用智能体"""
return {"analysis": f"As a generalist, I'll handle: {state['problem']}"}
def synthesizer_agent(state: MultiAgentState):
"""综合智能体:汇总各专家结果,形成最终答案"""
return {"final_answer": f"Based on {state['specialist_type']}'s analysis: {state.get('analysis', '')}"}
# 构建协作图
workflow = StateGraph(MultiAgentState)
workflow.add_node("planner", planner_agent)
workflow.add_node("coder", coder_agent)
workflow.add_node("mathematician", mathematician_agent)
workflow.add_node("generalist", general_agent)
workflow.add_node("synthesizer", synthesizer_agent)
workflow.set_entry_point("planner")
# 根据规划者的决策,路由到不同的专家
workflow.add_conditional_edges(
"planner",
lambda x: x['specialist_type'],
{"coder": "coder", "mathematician": "mathematician", "generalist": "generalist"}
)
workflow.add_edge("coder", "synthesizer")
workflow.add_edge("mathematician", "synthesizer")
workflow.add_edge("generalist", "synthesizer")
workflow.add_edge("synthesizer", END)
场景三:带人工审核的复杂工作流
LangGraph支持"人在回路",允许在关键节点引入人工审核。
python
# 带有人工审核节点的工作流示例
def content_generation_node(state):
"""内容生成节点"""
return {"draft": "Generated content draft..."}
def human_review_node(state):
"""人工审核节点(这里需要暂停等待人工输入)"""
# 在实际应用中,这里会暂停流程,等待用户在UI上审核
# 模拟人工批准
human_feedback = "APPROVED" # 或 "REJECTED"
return {"review_status": human_feedback, "feedback": "Looks good!"}
def revision_node(state):
"""修订节点"""
return {"revised_content": "Content revised based on feedback."}
def approval_node(state):
"""批准发布节点"""
return {"final_content": state.get('revised_content', state.get('draft')), "status": "PUBLISHED"}
workflow = StateGraph()
workflow.add_node("generate", content_generation_node)
workflow.add_node("human_review", human_review_node)
workflow.add_node("revise", revision_node)
workflow.add_node("approve", approval_node)
workflow.set_entry_point("generate")
workflow.add_edge("generate", "human_review")
# 根据人工审核结果决定流程走向
workflow.add_conditional_edges(
"human_review",
lambda x: "approve" if x.get("review_status") == "APPROVED" else "revise",
{"approve": "approve", "revise": "revise"}
)
workflow.add_edge("revise", "human_review") # 修订后返回人工再次审核
workflow.add_edge("approve", END)
🔄 MCP、A2A与LangGraph核心对比
理解了LangGraph的应用后,我们可以将其与之前讨论的MCP和A2A放在一个完整的智能体技术栈中对比:
| 维度 | MCP (模型上下文协议) | A2A (智能体协作协议) | LangGraph (智能体编排框架) |
|---|---|---|---|
| 核心定位 | 工具调用协议:标准化AI模型与外部工具的交互方式。 | 智能体协作协议 :定义智能体间发现、通信和协作的接口规范。 | 工作流编排引擎 :用于构建、运行和管理有状态智能体应用 的实现框架。 |
| 解决的核心问题 | 让AI能安全、标准化地使用各种外部功能(如数据库、API)。 | 让多个专业智能体能发现彼此、对话、分工协作,形成团队。 | 如何具体实现一个(或多个)智能体的复杂决策逻辑、状态管理和执行流程。 |
| 核心概念 | Host, Client, Server, Tools, Resources |
技能清单、智能体间通信协议、任务委托 | 图 、状态 、节点 、边 、检查点 |
| 工作层级 | 协议层:定义数据交换格式和通信标准。 | 架构/协议层:定义系统组件间的交互模式。 | 应用实现层:提供具体的库和API来编写代码。 |
| 相互关系 | LangGraph智能体的某个"工具节点",可以通过MCP Client 来调用MCP Server提供的工具。 | LangGraph是实现A2A协作模式的绝佳底层引擎之一。你可以用LangGraph的图来定义智能体间的路由、对话和任务传递逻辑。 | 在LangGraph构建的多智能体系统中,每个子智能体都可以通过MCP来增强自身能力。 |
| 类比 | 智能手机的充电接口协议 (如USB-C):定义了如何安全、高效地为各种手机供电的规范。 | 公司的部门协作章程:定义了市场部、研发部如何提交需求、开会协同的规则。 | 公司的项目经理和项目管理软件:负责具体规划任务、跟进进度、协调资源、确保项目按流程完成。 |
💎 总结与关系梳理
你可以这样理解它们在构建AI系统时的角色:
- MCP 是你的智能体获取"超能力"(使用工具)的标准方式。它解决了"手"和"脚"的问题。
- A2A 是你设计一个多智能体团队如何组织的蓝图。它解决了"团队结构"和"协作规则"的问题。
- LangGraph 是你动手搭建这个智能体或团队"大脑"和"神经系统"的施工工具包。它解决了"具体如何实现"的问题。
在实际技术栈中,它们完全互补 :你可以使用 LangGraph 作为核心引擎 ,按照 A2A 的协作理念 来设计多智能体图,图中的每个智能体在需要行动时,通过 MCP 协议去调用丰富的外部工具。
如果你有一个具体的业务场景(例如智能客服、自动化数据分析),我很乐意帮你分析如何结合这三者来设计架构。