全部產品
Search
文件中心

Tablestore:構建第一個知識庫

更新時間:Oct 22, 2026

本樣本使用 Python SDK 完成一個最小閉環:建立知識庫、上傳本地文檔、等待索引完成並執行檢索。

前提條件

  • 已建立 AgentStorage 執行個體,並獲得 AgentStorage 名稱和訪問地址(endpoint)。知識庫將建立在該執行個體中。

  • 已在同地區建立 OSS Bucket,並完成Table Store讀寫 OSS 的授權。

  • 已準備 AccessKey ID 和 AccessKey Secret。生產環境請使用 RAM 使用者或臨時憑證。

  • 本地有一個用於測試的 PDF、Word、Markdown 或文字檔。

步驟1:安裝 SDK

pip install tablestore-agent-storage

步驟2:建立用戶端

from tablestore_agent_storage import AgentStorageClient
import time

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_endpoint="https://oss-<region>.aliyuncs.com",
    oss_bucket_name="<bucket-name>",
)

步驟3:建立知識庫並上傳文檔

client.create_knowledge_base({
    "knowledgeBaseName": "product_docs_kb",
    "description": "產品文檔知識庫",
})

response = client.upload_documents({
    "knowledgeBaseName": "product_docs_kb",
    "documents": [{"filePath": "/path/to/product-guide.pdf"}],
})
doc_id = response["data"]["documentDetails"][0]["docId"]

SDK 先把本地檔案上傳到 OSS,再提交非同步匯入任務。建立知識庫時未指定檢索配置,服務使用預設配置。

步驟4:等待文檔可檢索

deadline = time.time() + 300

while time.time() < deadline:
    response = client.get_document({
        "knowledgeBaseName": "product_docs_kb",
        "docId": doc_id,
    })
    document = response["data"][0]
    status = document["status"]

    if status == "completed":
        break
    if status == "failed":
        raise RuntimeError(document.get("message", "文檔處理失敗"))
    time.sleep(5)
else:
    raise TimeoutError("等待文檔索引逾時")

文檔在 pending 或 indexing 狀態時還不能被檢索。生產代碼應使用帶退避和總逾時的輪詢,並處理 failed 狀態。

步驟5:執行檢索

response = client.retrieve({
    "knowledgeBaseName": "product_docs_kb",
    "retrievalQuery": {
        "type": "TEXT",
        "text": "產品的安裝步驟是什嗎?",
    },
})

for item in response["data"]["retrievalResults"]:
    print(f"[{item['score']:.4f}] {item['content'][:120]}")

以上步驟已經跑通“原始文檔 → 切片索引 → 相關內容召回”的完整流程。召回結果是供 RAG 應用使用的證據切片,不是模型產生的最終答案。

下一步