Agent Runtime(项目级智能体工作台)
这是什么 / 何时用
Agent Runtime(智能体工作台)是 Agentbase 提供的项目级托管智能体运行引擎(/v1/agent-runtime/project/*)。业务后端无需自行在应用层维护复杂的“Prompt 组装 → 模型推理 → 工具调用 → 上下文压缩 → 流式推送”ReAct 循环:只需在当前 Project 中配置对话模型(如 qwen-plus)、系统提示词及所需能力开关(企业知识库检索 Knowledge Search、长期记忆 Memory 或托管上下文 PowerContext、项目词库 Lexicons、AI Gateway 工具与 Skill 技能包),即可通过统一的 Project API Key 为不同业务终端用户(userId)创建连续会话(Thread)、异步提交任务(Run)、订阅支持断线重连的 AG-UI 流式事件(SSE),并在客户端工具(Client Tool)场景下暂停等待回传后继续同一 Run。
典型适用场景:
多租户企业智能客服与知识助手:后端持单个 Project API Key,通过传入业务系统自身的
userId(如user_zhangwei_001、user_lina_002)隔离不同终端用户的会话历史与长期记忆,同时共享项目级知识库(kb_enterprise_support)与合规词库(lex_enterprise_synonyms、lex_support_stopwords)。业务工具与前端交互协同:通过绑定同项目下的 AI Gateway(
gw_7194685489feb1e169548619),让智能体在推理过程中自动调用受控 MCP / HTTP 服务端工具,或触发CLIENT工具交由应用端执行并回传结果。高可靠长任务与移动端弱网恢复:Run 创建(
202 Accepted)与 SSE 事件流(GET .../events)解耦;客户端网络闪断不会取消后台 Run,重连时携带Last-Event-ID即可从断点继续接收增量事件。
前置
| 配置项 / 依赖 | 规范要求与 SIT 演示坐标 |
|---|---|
| API Endpoint | https://appbuild-sit.oceanbase.com/v1(项目级智能体工作台路径前缀:/v1/agent-runtime/project) |
| 所属组织与项目 | 组织:Agentbase 企业智能中台(69c6d1aa00062e6bb60);项目:企业智能客服与知识中台(Project ID:enterprise-ai-hub-210,Shared V2 存储模式) |
| 认证头与最小 Scope | X-Appwrite-Project: enterprise-ai-hub-210 + X-Appwrite-Key: <APPBASE_API_KEY>;API Key 必须包含 agent-runtime.project Scope(涵盖配置管理与会话运行全套 27 个端点) |
| SDK 版本基线 | 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) |
多用户隔离参数 userId | 1–128 位 ASCII 字母、数字或下划线(^[A-Za-z0-9_]{1,128}$),不区分大小写(服务端统一归一化为小写),system 为保留字。14 个项目共享配置接口不传 userId;13 个用户级 Thread/Run 接口必填 userId(POST 放 JSON Body,GET / DELETE 放 URL Query) |
| 关联项目资源(按需) | 对话模型:qwen-plus / qwen-turbo(Provider:dashscope-prod);向量模型:text-embedding-v3(1024 维);知识库:kb_enterprise_support;词库:lex_enterprise_synonyms、lex_support_stopwords;AI Gateway:gw_7194685489feb1e169548619(需为 Shared V2 项目且 Gateway 状态为 ACTIVE) |
使用骨架
初始化项目工作台并保存运行配置:查询
/v1/agent-runtime/project状态 → 执行幂等初始化POST /v1/agent-runtime/project→ 查询可用模型GET .../models→ 通过PATCH .../config配置qwen-plus、系统提示词、上下文预算及 Memory / Knowledge Search 开关。绑定项目词库与 AI Gateway:通过
PUT .../lexicons挂载企业同义词库与停用词库(配置stopIntercept: true与合规拦截话术stopReply);通过PUT .../gateway绑定活跃的 AI Gateway。上传与管理 Skill 技能包:通过
multipart/form-data上传含SKILL.md的.zip/.tar.gz/.tgz技能包至/v1/agent-runtime/project/skills,供智能体按需读取标准操作流程。为业务用户创建会话并幂等提交 Run:携带业务用户
userId(如user_zhangwei_001)调用POST .../threads创建会话 → 携带Idempotency-Key调用POST .../runs提交问题(返回202 Accepted及run_id)。订阅可恢复 SSE 事件流与读取最终消息:调用
GET .../runs/{runId}/events?userId=...实时消费TEXT_MESSAGE_CONTENT、TOOL_CALL_*等 AG-UI 事件并记录最新帧id;若网络断开则携带Last-Event-ID续连同一 Run;收到RUN_FINISHED后调用GET .../runs/{runId}/messages读取持久化回答与知识引用。处理 Client Tool 回传、显式取消与用量审计:当 Run 进入
WAITING_CLIENT_TOOL时,执行本地获准工具并通过POST .../runs/{runId}/tool-messages回传结果恢复同一 Run;需要终止任务时显式调用POST .../runs/{runId}/cancel;通过GET .../model-invocations与GET .../context-compactions审计 Token 消耗与上下文精简记录。
关键参数与返回
| 接口 / 阶段 | 关键输入参数与位置 | 返回结构核心字段与处理要点 |
|---|---|---|
更新配置 PATCH /project/config | Body(无 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(与 Memory 互斥)、knowledge_search_enabled、knowledge_base_ids(最多 100 个 ID)、memory_embedding_model_id、memory_embedding_dimensions。 | 返回完整 Config 对象与只读 config_hash。Run 受理时冻结当次配置快照,修改配置不影响在途 Run。 |
绑定词库 PUT /project/lexicons | Body(无 userId):bindings: [{ lexiconId, priority }](最多 100 项)、enabled: boolean、stopIntercept: boolean、stopReply: string(最长 4096 字符)。 | 返回生效的 LexiconBindings。开启 stopIntercept 后,用户输入命中 stop 词条将短路终止 Run 并直接返回 stopReply。 |
上传 Skill POST /project/skills | multipart/form-data(无 userId):二进制文件字段 file(.zip / .tar.gz / .tgz,<= 10 MiB,根目录含 SKILL.md)。 | 201 Created,返回 skill_id、name、description、front_matter、content_hash。列表接口另返回 skill_count 与 skill_limit。 |
创建会话 POST /project/threads | Body:{ "userId": "user_zhangwei_001" }。 | 201 Created,返回 thread_id、title(初始 null)、status: "ACTIVE"。后续所有对该 Thread 的操作必须使用相同 userId。 |
创建 Run POST /project/runs | Header:Idempotency-Key(1–128 bytes);Body:{ "userId", "thread_id", "user_message" }。 | 首次受理返回 202 Accepted(run_id、status: "QUEUED"、created_at);同幂等键同请求体重放返回 200 OK 且 idempotent_replay: true。 |
SSE 事件流 GET /project/runs/{runId}/events | Query:userId;Header:Accept: text/event-stream、重连时带 Last-Event-ID。 | 每帧含外层 id、event 与 data(JSON,含 type、messageId/toolCallId、delta 等)。外层 id 用于 Last-Event-ID 续连,不可与消息序号 message_seq 混用。 |
回传工具结果 POST /project/runs/{runId}/tool-messages | Body:{ "userId", "id", "role": "tool", "toolCallId", "content", "error" }(error 可选),其中 content 必须是 JSON 序列化后的字符串(如 "{\"status\":\"shipped\"}")。 | 202 Accepted,返回 Run(状态回到 QUEUED 继续执行同一 Run,不会新建第二个 Run)。 |
消息分页 GET .../messages | Query:userId、after(默认 0,传入上一页最后一条的 message_seq)、limit(默认 100,1–1000)。 | 返回 Message[] 数组(message_id、message_seq、message_type、payload、tool_call_id、trace_id)。 |
错误与边界
用户隔离与传参位置铁律:
userId只能在受控后端由真实登录态映射生成,严禁将 Project API Key 下发给前端并让前端自填userId。POST接口userId放 JSON Body,GET/DELETE接口userId放 URL Query;遗漏、双传、含连字符-或使用保留字system均返回400 general_argument_invalid。跨用户访问其他userId的 Thread/Run 统一返回404 NOT_FOUND。单会话并发互斥(
409 THREAD_BUSY):同一thread_id同一时刻只允许存在一个未结束的 Run(含WAITING_CLIENT_TOOL状态)。若需发起新对话,必须先完成当前客户端工具回传,或显式调用POST .../cancel并等待状态收敛为CANCELLED。SSE 断开不等于取消,游标过期需先读持久化事实:关闭 SSE 连接不会停止后台 Run。当断线时间过长导致
Last-Event-ID早于 Redis 保留窗口(默认 Run deadline 后 30 分钟或超过 8192 条事件)时,接口返回409 stream_cursor_expired(含earliest_event_id与latest_event_id)——此时应先调用GET .../runs/{runId}与GET .../messages恢复持久化状态与消息,切勿盲目重新创建 Run。Memory 与 PowerContext 互斥:在同一份项目配置中,
memory_enabled与powercontext_enabled不能同时为true;启用任一能力前必须先完成对应项目服务的初始化,而knowledge_search_enabled可与其中任意一种自由组合。外部工具副作用幂等保护:当 Run 返回
TOOL_RESULT_UNKNOWN或发生网络超时重连时,Runtime 不替外部业务系统回滚写操作;客户端按toolCallId去重,有副作用的业务操作必须先查询业务真实状态再决定是否重试。
SDK 类别差异
| SDK 类别与语言面 | 项目级智能体工作台(/v1/agent-runtime/project/*)接入方式 |
|---|---|
| Node.js Server SDK(server-sdk/nodejs.md) | 初始化 agentbase-node-sdk@2.10.0 的 Client(设置 Endpoint、Project ID enterprise-ai-hub-210 与含 agent-runtime.project 的 API Key),复用项目认证头通过原生 fetch / Web Streams 调用 /v1/agent-runtime/project/* 全量 27 个端点与可恢复 SSE 流。 |
| Java / Python / Go Server SDK(server-sdk/java.md、server-sdk/python.md、server-sdk/go.md) | 与 Node.js 相同,在受控服务端持有 Project API Key,通过标准 HTTP/SSE 客户端携带 X-Appwrite-Project、X-Appwrite-Key 与业务 userId 接入项目级智能体工作台。 |
| Web Client SDK(client-sdk/web.md) | 浏览器前端不得持有 Project API Key,也不直接调用 /v1/agent-runtime/project/*;前端通过业务后端封装的接口发起提问并消费后端转发的 SSE 事件流。 |
| Console SDK(console-sdk/nodejs.md) | 用于创建项目与签发包含 agent-runtime.project Scope 的 Project API Key。 |
各语言调用示例
每个卡片可切换语言页签(全页同步),卡片与「使用骨架」逐条对应。
1. 初始化项目工作台并保存运行配置
初始化项目智能体工作台(POST /v1/agent-runtime/project),查询可用模型(GET .../models),并通过 PATCH .../config 配置 qwen-plus、系统提示词、上下文窗口预算以及启用 Memory 与企业知识库检索(kb_enterprise_support)。项目配置接口无需传入 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!; // 具备 agent-runtime.project Scope
// Server SDK Client 统一管理项目坐标,同时构造项目级 Runtime 请求头
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. 幂等初始化项目 Agent Runtime(重复调用不会清空已有数据)
await fetch(`${ENDPOINT}/agent-runtime/project`, {
method: 'POST',
headers,
body: JSON.stringify({}),
});
// 2. 列出当前项目可用模型(确认 qwen-plus 具备 chat 能力)
const modelsRes = await fetch(`${ENDPOINT}/agent-runtime/project/models`, { headers });
const { models } = await modelsRes.json();
// 3. 稀疏更新项目智能体工作台配置
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"); // 具备 agent-runtime.project Scope
// 1. 幂等初始化项目 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. 稀疏更新项目配置(启用 qwen-plus、Memory 与企业知识库 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'] # 具备 agent-runtime.project Scope
HEADERS = {
'X-Appwrite-Project': PROJECT_ID,
'X-Appwrite-Key': API_KEY,
}
# 1. 幂等初始化项目 Agent Runtime
requests.post(f'{ENDPOINT}/agent-runtime/project', headers=HEADERS, json={}, timeout=15).raise_for_status()
# 2. 查询可用模型列表
models = requests.get(f'{ENDPOINT}/agent-runtime/project/models', headers=HEADERS, timeout=15).json()['models']
# 3. 稀疏更新项目配置
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. 幂等初始化项目 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. 稀疏更新项目智能体工作台配置
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. 初始化项目智能体工作台
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. 更新项目智能体配置
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. 绑定项目词库与 AI Gateway
通过 PUT /v1/agent-runtime/project/lexicons 绑定同义词词库(lex_enterprise_synonyms)与停用词词库(lex_support_stopwords),开启停用词阻断(stopIntercept: true);通过 PUT /v1/agent-runtime/project/gateway 绑定活跃的 AI Gateway(gw_7194685489feb1e169548619)。
- Node.js(Server)
- Java
- Python
- Go
- REST(curl)
// 1. 绑定项目词库并启用停用词短路拦截
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. 绑定同项目下状态为 ACTIVE 的 AI Gateway
await fetch(`${ENDPOINT}/agent-runtime/project/gateway`, {
method: 'PUT',
headers,
body: JSON.stringify({
gateway_id: 'gw_7194685489feb1e169548619',
}),
});// 1. 绑定项目词库并启用停用词短路阻断
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. 绑定 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. 绑定项目词库并启用停用词短路阻断
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. 绑定 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. 绑定项目词库与停用词阻断策略
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. 绑定 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. 上传与管理 Skill 技能包
通过 multipart/form-data 上传包含 SKILL.md 的 .zip / .tar.gz / .tgz 技能包至 /v1/agent-runtime/project/skills,并支持列表查询、全量替换与删除。
- 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. 上传 Skill 包(注意:不要手动设置 Content-Type,由 FormData 自动生成 multipart boundary)
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. 列出项目已上传的 Skill 包及配额(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);// 读取项目已上传的 Skill 列表与容量配额(上传与替换使用 multipart/form-data 字段 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. 上传 Skill 压缩包(multipart/form-data 字段名固定为 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. 查询 Skill 列表与配额
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
}# 上传 Skill 包(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"
# 列表:GET .../skills;单项:GET .../skills/{skillId};替换:PUT .../skills/{skillId};删除:DELETE .../skills/{skillId}4. 为业务用户创建会话并幂等提交 Run
为业务用户 user_zhangwei_001 创建会话(POST /v1/agent-runtime/project/threads,userId 放 JSON Body),并在该会话下携带 Idempotency-Key 异步提交 Run(POST /v1/agent-runtime/project/runs,返回 202 Accepted)。
- Node.js(Server)
- Java
- Python
- Go
- REST(curl)
const userId = 'user_zhangwei_001';
// 1. 为业务用户创建会话(POST 请求:userId 放在 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. 携带 Idempotency-Key 异步提交 Run(返回 202 Accepted 与 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. 创建会话(userId 在 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. 提交 Run(携带 Idempotency-Key,返回 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. 创建会话(POST 请求:userId 放在 JSON Body)
thread = requests.post(
f'{ENDPOINT}/agent-runtime/project/threads',
headers=HEADERS,
json={'userId': user_id},
timeout=15,
).json()
# 2. 提交 Run(携带 Idempotency-Key,首次返回 202 Accepted,同请求重放返回 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. 创建会话(POST 请求在 JSON Body 中传 userId)
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. 提交 Run(携带 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. 创建会话(POST 正文必填 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. 提交 Run(返回 202 Accepted 与 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. 订阅可恢复 SSE 事件流与读取最终消息
对 /v1/agent-runtime/project/runs/{runId}/events?userId=... 发起 GET(GET 请求 userId 放在 Query 中),实时解析 AG-UI 事件并保存最新外层帧 id;断线重连时携带 Last-Event-ID 续连同一 Run;收到终态事件后通过 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; // 断线重连时从断点续传
}
const res = await fetch(
`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(runId)}/events?userId=${encodeURIComponent(userId)}`,
{ headers: eventHeaders }
);
if (res.status === 409) {
// 游标过期(stream_cursor_expired):先读取持久化 Run 状态与消息,不要重复创建 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);
}
}
}
}
}
// 终态后按 message_seq 游标读取持久化消息
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")
// 断线续连时追加:.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));
}
});
// 终态后读取持久化消息
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:先读持久化状态与消息
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. 订阅 SSE 事件流(断线重连时加 -H 'Last-Event-ID: 21')
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. 终态后读取持久化消息(after 为会话内 message_seq 序号)
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. 处理 Client Tool 回传、显式取消与用量审计
当 Run 进入 WAITING_CLIENT_TOOL 时,调用 POST /v1/agent-runtime/project/runs/{runId}/tool-messages 回传工具结果以恢复同一 Run;需要终止任务时调用 POST .../cancel;并通过 GET .../model-invocations 与 GET .../context-compactions 读取各步 Token 消耗与上下文精简事件。
- Node.js(Server)
- Java
- Python
- Go
- REST(curl)
// 1. 回传客户端工具执行结果(content 必须是 JSON 序列化字符串;失败时可传 error 字段)
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. 显式取消正在执行的 Run(断开 SSE 不会取消 Run)
await fetch(`${ENDPOINT}/agent-runtime/project/runs/${encodeURIComponent(run.run_id)}/cancel`, {
method: 'POST',
headers,
body: JSON.stringify({ userId }),
});
// 3. 查询单次 Run 的模型调用 Token 消耗与耗时记录(GET 请求:userId 放 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. 查询会话的上下文自动精简记录
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. 回传 Client Tool 结果(POST 正文包含 userId、id、role="tool"、toolCallId、JSON 字符串 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. 显式取消 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. 查询模型调用记录
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. 回传客户端工具结果(恢复处于 WAITING_CLIENT_TOOL 的同一 Run)
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. 显式取消 Run
requests.post(
f'{ENDPOINT}/agent-runtime/project/runs/{run["run_id"]}/cancel',
headers=HEADERS,
json={'userId': user_id},
timeout=15,
)
# 3. 读取模型调用耗时与 Token 消耗记录
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. 回传客户端工具结果
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. 显式取消 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. 回传客户端工具结果
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. 显式取消 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. 查询模型调用记录与上下文精简记录
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"示例指引
各语言完整示例集:examples/javascript.md、examples/java.md、examples/python.md、examples/go.md。
各语言 Server SDK 初始化与错误模型:server-sdk/nodejs.md、server-sdk/java.md、server-sdk/python.md、server-sdk/go.md。
关联 REST API 参考与产品手册:apis/zh-CN/agent-runtime.md、智能体工作台产品手册。