LangGraph 介绍
TIP
LangGraph 是一个构建有状态、多步骤 AI 工作流的框架,支持循环、条件分支和复杂的状态管理。
与 LangChain 的区别
LangChain 线性链式执行,LangGraph 图结构支持循环。
安装
bash
pip install langgraph核心概念
- State:工作流的共享状态
- Node:图中的节点,执行具体操作
- Edge:节点之间的连接
最简单的图
python
from langgraph.graph import StateGraph, END
from typing import TypedDict
class AgentState(TypedDict):
messages: list[str]
def node_a(state: AgentState):
return {"messages": state["messages"] + ["A处理了"]}
def node_b(state: AgentState):
return {"messages": state["messages"] + ["B处理了"]}
graph = StateGraph(AgentState)
graph.add_node("a", node_a)
graph.add_node("b", node_b)
graph.set_entry_point("a")
graph.add_edge("a", "b")
graph.add_edge("b", END)
app = graph.compile()
result = app.invoke({"messages": ["开始"]})
print(result["messages"])