Agent Runtime (Project-level Agent Workbench)
Overview and use cases
Agent Runtime (agent workbench) is a project-level managed agent runtime engine provided by Agentbase (/v1/agent-runtime/project/*). The business backend does not need to maintain the complex "Prompt assembly → model inference → tool calling → context compression → streaming push" ReAct loop at the application layer: simply configure a conversational model (e.g. qwen-plus), a system prompt, and the desired capability toggles (enterprise knowledge base retrieval Knowledge Search, long-term Memory or managed context PowerContext, project Lexicons, AI Gateway tools and Skill packs) in the current project, and then use the unified Project API Key to create continuous sessions (Threads) for different business end users (userId), submit tasks asynchronously (Runs), subscribe to AG-UI streaming events (SSE) with reconnection support, and in client tool scenarios pause, await the callback, and continue the same Run.
Typical use cases:
Multi-tenant enterprise customer service and knowledge assistants: the backend holds a single Project API Key and, by passing the business system's own
userId(e.g.user_zhangwei_001,user_lina_002), isolates the session history and long-term memory of different end users while sharing the project-level knowledge base (kb_enterprise_support) and compliance lexicons (lex_enterprise_synonyms,lex_support_stopwords).Business tools and frontend interaction coordination: by binding an AI Gateway under the same project (
gw_7194685489feb1e169548619), the agent automatically calls controlled MCP / HTTP server-side tools during inference, or triggersCLIENTtools to be executed on the application side with results returned.High-reliability long tasks and mobile weak-network recovery: Run creation (
202 Accepted) and the SSE event stream (GET .../events) are decoupled; a brief client network interruption does not cancel the background Run, and on reconnection simply carryLast-Event-IDto continue receiving incremental events from the breakpoint.
Prerequisites
| Configuration item / dependency | Specification requirements and SIT demo coordinates |
|---|---|
| API Endpoint | https://appbuild-sit.oceanbase.com/v1 (project-level agent workbench path prefix: /v1/agent-runtime/project) |
| Owning organization and project | Organization: Agentbase 企业智能中台 (69c6d1aa00062e6bb60); project: 企业智能客服与知识中台 (Project ID: enterprise-ai-hub-210, Shared V2 storage mode) |
| Auth header and minimal scope | X-Appwrite-Project: enterprise-ai-hub-210 + X-Appwrite-Key: <APPBASE_API_KEY>; the API Key must include the agent-runtime.project scope (covering the full set of 27 endpoints for configuration management and session execution) |
| SDK version baseline | Node.js: agentbase-node-sdk@2.10.0; Python: agentbase-python-sdk==2.10.0; Java: io.agentbase:agentbase-server-java:2.10.0; Go: agentbase-go-sdk (v2.10.0) |
Multi-user isolation parameter userId | 1–128 ASCII letters, digits, or underscores (^[A-Za-z0-9_]{1,128}$), case-insensitive (the server normalizes everything to lowercase); system is a reserved word.14 project-shared configuration endpoints do not pass userId; 13 user-level Thread/Run endpoints require userId (POST in the JSON Body, GET / DELETE in the URL Query) |
| Associated project resources (as needed) | Chat models: qwen-plus / qwen-turbo (Provider: dashscope-prod); embedding model: text-embedding-v3 (1024 dimensions); knowledge base: kb_enterprise_support; lexicons: lex_enterprise_synonyms, lex_support_stopwords; AI Gateway: gw_7194685489feb1e169548619 (must be a Shared V2 project and the Gateway status must be ACTIVE) |
Usage workflow
Initialize the project workbench and save the run configuration: query the
/v1/agent-runtime/projectstatus → perform idempotent initializationPOST /v1/agent-runtime/project→ query available modelsGET .../models→ configurePATCH .../config, system prompt, context budget, and the Memory / Knowledge Search toggles viaqwen-plus.Bind project lexicons and the AI Gateway: mount the enterprise synonym and stopword lexicons via
PUT .../lexicons(configurestopIntercept: trueand compliance interception scriptsstopReply); bind an active AI Gateway viaPUT .../gateway.Upload and manage Skill packages: upload
.zip/.tar.gz/.tgzSkill packages containingSKILL.mdto/v1/agent-runtime/project/skillsviamultipart/form-data, allowing agents to read standard operating procedures on demand.Create sessions for business users and submit Runs idempotently: call
POST .../threadswith the business user'suserId(e.g.,user_zhangwei_001) to create a session → callPOST .../runswithIdempotency-Keyto submit the question (returns202 Acceptedandrun_id).Subscribe to the resumable SSE event stream and read the final message: call
GET .../runs/{runId}/events?userId=...to consume AG-UI events such asTEXT_MESSAGE_CONTENTandTOOL_CALL_*in real time and record the latest frameid; if the network disconnects, resume the same Run by passingLast-Event-ID; after receivingRUN_FINISHED, callGET .../runs/{runId}/messagesto read the persisted answer and knowledge references.Handle Client Tool returns, explicit cancellation, and usage auditing: when the Run enters
WAITING_CLIENT_TOOL, execute the locally approved tool and restore the same Run by returning the result viaPOST .../runs/{runId}/tool-messages; callPOST .../runs/{runId}/cancelexplicitly when a task needs to be terminated; audit Token consumption and context compaction records viaGET .../model-invocationsandGET .../context-compactions.
Key parameters and returns
| Endpoint / phase | Key input parameters and locations | Core return fields and handling points |
|---|---|---|
Update configuration PATCH /project/config | Body (no userId): system_prompt, model_id, model_parameters (temperature/top_p), context_window_tokens, reserved_output_tokens, max_steps, max_duration_ms, memory_enabled, powercontext_enabled (mutually exclusive with Memory), knowledge_search_enabled, knowledge_base_ids (at most 100 IDs), memory_embedding_model_id, memory_embedding_dimensions. | Returns the full Config object and the read-only config_hash. When a Run is accepted, the configuration snapshot for that run is frozen; modifying the configuration does not affect in-flight Runs. |
Bind lexicons PUT /project/lexicons | Body (no userId): bindings: [{ lexiconId, priority }] (at most 100 entries), enabled: boolean, stopIntercept: boolean, stopReply: string (max 4096 characters). | Returns the effective LexiconBindings. When stopIntercept is enabled, user input matching a stop entry will short-circuit and terminate the Run, directly returning stopReply. |
Upload Skill POST /project/skills | multipart/form-data (no userId): binary file field file (.zip / .tar.gz / .tgz, <= 10 MiB, root directory contains SKILL.md). | 201 Created, returning skill_id, name, description, front_matter, content_hash. The list endpoint additionally returns skill_count and skill_limit. |
Create session POST /project/threads | Body: { "userId": "user_zhangwei_001" }. | 201 Created, returning thread_id, title (initial null), status: "ACTIVE". All subsequent operations on this Thread must use the same userId. |
Create Run POST /project/runs | Header: Idempotency-Key (1–128 bytes); Body: { "userId", "thread_id", "user_message" }. | First acceptance returns 202 Accepted (run_id, status: "QUEUED", created_at); replaying with the same idempotency key and same request body returns 200 OK and idempotent_replay: true. |
SSE event stream GET /project/runs/{runId}/events | Query: userId; Header: Accept: text/event-stream, and on reconnection pass Last-Event-ID. | Each frame contains the outer id, event, and data (JSON, containing type, messageId/toolCallId, delta, etc.). The outer id is used for Last-Event-ID resumption and must not be confused with the message sequence number message_seq. |
Return tool result POST /project/runs/{runId}/tool-messages | Body: { "userId", "id", "role": "tool", "toolCallId", "content", "error" } (error optional), where content must be a JSON-serialized string (e.g., "{\"status\":\"shipped\"}"). | 202 Accepted, returning Run (status returns to QUEUED to continue executing the same Run; a second Run is not created). |
Message pagination GET .../messages | Query: userId, after (default 0, pass the message_seq of the last item on the previous page), limit (default 100, 1–1000). | Returns a Message[] array (message_id, message_seq, message_type, payload, tool_call_id, trace_id). |
Errors and boundaries
Iron rules for user isolation and parameter placement:
userIdcan only be generated by mapping a real login session in a controlled backend; it is strictly forbidden to hand the Project API Key to the frontend and let the frontend fill inuserIditself.POSTEndpointsuserIdplace it in the JSON Body;GET/DELETEendpoints place it in the URL Query viauserId; omitting it, passing it twice, including a hyphen-, or using the reserved wordsystemall return400 general_argument_invalid. Cross-user access to anotheruserId's Thread/Run uniformly returns404 NOT_FOUND.Single-session concurrency exclusivity (
409 THREAD_BUSY): only one unfinished Run (includingWAITING_CLIENT_TOOLstatus) may exist at any moment for the samethread_id. To start a new conversation, you must first complete the current client tool return, or explicitly callPOST .../canceland wait for the status to converge toCANCELLED.SSE disconnection is not cancellation; when the cursor expires, read persisted facts first: closing the SSE connection does not stop the background Run. When the disconnection lasts so long that
Last-Event-IDprecedes the Redis retention window (by default, 30 minutes after the Run deadline or more than 8192 events), the endpoint returns409 stream_cursor_expired(containingearliest_event_idandlatest_event_id) — in that case, first callGET .../runs/{runId}andGET .../messagesto restore the persisted state and messages; do not blindly create a new Run.Memory and PowerContext are mutually exclusive: in the same project configuration,
memory_enabledandpowercontext_enabledcannot both betrue; before enabling either capability, the corresponding project service must be initialized first, whileknowledge_search_enabledcan be freely combined with either one.Idempotency protection for external tool side effects: when a Run returns
TOOL_RESULT_UNKNOWNor a network timeout triggers a reconnect, the Runtime does not roll back write operations on external business systems; the client must deduplicate bytoolCallId, and business operations with side effects must first query the actual business state before deciding whether to retry.
SDK Category Differences
| SDK category and language coverage | Integration approach for the project-level agent workbench (/v1/agent-runtime/project/*) |
|---|---|
| Node.js Server SDK (server-sdk/nodejs.md) | Initialize the agentbase-node-sdk@2.10.0's Client (set the Endpoint, Project ID enterprise-ai-hub-210, and an API Key containing agent-runtime.project); reuse the project authentication header and call all 27 endpoints and the resumable SSE stream of /v1/agent-runtime/project/* via native fetch / Web Streams. |
| Java / Python / Go Server SDK (server-sdk/java.md, server-sdk/python.md, server-sdk/go.md) | Same as Node.js: hold the Project API Key on a controlled server, and connect to the project-level agent workbench with a standard HTTP/SSE client carrying X-Appwrite-Project, X-Appwrite-Key, and the business userId. |
| Web Client SDK (client-sdk/web.md) | The browser frontend must not hold the Project API Key and does not directly call /v1/agent-runtime/project/*; the frontend submits questions through endpoints wrapped by the business backend and consumes the SSE event stream forwarded by the backend. |
| Console SDK (console-sdk/nodejs.md) | Used to create projects and issue Project API Keys containing the agent-runtime.project Scope. |
Examples by language
Each card has switchable language tabs (synchronized across the full page); the cards correspond one-to-one with the entries in the "Usage workflow".
1. Initialize the project workbench and save the run configuration
Initialize the project agent workbench (POST /v1/agent-runtime/project), query available models (GET .../models), and configure qwen-plus, the system prompt, the context window budget, and enable Memory and enterprise knowledge base retrieval (kb_enterprise_support) via PATCH .../config. The project configuration endpoint does not require passing userId.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { Client } from 'agentbase-node-sdk';
const ENDPOINT = process.env.APPBASE_ENDPOINT ?? 'https://appbuild-sit.oceanbase.com/v1';
const PROJECT_ID = process.env.APPBASE_PROJECT_ID ?? 'enterprise-ai-hub-210';
const API_KEY = process.env.APPBASE_API_KEY!; // Requires the agent-runtime.project scope
// The Server SDK Client manages project coordinates uniformly while constructing project-level Runtime request headers
const client = new Client()
.setEndpoint(ENDPOINT)
.setProject(PROJECT_ID)
.setKey(API_KEY);
const headers = {
'X-Appwrite-Project': PROJECT_ID,
'X-Appwrite-Key': API_KEY,
'Content-Type': 'application/json',
};
// 1. Idempotently initialize the project Agent Runtime (repeated calls do not clear existing data)
await fetch(`${ENDPOINT}/agent-runtime/project`, {
method: 'POST',
headers,
body: JSON.stringify({}),
});
// 2. List models available to the current project (confirm qwen-plus has chat capability)
const modelsRes = await fetch(`${ENDPOINT}/agent-runtime/project/models`, { headers });
const { models } = await modelsRes.json();
// 3. Sparsely update the project agent workbench configuration
const configRes = await fetch(`${ENDPOINT}/agent-runtime/project/config`, {
method: 'PATCH',
headers,
body: JSON.stringify({
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,
}),
});
const config = await configRes.json();
console.log('Saved config_hash:', config.config_hash, 'models count:', models.length);import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
HttpClient http = HttpClient.newHttpClient();
String endpoint = "https://appbuild-sit.oceanbase.com/v1";
String projectId = "enterprise-ai-hub-210";
String apiKey = System.getenv("APPBASE_API_KEY"); // Requires the agent-runtime.project scope
// 1. Idempotently initialize the project Agent Runtime
HttpRequest initReq = HttpRequest.newBuilder(URI.create(endpoint + "/agent-runtime/project"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{}"))
.build();
http.send(initReq, HttpResponse.BodyHandlers.ofString());
// 2. Sparsely update project configuration (enable qwen-plus, Memory, and the enterprise knowledge base kb_enterprise_support)
String patchJson = """
{
"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
}
""";
HttpRequest configReq = HttpRequest.newBuilder(URI.create(endpoint + "/agent-runtime/project/config"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Content-Type", "application/json")
.method("PATCH", HttpRequest.BodyPublishers.ofString(patchJson))
.build();
HttpResponse<String> configRes = http.send(configReq, HttpResponse.BodyHandlers.ofString());
System.out.println(configRes.body());import os
import requests
ENDPOINT = os.environ.get('APPBASE_ENDPOINT', 'https://appbuild-sit.oceanbase.com/v1')
PROJECT_ID = os.environ.get('APPBASE_PROJECT_ID', 'enterprise-ai-hub-210')
API_KEY = os.environ['APPBASE_API_KEY'] # Requires the agent-runtime.project scope
HEADERS = {
'X-Appwrite-Project': PROJECT_ID,
'X-Appwrite-Key': API_KEY,
}
# 1. Idempotently initialize the project Agent Runtime
requests.post(f'{ENDPOINT}/agent-runtime/project', headers=HEADERS, json={}, timeout=15).raise_for_status()
# 2. Query the list of available models
models = requests.get(f'{ENDPOINT}/agent-runtime/project/models', headers=HEADERS, timeout=15).json()['models']
# 3. Sparsely update the project configuration
config = requests.patch(
f'{ENDPOINT}/agent-runtime/project/config',
headers=HEADERS,
json={
'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,
},
timeout=15,
).json()
print('config_hash:', config['config_hash'], 'models:', len(models))package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
)
func configureProjectRuntime() error {
endpoint := "https://appbuild-sit.oceanbase.com/v1"
projectID := "enterprise-ai-hub-210"
apiKey := os.Getenv("APPBASE_API_KEY")
// 1. Idempotently initialize the project Agent Runtime
initReq, _ := http.NewRequest(http.MethodPost, endpoint+"/agent-runtime/project", bytes.NewBufferString(`{}`))
initReq.Header.Set("X-Appwrite-Project", projectID)
initReq.Header.Set("X-Appwrite-Key", apiKey)
initReq.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(initReq)
if err != nil {
return err
}
_ = resp.Body.Close()
// 2. Sparsely update the project agent workbench configuration
patchBody := `{
"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
}`
cfgReq, _ := http.NewRequest(http.MethodPatch, endpoint+"/agent-runtime/project/config", bytes.NewBufferString(patchBody))
cfgReq.Header.Set("X-Appwrite-Project", projectID)
cfgReq.Header.Set("X-Appwrite-Key", apiKey)
cfgReq.Header.Set("Content-Type", "application/json")
cfgResp, err := http.DefaultClient.Do(cfgReq)
if err != nil {
return err
}
defer cfgResp.Body.Close()
raw, _ := io.ReadAll(cfgResp.Body)
fmt.Println(string(raw))
return nil
}# 1. Initialize the project agent workbench
curl -sS -X POST "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{}'
# 2. Update the project agent configuration
curl -sS -X PATCH "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/config" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"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
}'2. Bind project lexicons and the AI Gateway
Bind the synonym lexicon (lex_enterprise_synonyms) and stopword lexicon (lex_support_stopwords) via PUT /v1/agent-runtime/project/lexicons, and enable stopword blocking (stopIntercept: true); bind an active AI Gateway via PUT /v1/agent-runtime/project/gateway (gw_7194685489feb1e169548619).
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
// 1. Bind the project lexicon and enable stopword short-circuit interception
await fetch(`${ENDPOINT}/agent-runtime/project/lexicons`, {
method: 'PUT',
headers,
body: JSON.stringify({
enabled: true,
stopIntercept: true,
stopReply: '您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。',
bindings: [
{ lexiconId: 'lex_enterprise_synonyms', priority: 1 },
{ lexiconId: 'lex_support_stopwords', priority: 2 },
],
}),
});
// 2. Bind an AI Gateway in ACTIVE status within the same project
await fetch(`${ENDPOINT}/agent-runtime/project/gateway`, {
method: 'PUT',
headers,
body: JSON.stringify({
gateway_id: 'gw_7194685489feb1e169548619',
}),
});// 1. Bind project lexicons and enable stopword short-circuit blocking
String lexiconsJson = """
{
"enabled": true,
"stopIntercept": true,
"stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
"bindings": [
{"lexiconId": "lex_enterprise_synonyms", "priority": 1},
{"lexiconId": "lex_support_stopwords", "priority": 2}
]
}
""";
HttpRequest lexReq = HttpRequest.newBuilder(URI.create(endpoint + "/agent-runtime/project/lexicons"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Content-Type", "application/json")
.PUT(HttpRequest.BodyPublishers.ofString(lexiconsJson))
.build();
http.send(lexReq, HttpResponse.BodyHandlers.ofString());
// 2. Bind the AI Gateway
HttpRequest gwReq = HttpRequest.newBuilder(URI.create(endpoint + "/agent-runtime/project/gateway"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Content-Type", "application/json")
.PUT(HttpRequest.BodyPublishers.ofString("{\"gateway_id\":\"gw_7194685489feb1e169548619\"}"))
.build();
http.send(gwReq, HttpResponse.BodyHandlers.ofString());# 1. Bind project lexicons and enable stopword short-circuit blocking
requests.put(
f'{ENDPOINT}/agent-runtime/project/lexicons',
headers=HEADERS,
json={
'enabled': True,
'stopIntercept': True,
'stopReply': '您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。',
'bindings': [
{'lexiconId': 'lex_enterprise_synonyms', 'priority': 1},
{'lexiconId': 'lex_support_stopwords', 'priority': 2},
],
},
timeout=15,
).raise_for_status()
# 2. Bind the AI Gateway
requests.put(
f'{ENDPOINT}/agent-runtime/project/gateway',
headers=HEADERS,
json={'gateway_id': 'gw_7194685489feb1e169548619'},
timeout=15,
).raise_for_status()lexBody := `{
"enabled": true,
"stopIntercept": true,
"stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
"bindings": [
{"lexiconId": "lex_enterprise_synonyms", "priority": 1},
{"lexiconId": "lex_support_stopwords", "priority": 2}
]
}`
lexReq, _ := http.NewRequest(http.MethodPut, endpoint+"/agent-runtime/project/lexicons", bytes.NewBufferString(lexBody))
lexReq.Header.Set("X-Appwrite-Project", projectID)
lexReq.Header.Set("X-Appwrite-Key", apiKey)
lexReq.Header.Set("Content-Type", "application/json")
_, _ = http.DefaultClient.Do(lexReq)
gwReq, _ := http.NewRequest(http.MethodPut, endpoint+"/agent-runtime/project/gateway",
bytes.NewBufferString(`{"gateway_id":"gw_7194685489feb1e169548619"}`))
gwReq.Header.Set("X-Appwrite-Project", projectID)
gwReq.Header.Set("X-Appwrite-Key", apiKey)
gwReq.Header.Set("Content-Type", "application/json")
_, _ = http.DefaultClient.Do(gwReq)# 1. Bind project lexicons and the stopword blocking policy
curl -sS -X PUT "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/lexicons" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"enabled": true,
"stopIntercept": true,
"stopReply": "您好,您咨询的内容涉及企业受限或违规词条,当前请求已被拦截,请联系人工客服处理。",
"bindings": [
{"lexiconId": "lex_enterprise_synonyms", "priority": 1},
{"lexiconId": "lex_support_stopwords", "priority": 2}
]
}'
# 2. Bind the AI Gateway
curl -sS -X PUT "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/gateway" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"gateway_id":"gw_7194685489feb1e169548619"}'3. Upload and manage Skill packages
Upload .zip / .tar.gz / .tgz Skill packages containing SKILL.md to /v1/agent-runtime/project/skills via multipart/form-data, with support for list queries, full replacement, and deletion.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { readFile } from 'node:fs/promises';
const zipBytes = await readFile('./skills/enterprise-order-sop.zip');
const form = new FormData();
form.append('file', new Blob([zipBytes], { type: 'application/zip' }), 'enterprise-order-sop.zip');
// 1. Upload the Skill package (note: do not set Content-Type manually; FormData generates the multipart boundary automatically)
const uploadRes = await fetch(`${ENDPOINT}/agent-runtime/project/skills`, {
method: 'POST',
headers: {
'X-Appwrite-Project': PROJECT_ID,
'X-Appwrite-Key': API_KEY,
},
body: form,
});
const skill = await uploadRes.json();
// 2. List the project's uploaded Skill packages and quotas (skill_count / skill_limit)
const listRes = await fetch(`${ENDPOINT}/agent-runtime/project/skills`, {
headers: { 'X-Appwrite-Project': PROJECT_ID, 'X-Appwrite-Key': API_KEY },
});
const skillList = await listRes.json();
console.log('Uploaded skill:', skill.skill_id, 'Quota:', skillList.skill_count, '/', skillList.skill_limit);// Read the project's uploaded Skill list and capacity quota (upload and replace use the multipart/form-data field file)
HttpRequest listSkillsReq = HttpRequest.newBuilder(URI.create(endpoint + "/agent-runtime/project/skills"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.GET()
.build();
HttpResponse<String> skillsRes = http.send(listSkillsReq, HttpResponse.BodyHandlers.ofString());
System.out.println(skillsRes.body());# 1. Upload the Skill archive (multipart/form-data field name fixed as file)
with open('./skills/enterprise-order-sop.zip', 'rb') as fp:
skill = requests.post(
f'{ENDPOINT}/agent-runtime/project/skills',
headers=HEADERS,
files={'file': ('enterprise-order-sop.zip', fp, 'application/zip')},
timeout=30,
).json()
# 2. Query the Skill list and quotas
skill_list = requests.get(f'{ENDPOINT}/agent-runtime/project/skills', headers=HEADERS, timeout=15).json()
print('skill_id:', skill['skill_id'], 'count:', skill_list['skill_count'])import (
"mime/multipart"
"os"
)
func uploadSkillPackage(zipPath string) error {
file, err := os.Open(zipPath)
if err != nil {
return err
}
defer file.Close()
var body bytes.Buffer
writer := multipart.NewWriter(&body)
part, _ := writer.CreateFormFile("file", "enterprise-order-sop.zip")
_, _ = io.Copy(part, file)
_ = writer.Close()
req, _ := http.NewRequest(http.MethodPost, endpoint+"/agent-runtime/project/skills", &body)
req.Header.Set("X-Appwrite-Project", projectID)
req.Header.Set("X-Appwrite-Key", apiKey)
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}# Upload a Skill package (POST /v1/agent-runtime/project/skills)
curl -sS -X POST "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/skills" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-F "file=@./skills/enterprise-order-sop.zip"
# List: GET .../skills; single item: GET .../skills/{skillId}; replace: PUT .../skills/{skillId}; delete: DELETE .../skills/{skillId}4. Create sessions for business users and submit Runs idempotently
Create a session for business user user_zhangwei_001 (POST /v1/agent-runtime/project/threads, with userId in the JSON Body), and asynchronously submit a Run with Idempotency-Key in that session (POST /v1/agent-runtime/project/runs, returning 202 Accepted).
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
const userId = 'user_zhangwei_001';
// 1. Create a session for the business user (POST request: userId goes in the JSON Body)
const threadRes = await fetch(`${ENDPOINT}/agent-runtime/project/threads`, {
method: 'POST',
headers,
body: JSON.stringify({ userId }),
});
const thread = await threadRes.json(); // { thread_id, title, status: 'ACTIVE' }
// 2. Asynchronously submit a Run with an Idempotency-Key (returns 202 Accepted and run_id)
const runRes = await fetch(`${ENDPOINT}/agent-runtime/project/runs`, {
method: 'POST',
headers: {
...headers,
'Idempotency-Key': 'req_zhangwei_20261022_001',
},
body: JSON.stringify({
userId,
thread_id: thread.thread_id,
user_message: '请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。',
}),
});
const run = await runRes.json(); // { run_id, status: 'QUEUED', created_at }
console.log('Created thread:', thread.thread_id, 'Run queued:', run.run_id);String userId = "user_zhangwei_001";
// 1. Create a session (userId is required in the JSON Body)
HttpRequest createThreadReq = HttpRequest.newBuilder(URI.create(endpoint + "/agent-runtime/project/threads"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"userId\":\"" + userId + "\"}"))
.build();
HttpResponse<String> threadRes = http.send(createThreadReq, HttpResponse.BodyHandlers.ofString());
// 2. Submit a Run (with an Idempotency-Key, returns 202 Accepted)
String createRunBody = """
{
"userId": "user_zhangwei_001",
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"user_message": "请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。"
}
""";
HttpRequest createRunReq = HttpRequest.newBuilder(URI.create(endpoint + "/agent-runtime/project/runs"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Content-Type", "application/json")
.header("Idempotency-Key", "req_zhangwei_20261022_001")
.POST(HttpRequest.BodyPublishers.ofString(createRunBody))
.build();
HttpResponse<String> runRes = http.send(createRunReq, HttpResponse.BodyHandlers.ofString());
System.out.println("HTTP " + runRes.statusCode() + ": " + runRes.body());user_id = 'user_zhangwei_001'
# 1. Create a session (POST request: userId in the JSON Body)
thread = requests.post(
f'{ENDPOINT}/agent-runtime/project/threads',
headers=HEADERS,
json={'userId': user_id},
timeout=15,
).json()
# 2. Submit a Run (with Idempotency-Key; first call returns 202 Accepted, replaying the same request returns 200 OK)
run_resp = requests.post(
f'{ENDPOINT}/agent-runtime/project/runs',
headers={**HEADERS, 'Idempotency-Key': 'req_zhangwei_20261022_001'},
json={
'userId': user_id,
'thread_id': thread['thread_id'],
'user_message': '请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。',
},
timeout=15,
)
run_resp.raise_for_status()
run = run_resp.json()
print('thread_id:', thread['thread_id'], 'run_id:', run['run_id'], 'status:', run['status'])// 1. Create a session (POST request passes userId in the JSON Body)
threadReq, _ := http.NewRequest(http.MethodPost, endpoint+"/agent-runtime/project/threads",
bytes.NewBufferString(`{"userId":"user_zhangwei_001"}`))
threadReq.Header.Set("X-Appwrite-Project", projectID)
threadReq.Header.Set("X-Appwrite-Key", apiKey)
threadReq.Header.Set("Content-Type", "application/json")
threadResp, _ := http.DefaultClient.Do(threadReq)
defer threadResp.Body.Close()
// 2. Submit a Run (with an Idempotency-Key)
runBody := `{
"userId": "user_zhangwei_001",
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"user_message": "请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。"
}`
runReq, _ := http.NewRequest(http.MethodPost, endpoint+"/agent-runtime/project/runs", bytes.NewBufferString(runBody))
runReq.Header.Set("X-Appwrite-Project", projectID)
runReq.Header.Set("X-Appwrite-Key", apiKey)
runReq.Header.Set("Content-Type", "application/json")
runReq.Header.Set("Idempotency-Key", "req_zhangwei_20261022_001")
runResp, _ := http.DefaultClient.Do(runReq)
defer runResp.Body.Close()# 1. Create a session (POST body requires userId)
curl -sS -X POST "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/threads" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"userId":"user_zhangwei_001"}'
# 2. Submit a Run (returns 202 Accepted and a run_id)
curl -sS -X POST "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/runs" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Idempotency-Key: req_zhangwei_20261022_001" \
-H "Content-Type: application/json" \
-d '{
"userId": "user_zhangwei_001",
"thread_id": "th_01ja9x8k2m4n6p8q0r2s4t6v8w",
"user_message": "请帮我查询订单 ORD-20261022-889 的发货状态,并说明跨月退货如何处理增值税专用发票。"
}'5. Subscribe to the resumable SSE event stream and read the final message
Send a GET to /v1/agent-runtime/project/runs/{runId}/events?userId=... (GET request with userId in the Query), parse AG-UI events in real time and save the latest outer frame id; on disconnection, resume the same Run by passing Last-Event-ID; after receiving the terminal event, read the persisted messages via GET .../messages.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
async function consumeRunEvents(runId: string, userId: string, lastEventId?: string) {
const eventHeaders: Record<string, string> = {
'X-Appwrite-Project': PROJECT_ID,
'X-Appwrite-Key': API_KEY,
Accept: 'text/event-stream',
};
if (lastEventId) {
eventHeaders['Last-Event-ID'] = lastEventId; // On reconnect after disconnect, resume from the breakpoint
}
const res = await fetch(
`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(runId)}/events?userId=${encodeURIComponent(userId)}`,
{ headers: eventHeaders }
);
if (res.status === 409) {
// Cursor expired (stream_cursor_expired): first read the persisted Run state and messages; do not create a duplicate Run
console.warn('SSE cursor expired, falling back to persisted messages');
return;
}
const reader = res.body!.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
let currentId = lastEventId;
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
const frames = buffer.split('\n\n');
buffer = frames.pop() ?? '';
for (const frame of frames) {
for (const line of frame.split('\n')) {
if (line.startsWith('id: ')) currentId = line.slice(4).trim();
if (line.startsWith('data: ')) {
const event = JSON.parse(line.slice(6));
if (event.type === 'TEXT_MESSAGE_CONTENT') {
process.stdout.write(event.delta);
}
}
}
}
}
// After final state, read persisted messages using the message_seq cursor
const msgRes = await fetch(
`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(runId)}/messages?userId=${encodeURIComponent(userId)}&after=0&limit=100`,
{ headers: { 'X-Appwrite-Project': PROJECT_ID, 'X-Appwrite-Key': API_KEY } }
);
return { lastEventId: currentId, messages: await msgRes.json() };
}String runId = "run_01ja9x90a1b2c3d4e5f6g7h8j9";
HttpRequest sseReq = HttpRequest.newBuilder(
URI.create(endpoint + "/agent-runtime/project/runs/" + runId + "/events?userId=" + userId))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Accept", "text/event-stream")
// On reconnection after disconnect, append: .header("Last-Event-ID", lastEventId)
.GET()
.build();
HttpResponse<java.util.stream.Stream<String>> streamRes =
http.send(sseReq, HttpResponse.BodyHandlers.ofLines());
streamRes.body().forEach(line -> {
if (line.startsWith("data: ")) {
System.out.println("Event JSON: " + line.substring(6));
}
});
// Read persisted messages after final state
HttpRequest msgReq = HttpRequest.newBuilder(
URI.create(endpoint + "/agent-runtime/project/runs/" + runId + "/messages?userId=" + userId + "&after=0&limit=100"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.GET()
.build();
HttpResponse<String> msgRes = http.send(msgReq, HttpResponse.BodyHandlers.ofString());
System.out.println(msgRes.body());import json
def stream_run_and_fetch_messages(run_id: str, user_id: str, last_event_id: str | None = None):
sse_headers = {**HEADERS, 'Accept': 'text/event-stream'}
if last_event_id:
sse_headers['Last-Event-ID'] = last_event_id
with requests.get(
f'{ENDPOINT}/agent-runtime/project/runs/{run_id}/events',
params={'userId': user_id},
headers=sse_headers,
stream=True,
timeout=120,
) as resp:
if resp.status_code == 409:
# stream_cursor_expired: read the persisted state and messages first
return requests.get(
f'{ENDPOINT}/agent-runtime/project/runs/{run_id}/messages',
params={'userId': user_id, 'after': 0, 'limit': 100},
headers=HEADERS,
timeout=15,
).json()
resp.raise_for_status()
for raw_line in resp.iter_lines(decode_unicode=True):
if not raw_line:
continue
if raw_line.startswith('id: '):
last_event_id = raw_line[4:].strip()
elif raw_line.startswith('data: '):
event = json.loads(raw_line[6:])
if event.get('type') == 'TEXT_MESSAGE_CONTENT':
print(event.get('delta', ''), end='', flush=True)
return requests.get(
f'{ENDPOINT}/agent-runtime/project/runs/{run_id}/messages',
params={'userId': user_id, 'after': 0, 'limit': 100},
headers=HEADERS,
timeout=15,
).json()import "bufio"
func streamRunEvents(runID, userID, lastEventID string) error {
url := fmt.Sprintf("%s/agent-runtime/project/runs/%s/events?userId=%s", endpoint, runID, userID)
req, _ := http.NewRequest(http.MethodGet, url, nil)
req.Header.Set("X-Appwrite-Project", projectID)
req.Header.Set("X-Appwrite-Key", apiKey)
req.Header.Set("Accept", "text/event-stream")
if lastEventID != "" {
req.Header.Set("Last-Event-ID", lastEventID)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
line := scanner.Text()
if len(line) > 6 && line[:6] == "data: " {
fmt.Println(line[6:])
}
}
return scanner.Err()
}# 1. Subscribe to the SSE event stream (add -H 'Last-Event-ID: 21' on reconnect)
curl -sS -N --get "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/runs/$RUN_ID/events" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Accept: text/event-stream" \
--data-urlencode "userId=user_zhangwei_001"
# 2. Read persisted messages after the final state (after is the message_seq number within the session)
curl -sS --get "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/runs/$RUN_ID/messages" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
--data-urlencode "userId=user_zhangwei_001" \
--data-urlencode "after=0" \
--data-urlencode "limit=100"6. Handle Client Tool returns, explicit cancellation, and usage auditing
When the Run enters WAITING_CLIENT_TOOL, call POST /v1/agent-runtime/project/runs/{runId}/tool-messages to return the tool result and restore the same Run; call POST .../cancel when a task needs to be terminated; and read per-step Token consumption and context compaction events via GET .../model-invocations and GET .../context-compactions.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
// 1. Return the client tool execution result (content must be a JSON-serialized string; an error field can be passed on failure)
await fetch(`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(run.run_id)}/tool-messages`, {
method: 'POST',
headers,
body: JSON.stringify({
userId,
id: 'tmsg_01ja9x9c4d5e6f7g8h9j0k1l2m',
role: 'tool',
toolCallId: 'call_order_lookup_001',
content: JSON.stringify({ order_id: 'ORD-20261022-889', status: 'shipped', carrier: 'SF-Express' }),
}),
});
// 2. Explicitly cancel a running Run (disconnecting the SSE stream does not cancel the Run)
await fetch(`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(run.run_id)}/cancel`, {
method: 'POST',
headers,
body: JSON.stringify({ userId }),
});
// 3. Query the model call Token consumption and latency records for a single Run (GET request: userId in the Query)
const invocationsRes = await fetch(
`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(run.run_id)}/model-invocations?userId=${encodeURIComponent(userId)}`,
{ headers: { 'X-Appwrite-Project': PROJECT_ID, 'X-Appwrite-Key': API_KEY } }
);
const invocations = await invocationsRes.json();
// 4. Query a session's automatic context compaction records
const compactionsRes = await fetch(
`${ENDPOINT}/agent-runtime/project/threads/${encodeURIComponent(thread.thread_id)}/context-compactions?userId=${encodeURIComponent(userId)}`,
{ headers: { 'X-Appwrite-Project': PROJECT_ID, 'X-Appwrite-Key': API_KEY } }
);
const compactions = await compactionsRes.json();
console.log('Model steps:', invocations.items.length, 'Compactions:', compactions.items.length);// 1. Return the Client Tool result (POST body includes userId, id, role="tool", toolCallId, JSON string content)
String toolMsgJson = """
{
"userId": "user_zhangwei_001",
"id": "tmsg_01ja9x9c4d5e6f7g8h9j0k1l2m",
"role": "tool",
"toolCallId": "call_order_lookup_001",
"content": "{\\"order_id\\":\\"ORD-20261022-889\\",\\"status\\":\\"shipped\\"}"
}
""";
HttpRequest toolMsgReq = HttpRequest.newBuilder(
URI.create(endpoint + "/agent-runtime/project/runs/" + runId + "/tool-messages"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(toolMsgJson))
.build();
http.send(toolMsgReq, HttpResponse.BodyHandlers.ofString());
// 2. Explicitly cancel a Run
HttpRequest cancelReq = HttpRequest.newBuilder(
URI.create(endpoint + "/agent-runtime/project/runs/" + runId + "/cancel"))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"userId\":\"" + userId + "\"}"))
.build();
http.send(cancelReq, HttpResponse.BodyHandlers.ofString());
// 3. Query model call records
HttpRequest invReq = HttpRequest.newBuilder(
URI.create(endpoint + "/agent-runtime/project/runs/" + runId + "/model-invocations?userId=" + userId))
.header("X-Appwrite-Project", projectId)
.header("X-Appwrite-Key", apiKey)
.GET()
.build();
http.send(invReq, HttpResponse.BodyHandlers.ofString());# 1. Return the client tool result (resumes the same Run in WAITING_CLIENT_TOOL)
requests.post(
f'{ENDPOINT}/agent-runtime/project/runs/{run["run_id"]}/tool-messages',
headers=HEADERS,
json={
'userId': user_id,
'id': 'tmsg_01ja9x9c4d5e6f7g8h9j0k1l2m',
'role': 'tool',
'toolCallId': 'call_order_lookup_001',
'content': '{"order_id":"ORD-20261022-889","status":"shipped"}',
},
timeout=15,
).raise_for_status()
# 2. Explicitly cancel a Run
requests.post(
f'{ENDPOINT}/agent-runtime/project/runs/{run["run_id"]}/cancel',
headers=HEADERS,
json={'userId': user_id},
timeout=15,
)
# 3. Read model invocation latency and token consumption records
invocations = requests.get(
f'{ENDPOINT}/agent-runtime/project/runs/{run["run_id"]}/model-invocations',
params={'userId': user_id},
headers=HEADERS,
timeout=15,
).json()
print('Invocations:', len(invocations['items']))// 1. Return the client tool result
toolBody := `{
"userId": "user_zhangwei_001",
"id": "tmsg_01ja9x9c4d5e6f7g8h9j0k1l2m",
"role": "tool",
"toolCallId": "call_order_lookup_001",
"content": "{\"order_id\":\"ORD-20261022-889\",\"status\":\"shipped\"}"
}`
toolReq, _ := http.NewRequest(http.MethodPost,
endpoint+"/agent-runtime/project/runs/"+runID+"/tool-messages", bytes.NewBufferString(toolBody))
toolReq.Header.Set("X-Appwrite-Project", projectID)
toolReq.Header.Set("X-Appwrite-Key", apiKey)
toolReq.Header.Set("Content-Type", "application/json")
_, _ = http.DefaultClient.Do(toolReq)
// 2. Explicitly cancel a Run
cancelReq, _ := http.NewRequest(http.MethodPost,
endpoint+"/agent-runtime/project/runs/"+runID+"/cancel", bytes.NewBufferString(`{"userId":"user_zhangwei_001"}`))
cancelReq.Header.Set("X-Appwrite-Project", projectID)
cancelReq.Header.Set("X-Appwrite-Key", apiKey)
cancelReq.Header.Set("Content-Type", "application/json")
_, _ = http.DefaultClient.Do(cancelReq)# 1. Return the client tool result
curl -sS -X POST "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/runs/$RUN_ID/tool-messages" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"userId": "user_zhangwei_001",
"id": "tmsg_01ja9x9c4d5e6f7g8h9j0k1l2m",
"role": "tool",
"toolCallId": "call_order_lookup_001",
"content": "{\"order_id\":\"ORD-20261022-889\",\"status\":\"shipped\"}"
}'
# 2. Explicitly cancel a Run
curl -sS -X POST "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/runs/$RUN_ID/cancel" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"userId":"user_zhangwei_001"}'
# 3. Query model invocation records and context compaction records
curl -sS --get "https://appbuild-sit.oceanbase.com/v1/agent-runtime/project/runs/$RUN_ID/model-invocations" \
-H "X-Appwrite-Project: enterprise-ai-hub-210" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
--data-urlencode "userId=user_zhangwei_001"Example Guide
Complete example sets by language: examples/javascript.md, examples/java.md, examples/python.md, examples/go.md.
Server SDK initialization and error models by language: server-sdk/nodejs.md, server-sdk/java.md, server-sdk/python.md, server-sdk/go.md.
Related REST API reference and product manual: apis/zh-CN/agent-runtime.md, Agent Workbench Product Manual.