AgentbaseDocs
文档目录

Server SDK(Python)

Python 后端 / 管理脚本 / 数据管道以项目 API Key 调用 Server SDK(agentbase 包,snake_case)。API Key 请求跳过行级权限检查(hasRole),只存受控服务端。Node / Java / Go 面见同目录 nodejs.md / java.md / go.md。

制品与安装

要求 Python 3.9+,运行时依赖 requests 与 pydantic>=2,<3。制品未发布到 PyPI:从 agentbase-sdks release ZIP 解压后 pip 安装 wheel(含 Console 包),完整命令见 ../integration.md「Python 说明」与 ../examples/python.md「获取与安装」。不要安装开源 appwrite 包冒充(缺 TablesDB / Knowledge Bases 等 surface)。

初始化

agentbase 包的 __init__ 为空,全部符号按模块导入:

from agentbase.client import Client

client = (
    Client()
    .set_endpoint('https://appbuild.oceanbase.com/v1')   # SIT: https://appbuild-sit.oceanbase.com/v1
    .set_project('<PROJECT_ID>')
    .set_key('<SERVER_API_KEY>')                          # 最小 scope 的项目 API Key
)

其它配置(均链式返回 Client):set_organization(value)(组织级查询)、set_jwt(value) / set_session(value)(仅限 endpoint 明确要求用户身份的受控流程)、set_self_signed(status)、add_header(key, value)。

5 分钟上手

from agentbase.id import ID
from agentbase.query import Query
from agentbase.services.tables_db import TablesDB

tables_db = TablesDB(client)

tables_db.create(database_id='app-db', name='App')
tables_db.create_table(
    database_id='app-db', table_id='tasks', name='Tasks',
    row_security=True, enabled=True,
    columns=[{'key': 'title', 'type': 'string', 'size': 256, 'required': True}],
    indexes=[{'key': 'idx_title', 'type': 'unique', 'attributes': ['title']}],
)
tables_db.create_row(database_id='app-db', table_id='tasks', row_id=ID.unique(), data={'title': '写周报'})
rows = tables_db.list_rows(database_id='app-db', table_id='tasks',
                           queries=[Query.order_desc('$createdAt')], total=False)

调用约定

客户端配置、游标分页与文件上传实战

agentbase.client.Client 提供完整的链式配置方法,支持自定义超时、TLS 校验、国际化语言与自定义请求头:

Client 方法注入的 HTTP 请求头适用场景与安全约束
set_endpoint(endpoint)—(请求基准地址)必填,形如 https://appbuild-sit.oceanbase.com/v1 或 https://appbuild.oceanbase.com/v1。
set_project(value)X-Appwrite-Project必填,目标项目 ID(如演示项目 enterprise-ai-hub-210)。
set_key(value)X-Appwrite-Key服务端主用鉴权方式,跳过 RLS(hasRole),按最小 scope 授权。
set_jwt(value)X-Appwrite-JWT代表特定登录用户调用数据面接口(受该用户 RLS 行级权限约束)。
set_session(value)X-Appwrite-Session服务端转发浏览器登录会话 Cookie 时装载。
set_organization(value)X-Appwrite-Organization组织级查询与治理接口指定组织上下文(如 69c6d1aa00062e6bb60)。
set_locale(value)X-Appwrite-Locale指定国际化返回语种(如 zh-CN)。
set_self_signed(status)—(TLS 校验开关)仅用于自签名证书的私有测试实例,生产环境保持 False。
add_header(key, value)自定义请求头注入分布式追踪头(traceparent)或自定义幂等标识。

游标分页、文件上传与异步任务轮询模板

在 Python 数据管道或 AI 后端服务中,处理大表遍历(Query.cursor_after)、Storage 文件上传(InputFile)与异步任务状态机(如知识库摄取、Memory 写入、表结构增量列创建)的标准写法如下:

import os
import time
from typing import Callable, TypeVar
from agentbase.client import Client
from agentbase.exception import AgentbaseException
from agentbase.id import ID
from agentbase.input_file import InputFile
from agentbase.query import Query
from agentbase.services.knowledge_bases import KnowledgeBases
from agentbase.services.storage import Storage
from agentbase.services.tables_db import TablesDB

T = TypeVar('T')

client = (
    Client()
    .set_endpoint(os.environ.get('APPBASE_ENDPOINT', 'https://appbuild-sit.oceanbase.com/v1'))
    .set_project(os.environ.get('APPBASE_PROJECT_ID', 'enterprise-ai-hub-210'))
    .set_key(os.environ['APPBASE_API_KEY'])
)

tables_db = TablesDB(client)
storage = Storage(client)
kb = KnowledgeBases(client)


def call_with_retry(fn: Callable[[], T], max_attempts: int = 3) -> T:
    """对 429 限流与 502/503/504 网关瞬态错误执行指数退避重试。"""
    for attempt in range(1, max_attempts + 1):
        try:
            return fn()
        except AgentbaseException as err:
            retryable = err.code in (429, 502, 503, 504)
            if not retryable or attempt == max_attempts:
                raise
            time.sleep(min(1.0 * (2 ** (attempt - 1)), 8.0))
    raise RuntimeError('Unreachable')


def iterate_open_tickets() -> None:
    """使用 cursor_after 游标分页遍历 customer_tickets 表,关闭 total 计数降低开销。"""
    cursor = None
    page_size = 100
    while True:
        queries = [
            Query.equal('status', ['open', 'in_progress']),
            Query.order_asc('$id'),
            Query.limit(page_size),
        ]
        if cursor:
            queries.append(Query.cursor_after(cursor))

        page = call_with_retry(
            lambda: tables_db.list_rows(
                database_id='enterprise_biz_db',
                table_id='customer_tickets',
                queries=queries,
                total=False,
            )
        )
        if not page.rows:
            break
        for row in page.rows:
            print(f"Ticket {row.id}: {row.data.get('title')}")
        if len(page.rows) < page_size:
            break
        cursor = page.rows[-1].id


def upload_and_ingest_kb_doc(local_path: str) -> None:
    """上传 Markdown 文档到知识库桶并轮询摄取任务直至 ready。"""
    uploaded = storage.create_file(
        bucket_id='kb_enterprise_docs',
        file_id=ID.unique(),
        file=InputFile.from_path(local_path),
    )
    doc = kb.create_document(
        knowledge_base_id='kb_enterprise_support',
        document_id=ID.unique(),
        name='OceanBase分布式事务与向量索引排障指南.md',
        file_id=uploaded.id,
        sub_product_id='ob',
    )
    job = kb.create_ingestion(
        knowledge_base_id='kb_enterprise_support',
        document_id=doc.id,
    )
    while job.status in ('queued', 'running'):
        time.sleep(2.0)
        job = kb.get_ingestion(
            knowledge_base_id='kb_enterprise_support',
            document_id=doc.id,
            ingestion_id=job.id,
        )
    if job.status != 'ready':
        raise RuntimeError(f"Ingestion failed with status={job.status}")

与 Console SDK(agentbase_console)并用

Python 交付包 ZIP 中同时提供服务端数据面 wheel(agentbase)与管理面 wheel(agentbase_console)。在同一个 Python 进程中可同时导入两者(命名空间完全隔离):用 agentbase_console 执行组织/项目创建与 API Key 签发,再用 agentbase 执行业务表、存储、知识库与记忆数据面读写(详见 ../console-sdk/python.md)。

功能面导航

服务面与 Node 面同构(snake_case),全量映射见 nodejs.md「功能面导航」;各功能页:数据库、存储、函数、站点、用户、团队、消息、记忆、知识库(15.4.0 起补齐调用面)、LLM Gateway、AI Gateway、可观测、审核、横切服务。

无 Sql 服务(SQL 走 HTTP 形态或 Console SDK,../databases/sql-proxy.md);无 Realtime(客户端能力)。

错误处理

from agentbase.exception import AgentbaseException

try:
    tables_db.get_row(database_id='app-db', table_id='tasks', row_id='missing')
except AgentbaseException as error:
    print(error.code, error.type)   # code 为 HTTP 状态码:404 / 429 / 401·403

示例指引

事实源