Agent Runtime API
Before running the examples, replace <APPBASE_ENDPOINT_WITH_V1> with the intended environment API endpoint and verify that the project and credentials belong to that environment.
REST API reference documentation for the Project Agent Runtime. Business backends connect via a project-level API Key to the managed agent runtime engine (/v1/agent-runtime/project/*) under the current project, centrally managing project runtime configuration, lexicon bindings, AI Gateway tool discovery, and Skill package uploads, and through userId isolating and managing sessions (Thread), asynchronous tasks (Run), resumable streaming events (SSE), and client tool callbacks (Client Tool) for different business end users.
Resources and Base Paths
Base URL:
https://appbuild-sit.oceanbase.com/v1; the path prefix for the Project Agent Runtime is fixed at/v1/agent-runtime/project.Associated environment coordinates (using the SIT demo environment as an example):
Organization:
Agentbase 企业智能中台(69c6d1aa00062e6bb60)Project:
企业智能客服与知识中台(Project ID:enterprise-ai-hub-210, storage architecture: Shared V2)Model provider:
dashscope-prod(supports chat modelsqwen-plus,qwen-turbo, embedding modeltext-embedding-v3with 1024 dimensions, reranking modelqwen3.7-text-rerank, multimodal modelqwen-vl-max)AI Gateway:
prod-enterprise-ai-gateway(Gateway ID:gw_7194685489feb1e169548619)Enterprise knowledge base:
kb_enterprise_supportBusiness lexicons:
lex_enterprise_synonyms(enterprise synonym and expansion term lexicon),lex_support_stopwords(customer service compliance stopword lexicon)Business end-user examples:
user_zhangwei_001,user_lina_002
Core Resource Models and Responsibility Boundaries
| Resource object | Core identifier and path | Ownership scope | Key semantics and lifecycle notes |
|---|---|---|---|
| Project Runtime State | /v1/agent-runtime/project | Project sharing | initialized: boolean Indicates whether the current project's agent workspace has completed initialization; repeating POST initialization is idempotent and will not clear existing configuration and history. |
| Project Configuration (Config) | /v1/agent-runtime/project/config | Project-shared | Contains system_prompt, model_id, model_parameters, context window and output token budget, maximum reasoning steps and timeout duration, as well as memory_enabled, powercontext_enabled (mutually exclusive with Memory), knowledge_search_enabled, and knowledge_base_ids; returns a read-only config_hash. The effective configuration is frozen when a Run is accepted; modifying project configuration does not affect in-flight Runs. |
| Available Model List (ModelList) | /v1/agent-runtime/project/models | Project-shared | Lists the chat (chat) and embedding (embedding) models currently configured in the project and available for selection by the Agent Runtime. |
| Project Lexicon Bindings (LexiconBindings) | /v1/agent-runtime/project/lexicons | Project-shared | Mounts the lexicons under the current project (up to 100, sorted by priority ascending) to the Agent Runtime, supporting synonym/expansion term rewriting queries as well as short-circuit interception (stopIntercept: true) and preset compliance replies (stopReply) when stop stopwords are hit. |
| AI Gateway Binding (Gateway) | /v1/agent-runtime/project/gateway | Project-shared | Binds an AI Gateway (gateway_id) in the same project whose status is ACTIVE and which has an available published snapshot, enabling agents to automatically discover and call MCP / HTTP tools and Client Tools within the authorized scope at runtime (Shared V2 projects only). |
| Skill Package (Skill) | /v1/agent-runtime/project/skills/{skillId} | Project-shared | Uploads .zip / .tar.gz / .tgz archive packages (limit 10 MiB, root directory contains SKILL.md with YAML Front Matter) for agents to discover and read task instructions and operational guidelines on demand; uploading a skill package does not mean executing arbitrary scripts. |
| Session (Thread) | /v1/agent-runtime/project/threads/{threadId} | User-isolated (userId) | Carries the multi-turn continuous conversation history of the same business user, with a status of ACTIVE or ARCHIVED. At most one unfinished Run may exist in the same Thread at any given time. |
| Run | /v1/agent-runtime/project/runs/{runId} | User-isolated (userId) | A ReAct reasoning and tool-calling loop triggered by one user message; POST /runs accepts asynchronously and returns 202 Accepted (replaying the same request carrying Idempotency-Key returns 200 OK and idempotent_replay: true). |
| Message | .../threads/{threadId}/messages, .../runs/{runId}/messages | User-isolated (userId) | Persisted session or single-run message records, sorted by the incrementing in-session sequence number message_seq, with types covering USER, ASSISTANT, TOOL_CALL, TOOL_RESULT. |
| Streaming Event (SSE Event) | /v1/agent-runtime/project/runs/{runId}/events | User-isolated (userId) | A bounded incremental event stream based on the AG-UI protocol (text/event-stream), supporting resumption via Last-Event-ID after disconnection; an SSE disconnect does not cancel the background Run. |
| Model Invocation Record (ModelInvocation) | /v1/agent-runtime/project/runs/{runId}/model-invocations | User-isolated (userId) | Records the input/output/cache/reasoning token usage, duration, and status of each model reasoning step (AGENT_RESPONSE, CONTEXT_COMPACTION, MEMORY) within a single Run. |
| Context Compaction Record (ContextCompaction) | /v1/agent-runtime/project/threads/{threadId}/context-compactions | User-isolated (userId) | When the session history approaches the context budget, the Runtime automatically summarizes earlier history and retains recent messages; this endpoint returns an audit timeline of context compaction events. |
ReAct Execution Loop and Streaming Recovery Architecture
The business backend holds the Project API Key and calls
POST /v1/agent-runtime/project/runs, passinguserId,thread_id,user_message, andIdempotency-Key. The API validates project permissions and lexicon stopword rules, freezes the configuration snapshot, and returns202 Accepted(run_id,status=QUEUED).The backend subscribes to SSE via
GET /v1/agent-runtime/project/runs/{runId}/events?userId=.... The Runtime loads the Thread history, retrieves Memory / PowerContext, and computes the context token budget.Within the
max_stepsandmax_duration_mslimits, the Runtime loops model calls, sending prompts, context, and authorized tool schemas; the model returns answer increments or tool call requests.Server-side tool calls first validate the parameter schema and trusted identity, then execute Knowledge retrieval or AI Gateway tools, and persist
TOOL_RESULT. Client tool calls pushTOOL_CALL_START/TOOL_CALL_ARGS/TOOL_CALL_ENDand the Run entersWAITING_CLIENT_TOOL; after the application returnsuserId,toolCallId,content/errorto/runs/{runId}/tool-messages, the same Run is resumed viaQUEUEDback toRUNNING.During reasoning, the Runtime continuously pushes SSE frames such as
TEXT_MESSAGE_CONTENTwith incrementing event IDs. On completion, it persists the finalASSISTANTmessage andModelInvocationusage, updates the Run toSUCCEEDED, and pushesRUN_FINISHED.The backend retrieves persisted messages and knowledge source references via
GET /v1/agent-runtime/project/runs/{runId}/messages?userId=.... On SSE disconnection,Last-Event-IDcan be carried to resume; the disconnect itself does not cancel the background Run.
Run Lifecycle State Machine
| Initial state | Subsequent states | Trigger condition |
|---|---|---|
| Initial | SUBMITTING → QUEUED | Run registered and enqueued |
QUEUED | RUNNING | Worker begins execution |
RUNNING | WAITING_CLIENT_TOOL | Waiting for client tool result |
WAITING_CLIENT_TOOL | QUEUED | Calling /runs/{runId}/tool-messages to return the result |
RUNNING | SUCCEEDED / FAILED | Execution succeeded or failed, entering a terminal state |
RUNNING | CANCEL_REQUESTED → CANCELLED | Calling /runs/{runId}/cancel, waiting for the execution step to exit |
QUEUED / WAITING_CLIENT_TOOL | CANCELLED | Calling /runs/{runId}/cancel, entering the cancelled terminal state directly |
SUCCEEDED, FAILED, and CANCELLED are all terminal states.
| Run status | Status category | Meaning | Standard client handling action |
|---|---|---|---|
SUBMITTING | In progress | Task is being registered and its persistence record initialized | Continue polling or wait until it enters QUEUED |
QUEUED | In progress | Task is queued waiting for Worker execution (or re-queued after a client tool result is returned) | Establish or maintain the SSE subscription; never create a duplicate new Run |
RUNNING | In progress | Worker is executing model reasoning, context compaction, or server-side tool calls | Consume the SSE event stream in real time; if termination is needed, explicitly call /cancel |
WAITING_CLIENT_TOOL | Paused/waiting | The model triggered a client tool call of source: "CLIENT" and is waiting for the application to return the execution result | Validate the tool name and parameters, perform the locally approved operation, then call POST /runs/{runId}/tool-messages to resume the same Run |
CANCEL_REQUESTED | In progress | Cancellation request accepted, waiting for the current execution step to exit safely | Keep observing the status until it converges to a terminal state CANCELLED |
SUCCEEDED | Final state | Task execution completed and final answer has been persisted | Stop listening to the event stream and call GET /runs/{runId}/messages to read the final persisted message |
FAILED | Final state | Task terminated due to model rate limiting, context overflow, upstream exceptions, or tool failure | Read the Run object's error.code and error.message for troubleshooting or to notify the user |
CANCELLED | Final state | Task has been explicitly cancelled and its status has converged | Keep existing history; note that cancellation does not automatically roll back business side effects already produced by external tools |
Authentication and Permissions
For common request header conventions, see General Conventions. Project-level agent workbench APIs use a two-tier security model of Project API Key authentication + userId multi-tenant user isolation:
Request Headers and API Key Scope Matrix
| Header / Requirement | Example Value | Required Rules and Permission Boundary Description |
|---|---|---|
X-Appwrite-Project | enterprise-ai-hub-210 | Required. Specifies the target project ID; it is not appended to the URL path. |
X-Appwrite-Key | <APPBASE_API_KEY> | Required. A valid Server API Key belonging to the current project (supports standard Project API Keys and dynamic Project Keys; must be kept only in a controlled business backend and must never be delivered to browsers or mobile clients). |
| Required Permission Scope | agent-runtime.project | The project configuration and Thread/Run endpoints listed here require agent-runtime.project. Other project paths may require different scopes: for example, GET /v1/agent-runtime/project/version-binding uses agent-runtime.read and depends on the Agent Management switch. Check each endpoint's requirements. |
Idempotency-Key | req_zhangwei_20261022_001 | POST /v1/agent-runtime/project/runs Recommended to include (1–128 byte ASCII string). Replaying with the same project, same userId, and same request body returns the original Run (HTTP 200 + idempotent_replay: true); the same key with a different request body returns 409 IDEMPOTENCY_KEY_CONFLICT. |
Last-Event-ID | 21 | GET /v1/agent-runtime/project/runs/{runId}/events Optionally included when reconnecting after a disconnection; pass in the last received outer SSE frame id to resume unread events. |
Internal service coordination authentication: When the agent workbench internally calls an enabled Memory, Knowledge Base, or AI Gateway within the same project at runtime, the platform automatically issues an internal trusted runtime context to complete authentication; there is no need to additionally check the Memory or Knowledge public API Scope for the caller's Project API Key.
userId Business User Isolation Contract (Core Specification)
The business backend can serve tens of thousands of business end users (such as user_zhangwei_001 and user_lina_002) using the same Project API Key, without needing to create platform Accounts for end users in Agentbase in advance:
Format and case normalization:
The field name is strictly camelCase
userId(notuser_id).The value must be 1–128 ASCII letters, digits, or underscores (regex:
^[A-Za-z0-9_]{1,128}$), and must be passed as a JSON string or Query string (purely numeric identities must be written as"123"; JSON numbers, arrays, objects, null, hyphens-, whitespace, or Chinese characters are rejected).Case-insensitive; the server normalizes everything to lowercase:
"User_ZhangWei_001"and"user_zhangwei_001"point to the same user isolation space.Reserved word restriction:
system(including any casing such asSYSTEM) is a platform-reserved identity and must not be supplied externally.
Strict distinction of parameter location (no duplicate passing):
Project-level shared configuration endpoints (service initialization, configuration reads/writes, model listing, lexicon binding, AI Gateway binding, and Skill package management): do not pass
userId; this parameter is neither required nor allowed.User-level session and run endpoints (
/threads,/runs, and all their sub-resources): every request must includeuserId, wherePOSTrequests must place it in the JSON request body (Body), andGETandDELETErequests must place it in the URL query parameters (Query); providinguserIdin both Query and Body simultaneously is strictly forbidden.
Strong cross-user isolation semantics:
After a Thread is created, all subsequent operations on that Thread and its subordinate Runs (submitting a Run, querying status, subscribing to SSE, pulling messages, returning client tool results, cancelling a Run, archiving the Thread) must carry the same
userIdused at creation time.If a
user_lina_002is supplied to access athreadIdorrunIdbelonging touser_zhangwei_001, the server uniformly rejects it with404 NOT_FOUND(resource not visible), neither leaking the resource's existence nor altering its ownership.
Endpoint List
The following table lists the project configuration and user session/run endpoints covered here. Other project endpoints include GET / PUT /v1/agent-runtime/project/tool-discovery (uses agent-runtime.project) and GET /v1/agent-runtime/project/version-binding (uses agent-runtime.read; registered only when Agent Management is enabled). Availability and configuration depend on the target environment.
| Category | Method + Full Path | Required Scope | userId Requirement and Location | Idempotency | Success Status Code | Purpose Description |
|---|---|---|---|---|---|---|
| Service Initialization | GET /v1/agent-runtime/project | agent-runtime.project | Not required | Idempotent | 200 | Queries whether the Agent Runtime of the current project has been initialized (initialized) |
| Service Initialization | POST /v1/agent-runtime/project | agent-runtime.project | Not required | Idempotent | 200 | Explicitly initializes the Agent Runtime of the current project (repeated calls do not clear configuration) |
| Project Configuration | GET /v1/agent-runtime/project/config | agent-runtime.project | Not required | Idempotent | 200 | Reads the current project's agent configuration and read-only config_hash |
| Project Configuration | PATCH /v1/agent-runtime/project/config | agent-runtime.project | Not required | Conditionally idempotent | 200 | Sparsely updates the project agent configuration (model, prompt, budget, Memory/PowerContext/Knowledge switches) |
| Model Catalog | GET /v1/agent-runtime/project/models | agent-runtime.project | Not required | Idempotent | 200 | Lists the models and capability tags available to the agent workbench in the current project (chat / embedding) |
| Lexicon Binding | GET /v1/agent-runtime/project/lexicons | agent-runtime.project | Not required | Idempotent | 200 | Reads the lexicon list bound to the current project's agent workbench and the stopword blocking policy |
| Lexicon Binding | PUT /v1/agent-runtime/project/lexicons | agent-runtime.project | Not required | Idempotent | 200 | Fully sets the bound lexicon priority list, enabled, stopIntercept, and stopReply of the agent workbench |
| AI Gateway | GET /v1/agent-runtime/project/gateway | agent-runtime.project | Not required | Idempotent | 200 | Reads the AI Gateway bound to the current project's agent workbench (gateway_id) |
| AI Gateway | PUT /v1/agent-runtime/project/gateway | agent-runtime.project | Not required | Idempotent | 200 | Binds to or switches to an AI Gateway in the same project that is in ACTIVE state and has an available snapshot |
| Skill Management | GET /v1/agent-runtime/project/skills | agent-runtime.project | Not required | Idempotent | 200 | Lists the Skill packages uploaded in the current project and the capacity quota (skill_count / skill_limit) |
| Skill Management | POST /v1/agent-runtime/project/skills | agent-runtime.project | Not required | Non-idempotent | 201 | Uploads a new Skill archive package via multipart/form-data (.zip / .tar.gz / .tgz) |
| Skill Management | GET /v1/agent-runtime/project/skills/{skillId} | agent-runtime.project | Not required | Idempotent | 200 | Reads the metadata, front_matter, and content_hash of a specified Skill package |
| Skill Management | PUT /v1/agent-runtime/project/skills/{skillId} | agent-runtime.project | Not required | Idempotent | 200 | Uploads a new archive package to fully replace the content of the specified skillId |
| Skill Management | DELETE /v1/agent-runtime/project/skills/{skillId} | agent-runtime.project | Not required | Idempotent | 204 | Deletes the specified skillId Skill package |
| Session Management | POST /v1/agent-runtime/project/threads | agent-runtime.project | Required (JSON Body) | Non-idempotent | 201 | Creates a new continuous conversation Thread for the specified userId |
| Session Management | GET /v1/agent-runtime/project/threads | agent-runtime.project | Required (URL Query) | Idempotent | 200 | Lists the session list for the specified userId in descending order by update time (supports limit) |
| Session Management | GET /v1/agent-runtime/project/threads/{threadId} | agent-runtime.project | Required (URL Query) | Idempotent | 200 | Queries the status and title of a single Thread under the specified userId |
| Session Management | DELETE /v1/agent-runtime/project/threads/{threadId} | agent-runtime.project | Required (URL Query) | Idempotent | 204 | Archives the Thread for the specified userId (status set to ARCHIVED; long-term memory is not deleted) |
| Session History | GET /v1/agent-runtime/project/threads/{threadId}/messages | agent-runtime.project | Required (URL Query) | Idempotent | 200 | Reads persisted session messages with pagination by after (message_seq) and limit cursor |
| Session History | GET /v1/agent-runtime/project/threads/{threadId}/context-compactions | agent-runtime.project | Required (URL Query) | Idempotent | 200 | Reads the session's automatic context compaction event records |
| Run Management | POST /v1/agent-runtime/project/runs | agent-runtime.project | Required (JSON Body) | Idempotent (requires Idempotency-Key) | 202 (replay 200) | Submits a user message within the specified Thread and asynchronously starts a ReAct Run |
| Run Management | GET /v1/agent-runtime/project/runs/{runId} | agent-runtime.project | Required (URL Query) | Idempotent | 200 | Queries the current run status and error details of the specified runId |
| Run Management | POST /v1/agent-runtime/project/runs/{runId}/cancel | agent-runtime.project | Required (JSON Body) | Idempotent | 202 or 200 | Explicitly request cancellation of a Run that is queued, running, or waiting for client tools |
| Streaming Events | GET /v1/agent-runtime/project/runs/{runId}/events | agent-runtime.project | Required (URL Query) | Idempotent | 200 | Subscribes to the AG-UI protocol SSE incremental event stream, with Last-Event-ID reconnection after disconnection |
| Run Messages | GET /v1/agent-runtime/project/runs/{runId}/messages | agent-runtime.project | Required (URL Query) | Idempotent | 200 | Reads the persisted messages produced by a single Run by after (message_seq) and limit |
| Client Tools | POST /v1/agent-runtime/project/runs/{runId}/tool-messages | agent-runtime.project | Required (JSON Body) | Idempotent (reuse id) | 202 | Returns the client tool result to a Run in WAITING_CLIENT_TOOL so execution can continue |
| Model Usage | GET /v1/agent-runtime/project/runs/{runId}/model-invocations | agent-runtime.project | Required (URL Query) | Idempotent | 200 | Reads the model call details, Token consumption, and latency records for each inference step of a single Run |
Requests and Responses
The following sections present, endpoint by endpoint in business integration order, the complete input parameter tables, output Schemas, executable curl examples, and real HTTP response examples.
1. Service Status and Initialization
1.1 Query service initialization status: GET /v1/agent-runtime/project
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required (operates on project-shared resources).Output Schema (
State):{ "initialized": boolean }. Whenfalseis returned, you must first callPOST /v1/agent-runtime/projectto complete initialization.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"initialized": true
}1.2 Initialize the project agent workbench: POST /v1/agent-runtime/project
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Request body: empty JSON object
{}. Repeated calls are idempotent and do not reset or clear existing configuration.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Content-Type: application/json' \
--data '{}'
)Response example (200 OK):
{
"initialized": true
}2. Project Configuration and Available Model Catalog
2.1 List available project models: GET /v1/agent-runtime/project/models
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Output Schema (
ModelList): contains amodelsarray, each item withmodel_id(string) andcapabilities(capability array, e.g.["chat"],["embedding"]). The agent's primary conversation model should be a model withchatcapability (e.g.qwen-plus,qwen-turbo).
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/models' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"models": [
{
"model_id": "qwen-plus",
"capabilities": [
"chat"
]
},
{
"model_id": "qwen-turbo",
"capabilities": [
"chat"
]
},
{
"model_id": "text-embedding-v3",
"capabilities": [
"embedding"
]
}
]
}2.2 Read the project agent configuration: GET /v1/agent-runtime/project/config
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Output Schema (
Config): returns the full configuration fields and a read-only configuration summaryconfig_hash. Fields not yet configured may returnnull; clients should treat this as "not configured" rather than the numeric value0.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/config' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"system_prompt": "你是企业智能客服与知识中台助手,请优先检索企业知识库回答问题,保留引用来源。",
"model_id": "qwen-plus",
"model_parameters": {
"temperature": 0.3,
"top_p": 0.9
},
"context_window_tokens": 32768,
"reserved_output_tokens": 2048,
"max_steps": 12,
"max_duration_ms": 120000,
"memory_enabled": true,
"powercontext_enabled": false,
"knowledge_search_enabled": true,
"knowledge_base_ids": [
"kb_enterprise_support"
],
"memory_embedding_model_id": "text-embedding-v3",
"memory_embedding_dimensions": 1024,
"config_hash": "8f9d2a7e4b1c6f03981e2d5c4a7b8e9f"
}2.3 Sparsely update the project agent configuration: PATCH /v1/agent-runtime/project/config
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Update semantics: when saving an executable configuration for the first time,
model_id,model_parameters,context_window_tokens,reserved_output_tokens,max_steps, andmax_duration_msmust all be provided. SubsequentPATCHcalls only need to send changed fields; note thatmodel_parametersreplaces the entire object rather than merging key by key. The server internally performs concurrency control automatically based on the latestconfig_hash, and returns409 STATE_CONFLICTif a concurrent modification conflict occurs.
Request body parameter table (ConfigPatch):
| Field name | Type | Required | Constraints and business semantics |
|---|---|---|---|
system_prompt | string | null | No | System prompt (0–200,000 characters); pass an empty string or null to use the platform default behavior. |
model_id | string | Required on first save | A model ID within the project with chat capability (e.g. qwen-plus). |
model_parameters | object | null | Required on first save | Only temperature (0–1) and top_p (0–1) are allowed; pass {} or null to clear explicit sampling parameters. |
context_window_tokens | integer | Required on first save | Total context window Token count (> 0, e.g. 32768, 65536). |
reserved_output_tokens | integer | Required on first save | Token budget reserved for model output (> 0 and must be less than context_window_tokens). |
max_steps | integer | Required on first save | Maximum number of ReAct reasoning steps allowed per Run (> 0, e.g. 12). |
max_duration_ms | integer | Required on first save | Maximum execution duration allowed per Run (milliseconds, > 0, e.g. 120000). |
memory_enabled | boolean | No | Whether to enable project long-term memory (the Memory service must first be initialized and enabled in the project; strictly mutually exclusive with powercontext_enabled). |
powercontext_enabled | boolean | No | Whether to enable managed PowerContext (a Shared V2 project must first initialize PowerContext to the ready state; enabling this automatically disables memory_enabled, and setting both to true in the same request returns 400). |
knowledge_search_enabled | boolean | No | Whether to enable the enterprise knowledge base retrieval tool (knowledge_retrieve). When newly enabled, at least 1 knowledge_base_ids must be specified at the same time. |
knowledge_base_ids | string[] | Conditionally required | Array of knowledge base IDs in this project that may be retrieved (at most 100 distinct valid IDs, e.g. ["kb_enterprise_support"]). |
memory_embedding_model_id | string | null | No | Embedding model ID used by Memory (e.g. text-embedding-v3). |
memory_embedding_dimensions | integer | null | No | Embedding vector dimension used by Memory (> 0, e.g. 1024; must match the project Memory configuration). |
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request PATCH \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/config' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Content-Type: application/json' \
--data '{
"system_prompt": "你是企业智能客服与知识中台助手,请优先检索企业知识库回答问题,保留引用来源。",
"model_id": "qwen-plus",
"model_parameters": {
"temperature": 0.3,
"top_p": 0.9
},
"context_window_tokens": 32768,
"reserved_output_tokens": 2048,
"max_steps": 12,
"max_duration_ms": 120000,
"memory_enabled": true,
"powercontext_enabled": false,
"knowledge_search_enabled": true,
"knowledge_base_ids": [
"kb_enterprise_support"
],
"memory_embedding_model_id": "text-embedding-v3",
"memory_embedding_dimensions": 1024
}'
)Response example (200 OK):
{
"system_prompt": "你是企业智能客服与知识中台助手,请优先检索企业知识库回答问题,保留引用来源。",
"model_id": "qwen-plus",
"model_parameters": {
"temperature": 0.3,
"top_p": 0.9
},
"context_window_tokens": 32768,
"reserved_output_tokens": 2048,
"max_steps": 12,
"max_duration_ms": 120000,
"memory_enabled": true,
"powercontext_enabled": false,
"knowledge_search_enabled": true,
"knowledge_base_ids": [
"kb_enterprise_support"
],
"memory_embedding_model_id": "text-embedding-v3",
"memory_embedding_dimensions": 1024,
"config_hash": "9c4e1b2d5a8f70316e9d4c2b1a0f8e7d"
}3. Project Lexicon Binding and Stopword Blocking (Lexicons)
The agent workbench supports binding business lexicons under the current project (synonyms synonym, expansion terms expansion, stopwords stop), effective during conversational retrieval rewriting and input compliance interception.
3.1 Read the bound lexicon configuration: GET /v1/agent-runtime/project/lexicons
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/lexicons' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"enabled": true,
"stopIntercept": true,
"stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
"bindings": [
{
"lexiconId": "lex_enterprise_synonyms",
"priority": 1
},
{
"lexiconId": "lex_support_stopwords",
"priority": 2
}
]
}3.2 Update the bound lexicon configuration: PUT /v1/agent-runtime/project/lexicons
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Request body parameter table (
LexiconBindingsInput):
| Field name | Type | Required | Default value | Constraints and business semantics |
|---|---|---|---|---|
bindings | array | Yes | [] | Ordered lexicon binding array (at most 100 items; duplicate lexiconId values are forbidden). Each item must be strictly {"lexiconId": string, "priority": integer}, where priority is an integer from 0–2147483647; lower values indicate higher priority. |
enabled | boolean | No | false | Whether to enable the bound lexicon rules. |
stopIntercept | boolean | No | true | Whether to immediately short-circuit and block the current Run when user input matches a stop (stopword) lexicon entry. |
stopReply | string | No | "" | The preset compliance message returned directly when a stopword short-circuit block is triggered (up to 4096 characters). |
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request PUT \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/lexicons' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Content-Type: application/json' \
--data '{
"enabled": true,
"stopIntercept": true,
"stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
"bindings": [
{
"lexiconId": "lex_enterprise_synonyms",
"priority": 1
},
{
"lexiconId": "lex_support_stopwords",
"priority": 2
}
]
}'
)Response example (200 OK):
{
"enabled": true,
"stopIntercept": true,
"stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
"bindings": [
{
"lexiconId": "lex_enterprise_synonyms",
"priority": 1
},
{
"lexiconId": "lex_support_stopwords",
"priority": 2
}
]
}4. AI Gateway Binding
AI Gateway binding requires the current project to use the Shared V2 storage mode and the target Gateway to be in the ACTIVE state with an available snapshot already published in the current region.
4.1 Read the bound AI Gateway: GET /v1/agent-runtime/project/gateway
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required. Returns404 NOT_FOUNDwhen no Gateway is bound.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/gateway' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"gateway_id": "gw_7194685489feb1e169548619",
"created_at": "2026-10-22T08:00:00Z"
}4.2 Bind or switch AI Gateway: PUT /v1/agent-runtime/project/gateway
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Request body:
{ "gateway_id": "gw_7194685489feb1e169548619" }(required string; passing an empty string to unbind is not supported — switch to another valid Gateway by callingPUTagain).
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request PUT \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/gateway' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Content-Type: application/json' \
--data '{
"gateway_id": "gw_7194685489feb1e169548619"
}'
)Response example (200 OK):
{
"gateway_id": "gw_7194685489feb1e169548619",
"created_at": "2026-10-22T08:00:00Z"
}5. Skill Package Management
Skill archive packages support the .zip, .tar.gz, or .tgz formats, with a maximum size of 10 MiB per package. The root directory must contain a SKILL.md with YAML Front Matter (name: 1–64 lowercase letters/digits/single hyphens; description: 1–1024 characters).
5.1 Upload a Skill package: POST /v1/agent-runtime/project/skills
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Request format:
multipart/form-data, with the required binary file fieldfile.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--form 'file=@./enterprise-order-sop.zip'
)Response example (201 Created):
{
"skill_id": "skill_order_sop_01",
"name": "enterprise-order-sop",
"description": "企业订单查询、异常催单与退换货标准处理流程规范。",
"front_matter": {
"name": "enterprise-order-sop",
"description": "企业订单查询、异常催单与退换货标准处理流程规范。"
},
"content_hash": "sha256:4a8b9c1d2e3f5a6b7c8d9e0f1a2b3c4d",
"created_by": "api_key_enterprise",
"created_at": "2026-10-22T08:05:00Z",
"updated_at": "2026-10-22T08:05:00Z"
}5.2 List project Skill packages: GET /v1/agent-runtime/project/skills
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Output Schema (
SkillList): returns theitemsarray, a directory summaryskill_catalog_hash, the current upload countskill_count, and the project quota limitskill_limit.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"items": [
{
"skill_id": "skill_order_sop_01",
"name": "enterprise-order-sop",
"description": "企业订单查询、异常催单与退换货标准处理流程规范。",
"front_matter": {
"name": "enterprise-order-sop",
"description": "企业订单查询、异常催单与退换货标准处理流程规范。"
},
"content_hash": "sha256:4a8b9c1d2e3f5a6b7c8d9e0f1a2b3c4d",
"created_by": "api_key_enterprise",
"created_at": "2026-10-22T08:05:00Z",
"updated_at": "2026-10-22T08:05:00Z"
}
],
"skill_catalog_hash": "cat_9f8e7d6c5b4a3210",
"skill_count": 1,
"skill_limit": 10
}5.3 Read a single Skill's metadata: GET /v1/agent-runtime/project/skills/{skillId}
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills/skill_order_sop_01' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK): returns the same Skill JSON object as the upload response (without the binary archive stream).
5.4 Replace a Skill package: PUT /v1/agent-runtime/project/skills/{skillId}
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.Request format:
multipart/form-data, with the required binary file fieldfile.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request PUT \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills/skill_order_sop_01' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--form 'file=@./enterprise-order-sop-v2.zip'
)Response example (200 OK): returns the updated Skill JSON object (with content_hash and updated_at refreshed).
5.5 Delete a Skill package: DELETE /v1/agent-runtime/project/skills/{skillId}
Permission Scope:
agent-runtime.projectUser parameter:
userIdis not required.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request DELETE \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/skills/skill_order_sop_01' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example: HTTP/1.1 204 No Content (no response body).
6. Thread Management and History Reading
6.1 Create a thread: POST /v1/agent-runtime/project/threads
Permission Scope:
agent-runtime.projectUser parameter:
userIdRequired (JSON Body), specifying the business end user who owns the new thread.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Content-Type: application/json' \
--data '{
"userId": "user_zhangwei_001"
}'
)Response example (201 Created):
{
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"title": null,
"status": "ACTIVE"
}6.2 List user threads: GET /v1/agent-runtime/project/threads
Permission Scope:
agent-runtime.projectQuery parameters:
userId(string, required): the target business user ID (only that user's own threads are returned).limit(integer, optional, default100, range1–1000): the maximum number of threads returned, sorted by most recent update time in descending order.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads?userId=user_zhangwei_001&limit=50' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
[
{
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"title": "专票开具与订单发货咨询",
"status": "ACTIVE"
}
]6.3 Query a single thread: GET /v1/agent-runtime/project/threads/{threadId}
Permission Scope:
agent-runtime.projectPath parameter:
threadId(required).Query parameter:
userId(string, required; must be the same user who created the Thread).
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads/th_01ja9x8k2m4n6p8q0r2s4t6v8w?userId=user_zhangwei_001' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"title": "专票开具与订单发货咨询",
"status": "ACTIVE"
}6.4 Archive a thread: DELETE /v1/agent-runtime/project/threads/{threadId}
Permission Scope:
agent-runtime.projectPath parameter:
threadId(required).Query parameter:
userId(string, required).Behavior description: changes the thread state to
ARCHIVEDand returns204 No Contenton success. If the thread still has unfinished Runs, wait for them to finish or call the cancel endpoint first. Archiving a thread does not delete that user's long-term memory in Memory or PowerContext.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request DELETE \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads/th_01ja9x8k2m4n6p8q0r2s4t6v8w?userId=user_zhangwei_001' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example: HTTP/1.1 204 No Content.
6.5 Read thread persisted messages: GET /v1/agent-runtime/project/threads/{threadId}/messages
Permission Scope:
agent-runtime.projectQuery parameters:
userId(string, required): the ID of the user the thread belongs to.after(integer, optional, default0): cursor over the monotonically increasing message sequence numbermessage_seqwithin the thread; when paging forward, pass themessage_seqof the last message on the previous page (must not be mixed with the SSE eventid).limit(integer, optional, default100, range1–1000): number of items returned per page.
Message object (Message) field descriptions:
| Field name | Type | Description |
|---|---|---|
message_id | string | Unique message identifier |
thread_id | string | ID of the thread the message belongs to |
run_id | string | ID of the Run that produced the message |
trace_id | string (optional) | Associated Observability Trace ID |
message_seq | integer | Strictly increasing message sequence number within a session (used for after cursor pagination and client-side deduplication) |
message_type | string | Enum: USER, ASSISTANT, TOOL_CALL, TOOL_RESULT |
payload | string | object | USER and ASSISTANT messages are plain string text; TOOL_CALL and TOOL_RESULT are structured JSON objects |
tool_call_id | string | null | Tool call association ID (null for ordinary text messages) |
created_at | string | RFC 3339 UTC creation time |
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads/th_01ja9x8k2m4n6p8q0r2s4t6v8w/messages?userId=user_zhangwei_001&after=0&limit=100' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
[
{
"message_id": "msg_01ja9x9a1b2c3d4e5f6g7h8j9k",
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
"message_seq": 1,
"message_type": "USER",
"payload": "请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。",
"tool_call_id": null,
"created_at": "2026-10-22T08:10:00Z"
},
{
"message_id": "msg_01ja9x9f9e8d7c6b5a4f3e2d1c",
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
"trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"message_seq": 4,
"message_type": "ASSISTANT",
"payload": "订单 ORD-20261022-889 已通过顺丰发出。若跨月发生退货且增值税专用发票已认证抵扣,需由购买方在税务系统填开《开具红字增值税专用发票信息表》,审核通过后方可开具红字发票。",
"tool_call_id": null,
"created_at": "2026-10-22T08:10:04Z"
}
]6.6 Read session context compaction records: GET /v1/agent-runtime/project/threads/{threadId}/context-compactions
Permission Scope:
agent-runtime.projectQuery parameters:
userId(string, required). Returns at most 1000 context compaction and run boundary events (CONTEXT_COMPACTION_STARTED,CONTEXT_COMPACTION_COMPLETED,CONTEXT_COMPACTION_FAILED,RUN_FINISHED,RUN_ERROR).
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/threads/th_01ja9x8k2m4n6p8q0r2s4t6v8w/context-compactions?userId=user_zhangwei_001' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"items": [
{
"run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
"event_seq": 12,
"type": "CONTEXT_COMPACTION_COMPLETED",
"payload": [],
"created_at": "2026-10-22T08:10:02Z"
}
]
}7 Run submission, streaming subscription, client tool result return, and model call records
7.1 Create and asynchronously submit a Run: POST /v1/agent-runtime/project/runs
Permission Scope:
agent-runtime.projectRequest headers: may carry
Idempotency-Key(1–128 bytes).Request body parameter table (
CreateRun):
| Field name | Type | Required | Constraints and description |
|---|---|---|---|
userId | string | Yes | Must exactly match (case-insensitive) the business user ID that the target thread_id belongs to. |
thread_id | string | Yes | Target session ID. An unfinished active Run must not exist under the same Thread, otherwise 409 THREAD_BUSY is returned. |
user_message | string | Yes | Non-empty text message of the user's input for this turn. |
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Idempotency-Key: req_zhangwei_20261022_001' \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--data '{
"userId": "user_zhangwei_001",
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"user_message": "请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。"
}'
)First acceptance response example (202 Accepted):
{
"run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
"status": "QUEUED",
"created_at": "2026-10-22T08:10:00Z"
}Replay response example with the same Idempotency-Key and identical request body (200 OK):
{
"run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
"status": "RUNNING",
"created_at": "2026-10-22T08:10:00Z",
"idempotent_replay": true
}7.2 Query Run status: GET /v1/agent-runtime/project/runs/{runId}
Permission Scope:
agent-runtime.projectQuery parameter:
userId(string, required).
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9?userId=user_zhangwei_001' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
"status": "SUCCEEDED",
"created_at": "2026-10-22T08:10:00Z"
}7.3 Subscribe to the resumable SSE event stream: GET /v1/agent-runtime/project/runs/{runId}/events
Permission Scope:
agent-runtime.projectQuery parameter:
userId(string, required).Request headers:
Accept: text/event-stream; carryLast-Event-ID: <上次收到的外层帧 id>when reconnecting after disconnection.
Complete table of SSE event types (AG-UI protocol):
Event type | data Core JSON fields | Client-side handling semantics |
|---|---|---|
RUN_STARTED | runId, threadId | Marks the start of the current Run's execution |
TEXT_MESSAGE_START | messageId, role: "assistant" | Initializes an assistant answer message container |
TEXT_MESSAGE_CONTENT | messageId, delta: string | Appends streamed answer text fragments according to messageId |
TEXT_MESSAGE_END | messageId | Current paragraph text output is complete (does not mean the entire Run has ended) |
REASONING_START / REASONING_END / REASONING_MESSAGE_END | messageId | Maintains display state boundaries for the model's thinking/reasoning process |
REASONING_MESSAGE_START / REASONING_MESSAGE_CONTENT | messageId, role: "reasoning", delta: string | Displays streamed model thinking fragments |
TOOL_CALL_START | toolCallId, toolCallName, toolCallSource | Records the start of a tool call (toolCallSource is either "CLIENT" or a server-side tool source) |
TOOL_CALL_ARGS | toolCallId, toolCallSource, delta: string | Concatenates tool call argument JSON fragments according to toolCallId (non-client tools may be masked as {"redacted":true}) |
TOOL_CALL_END | toolCallId, toolCallSource | Tool argument transmission is complete; if toolCallSource === "CLIENT", query the Run status, and after it enters WAITING_CLIENT_TOOL, execute the local tool and return |
TOOL_CALL_RESULT | toolCallId, messageId, role: "tool", content | Tool result has been recorded (default notification summary is {"status":"completed"}; the full structured result is read via the message API) |
RUN_FINISHED | runId, threadId | Run completed normally; subsequently read the Run final state and persisted messages |
RUN_ERROR | runId, threadId, message, code (optional) | Run execution errored or was canceled (e.g., code: "RUN_CANCELLED"); read the Run status to confirm the final state |
CUSTOM | name, value: object | Platform extension events: appbase.context.compaction (context compaction), appbase.run.cancelled (cancellation notice), appbase.stream.attempt_aborted (Worker failover discarding a temporary output attempt; the client should calibrate the UI based on persisted messages) |
First connection and reconnect/resume call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
# Subscribe to the event stream for the first time
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET -N \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/events?userId=user_zhangwei_001' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Accept: text/event-stream'
# After disconnection, resume the same Run by carrying Last-Event-ID
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET -N \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/events?userId=user_zhangwei_001' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Accept: text/event-stream' \
--header 'Last-Event-ID: 20'
)SSE response stream example (200 OK):
id: 21
event: TEXT_MESSAGE_CONTENT
data: {"type":"TEXT_MESSAGE_CONTENT","timestamp":1792656603000,"messageId":"msg_01ja9x9f9e8d7c6b5a4f3e2d1c","delta":"订单 ORD-20261022-889 已通过顺丰发出。"}
id: 22
event: RUN_FINISHED
data: {"type":"RUN_FINISHED","timestamp":1792656604000,"runId":"run_01ja9x90a1b2c3d4e5f6g7h8j9","threadId":"th_01ja9x8k2m4n6p8q0r2s4t6v8w"}7.4 Return client tool results: POST /v1/agent-runtime/project/runs/{runId}/tool-messages
When a Run is paused in the WAITING_CLIENT_TOOL state because a CLIENT tool was triggered, the business side executes the local approved logic and calls this API to return the result, continuing the same Run.
Permission Scope:
agent-runtime.projectRequest body parameter table (
ToolMessage):
| Field name | Type | Required | Constraints and description |
|---|---|---|---|
userId | string | Yes | Must be consistent with the business user ID that the current Run belongs to. |
id | string | Yes | Client-generated unique identifier of the tool message (kept unchanged when retrying the same return). |
role | string | Yes | Fixed to "tool". |
toolCallId | string | Yes | Corresponds to the toolCallId in the TOOL_CALL_START / TOOL_CALL_END events. |
content | string | Yes | JSON-serialized string (note: must be a string, e.g., "{\"order_id\":\"ORD-20261022-889\",\"status\":\"shipped\"}"; you cannot pass a JSON object directly; when returning a failure you may pass "{}"). If the tool declared a outputSchema in the Gateway, the success result will be validated against that Schema. |
error | string | No | When local tool execution fails, fill in an explanation of the error so the model becomes aware of the failure and continues making decisions. |
Call example (successful return):
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/tool-messages' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Content-Type: application/json' \
--data '{
"userId": "user_zhangwei_001",
"id": "tmsg_01ja9x9c4d5e6f7g8h9j0k1l2m",
"role": "tool",
"toolCallId": "call_order_lookup_001",
"content": "{\"order_id\":\"ORD-20261022-889\",\"status\":\"shipped\",\"carrier\":\"SF-Express\"}"
}'
)Response example (202 Accepted):
{
"run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
"status": "QUEUED",
"created_at": "2026-10-22T08:10:00Z"
}7.5 Cancel a Run: POST /v1/agent-runtime/project/runs/{runId}/cancel
Permission Scope:
agent-runtime.projectRequest body:
{ "userId": "user_zhangwei_001" }(required).Behavior description: Disconnecting the SSE stream does not cancel the background Run; you must explicitly call this API. Upon acceptance it returns
202 Accepted(statusCANCEL_REQUESTED); if the Run is already in a final state,200 OKis returned.
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request POST \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/cancel' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @- \
--header 'Content-Type: application/json' \
--data '{
"userId": "user_zhangwei_001"
}'
)Response example (202 Accepted):
{
"run_id": "run_01ja9x90a1b2c3d4e5f6g7h8j9",
"status": "CANCEL_REQUESTED",
"created_at": "2026-10-22T08:10:00Z"
}7.6 Read persisted messages of a single Run: GET /v1/agent-runtime/project/runs/{runId}/messages
Permission Scope:
agent-runtime.projectQuery parameters:
userId(required),after(optional, default0),limit(optional, default100).
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/messages?userId=user_zhangwei_001&after=0&limit=100' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK): Returns a Message[] array with the same structure as GET /threads/{threadId}/messages, containing only messages produced by this runId (including knowledge base retrieval fragments in TOOL_CALL and TOOL_RESULT, and the final ASSISTANT answer).
7.7 Read model call records of a single Run: GET /v1/agent-runtime/project/runs/{runId}/model-invocations
Permission Scope:
agent-runtime.projectQuery parameter:
userId(string, required).
Call example:
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable --request GET \
'<APPBASE_ENDPOINT_WITH_V1>/agent-runtime/project/runs/run_01ja9x90a1b2c3d4e5f6g7h8j9/model-invocations?userId=user_zhangwei_001' \
--header 'X-Appwrite-Project: <APPBASE_PROJECT_ID>' \
--header @-
)Response example (200 OK):
{
"items": [
{
"invocation_id": "inv_01ja9x92b3c4d5e6f7g8h9j0k1",
"model_step": 1,
"purpose": "AGENT_RESPONSE",
"attempt": 1,
"model_id": "qwen-plus",
"input_tokens": 1420,
"output_tokens": 215,
"cached_tokens": 0,
"reasoning_tokens": null,
"provider_usage_available": true,
"provider_request_id": "chatcmpl-9f8e7d6c-dashscope",
"duration_ms": 1580,
"status": "SUCCEEDED",
"started_at": "2026-10-22T08:10:01Z",
"finished_at": "2026-10-22T08:10:02.580Z"
}
]
}Errors and boundaries
Error response structure
Project-level agent workbench APIs may return two types of error structures, and clients should be compatible with both:
Runtime domain errors (
RuntimeError):
{
"error": {
"code": "THREAD_BUSY",
"message": "thread has an open run"
},
"request_id": "req_01ja9x9z8y7x6w5v4u3t2s1r0q"
}Platform gateway-layer errors (
PlatformError) (triggered during API Key authentication, Scope validation, and parameter format validation):
{
"message": "Invalid `userId` param: Value must be a valid string of 1 to 128 alphanumeric or underscore characters.",
"code": 400,
"type": "general_argument_invalid",
"version": "2.10.0"
}SSE cursor expiration error (HTTP
409): May be returned when the cache still contains entries andLast-Event-IDis too far behind. Default retention is 30 minutes, measured from the Run deadline for ordinary events and from publication time for terminal events; the entry limit may evict older events sooner. If the entire cache is absent, terminal Runs or Runs waiting for a client tool may return fallback events instead of 409; check the Run state and persisted messages:
{
"code": "stream_cursor_expired",
"earliest_event_id": 300,
"latest_event_id": 650
}Troubleshooting table of common status codes and business error codes
| HTTP status / occurrence location | Error code (error.code / type / code) | Trigger reason | Standard client recovery and troubleshooting strategy |
|---|---|---|---|
400 Bad Request | general_argument_invalid / INVALID_REQUEST | Missing or invalid userId (e.g., containing a hyphen -, passing system, putting it in the wrong Query/Body location, or passing it twice); or both memory_enabled and powercontext_enabled set to true; or enabling knowledge retrieval without selecting a knowledge_base_ids. | Verify the userId regex (^[A-Za-z0-9_]{1,128}$) and the parameter location (POST in Body, GET/DELETE in Query); verify configuration mutual-exclusion and the non-empty knowledge base constraint. |
401 / 403 | user_unauthorized / general_access_forbidden | X-Appwrite-Project does not match the API Key, or the API Key lacks the agent-runtime.project Scope. | In the Console, check the agent-runtime.project permission Scope for the current project's API Key. |
404 Not Found | NOT_FOUND / lexicon_not_found | threadId, runId, or skillId does not exist, or the passed userId does not match the user who created the Thread/Run, or the AI Gateway has not been bound yet. | Verify that the resource ID and its owning userId are consistent; cross-user access is always rejected as not found. |
409 Conflict | STATE_CONFLICT | A business API was called before the project Agent Runtime was initialized, or a config_hash optimistic-locking conflict occurred during concurrent multi-user updates to /config. | Call POST /v1/agent-runtime/project first to initialize; on configuration conflict, re-GET /config and merge changes before retrying. |
409 Conflict | THREAD_BUSY | The target thread_id already has an active Run in the SUBMITTING, QUEUED, RUNNING, WAITING_CLIENT_TOOL, or CANCEL_REQUESTED state. | Continue subscribing to or polling the existing active Run; if waiting for a client tool, return tool-messages; if the old task truly needs to be abandoned, call /cancel first and wait for the final state. |
409 Conflict | IDEMPOTENCY_KEY_CONFLICT | The same Idempotency-Key was used to submit a different thread_id, userId, or user_message. | Retrying the same submission must keep the request body completely identical; a new Idempotency-Key must be generated when asking a new question. |
409 Conflict | stream_cursor_expired | The Last-Event-ID carried on reconnection has slid out of the bounded event stream cache window. | First call GET /runs/{runId} and GET /runs/{runId}/messages to recover persisted state and messages; if the Run is still running, resubscribe from earliest_event_id - 1 — never create a duplicate Run. |
Run FAILED | MODEL_RATE_LIMITED | The upstream model provider (e.g., DashScope) triggered TPM / RPM rate limiting. | Check the model provider's quota and concurrency, apply exponential backoff, and start a new Run as needed. |
Run FAILED | MODEL_UPSTREAM_FAILED | Upstream model call timed out, credentials expired, or an abnormal response was returned. | Check the provider_request_id and error details in GET /runs/{runId}/model-invocations, and troubleshoot LLM Provider connectivity. |
Run FAILED | CONTEXT_BUDGET_EXCEEDED / CONTEXT_PREPARE_FAILED / CONTEXT_FRESH_TAIL_TOO_LARGE | A single user input, tool definition, or recent uncompressed messages exceeded the input budget of context_window_tokens - reserved_output_tokens. | Increase context_window_tokens, reduce reserved_output_tokens appropriately, or streamline single-turn input and the number of mounted tools. |
Run FAILED | RUN_DEADLINE_EXCEEDED | The total execution time of a single Run exceeded the configured max_duration_ms. | Investigate slow tool call durations, or appropriately raise max_duration_ms in PATCH /config. |
Run FAILED | TOOL_RESULT_UNKNOWN | An external tool call was interrupted by a network outage or process restart during execution, so it cannot be confirmed whether the external write operation took effect. | Never blindly and automatically redo side-effecting tool calls; first query the real state of the external business system, confirm it, and then decide on subsequent actions. |
503 Service Unavailable | RUN_ADMISSION_DISABLED | The instance is under maintenance or paused from accepting new Runs. | Keep the original Idempotency-Key and retry with delayed backoff. |
Correspondence with the Server SDK
Project workbench endpoints are under /v1/agent-runtime/project/*. From your backend, send HTTP or SSE requests to the configured Agentbase endpoint using X-Appwrite-Project and a suitably scoped X-Appwrite-Key. Disable automatic redirects. See the SDK integration guide for supported installation options and the Agent Runtime SDK reference for request guidance.
| Business action | HTTP method and path | Request authentication header and userId location | Backend HTTP request |
|---|---|---|---|
| Query / initialize workbench | GET | POST /v1/agent-runtime/project | X-Appwrite-Project + X-Appwrite-Key (no userId) | Send the project headers with GET or POST {} (see the Agent Runtime SDK reference) |
| Read / update workbench configuration | GET | PATCH /v1/agent-runtime/project/config | X-Appwrite-Project + X-Appwrite-Key (no userId) | GET Reads configuration and config_hash; PATCH sends a sparse JSON configuration object |
| List available models | GET /v1/agent-runtime/project/models | X-Appwrite-Project + X-Appwrite-Key (no userId) | GET Reads models[] (including model_id and capabilities) |
| Read / bind project lexicon | GET | PUT /v1/agent-runtime/project/lexicons | X-Appwrite-Project + X-Appwrite-Key (no userId) | GET / PUT JSON { bindings, enabled, stopIntercept, stopReply } |
| Read / bind AI Gateway | GET | PUT /v1/agent-runtime/project/gateway | X-Appwrite-Project + X-Appwrite-Key (no userId) | GET / PUT JSON { gateway_id } |
| Skill package management | GET | POST /v1/agent-runtime/project/skills, GET | PUT | DELETE .../skills/{skillId} | X-Appwrite-Project + X-Appwrite-Key (no userId) | Upload and replacement use multipart/form-data (field file) |
| Create / query / archive Thread | POST | GET /v1/agent-runtime/project/threads, GET | DELETE .../threads/{threadId} | POST Pass userId in the JSON Body; GET/DELETE pass userId in the Query | Map a stable lowercase userId per business end user and call |
| Read session messages and context compaction | GET .../threads/{threadId}/messages, GET .../threads/{threadId}/context-compactions | Pass userId in the Query (pass after and limit additionally for message pagination) | Use the message_seq at the end of the previous page as the after of the next page |
| Create / query / cancel Run | POST /v1/agent-runtime/project/runs, GET .../runs/{runId}, POST .../runs/{runId}/cancel | POST passes userId in the Body (creation includes the Idempotency-Key header); GET passes userId in the Query | Creation acceptance returns 202 and run_id, decoupled from the SSE subscription |
| Subscribe to the resumable SSE event stream | GET /v1/agent-runtime/project/runs/{runId}/events | Pass userId in the Query; Header carries Accept: text/event-stream and optional Last-Event-ID | Use a streaming HTTP client to parse AG-UI events frame by frame and record the latest id |
| Returns the client tool result | POST /v1/agent-runtime/project/runs/{runId}/tool-messages | Pass in the Body { userId, id, role: "tool", toolCallId, content, error? } | Return to the same runId in the WAITING_CLIENT_TOOL state |
| Read Run messages and model calls | GET .../runs/{runId}/messages, GET .../runs/{runId}/model-invocations | Pass userId in the Query | After the final state, read the final persisted answer, knowledge retrieval citations, and per-step Token consumption |
2.12.0 endpoints and compatibility
Paths below are relative to /v1. Server requests carry X-Appwrite-Project and X-Appwrite-Key; keep the key on the server. Scopes below are necessary; dataset access, ownership and resource state may add checks. HTTP 202 means accepted; use the returned operation identifier to read its terminal result.
| HTTP | Scope | SDK |
|---|---|---|
GET /powercontext/subjects/{subjectId} | users.read | powercontext.resolveSubject |
GET /powercontext/subjects/{subjectId}
Resolve a PowerContext authorization subject
| Parameter | Location | Required | Type | Constraints / default | Meaning |
|---|---|---|---|---|---|
subjectId | path | yes | string | — | Application user ID or backend-owned UID. |
kind | query | no | string | enum=account, external; default="account" | Identity source. |
Success response: HTTP 200 — any.
Errors and retries
400/422: check types, enumerations and rules. 401/403: verify identity and scopes; dataset analyses additionally require trace and dataset read access. 404: check that the resource exists in the current project. 409: read current state before deciding to retry. 429: honor Retry-After. After 5xx or network loss, inspect operation state first. Preserve an idempotency key across retries; change it only for a deliberate new operation. Confirm deletion and clearing targets before writing.