小程序开放平台

文档中心
「函数式智能体」简介
「函数式智能体」开发框架
「函数式智能体」访问与调用

使用 xhs.cloud.AI.agent 在小程序/小组件内访问智能体

智能体框架
>
「函数式智能体」访问与调用
>
更新时间:2025-08-13 17:44:07

一、小程序/小组件内调用智能体

小程序/小组件从基础库从 x.x.x 版本开始内置了 Agent 对话能力,开发者可以直接通过小程序/小组件内,通过 xhs.cloud.AI 调用 agent 进行对话

... existing code ...
  async onLoad() {
    console.log("页面加载");
    await this.initAgent();
  },
 
  // 初始化agent
  async initAgent() {
    try {
      const agentId = "921e2e0eaf004d7aa376ee8985e929bb";
      this.agent = xhs.cloud.AI.createAgent({
        agentId,
        env: 'production',
        version: 'latest'
      });
      
      console.log("Agent初始化成功");
    } catch (error) {
      console.error("Agent初始化失败:", error);
      xhs.showToast({
        title: "Agent初始化失败",
        icon: "none",
      });
    }
 }
... existing code ...

开发者调用 xhs.cloud.AI.createAgent 可以得到一个智能体 Agent。Agent 上一共挂载了3个实例属性和7个实例方法,方法的具体参数见JS API文档。

二、Agent 创建 - xhs.cloud.AI.createAgent

使用示例

... existing code ...
  async onLoad() {
    console.log("页面加载");
    await this.initAgent();
  },
 
  // 初始化agent
  async initAgent() {
    try {
      const agentId = "921e2e0eaf004d7aa376ee8985e929bb";
      this.agent = xhs.cloud.AI.createAgent({
        agentId,
        env: 'production',
        version: 'latest'
      });
      
      console.log("Agent初始化成功");
    } catch (error) {
      console.error("Agent初始化失败:", error);
      xhs.showToast({
        title: "Agent初始化失败",
        icon: "none",
      });
    }
 }
... existing code ...

开发者调用 xhs.cloud.AI.createAgent 可以得到一个智能体 Agent

类型声明

xhs.cloud.AI.createAgent({
    agentId,
    accessToken,
    env: 'production',
    version: 'latest'
});

返回值

属性名
类型
说明
最低支持版本
agentAgentAgent实例x.x.x
agentId属性智能体IDx.x.x
agentVersion属性智能体版本x.x.x
env属性环境x.x.x
sendMessage同步方法与智能体进行对话x.x.x
getAgentInfo异步方法获取智能体信息x.x.x
getHistoryMessages异步方法获取历史对话信息x.x.x
getConversations异步方法获取当前智能体会话x.x.x

入参说明

属性名
是否必传
类型
说明
最低支持版本
agentIdstring智能体agentid开放平台获取x.x.x
envstring环境变量,可选值:development 开发环境智能体、production 生产环境智能体x.x.x
version当 env 为 development 必传、当 env 为 production,默认 lateststring智能体函数版本:development - 可能存在多个开发版本,不同智能体存在差异、production - 仅存在一个版本,默认 latestx.x.x

三、Agent 实例

3.1 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()

getAgentInfo

使用示例

const agent = this.getAgent();
if (!agent) return;
const agentInfo = await agent.getAgentInfo();
console.log("res", agentInfo);

类型声明

const agentInfo = await agent.getAgentInfo();

返回值

属性名
类型
说明
最低支持版本
agentInfoobject智能体信息x.x.x
hasConversationboolean是否存在会话x.x.x

AgentInfo 类型说明:

属性名
类型
说明
最低支持版本
agent_namestring智能体名称x.x.x
agent_idstring智能体idx.x.x
agent_iconstring智能体图标x.x.x

getHistoryMessages

使用示例

 
  // 获取历史记录
  async getChatRecords() {
    const agent = this.getAgent();
    if (!agent) return;
 
    const response = await agent.getConversations();
    console.log("=== conversations", response);
    if (response.code !== 0) {
      xhs.showToast({
        title: "获取历史记录失败",
        icon: "none",
      });
      return;
    }
 
    const conversations = response.data.conversations;
    if (conversations && conversations.length > 0) {
      const res = await agent.getHistoryMessages({
        conversation_id: conversations[0].id,
        cursor: 1,
        count: 10,
        sort: "desc",
      });
      console.log("=== getHistoryMessages", res);
    }
  },
类型声明
const agentInfo = await agent.getHistoryMessages({
    conversation_id: conversations[0].id,
    cursor: 1,
    count: 10,
    sort: "desc"
});

入参说明

属性名
类型
字段描述及类型
最低支持版本
conversation_idstring会话 idx.x.x
cursorstring请求的游标x.x.x
countnumber分页大小x.x.x
sortstring历史记录排序x.x.x

返回值

 
export interface UserRecord {
    content: string;
    role: 'user';
}
export interface AssistantRecord {
    content: string;
    role: 'assistant';
    reasoningContent: string;
    type: MessageType;
}
export type CreateRecordPairResponse = BaseResponse;
export interface ParticipantInfo {
    id: string;
    name: string;
    desc: string;
    avatar_url: string;
}
export interface GetHistoryMessagesData {
    message_list: (UserRecord | AssistantRecord)[];
    conversation_id: string;
    participant_info_map: Record<string, ParticipantInfo>;
    next_cursor: number;
    has_more: boolean;
}

getConversations

使用示例

 
const agent = this.getAgent();
if (!agent) return;
const agentInfo = await agent.getConversations();
console.log("res", agentInfo);

类型声明

const agentInfo = await agent.getConversations();

返回值

export interface Conversation {
    id: string;
    createAt: string;
}
export interface GetConversationsData {
    conversations: Conversation[];
}
属性名
类型
说明
最低支持版本
conversations数组会话列表x.x.x
属性名
类型
说明
最低支持版本
idstring会话 idx.x.x
createAtstring会话创建时间x.x.x