LangGraph 中的应用程序从一个入口点开始,根据执行情况,流程可能会进入一个函数或另一个函数,直到到达END。
1. 状态
**状态(State)**是 LangGraph 的核心概念。它表示流经您应用程序的所有信息。
from typing_extensions import TypedDict
class State(TypedDict):
graph_state: str
状态是用户定义的,因此字段应精心设计,以包含决策过程所需的所有数据!
2. 节点
**节点(Nodes)**是 Python 函数。每个节点:
- 将状态作为输入
- 执行一些操作
- 返回状态的更新
def node_1(state):
print("---Node 1---")
return {"graph_state": state['graph_state'] +" I am"}
def node_2(state):
print("---Node 2---")
return {"graph_state": state['graph_state'] +" happy!"}
def node_3(state):
print("---Node 3---")
return {"graph_state": state['graph_state'] +" sad!"}
例如,节点可以包含:
- LLM 调用:生成文本或做出决策
- 工具调用:与外部系统交互
- 条件逻辑:确定后续步骤
- 人工干预:从用户获取输入
3. 边
**边(Edges)**连接节点并定义通过图的可能路径
import random
from typing import Literal
def decide_mood(state) -> Literal["node_2", "node_3"]:
# Often, we will use state to decide on the next node to visit
user_input = state['graph_state']
# Here, let's just do a 50 / 50 split between nodes 2, 3
if random.random() < 0.5:
# 50% of the time, we return Node 2
return "node_2"
# 50% of the time, we return Node 3
return "node_3"
边可以是:
- 直接的:始终从节点 A 到节点 B
- 有条件的:根据当前状态选择下一个节点
4. 状态图
**状态图(StateGraph)**是包含您整个代理工作流的容器
from IPython.display import Image, display
from langgraph.graph import StateGraph, START, END
# Build graph
builder = StateGraph(State)
builder.add_node("node_1", node_1)
builder.add_node("node_2", node_2)
builder.add_node("node_3", node_3)
# Logic
builder.add_edge(START, "node_1")
builder.add_conditional_edges("node_1", decide_mood)
builder.add_edge("node_2", END)
builder.add_edge("node_3", END)
# Add
graph = builder.compile()