背景
在構建聊天機器人時,將對話狀態傳入和傳出鏈至關重要。 LangGraph 實現了內置的持久層,允許鏈狀態自動持久化在內存或外部后端(如 SQLite、Postgres 或 Redis)中。在本文我們將演示如何通過將任意 LangChain runnables 包裝在最小的 LangGraph 應用程序中來添加持久性。這使我們能夠持久化消息歷史記錄和鏈狀態的其他元素,從而簡化多輪應用程序的開發。它還支持多線程,使單個應用程序能夠與多個用戶分別交互。
溫馨提示:本文搭配 jupyter-lab 食用更佳。
使用 Qwen3 聊天模型
pip install -qU "langchain[openai]"
from pydantic import SecretStr
import osos.environ["OPENAI_BASE_URL"] = "https://api.siliconflow.cn/v1/"
os.environ["OPENAI_API_KEY"] = "sk-xxx"from langchain.chat_models import init_chat_modelllm = init_chat_model("Qwen/Qwen3-8B", model_provider="openai")
示例:消息輸入
聊天模型接受消息列表作為輸入并輸出消息。 LangGraph 包括一個內置的 MessagesState,我們可以將其用于此目的。下面,我們將圖狀態定義為消息列表,向圖中添加一個調用聊天模型的節點,使用內存檢查點編譯器編譯圖,以在運行之間存儲消息。
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import START, MessagesState, StateGraph# Define a new graph
workflow = StateGraph(state_schema=MessagesState)# Define the function that calls the model
def call_model(state: MessagesState):response = llm.invoke(state["messages"])# Update message history with response:return {"messages": response}# Define the (single) node in the graph
workflow.add_edge(START, "model")
workflow.add_node("model"