微信小程序基础库 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 返回,该接口的返回值对 SSE 做了不同程度的封装,开发者能根据实际需求获取到文本流和完整数据流。
使用示例
const hy = wx.cloud.extend.AI.createModel("hunyuan-exp"); // 创建模型
const res = await hy.streamText({
data: {
model: "hunyuan-turbos-latest",
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-turbos-latest", 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) |