Server SDK(Python)
Python backends / admin scripts / data pipelines call the Server SDK (agentbase package, snake_case) with aproject API Key. API Key requestsskip row-level permission checks (hasRole) and must be stored only on controlled servers. For the Node / Java / Go faces, see nodejs.md / java.md / go.md in the same directory.
Artifacts and installation
Requires Python 3.9+, with runtime dependencies requests and pydantic>=2,<3. The artifactis not published to PyPI: extract the wheel (including the Console package) from the agentbase-sdks release ZIP and pip install it; for full commands see ../integration.md "Python notes" and ../examples/python.md "Obtaining and installing". Do not install the open-source appwrite package as a substitute (it lacks the TablesDB / Knowledge Bases and other surfaces).
Initialization
The agentbase package's __init__ is empty; all symbols are imported per module:
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>') # Project API Key with minimal scope
)Other configuration (all return Client via chaining): set_organization(value) (organization-level queries), set_jwt(value) / set_session(value) (only for controlled flows where the endpoint explicitly requires user identity), set_self_signed(status), add_header(key, value).
5-minute quickstart
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)Calling conventions
Methodsynchronous returns a pydantic model: accessed byfield name (
user.id,listed.total); themodel_typeparameter only types the businessdatapayload of documents / rows (dict by default).columns/indexesare a list of dicts; incremental column endpoints mostly return a 202 asynchronous task.update_rows/delete_rowsoperate on the whole table when no queries are supplied; always add anQueryfilter.Use
agentbase.query.Queryfor queries (isomorphic with Node) andagentbase.id.IDfor IDs; permissions can usePermission.read(Role.any())or a raw syntax string list passed directly.
Client configuration, cursor pagination, and file upload in practice
agentbase.client.Client provides complete chainable configuration methods, supporting custom timeouts, TLS verification, locale languages, and custom request headers:
Client Method | Injected HTTP header | Use cases and security constraints |
|---|---|---|
set_endpoint(endpoint) | — (request base URL) | Required, in the form https://appbuild-sit.oceanbase.com/v1 or https://appbuild.oceanbase.com/v1. |
set_project(value) | X-Appwrite-Project | Required, target project ID (e.g. the demo project enterprise-ai-hub-210). |
set_key(value) | X-Appwrite-Key | The primary server-side authentication method, skips RLS (hasRole), authorized with the minimal scopes. |
set_jwt(value) | X-Appwrite-JWT | Calls data-plane APIs on behalf of a specific logged-in user (bound by that user's RLS row-level permissions). |
set_session(value) | X-Appwrite-Session | Loaded when the server forwards a browser login session Cookie. |
set_organization(value) | X-Appwrite-Organization | Specifies the organization context for organization-level query and governance APIs (e.g. 69c6d1aa00062e6bb60). |
set_locale(value) | X-Appwrite-Locale | Specifies the language for internationalized responses (e.g. zh-CN). |
set_self_signed(status) | — (TLS verification toggle) | Use only for private test instances with self-signed certificates; keep False in production. |
add_header(key, value) | Custom request headers | Inject distributed tracing headers (traceparent) or custom idempotency identifiers. |
Cursor pagination, file upload, and async task polling templates
In Python data pipelines or AI backend services, the standard patterns for handling large-table traversal (Query.cursor_after), Storage file upload (InputFile), and async task state machines (such as knowledge base ingestion, memory writes, and incremental column creation for table schemas) are as follows:
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}")Using together with the Console SDK (agentbase_console)
The Python delivery package ZIP includes both the server-side data-plane wheel (agentbase) and the management-plane wheel (agentbase_console). Both can be imported in the same Python process (namespaces fully isolated): use agentbase_console to perform organization/project creation and API Key issuance, then use agentbase to perform data-plane reads and writes for business tables, storage, knowledge bases, and memory (see ../console-sdk/python.md).
Feature surface navigation
The service plane is isomorphic with the Node plane (snake_case); for the full mapping see nodejs.md "Feature plane navigation"; feature pages: Databases, Storage, Functions, Sites, Users, Teams, Messaging, memory, knowledge base (call surface available from 15.4.0), LLM Gateway, AI Gateway, observability, moderation, cross-cutting services.
No Sql service (SQL uses the HTTP form or the Console SDK, see ../databases/sql-proxy.md); no Realtime (client-side capability).
Error Handling
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 is the HTTP status code: 404 / 429 / 401·403Example Guide
Complete Python (Server / Console) call syntax: ../examples/python.md