小程序调用
微信小程序通过 wx.cloud.extend.AI 调用 CloudBase AI 大模型,无需额外安装 SDK。
前置条件
- 微信基础库版本 ≥ 3.7.1
- 已开通云开发环境
- 已配置大模型(见 大模型配置指南)
初始化
在 app.js 中初始化云开发:
App({
onLaunch() {
wx.cloud.init({
env: "<YOUR_ENV_ID>"
});
}
});
文本生成
generateText() - 非流式
一次性返回完整结果,适用于短文本生成。
const model = wx.cloud.extend.AI.createModel("hunyuan-exp");
const res = await model.generateText({
model: "hunyuan-turbos-latest",
messages: [{ role: "user", content: "介绍一下李白" }],
});
// 返回值为原始模型响应
console.log(res.choices[0].message.content);
console.log(res.usage); // { prompt_tokens, completion_tokens, total_tokens }
返回值
interface GenerateTextResponse {
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;
};
}
streamText() - 流式
流式返回文本,适用于实时对话、长文本生成场景。
const model = wx.cloud.extend.AI.createModel("hunyuan-exp");
const res = await model.streamText({
data: {
model: "hunyuan-turbos-latest",
messages: [{ role: "user", content: "介绍一下李白" }],
}
});
// 使用 textStream 获取增量文本
for await (const text of res.textStream) {
console.log("文本片段:", text);
}
参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| data | object | 是 | 请求参数,包含 model 和 messages |
| data.model | string | 是 |