跳到主要内容

微信小程序基础库 API

微信小程序基础库从 3.7.1 版本开始内置了云开发 AI+ 能力,开发者可以直接通过小程序中的 wx.cloud.extend.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 返回,该接口的返回值对 SEE 做了不同程度的封装,开发者能根据实际需求获取到文本流和完整数据流。

使用示例

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.dataunknown{model: "hunyuan-lite", messages: [{ role: "user", content: "你好,请你介绍一下李白" }]}各家大模型的调用参数不同,请根据实际调用模型传入正确的参数。
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 属性名类型说明
textStreamAsyncIterable<string>以流式返回的大模型生成文本,可参考使用示例获取到生成的增量文本。
eventStreamAsyncIterable<{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>;

参数

参数名必填类型示例说明
dataunknown{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.botIdstring要获取信息的 Agent 的 id

返回值

属性名类型示例说明
botIdstring"bot-27973647"Agent ID
namestring"信达雅翻译"Agent 名称
introductionstringAgent 简介
welcomeMessagestringAgent 欢迎语
avatarstringAgent 头像链接
backgroundstringAgent 聊天背景图链接
isNeedRecommendbooleanAgent 回答后是否推荐问题
typestringAgent 类型

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.pageNumbernumber分页大小
props.pageSizenumber分页下标
props.enablebooleanAgent 是否启用
props.namestringAgent 名字,用于模糊查询
props.informationstringAgent 信息,用于模糊查询
props.introductionstringAgent 简介,用于模糊查询

返回值

属性名类型示例说明
totalnumber---Agent 总数
botListArray<object>Agent 列表
botList[n].botIdstring"bot-27973647"Agent ID
botList[n].namestring"信达雅翻译"Agent 名称
botList[n].introductionstringAgent 简介
botList[n].welcomeMessagestringAgent 欢迎语
botList[n].avatarstringAgent 头像链接
botList[n].backgroundstringAgent 聊天背景图链接
botList[n].isNeedRecommendbooleanAgent 回答后是否推荐问题
botList[n].typestringAgent 类型

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;
}>;
},
onText: OnText,
onEvent: OnEvent,
onFinish: OnFinish
});

参数

参数名必填类型说明
props.data.botIdnumberAgent id
props.data.msgnumber此次对话要发送的消息
props.data.historyboolean在此次对话前发生的聊天记录
props.data.history[n].rolestring本聊天信息的发送角色
props.data.history[n].contentstring本聊天信息的内容
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.botIdstringAgent id
props.sortstring排序方式
props.pageSizenumber分页大小
props.pageNumbernumber分页下标

返回值

属性名类型说明
totalnumber对话总数
recordListArray<object>对话总数
recordList[n].botIdstringAgent ID
recordList[n].recordIdstring对话ID,由系统生成
recordList[n].rolestring对话中的角色
recordList[n].contentstring对话内容
recordList[n].conversationstring用户标识
recordList[n].typestring对话数据类型
recordList[n].imagestring对话生成的图片链接
recordList[n].triggerSrcstring对话发起来源
recordList[n].replyTostring对话回复的记录ID
recordList[n].createTimestring对话时间

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

参数

参数名必填类型说明
props.userFeedbackIUserFeedback用户反馈,详见 IUserFeedback 类型定义
props.botIdstring将要获取聊天记录的 Agent 的 id
props.sortstring排序方式
props.pageSizenumber分页大小
props.pageNumbernumber分页下标

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 sendFeedback(props: {
botId: string;
type: string;
sender: string;
senderFilter: string;
minRating: number;
maxRating: number;
from: number;
to: number;
pageSize: number;
pageNumber: number;
});

参数

参数名必填类型说明
props.botIdstringAgent id
props.typestring用户反馈类型,点赞 upvote 点踩 downvote
props.senderstring评论创建用户
props.senderFilterstring评论创建用户过滤关系 include:包含 exclude:不包含 equal:等于 unequal:不等于 prefix:前缀
props.minRatingnumber最低评分
props.maxRatingnumber最高评分
props.fromnumber开始时间戳
props.tonumber结束时间戳
props.pageSizenumber分页大小
props.pageNumbernumber分页下标

返回值

属性名类型说明
feedbackListobject[]反馈查询结果
feedbackList[n].recordIdstring对话记录 ID
feedbackList[n].typestring用户反馈类型,点赞 upvote 点踩 downvote
feedbackList[n].botIdstringAgent ID
feedbackList[n].commentstring用户评论
feedbackList[n].ratingnumber用户评分
feedbackList[n].tagsstring[]用户反馈的标签数组
feedbackList[n].inputstring用户输入的问题
feedbackList[n].aiAnswerstringAgent 的回答
totalnumber反馈总数

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.botIdstringAgent id
props.data.namestringAgent 名称
props.data.introductionstringAgent 简介
props.data.agentSettingstringAgent 设定
props.data.msgstring用户发送信息
props.data.historyArray历史对话信息
props.data.history[n].rolestring历史信息角色
props.data.history[n].contentstring历史信息内容
props.onText(text: string) => unknown;接收到新文本返回时触发的回调函数,参数为增量的文本
props.onEvent(prop: { data: string }) => unknown;接收到新事件返回时触发的回调函数,参数为事件,prop.data 为此次事件包含的数据的字符串
props.onFinish(text: string) => unknown;当本次调用完全结束时触发的回调函数,参数为本次调用返回的完整文本