

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 将 AgentCore 内存与 LangChain 或集成 LangGraph
<a name="memory-integrate-lang"></a>

 [LangChain 并且 LangGraph](https://www.langchain.com/langgraph)是强大的开源框架，用于通过基于图形的架构开发代理。它们为定义代理与用户、其工具和内存的交互提供了一个简单的界面。

当涉及到内存[持久性时，其中 LangGraph 有两个主要的内存概念](https://docs.langchain.com/oss/python/langgraph/persistence)。 Short-term，原始上下文通过检查点对象保存，而智能的长期内存检索是通过在内存存储中保存和搜索来完成的。为了解决这两个用例，创建了涵盖检查点工作流程和商店工作流程的集成：
+  `AgentCoreMemorySaver`-用于保存和加载检查点对象，包括用户和 AI 消息、图表执行状态和其他元数据
+  `AgentCoreMemoryStore`-用于保存对话消息，让 AgentCore 内存服务在后台提取见解、摘要和用户偏好，然后让代理在将来的对话中搜索这些智能记忆

这些集成易于设置，只需要指定内存的内存 ID。 AgentCore 由于它们被保存到服务内的永久存储器中，因此无需担心因容器退出、不可靠的内存解决方案或代理应用程序崩溃而丢失这些交互。

**Topics**
+ [先决条件](#prerequisites)
+ [短期内存持久性的配置](#memory-short-term-memory)
+ [智能长期内存搜索的配置](#long-term-memory)
+ [使用配置创建代理](#create-agent)
+ [调用代理](#memory-gs-invoke-agent)
+ [资源](#resources)

## 先决条件
<a name="prerequisites"></a>

在将 AgentCore 内存与 LangChain 和集成之前需要满足的要求 LangGraph。

1.  Amazon 拥有亚马逊 Bedrock 访问权限的账户 AgentCore 

1. 已配置的 Amazon 凭据 (boto3)

1. 一段 AgentCore 回忆

1. 所需的 IAM 权限：
   +  `bedrock-agentcore:CreateEvent` 
   +  `bedrock-agentcore:ListEvents` 
   +  `bedrock-agentcore:RetrieveMemories` 

## 短期内存持久性的配置
<a name="memory-short-term-memory"></a>

`AgentCoreMemorySaver`in 通过 M [ AgentCore emory blob 类型 LangGraph 处理对话状态、执行上下文和后台状态变量的所有保存和加载。](https://docs.amazonaws.cn/bedrock-agentcore/latest/APIReference/API_CreateEvent.html#API_CreateEvent_RequestSyntax)这意味着唯一需要的设置是在编译代理图时指定检查点，然后在调用代理[RunnableConfig](https://python.langchain.com/docs/concepts/runnables/#runnableconfig)时`thread_id`在中提供`actor_id`和。配置如下所示，代理调用将在下一节中显示。如果您的应用程序只需要简单的对话持久性，请随时跳过长期记忆部分。

```
# Import LangGraph and LangChain components
from langchain.chat_models import init_chat_model
from langgraph.prebuilt import create_react_agent

# Import the AgentCore Memory integrations
from langgraph_checkpoint_aws import AgentCoreMemorySaver

REGION = "us-west-2"
MEMORY_ID = "YOUR_MEMORY_ID"
MODEL_ID = "us.anthropic.claude-3-7-sonnet-20250219-v1:0"

# Initialize checkpointer for state persistence. No additional setup required.
# Sessions will be saved and persisted for actor_id/session_id combinations
checkpointer = AgentCoreMemorySaver(MEMORY_ID, region_name=REGION)
```

## 智能长期内存搜索的配置
<a name="long-term-memory"></a>

对于长期内存存储 LangGraph，您可以更灵活地处理消息。例如，如果应用程序只关注用户首选项，则您只需要在对话中存储`HumanMessage`对象即可。对于摘要，所有类型`HumanMessage`和都`ToolMessage`将是相关的。`AIMessage`有很多方法可以做到这一点，但常见的实现模式是使用模型前和后模型挂钩，如下例所示。为了检索内存，你可以在预建模挂钩中添加一个`store.search(query)`调用并将其附加到用户的消息中，这样代理就可以获得所有的上下文。或者，可以向代理人提供根据需要搜索信息的工具。所有这些实现模式均受支持，实施方式将因应用程序而异。

```
from langgraph_checkpoint_aws import (
    AgentCoreMemoryStore
)

# Initialize store for saving and searching over long term memories
# such as preferences and facts across sessions
store = AgentCoreMemoryStore(MEMORY_ID, region_name=REGION)

# Pre-model hook runs and saves messages of your choosing to AgentCore Memory
# for async processing and extraction
def pre_model_hook(state, config: RunnableConfig, *, store: BaseStore):
    """Hook that runs pre-LLM invocation to save the latest human message"""
    actor_id = config["configurable"]["actor_id"]
    thread_id = config["configurable"]["thread_id"]

    # Saving the message to the actor and session combination that we get at runtime
    namespace = (actor_id, thread_id)

    messages = state.get("messages", [])
    # Save the last human message we see before LLM invocation
    for msg in reversed(messages):
        if isinstance(msg, HumanMessage):
            store.put(namespace, str(uuid.uuid4()), {"message": msg})
            break

    # OPTIONAL: Retrieve user preferences based on the last message and append to state
    # user_preferences_namespace = ("preferences", actor_id)
    # preferences = store.search(user_preferences_namespace, query=msg.content, limit=5)
    # # Add to input messages as needed

    return {"llm_input_messages": messages}
```

## 使用配置创建代理
<a name="create-agent"></a>

初始化 LLM 并使用内存配置创建 LangGraph 代理。

```
# Initialize LLM
llm = init_chat_model(MODEL_ID, model_provider="bedrock_converse", region_name=REGION)

# Create a pre-built langgraph agent (configurations work for custom agents too)
graph = create_react_agent(
    model=llm,
    tools=tools,
    checkpointer=checkpointer, # AgentCoreMemorySaver we created above
    store=store, # AgentCoreMemoryStore we created above
    pre_model_hook=pre_model_hook, # OPTIONAL: Function we defined to save user messages
    # post_model_hook=post_model_hook # OPTIONAL: Can save AI messages to memory if needed
)
```

## 调用代理
<a name="memory-gs-invoke-agent"></a>

调用代理。

```
# Specify config at runtime for ACTOR and SESSION
config = {
    "configurable": {
        "thread_id": "session-1", # REQUIRED: This maps to Bedrock AgentCore session_id under the hood
        "actor_id": "react-agent-1", # REQUIRED: This maps to Bedrock AgentCore actor_id under the hood
    }
}

# Invoke the agent
response = graph.invoke(
    {"messages": [("human", "I like sushi with tuna. In general seafood is great.")]},
    config=config
)

# ... agent will answer

# Agent will have the conversation and state persisted on the next message
# Because the session ID is the same in the runtime config
response = graph.invoke(
    {"messages": [("human", "What did I just say?")]},
    config=config
)

# Define a new session in the runtime config to test long term retrieval
config = {
    "configurable": {
        "thread_id": "session-2", # New session ID
        "actor_id": "react-agent-1", # Same actor ID
    }
}

# Invoke the agent (it will retrieve long term memories from other session)
response = graph.invoke(
    {"messages": [("human", "Lets make a meal tonight, what should I cook?")]},
    config=config
)
```

## 资源
<a name="resources"></a>
+  [LangChain x Amazon Github 存储库 ](https://github.com/langchain-ai/langchain-aws/tree/main) 
+  [Pypi 软件包 ](https://pypi.org/project/langgraph-checkpoint-aws/) 
+  [AgentCoreMemorySaver 实施 ](https://github.com/langchain-ai/langchain-aws/blob/main/libs/langgraph-checkpoint-aws/langgraph_checkpoint_aws/agentcore/saver.py) 
+  [AgentCoreMemorySaver 示例笔记本（仅限检查点）](https://github.com/langchain-ai/langchain-aws/blob/main/samples/memory/agentcore_memory_checkpointer.ipynb) 