Skip to content

LangGraph 节点与边

TIP

节点是图的基本执行单元,边定义了节点之间的连接关系。

节点

python
def llm_node(state: AgentState):
    response = llm.invoke(state["input"])
    return {"messages": state["messages"] + [response]}

def tool_node(state: AgentState):
    result = tools[state["next_tool"]].run(state["tool_input"])
    return {"observations": [result]}

边类型

python
# 普通边
graph.add_edge("node_a", "node_b")

# 条件边
def should_continue(state):
    if state.get("error"):
        return "error_handler"
    return "continue"

graph.add_conditional_edges(
    "llm_node",
    should_continue,
    {"continue": "tool_node", "error_handler": "error_node"}
)

# 入口和出口
graph.set_entry_point("start_node")
graph.add_edge("final_node", END)

循环结构

python
builder.add_edge("agent", "tools")
builder.add_conditional_edges(
    "tools",
    should_continue,
    {"continue": "agent", "end": END}
)