使用示例
async sendMessage() {
const agent = this.getAgent();
if (!agent) return;
// 重置状态
this.setData({
thinkingText: "",
streamText: "",
isThinkingCollapsed: false,
thinkingScrollIntoView: "",
replyScrollIntoView: "",
});
// 显示加载中
xhs.showLoading({
title: "正在调酒中...",
});
const content = '{"user_taste": "酸", "user_mood": "开心"}';
console.log("准备调用 Agent AI API,参数:", content);
let thinkingText = "";
let result = "";
// 使用回调方式发送消息
const { message, onMessage, onSuccess, onError } = agent.sendMessage({
msg: content,
history: [],
});
onSuccess((result) => {
console.log("请求成功:", result);
console.log("API调用成功,返回结果:", result);
xhs.hideLoading();
// 检查是否需要自动折叠思考卡片
this.checkAutoCollapse();
});
// 监听流式消息
onMessage((chunkStr) => {
console.log("收到消息块:", chunkStr, "api-message", message);
xhs.hideLoading();
if (chunkStr === "[DONE]") {
return;
}
let chunk = "";
try {
chunk = JSON.parse(chunkStr);
} catch (error) {
console.error("解析消息块失败:", error);
return;
}
// 解析消息块
if (chunk.choices && chunk.choices[0] && chunk.choices[0].message) {
const message = chunk.choices[0].message;
// 处理思考内容
if (message.reasoning_content) {
thinkingText += message.reasoning_content;
this.setData({
thinkingText: thinkingText,
});
this.scrollThinkingToBottom();
}
// 处理回复内容
if (message.content) {
result += message.content;
this.setData({
streamText: result,
});
this.scrollReplyToBottom();
}
}
});
// 监听错误回调
onError((error) => {
console.error("请求失败:", error);
xhs.hideLoading();
xhs.showToast({
title: "生成失败,请重试",
icon: "none",
});
});
},
function sendMessage(props: {
botId: string;
msg: string;
history?: Array<{
role: string;
content: string;
}>;
});
属性名 | 类型 | 说明 |
|---|---|---|
| onMessage | function | 消息回调 |
| onError | function | 失败回调 |
| onSuccess | function | 成功回调 |
| abort | function | 中断消息收发 |
| message | object | 当前发送的消息 |
// 使用回调方式发送消息
const { message, onMessage, onSuccess, onError, abort } = agent.sendMessage({
msg: content,
history: [],
});
abort()