Calling from Node.js
Node.js applications can call Agents through the CloudBase Node SDK or HTTP API.
Check which protocol your Agent uses
An Agent's communication protocol is determined by the template it was created from. If its endpoint on the console's "Integration & Debugging" page ends with /acp (the cloudbase-agent template), it uses the ACP protocol; self-hosted HTTP Agents use the AG-UI protocol. The examples below are grouped by protocol.
Prerequisites
- Node.js 18+
- CloudBase environment activated
- Agent created
Calling an ACP Protocol Agent (cloudbase-agent template)
Write the request body in the JSON-RPC format of the ACP protocol and parse the SSE stream line by line:
const response = await fetch(
'https://your-env-id.api.tcloudbasegateway.com/v1/aibot/bots/your-agent-id/acp',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer <YOUR_API_KEY>',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'session/prompt',
params: {
prompt: [{ type: 'text', text: 'Hello' }],
// Multi-turn: pass back the sessionId returned in previous events to keep context
// sessionId: 'your-session-id',
},
}),
}
);
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
for (const line of decoder.decode(value).split('\n')) {
if (!line.startsWith('data: ') || line.slice(6) === '[DONE]') continue;
try {
const frame = JSON.parse(line.slice(6));
const update = frame?.params?.update;
if (update?.sessionUpdate === 'agent_message_chunk') {
process.stdout.write(update.content.text); // reply text increment
}
} catch (e) {}
}
}
Calling an AG-UI Protocol Agent (self-hosted HTTP Agent)
Using Node SDK
Installation
npm install @cloudbase/node-sdk
Basic Usage
const cloudbase = require('@cloudbase/node-sdk');
const app = cloudbase.init({
env: 'your-env-id',
});
const ai = app.ai();
const res = await ai.bot.sendMessage({
// botId is required, identifies the Agent to call
botId: 'your-agent-id',
// Parameter structure reference front-end and back-end communication protocol:
// https://docs.cloudbase.net/ai/agent/http-agent-protocol
threadId: 'your-thread-id',
runId: 'your-run-id',
messages: [
{ id: 'msg-1', role: 'user', content: 'Hello' }
],
tools: [],
context: [],
state: {},
forwardedProps: {}
});
// Stream the response
let text = '';
for await (const data of res.dataStream) {
// Output based on event type, response events reference:
// https://docs.cloudbase.net/ai/agent/http-agent-protocol#%E5%93%8D%E5%BA%94%E4%BA%8B%E4%BB%B6
switch (data.type) {
case 'TEXT_MESSAGE_CONTENT':
text += data.delta;
process.stdout.write(data.delta); // Real-time output
break;
case 'RUN_ERROR':
console.error('Error:', data.message);
break;
case 'RUN_FINISHED':
// Run finished
break;
}
}
console.log('\nComplete response:', text);
Multi-turn Conversation
Multi-turn conversations are linked through threadId for the same session, passing historical messages through messages:
const { v4: uuidv4 } = require('uuid');
// Use the same threadId to link multi-turn conversations
const threadId = uuidv4();
const messages = [];
// First round of conversation
messages.push({ id: uuidv4(), role: 'user', content: 'Hello' });
const res1 = await ai.bot.sendMessage({
botId: 'your-agent-id',
threadId: threadId,
runId: uuidv4(),
messages: messages,
tools: [],
context: [],
state: {},
forwardedProps: {}
});
let answer1 = '';
for await (const data of res1.dataStream) {
if (data.type === 'TEXT_MESSAGE_CONTENT') {
answer1 += data.delta;
}
}
// Record AI reply
messages.push({ id: uuidv4(), role: 'assistant', content: answer1 });
// Second round of conversation
messages.push({ id: uuidv4(), role: 'user', content: 'Continue chatting' });
const res2 = await ai.bot.sendMessage({
botId: 'your-agent-id',
threadId: threadId,
runId: uuidv4(),
messages: messages,
});
Using HTTP API
Agent API Address
In CloudBase Console → "AI Agent" → Select corresponding Agent → View "API Address", format:
https://{envId}.api.tcloudbasegateway.com/v1/aibot/bots/{agentId}/send-message
const response = await fetch(
'https://your-env-id.api.tcloudbasegateway.com/v1/aibot/bots/your-agent-id/send-message',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'text/event-stream',
'Authorization': 'Bearer <YOUR_API_KEY>',
},
body: JSON.stringify({
threadId: 'thread-xxx',
runId: 'run-xxx',
messages: [{ id: '1', role: 'user', content: 'Hello' }],
tools: [],
context: [],
state: {},
}),
}
);
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = decoder.decode(value);
for (const line of text.split('\n')) {
if (line.startsWith('data: ') && line.slice(6) !== '[DONE]') {
try {
const event = JSON.parse(line.slice(6));
if (event.type === 'TEXT_MESSAGE_CONTENT') {
process.stdout.write(event.delta);
}
} catch (e) {}
}
}
}