智慧體課程文件

LangGraph 的構建模組

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

LangGraph 的構建模組

要使用 LangGraph 構建應用程式,您需要了解其核心元件。讓我們探索構成 LangGraph 應用程式的基本構建模組。

Building Blocks

LangGraph 中的應用程式從一個入口點開始,根據執行情況,流程可能會進入一個函式或另一個函式,直到到達END。

Application

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 呼叫:生成文字或做出決策
  • 工具呼叫:與外部系統互動
  • 條件邏輯:確定後續步驟
  • 人工干預:從使用者獲取輸入

💡 資訊:一些整個工作流所需的節點,如 START 和 END,直接從 LangGraph 中存在。

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

然後可以將其視覺化!

# 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 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.