

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 將 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) 有兩個主要的記憶體概念。透過檢查點物件儲存短期原始內容，而智慧型長期記憶體擷取是透過儲存和搜尋記憶體存放區來完成。為了解決這兩個使用案例，已建立整合以涵蓋檢查點工作流程和存放區工作流程：
+  `AgentCoreMemorySaver` - 用於儲存和載入檢查點物件，包括使用者和 AI 訊息、圖形執行狀態和其他中繼資料
+  `AgentCoreMemoryStore` - 用來儲存對話訊息，讓 AgentCore 記憶體服務在背景擷取見解、摘要和使用者偏好設定，然後讓客服人員在未來對話中搜尋這些智慧型記憶

這些整合易於設定，只需要指定 AgentCore 記憶體的記憶體 ID。由於它們儲存在服務內的持久性儲存體，因此不需要擔心透過容器結束、不可靠的記憶體內解決方案或代理程式應用程式當機而失去這些互動。

**Topics**
+ [先決條件](#prerequisites)
+ [短期記憶體持久性的組態](#memory-short-term-memory)
+ [智慧型長期記憶體搜尋的組態](#long-term-memory)
+ [使用組態建立代理程式](#create-agent)
+ [叫用代理程式](#memory-gs-invoke-agent)
+ [Resources](#resources)

## 先決條件
<a name="prerequisites"></a>

將 AgentCore 記憶體與 LangChain 和 LangGraph 整合之前所需的需求。

1.  AWS 具有 Bedrock Amazon Bedrock AgentCore 存取權的帳戶

1. 設定的 AWS 登入資料 (boto3)

1. AgentCore 記憶體

1. 必要的 IAM 許可：
   +  `bedrock-agentcore:CreateEvent` 
   +  `bedrock-agentcore:ListEvents` 
   +  `bedrock-agentcore:RetrieveMemories` 

## 短期記憶體持久性的組態
<a name="memory-short-term-memory"></a>

LangGraph `AgentCoreMemorySaver`中的 會透過 [AgentCore Memory Blob 類型](https://docs.aws.amazon.com/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` 、 `AIMessage` 和 `ToolMessage`都是相關的。執行此操作的方法有很多種，但常見的實作模式是使用模型前後勾點，如以下範例所示。對於擷取記憶體，您可以在模型前勾點中新增`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
)
```

## Resources
<a name="resources"></a>
+  [LangChain x AWS 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) 