小程序开放平台

文档中心
智能体API
消费侧(小组件/小程序)API
sendMessage
getAgentInfo
getHistoryMessages
getConversations
queryTasks

sendMessage

应用开发
>
API和SDK
>
消费侧(小组件/小程序)API
>
sendMessage
>
更新时间:2025-11-13 17:39:59

sendMessage()

使用示例

 
  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;
  }>;
});

返回值

属性名
类型
说明
onMessagefunction消息回调
onErrorfunction失败回调
onSuccessfunction成功回调
abortfunction中断消息收发
messageobject当前发送的消息

中断消息

// 使用回调方式发送消息
const { message, onMessage, onSuccess, onError, abort } = agent.sendMessage({
  msg: content,
  history: [],
});
abort()
该文档是否对您有帮助?