wx-server-sdk Integration
Call CloudBase AI models from WeChat Cloud Functions using the built-in wx-server-sdk. No additional installation is required. Supports text generation, streaming output, and more.
Online Example
View example code in CodeSandbox → (Note: This code must be deployed as a WeChat Cloud Function; it cannot run directly in CodeSandbox)
Prerequisites
- A CloudBase environment (older plans can be upgraded), with model switch enabled (see Overview)
- wx-server-sdk 3.0.5-beta.1 or higher (required for
cloud.ai())
Version Requirement
The cloud.ai() API requires wx-server-sdk 3.0.5-beta.1 or higher. Specify the version in your cloud function's package.json:
{
"dependencies": {
"wx-server-sdk": "3.0.5-beta.1"
}
}
Initialization
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
timeout: 60000 // AI generation may take longer, recommend setting a longer timeout
})
exports.main = async (event, context) => {
const ai = cloud.ai()
// Use AI features
}
Timeout Configuration
AI model text generation may take longer. It's recommended to set timeout to 60000 (60 seconds) or higher to avoid request timeouts.
Text Generation
generateText() - Non-streaming
Returns the complete result at once.
const ai = cloud.ai()
const model = ai.createModel('cloudbase')
const result = await model.generateText({
model: 'hy3-preview',
messages: [{ role: 'user', content: 'Introduce Li Bai' }],
})
console.log(result.text) // Generated text
console.log(result.usage) // Token usage
console.log(result.messages) // Complete message history
Return Value
| Property | Type | Description |
|---|---|---|
| text | string | Generated text |
| messages | ChatModelMessage[] | Complete message history |
| usage | Usage | Token usage |
| rawResponses | unknown[] | Raw model responses |
| error | unknown | Error information (if any) |
streamText() - Streaming
Returns text in a stream, suitable for real-time conversation scenarios.
const ai = cloud.ai()
const model = ai.createModel('cloudbase')
const res = await model.streamText({
model: 'hy3-preview',
messages: [{ role: 'user', content: 'Introduce Li Bai' }],
})
// Method 1: Iterate text stream (recommended)
for await (const text of res.textStream) {
console.log(text) // Incremental text
}
// Method 2: Iterate data stream for complete response data
for await (const data of res.dataStream) {
console.log(data) // Contains choices, usage, and other complete information
}
// Get final results
const messages = await res.messages
const usage = await res.usage
Return Value
| Property | Type | Description |
|---|---|---|
| textStream | AsyncIterable<string> | Incremental text stream |
| dataStream | AsyncIterable<DataChunk> | Complete data stream |
| messages | Promise<ChatModelMessage[]> | Final message history |
| usage | Promise<Usage> | Final token usage |
Complete Examples
AI Chat API
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
timeout: 60000
})
exports.main = async (event, context) => {
const { messages } = event
const ai = cloud.ai()
const model = ai.createModel('cloudbase')
try {
const result = await model.generateText({
model: 'hy3-preview',
messages
})
return {
success: true,
text: result.text,
usage: result.usage
}
} catch (error) {
return {
success: false,
error: error.message
}
}
}
Streaming Response
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
timeout: 60000
})
exports.main = async (event, context) => {
const { messages } = event
const ai = cloud.ai()
const model = ai.createModel('cloudbase')
const res = await model.streamText({
model: 'hy3-preview',
messages
})
// Collect complete text
let fullText = ''
for await (const text of res.textStream) {
fullText += text
}
const usage = await res.usage
return {
text: fullText,
usage
}
}
Differences from @cloudbase/node-sdk
| Feature | wx-server-sdk | @cloudbase/node-sdk |
|---|---|---|
| Installation | Built-in, no install needed | npm install @cloudbase/node-sdk |
| Version requirement | 3.0.5-beta.1+ | 3.16.0+ |
| Initialization | cloud.init() | tcb.init() |
| AI entry point | cloud.ai() | app.ai() |
| Image generation | Supported | Supported |
| Runtime environment | WeChat Cloud Functions | WeChat Cloud Functions / Cloud Hosting / standalone Node.js |