开源智能体平台Idun-Agent-Platform:从架构设计到生产部署全解析
2026/5/10 8:58:16
LangGraph 与 LangChain 是深度协同、互补增强的关系。LangGraph 并不是取代 LangChain,而是在其基础上扩展了复杂控制流的能力,使得开发者可以构建更强大、灵活的 AI 应用(尤其是智能体系统)。以下是它们如何协同工作的详细说明:
LangChain 提供了基础组件:
fromlangchain_openaiimportChatOpenAIfromlangchain_core.toolsimporttoolfromlangchain_core.messagesimportHumanMessagefromlanggraph.graphimportStateGraph,MessagesState# 1. 使用 LangChain 定义工具和模型@tooldefsearch(query:str)->str:return"北京今天的天气晴朗。"llm=ChatOpenAI(model="gpt-4o")llm_with_tools=llm.bind_tools([search])# 2. 在 LangGraph 节点中调用 LangChain 组件defagent_node(state:MessagesState):messages=state["messages"]response=llm_with_tools.invoke(messages)return{"messages":[response]}# 3. 用 LangGraph 编排(支持工具调用循环)workflow=StateGraph(MessagesState)workflow.add_node("agent",agent_node)workflow.set_entry_point("agent")workflow.add_conditional_edges("agent",# LangChain 的工具调用路由逻辑lambdax:"tools"ifx["messages"][-1].tool_callselseEND,)workflow.add_node("tools",ToolNode([search]))workflow.add_edge("tools","agent")app=workflow.compile()这就实现了经典的 ReAct Agent 循环:思考 → 调用工具 → 观察 → 再思考。
LangGraph 支持持久化状态(通过 checkpointer),可与 LangChain 的记忆机制结合:
fromlanggraph.checkpoint.memoryimportMemorySaver memory=MemorySaver()app=workflow.compile(checkpointer=memory)# 带线程 ID 的对话(类似 LangChain 的 Conversation ID)config={"configurable":{"thread_id":"user_123"}}result=app.invoke({"messages":[HumanMessage("你好")]},config)这使得多轮对话状态可跨请求保留,与 LangChain 的 ConversationBufferMemory 思路一致,但更强大(支持任意状态结构)。
客服机器人:
LangChain 处理意图识别 + 知识库检索,LangGraph 控制“澄清 → 查询 → 确认 → 结束”流程。
数据分析 Agent:
LangChain 调用 Python REPL 工具,LangGraph 实现“生成代码 → 执行 → 验证结果 → 修正”的循环。
多智能体系统:
每个智能体用 LangChain 构建,LangGraph 协调它们之间的消息传递和任务分配。