View a markdown version of this page

将 AgentCore 内存与 LangChain 或集成 LangGraph - Amazon Bedrock AgentCore

将 AgentCore 内存与 LangChain 或集成 LangGraph

LangChain 并且 LangGraph是强大的开源框架,用于通过基于图形的架构开发代理。它们提供了一个简单的界面,用于定义代理与用户、其工具和内存的交互。

在内存持久性方面, LangGraph 有两个主要的内存概念。 Short-term,原始上下文通过检查点对象保存,而智能的长期内存检索是通过保存和搜索内存存储来完成的。为了解决这两个用例,我们创建了涵盖检查点工作流程和商店工作流程的集成:

  • AgentCoreMemorySaver-用于保存和加载检查点对象,其中包括用户和 AI 消息、图形执行状态以及其他元数据

  • AgentCoreMemoryStore-用于保存对话消息,让 M AgentCore emory 服务在后台提取见解、摘要和用户偏好,然后让代理在未来的对话中搜索这些智能记忆

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

先决条件

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

  1. AWS 拥有 Bedrock Amazon Bedrock 权限的账户 AgentCore

  2. 已配置的 AWS 凭证 (boto3)

  3. 一段 AgentCore 回忆

  4. 所需的 IAM 权限:

    • bedrock-agentcore:CreateEvent

    • bedrock-agentcore:ListEvents

    • bedrock-agentcore:RetrieveMemories

短期内存持久性的配置

in 通过 M AgentCore emory blob 类型AgentCoreMemorySaver在幕后 LangGraph 处理对话状态、执行上下文和状态变量的所有保存和加载。这意味着唯一需要的设置就是在编译代理图时指定检查点,然后在调用代理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对象即可。对于摘要,所有类型HumanMessageAIMessage、和都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 )

资源