

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# 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) に関して 2 つの主要なメモリ概念があります。短期的な raw コンテキストはチェックポイントオブジェクトを介して保存され、インテリジェントな長期メモリ取得はメモリストアを保存して検索することによって行われます。これら 2 つのユースケースに対処するために、チェックポイントワークフローとストアワークフローの両方をカバーする統合が作成されました。
+  `AgentCoreMemorySaver` - ユーザーおよび AI メッセージ、グラフ実行状態、追加のメタデータを含むチェックポイントオブジェクトを保存およびロードするために使用されます
+  `AgentCoreMemoryStore` - 会話メッセージを保存し、AgentCore Memory サービスを残してインサイト、概要、ユーザー設定をバックグラウンドで抽出し、エージェントが将来の会話でインテリジェントな記憶を検索できるようにするために使用されます。

これらの統合は簡単にセットアップでき、必要なのは AgentCore メモリのメモリ ID を指定するだけです。これらはサービス内の永続的ストレージに保存されるため、コンテナの終了、信頼性の高いインメモリソリューション、またはエージェントアプリケーションのクラッシュによってこれらのインタラクションが失われる心配はありません。

**Topics**
+ [前提条件](#prerequisites)
+ [短期メモリ永続性の設定](#memory-short-term-memory)
+ [インテリジェントな長期メモリ検索の設定](#long-term-memory)
+ [設定を使用してエージェントを作成する](#create-agent)
+ [エージェントを呼び出す](#memory-gs-invoke-agent)
+ [リソース](#resources)

## 前提条件
<a name="prerequisites"></a>

AgentCore Memory を 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
)
```

## リソース
<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) 