View a markdown version of this page

AgentCore 메모리를 LangChain 또는 LangGraph와 통합 - Amazon Bedrock AgentCore

AgentCore 메모리를 LangChain 또는 LangGraph와 통합

LangChain 및 LangGraph는 그래프 기반 아키텍처를 통해 에이전트를 개발하기 위한 강력한 오픈 소스 프레임워크입니다. 사용자, 도구 및 메모리와의 에이전트 상호 작용을 정의하기 위한 간단한 인터페이스를 제공합니다.

LangGraph에는 메모리 지속성과 관련된 두 가지 주요 메모리 개념이 있습니다. 단기 원시 컨텍스트는 체크포인트 객체를 통해 저장되는 반면, 지능형 장기 메모리 검색은 메모리 스토어를 통해 저장하고 검색하여 수행됩니다. 이 두 사용 사례를 해결하기 위해 체크포인트 워크플로와 스토어 워크플로를 모두 포함하도록 통합이 생성되었습니다.

  • AgentCoreMemorySaver - 사용자 및 AI 메시지, 그래프 실행 상태 및 추가 메타데이터를 포함하는 체크포인트 객체를 저장하고 로드하는 데 사용됩니다.

  • AgentCoreMemoryStore - 대화형 메시지를 저장하고 AgentCore 메모리 서비스를 남겨 백그라운드에서 인사이트, 요약 및 사용자 기본 설정을 추출한 다음 에이전트가 향후 대화에서 이러한 지능형 메모리를 검색할 수 있도록 하는 데 사용됩니다.

이러한 통합은 AgentCore 메모리의 메모리 ID만 지정하면 되므로 설정하기 쉽습니다. 서비스 내의 영구 스토리지에 저장되므로 컨테이너 종료, 신뢰할 수 없는 인 메모리 솔루션 또는 에이전트 애플리케이션 충돌을 통해 이러한 상호 작용이 손실될 염려가 없습니다.

사전 조건

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

단기 메모리 지속성을 위한 구성

LangGraphAgentCoreMemorySaver의는 AgentCore 메모리 BLOB 유형를 통해 후드에서 대화 상태, 실행 컨텍스트 및 상태 변수의 모든 저장 및 로드를 처리합니다. 즉, 필요한 유일한 설정은 에이전트 그래프를 컴파일할 때 체크포인트를 지정한 다음 에이전트를 호출할 때 RunnableConfigthread_idactor_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 )

리소스