
構建自定義云存儲:NAS廠商 REST API 使用指南(Synology/QNAP)
管理多智能體系統的一個關鍵方面是確保所有智能體在對任務當前狀態達成共識的情況下運行。LangGraph 通過自動狀態管理解決了這個問題。這意味著該庫會在智能體執行任務時自動處理中央狀態對象的跟蹤和更新。
此狀態對象充當關鍵信息的存儲庫,這些信息需要在工作流的不同點之間訪問。這些信息可能包括:
要開始使用 LangGraph,您需要安裝它。
要安裝 LangGraph,請打開終端或命令提示符并運行以下命令:
pip install -U langgraph
此命令將下載并安裝最新版本的 LangGraph。此-U
標志可確保您獲取最新版本。
這個例子是理解 LangGraph 基本概念的一個很好的起點。
from typing import Annotated
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
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)
#pip install -U langchain_anthropic
from langchain_anthropic import ChatAnthropic
llm = ChatAnthropic(model="claude-3-5-sonnet-20240620")
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)
# 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)
graph = graph_builder.compile()
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
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 聊天機器人中可以顯著增強其功能,使其能夠按照您喜歡的方式訪問和處理信息。
通過工具集成增強我們的基本聊天機器人
讓我們修改上一節中創建的基本聊天機器人,使其包含一個可以在網絡上搜索信息的工具。我們將使用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()
解釋:
TavilySearchResults
。llm.bind_tools()
。這將告知 LLM 可用的工具及其用法。ToolNode
,傳入可用工具列表。ToolNode
到 LangGraph 中graph_builder.add_node()
。graph_builder.add_conditional_edges()
LLM 是否決定調用工具來設置路由邏輯。該tools_condition
函數檢查 LLM 的響應是否包含工具調用指令。graph_builder.add_edge()
將流引導回節點chatbot
,以允許對話繼續。現在,當您運行聊天機器人并提出需要外部信息的問題時,LLM 可以選擇調用網絡搜索工具,檢索相關數據并將其合并到其響應中。
記憶對于創建可以通過記住過去的互動進行有意義的對話的聊天機器人至關重要。
LangGraph 的檢查點系統
checkpointer
對象。該對象負責保存圖在不同時間點的狀態。thread_id
。 此 ID 用于checkpointer
跟蹤不同的對話線程。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)
解釋:
MemorySaver
:MemorySaver
從中導入類langgraph.checkpoint.memory
。MemorySaver
對象:實例化一個MemorySaver
對象,它將處理保存和加載圖形的狀態。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 能夠管理狀態、協調多個代理并允許人工反饋,讓您構建比簡單的問答機器人更復雜、互動性更強的 AI 系統。以下是 LangGraph 的一些用途:
這些例子突出了LangGraph 如何幫助彌合人工智能能力與現實世界復雜性之間的差距。
我們的 LangGraph 教程到此結束!正如您所了解的,LangGraph 通過提供構建有狀態、代理驅動系統的框架,支持創建超越簡單輸入輸出循環的 AI 應用程序。您已經獲得了定義圖、管理狀態和集成工具的實踐經驗。
文章轉載自:LangGraph 教程:初學者綜合指南