| name | ai-model-cloudbase |
| description | Complete guide for calling AI models with CloudBase - covers JS/Node SDK and WeChat Mini Program. Text generation, streaming, and image generation. |
| alwaysApply | false |
When to use this skill
Use this skill for calling AI models using CloudBase across all platforms.
Supported platforms:
| Platform | SDK/API | Section |
|---|
| Web (Browser) | @cloudbase/js-sdk | Part 1 |
| Node.js (Server/Cloud Functions) | @cloudbase/node-sdk ≥3.16.0 | Part 1 (same API, different init) |
| Any platform (HTTP) | HTTP API / OpenAI SDK | Part 2 |
| WeChat Mini Program | wx.cloud.extend.AI | Part 3 ⚠️ Different API |
How to use this skill (for a coding agent)
- Identify the target platform - Ask user which platform they're developing for
- Confirm CloudBase environment - Get
env (environment ID) and credentials
- Pick the appropriate section - Part 1 for JS/Node SDK, Part 3 for WeChat Mini Program
- Follow CloudBase API shapes exactly - Do not invent new APIs
Part 1: CloudBase JS SDK & Node SDK
JS SDK and Node SDK share the same AI API. Only initialization differs.
Installation
npm install @cloudbase/js-sdk
npm install @cloudbase/node-sdk
⚠️ Node SDK AI feature requires version 3.16.0 or above. Check your version with npm list @cloudbase/node-sdk.
Initialization - Web (JS SDK)
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
env: "<YOUR_ENV_ID>",
accessKey: "<YOUR_PUBLISHABLE_KEY>"
});
const auth = app.auth();
await auth.signInAnonymously();
const ai = app.ai();
Initialization - Node.js (Node SDK)
const tcb = require('@cloudbase/node-sdk');
const app = tcb.init({ env: '<YOUR_ENV_ID>' });
exports.main = async (event, context) => {
const ai = app.ai();
};
generateText() - Non-streaming
const model = ai.createModel("hunyuan-exp");
const result = await model.generateText({
model: "hunyuan-lite",
messages: [{ role: "user", content: "你好,请你介绍一下李白" }],
});
console.log(result.text);
console.log(result.usage);
console.log(result.messages);
console.log(result.rawResponses);
streamText() - Streaming
const model = ai.createModel("hunyuan-exp");
const res = await model.streamText({
model: "hunyuan-turbos-latest",
messages: [{ role: "user", content: "你好,请你介绍一下李白" }],
});
for await (let text of res.textStream) {
console.log(text);
}
for await (let data of res.dataStream) {
console.log(data);
}
const messages = await res.messages;
const usage = await res.usage;
generateImage() - Image Generation
⚠️ Image generation is currently only available in Node SDK, not in JS SDK (Web) or WeChat Mini Program.
const imageModel = ai.createImageModel("hunyuan-image");
const res = await imageModel.generateImage({
model: "hunyuan-image",
prompt: "一只可爱的猫咪在草地上玩耍",
size: "1024x1024",
version: "v1.9",
});
console.log(res.data[0].url);
console.log(res.data[0].revised_prompt);
Part 2: CloudBase HTTP API
API Endpoint
https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/<PROVIDER>/v1/chat/completions
cURL - Non-streaming
curl -X POST 'https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/deepseek/v1/chat/completions' \
-H 'Authorization: Bearer <YOUR_API_KEY>' \
-H 'Content-Type: application/json' \
-d '{"model": "deepseek-r1", "messages": [{"role": "user", "content": "你好"}], "stream": false}'
cURL - Streaming
curl -X POST 'https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/deepseek/v1/chat/completions' \
-H 'Authorization: Bearer <YOUR_API_KEY>' \
-H 'Content-Type: application/json' \
-H 'Accept: text/event-stream' \
-d '{"model": "deepseek-r1", "messages": [{"role": "user", "content": "你好"}], "stream": true}'
OpenAI SDK Compatible
const OpenAI = require("openai");
const client = new OpenAI({
apiKey: "<YOUR_API_KEY>",
baseURL: "https://<ENV_ID>.api.tcloudbasegateway.com/v1/ai/deepseek/v1",
});
const completion = await client.chat.completions.create({
model: "deepseek-r1",
messages: [{ role: "user", content: "你好" }],
stream: true,
});
for await (const chunk of completion) {
console.log(chunk);
}
Part 3: WeChat Mini Program
⚠️ WeChat Mini Program API is DIFFERENT from JS/Node SDK. Pay attention to the parameter structure.
Requires base library 3.7.1+. No extra SDK needed.
Initialization
App({
onLaunch: function() {
wx.cloud.init({ env: "<YOUR_ENV_ID>" });
}
})
generateText() - Non-streaming
⚠️ Different from JS/Node SDK: Return value is raw model response.
const model = wx.cloud.extend.AI.createModel("hunyuan-exp");
const res = await model.generateText({
model: "hunyuan-lite",
messages: [{ role: "user", content: "你好" }],
});
console.log(res.choices[0].message.content);
console.log(res.usage);
streamText() - Streaming
⚠️ Different from JS/Node SDK: Must wrap parameters in data object, supports callbacks.
const model = wx.cloud.extend.AI.createModel("hunyuan-exp");
const res = await model.streamText({
data: {
model: "hunyuan-lite",
messages: [{ role: "user", content: "hi" }]
},
onText: (text) => {
console.log("New text:", text);
},
onEvent: ({ data }) => {
console.log("Event:", data);
},
onFinish: (fullText) => {
console.log("Done:", fullText);
}
});
for await (let str of res.textStream) {
console.log(str);
}
( event res.) {
.(event);
(event. === ) {
;
}
}
API Comparison: JS/Node SDK vs WeChat Mini Program
| Feature | JS/Node SDK | WeChat Mini Program |
|---|
| Namespace | app.ai() | wx.cloud.extend.AI |
| generateText params | Direct object | Direct object |
| generateText return | { text, usage, messages } | Raw: { choices, usage } |
| streamText params | Direct object | ⚠️ Wrapped in data: {...} |
| streamText return | { textStream, dataStream } | { textStream, eventStream } |
| Callbacks | Not supported | onText, onEvent, onFinish |
| Image generation | Node SDK only | Not available |
Type Definitions
JS/Node SDK - BaseChatModelInput
interface BaseChatModelInput {
model: string;
messages: Array<ChatModelMessage>;
temperature?: number;
topP?: number;
}
type ChatModelMessage =
| { role: "user"; content: string }
| { role: "system"; content: string }
| { role: "assistant"; content: string };
JS/Node SDK - generateText() Return
interface GenerateTextResult {
text: string;
messages: Array<ChatModelMessage>;
usage: Usage;
rawResponses: Array<unknown>;
error?: unknown;
}
interface Usage {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
}
JS/Node SDK - streamText() Return
interface StreamTextResult {
textStream: AsyncIterable<string>;
dataStream: AsyncIterable<DataChunk>;
messages: Promise<ChatModelMessage[]>;
usage: Promise<Usage>;
error?: unknown;
}
interface DataChunk {
choices: Array<{
finish_reason: string;
delta: ChatModelMessage;
}>;
usage: Usage;
rawResponse: unknown;
}
WeChat Mini Program - streamText() Input
interface WxStreamTextInput {
data: {
model: string;
messages: Array<{
role: "user" | "system" | "assistant";
content: string;
}>;
};
onText?: (text: string) => void;
onEvent?: (prop: { data: string }) => void;
onFinish?: (text: string) => void;
}
WeChat Mini Program - streamText() Return
interface WxStreamTextResult {
textStream: AsyncIterable<string>;
eventStream: AsyncIterable<{
event?: unknown;
id?: unknown;
data: string;
}>;
}
WeChat Mini Program - generateText() Return
interface WxGenerateTextResponse {
id: string;
object: "chat.completion";
created: number;
model: string;
choices: Array<{
index: number;
message: {
role: "assistant";
content: string;
};
finish_reason: string;
}>;
usage: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
}
HunyuanGenerateImageInput (JS/Node SDK only)
interface HunyuanGenerateImageInput {
model: "hunyuan-image" | string;
prompt: string;
version?: "v1.8.1" | "v1.9";
size?: string;
negative_prompt?: string;
style?: string;
revise?: boolean;
n?: number;
footnote?: string;
seed?: number;
}
interface HunyuanGenerateImageOutput {
id: string;
created: number;
data: Array<{
url: string;
revised_prompt?: string;
}>;
}
Best Practices
- Use streaming for long responses - Better user experience
- Handle errors gracefully - Wrap AI calls in try/catch
- Keep API Keys secure - Never expose in client-side code
- Initialize early - Initialize SDK/cloud in app entry point
- Check for [DONE] - In WeChat Mini Program streaming, check
event.data === "[DONE]" to stop