狀態管理

管理多智能體系統的一個關鍵方面是確保所有智能體在對任務當前狀態達成共識的情況下運行。LangGraph 通過自動狀態管理解決了這個問題。這意味著該庫會在智能體執行任務時自動處理中央狀態對象的跟蹤和更新。

此狀態對象充當關鍵信息的存儲庫,這些信息需要在工作流的不同點之間訪問。這些信息可能包括:

LangGraph 入門

安裝

要開始使用 LangGraph,您需要安裝它。

要安裝 LangGraph,請打開終端或命令提示符并運行以下命令:

pip install -U langgraph

此命令將下載并安裝最新版本的 LangGraph。此-U標志可確保您獲取最新版本。

在 LangGraph 中創建基本聊天機器人

這個例子是理解 LangGraph 基本概念的一個很好的起點。

  1. 導入必要的庫:首先從 LangGraph 和其他相關庫導入所需的類和模塊。
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
  1. 定義狀態結構:創建一個定義狀態對象結構的類,該類將保存需要在圖中的節點之間共享和更新的信息。
class State(TypedDict):
# 'messages' will store the chatbot conversation history.
# The 'add_messages' function ensures new messages are appended to the list.
messages: Annotated[list, add_messages]

# Create an instance of the StateGraph, passing in the State class
graph_builder = StateGraph(State)
  1. 初始化 LLM:實例化您選擇的 LLM 模型,并提供所有必要的 API 密鑰或配置參數。此 LLM 將用于支持聊天機器人的響應。
#pip install -U langchain_anthropic
from langchain_anthropic import ChatAnthropic

llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")
  1. 創建聊天機器人節點:定義一個 Python 函數,封裝聊天機器人節點的邏輯。該函數將當前狀態作為輸入,并根據 LLM 的輸出生成響應。
def chatbot(state: State):
# Use the LLM to generate a response based on the current conversation history.
response = llm.invoke(state["messages"])

# Return the updated state with the new message appended
return {"messages": [response]}

# Add the 'chatbot' node to the graph,
graph_builder.add_node("chatbot", chatbot)
  1. 定義入口點和終點:指定圖表內工作流的起點和終點。
# For this basic chatbot, the 'chatbot' node is both the entry and finish point
graph_builder.add_edge(START, "chatbot")
graph_builder.add_edge("chatbot", END)
  1. 編譯圖表:通過編譯圖表創建可運行的實例。
graph = graph_builder.compile()
  1. 可視化圖形:通過運行簡單的 Python 代碼,您可以可視化帶有節點和邊的圖形。
from IPython.display import Image, display

try:
display(Image(graph.get_graph().draw_mermaid_png()))
except Exception:
# This requires some extra dependencies and is optional
pass
  1. 運行聊天機器人:實現一個循環來與用戶交互,將他們的輸入提供給圖表并顯示聊天機器人的響應。
while True:
user_input = input("User: ")
if user_input.lower() in ["quit", "exit", "q"]:
print("Goodbye!")
break

# Process user input through the LangGraph
for event in graph.stream({"messages": [("user", user_input)]}):
for value in event.values():
print("Assistant:", value["messages"][-1].content)

此代碼片段提供了 LangGraph 聊天機器人的基本結構。您可以通過添加更復雜的狀態管理和不同的 LLM 模型,或連接到外部工具和 API 來擴展此結構。關鍵在于為不同的任務定義清晰的節點,并使用邊來建立聊天機器人內部所需的信息流和控制。

高級 LangGraph 技術

工具集成

將工具集成到您的 LangGraph 聊天機器人中可以顯著增強其功能,使其能夠按照您喜歡的方式訪問和處理信息。

通過工具集成增強我們的基本聊天機器人

讓我們修改上一節中創建的基本聊天機器人,使其包含一個可以在網絡上搜索信息的工具。我們將使用TavilySearchResults中的工具。本示例需要Tavily API 密鑰。langchain_community.tools.tavily_search

#pip install -U tavily-python langchain_community
from typing import Annotated
from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import BaseMessage
from typing_extensions import TypedDict

from langgraph.graph import StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition

class State(TypedDict):
messages: Annotated[list, add_messages]

graph_builder = StateGraph(State)

tool = TavilySearchResults(max_results=2)
tools = [tool]
llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")
llm_with_tools = llm.bind_tools(tools)

def chatbot(state: State):
return {"messages": [llm_with_tools.invoke(state["messages"])]}

graph_builder.add_node("chatbot", chatbot)

tool_node = ToolNode(tools=[tool])
graph_builder.add_node("tools", tool_node)

graph_builder.add_conditional_edges(
"chatbot",
tools_condition,
)
# Any time a tool is called, we return to the chatbot to decide the next step
graph_builder.add_edge("tools", "chatbot")
graph_builder.set_entry_point("chatbot")
graph = graph_builder.compile()

解釋:

  1. 導入工具:導入必要的工具類,在本例中為TavilySearchResults
  2. 定義并綁定工具:創建工具實例并使用 將其綁定到 LLM llm.bind_tools()。這將告知 LLM 可用的工具及其用法。
  3. 創建 ToolNode:實例化一個ToolNode,傳入可用工具列表。
  4. 將 ToolNode 添加到圖表中:使用將其合并ToolNode到 LangGraph 中graph_builder.add_node()。
  5. 條件路由:根據graph_builder.add_conditional_edges()LLM 是否決定調用工具來設置路由邏輯。該tools_condition函數檢查 LLM 的響應是否包含工具調用指令。
  6. 環回:執行該工具后,用于graph_builder.add_edge()將流引導回節點chatbot,以允許對話繼續。

現在,當您運行聊天機器人并提出需要外部信息的問題時,LLM 可以選擇調用網絡搜索工具,檢索相關數據并將其合并到其響應中。

為聊天機器人添加記憶

記憶對于創建可以通過記住過去的互動進行有意義的對話的聊天機器人至關重要。

LangGraph 的檢查點系統

  1. Checkpointer:當你編譯你的 LangGraph 時,你可以提供一個checkpointer對象。該對象負責保存圖在不同時間點的狀態。
  2. 線程 ID:每次調用圖表時,您都需要提供一個thread_id。 此 ID 用于checkpointer跟蹤不同的對話線程。
  3. 自動保存和加載: LangGraph 會在給定 的每個圖執行步驟后自動保存狀態thread_id。當您使用相同的 再次調用該圖時thread_id,它會自動加載已保存的狀態,使聊天機器人能夠從中斷的地方繼續對話。

使用檢查點實現內存

基于前面的代碼,下面介紹如何使用 LangGraph 的檢查點添加內存:

# ... (Previous code to define State, graph_builder, nodes, and edges)

from langgraph.checkpoint.memory import MemorySaver

# Create a MemorySaver object to act as the checkpointer
memory = MemorySaver()

# Compile the graph, passing in the 'memory' object as the checkpointer
graph = graph_builder.compile(checkpointer=memory)

# ... (Rest of the code to run the chatbot)

解釋:

  1. 導入 MemorySaverMemorySaver從中導入類langgraph.checkpoint.memory
  2. 創建 MemorySaver對象:實例化一個MemorySaver對象,它將處理保存和加載圖形的狀態。
  3. 傳遞給 compile():編譯圖形時,將memory對象作為checkpointer參數傳遞。

現在,當您運行聊天機器人時,首先,使用thread_id作為此對話的密鑰:

config = {"configurable": {"thread_id": "1"}}

每個唯一的thread_id對話都會有其歷史存儲。

現在開始對話:

while True:
user_input = input("User: ")
if user_input.lower() in ["quit", "exit", "q"]:
print("Goodbye!")
break

# Process user input through the LangGraph
for event in graph.stream({"messages": [("user", user_input)]}, config):
for value in event.values():
print("Assistant:", value["messages"][-1].content)

注意:調用我們的圖表時,配置作為第二個位置參數提供。

人在循環中

當您想要在 AI 應用程序中加入人工監督、驗證或決策時,人機交互工作流程至關重要。

利用中斷實現人機交互

interrupt_before以下代碼演示了如何使用 LangGraph 的or功能實現人機交互interrupt_after。具體細節如下:

from typing import Annotated

from langchain_anthropic import ChatAnthropic
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import BaseMessage
from typing_extensions import TypedDict

from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import StateGraph
from langgraph.graph.message import add_messages
from langgraph.prebuilt import ToolNode, tools_condition

class State(TypedDict):
messages: Annotated[list, add_messages]

graph_builder = StateGraph(State)

tool = TavilySearchResults(max_results=2)
tools = [tool]
llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")
llm_with_tools = llm.bind_tools(tools)

def chatbot(state: State):
return {"messages": [llm_with_tools.invoke(state["messages"])]}

graph_builder.add_node("chatbot", chatbot)

tool_node = ToolNode(tools=[tool])
graph_builder.add_node("tools", tool_node)

graph_builder.add_conditional_edges(
"chatbot",
tools_condition,
)
graph_builder.add_edge("tools", "chatbot")
graph_builder.set_entry_point("chatbot")

memory = MemorySaver()
graph = graph_builder.compile(
checkpointer=memory,
# This is new!
interrupt_before=["tools"],
# Note: can also interrupt __after__ actions, if desired.
# interrupt_after=["tools"]
)

解釋:

在這個特定的例子中,計算圖將在執行tools節點之前暫停。該tools節點負責運行LLM在其輪次中可能請求的任何工具。通過在這個節點中斷,你實際上可以允許人類執行以下任一操作:

LangGraph 的實際用途

LangGraph 能夠管理狀態、協調多個代理并允許人工反饋,讓您構建比簡單的問答機器人更復雜、互動性更強的 AI 系統。以下是 LangGraph 的一些用途:

這些例子突出了LangGraph 如何幫助彌合人工智能能力與現實世界復雜性之間的差距。

結論

我們的 LangGraph 教程到此結束!正如您所了解的,LangGraph 通過提供構建有狀態、代理驅動系統的框架,支持創建超越簡單輸入輸出循環的 AI 應用程序。您已經獲得了定義圖、管理狀態和集成工具的實踐經驗。

文章轉載自:LangGraph 教程:初學者綜合指南

上一篇:

什么是SalesforceAPI

下一篇:

全面指南:API測試定義、測試方法與高效實踐技巧
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費