Skip to main content

Calling from Node.js

Node.js applications can call Agents through the CloudBase Node SDK or HTTP API.

Prerequisites

  • Node.js 18+
  • CloudBase environment activated
  • Agent created

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) {}
}
}
}