全部產品
Search
文件中心

:Agent Storage SDK

更新時間:Jul 29, 2026

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:tablestore;Node.js:tablestore

Python:tablestore-agent-storage;TypeScript:@tablestore/agent-storage

用戶端類

OTSClient / AsyncOTSClient / TableStore.Client

AgentStorageClient

覆蓋能力

Table Store全量介面,含記憶庫介面

Agent 儲存服務介面(記憶庫、檔案記憶和知識庫)

認證方式

AccessKey(AK/SK)

API Key 或 AccessKey(AK/SK)

安裝和配置

前提條件

  • 已開通Table Store服務並建立執行個體,擷取執行個體的 HTTPS Endpoint 與執行個體名。

  • 若使用 API Key 認證:已在目標執行個體上建立 API Key,並為 API Key 綁定的 RAM 子帳號授予 ots:CallWithBearerToken 許可權。API Key 的介面許可權繼承該子帳號的 RAM 策略。

  • 若使用知識庫能力:已開通阿里雲Object Storage Service 並建立 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)

全功能訪問,含表格管理與資料操作

Table Store全部介面

HTTP / HTTPS

API Key

AI 情境輕量接入,免管理 AccessKey ID/Secret

Agent 儲存服務介面

強制 HTTPS

API Key 的建立與授權流程詳見 API Key 管理。

初始化用戶端

推薦使用 API Key 認證;如需知識庫上傳或其他Table Store介面,需同時提供 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 訪問

訪問Table Store完整介面或上傳知識庫文檔(涉及 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,切片索引與檢索由Table Store完成,使用前需同時配置 OSS 與Table Store。

建立知識庫時如果不顯式指定向量模型,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

新增檔案

add_item

addItem

列出檔案

list_items

listItems

讀取檔案或中繼資料

get_item

getItem

更新內容或重新命名

update_item

updateItem

刪除檔案

delete_item

deleteItem

列出歷史版本

list_item_versions

listItemVersions

讀取歷史版本

get_item_version

getItemVersion

脫敏歷史版本

redact_item_version

redactItemVersion

所有檔案操作都要求傳入完整的四級 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。