在小程序中调用
微信小程序可以通过 wx.cloud.extend.AI 调用云开发 Agent,支持流式输出。
前置条件
- 小程序基础库 3.7.1+
- 已开通云开发环境
- 已创建 Agent
初始化
// app.js
App({
onLaunch() {
wx.cloud.init({
env: 'your-env-id',
});
}
});
基础调用
async function sendMessage(message) {
const res = await wx.cloud.extend.AI.bot.sendMessage({
data: {
botId: 'your-agent-id',
msg: message,
}
});
// 流式接收响应
let response = '';
for await (const chunk of res.textStream) {
response += chunk;
console.log(chunk);
}
return response;
}
sendMessage('你好');
完整示例
// pages/chat/chat.js
Page({
data: {
messages: [],
inputValue: '',
loading: false,
},
onInput(e) {
this.setData({ inputValue: e.detail.value });
},
async sendMessage() {
const { inputValue, messages } = this.data;
if (!inputValue.trim() || this.data.loading) return;
this.setData({
messages: [...messages, { role: 'user', content: inputValue }],
inputValue: '',
loading: true,
});
try {
const res = await wx.cloud.extend.AI.bot.sendMessage({
data: {
botId: 'your-agent-id',
msg: inputValue,
}
});
// 添加空的助手消息
this.setData({
messages: [...this.data.messages, { role: 'assistant', content: '' }],
});
// 流式接收响应
let fullText = '';
for await (const text of res.textStream) {
fullText += text;
const updatedMessages = [...this.data.messages];
updatedMessages[updatedMessages.length - 1].content = fullText;
this.setData({ messages: updatedMessages });
}
} catch (error) {
console.error('发送消息失败:', error);
wx.showToast({ title: '发送失败', icon: 'none' });
} finally {
this.setData({ loading: false });
}
},
});