簡介
從頭開始建立代理對於理解這個概念非常有用,但生產需要一個框架。 LangGraph(由 LangChain 團隊開發)是目前可用於有狀態、基於圖表的代理程式工作流程的最強大的框架。
1. LangChain 與 LangGraph
| 浪鏈 | 郎圖 | |
|---|---|---|
| 範式 | 鏈條(線性) | 圖表(循環) |
| 狀態 | 無國籍 | 有狀態 |
| 最適合 | 簡單的管道,RAG | 複雜代理,多步驟 |
| 控制流程 | 順序 | 條件路由 |
2. LangGraph 基礎知識
from langgraph.graph import StateGraph, MessagesState, START, END
def call_llm(state: MessagesState):
response = model.invoke(state["messages"])
return {"messages": [response]}
def use_tools(state: MessagesState):
# Execute tool calls
...
# Build graph
graph = StateGraph(MessagesState)
graph.add_node("llm", call_llm)
graph.add_node("tools", use_tools)
graph.add_edge(START, "llm")
graph.add_conditional_edges("llm", should_use_tools, {"yes": "tools", "no": END})
graph.add_edge("tools", "llm")
agent = graph.compile()
總結
- LangGraph = 代理程式工作流程的狀態機
- 節點 = 函數,邊 = 轉換,狀態 = 共享數據
- 複雜決策樹的條件路由
- 人機互動內建支持
- 長期運作的工作流程的持久性
練習
1.用LangGraph實現研究代理 2.新增人機互動審核步驟 3. 工具失敗時實作重試邏輯 4. 建構一個具有 3 個以上條件分支的代理