# wx.cloud.extend.AI

微信小程序基础库版本 3.7.1 及以上,支持通过微信云开发的 wx.cloud.extend.AI 扩展接口调用 AI 相关能力。

# 初始化

在使用 AI 相关能力前,需要传入云开发环境进行初始化。

wx.cloud.init({
  env: "your-env-id",
});

初始化完毕后,即可通过 wx.cloud.extend.AI 使用扩展接口来调用 AI 相关能力。

# 大模型

# AI.createModel()

创建指定的 AI 模型。

# 使用示例

const model = wx.cloud.extend.AI.createModel("hunyuan-exp");

# 类型声明

function createModel(model: string): ChatModel;

返回一个提供 AI 生成文本能力的对象。

# ChatModel.streamText()

以流式调用大模型生成文本。流式调用时,生成的文本及其他响应数据会通过 SSE 返回,该接口的返回值对 SSE 做了不同程度的封装,开发者能根据实际需求获取到文本流和完整数据流。

# 使用示例

const hy = wx.cloud.extend.AI.createModel("hunyuan-exp"); // 创建模型
const res = await hy.streamText({
  data: {
    model: "hunyuan-lite",
    messages: [
      {
        role: "user",
        content: "hi"
      }
    ]
  }
});

for await (let str of res.textStream) {
  console.log(str); // 打印生成的文本
}
for await (let event of res.eventStream) {
  console.log(event); // 打印每次返回的完整数据

  // 当大模型结束传输时,通常会发一条 [DONE] 数据,在此之后即可停止循环
  if (event.data === "[DONE]") {
    break;
  }
}

# 类型声明

function streamText(props: StreamTextInput): Promise<StreamTextResult>;

interface StreamTextResult {
  eventStream: EventStream;
  textStream: TextStream;
}

interface StreamTextInput {
  data: unknown;
  onEvent?: OnEvent;
  onText?: OnText;
  onFinish?: OnFinish;
}

interface OnEvent {
  (prop: { data: string }): unknown;
}

interface OnText {
  (text: string): unknown;
}

interface OnFinish {
  (text: string): unknown;
}

interface EventStream {
  [Symbol.asyncIterator](): AsyncIterator<{
    event?: unknown;
    id?: unknown;
    data: string;
  }>;
}

interface TextStream {
  [Symbol.asyncIterator](): AsyncIterator<string>;
}

# 参数

参数名 必填 类型 示例 说明
props.data unknown {model: "hunyuan-lite", messages: [{ role: "user", content: "你好,请你介绍一下李白" }]} 各家大模型的调用参数不同,请根据实际调用模型传入正确的参数。
props.tools object -- 工具调用相关参数
props.tools.autoExecute boolean true 是否自动调用工具,默认为 true
props.tools.maxStep number 10 最大自动执行的次数,默认为 10 次
props.tools.list Array -- 工具列表
props.tools.list[n].name string "get_weather" 工具名称
props.tools.list[n].description string 返回某个城市的某天的温度信息。调用示例:get_weather({city: '北京',date: '03-19'}) 工具描述
props.tools.list[n].fn function ({ city, date }) => city + "在" + date + "的温度是:" + (20 + (Math.random() * 10)) 工具执行的回调函数
props.tools.list[n].parameters {"type":"object","properties":{"city":{"type":"string","description":"要查询的城市"},"date":{"type":"string","description":"要查询的日期"}},"required":["city","date"]} -- 工具执行回调函数的入参 schema 定义
props.tools.onToolEvent function console.warn 监听大模型执行 tool_call 的事件
props.onText (text: string) => unknown; (text) => console.log(text) 接收到新文本返回时触发的回调函数,参数为增量的文本
props.onEvent (prop: { data: string }) => unknown; ({data}) => console.log(data) 接收到新事件返回时触发的回调函数,参数为事件,prop.data 为此次事件包含的数据
props.onFinish (text: string) => unknown; (text) => console.log(text) 当本次调用完全结束时触发的回调函数,参数为本次调用返回的完整文本

# 返回值

StreamTextResult 属性名 类型 说明
textStream AsyncIterable<string> 以流式返回的大模型生成文本,可参考使用示例获取到生成的增量文本。
eventStream AsyncIterable<{data: string, event?: unknown, id?: unknown}> 以流式返回的大模型响应数据,可参考使用示例获取到生成的增量数据。由于各家大模型响应值互有出入,请根据实际情况合理使用。

# ChatModel.generateText()

调用大模型生成文本。

# 使用示例

const hy = wx.cloud.extend.AI.createModel("hunyuan-exp"); // 创建模型
const res = await hy.generateText({
  model: "hunyuan-lite",
  messages: [{ role: "user", content: "你好" }],
});
console.log(res);
// {
//   "id": "27dae91f4e9a4777782c61f89acf8ea4",
//   "object": "chat.completion",
//   "created": 1737602298,
//   "model": "hunyuan-lite",
//   "system_fingerprint": "",
//   "choices": [
//     {
//       "index": 0,
//       "message": {
//         "role": "assistant",
//         "content": "你好!很高兴与你交流。请问有什么我可以帮助你的吗?无论是关于生活、工作、学习还是其他方面的问题,我都会尽力为你提供帮助。"
//       },
//       "finish_reason": "stop"
//     }
//   ],
//   "usage": {
//     "prompt_tokens": 3,
//     "completion_tokens": 33,
//     "total_tokens": 36
//   },
//   "note": "以上内容为AI生成,不代表开发者立场,请勿删除或修改本标记"
// }
console.log(res.choices[0].message.content);
// 你好!很高兴与你交流。请问有什么我可以帮助你的吗?无论是关于生活、工作、学习还是其他方面的问题,我都会尽力为你提供帮助。

# 类型声明

function generateText(data: unknown): Promise<unknown>;

# 参数

参数名 必填 类型 示例 说明
data unknown {model: "hunyuan-lite", messages: [{ role: "user", content: "你好,请你介绍一下李白" }]} 各家大模型的调用参数不同,请根据实际调用模型传入正确的参数。

# 返回值

该接口直接返回实际调用大模型的响应值,需要根据实际响应内容解析出需要的数据。参见上文使用示例。

# Agent

# AI.bot.get()

获取某个 Agent 的信息。

# 使用示例

await wx.cloud.extend.AI.bot.get({ botId: "botId-xxx" });

# 类型声明

function get(props: { botId: string });

# 参数

参数名 必填 类型 说明
props.botId string 要获取信息的 Agent 的 id

# 返回值

属性名 类型 示例 说明
botId string "bot-27973647" Agent ID
name string "信达雅翻译" Agent 名称
introduction string Agent 简介
welcomeMessage string Agent 欢迎语
avatar string Agent 头像链接
background string Agent 聊天背景图链接
isNeedRecommend boolean Agent 回答后是否推荐问题
type string Agent 类型

# AI.bot.list()

批量获取多个 Agent 的信息。

# 使用示例

await wx.cloud.extend.AI.bot.list({
  pageNumber: 1,
  pageSize: 10,
  name: "",
  enable: true,
  information: "",
  introduction: "",
});

# 类型声明

function list(props: {
  name: string;
  introduction: string;
  information: string;
  enable: boolean;
  pageSize: number;
  pageNumber: number;
});

# 参数

参数名 必填 类型 说明
props.pageNumber number 分页大小
props.pageSize number 分页下标
props.enable boolean Agent 是否启用
props.name string Agent 名字,用于模糊查询
props.information string Agent 信息,用于模糊查询
props.introduction string Agent 简介,用于模糊查询

# 返回值

属性名 类型 示例 说明
total number --- Agent 总数
botList Array<object> Agent 列表
botList[n].botId string "bot-27973647" Agent ID
botList[n].name string "信达雅翻译" Agent 名称
botList[n].introduction string Agent 简介
botList[n].welcomeMessage string Agent 欢迎语
botList[n].avatar string Agent 头像链接
botList[n].background string Agent 聊天背景图链接
botList[n].isNeedRecommend boolean Agent 回答后是否推荐问题
botList[n].type string Agent 类型

# AI.bot.sendMessage()

与 Agent 进行对话。

# 使用示例

const res = await wx.cloud.extend.AI.bot.sendMessage({
  data: {
    botId: 'xxx-bot-id',
    msg: "你是谁"
  }
})
for await (let x of res.textStream) {
  console.log(x)
}

# 类型声明

function sendMessage(props: {
  data: {
    botId: string;
    msg: string;
    history: Array<{
      role: string;
      content: string;
    }>;
    files?: Array<string>,
  },
  onText: OnText,
  onEvent: OnEvent,
  onFinish: OnFinish
});

# 参数

参数名 必填 类型 说明
props.data.botId number Agent id
props.data.msg number 此次对话要发送的消息
props.data.history boolean 在此次对话前发生的聊天记录
props.data.history[n].role string 本聊天信息的发送角色
props.data.history[n].content string 本聊天信息的内容
props.data.files Array<string> 本聊天信息附带的文件内容,需要填入云存储的文件 cloud id
props.onText (text: string) => unknown; 接收到新文本返回时触发的回调函数,参数为增量的文本
props.onEvent (prop: { data: string }) => unknown; 接收到新事件返回时触发的回调函数,参数为事件,prop.data 为此次事件包含的数据的字符串
props.onFinish (text: string) => unknown; 当本次调用完全结束时触发的回调函数,参数为本次调用返回的完整文本

# AI.bot.getChatRecords()

获取聊天记录。

# 使用示例

await wx.cloud.extend.AI.bot.getChatRecords({
  botId: "botId-xxx",
  pageNumber: 1,
  pageSize: 10,
  sort: "asc",
});

# 类型声明

function getChatRecords(props: {
  botId: string;
  sort: string;
  pageSize: number;
  pageNumber: number;
});

# 参数

参数名 必填 类型 说明
props.botId string Agent id
props.sort string 排序方式
props.pageSize number 分页大小
props.pageNumber number 分页下标

# 返回值

属性名 类型 说明
total number 对话总数
recordList Array<object> 对话总数
recordList[n].botId string Agent ID
recordList[n].recordId string 对话ID,由系统生成
recordList[n].role string 对话中的角色
recordList[n].content string 对话内容
recordList[n].conversation string 用户标识
recordList[n].type string 对话数据类型
recordList[n].image string 对话生成的图片链接
recordList[n].triggerSrc string 对话发起来源
recordList[n].replyTo string 对话回复的记录ID
recordList[n].createTime string 对话时间

# AI.bot.sendFeedback()

发送对某条聊天记录的反馈信息。

# 使用示例

const res = await wx.cloud.extend.AI.bot.sendFeedback({
  userFeedback: {
    botId: "botId-xxx",
    recordId: "recordId-xxx",
    comment: "非常棒",
    rating: 5,
    tags: ["优美"],
    aiAnswer: "落英缤纷",
    input: "来个成语",
    type: "upvote",
  },
});

# 类型声明

function sendFeedback(props: { userFeedback: IUserFeedback, botId: string });

# 参数

参数名 必填 类型 说明
props.userFeedback IUserFeedback 用户反馈,详见 IUserFeedback 类型定义
props.botId string 将要反馈的 Agent id

# AI.bot.getFeedBack()

获取已存在的反馈信息。

# 使用示例

const res = await wx.cloud.extend.AI.bot.getFeedBack({
  botId: "botId-xxx",
  from: 0,
  to: 0,
  maxRating: 4,
  minRating: 3,
  pageNumber: 1,
  pageSize: 10,
  sender: "user-a",
  senderFilter: "include",
  type: "upvote",
});

# 类型声明

function getFeedBack(props: {
  botId: string;
  type: string;
  sender: string;
  senderFilter: string;
  minRating: number;
  maxRating: number;
  from: number;
  to: number;
  pageSize: number;
  pageNumber: number;
});

# 参数

参数名 必填 类型 说明
props.botId string Agent id
props.type string 用户反馈类型,点赞 upvote 点踩 downvote
props.sender string 评论创建用户
props.senderFilter string 评论创建用户过滤关系 include:包含 exclude:不包含 equal:等于 unequal:不等于 prefix:前缀
props.minRating number 最低评分
props.maxRating number 最高评分
props.from number 开始时间戳
props.to number 结束时间戳
props.pageSize number 分页大小
props.pageNumber number 分页下标

# 返回值

属性名 类型 说明
feedbackList object[] 反馈查询结果
feedbackList[n].recordId string 对话记录 ID
feedbackList[n].type string 用户反馈类型,点赞 upvote 点踩 downvote
feedbackList[n].botId string Agent ID
feedbackList[n].comment string 用户评论
feedbackList[n].rating number 用户评分
feedbackList[n].tags string[] 用户反馈的标签数组
feedbackList[n].input string 用户输入的问题
feedbackList[n].aiAnswer string Agent 的回答
total number 反馈总数

# AI.bot.getRecommendQuestions()

获取推荐的问题。

# 使用示例

const res = await wx.cloud.extend.AI.bot.getRecommendQuestions({
  data: {
    botId: "xxx-bot-id",
    msg: "你是谁"
  }
})
for await (let x of res.textStream) {
  console.log(x)
}

# 类型声明

function getRecommendQuestions(props: {
  data: {
    botId: string;
    name: string;
    introduction: string;
    agentSetting: string;
    msg: string;
    history: Array<{
      role: string;
      content: string;
    }>;
  },
  onText: OnText,
  onEvent: OnEvent,
  onFinish: OnFinish
});

# 参数

参数名 必填 类型 说明
props.data.botId string Agent id
props.data.name string Agent 名称
props.data.introduction string Agent 简介
props.data.agentSetting string Agent 设定
props.data.msg string 用户发送信息
props.data.history Array 历史对话信息
props.data.history[n].role string 历史信息角色
props.data.history[n].content string 历史信息内容
props.onText (text: string) => unknown; 接收到新文本返回时触发的回调函数,参数为增量的文本
props.onEvent (prop: { data: string }) => unknown; 接收到新事件返回时触发的回调函数,参数为事件,prop.data 为此次事件包含的数据的字符串
props.onFinish (text: string) => unknown; 当本次调用完全结束时触发的回调函数,参数为本次调用返回的完整文本

# AI.bot.uploadFiles()

将云存储中的文件上传至 Agent,用于进行文档聊天。

# 使用示例

await wx.cloud.extend.AI.bot.uploadFiles({
  botId: 'bot-xx',
  fileList: [{
      fileId: 'cloud://xxx.pdf', 
      fileName: 'xxx.pdf', 
      type: 'file'
  }]
})

# 类型声明

function uploadFiles(props: {
  botId: string,
  fileList: Array<{
    fileId: string;
    fileName: string;
    type: string;
  }>
});

# 参数

参数名 必填 类型 说明
props.botId string Agent id
props.fileList Array 文件列表
props.fileList[n].fileId string 文件的云存储 cloud id
props.fileList[n].fileName string 文件名
props.fileList[n].type string 暂时只支持 "file"