Tablestore Agent Storage SDK lets you add Memory Store and Knowledge Base capabilities to AI agents in Python and TypeScript. Unlike the general-purpose Tablestore SDK, Agent Storage SDK supports API Key authentication, removing the need to manage AccessKey credentials.
Differences from Tablestore SDK
Agent Storage SDK is separate from Tablestore SDK and covers agent storage operations only. The following table lists the key differences.
|
Dimension |
Tablestore SDK |
Agent Storage SDK |
|
Package |
Python: |
Python: |
|
Client class |
|
|
|
Scope |
All Tablestore operations, including Memory Store |
Agent storage operations only (Memory Store and Knowledge Base) |
|
Authentication |
AccessKey (AK/SK) |
API Key or AccessKey (AK/SK) |
Installation and configuration
Prerequisites
A Tablestore instance with an HTTPS endpoint and instance name.
If you use API Key authentication: an API Key created on the target instance. The RAM user bound to the API Key must have the
ots:CallWithBearerTokenpermission, and the API Key inherits all RAM policies of that user.If you use Knowledge Base features: an OSS bucket for storing source documents. The SDK requires OSS access credentials (AccessKey) for document uploads. Pass
oss_endpointandoss_bucketwhen initializing the client.
Installation
Install the package for your language.
Python
pip install tablestore-agent-storage
TypeScript/Node.js
npm install @tablestore/agent-storage
Authentication
Agent Storage SDK supports two authentication methods.
|
Method |
Use case |
Supported operations |
Transport |
|
AccessKey (AK/SK) |
Full access, including table management and data operations |
All Tablestore operations |
HTTP or HTTPS |
|
API Key |
Lightweight integration for AI scenarios without managing AccessKey credentials |
Memory Store and Knowledge Base operations only |
HTTPS only |
To create and authorize API Keys, see API key management.
Initialize the client
Use API Key authentication for most agent use cases. To upload Knowledge Base documents or access other Tablestore operations, provide AccessKey credentials and OSS configuration.
Use an API Key (recommended)
Initialize the client with the api_key parameter and instance information. The endpoint must use 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
Pass the API Key in the x-ots-apikey request header.
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 '{}'
Use an AccessKey
Use AccessKey authentication to access all Tablestore operations or upload Knowledge Base documents through OSS.
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>",
# To use Knowledge Base features, configure OSS as well
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,
});
Memory Store examples
Memory Store persists multi-turn conversation memories for AI agents and supports vector-based semantic retrieval. SDK methods correspond to REST API operations. Python methods use snake_case and TypeScript methods use camelCase; parameters match the API specification.
Python
# 1. Create a memory store
client.create_memory_store({
"memoryStoreName": "agent_memory",
"description": "Long-term memory store for agents",
"extractInstructions": "Focus on the user's dietary preferences and travel habits",
})
# 2. Write memories
client.add_memories({
"memoryStoreName": "agent_memory",
"scope": {
"appId": "app-001",
"tenantId": "user-001",
"agentId": "assistant",
"runId": "session-001",
},
"messages": [
{"role": "user", "content": "I like drinking americano coffee"},
],
"sync": True,
})
# 3. Search memories
result = client.search_memories({
"memoryStoreName": "agent_memory",
"scope": {
"appId": "app-001",
"tenantId": "user-001",
"agentId": "*",
"runId": "*",
},
"query": "What beverages does the user like",
"topK": 5,
"includeEvidence": True,
"minSimilarity": 0.3,
})
for hit in result["data"]["memories"]:
print(hit["content"], hit["similarity"])
# 4. List memory stores
resp = client.list_memory_stores({})
for store in resp["stores"]:
print(store["memoryStoreName"])
TypeScript
// 1. Create a memory store
await client.createMemoryStore({
memoryStoreName: 'agent_memory',
description: 'Long-term memory store for agents',
});
// 2. Write memories
await client.addMemories({
memoryStoreName: 'agent_memory',
scope: {
appId: 'app-001',
tenantId: 'user-001',
agentId: 'assistant',
runId: 'session-001',
},
messages: [{ role: 'user', content: 'I like drinking americano coffee' }],
sync: true,
});
// 3. Search memories
const result = await client.searchMemories({
memoryStoreName: 'agent_memory',
scope: { appId: 'app-001', tenantId: 'user-001', agentId: '*', runId: '*' },
query: 'What beverages does the user like',
topK: 5,
includeEvidence: true,
});
for (const hit of result.data.memories) {
console.log(hit.content, hit.similarity);
}
The SDK also provides methods for updating memory stores, deleting memory stores, listing memories by scope, getting individual memories, and querying asynchronous tasks. Memory Store API reference documents all available operations and parameters.
Knowledge Base examples
Knowledge Base supports automatic document chunking, vectorization, and hybrid retrieval for enterprise Q&A and RAG. Source documents are stored in OSS, while Tablestore handles chunk indexing and retrieval. Configure both OSS and Tablestore before use.
If you create a knowledge base without specifying an embedding model, the SDK uses Alibaba Cloud Model Studio text-embedding-v4 (1024 dimensions). Hybrid retrieval is enabled by default, combining vector search and full-text search.
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. Create a knowledge base (uses Model Studio text-embedding-v4 by default;
# default retrieval mode is hybrid retrieval combining vector search and full-text search)
client.create_knowledge_base({
"knowledgeBaseName": "product_kb",
"description": "Product knowledge base",
})
# 2. Upload local documents (the SDK uploads files to OSS first, then triggers chunking and vectorization)
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. List documents in the knowledge base
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. Retrieve
from tablestore_agent_storage.models import RetrieveRequest, RetrievalQuery
req = RetrieveRequest(
knowledge_base_name="product_kb",
retrieval_query=RetrievalQuery(text="What is the Agent Storage SDK used for"),
)
result = client.retrieve(req)
for hit in result["data"]["retrievalResults"]:
print(hit)
# 5. Delete documents
client.delete_documents({
"knowledgeBaseName": "product_kb",
"documents": [{"documentId": "doc-guide-001"}],
})
# 6. Delete the knowledge base
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. Create a knowledge base (uses Model Studio text-embedding-v4 by default;
// default retrieval mode is hybrid retrieval combining vector search and full-text search)
await client.createKnowledgeBase({
knowledgeBaseName: 'product_kb',
description: 'Product knowledge base',
});
// 2. Upload local documents (the SDK uploads files to OSS first, then triggers chunking and vectorization)
// The TypeScript SDK generates docId on the server side during upload and does not accept custom documentId
await client.uploadDocuments({
knowledgeBaseName: 'product_kb',
documents: [
{ filePath: './docs/product-overview.txt' },
{ filePath: './docs/sdk-intro.txt' },
],
});
// 3. List documents in the knowledge base
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. Retrieve
const result = await client.retrieve({
knowledgeBaseName: 'product_kb',
retrievalQuery: { text: 'What is the Agent Storage SDK used for' },
});
for (const hit of result.data.retrievalResults) {
console.log(hit);
}
// 5. Delete documents (TypeScript requires specifying the documents to delete via ossKey returned from the previous step)
await client.deleteDocuments({
knowledgeBaseName: 'product_kb',
documents: [{ ossKey: '<oss-key-from-list>' }],
});
// 6. Delete the knowledge base
await client.deleteKnowledgeBase({ knowledgeBaseName: 'product_kb' });
Document chunking and vectorization run asynchronously after upload. Query the status field through list_documents (TypeScript: listDocuments) to check indexing progress.