將 AgentCore 記憶體與 LangChain 或 LangGraph 整合
LangChain 和 LangGraph
在 LangGraph 中,記憶體持久性
-
AgentCoreMemorySaver- 用於儲存和載入檢查點物件,包括使用者和 AI 訊息、圖形執行狀態和其他中繼資料 -
AgentCoreMemoryStore- 用來儲存對話訊息,讓 AgentCore 記憶體服務在背景擷取見解、摘要和使用者偏好設定,然後讓客服人員在未來對話中搜尋這些智慧型記憶
這些整合易於設定,只需要指定 AgentCore 記憶體的記憶體 ID。由於它們儲存在服務內的持久性儲存體,因此不需要擔心透過容器結束、不可靠的記憶體內解決方案或代理程式應用程式當機而失去這些互動。
先決條件
將 AgentCore 記憶體與 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 )