Tablestore Agent Storage SDK 面向 AI Agent 存储场景,统一封装记忆库、文件记忆和知识库接口,提供 Python 与 TypeScript 版本,并支持通过 API Key 简化服务接口认证。
与 Tablestore SDK 的区别
Agent Storage SDK 是 Tablestore SDK 之外的独立 SDK,专注于 Agent 存储场景。两者主要差异如下。
|
维度 |
Tablestore SDK |
Agent Storage SDK |
|
包名 |
Python: |
Python: |
|
客户端类 |
|
|
|
覆盖能力 |
表格存储全量接口,含记忆库接口 |
Agent 存储服务接口(记忆库、文件记忆和知识库) |
|
认证方式 |
AccessKey(AK/SK) |
API Key 或 AccessKey(AK/SK) |
安装和配置
前提条件
-
已开通表格存储服务并创建实例,获取实例的 HTTPS Endpoint 与实例名。
-
若使用 API Key 认证:已在目标实例上创建 API Key,并为 API Key 绑定的 RAM 子账号授予
ots:CallWithBearerToken权限。API Key 的接口权限继承该子账号的 RAM 策略。 -
若使用知识库能力:已开通阿里云对象存储 OSS 并创建 Bucket,用于存储原始文档。上传文档时 SDK 需要 OSS 访问凭证(AccessKey),初始化客户端时需额外传入
oss_endpoint和oss_bucket参数。
安装
按语言选择对应的包。文件记忆的 Item 接口要求 Python SDK 1.0.10 及以上版本,或 TypeScript SDK 0.0.11 及以上版本。
Python
pip install "tablestore-agent-storage>=1.0.10"
TypeScript/Node.js
npm install "@tablestore/agent-storage@^0.0.11"
认证方式
Agent Storage SDK 支持两种认证方式,对比如下。
|
认证方式 |
适用场景 |
支持接口 |
传输要求 |
|
AccessKey(AK/SK) |
全功能访问,含表格管理与数据操作 |
表格存储全部接口 |
HTTP / HTTPS |
|
API Key |
AI 场景轻量接入,免管理 AccessKey ID/Secret |
Agent 存储服务接口 |
强制 HTTPS |
API Key 的创建与授权流程详见 API Key 管理。
初始化客户端
推荐使用 API Key 认证;如需知识库上传或其他表格存储接口,需同时提供 AccessKey 与 OSS 配置。
使用 API Key 访问(推荐)
通过 api_key 参数和实例信息初始化客户端,端点必须为 HTTPS。
Python
from tablestore_agent_storage import AgentStorageClient
client = AgentStorageClient(
api_key="<your-api-key>",
ots_endpoint="https://<instance>.<region>.ots.aliyuncs.com",
ots_instance_name="<instance-name>",
)
resp = client.list_memory_stores({})
for store in resp["stores"]:
print(store["memoryStoreName"])
TypeScript
import { AgentStorageClient } from '@tablestore/agent-storage';
const client = new AgentStorageClient({
apiKey: '<your-api-key>',
endpoint: 'https://<instance>.<region>.ots.aliyuncs.com',
instanceName: '<instance-name>',
});
const resp = await client.listMemoryStores({});
for (const store of resp.stores) {
console.log(store.memoryStoreName);
}
cURL
API Key 通过 x-ots-apikey 请求头传递。
curl -X POST 'https://<instance>.<region>.ots.aliyuncs.com/ListMemoryStores' \
-H 'x-ots-instancename: <instance-name>' \
-H 'x-ots-apikey: <your-api-key>' \
-H 'Content-Type: application/json' \
-d '{}'
使用 AccessKey 访问
访问表格存储完整接口或上传知识库文档(涉及 OSS)时,使用 AccessKey 认证。
Python
from tablestore_agent_storage import AgentStorageClient
client = AgentStorageClient(
access_key_id="<AccessKey ID>",
access_key_secret="<AccessKey Secret>",
ots_endpoint="https://<instance>.<region>.ots.aliyuncs.com",
ots_instance_name="<instance-name>",
# 若使用知识库能力,需同时配置 OSS
oss_endpoint="https://oss-<region>.aliyuncs.com",
oss_bucket_name="<bucket-name>",
)
TypeScript
import { AgentStorageClient } from '@tablestore/agent-storage';
const client = new AgentStorageClient({
endpoint: 'https://<instance>.<region>.ots.aliyuncs.com',
instanceName: '<instance-name>',
accessKeyId: process.env.OTS_ACCESS_KEY_ID,
accessKeySecret: process.env.OTS_ACCESS_KEY_SECRET,
});
知识库使用示例
知识库(Knowledge Base)支持文档自动切片、向量化与混合检索,适合企业问答、RAG 等场景。文档源文件存储在 OSS,切片索引与检索由表格存储完成,使用前需同时配置 OSS 与表格存储。
创建知识库时如果不显式指定向量模型,SDK 使用阿里云百炼 text-embedding-v4 模型(1024 维),默认检索方式为向量检索与全文检索的混合检索。
Python
from tablestore_agent_storage import AgentStorageClient
client = AgentStorageClient(
access_key_id="<AccessKey ID>",
access_key_secret="<AccessKey Secret>",
oss_endpoint="https://oss-<region>.aliyuncs.com",
oss_bucket_name="<bucket-name>",
ots_endpoint="https://<instance>.<region>.ots.aliyuncs.com",
ots_instance_name="<instance-name>",
)
# 1. 创建知识库(默认使用百炼 text-embedding-v4 向量模型,
# 默认检索方式为向量检索 + 全文检索的混合检索)
client.create_knowledge_base({
"knowledgeBaseName": "product_kb",
"description": "产品知识库",
})
# 2. 上传本地文档(SDK 会先将文件上传至 OSS,再触发切片与向量化)
client.upload_documents({
"knowledgeBaseName": "product_kb",
"documents": [
{
"documentId": "doc-guide-001",
"filePath": "./docs/product-overview.txt",
},
{
"documentId": "doc-guide-002",
"filePath": "./docs/sdk-intro.txt",
},
],
})
# 3. 列出知识库中的文档
resp = client.list_documents({
"knowledgeBaseName": "product_kb",
"maxResults": 10,
})
for doc in resp["data"]["documentDetails"]:
print(doc.get("documentId"), doc.get("ossKey"), doc.get("status"))
# 4. 检索
from tablestore_agent_storage.models import RetrieveRequest, RetrievalQuery
req = RetrieveRequest(
knowledge_base_name="product_kb",
retrieval_query=RetrievalQuery(text="Agent Storage SDK 有什么用"),
)
result = client.retrieve(req)
for hit in result["data"]["retrievalResults"]:
print(hit)
# 5. 删除文档
client.delete_documents({
"knowledgeBaseName": "product_kb",
"documents": [{"documentId": "doc-guide-001"}],
})
# 6. 删除知识库
client.delete_knowledge_base({"knowledgeBaseName": "product_kb"})
TypeScript
import { NodeAgentStorageClient } from '@tablestore/agent-storage/node';
const client = new NodeAgentStorageClient({
accessKeyId: '<AccessKey ID>',
accessKeySecret: '<AccessKey Secret>',
endpoint: 'https://<instance>.<region>.ots.aliyuncs.com',
instanceName: '<instance-name>',
ossEndpoint: 'https://oss-<region>.aliyuncs.com',
ossBucketName: '<bucket-name>',
ossAccessKeyId: '<AccessKey ID>',
ossAccessKeySecret: '<AccessKey Secret>',
});
// 1. 创建知识库(默认使用百炼 text-embedding-v4 向量模型,
// 默认检索方式为向量检索 + 全文检索的混合检索)
await client.createKnowledgeBase({
knowledgeBaseName: 'product_kb',
description: '产品知识库',
});
// 2. 上传本地文档(SDK 会先将文件上传至 OSS,再触发切片与向量化)
// TypeScript SDK 在上传时由服务端自动生成 docId,不接受自定义 documentId
await client.uploadDocuments({
knowledgeBaseName: 'product_kb',
documents: [
{ filePath: './docs/product-overview.txt' },
{ filePath: './docs/sdk-intro.txt' },
],
});
// 3. 列出知识库中的文档
const resp = await client.listDocuments({
knowledgeBaseName: 'product_kb',
maxResults: 10,
});
for (const doc of resp.data.documentDetails) {
console.log(doc.docId, doc.ossKey, doc.status);
}
// 4. 检索
const result = await client.retrieve({
knowledgeBaseName: 'product_kb',
retrievalQuery: { text: 'Agent Storage SDK 有什么用' },
});
for (const hit of result.data.retrievalResults) {
console.log(hit);
}
// 5. 删除文档(TypeScript 需要通过上一步返回的 ossKey 指定要删除的文档)
await client.deleteDocuments({
knowledgeBaseName: 'product_kb',
documents: [{ ossKey: '<oss-key-from-list>' }],
});
// 6. 删除知识库
await client.deleteKnowledgeBase({ knowledgeBaseName: 'product_kb' });
上传文档后,切片与向量化异步执行,通常数十秒到数分钟完成。可通过 list_documents(TypeScript 为 listDocuments)查询文档 status 字段确认索引进度。
记忆库使用示例
记忆库(Memory Store)用于持久化 AI Agent 的多轮对话记忆,并支持基于向量的语义检索。SDK 方法与 REST API 一一对应,Python 使用 snake_case,TypeScript 使用 camelCase,入参与接口一致。
Python
# 1. 创建记忆库
client.create_memory_store({
"memoryStoreName": "agent_memory",
"description": "Agent 长期记忆库",
"extractInstructions": "重点关注用户的饮食偏好与出行习惯",
})
# 2. 写入记忆
client.add_memories({
"memoryStoreName": "agent_memory",
"scope": {
"appId": "app-001",
"tenantId": "user-001",
"agentId": "assistant",
"runId": "session-001",
},
"messages": [
{"role": "user", "content": "我喜欢喝美式咖啡"},
],
"sync": True,
})
# 3. 检索记忆
result = client.search_memories({
"memoryStoreName": "agent_memory",
"scope": {
"appId": "app-001",
"tenantId": "user-001",
"agentId": "*",
"runId": "*",
},
"query": "用户喜欢什么饮品",
"topK": 5,
"includeEvidence": True,
"minSimilarity": 0.3,
})
for hit in result["data"]["memories"]:
print(hit["content"], hit["similarity"])
# 4. 列出记忆库中的 Scope
scopes = client.list_memory_store_scopes({
"memoryStoreName": "agent_memory",
"scope": {
"appId": "app-001",
"tenantId": "*",
"agentId": "*",
"runId": "*",
},
})
for scope in scopes["scopes"]:
print(scope)
# 5. 列出记忆库
resp = client.list_memory_stores({})
for store in resp["stores"]:
print(store["memoryStoreName"])
TypeScript
// 1. 创建记忆库
await client.createMemoryStore({
memoryStoreName: 'agent_memory',
description: 'Agent 长期记忆库',
});
// 2. 写入记忆
await client.addMemories({
memoryStoreName: 'agent_memory',
scope: {
appId: 'app-001',
tenantId: 'user-001',
agentId: 'assistant',
runId: 'session-001',
},
messages: [{ role: 'user', content: '我喜欢喝美式咖啡' }],
sync: true,
});
// 3. 检索记忆
const result = await client.searchMemories({
memoryStoreName: 'agent_memory',
scope: { appId: 'app-001', tenantId: 'user-001', agentId: '*', runId: '*' },
query: '用户喜欢什么饮品',
topK: 5,
includeEvidence: true,
});
for (const hit of result.data.memories) {
console.log(hit.content, hit.similarity);
}
// 4. 列出记忆库中的 Scope
const scopes = await client.listMemoryStoreScopes({
memoryStoreName: 'agent_memory',
scope: { appId: 'app-001', tenantId: '*', agentId: '*', runId: '*' },
});
for (const scope of scopes.scopes) {
console.log(scope);
}
除上述示例外,SDK 还提供更新和删除记忆库、获取和更新单条记忆、查询异步任务以及记忆整理(Dream)等方法。完整接口清单与参数说明详见 记忆存储 API 接口介绍。
文件记忆使用示例
文件记忆使用文件路径组织长期上下文,适合保存用户画像、会话摘要和 Agent 工作文件。SDK 会自动补充 Item 接口所需的 memoryfile 类型,调用时只需指定记忆库、Scope、路径和内容。
|
能力 |
Python |
TypeScript |
|
新增文件 |
|
|
|
列出文件 |
|
|
|
读取文件或元数据 |
|
|
|
更新内容或重命名 |
|
|
|
删除文件 |
|
|
|
列出历史版本 |
|
|
|
读取历史版本 |
|
|
|
脱敏历史版本 |
|
|
所有文件操作都要求传入完整的四级 Scope,即 appId、tenantId、agentId 和 runId,且不支持通配符 *。
历史版本脱敏不可逆,只清除指定历史版本的路径、内容、摘要和大小,不修改当前文件。
以下示例假设已完成客户端初始化。
Python
scope = {
"appId": "app-001",
"tenantId": "user-001",
"agentId": "assistant",
"runId": "session-001",
}
client.create_memory_store({
"memoryStoreName": "agent_files",
"storageMode": "filemem",
})
created = client.add_item({
"memoryStoreName": "agent_files",
"scope": scope,
"path": "/profile/preferences.md",
"content": "# 用户偏好\n\n- 喜欢美式咖啡\n",
})
page = client.list_items({
"memoryStoreName": "agent_files",
"scope": scope,
"pathPrefix": "/profile/",
})
current = client.get_item({
"memoryStoreName": "agent_files",
"scope": scope,
"path": "/profile/preferences.md",
"includeContent": False,
})
updated = client.update_item({
"memoryStoreName": "agent_files",
"scope": scope,
"path": "/profile/preferences.md",
"content": "# 用户偏好\n\n- 喜欢拿铁\n",
"expectedSha256": current["contentSha256"],
})
renamed = client.update_item({
"memoryStoreName": "agent_files",
"scope": scope,
"path": "/profile/preferences.md",
"newPath": "/profile/user-preferences.md",
"expectedSha256": updated["contentSha256"],
})
versions = client.list_item_versions({
"memoryStoreName": "agent_files",
"scope": scope,
"itemId": created["itemId"],
"limit": 20,
})
version = versions["versions"][0]
snapshot = client.get_item_version({
"memoryStoreName": "agent_files",
"scope": scope,
"itemId": version["itemId"],
"versionId": version["versionId"],
"versionSeq": version["versionSeq"],
})
client.redact_item_version({
"memoryStoreName": "agent_files",
"scope": scope,
"itemId": version["itemId"],
"versionId": version["versionId"],
"versionSeq": version["versionSeq"],
"sessionId": "privacy-job-001",
})
client.delete_item({
"memoryStoreName": "agent_files",
"scope": scope,
"path": "/profile/user-preferences.md",
"expectedSha256": renamed["contentSha256"],
})
print(page["items"], snapshot.get("content"))
TypeScript
const scope = {
appId: 'app-001',
tenantId: 'user-001',
agentId: 'assistant',
runId: 'session-001',
};
await client.createMemoryStore({
memoryStoreName: 'agent_files',
storageMode: 'filemem',
});
const created = await client.addItem({
memoryStoreName: 'agent_files',
scope,
path: '/profile/preferences.md',
content: '# 用户偏好\n\n- 喜欢美式咖啡\n',
});
const page = await client.listItems({
memoryStoreName: 'agent_files',
scope,
pathPrefix: '/profile/',
});
const current = await client.getItem({
memoryStoreName: 'agent_files',
scope,
path: '/profile/preferences.md',
includeContent: false,
});
const updated = await client.updateItem({
memoryStoreName: 'agent_files',
scope,
path: '/profile/preferences.md',
content: '# 用户偏好\n\n- 喜欢拿铁\n',
expectedSha256: current.contentSha256,
});
const renamed = await client.updateItem({
memoryStoreName: 'agent_files',
scope,
path: '/profile/preferences.md',
newPath: '/profile/user-preferences.md',
expectedSha256: updated.contentSha256,
});
const versions = await client.listItemVersions({
memoryStoreName: 'agent_files',
scope,
itemId: created.itemId,
limit: 20,
});
const version = versions.versions[0];
const snapshot = await client.getItemVersion({
memoryStoreName: 'agent_files',
scope,
itemId: version.itemId,
versionId: version.versionId,
versionSeq: version.versionSeq,
});
await client.redactItemVersion({
memoryStoreName: 'agent_files',
scope,
itemId: version.itemId,
versionId: version.versionId,
versionSeq: version.versionSeq,
sessionId: 'privacy-job-001',
});
await client.deleteItem({
memoryStoreName: 'agent_files',
scope,
path: '/profile/user-preferences.md',
expectedSha256: renamed.contentSha256,
});
console.log(page.items, snapshot.content);
expectedSha256 是可选的并发保护参数。多个调用方可能修改同一路径时,建议传入最近一次读取到的 contentSha256;摘要不匹配时,应重新读取文件,再决定是否重试。
文件视图使用示例
创建 file+ots 模式的记忆库后,可以继续通过结构化记忆接口写入、检索和更新记忆,并通过 Item 接口读取服务生成的文件视图。
client.create_memory_store({
"memoryStoreName": "agent_memory",
"storageMode": "file+ots",
})
使用完整 Scope 列出文件,并按路径读取文件内容。
page = client.list_items({
"memoryStoreName": "agent_memory",
"scope": scope,
})
for entry in page["items"]:
item = client.get_item({
"memoryStoreName": "agent_memory",
"scope": scope,
"path": entry["path"],
})
print(item["path"], item["content"])
当 list_items 返回 readOnly: true 时,文件视图为只读。应通过 add_memories、update_memory 和 delete_memory 等结构化记忆接口维护源记忆;对文件视图调用写入方法会返回 READ_ONLY_STORE。