跳到内容

内存

LangGraph支持两种对于构建对话代理至关重要的内存类型:

  • 短期内存:通过在会话中维护消息历史来跟踪正在进行的对话。
  • 长期内存:在不同会话之间存储用户特定或应用程序级别的数据。

本指南演示了如何在LangGraph中将这两种内存类型与代理结合使用。要更深入地了解内存概念,请参阅LangGraph内存文档

image

短期内存长期内存都需要持久存储,以在LLM交互中保持连续性。在生产环境中,这些数据通常存储在数据库中。

术语

在LangGraph中

  • 短期内存也称为线程级内存
  • 长期内存也称为跨线程内存

线程表示由相同thread_id分组的一系列相关运行。

短期内存

短期内存使代理能够跟踪多轮对话。要使用它,您必须:

  1. 在创建代理时提供checkpointercheckpointer可以实现代理状态的持久性
  2. 在运行代理时在配置中提供thread_idthread_id是对话会话的唯一标识符。

API参考:create_react_agent | InMemorySaver

from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.memory import InMemorySaver

checkpointer = InMemorySaver() # (1)!


def get_weather(city: str) -> str:
    """Get weather for a given city."""
    return f"It's always sunny in {city}!"


agent = create_react_agent(
    model="anthropic:claude-3-7-sonnet-latest",
    tools=[get_weather],
    checkpointer=checkpointer # (2)!
)

# Run the agent
config = {
    "configurable": {
        "thread_id": "1"  # (3)!
    }
}

sf_response = agent.invoke(
    {"messages": [{"role": "user", "content": "what is the weather in sf"}]},
    config
)

# Continue the conversation using the same thread_id
ny_response = agent.invoke(
    {"messages": [{"role": "user", "content": "what about new york?"}]},
    config # (4)!
)
  1. InMemorySaver是一个检查点,将代理的状态存储在内存中。在生产环境中,您通常会使用数据库或其他持久存储。请查阅检查点文档以获取更多选项。如果您使用LangGraph平台进行部署,该平台将为您提供一个生产就绪的检查点。
  2. checkpointer被传递给代理。这使得代理能够在其调用之间持久化其状态。
  3. 配置中提供了一个唯一的thread_id。此ID用于标识对话会话。该值由用户控制,可以是任何字符串。
  4. 代理将使用相同的thread_id继续对话。这将允许代理推断用户是在特别询问纽约的天气

当代理第二次使用相同的thread_id被调用时,第一次对话的原始消息历史会自动包含在内,从而允许代理推断用户是在特别询问纽约的天气

LangGraph平台提供生产就绪的检查点

如果您使用LangGraph平台,在部署期间,您的检查点将自动配置为使用生产就绪的数据库。

管理消息历史

长对话可能超出LLM的上下文窗口。常见的解决方案是:

  • 摘要:维护对话的运行摘要。
  • 裁剪:删除历史记录中的前N条或后N条消息。

这使得代理能够跟踪对话而不会超出LLM的上下文窗口。

要管理消息历史,请指定pre_model_hook——一个始终在调用语言模型之前运行的函数(节点)。

总结消息历史

image

长对话可能超出LLM的上下文窗口。一个常见的解决方案是维护对话的运行摘要。这使得代理能够跟踪对话而不会超出LLM的上下文窗口。

要总结消息历史,您可以将pre_model_hook与预构建的SummarizationNode一起使用。

API参考:ChatAnthropic | count_tokens_approximately | create_react_agent | AgentState | InMemorySaver

from langchain_anthropic import ChatAnthropic
from langmem.short_term import SummarizationNode
from langchain_core.messages.utils import count_tokens_approximately
from langgraph.prebuilt import create_react_agent
from langgraph.prebuilt.chat_agent_executor import AgentState
from langgraph.checkpoint.memory import InMemorySaver
from typing import Any

model = ChatAnthropic(model="claude-3-7-sonnet-latest")

summarization_node = SummarizationNode( # (1)!
    token_counter=count_tokens_approximately,
    model=model,
    max_tokens=384,
    max_summary_tokens=128,
    output_messages_key="llm_input_messages",
)

class State(AgentState):
    # NOTE: we're adding this key to keep track of previous summary information
    # to make sure we're not summarizing on every LLM call
    context: dict[str, Any]  # (2)!


checkpointer = InMemorySaver() # (3)!

agent = create_react_agent(
    model=model,
    tools=tools,
    pre_model_hook=summarization_node, # (4)!
    state_schema=State, # (5)!
    checkpointer=checkpointer,
)
  1. InMemorySaver是一个检查点,将代理的状态存储在内存中。在生产环境中,您通常会使用数据库或其他持久存储。请查阅检查点文档以获取更多选项。如果您使用LangGraph平台进行部署,该平台将为您提供一个生产就绪的检查点。
  2. context键被添加到代理的状态中。该键包含摘要节点的簿记信息。它用于跟踪上次的摘要信息,并确保代理不会在每次LLM调用时都进行摘要,这可能会效率低下。
  3. checkpointer被传递给代理。这使得代理能够在其调用之间持久化其状态。
  4. pre_model_hook设置为SummarizationNode。此节点将在将消息历史发送到LLM之前对其进行摘要。摘要节点将自动处理摘要过程,并使用新的摘要更新代理的状态。如果需要,您可以将其替换为自定义实现。请参阅create_react_agent API参考以获取更多详细信息。
  5. state_schema设置为State类,这是一个包含额外context键的自定义状态。

裁剪消息历史

要裁剪消息历史,您可以将pre_model_hooktrim_messages函数一起使用。

API参考:trim_messages | count_tokens_approximately | create_react_agent

from langchain_core.messages.utils import (
    trim_messages,
    count_tokens_approximately
)
from langgraph.prebuilt import create_react_agent

# This function will be called every time before the node that calls LLM
def pre_model_hook(state):
    trimmed_messages = trim_messages(
        state["messages"],
        strategy="last",
        token_counter=count_tokens_approximately,
        max_tokens=384,
        start_on="human",
        end_on=("human", "tool"),
    )
    return {"llm_input_messages": trimmed_messages}

checkpointer = InMemorySaver()
agent = create_react_agent(
    model,
    tools,
    pre_model_hook=pre_model_hook,
    checkpointer=checkpointer,
)

要了解更多关于使用pre_model_hook管理消息历史的信息,请参阅此操作指南

从工具读取

LangGraph允许代理在其工具内部访问其短期内存(状态)。

API参考:InjectedState | create_react_agent

from typing import Annotated
from langgraph.prebuilt import InjectedState, create_react_agent

class CustomState(AgentState):
    user_id: str

def get_user_info(
    state: Annotated[CustomState, InjectedState]
) -> str:
    """Look up user info."""
    user_id = state["user_id"]
    return "User is John Smith" if user_id == "user_123" else "Unknown user"

agent = create_react_agent(
    model="anthropic:claude-3-7-sonnet-latest",
    tools=[get_user_info],
    state_schema=CustomState,
)

agent.invoke({
    "messages": "look up user information",
    "user_id": "user_123"
})

有关更多信息,请参阅上下文指南。

从工具写入

要在执行期间修改代理的短期内存(状态),您可以直接从工具返回状态更新。这对于持久化中间结果或使信息可供后续工具或提示访问非常有用。

API参考:InjectedToolCallId | RunnableConfig | ToolMessage | InjectedState | create_react_agent | AgentState | Command

from typing import Annotated
from langchain_core.tools import InjectedToolCallId
from langchain_core.runnables import RunnableConfig
from langchain_core.messages import ToolMessage
from langgraph.prebuilt import InjectedState, create_react_agent
from langgraph.prebuilt.chat_agent_executor import AgentState
from langgraph.types import Command

class CustomState(AgentState):
    user_name: str

def update_user_info(
    tool_call_id: Annotated[str, InjectedToolCallId],
    config: RunnableConfig
) -> Command:
    """Look up and update user info."""
    user_id = config["configurable"].get("user_id")
    name = "John Smith" if user_id == "user_123" else "Unknown user"
    return Command(update={
        "user_name": name,
        # update the message history
        "messages": [
            ToolMessage(
                "Successfully looked up user information",
                tool_call_id=tool_call_id
            )
        ]
    })

def greet(
    state: Annotated[CustomState, InjectedState]
) -> str:
    """Use this to greet the user once you found their info."""
    user_name = state["user_name"]
    return f"Hello {user_name}!"

agent = create_react_agent(
    model="anthropic:claude-3-7-sonnet-latest",
    tools=[update_user_info, greet],
    state_schema=CustomState
)

agent.invoke(
    {"messages": [{"role": "user", "content": "greet the user"}]},
    config={"configurable": {"user_id": "user_123"}}
)

有关更多详细信息,请参阅如何从工具更新状态

长期内存

使用长期内存来跨对话存储用户特定或应用程序特定的数据。这对于聊天机器人等应用程序非常有用,您可能希望记住用户偏好或其他信息。

要使用长期内存,您需要:

  1. 配置一个存储以在调用之间持久化数据。
  2. 使用get_store函数从工具或提示中访问存储。

读取

代理可以用来查找用户信息的一个工具
from langchain_core.runnables import RunnableConfig
from langgraph.config import get_store
from langgraph.prebuilt import create_react_agent
from langgraph.store.memory import InMemoryStore

store = InMemoryStore() # (1)!

store.put(  # (2)!
    ("users",),  # (3)!
    "user_123",  # (4)!
    {
        "name": "John Smith",
        "language": "English",
    } # (5)!
)

def get_user_info(config: RunnableConfig) -> str:
    """Look up user info."""
    # Same as that provided to `create_react_agent`
    store = get_store() # (6)!
    user_id = config["configurable"].get("user_id")
    user_info = store.get(("users",), user_id) # (7)!
    return str(user_info.value) if user_info else "Unknown user"

agent = create_react_agent(
    model="anthropic:claude-3-7-sonnet-latest",
    tools=[get_user_info],
    store=store # (8)!
)

# Run the agent
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    config={"configurable": {"user_id": "user_123"}}
)
  1. InMemoryStore是一个将数据存储在内存中的存储。在生产环境中,您通常会使用数据库或其他持久存储。请查阅存储文档以获取更多选项。如果您使用LangGraph平台进行部署,该平台将为您提供一个生产就绪的存储。
  2. 对于此示例,我们使用put方法向存储写入一些示例数据。请参阅BaseStore.put API参考以获取更多详细信息。
  3. 第一个参数是命名空间。它用于将相关数据分组。在此示例中,我们使用users命名空间来分组用户数据。
  4. 命名空间内的键。此示例使用用户ID作为键。
  5. 我们要为给定用户存储的数据。
  6. get_store函数用于访问存储。您可以在代码的任何地方调用它,包括工具和提示。此函数返回在创建代理时传递给代理的存储。
  7. get方法用于从存储中检索数据。第一个参数是命名空间,第二个参数是键。这将返回一个StoreValue对象,其中包含值和有关值的元数据。
  8. store被传递给代理。这使得代理能够在运行工具时访问存储。您还可以使用get_store函数从代码的任何地方访问存储。

写入

一个更新用户信息的工具示例
from typing_extensions import TypedDict

from langgraph.config import get_store
from langgraph.prebuilt import create_react_agent
from langgraph.store.memory import InMemoryStore

store = InMemoryStore() # (1)!

class UserInfo(TypedDict): # (2)!
    name: str

def save_user_info(user_info: UserInfo, config: RunnableConfig) -> str: # (3)!
    """Save user info."""
    # Same as that provided to `create_react_agent`
    store = get_store() # (4)!
    user_id = config["configurable"].get("user_id")
    store.put(("users",), user_id, user_info) # (5)!
    return "Successfully saved user info."

agent = create_react_agent(
    model="anthropic:claude-3-7-sonnet-latest",
    tools=[save_user_info],
    store=store
)

# Run the agent
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    config={"configurable": {"user_id": "user_123"}} # (6)!
)

# You can access the store directly to get the value
store.get(("users",), "user_123").value
  1. InMemoryStore是一个将数据存储在内存中的存储。在生产环境中,您通常会使用数据库或其他持久存储。请查阅存储文档以获取更多选项。如果您使用LangGraph平台进行部署,该平台将为您提供一个生产就绪的存储。
  2. UserInfo类是一个TypedDict,它定义了用户信息结构。LLM将使用它根据模式格式化响应。
  3. save_user_info函数是一个允许代理更新用户信息的工具。这对于用户希望更新其个人资料信息的聊天应用程序可能很有用。
  4. get_store函数用于访问存储。您可以在代码的任何地方调用它,包括工具和提示。此函数返回在创建代理时传递给代理的存储。
  5. put方法用于将数据存储在存储中。第一个参数是命名空间,第二个参数是键。这将把用户信息存储在存储中。
  6. user_id在配置中传递。这用于标识正在更新其信息的用户。

LangGraph还允许您通过语义相似性在长期内存中搜索项目。

预构建内存工具

LangMem是一个LangChain维护的库,提供用于管理代理中长期内存的工具。请参阅LangMem文档以获取使用示例。

附加资源