View a markdown version of this page

场景:使用 AgentCore 内存的客户支持 AI 代理 - Amazon Bedrock AgentCore

场景:使用 AgentCore 内存的客户支持 AI 代理

在本节中,您将学习如何构建客户支持人工智能代理,该代理使用 AgentCore 内存通过维护对话历史记录和提取有关用户偏好的长期见解来提供个性化帮助。本主题包括 AgentCore CLI 和 AWS SDK 的代码示例。

以客户莎拉为例,她与您的购物网站的支持人工智能代理接触,询问延迟的订单。通过 AgentCore 内存 API 的交互流程如下所示:

记忆内 AgentCore 存

步骤 1:创建内 AgentCore 存

首先,创建具有短期和长期记忆能力的内存资源,配置提取长期信息的策略。

AgentCore CLI
  1. 使用语义策略创建内存:

    agentcore add memory --name CustomerSupportSemantic --strategies SEMANTIC agentcore deploy
    注意

    C AgentCore LI 提供内存资源管理。要进行事件操作(创建事件、列出事件等),请使用 AWS Python SDK (Boto3) 或 AWS SDK。

Interactive
  1. 运行打开 agentcore TUI,然后选择添加并选择内存

  2. 选择语策略:

    记忆向导:选择语义策略
  3. 查看配置并按 Enter 进行确认:

    内存向导:查看配置
AWS SDK
  1. import boto3 import time from datetime import datetime # Initialize the Boto3 clients for control plane and data plane operations control_client = boto3.client('bedrock-agentcore-control') data_client = boto3.client('bedrock-agentcore') print("Creating a new memory resource...") # Create the memory resource with defined strategies response = control_client.create_memory( name="ShoppingSupportAgentMemory", description="Memory for a customer support agent.", memoryStrategies=[ { 'summaryMemoryStrategy': { 'name': 'SessionSummarizer', 'namespaceTemplates': ['/summaries/{actorId}/{sessionId}/'] } }, { 'userPreferenceMemoryStrategy': { 'name': 'UserPreferenceExtractor', 'namespaceTemplates': ['/users/{actorId}/preferences/'] } } ] ) memory_id = response['memory']['id'] print(f"Memory resource created with ID: {memory_id}") # Poll the memory status until it becomes ACTIVE while True: mem_status_response = control_client.get_memory(memoryId=memory_id) status = mem_status_response.get('memory', {}).get('status') if status == 'ACTIVE': print("Memory resource is now ACTIVE.") break elif status == 'FAILED': raise Exception("Memory resource creation FAILED.") print("Waiting for memory to become active...") time.sleep(10)

步骤 2:启动会话

当 Sarah 发起对话时,代理会创建一个新的、唯一的会话 ID 来单独跟踪此次互动。

# Unique identifier for the customer, Sarah sarah_actor_id = "user-sarah-123" # Unique identifier for this specific support session support_session_id = "customer-support-session-1" print(f"Session started for Actor ID: {sarah_actor_id}, Session ID: {support_session_id}")

第 3 步:捕获对话历史记录

当莎拉解释她的问题时,特工捕捉了对话的每一个转折(包括她的问题和经纪人的回答)。这会将完整的对话填充到短期记忆中,并为长期记忆策略的处理提供了原始数据。

print("Capturing conversational events...") full_conversation_payload = [ { 'conversational': { 'role': 'USER', 'content': {'text': "Hi, my order #ABC-456 is delayed."} } }, { 'conversational': { 'role': 'ASSISTANT', 'content': {'text': "I'm sorry to hear that, Sarah. Let me check the status for you."} } }, { 'conversational': { 'role': 'USER', 'content': {'text': "By the way, for future orders, please always use FedEx. I've had issues with other carriers."} } }, { 'conversational': { 'role': 'ASSISTANT', 'content': {'text': "Thank you for that information. I have made a note to use FedEx for your future shipments."} } } ] data_client.create_event( memoryId=memory_id, actorId=sarah_actor_id, sessionId=support_session_id, eventTimestamp=datetime.now(), payload=full_conversation_payload ) print("Conversation history has been captured in short-term memory.")

步骤 4:生成长期记忆

异步提取过程在后台运行。此过程使用您配置的内存策略分析最近的原始事件,以提取长期记忆,例如摘要、语义事实或用户偏好,然后将其存储起来以备将来使用。

步骤 5:从短期记忆中检索过去的互动

为了提供情境感知帮助,代理会加载当前的对话历史记录。这可以帮助代理了解Sarah在正在进行的聊天中提出了哪些问题。

print("\nRetrieving current conversation history from short-term memory...") response = data_client.list_events( memoryId=memory_id, actorId=sarah_actor_id, sessionId=support_session_id, maxResults=10 ) # Reverse the list of events to display them in chronological order event_list = reversed(response.get('events', [])) for event in event_list: print(event)

第 6 步:使用长期记忆获得个性化帮助

代理对提取的长期记忆进行语义搜索,以找到有关莎拉偏好、订单历史或过去担忧的相关见解。这使代理可以提供高度个性化的帮助,而无需让 Sarah 重复她在之前的聊天中已经分享过的信息。

# Wait for the asynchronous extraction to finish print("\nWaiting 60 seconds for long-term memory processing...") time.sleep(60) # --- Example 1: Retrieve the user's shipping preference --- print("\nRetrieving user preferences from long-term memory...") preference_response = data_client.retrieve_memory_records( memoryId=memory_id, namespace=f"/users/{sarah_actor_id}/preferences/", searchCriteria={"searchQuery": "Does the user have a preferred shipping carrier?"} ) for record in preference_response.get('memoryRecordSummaries', []): print(f"- Retrieved Record: {record}") # --- Example 2: Broad query about the user's issue (across sessions with the help of namespacePath) --- print("\nPerforming a broad search for user's reported issues...") issue_response = data_client.retrieve_memory_records( memoryId=memory_id, namespacePath=f"/summaries/{sarah_actor_id}/", searchCriteria={"searchQuery": "What problem did the user report with their order?"} ) for record in issue_response.get('memoryRecordSummaries', []): print(f"- Retrieved Record: {record}")

这种集成方法使代理能够在会话中维护丰富的背景信息,识别回头客,回忆重要细节,无缝提供个性化体验,从而提供更快、更自然、更有效的客户支持。