AgentCore メモリを LangChain または LangGraph と統合する
LangChain と LangGraph
LangGraph には、メモリ永続性
-
AgentCoreMemorySaver- ユーザーおよび AI メッセージ、グラフ実行状態、追加のメタデータを含むチェックポイントオブジェクトを保存およびロードするために使用されます -
AgentCoreMemoryStore- 会話メッセージを保存し、AgentCore Memory サービスを残してインサイト、概要、ユーザー設定をバックグラウンドで抽出し、エージェントが将来の会話でインテリジェントな記憶を検索できるようにするために使用されます。
これらの統合は簡単にセットアップでき、必要なのは AgentCore メモリのメモリ ID を指定するだけです。これらはサービス内の永続的ストレージに保存されるため、コンテナの終了、信頼性の高いインメモリソリューション、またはエージェントアプリケーションのクラッシュによってこれらのインタラクションが失われる心配はありません。
前提条件
AgentCore Memory を LangChain および LangGraph と統合する前に必要な要件。
-
AWS Bedrock Amazon Bedrock AgentCore アクセスを持つ アカウント
-
設定された AWS 認証情報 (boto3)
-
AgentCore メモリ
-
必要な IAM アクセス許可:
-
bedrock-agentcore:CreateEvent -
bedrock-agentcore:ListEvents -
bedrock-agentcore:RetrieveMemories
-
短期メモリ永続性の設定
LangGraph AgentCoreMemorySaver の は、AgentCore Memory BLOB タイプ を通じて、会話状態、実行コンテキスト、状態変数の保存とロードをすべて処理します。つまり、必要な設定は、エージェントグラフをコンパイルするときにチェックポイントを指定し、エージェントを呼び出すときに RunnableConfigthread_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)
インテリジェントな長期メモリ検索の設定
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}
設定を使用してエージェントを作成する
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 )
エージェントを呼び出す
エージェントを呼び出します。
# 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 )