
Cloudbase Agent
- 3 installs
- 27 repo stars
- Updated August 4, 2026
- tencentcloudbase/cloudbase-skills
Build and deploy AI agents with the CloudBase Agent SDK (TypeScript and Python) implementing the AG-UI protocol via LangGraph, LangChain, or CrewAI adapters.
About
A router skill for building and deploying AG-UI-protocol AI agents with the CloudBase Agent SDK in TypeScript or Python. A developer uses it to deploy agent servers, wire LangGraph/LangChain/CrewAI adapters, and build web or mini-program UI clients.
- TypeScript (@cloudbase/agent-server) and Python (FastAPI) support
- AG-UI protocol with LangGraph, LangChain, and CrewAI adapters
Cloudbase Agent by the numbers
- 3 all-time installs (skills.sh)
- Ranked #13,657 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/tencentcloudbase/cloudbase-skills --skill cloudbase-agentAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 3 |
|---|---|
| repo stars | ★ 27 |
| Last updated | August 4, 2026 |
| Repository | tencentcloudbase/cloudbase-skills ↗ |
What it does
Build and deploy AI agents with the CloudBase Agent SDK (TypeScript and Python) implementing the AG-UI protocol via LangGraph, LangChain, or CrewAI adapters.
Files
Standalone Install Note
If this environment only installed the current skill, start from the CloudBase main entry and use the published cloudbase/references/... paths for sibling skills.
- CloudBase main entry:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/SKILL.md - Current skill raw source:
https://cnb.cool/tencent/cloud/cloudbase/cloudbase-skills/-/git/raw/main/skills/cloudbase/references/cloudbase-agent/SKILL.md
Keep local references/... paths for files that ship with the current skill directory. When this file points to a sibling skill such as auth-tool or web-development, use the standalone fallback URL shown next to that reference.
CloudBase Agent SDK — Language Router
This skill supports TypeScript and Python. Determine the language first, then read the corresponding skill file. If the user does not explicitly specify which programming language to use, TypeScript must be enforced.
Step 1: Determine Language
| Signal | Language |
|---|---|
| User says "TypeScript", "Node.js", "TS" | TypeScript |
| User says "Python", "FastAPI", "pip" | Python |
| No clear signal | TypeScript |
Step 2: Read the Language-Specific Skill File
- TypeScript → Read ts/skill.md — then follow ALL instructions in that file
- Python → Read py/skill.md — then follow ALL instructions in that file
⚠️ IMPORTANT: After determining the language, you MUST read the corresponding skill file above. Do NOT proceed with any code generation until you have read it. Each language skill file is self-contained with its own quick start, routing table, deployment instructions, and adapter guides.
Building Custom Adapters
An adapter bridges your AI framework to the AG-UI protocol. It converts AG-UI input (messages, tools, state) into your framework's format, and converts your framework's streaming output into AG-UI events.
Prerequisites: Deep understanding of both your AI framework's API and the AG-UI protocol events.
When to build your own: No existing adapter for your framework (check AG-UI ecosystem first).
Extend AbstractAgent and implement run() that returns Observable<BaseEvent>.
Structure
import { AbstractAgent, RunAgentInput, BaseEvent, EventType } from "@ag-ui/client";
import { Observable, Subscriber } from "rxjs";
export class MyAdapter extends AbstractAgent {
run(input: RunAgentInput): Observable<BaseEvent> {
return new Observable((subscriber) => this._run(subscriber, input));
}
private async _run(subscriber: Subscriber<BaseEvent>, input: RunAgentInput) {
const { messages, runId, threadId, tools } = input;
subscriber.next({ type: EventType.RUN_STARTED, threadId, runId });
try {
// 1. Convert AG-UI input to your framework's format
// 2. Call your framework
// 3. Convert your framework's output to AG-UI events (see Event Sequence below)
subscriber.next({ type: EventType.RUN_FINISHED, threadId, runId });
} catch (error) {
subscriber.next({ type: EventType.RUN_ERROR, message: error.message });
}
subscriber.complete();
}
}Event Sequence (Brief)
Text: TEXT_MESSAGE_START → TEXT_MESSAGE_CONTENT (repeat) → TEXT_MESSAGE_END
Tool call: TOOL_CALL_START → TOOL_CALL_ARGS → TOOL_CALL_END
Tool result (server-executed tools only): TOOL_CALL_RESULT
Always emit full lifecycle. parentMessageId links tool calls to their parent message.
For complete event reference, see AG-UI Protocol.
@cloudbase/agent-adapter-langchain
Adapter that wraps LangChain's createAgent() as an AG-UI compatible agent. Provides LangchainAgent wrapper class and clientTools() middleware for client tools support.
Basic Usage
import { createAgent as createLangchainAgent } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { LangchainAgent, clientTools } from "@cloudbase/agent-adapter-langchain";
const model = new ChatOpenAI({ model: "gpt-4o" });
const checkpointer = new MemorySaver();
const lcAgent = createLangchainAgent({
model,
checkpointer,
middleware: [clientTools()],
});
const agent = new LangchainAgent({ agent: lcAgent });Checkpointer (Required)
LangchainAgent requires the agent to be created with a checkpointer.
MemorySaver (Development)
import { MemorySaver } from "@langchain/langgraph";
const lcAgent = createLangchainAgent({
model,
checkpointer: new MemorySaver(),
middleware: [clientTools()],
});CloudBaseSaver (Production)
Persistent storage using Tencent CloudBase document database. On CloudBase cloud function/cloudrun, requests are authenticated - extract user ID from the JWT in Authorization header.
import { run } from "@cloudbase/agent-server";
import { LangchainAgent, clientTools } from "@cloudbase/agent-adapter-langchain";
import { CloudBaseSaver } from "@cloudbase/agent-adapter-langgraph";
import { createAgent as createLangchainAgent } from "langchain";
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: process.env.CLOUDBASE_ENV_ID });
run({
createAgent: ({ request }) => {
// Extract user ID from JWT (sub field)
const token = request.headers.get("Authorization")?.slice(7);
const payload = JSON.parse(atob(token.split(".")[1]));
const userId = payload.sub;
const checkpointer = new CloudBaseSaver({
db: app.database(),
userId, // Multi-tenant isolation
});
const lcAgent = createLangchainAgent({
model,
checkpointer,
middleware: [clientTools()],
});
return { agent: new LangchainAgent({ agent: lcAgent }) };
},
port: 9000,
});With @cloudbase/agent-server
import { run } from "@cloudbase/agent-server";
run({
createAgent: () => ({ agent }),
port: 9000,
});clientTools() Middleware
Enables client-defined tools in your LangChain agent:
- Injects client tools - Adds client tools to the LLM's available tool list
- Routes to END - When a client tool is called, skips ToolNode and routes to END so client can execute
@cloudbase/agent-adapter-langgraph
Adapter that wraps a compiled LangGraph StateGraph workflow as an AG-UI compatible agent. Provides ClientStateAnnotation with pre-wired messages and client.tools fields for seamless AG-UI protocol integration.
Installation
npm install @cloudbase/agent-adapter-langgraph@latest @langchain/langgraph @langchain/openaiImportant: Always use @latest for @cloudbase/agent-* packages to get the newest stable releases. Do NOT specify version ranges like ^1.0.0 or exact versions like 1.0.0, as the package versions may not follow semantic versioning expectations and such versions may not exist.
For projects requiring version locking, install first with @latest, then commit package-lock.json.
Exports
import {
LanggraphAgent,
ClientStateAnnotation,
ClientState,
CloudBaseSaver // Tencent CloudBase checkpointer
} from "@cloudbase/agent-adapter-langgraph";Basic Usage
import { LanggraphAgent } from "@cloudbase/agent-adapter-langgraph";
const agent = new LanggraphAgent({
compiledWorkflow: graph, // compiled StateGraph (required)
logger: myLogger, // optional
});Checkpointer (Required)
LanggraphAgent requires the workflow to be compiled with a checkpointer.
MemorySaver (Development)
import { MemorySaver } from "@langchain/langgraph";
const graph = workflow.compile({ checkpointer: new MemorySaver() });CloudBaseSaver (Production)
Persistent storage using Tencent CloudBase document database. On CloudBase cloud function/cloudrun, requests are authenticated - extract user ID from the JWT in Authorization header.
import { run } from "@cloudbase/agent-server";
import { CloudBaseSaver, LanggraphAgent } from "@cloudbase/agent-adapter-langgraph";
import tcb from "@cloudbase/node-sdk";
const app = tcb.init({ env: process.env.CLOUDBASE_ENV_ID });
run({
createAgent: ({ request }) => {
// Extract user ID from JWT (sub field)
const token = request.headers.get("Authorization")?.slice(7);
const payload = JSON.parse(atob(token.split(".")[1]));
const userId = payload.sub;
const checkpointer = new CloudBaseSaver({
db: app.database(),
userId, // Multi-tenant isolation
});
const graph = workflow.compile({ checkpointer });
return { agent: new LanggraphAgent({ compiledWorkflow: graph }) };
},
port: 9000,
});Client Tools
Client tools are tools defined by the client, not the server. They let the agent request actions only the client can perform (e.g., show modal, navigate, access local storage). The flow:
1. Client defines tools with handlers and sends them in request 2. Server binds client tools alongside server tools, LLM can call any 3. Server detects client tool call → routes to END (doesn't execute) 4. Client receives TOOL_CALL_* events, executes handler locally 5. Client sends tool result back, agent resumes
Server Side: Bind and Route
import { ClientState } from "@cloudbase/agent-adapter-langgraph";
// 1. Bind client tools to model (alongside server tools)
async function chatNode(state: ClientState) {
const clientTools = state.client?.tools || [];
const modelWithTools = model.bindTools([...clientTools, ...serverTools]);
// ...
}
// 2. Route client tool calls to END (let client handle)
function shouldContinue(state: ClientState): "tools" | "end" {
const lastMessage = state.messages[state.messages.length - 1];
if (lastMessage.tool_calls?.length > 0) {
const hasServerToolCall = lastMessage.tool_calls.some(tc => serverToolNames.has(tc.name));
if (hasServerToolCall) return "tools"; // Server executes
}
return "end"; // Client tool or no tool → end, client handles
}Complete Workflow Pattern
import { StateGraph, START, END, Command } from "@langchain/langgraph";
import { ClientStateAnnotation, ClientState } from "@cloudbase/agent-adapter-langgraph";
import { MemorySaver } from "@langchain/langgraph";
import { ChatOpenAI } from "@langchain/openai";
import { SystemMessage } from "@langchain/core/messages";
import { RunnableConfig } from "@langchain/core/runnables";
async function chatNode(state: ClientState, config?: RunnableConfig) {
const model = new ChatOpenAI({ model: "gpt-4o" });
const modelWithTools = model.bindTools([...(state.client?.tools || [])], {
parallel_tool_calls: false, // Recommended: avoid race conditions
});
const response = await modelWithTools.invoke([
new SystemMessage({ content: "You are a helpful assistant." }),
...state.messages,
], config);
return new Command({ goto: END, update: { messages: [response] } });
}
const workflow = new StateGraph(ClientStateAnnotation)
.addNode("chat_node", chatNode)
.addEdge(START, "chat_node");
export const graph = workflow.compile({ checkpointer: new MemorySaver() });With @cloudbase/agent-server
Deploy your LangGraph workflow as an HTTP endpoint that speaks the AG-UI protocol. Clients can connect via SSE to stream events.
import { run } from "@cloudbase/agent-server";
import { LanggraphAgent } from "@cloudbase/agent-adapter-langgraph";
run({
createAgent: () => ({
agent: new LanggraphAgent({ compiledWorkflow: graph })
}),
port: 3000
});Agent Deployment Guide
Core Principle
Always use the `manageAgent` MCP tool to deploy Agent services.
It natively supports SSE streaming, session persistence, and Node.js 20 runtime — purpose-built for Agent scenarios.
Do NOT use createFunction or manageCloudRun for Agent deployment.
Why HTTP Cloud Functions First
| Dimension | HTTP Cloud Functions | CloudRun |
|---|---|---|
| SSE Streaming | ✅ Native support | ✅ Supported |
| WebSocket | ✅ Native support | ✅ Supported |
| Deployment Complexity | Low (no Dockerfile needed) | High (container config required) |
| Cost | Pay-per-invocation, scales to zero | Pay-per-instance-hour |
| Cold Start | Yes, mitigated with provisioned instances | Yes, mitigated with min instances |
| Supported Runtimes | Node.js, Python | Any |
Deployment Steps (HTTP Cloud Functions)
1. Ensure project has scf_bootstrap startup script (see below) 2. Deploy using manageAgent MCP tool with runtime="Nodejs20.19":
manageAgent(action="create", runtime="Nodejs20.19", installDependency=true, targetPath="...")3. Set environment variables (OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MODEL, etc.) 4. Verify SSE connectivity
⚠️ CRITICAL: Always setinstallDependency=trueto let cloud install dependencies automatically. Without this, you'll getERR_MODULE_NOT_FOUNDerrors.
For server code and adapter usage, see server-quickstart and adapter-langgraph.
Dependency Alignment Policy (CRITICAL)
*Always use `latest` for `@cloudbase/agent- and @langchain/` packages. Never specify version ranges.*
Reference example (adapt based on your actual dependencies):
{
"dependencies": {
"@cloudbase/agent-server": "latest",
"@cloudbase/agent-adapter-langgraph": "latest",
"@langchain/langgraph": "latest",
"@langchain/openai": "latest"
}
}Why?@cloudbase/agent-adapter-langgraphhas peer dependency on specific@langchain/coreversions. Specifying version ranges like^0.3.44causes[ResourceNotFound.Package] Dependency errorduring cloud build.
---
Node.js Runtime Version
Always select Node.js 20 runtime (runtime="Nodejs20"):
- Full compatibility with all
@cloudbase/agent-*packages - ES Module support (
"type": "module"in package.json) - Stable and well-tested on the CloudBase platform
Do NOT use Node.js 16 or earlier — many SDK features require Node.js >= 20.
Startup Script (scf_bootstrap)
The startup script must be named scf_bootstrap (no file extension), placed in the project root, and have executable permissions:
#!/bin/sh
node src/index.jschmod +x scf_bootstrapIMPORTANT: Thescf_bootstrapscript should be minimal — just start the Node.js application. Do NOT includenpm installin this script. Dependencies are handled during deployment.
NOTE: Use#!/bin/sh(not#!/bin/bash) for maximum compatibility. The entry point should match your actual server entry file.
Port & CORS
- Your server should listen on port
9000(the default for CloudBase Agent) - In production (CloudBase), CORS is handled by the API gateway — no need to enable it in code
- For local development, conditionally enable CORS via an environment variable (e.g.,
ENABLE_CORS=true)
Environment Variables
| Variable | Required | Purpose |
|---|---|---|
OPENAI_API_KEY | ✅ | OpenAI API key or compatible service key |
OPENAI_BASE_URL | ✅ | API base URL, e.g. https://api.openai.com/v1 |
OPENAI_MODEL | ✅ | Model name, e.g. gpt-4o or gpt-3.5-turbo |
LOG_LEVEL | ❌ | Log level: trace/debug/info/warn/error/fatal (default: info) |
ENABLE_CORS | ❌ | Set to true to enable CORS (local dev only) |
When to Use CloudRun Instead
Despite HTTP Cloud Functions being preferred, use CloudRun in these cases:
- Custom Docker image required (special system-level dependencies like FFmpeg, Chromium, etc.)
- Resource requirements exceed Cloud Function limits
- Persistent local file storage needed
- Need to install native C extensions that require specific OS packages
For CloudRun deployment, use a Dockerfile:
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm i --production
COPY src ./src
ENV NODE_ENV=production
EXPOSE 9000
CMD ["node", "src/index.js"]Summary
| Decision | Choice |
|---|---|
| Deployment tool | manageAgent MCP tool (MUST USE) |
| Node.js runtime | Node.js 20.19 (MUST USE, runtime="Nodejs20.19") |
| Dependency install | installDependency=true (MUST SET, or get ERR_MODULE_NOT_FOUND) |
| Default platform | HTTP Cloud Functions |
| Fallback platform | CloudRun (only for special requirements) |
| Startup script | scf_bootstrap — #!/bin/sh + node src/index.js |
| Port | Listen on port 9000 |
| CORS | Production uses API gateway; local dev via ENABLE_CORS env var |
| Module system | ES Modules ("type": "module" in package.json) |
AG-UI Protocol
Open, event-based protocol for agent-UI communication. Server streams events to client via SSE.
Event Patterns
Start-Content-End: For streaming content
TEXT_MESSAGE_START → TEXT_MESSAGE_CONTENT (repeat) → TEXT_MESSAGE_END
TOOL_CALL_START → TOOL_CALL_ARGS (repeat) → TOOL_CALL_ENDLifecycle: Wraps every agent run
RUN_STARTED → [events] → RUN_FINISHED | RUN_ERRORSnapshot-Delta: For state sync
STATE_SNAPSHOT (full state) → STATE_DELTA (JSON Patch updates)Core Events
| Event | Key Fields |
|---|---|
RUN_STARTED | threadId, runId |
RUN_FINISHED | threadId, runId |
RUN_ERROR | message, code? |
TEXT_MESSAGE_START | messageId, role |
TEXT_MESSAGE_CONTENT | messageId, delta |
TEXT_MESSAGE_END | messageId |
TOOL_CALL_START | toolCallId, toolCallName, parentMessageId? |
TOOL_CALL_ARGS | toolCallId, delta |
TOOL_CALL_END | toolCallId |
TOOL_CALL_RESULT | toolCallId, messageId, content |
STATE_SNAPSHOT | snapshot |
STATE_DELTA | delta (RFC 6902 JSON Patch) |
MESSAGES_SNAPSHOT | messages[] |
Input Types
interface RunAgentInput {
threadId: string;
runId: string;
messages: Message[];
tools: Tool[];
state?: unknown;
context?: Context[];
forwardedProps?: Record<string, unknown>;
}
interface Message {
id: string;
role: "user" | "assistant" | "system" | "tool";
content: string;
name?: string; // for tool messages
toolCalls?: ToolCall[]; // for assistant messages
toolCallId?: string; // for tool messages
}
interface ToolCall {
id: string;
type: "function";
function: { name: string; arguments: string };
}
interface Tool {
name: string;
description: string;
parameters?: JSONSchema;
}Tool Execution Flow
Server-executed tools: 1. Agent emits TOOL_CALL_START/ARGS/END 2. Server executes tool 3. Server emits TOOL_CALL_RESULT 4. Agent continues with result
Client tools: 1. Agent emits TOOL_CALL_START/ARGS/END 2. Server emits RUN_FINISHED (run pauses) 3. Client executes tool locally 4. Client sends new request with tool result in messages 5. Agent continues
Full Reference
For complete protocol specification: https://docs.ag-ui.com/concepts/events
@cloudbase/agent-server
Deploy AG-UI compatible agents as HTTP servers.
Installation
npm install @cloudbase/agent-server@latestImportant: Always use @latest for @cloudbase/agent-* packages. Do NOT use version ranges like ^1.0.0 or exact versions, as these versions may not exist. The packages do not follow traditional semantic versioning.
Deployment Methods
run() - Standalone
import { run } from "@cloudbase/agent-server";
run({ createAgent: () => ({ agent }), port: 9000 });createExpressServer() - Get App
import { createExpressServer } from "@cloudbase/agent-server";
const app = createExpressServer({ createAgent: () => ({ agent }) });
app.listen(9000);createExpressRoutes() - Add to Existing
import { createExpressRoutes } from "@cloudbase/agent-server";
createExpressRoutes({ createAgent: () => ({ agent }), express: app, basePath: "/api/" });Endpoints Created
| Endpoint | Purpose |
|---|---|
/agui | CopilotKit RPC endpoint |
/send-message | AG-UI endpoint (SSE) |
/healthz | Health check |
/chat/completions | OpenAI-compatible endpoint |
/v1/aibot/bots/:agentId/... | Same endpoints with bot ID (when no basePath) |
AgentCreatorContext
interface AgentCreatorContext {
request: Request; // Web Standard Request
logger?: Logger; // Pino-style logger (AGUI routes only)
requestId?: string; // Unique request ID (AGUI routes only)
}
createAgent: (ctx: AgentCreatorContext) => ({
agent, // Your adapter instance
cleanup?: () => void // Called when request ends
})Cleanup Pattern
createAgent: (ctx) => {
const db = connectToDatabase();
ctx.logger?.info("Connected to database");
return {
agent: new LanggraphAgent({ workflow }),
cleanup: () => db.close()
};
}All Options
run({
createAgent,
port: 9000,
basePath: "/api/", // Custom base path (default: dual endpoints)
cors: true, // or { origin: "https://..." }
useAGUI: true, // Enable /agui endpoint (default: true)
aguiOptions: {
runtimeOptions: {}, // CopilotRuntimeOptions
endpointOptions: {} // CreateCopilotRuntimeServerOptions
},
logger: createConsoleLogger("debug"),
observability: { type: "otlp", url: "...", headers: {...} }
});Logger Exports
import {
noopLogger, // Silent logger (default)
createConsoleLogger, // Console logger
generateRequestId,
extractRequestId,
getOrGenerateRequestId
} from "@cloudbase/agent-server";
// Custom logger (Pino-style interface)
const logger = {
info: (obj, msg) => console.log(msg, obj),
error: (obj, msg) => console.error(msg, obj),
debug: (obj, msg) => console.debug(msg, obj),
child: (bindings) => ({ ...logger })
};Observability
Requires @cloudbase/agent-observability package:
run({
createAgent,
observability: { type: "console" } // Logs traces to stdout
});
// OTLP exporter (Langfuse, Jaeger, etc.)
run({
createAgent,
observability: {
type: "otlp",
url: "https://cloud.langfuse.com/api/public/otlp/v1/traces",
headers: { Authorization: "Basic xxx" }
}
});
// Multiple exporters
run({
createAgent,
observability: [
{ type: "console" },
{ type: "otlp", url: "http://localhost:4318/v1/traces" }
]
});Error Handling
import { ErrorCode, isErrorWithCode } from "@cloudbase/agent-server";
// ErrorCode enum values for error handlingBuilding UI Clients
Connect your UI to AG-UI endpoints served by @cloudbase/agent-server.
Web Applications
Use @ag-ui/client (official AG-UI SDK):
npm install @ag-ui/client@latestimport { HttpAgent } from "@ag-ui/client";
const agent = new HttpAgent({ url: "http://localhost:9000/send-message" });
for await (const event of agent.run({
threadId: "thread-1",
runId: "run-1",
messages: [{ id: "m1", role: "user", content: "Hello" }]
})) {
console.log(event.type, event);
}See AG-UI documentation for full API: https://docs.ag-ui.com
WeChat Mini Program
Use @cloudbase/agent-ui-miniprogram (headless behavior mixin):
npm install @cloudbase/agent-ui-miniprogram@latestimport { createAGUIBehavior, CloudbaseTransport } from "@cloudbase/agent-ui-miniprogram";
Component({
behaviors: [createAGUIBehavior({
transport: new CloudbaseTransport({ botId: "your-bot-id" })
})],
methods: {
onSend() {
this.agui.sendMessage(this.data.inputText);
}
}
});
// State: this.data.agui.uiMessages, this.data.agui.isRunningBeyond basic usage, the package offers more createAGUIBehavior options, this.agui.* namespace methods, state getters, and UIMessage format for rendering.
@cloudbase/agent-ui-miniprogram
WeChat Mini Program SDK for AG-UI protocol. Headless behavior mixin pattern.
Installation
npm install @cloudbase/agent-ui-miniprogram@latestBasic Usage
import { createAGUIBehavior, CloudbaseTransport } from "@cloudbase/agent-ui-miniprogram";
const transport = new CloudbaseTransport({ botId: "your-bot-id" });
Component({
behaviors: [createAGUIBehavior({ transport })],
methods: {
onSend() {
this.agui.sendMessage(this.data.inputText);
}
}
});createAGUIBehavior Options
createAGUIBehavior({
transport, // Transport instance (CloudbaseTransport)
messages: [], // Initial message history
tools: [{ // Client tools the agent can invoke
name: "get_weather",
description: "Get weather",
parameters: { type: "object", properties: { city: { type: "string" } } },
handler: async ({ args }) => ({ temp: 72 })
}],
threadId: "custom-id", // Custom thread ID (auto-generated if omitted)
contexts: [], // Additional context objects
onRawEvent: (event) => {} // Callback for each raw AG-UI event
})Namespace Methods (this.agui.*)
| Method | Description |
|---|---|
init({ transport, threadId? }) | Initialize transport at runtime |
| `sendMessage(text \ | Message[])` |
appendMessage(message) | Add message without running agent |
setMessages(messages) | Replace entire message history |
reset() | Reset to initial state |
setThreadId(id) | Change thread ID |
addTool(tool) | Register a client tool |
removeTool(name) | Remove tool by name |
updateTool(name, updates) | Update tool properties |
clearTools() | Remove all tools |
State Getters (this.agui. or this.data.agui.)
| Property | Type | Description |
|---|---|---|
messages | Message[] | Raw message history |
uiMessages | UIMessage[] | Messages formatted for UI rendering |
isRunning | boolean | Agent is processing |
runId | `string \ | null` |
activeToolCalls | ToolCallState[] | Tool calls in progress |
error | `AGUIClientError \ | null` |
threadId | string | Current thread ID |
tools | Tool[] | Registered tools (definitions only) |
contexts | Context[] | Context objects |
config | CreateAGUIBehaviorOptions | Current configuration |
CloudbaseTransport
Production transport for WeChat Cloud Development:
import { CloudbaseTransport } from "@cloudbase/agent-ui-miniprogram";
const transport = new CloudbaseTransport({
botId: "bot-xxxxxx" // From Cloud Development console
});Requires wx.cloud.extend.AI.bot.sendMessage API.
Imperative Pattern
Use aguiBehavior (no static config) for runtime-only initialization:
import { aguiBehavior, CloudbaseTransport } from "@cloudbase/agent-ui-miniprogram";
Component({
behaviors: [aguiBehavior],
lifetimes: {
attached() {
this.agui.init({
transport: new CloudbaseTransport({ botId: "my-bot" })
});
}
}
});Client Tool Example
Component({
behaviors: [createAGUIBehavior({ transport })],
lifetimes: {
attached() {
this.agui.addTool({
name: "show_toast",
description: "Show a toast message",
parameters: {
type: "object",
properties: { title: { type: "string" } },
required: ["title"]
},
handler: async ({ args }) => {
wx.showToast({ title: args.title });
return { success: true };
}
});
}
}
});UIMessage Format
uiMessages groups consecutive same-role messages with parts:
interface UIMessage {
id: string;
role: "user" | "assistant";
parts: (TextPart | ToolPart)[];
}
interface TextPart { type: "text"; text: string; }
interface ToolPart {
type: "tool";
toolCallId: string;
name: string;
args?: Record<string, unknown>;
status: "pending" | "ready" | "executing" | "completed" | "failed";
result?: unknown;
error?: AGUIClientError;
}