四、添加記憶
聊天機器人現在可以使用工具來回答用户問題,但它不記得之前交互的上下文。這限制了它進行連貫的多輪對話的能力。
LangGraph 通過持久化檢查點解決了這個問題。如果你在編譯圖時提供一個 checkpointer,並在調用圖時提供一個 thread_id,LangGraph 會在每一步之後自動保存狀態。當你使用相同的 thread_id 再次調用圖時,圖會加載其保存的狀態,允許聊天機器人從上次停止的地方繼續。
我們稍後會看到檢查點比簡單的聊天記憶_強大得多_ - 它讓你可以隨時保存和恢復複雜狀態,用於錯誤恢復、人機協作工作流、時間旅行交互等等。但首先,讓我們添加檢查點來啓用多輪對話。
1. 創建一個 MemorySaver 檢查點器
創建一個 MemorySaver 檢查點器:
--- python ---
from langgraph.checkpoint.memory import InMemorySaver
memory = InMemorySaver()
--- js ---
import { MemorySaver } from "@langchain/langgraph";
const memory = new MemorySaver();
這是一個內存檢查點器,對於教程來説很方便。但是,在生產應用程序中,你可能會將其更改為使用 SqliteSaver 或 PostgresSaver 並連接數據庫。
2. 編譯圖
使用提供的檢查點器編譯圖,它將在圖處理每個節點時檢查點 State:
--- python ---
graph = graph_builder.compile(checkpointer=memory)
--- js ---
const graph = new StateGraph(State)
.addNode("chatbot", chatbot)
.addNode("tools", new ToolNode(tools))
.addConditionalEdges("chatbot", toolsCondition, ["tools", END])
.addEdge("tools", "chatbot")
.addEdge(START, "chatbot")
.compile({ checkpointer: memory });
3. 與你的聊天機器人交互
現在你可以與你的機器人交互了!
- 選擇一個線程作為此對話的鍵。
--- python ---
config = {"configurable": {"thread_id": "1"}}
--- js ---
const config = { configurable: { thread_id: "1" } };
- 調用你的聊天機器人:
--- python ---
user_input = "Hi there! My name is Will."
# config 是 stream() 或 invoke() 的**第二個位置參數**!
events = graph.stream(
{"messages": [{"role": "user", "content": user_input}]},
config,
stream_mode="values",
)
for event in events:
event["messages"][-1].pretty_print()
================================ Human Message =================================
Hi there! My name is Will.
================================== Ai Message ==================================
Hello Will! It's nice to meet you. How can I assist you today? Is there anything specific you'd like to know or discuss?
config 在調用我們的圖時作為**