使用示例
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) => {
/*
result 完整数据格式:
{
code: 0,
msg: "success",
data: {
record_id: "rec-1234567890",
conversation_id: "conv-12345",
created: 1704067200000,
model: "qwen-plus",
version: "1.0.0"
}
}
*/
console.log("请求成功:", 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);
/*
chunk 完整数据格式:
{
id: "chatcmpl-xxx",
object: "chat.completion.chunk",
created: 1704067200,
model: "qwen-plus",
choices: [{
index: 0,
delta: {
content: "你好",
reasoning_content: "让我思考一下...",
role: "assistant"
},
finish_reason: null
}]
}
*/
} catch (error) {
console.error("解析消息块失败:", error);
return;
}
if (chunk.choices && chunk.choices[0] && chunk.choices[0].message) {
const message = chunk.choices[0].message;
/*
message 完整数据格式:
{
content: "你好",
reasoning_content: "让我思考一下...",
role: "assistant",
type: "text"
}
*/
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) => {
/*
error 完整数据格式:
{
code: "NETWORK_ERROR",
message: "网络请求失败",
requestId: "req-1234567890"
}
*/
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()