Agents 课程文档

LangGraph 的构建块

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

LangGraph 的构建块

要使用 LangGraph 构建应用程序,您需要了解其核心组件。让我们探索构成 LangGraph 应用程序的基本构建块。

Building Blocks

LangGraph 中的应用程序从入口点开始,根据执行情况,流程可能会转到一个函数或另一个函数,直到到达 END。

Application

1. 状态

状态是 LangGraph 的核心概念。它代表了流经您的应用程序的所有信息。

from typing_extensions import TypedDict

class State(TypedDict):
    graph_state: str

状态是用户定义的,因此应仔细设计字段,以包含决策过程所需的所有数据!

💡 提示: 仔细考虑您的应用程序需要在步骤之间跟踪哪些信息。

2. 节点

节点是 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 调用:生成文本或做出决策
  • 工具调用:与外部系统交互
  • 条件逻辑:确定下一步操作
  • 人工干预:从用户获取输入

💡 信息: 一些整个工作流程必需的节点(如 START 和 END)直接来自 langGraph。

3. 边

连接节点并定义通过图的可能路径

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

StateGraph 是容纳您整个 Agent 工作流程的容器

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()

然后可以将其可视化!

# View
display(Image(graph.get_graph().draw_mermaid_png()))
Graph Visualization

但最重要的是,可以调用

graph.invoke({"graph_state" : "Hi, this is Lance."})

输出

---Node 1---
---Node 3---
{'graph_state': 'Hi, this is Lance. I am sad!'}

下一步是什么?

在下一节中,我们将通过构建我们的第一个图来将这些概念付诸实践。该图可以让 Alfred 接收您的电子邮件,对其进行分类,并在邮件是真实邮件的情况下起草初步答复。

< > 在 GitHub 上更新