快速开始

更新时间:
复制 MD 格式

记忆存储服务支持结构化记忆和文件记忆。结构化记忆适用于从对话中抽取和检索长期记忆,文件记忆适用于直接管理 Markdown 或 UTF-8 记忆文件。

前提条件

  • 已开通 Tablestore 服务,创建华北 2(北京)地域的实例,并获取实例的 Endpoint 和实例名称。

  • 已获取 AccessKey ID 与 AccessKey Secret,或已创建 API Key。API Key 创建方式参见API Key 管理

文件记忆

已有记忆文件或需要自行组织 Agent 记忆目录时,可以通过 Agent Storage SDK 直接写入和读取文件。以下示例使用 Python 完成安装、创建文件记忆库、写入文件和读取文件。

  1. 安装 Agent Storage SDK。文件记忆要求 Python SDK 1.0.10 及以上版本。

    pip install tablestore-agent-storage
  2. 初始化客户端,创建文件记忆库,然后写入并读取文件。

    from tablestore_agent_storage import AgentStorageClient
    
    client = AgentStorageClient(
        api_key="<your-api-key>",
        ots_endpoint="https://<instance>.cn-beijing.ots.aliyuncs.com",
        ots_instance_name="<instance-name>",
    )
    
    scope = {
        "appId": "app-001",
        "tenantId": "user-001",
        "agentId": "assistant",
        "runId": "session-001",
    }
    
    client.create_memory_store({
        "memoryStoreName": "agent_files",
        "storageMode": "filemem",
    })
    
    client.add_item({
        "memoryStoreName": "agent_files",
        "scope": scope,
        "path": "/profile/preferences.md",
        "content": "# 用户偏好\n\n- 喜欢美式咖啡\n- 偏好简洁回答\n",
    })
    
    item = client.get_item({
        "memoryStoreName": "agent_files",
        "scope": scope,
        "path": "/profile/preferences.md",
    })
    print(item["content"])

Agent Storage SDK 的初始化方式和更多用法参见Agent Storage SDK

结构化记忆

结构化记忆支持通过 CLI、Agent Storage SDK、Tablestore 原生 SDK 或 AI Agent 框架创建记忆库、写入对话并检索长期记忆。选择一种接入方式完成操作。

CLI

CLI 适合在命令行中完成凭证配置、记忆库管理、记忆写入和检索验证。

  1. 安装命令行工具。要求 Node.js 18 及以上版本。

    npm install -g @tablestore/tablestore-agent-cli
    tablestore-agent-cli version
  2. 配置 AccessKey、地域和 Tablestore 实例信息。

    tablestore-agent-cli configure set access_key_id '<AccessKey ID>'
    tablestore-agent-cli configure set access_key_secret '<AccessKey Secret>'
    tablestore-agent-cli configure set region 'cn-beijing'
    tablestore-agent-cli configure set ots_endpoint 'https://<instance>.cn-beijing.ots.aliyuncs.com'
    tablestore-agent-cli configure set ots_instance_name '<instance-name>'
  3. 诊断记忆存储配置和连通性。

    tablestore-agent-cli doctor memory
  4. 创建结构化记忆库。

    tablestore-agent-cli memory create \
      --store agent_memory \
      --description "Agent 长期记忆库"
  5. 写入一条记忆,并等待记忆抽取完成。

    tablestore-agent-cli memory add \
      --store agent_memory \
      --app-id app-001 \
      --tenant-id user-001 \
      --agent-id assistant \
      --run-id session-001 \
      --text "用户喜欢喝咖啡,偏好简洁的回答风格" \
      --sync
  6. 检索长期记忆。agentIdrunId 使用 *,可以跨 Agent 和跨会话检索。

    tablestore-agent-cli memory search \
      --store agent_memory \
      --app-id app-001 \
      --tenant-id user-001 \
      --agent-id '*' \
      --run-id '*' \
      --query "用户喜欢什么饮品" \
      --top-k 5
  7. 查看当前会话的短期记忆。短期记忆查询需要填写完整的四级 Scope,不支持通配符。

    tablestore-agent-cli memory msg-list \
      --store agent_memory \
      --app-id app-001 \
      --tenant-id user-001 \
      --agent-id assistant \
      --run-id session-001

--sync 会等待记忆抽取完成。索引可见性可能稍有延迟;如果首次检索没有返回结果,请稍后重试。

更多 CLI 命令和记忆库操作参见命令行工具记忆库操作

Agent Storage SDK

以下提供 Python 和 TypeScript 示例,并使用 API Key 初始化客户端,完成创建记忆库、写入记忆和执行检索。

Python

安装 SDK:

pip install tablestore-agent-storage

最简示例:

from tablestore_agent_storage import AgentStorageClient

client = AgentStorageClient(
    api_key="<your-api-key>",
    ots_endpoint="https://<instance>.cn-beijing.ots.aliyuncs.com",
    ots_instance_name="<instance-name>",
)

scope = {
    "appId": "app-001",
    "tenantId": "user-001",
    "agentId": "assistant",
    "runId": "session-001",
}

# 1. 创建记忆库
client.create_memory_store({"memoryStoreName": "agent_memory"})

# 2. 写入记忆
client.add_memories({
    "memoryStoreName": "agent_memory",
    "scope": scope,
    "text": "用户喜欢喝咖啡,偏好简洁的回答风格",
    "sync": True,
})

# 3. 执行语义检索
result = client.search_memories({
    "memoryStoreName": "agent_memory",
    "scope": {"appId": "app-001", "tenantId": "user-001", "agentId": "*", "runId": "*"},
    "query": "用户喜欢什么饮品",
    "topK": 5,
})
for item in result.get("results", []):
    unit = item["unit"]
    print(f"[{item['score']:.4f}] {unit['text']}")

TypeScript

安装 SDK:

npm install @tablestore/agent-storage

最简示例:

import { AgentStorageClient } from '@tablestore/agent-storage';

const client = new AgentStorageClient({
  apiKey: '<your-api-key>',
  endpoint: 'https://<instance>.cn-beijing.ots.aliyuncs.com',
  instanceName: '<instance-name>',
});

const scope = {
  appId: 'app-001',
  tenantId: 'user-001',
  agentId: 'assistant',
  runId: 'session-001',
};

// 1. 创建记忆库
await client.createMemoryStore({ memoryStoreName: 'agent_memory' });

// 2. 写入记忆
await client.addMemories({
  memoryStoreName: 'agent_memory',
  scope,
  text: '用户喜欢喝咖啡,偏好简洁的回答风格',
  sync: true,
});

// 3. 执行语义检索
const result: any = await client.searchMemories({
  memoryStoreName: 'agent_memory',
  scope: { appId: 'app-001', tenantId: 'user-001', agentId: '*', runId: '*' },
  query: '用户喜欢什么饮品',
  topK: 5,
});
for (const item of result.results ?? []) {
  console.log(`[${item.score.toFixed(4)}] ${item.unit.text}`);
}

Tablestore 原生 SDK

Tablestore 原生 SDK 提供 Python 与 Node.js 两种语言,将记忆存储能力与已有的 Tablestore 应用集成。原生 SDK 目前仅支持 AccessKey 认证。

Python

安装 SDK(要求 tablestore 版本 6.4.7 及以上):

pip install tablestore

最简示例:

from tablestore import OTSClient

client = OTSClient(
    "https://<instance>.cn-beijing.ots.aliyuncs.com",
    "<AccessKey ID>",
    "<AccessKey Secret>",
    "<instance-name>",
)

scope = {
    "appId": "app-001",
    "tenantId": "user-001",
    "agentId": "assistant",
    "runId": "session-001",
}

# 1. 创建记忆库
client.create_memory_store({"memoryStoreName": "agent_memory"})

# 2. 写入记忆
client.add_memories({
    "memoryStoreName": "agent_memory",
    "scope": scope,
    "text": "用户喜欢喝咖啡,偏好简洁的回答风格",
    "sync": True,
})

# 3. 执行语义检索
result = client.search_memories({
    "memoryStoreName": "agent_memory",
    "scope": {"appId": "app-001", "tenantId": "user-001", "agentId": "*", "runId": "*"},
    "query": "用户喜欢什么饮品",
    "topK": 5,
})
for item in result.get("results", []):
    unit = item["unit"]
    print(f"[{item['score']:.4f}] {unit['text']}")

Node.js

安装 SDK(要求 tablestore 版本 5.6.5 及以上):

npm install tablestore

最简示例:

const TableStore = require("tablestore");

const client = new TableStore.Client({
  accessKeyId: "<AccessKey ID>",
  secretAccessKey: "<AccessKey Secret>",
  endpoint: "https://<instance>.cn-beijing.ots.aliyuncs.com",
  instancename: "<instance-name>",
});

async function main() {
  const scope = {
    appId: "app-001",
    tenantId: "user-001",
    agentId: "assistant",
    runId: "session-001",
  };

  await client.createMemoryStore({ memoryStoreName: "agent_memory" });

  await client.addMemories({
    memoryStoreName: "agent_memory",
    scope,
    text: "用户喜欢喝咖啡,偏好简洁的回答风格",
    sync: true,
  });

  const result = await client.searchMemories({
    memoryStoreName: "agent_memory",
    scope: { appId: "app-001", tenantId: "user-001", agentId: "*", runId: "*" },
    query: "用户喜欢什么饮品",
    topK: 5,
  });
  for (const item of result.results ?? []) {
    console.log(`[${item.score.toFixed(4)}] ${item.unit.text}`);
  }
}

main().catch(console.error);

完整原生 SDK 用法参见Python SDK 使用介绍Node.js SDK 使用介绍

AI Agent 框架

如果在 OpenClaw、Hermes、Claude 等 AI Agent 框架中使用记忆存储,可通过对应插件让 Agent 直接读写记忆库,无需手动编写 SDK 调用代码。

各框架的详细集成步骤参见Agent 生态集成