全部产品
Search
文档中心

云原生数据库 PolarDB:使用PolarSearch记忆容器为AI智能体(Agent)构建长短期记忆

更新时间:Jun 22, 2026

当AI 智能体(Agent)在多轮对话或执行连续任务时,往往因为缺乏对历史信息的有效记忆而无法记住用户的偏好、历史指令或上下文,导致交互体验中断、任务执行效率低下。PolarSearch记忆容器(Memory Container)专为解决此问题而设计。它为AI智能体提供了一个内置于PolarDB PostgreSQL版的长短期记忆管理系统。通过该功能,智能体能够自动地将对话信息结构化、持久化,并能在后续交互中通过语义检索快速调用相关记忆,从而为用户提供真正连续、个性化且高效的服务。

说明

PolarSearch记忆容器功能目前处于灰度阶段。若您有相关需求,请提交工单联系我们为您处理。

工作原理

PolarSearch记忆容器通过一套自动化的处理流程,将非结构化的对话数据转化为可检索、可利用的结构化记忆。其核心在于三级存储架构和智能化的记忆处理流程。

三级存储架构

为了平衡不同时效性记忆的存储和检索效率,记忆容器采用了分层设计:

记忆类型

索引类型

核心作用

短期记忆 (Working Memory)

倒排索引

存储原始的、未经处理的短期会话信息,使用倒排索引进行快速检索,主要用于维持当前对话的上下文。

长期记忆 (Long-Term Memory)

向量索引+倒排索引

通过大语言模型(LLM)从对话中提取关键事实(Facts),并将其向量化后存储。这部分记忆支持KNN语义搜索,用于深层次的经验和知识检索。

记忆历史 (Memory History)

倒排索引

记录每一次记忆操作(如新增、修改),形成完整的审计日志,确保记忆的演变过程可追溯。

记忆处理流程

当智能体接收到新的信息时,记忆容器会触发一系列处理动作,实现记忆的自动摄取、持久化和检索。

image
  1. 记忆摄取:

    • 输入与预处理:使用Elasticsearch协议接收来自智能体的对话输入,并可调用大语言模型(LLM)进行摘要生成、意图分类或标签提取等预处理。

    • 路由决策:记忆路由(Memory Router)分析输入内容,并与现有记忆进行比对,决策是新增(ADD)、更新(UPDATE)还是删除(DELETE)一条记忆。

  2. 记忆持久化:

    • 短期记忆:原始对话内容存入短期记忆。

    • 长期记忆:由LLM抽取的结构化记忆事实,经过Embedding模型向量化后,存入长期记忆。

    • 记忆历史:所有操作记录写入记忆历史,形成审计轨迹。

  3. 记忆检索:

    • 输入解析:接收检索条件,通过Elasticsearch协议解析多模态检索请求,调用权限验证模块确认数据访问边界。

    • 混合索引检索:在长期记忆中执行混合检索(ANN向量相似度搜索和倒排索引过滤),并在短期记忆中进行关键词匹配。同时根据记忆时间戳进行权重调整。

    • 结果整合:重排模型(Reranker)对检索结果进行优化排序,并根据时间戳等信息消除冲突,最终将最相关的记忆返回给智能体。

功能优势

能力维度

传统方案

PolarSearch解决方案

记忆利用率

历史数据沉淀低于30%,难以有效利用。

通过LLM抽取事实,结合语义索引,将有效信息利用率提升至85%以上。

检索效率

依赖关键词匹配,准确率≤60%。

采用向量与倒排混合索引,并进行重排序(Rerank),语义检索准确率可达95%以上。

企业合规

多租户隔离和权限管控实现复杂。

原生支持多租户隔离、RBAC权限控制和操作审计,满足企业级安全要求。

系统扩展性

单点存储容量上限TB级。

基于云原生分布式存储架构,存储容量可扩展至PB级。

开发成本

功能需定制开发,周期长。

提供开箱即用的API和SDK,简化开发流程,帮助您快速集成。

适用范围

快速开始

本指南将引导您完成从环境准备到成功存入并检索一条记忆的全过程。

整体流程:准备环境 -> 启用插件 -> 注册模型 -> 创建记忆容器 -> 存入与验证记忆。

步骤一:配置访问凭证与环境变量

在开始操作前,请先准备好以下信息,并设置为环境变量。这将有效简化后续的curl命令,避免重复修改。统一管理所有配置和凭证,方便后续命令的复制和执行。

变量名

含义

示例值

POLARSEARCH_HOST_PORT

PolarSearch节点的连接地址与端口。

pc-xxx.polardbsearch.rds.aliyuncs.com:3001

USER_PASSWORD

PolarSearch节点的管理员账号。

polarsearch_user:your_assword

YOUR_API_KEY

阿里云大模型服务平台百炼的API Key。

sk-xxxxxxxxxxxxxxxxxxxxxxxx

操作步骤: 在您的终端中执行以下命令,将示例值替换为您的真实信息。

# 设置 PolarSearch 访问地址和端口
export POLARSEARCH_HOST_PORT="pc-xxx.polardbsearch.rds.aliyuncs.com:3001"

# 设置 PolarSearch 管理员密码
export USER_PASSWORD="polarsearch_user:your_assword"

# 设置您的千问 API Key
export YOUR_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxx"

步骤二:启用记忆容器插件

执行以下命令,在PolarDB集群中启用记忆容器功能。

命令行

curl -XPUT "http://${POLARSEARCH_HOST_PORT}/_cluster/settings" \
--user "${USER_PASSWORD}" \
-H 'Content-Type: application/json' \
-d '{
  "persistent": {
    "plugins.ml_commons.agentic_memory_enabled": true
  }
}'

Dashboard

PUT _cluster/settings
{
  "persistent": {
    "plugins.ml_commons.agentic_memory_enabled": true
   }
}

步骤三:注册模型

您需要向PolarSearch注册一个用于事实抽取的LLM和一个用于语义化的Embedding模型。

注册文本向量化模型(Embedding)

创建一个连接器(Connector)指向阿里云大模型服务平台百炼的Embedding模型服务,并将其注册为PolarSearch可调用的模型。

  1. 设置可信端点:将模型的API Endpoint添加到可信列表,允许PolarSearch调用。

    命令行

    curl -XPUT "http://${POLARSEARCH_HOST_PORT}/_cluster/settings" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d '{
      "persistent": {
        "plugins.ml_commons.trusted_connector_endpoints_regex": [
          "^https://dashscope.aliyuncs.com/compatible-mode/v1/.*$"
        ]
      }
    }'
    

    Dashboard

    PUT _cluster/settings
    {
      "persistent": {
        "plugins.ml_commons.trusted_connector_endpoints_regex": [
          "^https://dashscope.aliyuncs.com/compatible-mode/v1/.*$"
        ]
      }
    }
  2. 创建模型连接器:配置连接text-embedding-v4模型的参数。

    说明

    pre_process_function和post_process_function用于适配不同模型服务的请求和响应格式。此处使用内置的openai.embedding格式转换函数,因为它与阿里云大模型服务平台百炼兼容模式的格式一致。

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/connectors/_create" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d '{
      "name": "qwen embedding connector",
      "description": "The connector to qwen embedding model",
      "version": 1,
      "protocol": "http",
      "parameters": {
        "model": "text-embedding-v4",
        "endpoint": "dashscope.aliyuncs.com/compatible-mode"
      },
      "credential": {
          "api_key": "${YOUR_API_KEY}"
      },
      "actions": [
        {
          "action_type": "predict",
          "method": "POST",
          "headers": {
            "Authorization": "Bearer ${credential.api_key}",
            "content-type": "application/json"
          },
          "url": "https://${parameters.endpoint}/v1/embeddings",
          "request_body": "{ \"model\": \"${parameters.model}\", \"input\": ${parameters.input} }",
          "pre_process_function": "connector.pre_process.openai.embedding",
          "post_process_function":"connector.post_process.openai.embedding"
          }
        ]
    }'

    Dashboard

    重要

    请替换以下命令中的<YOUR_API_KEY>为您真实的阿里云大模型服务平台百炼的API Key。

    POST _plugins/_ml/connectors/_create
    {
      "name": "qwen embedding connector",
      "description": "The connector to qwen embedding model",
      "version": 1,
      "protocol": "http",
      "parameters": {
        "model": "text-embedding-v4",
        "endpoint": "dashscope.aliyuncs.com/compatible-mode"
      },
      "credential": {
          "api_key": "<YOUR_API_KEY>"
      },
      "actions": [
        {
          "action_type": "predict",
          "method": "POST",
          "headers": {
            "Authorization": "Bearer ${credential.api_key}",
            "content-type": "application/json"
          },
          "url": "https://${parameters.endpoint}/v1/embeddings",
          "request_body": "{ \"model\": \"${parameters.model}\", \"input\": ${parameters.input} }",
          "pre_process_function": "connector.pre_process.openai.embedding",
          "post_process_function":"connector.post_process.openai.embedding"
          }
        ]
    }
  3. 执行成功后,系统会返回一个connector_id。请记录该ID,后续步骤将使用。

    {"connector_id": "LBFt6ZsBk04xxx"}
  4. 注册模型:此步骤将上一步创建的Connector注册为一个模型。

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/models/_register" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d '{
      "name": "qwen embedding model",
      "function_name": "remote",
      "description": "Embedding model for memory",
      "connector_id": "LBFt6Zsxxx"
    }'

    Dashboard

    POST _plugins/_ml/models/_register
    {
      "name": "qwen embedding model",
      "function_name": "remote",
      "description": "Embedding model for memory",
      "connector_id": "LBFt6ZsBk04xxx"
    }

    执行成功后,系统会返回一个 model_id。请记录该 ID,后续步骤将使用。

    # 记录返回的 model_id
    {"task_id": "LRFx6ZsBk04ixxx","status": "CREATED","model_id": "LhFx6ZsBk04xxx"}
  5. 测试模型:通过下述查询可以直接与大模型对话并查看大模型返回结果。

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/_predict/text_embedding/<上一步获取的模型ID>" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d'{
      "text_docs":[ "Bob likes swimming. Context: He expressed his interest in swimming."],
      "return_number": true,
      "target_response": ["sentence_embedding"]
    }'

    Dashboard

    POST _plugins/_ml/_predict/text_embedding/<上一步获取的模型ID>
    {
      "text_docs":[ "Bob likes swimming. Context: He expressed his interest in swimming."],
      "return_number": true,
      "target_response": ["sentence_embedding"]
    }

    预期返回结果如下:

    {
      "inference_results": [
        {
          "output": [
            {
              "name": "sentence_embedding",
              "data_type": "FLOAT32",
              "shape": [
                1024
              ],
              "data": [
                0.019752666354179382,
                -0.03468115255236626,
                0.05591931194067001,
                ...
              ]
            }
          ],
          "status_code": 200
        }
      ]
    }

注册文本生成模型(LLM)

创建并注册一个连接到阿里云大模型服务平台百炼qwen-plus大模型的连接器。

  1. 创建模型连接器(Connector):

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/connectors/_create" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d '{
      "name": "QWen LLM Connector",
      "description": "The connector to qwen LLM",
      "version": 1,
      "protocol": "http",
      "parameters": {
        "model": "qwen-plus",
        "endpoint": "dashscope.aliyuncs.com/compatible-mode"
      },
      "credential": {
          "api_key": "${YOUR_API_KEY}"
      },
      "actions": [
        {
          "action_type": "predict",
          "method": "POST",
          "headers": {
            "Authorization": "Bearer ${credential.api_key}",
            "content-type": "application/json"
          },
          "url": "https://${parameters.endpoint}/v1/chat/completions",
          "request_body": "{ \"model\":\"${parameters.model}\", \"system\": \"${parameters.system_prompt}\", \"messages\": [ { \"role\": \"system\", \"content\": \"${parameters.system_prompt}\" }, { \"role\": \"user\", \"content\": \"${parameters.user_prompt}\" } ], \"response_format\": { \"type\": \"json_object\" } }"
          }
        ]
    }'

    Dashboard

    重要

    请替换以下命令中的<YOUR_API_KEY>为您真实的阿里云大模型服务平台百炼的API Key。

    POST /_plugins/_ml/connectors/_create
    {
      "name": "QWen LLM Connector",
      "description": "The connector to qwen LLM",
      "version": 1,
      "protocol": "http",
      "parameters": {
        "model": "qwen-plus",
        "endpoint": "dashscope.aliyuncs.com/compatible-mode"
      },
      "credential": {
          "api_key": "<YOUR_API_KEY>"
      },
      "actions": [
        {
          "action_type": "predict",
          "method": "POST",
          "headers": {
            "Authorization": "Bearer ${credential.api_key}",
            "content-type": "application/json"
          },
          "url": "https://${parameters.endpoint}/v1/chat/completions",
          "request_body": "{ \"model\":\"${parameters.model}\", \"system\": \"${parameters.system_prompt}\", \"messages\": [ { \"role\": \"system\", \"content\": \"${parameters.system_prompt}\" }, { \"role\": \"user\", \"content\": \"${parameters.user_prompt}\" } ], \"response_format\": { \"type\": \"json_object\" } }"
          }
        ]
    }
  2. 执行成功后,系统会返回一个connector_id。请记录该ID,后续步骤将使用。

    {"connector_id": "PRGy6ZsBk04xxx"}
  3. 注册模型:此步骤将上一步创建的Connector注册为一个模型。

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/models/_register" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d '{
      "name": "qwen llm model",
      "function_name": "remote",
      "description": "LLM model for memory",
      "connector_id": "PRGy6ZsBk04xxx"
    }'

    Dashboard

    POST _plugins/_ml/models/_register
    {
      "name": "qwen llm model",
      "function_name": "remote",
      "description": "LLM model for memory",
      "connector_id": "PRGy6ZsBk04xxx"
    }

    执行成功后,系统会返回一个 model_id。请记录该 ID,后续步骤将使用。

    # 记录返回的 model_id
    {"task_id": "PhGy6ZsBk04xxx","status": "CREATED","model_id": "PxGy6ZsBk04xxx"}
  4. 发布模型:

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/models/<上一步获取的模型ID>/_deploy" \
    --user "${USER_PASSWORD}"

    Dashboard

    POST _plugins/_ml/models/<上一步获取的模型ID>/_deploy

    执行成功后,如果status为COMPLETED代表已部署成功。

    {"task_id": "NxGI6ZsBk04xxx","task_type": "DEPLOY_MODEL","status": "COMPLETED"}
  5. 测试模型:通过下述查询可以直接与大模型对话并查看大模型返回结果。

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/models/<上一步获取的模型ID>/_predict" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d'{
      "parameters": {
        "system_prompt": "<ROLE>You are a USER PREFERENCE EXTRACTOR, not a chat assistant. Your only job is to output JSON facts. Do not answer questions, make suggestions, ask follow-ups, or perform actions.</ROLE>\n\n<SCOPE>\n• Extract preferences only from USER messages. Assistant messages are context only.\n• Explicit: user states a preference (\"I prefer/like/dislike ...\"; \"always/never/usually ...\"; \"set X to Y\"; \"run X when Y\").\n• Implicit: infer only with strong signals: repeated choices (>=2) or clear habitual language. Do not infer from a single one-off.\n</SCOPE>\n\n<EXTRACT>\n• Specific, actionable, likely long-term preferences (likes/dislikes/choices/settings). Ignore non-preferences.\n</EXTRACT>\n\n<STYLE & RULES>\n• One sentence per preference; merge related details; no duplicates; preserve user wording and numbers; avoid relative time; keep each fact < 350 chars.\n• Format: \"Preference sentence. Context: <why/how>. Categories: cat1,cat2\"\n</STYLE & RULES>\n\n<OUTPUT>\nReturn ONLY one minified JSON object exactly as {\"facts\":[\"Preference sentence. Context: <why/how>. Categories: cat1,cat2\"]}. If none, return {\"facts\":[]}. The first character MUST be '{' and the last MUST be '}'. No preambles, explanations, code fences, XML, or other text.\n</OUTPUT>",
        "user_prompt": "I am Alice, I like travel."
      }
    }'

    Dashboard

    POST _plugins/_ml/models/<上一步获取的模型ID>/_predict
    {
      "parameters": {
        "system_prompt": "<ROLE>You are a USER PREFERENCE EXTRACTOR, not a chat assistant. Your only job is to output JSON facts. Do not answer questions, make suggestions, ask follow-ups, or perform actions.</ROLE>\n\n<SCOPE>\n• Extract preferences only from USER messages. Assistant messages are context only.\n• Explicit: user states a preference (\"I prefer/like/dislike ...\"; \"always/never/usually ...\"; \"set X to Y\"; \"run X when Y\").\n• Implicit: infer only with strong signals: repeated choices (>=2) or clear habitual language. Do not infer from a single one-off.\n</SCOPE>\n\n<EXTRACT>\n• Specific, actionable, likely long-term preferences (likes/dislikes/choices/settings). Ignore non-preferences.\n</EXTRACT>\n\n<STYLE & RULES>\n• One sentence per preference; merge related details; no duplicates; preserve user wording and numbers; avoid relative time; keep each fact < 350 chars.\n• Format: \"Preference sentence. Context: <why/how>. Categories: cat1,cat2\"\n</STYLE & RULES>\n\n<OUTPUT>\nReturn ONLY one minified JSON object exactly as {\"facts\":[\"Preference sentence. Context: <why/how>. Categories: cat1,cat2\"]}. If none, return {\"facts\":[]}. The first character MUST be '{' and the last MUST be '}'. No preambles, explanations, code fences, XML, or other text.\n</OUTPUT>",
        "user_prompt": "I am Alice, I like travel."
      }
    }

    预期返回结果如下:

    {
      "inference_results": [
        {
          "output": [
            {
              "name": "response",
              "dataAsMap": {
                "choices": [
                  {
                    "message": {
                      "role": "assistant",
                      "content": """{"facts":["I like travel. Context: Stated preference. Categories: interest"]}"""
                    },
                    "finish_reason": "stop",
                    "index": 0,
                    "logprobs": null
                  }
                ],
                "object": "chat.completion",
                "usage": {
                  "prompt_tokens": 325,
                  "completion_tokens": 17,
                  "total_tokens": 342,
                  "prompt_tokens_details": {
                    "cached_tokens": 0
                  }
                },
                "created": 1769152651,
                "system_fingerprint": null,
                "model": "qwen-plus",
                "id": "chatcmpl-50c6bfc9-xxx-xxx-xxx-1a39cfe080f5"
              }
            }
          ],
          "status_code": 200
        }
      ]
    }

步骤四:创建记忆容器

  1. 创建一个记忆容器实例,并配置其使用的模型、存储策略和自动化行为。执行以下命令创建一个名为agentic memory test的记忆容器。

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/memory_containers/_create" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d'{
      "name": "my agentic memory test",
      "description": "Store conversations with semantic search and summarization",
      "configuration": {
        "embedding_model_type": "TEXT_EMBEDDING",
        "embedding_model_id": "<上一步获取的Embedding模型ID>",
        "embedding_dimension": 1024,
        "llm_id": "<上一步获取的LLM模型ID>",
        "index_prefix": "mem_test",
        "index_settings": {
          "short_term_memory_index": {
            "index": {
              "number_of_shards": "2",
              "number_of_replicas": "2"
            }
          },
          "long_term_memory_index": {
            "index": {
              "number_of_shards": "2",
              "number_of_replicas": "2"
            }
          },
          "long_term_memory_history_index": {
            "index": {
              "number_of_shards": "2",
              "number_of_replicas": "2"
            }
          }
        },
        "strategies": [
          {
            "type": "SEMANTIC",
            "namespace": ["user_id"],
            "configuration": {
              "llm_result_path": "$.choices[0].message.content"
            }
          },
          {
            "type": "USER_PREFERENCE",
            "namespace": ["user_id"],
            "configuration": {
              "llm_result_path": "$.choices[0].message.content"
            }
          },
          {
            "type": "SUMMARY",
            "namespace": ["agent_id"],
            "configuration": {
              "llm_result_path": "$.choices[0].message.content"
            }
          }
        ],
        "parameters": {
          "llm_result_path": "$.choices[0].message.content"
        }
      }
    }'

    Dashboard

    POST _plugins/_ml/memory_containers/_create
    {
      "name": "my agentic memory test",
      "description": "Store conversations with semantic search and summarization",
      "configuration": {
        "embedding_model_type": "TEXT_EMBEDDING",
        "embedding_model_id": "<上一步获取的Embedding模型ID>",
        "embedding_dimension": 1024,
        "llm_id": "<上一步获取的LLM模型ID>",
        "index_prefix": "mem_test",
        "index_settings": {
          "short_term_memory_index": {
            "index": {
              "number_of_shards": "2",
              "number_of_replicas": "2"
            }
          },
          "long_term_memory_index": {
            "index": {
              "number_of_shards": "2",
              "number_of_replicas": "2"
            }
          },
          "long_term_memory_history_index": {
            "index": {
              "number_of_shards": "2",
              "number_of_replicas": "2"
            }
          }
        },
        "strategies": [
          {
            "type": "SEMANTIC",
            "namespace": ["user_id"],
            "configuration": {
              "llm_result_path": "$.choices[0].message.content"
            }
          },
          {
            "type": "USER_PREFERENCE",
            "namespace": ["user_id"],
            "configuration": {
              "llm_result_path": "$.choices[0].message.content"
            }
          },
          {
            "type": "SUMMARY",
            "namespace": ["agent_id"],
            "configuration": {
              "llm_result_path": "$.choices[0].message.content"
            }
          }
        ],
        "parameters": {
          "llm_result_path": "$.choices[0].message.content"
        }
      }
    }

    参数说明

    • index_prefix:为该容器创建的内部索引(如短期、长期记忆索引)的统一前缀。

    • index_settings:可为不同记忆索引配置分片(shards)和副本(replicas)数量,以实现高可用。

    • strategies:定义自动化策略。本例中定义了一个SEMANTIC策略,它会在user_id这个命名空间 (Namespace) 下,自动从对话中提取语义事实。

    • llm_result_path:使用JSONPath语法,指定如何从LLM返回的JSON响应中提取核心内容。$.choices[0].message.content适配了阿里云大模型服务平台百炼兼容模式的响应结构。

  2. 执行成功后,系统会返回一个memory_container_id。请记录该 ID,后续步骤将使用。

    # 记录返回的 model_id
    {"memory_container_id": "QRHF6ZsBk04xxx","status": "created"}

    创建记忆容器后,实际将创建以下索引和管道(pipeline):

    .plugins-ml-am-mem_test-memory-long-term
    .plugins-ml-am-mem_test-memory-working
    .plugins-ml-am-mem_test-memory-history
    .plugins-ml-am-mem_test-memory-long-term-embedding" : {
        "description" : "Agentic Memory Text embedding pipeline",
        "processors" : [
          {
            "text_embedding" : {
              "model_id" : "QRHF6ZsBk04xxx",
              "field_map" : {
                "memory" : "memory_embedding"
              }
            }
          }
        ]
    }

步骤五:存入与验证记忆

向记忆容器中添加一段对话,并验证其是否被正确地存入短期和长期记忆中。

  1. 存入记忆: 向容器中POST一段关于用户Bob的对话。"infer": true参数会触发之前配置的SEMANTIC策略,调用LLM提取事实。

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/memory_containers/<上一步创建的记忆容器ID>/memories" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d'{
       "messages": [
          {
          "role": "user",
          "content":  [
            {
              "text": "I am Bob, I really like swimming.",
              "type": "text"
            }
          ]
        },
        {
          "role": "assistant",
          "content":  [
            {
              "text": "Cool, nice. Hope you enjoy your life.",
              "type": "text"
            }
          ]
        }
        ],
      "namespace": {
        "user_id": "bob"
      },
      "tags": {
        "topic": "personal info"
      },
      "infer": true,
      "memory_type": "conversation"
    }'

    Dashboard

    POST _plugins/_ml/memory_containers/<memory_container_id>/memories
    {
       "messages": [
          {
          "role": "user",
          "content":  [
            {
              "text": "I am Bob, I really like swimming.",
              "type": "text"
            }
          ]
        },
        {
          "role": "assistant",
          "content":  [
            {
              "text": "Cool, nice. Hope you enjoy your life.",
              "type": "text"
            }
          ]
        }
        ],
      "namespace": {
        "user_id": "bob"
      },
      "tags": {
        "topic": "personal info"
      },
      "infer": true,
      "memory_type": "conversation"
    }
  2. 验证短期记忆: 直接查询为短期记忆创建的索引,可以看到原始对话被完整保存。

    命令行

    curl -XGET "http://${POLARSEARCH_HOST_PORT}/.plugins-ml-am-<上一步创建的记忆容器index_prefix>-memory-working/_search?pretty" \
    --user "${USER_PASSWORD}" \

    Dashboard

    GET .plugins-ml-am-<上一步创建的记忆容器index_prefix>-memory-working/_search?pretty

    预期输出(部分展示):

    {
      "_source" : {
        "memory_container_id": "QRHF6ZsBk04xxx",
        "payload_type" : "conversational",
        "messages" : [
          { "role" : "user", "content": [{ "text": "I am Bob, I really like swimming.","type": "text"}] },
          { "role" : "assistant", "content": [{ "text": "Cool, nice. Hope you enjoy your life.","type": "text"}] }
        ],
        "namespace" : { "user_id" : "bob" }
      }
    }
  3. 验证长期记忆: 查询长期记忆索引,可以看到LLM成功提取了核心事实“Bob likes swimming”,并由Embedding模型生成了对应的向量memory_embedding。

    命令行

    curl -XGET "http://${POLARSEARCH_HOST_PORT}/.plugins-ml-am-<上一步创建的记忆容器index_prefix>-memory-long-term/_search?pretty" \
    --user "${USER_PASSWORD}" \

    Dashboard

    GET .plugins-ml-am-<上一步创建的记忆容器index_prefix>-memory-long-term/_search?pretty

    预期输出(部分展示):

    {
      "_source" : {
        "created_time": 1769155210918,
        "memory": "Bob likes swimming.",
        "memory_container_id": "QRHF6ZsBk04xxx",
        "tags": {
          "topic": "personal info"
        },
        "last_updated_time": 1769155210918,
        "memory_embedding" : [ 0.0195..., -0.0387..., ... ],
        "namespace" : { "user_id" : "bob" }
      }
    }
  4. 查看记录历史,memory-history索引中有两条ADD记录和对应的记忆时间戳。

    命令行

    curl -XGET "http://${POLARSEARCH_HOST_PORT}/.plugins-ml-am-<上一步创建的记忆容器index_prefix>-memory-history/_search?pretty" \
    --user "${USER_PASSWORD}" \

    Dashboard

    GET .plugins-ml-am-<上一步创建的记忆容器index_prefix>-memory-history/_search?pretty

    预期输出(部分展示):

    {
      "_source": {
        "created_time": 1769155211164,
        "memory_id": "TBHe6ZsBk04xxx",
        "namespace_size": 1,
        "namespace": {
          "user_id": "bob"
        },
        "action": "ADD",
        "memory_container_id": "QRHF6ZsBk04xxx",
        "after": {
          "memory": "Bob likes swimming."
        },
        "tags": {
          "topic": "personal info"
        }
      }
    }

至此,您已成功为AI智能体存入了一条可供长期检索的记忆。

步骤六:(可选)更新记忆

记忆容器能够提取和更新长期记忆。

  1. 首先插入一段记忆:

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/memory_containers/<上一步创建的记忆容器ID>/memories" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d'{
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "text": "我叫NameA,我来自AreaA,目前我居住在AreaB.",
              "type": "text"
            }
          ]
        },
        {
          "role": "assistant",
          "content": [
            {
              "text": "你好,NameA!很高兴认识你.",
              "type": "text"
            }
          ]
        }
      ],
      "namespace": {
        "user_id": "NameA"
      },
      "tags": {
        "topic": "personal info"
      },
      "infer": true,
      "memory_type": "conversation"
    }'

    Dashboard

    POST _plugins/_ml/memory_containers/<memory_container_id>/memories
    {
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "text": "我叫NameA,我来自AreaA,目前我居住在AreaB.",
              "type": "text"
            }
          ]
        },
        {
          "role": "assistant",
          "content": [
            {
              "text": "你好,NameA!很高兴认识你.",
              "type": "text"
            }
          ]
        }
      ],
      "namespace": {
        "user_id": "NameA"
      },
      "tags": {
        "topic": "personal info"
      },
      "infer": true,
      "memory_type": "conversation"
    }
  2. 搜索长期记忆索引:

    命令行

    curl -XGET "http://${POLARSEARCH_HOST_PORT}/.plugins-ml-am-<上一步创建的记忆容器index_prefix>-memory-long-term/_search" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d'{
      "_source": {
        "excludes": ["memory_embedding"]
      },
      "query": {
        "match_all": {}
      }
    }'

    Dashboard

    GET .plugins-ml-am-<上一步创建的记忆容器index_prefix>-memory-long-term/_search
    {
      "_source": {
        "excludes": ["memory_embedding"]
      },
      "query": {
        "match_all": {}
      }
    }

    预期输出(部分展示):

    {
      "hits": [
          {
            "_source": {
              "created_time": 1769156096335,
              "memory": "NameA is from AreaA.",
              "last_updated_time": 1769156096335,
              "namespace": {
                "user_id": "NameA"
              },
              "memory_container_id": "QRHF6ZsBk04xxx",
              "tags": {
                "topic": "personal info"
              }
            }
          },
          {
            "_source": {
              "created_time": 1769156096335,
              "memory": "NameA currently resides in AreaB.",
              "last_updated_time": 1769156096335,
              "namespace": {
                "user_id": "NameA"
              },
              "memory_container_id": "QRHF6ZsBk04xxx",
              "tags": {
                "topic": "personal info"
              }
            }
          }
       ]
    }
  3. 再次插入一段记忆,记忆内容与先前插入的存在冲突:

    命令行

    curl -XPOST "http://${POLARSEARCH_HOST_PORT}/_plugins/_ml/memory_containers/<上一步创建的记忆容器ID>/memories" \
    --user "${USER_PASSWORD}" \
    -H 'Content-Type: application/json' \
    -d'{
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "text": "我叫NameA,目前我居住在AreaC.",
              "type": "text"
            }
          ]
        },
        {
          "role": "assistant",
          "content": [
            {
              "text": "你好,NameA!很高兴认识你.",
              "type": "text"
            }
          ]
        }
      ],
      "namespace": {
        "user_id": "NameA"
      },
      "tags": {
        "topic": "personal info"
      },
      "infer": true,
      "memory_type": "conversation"
    }'

    Dashboard

    POST _plugins/_ml/memory_containers/<memory_container_id>/memories
    {
      "messages": [
        {
          "role": "user",
          "content": [
            {
              "text": "我叫NameA,目前我居住在AreaC.",
              "type": "text"
            }
          ]
        },
        {
          "role": "assistant",
          "content": [
            {
              "text": "你好,NameA!很高兴认识你.",
              "type": "text"
            }
          ]
        }
      ],
      "namespace": {
        "user_id": "NameA"
      },
      "tags": {
        "topic": "personal info"
      },
      "infer": true,
      "memory_type": "conversation"
    }
  4. 再次搜索长期记忆索引看到内容已经更新(部分展示):

    {
      "hits": [
          {
            "_source": {
              "created_time": 1769156096335,
              "memory": "NameA resides in AreaC.",
              "last_updated_time": 1769156493970,
              "namespace": {
                "user_id": "NameA"
              },
              "memory_container_id": "QRHF6ZsBk04xxx",
              "tags": {
                "topic": "personal info"
              }
            }
          }
       ]
    }

场景实践:构建一个旅行记忆智能体

本节将展示如何利用记忆容器的API,构建一个可以记录用户旅行偏好并提供个性化建议的Python智能体。

准备工作

在运行代码前,请确保已安装必要的Python库。在requirements.txt文件中添加如下依赖库。

requests
openai

执行pip install -r requirements.txt进行安装。

核心代码解析

以下是与记忆容器交互的关键函数:

  • opensearch_request():封装了对PolarSearch API的HTTP请求,统一处理认证和错误。

  • add_memory():调用记忆容器的memories接口,将新的对话信息存入记忆。

  • search_memories():调用_search接口,在长期和短期记忆中检索与用户查询相关的信息。

  • generate_response_with_memories():将检索到的记忆作为上下文,连同用户当前问题一起提交给LLM,生成更具个性化的回复。

完整示例代码

以下是经过安全修复和逻辑优化的完整Python脚本。请将代码保存为trip_agent.py,并根据提示设置环境变量。

单击展开查看详细代码示例

#!/usr/bin/env python3
"""
Trip Memory Agent - A simplified memory agent that tracks user information
and manages memories using OpenSearch as the backend.
"""
import os
import json
import requests
from requests.auth import HTTPBasicAuth
import urllib3
from typing import Optional, List, Dict, Any

# Disable HTTPS warnings for local development
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Import OpenAI library for LLM operations
import openai

# --- Configuration from Environment Variables ---
OPENSEARCH_URL = os.getenv('OPENSEARCH_URL')
OPENSEARCH_USERNAME = os.getenv('OPENSEARCH_USERNAME', 'admin')
OPENSEARCH_PASSWORD = os.getenv('OPENSEARCH_PASSWORD')
CONTAINER_ID = os.getenv('MEM_CONTAINER_ID')
QWEN_API_KEY = os.getenv('QWEN_API_KEY')
QWEN_BASE_URL = os.getenv('QWEN_BASE_URL', 'https://dashscope.aliyuncs.com/compatible-mode/v1')
QWEN_MODEL_NAME = os.getenv('QWEN_MODEL_NAME', 'qwen-max')

# Global variable to store current user ID
current_user_id = None

# Global OpenAI client instance
llm_client = None


# --- OpenSearch Helper ---
def opensearch_request(method: str, endpoint: str, json_data: Optional[Dict] = None) -> requests.Response:
    """Make an HTTP request to the OpenSearch API."""
    if not all([OPENSEARCH_URL, OPENSEARCH_USERNAME, OPENSEARCH_PASSWORD, CONTAINER_ID]):
        raise ValueError("OpenSearch environment variables are not fully configured.")

    url = f"{OPENSEARCH_URL}{endpoint}"
    auth = HTTPBasicAuth(OPENSEARCH_USERNAME, OPENSEARCH_PASSWORD)
    try:
        response = getattr(requests, method.lower())(url, json=json_data, auth=auth, verify=False, timeout=20)
        response.raise_for_status()
        return response
    except requests.exceptions.RequestException as e:
        print(f"Error communicating with OpenSearch: {e}")
        # Return a mock response to prevent crashes, or handle more gracefully
        # For this example, we re-raise to make the error obvious
        raise e


# --- User Management ---
def get_user_id():
    """Get user ID from global variable or prompt the user."""
    global current_user_id
    if not current_user_id:
        print("=" * 50)
        print("Welcome to the Trip Memory Agent!")
        print("=" * 50)
        print("Hello! I don't know you yet. Please tell me your name:")
        user_input = input("> ")
        current_user_id = user_input.strip()
        print(f"Nice to meet you, {current_user_id}!")
    return current_user_id


# --- LLM-Powered Helper Functions ---
def is_trip_plan_request(query: str) -> bool:
    """Determine if a user's query is a request for a trip plan using an LLM."""
    if not query.strip():
        return False
    try:
        prompt = f"""请判断以下用户输入是否是在请求制定旅行计划(旅行规划)。
请只回答"YES"或"NO",不需要其他解释。
用户输入: {query}"""
        response = llm_client.chat.completions.create(
            model=QWEN_MODEL_NAME,
            messages=[{"role": "user", "content": prompt}],
            max_tokens=10,
            temperature=0.0
        )
        result = response.choices[0].message.content.strip().upper()
        return result == "YES"
    except Exception as e:
        print(f"Error detecting trip plan request with LLM: {e}. Falling back to keywords.")
        keywords = ['plan a trip', 'trip plan', 'plan my travel', 'travel plan']
        return any(keyword in query.lower() for keyword in keywords)


def extract_keywords(query: str) -> List[str]:
    """Extract keywords from a query using an LLM for better search results."""
    try:
        prompt = f"""Extract the most important keywords from the following query for search purposes.
Focus on locations, activities, and specific preferences.
Return only a JSON array of strings (keywords).
Query: {query}"""
        response = llm_client.chat.completions.create(
            model=QWEN_MODEL_NAME,
            messages=[{"role": "user", "content": prompt}],
            max_tokens=100,
            temperature=0.0
        )
        extracted_content = response.choices[0].message.content.strip()
        return json.loads(extracted_content)
    except (Exception, json.JSONDecodeError) as e:
        print(f"Error extracting keywords with LLM: {e}. Falling back to splitting query.")
        return query.split()


def generate_response_with_memories(query: str, search_results: List[Dict]) -> str:
    """Generate a response using an LLM with memory context."""
    if not search_results:
        return "I couldn't find any relevant memories for your query."

    context = "Here is relevant information I found in your memories:\n"
    for result in search_results:
        context += f"- {result['content']}\n"

    prompt = f"""You are a helpful trip planning assistant. Based on the user's past memories and their current request, generate a helpful and personalized response.

{context}
User's current request: {query}

Your response:"""
    try:
        response = llm_client.chat.completions.create(
            model=QWEN_MODEL_NAME,
            messages=[{"role": "system", "content": prompt}],
            max_tokens=1024,
            temperature=0.7
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        print(f"Error generating response with LLM: {e}")
        return "I found some memories, but I encountered an error while trying to generate a response."


# --- Core Memory Management Functions (Our "Tools") ---

def add_memory(message: str) -> Dict[str, Any]:
    """Add a new piece of information (a memory) for the current user."""
    global current_user_id
    payload = {
        "messages": [{"role": "user", "content": [{"text": message, "type": "text"}]}],
        "infer": True,
        "memory_type": "conversation",
        "namespace": {"user_id": current_user_id}
    }
    response = opensearch_request("POST", f"/_plugins/_ml/memory_containers/{CONTAINER_ID}/memories", payload)
    return response.json()


def search_memories(query: str) -> Dict[str, Any]:
    """Search the user's memories based on a query."""
    global current_user_id
    keywords = extract_keywords(query)

    search_query = {
        "query": {
            "bool": {
                "must": [{"term": {"namespace.user_id": current_user_id}}],
                "should": [
                    {"multi_match": {"query": " ".join(keywords), "fields": ["memory", "messages.content.text"]}}],
                "minimum_should_match": 1 if keywords else 0
            }
        },
        "sort": [{"created_time": {"order": "desc"}}],
        "size": 10  # Limit number of results
    }

    all_hits = []
    for index_suffix in ["long-term", "working"]:
        try:
            response = opensearch_request("POST",
                                          f"/_plugins/_ml/memory_containers/{CONTAINER_ID}/memories/{index_suffix}/_search",
                                          search_query)
            result = response.json()
            if "hits" in result and "hits" in result["hits"]:
                all_hits.extend(result["hits"]["hits"])
        except Exception as e:
            print(f"Error searching {index_suffix} memory: {e}")

    all_hits.sort(key=lambda x: x.get('_source', {}).get('created_time', ''), reverse=True)

    formatted_results = []
    for hit in all_hits:
        source = hit.get('_source', {})
        content = source.get('memory', '')
        if not content and 'messages' in source:
            content = " ".join(
                item['text'] for msg in source['messages'] if 'content' in msg
                for item in msg['content'] if isinstance(item, dict) and 'text' in item
            )

        index_type = "long-term" if 'long-term' in hit.get('_index', '') else "working"
        formatted_results.append({
            "memory_id": hit.get('_id'),
            "index_type": index_type,
            "timestamp": source.get('created_time'),
            "content": content.strip()
        })
    return {"status": "success", "results": formatted_results, "total_found": len(formatted_results)}


def find_and_update_memory(query: str, new_text: str) -> Dict[str, Any]:
    """Find a memory based on a query and update its content."""
    search_result = search_memories(query)
    if not search_result["results"]:
        return {"status": "error", "message": "No matching memory found to update."}

    # Update the most recent/relevant memory
    memory_to_update = search_result["results"][0]
    memory_id = memory_to_update["memory_id"]
    index_type = memory_to_update["index_type"]

    payload = {"memory": new_text}
    response = opensearch_request("PUT",
                                  f"/_plugins/_ml/memory_containers/{CONTAINER_ID}/memories/{index_type}/{memory_id}",
                                  payload)
    return {"status": "success", "updated_memory_id": memory_id, "details": response.json()}


def find_and_delete_memory(query: str) -> Dict[str, Any]:
    """Find a memory based on a query and delete it."""
    search_result = search_memories(query)
    if not search_result["results"]:
        return {"status": "error", "message": "No matching memory found to delete."}

    # Delete the most recent/relevant memory
    memory_to_delete = search_result["results"][0]
    memory_id = memory_to_delete["memory_id"]
    index_type = memory_to_delete["index_type"]

    response = opensearch_request("DELETE",
                                  f"/_plugins/_ml/memory_containers/{CONTAINER_ID}/memories/{index_type}/{memory_id}")
    return {"status": "success", "deleted_memory_id": memory_id, "details": response.json()}


# --- Agent Logic ---

def main():
    """Main function to run the trip memory agent without 'strands'."""
    global llm_client

    # --- Initialization ---
    if not all([QWEN_API_KEY, QWEN_BASE_URL, QWEN_MODEL_NAME]):
        print("Error: Qwen LLM environment variables are not configured.")
        return

    llm_client = openai.OpenAI(api_key=QWEN_API_KEY, base_url=QWEN_BASE_URL)
    get_user_id()

    # --- Tool Definitions for the LLM ---
    tools = [
        {
            "type": "function",
            "function": {
                "name": "add_memory",
                "description": "Adds a new piece of information or a memory about the user. Use this to remember user preferences, facts, or past events.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "message": {
                            "type": "string",
                            "description": "The information or content of the memory to be saved. e.g., 'I love to visit historical museums.'"
                        }
                    },
                    "required": ["message"]
                }
            }
        },
        {
            "type": "function",
            "function": {
                "name": "search_memories",
                "description": "Searches for and retrieves existing memories about the user. Use this when the user asks what you know about them, asks for past information, or wants a trip plan based on their preferences.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "The search query to find relevant memories. e.g., 'my preferences', 'what do you know about me', 'trip to Paris'"
                        }
                    },
                    "required": ["query"]
                }
            }
        },
        {
            "type": "function",
            "function": {
                "name": "find_and_update_memory",
                "description": "Finds a specific memory using a search query and updates its content with new text.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {"type": "string",
                                  "description": "A query to identify the memory to update. e.g., 'my favorite food'"},
                        "new_text": {"type": "string",
                                     "description": "The new content for the memory. e.g., 'My favorite food is now ramen.'"}
                    },
                    "required": ["query", "new_text"]
                }
            }
        },
        {
            "type": "function",
            "function": {
                "name": "find_and_delete_memory",
                "description": "Finds a specific memory using a search query and deletes it.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "query": {"type": "string",
                                  "description": "A query to identify the memory to delete. e.g., 'my old address'"}
                    },
                    "required": ["query"]
                }
            }
        }
    ]

    # Map tool names to actual Python functions
    available_tools = {
        "add_memory": add_memory,
        "search_memories": search_memories,
        "find_and_update_memory": find_and_update_memory,
        "find_and_delete_memory": find_and_delete_memory,
    }

    system_prompt = f"""You are a trip assistant for a user named {current_user_id}. Your job is to help them by managing their memories and planning trips.
You have access to the following tools: `add_memory`, `search_memories`, `update_memory`, and `delete_memory`.
- When a user provides new information about themselves, use `add_memory`.
- When a user asks what you know about them, asks for their preferences, or wants a trip plan, use `search_memories` to get context first.
- When a user wants to change a piece of information, use `find_and_update_memory`.
- When a user wants to forget something, use `find_and_delete_memory`.
- Always respond to the user in a friendly and conversational manner. After a tool is used, explain what you did in simple terms."""

    messages = [{"role": "system", "content": system_prompt}]

    print("\nTrip Memory Agent is ready!")
    print(f"Hello {current_user_id}! I can remember things for you, search your memories, and help plan trips.")

    # --- Main Interaction Loop ---
    while True:
        try:
            user_input = input(f"\n{current_user_id}> ")
            if user_input.lower() in ['quit', 'exit', 'bye']:
                print("Goodbye!")
                break

            messages.append({"role": "user", "content": user_input})

            # Special fast-path for trip planning
            if is_trip_plan_request(user_input):
                print("This looks like a trip plan request. Searching memories for context...")
                search_result = search_memories(user_input)
                if search_result.get("total_found", 0) > 0:
                    print("Found relevant memories! Generating a personalized plan...")
                    response = generate_response_with_memories(user_input, search_result["results"])
                    print(f"\nAgent: {response}")
                else:
                    print("I couldn't find any relevant memories to help with that plan. Let's start from scratch!")
                    # Let the general agent handle it now
                    pass
                messages.pop()  # Remove user input to avoid double processing
                continue

            print("Thinking...")
            # --- First LLM Call: Decide whether to use a tool ---
            response = llm_client.chat.completions.create(
                model=QWEN_MODEL_NAME,
                messages=messages,
                tools=tools,
                tool_choice="auto"
            )
            response_message = response.choices[0].message

            # Check if the model wants to call a tool
            if response_message.tool_calls:
                messages.append(response_message)  # Append the model's decision

                # --- Execute Tool Calls ---
                for tool_call in response_message.tool_calls:
                    function_name = tool_call.function.name
                    function_to_call = available_tools.get(function_name)

                    if not function_to_call:
                        print(f"Error: LLM tried to call an unknown function '{function_name}'")
                        continue

                    try:
                        function_args = json.loads(tool_call.function.arguments)
                        print(f"Calling tool: `{function_name}` with args: {function_args}")

                        function_response = function_to_call(**function_args)

                        # Append the tool's result to the message history
                        messages.append({
                            "tool_call_id": tool_call.id,
                            "role": "tool",
                            "name": function_name,
                            "content": json.dumps(function_response)
                        })
                    except Exception as e:
                        print(f"Error executing tool '{function_name}': {e}")
                        messages.append({
                            "tool_call_id": tool_call.id,
                            "role": "tool",
                            "name": function_name,
                            "content": f'{{"status": "error", "message": "{str(e)}"}}'
                        })

                # --- Second LLM Call: Generate a natural language response ---
                print("Summarizing tool results...")
                second_response = llm_client.chat.completions.create(
                    model=QWEN_MODEL_NAME,
                    messages=messages
                )
                final_response = second_response.choices[0].message.content
                print(f"\nAgent: {final_response}")
                messages.append({"role": "assistant", "content": final_response})

            else:
                # The model decided to just chat
                final_response = response_message.content
                print(f"\nAgent: {final_response}")
                messages.append({"role": "assistant", "content": final_response})

        except Exception as e:
            print(f"\nAn unexpected error occurred: {e}")
            # Reset messages on critical error to prevent bad state
            messages = [{"role": "system", "content": system_prompt}]


if __name__ == "__main__":
    # Before running, set your environment variables:
    # export OPENSEARCH_URL="https://..."
    # export OPENSEARCH_USERNAME="admin"
    # export OPENSEARCH_PASSWORD="your_password"
    # export MEM_CONTAINER_ID="your_container_id"
    # export QWEN_API_KEY="your_api_key"
    main()

运行与交互

  1. 设置环境变量:在终端中设置脚本所需的环境变量。

  2. 运行脚本:python trip_agent.py

  3. 交互示例:

    单击展开查看详细交互示例

    ==================================================
    Welcome to the Trip Memory Agent!
    ==================================================
    Hello! I don't know you yet. Please tell me your name:
    > ABC
    Nice to meet you, ABC!
    
    Trip Memory Agent is ready!
    Hello ABC! I can remember things for you, search your memories, and help plan trips.
    
    ABC> i like hiking and travelling
    Thinking...
    Calling tool: `add_memory` with args: {'message': 'i like hiking and travelling'}
    Summarizing tool results...
    
    Agent: Great to know that you enjoy hiking and traveling, ABC! I've added this information to your profile. Whenever you're looking for trip ideas, I'll make sure to suggest some amazing hiking spots and travel destinations for you. 
    
    ABC> I like listen to music
    Thinking...
    Calling tool: `add_memory` with args: {'message': 'I like listen to music'}
    Summarizing tool results...
    
    Agent: Awesome, ABC! I've noted that you like listening to music. Whether it's for your travels or just everyday life, I can help you find some great playlists and music recommendations. Let me know if you have any favorite genres or artists!
    
    ABC> what do you know about me
    Thinking...
    Calling tool: `search_memories` with args: {'query': 'what do you know about me'}
    Summarizing tool results...
    
    Agent: I know a few things about you, ABC! Here’s what I have:
    
    1. You like hiking and traveling. These are some of your favorite activities, and you enjoy exploring new places and being outdoors.
    2. You also enjoy listening to music. It seems to be a big part of your life, whether it's for relaxation or just something you do regularly.
    
    If there's anything else you'd like to add or if you want to update any of this information, just let me know! 
    
    ABC> I live in Beijing
    Thinking...
    Calling tool: `add_memory` with args: {'message': 'I live in Beijing'}
    Summarizing tool results...
    
    Agent: Thanks for letting me know, ABC! I've added that you live in Beijing to your profile. This will help me tailor my suggestions and plans to be more relevant to your location. If you have any other details or preferences you'd like to share, feel free to let me know! 
    
    ABC> help me plan a weekend trip
    This looks like a trip plan request. Searching memories for context...
    Found relevant memories! Generating a personalized plan...
    
    Agent: Of course, I'd be happy to help you plan a fantastic weekend trip! Given your love for hiking, traveling, and music, how about we create an itinerary that combines all these interests? Here are a couple of ideas:
    
    ### Option 1: Hiking and Music in the Mountains
    **Destination:** **Yunmeng Mountain (云蒙山)**, Huairou District, Beijing
    
    **Day 1:**
    - **Morning:** Start early and drive to Yunmeng Mountain. It's about a 2-hour drive from central Beijing.
    - **Midday:** Arrive at Yunmeng Mountain and begin your hike. The trails here offer stunning views and a peaceful atmosphere. You can choose from various routes, ranging from easy to challenging.
    - **Afternoon:** After your hike, find a scenic spot to relax and enjoy a picnic lunch. Bring along some of your favorite music to set the mood.
    - **Evening:** Check into a local guesthouse or a small hotel in the area. Many places offer traditional Chinese-style accommodations with a cozy, rustic feel.
    
    **Day 2:**
    - **Morning:** Wake up early and head out for another short hike or a leisurely walk to explore more of the area.
    - **Midday:** Visit a local restaurant for a hearty brunch. Try some of the local specialties like *huai rou duck* (怀柔烤鸭) or *noodles with mountain vegetables*.
    - **Afternoon:** Return to Beijing. On the way back, you can stop at a local market or a small town to pick up some souvenirs or fresh produce.
    
    ### Option 2: Cultural Exploration and Nature
    **Destination:** **Jiulongshan (九龙山)**, Miyun District, Beijing
    
    **Day 1:**
    - **Morning:** Drive to Jiulongshan, which is about 1.5 hours from central Beijing. This area is known for its beautiful landscapes and historical sites.
    - **Midday:** Begin your hike in Jiulongshan. The trails here are well-maintained and offer a mix of natural beauty and cultural landmarks.
    - **Afternoon:** After your hike, visit the nearby **Jinshanling Great Wall**. It’s less crowded than other sections of the Great Wall and offers breathtaking views.
    - **Evening:** Stay at a local inn or a homestay near the Great Wall. Some places even offer live music performances in the evenings, which would be a perfect way to unwind after a day of hiking.
    
    **Day 2:**
    - **Morning:** Take a leisurely walk around the area or visit a local village to experience the rural life of Beijing.
    - **Midday:** Enjoy a traditional Chinese lunch at a local restaurant.
    - **Afternoon:** Head back to Beijing. If you have time, you could stop at a scenic spot or a small park to relax and listen to some music before returning home.
    
    Both options offer a great balance of outdoor activities, cultural experiences, and relaxation. Which one do you think you’d prefer, or is there anything else you’d like to add to the itinerary?
    
    ABC> I live in Shanghai now
    Thinking...
    Calling tool: `find_and_update_memory` with args: {'query': 'I live in Beijing', 'new_text': 'I live in Shanghai now'}
    Summarizing tool results...
    
    Agent: Got it, ABC! I've updated your information to reflect that you now live in Shanghai. This will help me provide more relevant suggestions and plans for your new location. If there's anything else you'd like to update or add, just let me know! 
    
    (I used the `find_and_update_memory` tool to change your location from Beijing to Shanghai.)
    
    ABC> where do i live
    Thinking...
    Calling tool: `search_memories` with args: {'query': 'where do i live'}
    Summarizing tool results...
    
    Agent: You currently live in Shanghai, ABC! I updated this information recently, so it's all set. If you have any other questions or need more details, feel free to ask! 
    
    (I used the `search_memories` tool to find and confirm your current location.)
    
    ABC> help me plan a weekend trip
    This looks like a trip plan request. Searching memories for context...
    Found relevant memories! Generating a personalized plan...
    
    Agent: 考虑到你目前居住在上海,并且喜欢周末自驾游、远足和听音乐,我为你规划了一个完美的周末旅行。你可以前往浙江省的莫干山,那里距离上海大约3小时车程,是一个非常适合短途旅行的目的地。
    
    **行程建议:**
    
    - **第一天:**
      - 上午从上海出发,驾车前往莫干山。
      - 中午抵达后,在当地的特色餐馆享用午餐。
      - 下午开始徒步探索莫干山,享受自然风光。你可以选择一些风景优美的步道,如剑池、大坑景区等。
      - 晚上入住一家舒适的民宿,放松身心。
    
    - **第二天:**
      - 早上可以在民宿附近散步,呼吸新鲜空气。
      - 上午可以选择继续徒步或参观当地的茶园,体验采茶乐趣。
      - 中午在茶园附近的餐厅享用午餐。
      - 下午返回上海,结束愉快的周末之旅。
    
    **注意事项:**
    - 请确保车辆状况良好,提前检查油量和轮胎。
    - 准备一些你喜欢的音乐,让旅途更加愉快。
    - 根据天气情况准备适当的衣物和装备,尤其是徒步时需要的鞋子和背包。
    - 提前预订民宿,以确保有合适的住宿。
    
    希望这个计划能让你度过一个愉快的周末!如果你有任何其他需求或想要调整行程,请随时告诉我。
    

API 参考

本指南中主要使用了以下API,更多详细用法请参考OpenSearch官方文档:

计费说明

使用 PolarSearch 记忆容器功能会涉及以下几部分费用,请在生产使用前仔细评估:

  1. 计算节点费用:作为PolarDB的一部分,PolarSearch节点会产生相应的节点计算节点费用。

  2. 模型服务费用:调用外部模型(如阿里云大模型服务平台百炼)进行事实抽取和向量化会产生相应的API调用费用。

常见问题

model_id和connector_id有什么区别,创建记忆容器时应该用哪个?

  • connector_id是您创建的指向外部模型服务(如阿里云大模型服务平台百炼)的连接器的ID。

  • model_id是您将该连接器注册到PolarSearch后,PolarSearch内部为该模型分配的ID。

在创建记忆容器时,embedding_model_id和llm_id字段需使用model_id。

llm_result_path参数如何配置?

该参数使用JSONPath语法,用于从LLM返回的复杂JSON响应中精确提取需要作为记忆事实的文本内容。您需要根据所使用LLM的实际API响应结构来配置此路径。例如,对于阿里云大模型服务平台百炼兼容模式,其核心内容位于{"choices":[{"message":{"content":"..."}}]},因此路径配置为$.choices[0].message.content。