小程序开放平台

文档中心
智能体API
消费侧(小组件)API
sendMessage
getAgentInfo
getHistoryMessages
getConversations
queryTasks
uploadOpenAiFile(新增)

sendMessage

应用开发
>
API和SDK
>
消费侧(小组件)API
>
sendMessage
>
更新时间:2026-02-05 21:21:45

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) => {
    /*
    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;
  }>;
});

返回值

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

中断消息

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