如何添加线程级持久化(函数式 API)¶
许多 AI 应用程序需要内存来在同一线程上的多次交互中共享上下文(例如,对话的多个回合)。在 LangGraph 函数式 API 中,这种内存可以使用线程级持久化添加到任何entrypoint()工作流中。
在创建 LangGraph 工作流时,您可以设置它以使用检查点保存器来持久化其结果
-
创建一个检查点保存器的实例
-
将
checkpointer
实例传递给entrypoint()
装饰器 -
(可选)在工作流函数签名中公开
previous
参数@entrypoint(checkpointer=checkpointer) def workflow( inputs, *, # you can optionally specify `previous` in the workflow function signature # to access the return value from the workflow as of the last execution previous ): previous = previous or [] combined_inputs = previous + inputs result = do_something(combined_inputs) ...
-
(可选)选择哪些值将从工作流返回,哪些值将由检查点保存器保存为
previous
本指南展示了如何为你的工作流添加线程级持久化。
注意
如果您需要跨多个对话或用户共享的内存(跨线程持久化),请查看此操作指南。
注意
如果您需要将线程级持久化添加到 StateGraph
,请查看此操作指南。
设置¶
首先,我们需要安装所需的软件包
接下来,我们需要为 Anthropic 设置 API 密钥(我们将使用的 LLM)。
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("ANTHROPIC_API_KEY")
设置 LangSmith 以进行 LangGraph 开发
注册 LangSmith 以快速发现问题并提高 LangGraph 项目的性能。LangSmith 允许您使用跟踪数据来调试、测试和监控使用 LangGraph 构建的 LLM 应用程序——阅读此处了解更多关于如何开始的信息。
示例:具有短期记忆的简单聊天机器人¶
我们将使用一个包含单个任务的工作流,该任务调用一个聊天模型。
首先让我们定义我们将要使用的模型
from langchain_anthropic import ChatAnthropic
model = ChatAnthropic(model="claude-3-5-sonnet-latest")
API 参考:ChatAnthropic
现在我们可以定义我们的任务和工作流。为了添加持久化,我们需要将检查点保存器传递给entrypoint()装饰器。
from langchain_core.messages import BaseMessage
from langgraph.graph import add_messages
from langgraph.func import entrypoint, task
from langgraph.checkpoint.memory import MemorySaver
@task
def call_model(messages: list[BaseMessage]):
response = model.invoke(messages)
return response
checkpointer = MemorySaver()
@entrypoint(checkpointer=checkpointer)
def workflow(inputs: list[BaseMessage], *, previous: list[BaseMessage]):
if previous:
inputs = add_messages(previous, inputs)
response = call_model(inputs).result()
return entrypoint.final(value=response, save=add_messages(inputs, response))
API 参考:BaseMessage | add_messages | entrypoint | task | MemorySaver
如果我们尝试使用此工作流,对话的上下文将在交互之间持久化
注意
如果您正在使用 LangGraph Cloud 或 LangGraph Studio,则无需将 checkpointer 传递给 entrypoint 装饰器,因为它会自动完成。
我们现在可以与智能体交互,并看到它记住了之前的消息!
config = {"configurable": {"thread_id": "1"}}
input_message = {"role": "user", "content": "hi! I'm bob"}
for chunk in workflow.stream([input_message], config, stream_mode="values"):
chunk.pretty_print()
==================================[1m Ai Message [0m==================================
Hi Bob! I'm Claude. Nice to meet you! How are you today?
input_message = {"role": "user", "content": "what's my name?"}
for chunk in workflow.stream([input_message], config, stream_mode="values"):
chunk.pretty_print()
==================================[1m Ai Message [0m==================================
Your name is Bob.
thread_id
。砰!所有记忆都消失了!
input_message = {"role": "user", "content": "what's my name?"}
for chunk in workflow.stream(
[input_message],
{"configurable": {"thread_id": "2"}},
stream_mode="values",
):
chunk.pretty_print()
==================================[1m Ai Message [0m==================================
I don't know your name unless you tell me. Each conversation I have starts fresh, so I don't have access to any previous interactions or personal information unless you share it with me.
流式传输令牌
如果您想从聊天机器人流式传输 LLM 令牌,您可以使用 stream_mode="messages"
。查看此操作指南以了解更多信息。