在这个LangGraph示例中,多个顺序节点的处理机制展示了工作流的线性执行过程:通过定义两个独立的节点函数(first_note和second_node),每个节点负责处理状态的不同部分,然后使用add_edge方法将它们按顺序连接起来,形成一条从入口点到出口点的执行路径。这种设计使得复杂任务可以分解为多个简单的步骤,每个节点都可以独立开发和测试,同时保持整个工作流的清晰性和可维护性。
from typing import TypedDict
from langgraph.graph import StateGraph
class AgentState(TypedDict):
name: str
age: str
final: str
def first_note(state: AgentState) -> AgentState:
"""This is the first node of our sequence"""
state["final"] = f"Hi {state["name"]}"
return state
def second_node(state: AgentState) -> AgentState:
"""This is the second node of our sequence"""
state["final"] = state["final"] + f", you are {state["age"]} years old!"
return state
graph = StateGraph(AgentState)
graph.add_node("first_note", first_note)
graph.add_node("second_node", second_node)
graph.set_entry_point("first_note")
graph.add_edge("first_note", "second_node")
graph.set_finish_point("second_node")
app = graph.compile()
from IPython.display import Image, display
display(Image(app.get_graph().draw_mermaid_png()))
answers = app.invoke({"name": "Alex", "age": "25"})
print(answers["final"])
运行结果:
Hi Alex, you are 25 years old!
add_edge 是 LangGraph 中用于连接节点的核心方法,它定义了工作流中节点之间的执行顺序。
关键特点
- 顺序控制: 指定节点执行的先后顺序
- 线性流程: 从源节点到目标节点的单向连接
- 状态传递: 自动将状态从一个节点传递到下一个节点