跳到主要内容

概述

提供云开发 AI 接入能力,快速接入大模型和 Agent。


基础使用示例

Publishable Key 可前往 云开发平台/API Key 配置 中生成

类型声明

function ai(): AI;

返回值

返回新创建的 AI 实例。

import cloudbase from "@cloudbase/js-sdk";

// 初始化
const app = cloudbase.init({
env: "your-env-id", // 替换为您的环境ID
region: "ap-shanghai", // 地域,默认为上海
accessKey: "", // 填入生成的 Publishable Key
});

// 如果填入了 accessKey,则不需要此步骤
await app.auth.signInAnonymously();

const ai = app.ai();

AI

用于创建 AI 模型的类。

createModel

function createModel(model: string): ChatModel;

创建指定的 AI 模型。

  • 创建一个新的 AI 模型实例
  • 返回一个实现了 ChatModel 抽象类的模型实例
  • 该实例提供 AI 生成文本相关能力

参数

model
string

模型标识符,如 'hunyuan-exp'、'hunyuan-lite' 等

返回

ChatModel
ChatModel

实现了 ChatModel 抽象类的模型实例,提供 AI 生成文本相关能力

示例

// 创建混元体验版模型
const model = ai.createModel("hunyuan-exp");

// 创建混元轻量版模型
const liteModel = ai.createModel("hunyuan-lite");

bot

挂载了 Bot 类的实例,上面集合了一系列与 Agent 交互的方法。具体可参考 Bot 类 的详细文档。

使用示例

const agentList = await ai.bot.list({ pageNumber: 1, pageSize: 10 });

registerFunctionTool

function registerFunctionTool(functionTool: FunctionTool): void;

注册函数工具。在进行大模型调用时,可以告知大模型可用的函数工具,当大模型的响应被解析为工具调用时,会自动调用对应的函数工具。

参数

functionTool
FunctionTool

要注册的函数工具定义

返回

void
undefined

无返回值

示例

// 定义获取天气的工具
const getWeatherTool = {
name: "get_weather",
description: "返回某个城市的天气信息。调用示例:get_weather({city: '北京'})",
fn: ({ city }) => `${city}的天气是:秋高气爽!!!`,
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "要查询的城市",
},
},
required: ["city"],
},
};

// 注册工具
ai.registerFunctionTool(getWeatherTool);

// 使用工具进行对话
const model = ai.createModel("hunyuan-exp");
const result = await model.generateText({
model: "hunyuan-turbo",
tools: [getWeatherTool],
messages: [
{
role: "user",
content: "请告诉我北京的天气状况",
},
],
});

console.log(result.text);

ChatModel

这个抽象类描述了 AI 生文模型类提供的接口。

generateText

function generateText(data: BaseChatModelInput): Promise<{
rawResponses: Array<unknown>;
text: string;
messages: Array<ChatModelMessage>;
usage: Usage;
error?: unknown;
}>;

调用大模型生成文本。

  • 向大模型发送消息并获取生成的文本响应
  • 支持完整的对话上下文管理
  • 返回详细的调用信息和 token 消耗统计

参数

data
BaseChatModelInput

大模型输入参数,包含模型配置和消息内容

返回

Promise
object

大模型生成文本的响应结果

示例

const model = ai.createModel("hunyuan-exp");
const result = await model.generateText({
model: "hunyuan-lite",
messages: [{ role: "user", content: "你好,请你介绍一下李白" }],
});

console.log("生成的文本:", result.text);
console.log("消耗的token:", result.usage);

streamText

function streamText(data: BaseChatModelInput): Promise<StreamTextResult>;

以流式调用大模型生成文本。

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

参数

data
BaseChatModelInput

大模型输入参数,包含模型配置和消息内容

返回

Promise
StreamTextResult

流式文本生成的结果,包含文本流和数据流

示例

const model = ai.createModel("hunyuan-exp");
const result = await model.streamText({
model: "hunyuan-lite",
messages: [{ role: "user", content: "你好,请你介绍一下李白" }],
});

// 获取文本流
for await (let chunk of result.textStream) {
console.log("收到文本块:", chunk);
}

// 1
// 加
// 1
// 的结果
// 是
// 2
// 。

// 获取数据流
for await (let data of result.dataStream) {
console.log("收到数据块:", data);
}

// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hunyuan-lite", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hunyuan-lite", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hunyuan-lite", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hunyuan-lite", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hunyuan-lite", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hunyuan-lite", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hunyuan-lite", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hunyuan-lite", version: "202404011000", choices: Array(1), …}

Bot

用于与 Agent 交互的类。

get

function get(props: { botId: string }): Promise<BotInfo>;

获取某个 Agent 的信息。

  • 根据 Agent ID 获取详细的 Agent 信息
  • 返回 Agent 的基本配置、欢迎语、头像等完整信息

参数

props
object

获取 Agent 信息的参数

返回

Promise
BotInfo

Agent 的详细信息

示例

const res = await ai.bot.get({ botId: "botId-xxx" });
console.log("Agent 信息:", res);

list

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

批量获取多个 Agent 的信息。

  • 查询和筛选可用的 Agent 列表
  • 支持分页查询和条件筛选
  • 返回 Agent 的基本信息和配置详情
  • 适用于构建 Agent 选择器、Agent 管理界面等应用

参数

props
object

查询 Agent 列表的参数

返回

Promise
AgentListResult

Agent 列表查询结果

示例

const agentList = await ai.bot.list({
pageNumber: 1,
pageSize: 10,
name: "",
enable: true,
information: "",
introduction: "",
});

console.log("Agent 总数:", agentList.total);
console.log("Agent 列表:", agentList.botList);

sendMessage

function sendMessage(props: {
botId: string;
msg: string;
history: Array<{
role: string;
content: string;
}>;
}): Promise<StreamResult>;

与 Agent 进行对话。

  • 响应会通过 SSE 返回,该接口的返回值对 SSE 做了不同程度的封装,开发者能根据实际需求获取到文本流和完整数据流。
  • 支持多轮对话上下文管理
  • 返回流式响应,支持实时获取 Agent 回复
  • 适用于构建聊天机器人、智能助手等应用

参数

props
object

发送消息的参数

返回

Promise
StreamResult

流式对话结果,包含文本流和数据流

示例

const res = await ai.bot.sendMessage({
botId: "botId-xxx",
history: [{ content: "你是李白。", role: "user" }],
msg: "你好",
});

// 获取文本流
for await (let text of res.textStream) {
console.log("Agent 回复:", text);
}

// 获取数据流
for await (let data of res.dataStream) {
console.log("详细数据:", data);
}

getChatRecords

function getChatRecords(props: {
botId: string;
sort: string;
pageSize: number;
pageNumber: number;
}): Promise<ChatRecordsResult>;

获取聊天记录。

  • 获取指定 Agent 的历史聊天记录
  • 支持分页查询和排序
  • 返回完整的对话历史信息
  • 适用于构建聊天历史查看功能

参数

props
object

获取聊天记录的参数

返回

Promise
ChatRecordsResult

聊天记录查询结果

示例

const records = await ai.bot.getChatRecords({
botId: "botId-xxx",
pageNumber: 1,
pageSize: 10,
sort: "asc",
});

console.log("总记录数:", records.total);
console.log("记录列表:", records.recordList);

sendFeedback

function sendFeedback(props: {
userFeedback: IUserFeedback;
botId: string;
}): Promise<void>;

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

  • 对指定的聊天记录进行评价和反馈
  • 支持评分、评论、标签等多种反馈方式
  • 帮助改进 Agent 的回答质量
  • 适用于构建用户反馈系统

参数

props
object

发送反馈的参数

返回

Promise
void

无返回值

示例

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

console.log("反馈发送成功");

getFeedback

function getFeedback(props: {
botId: string;
type: string;
sender: string;
senderFilter: string;
minRating: number;
maxRating: number;
from: number;
to: number;
pageSize: number;
pageNumber: number;
}): Promise<FeedbackResult>;

获取已存在的反馈信息。

  • 查询指定 Agent 的用户反馈记录
  • 支持多种过滤条件:时间范围、评分范围、用户过滤等
  • 返回分页的反馈结果和统计信息
  • 适用于构建反馈分析和管理系统

参数

props
object

查询反馈信息的参数

返回

Promise
FeedbackResult

反馈查询结果

示例

const res = await 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",
});

console.log("反馈总数:", res.total);
console.log("反馈列表:", res.feedbackList);

uploadFiles

function uploadFiles(props: {
botId: string;
fileList: Array<{
fileId: string;
fileName: string;
type: "file";
}>;
}): Promise<void>;

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

  • 支持将云存储中的文件上传到指定的 Agent
  • 上传后的文件可用于文档聊天功能
  • 支持批量上传多个文件
  • 适用于构建文档问答、文件分析等应用场景

参数

props
object

文件上传参数

返回

Promise
void

无返回值

示例

// 上传单个文件到指定 Agent
await ai.bot.uploadFiles({
botId: "botId-xxx",
fileList: [
{
fileId: "cloud://document.docx",
fileName: "document.docx",
type: "file",
},
],
});

console.log("文件上传成功");

getRecommendQuestions

function getRecommendQuestions(props: {
botId: string;
name: string;
introduction: string;
agentSetting: string;
msg: string;
history: Array<{
role: string;
content: string;
}>;
}): Promise<StreamResult>;

获取推荐的问题,基于对话上下文智能生成相关问题建议。

  • 根据当前对话内容和历史记录智能推荐相关问题
  • 支持流式返回,实时获取推荐问题
  • 适用于构建智能对话助手、聊天机器人等应用
  • 帮助用户发现更多相关话题,提升对话体验

参数

props
object

获取推荐问题的参数

返回

Promise
StreamResult

流式返回的推荐问题结果

示例

// 获取推荐问题
const res = await ai.bot.getRecommendQuestions({
botId: "botId-xxx",
name: "智能助手",
introduction: "我是一个智能对话助手",
agentSetting: "专业、友好的AI助手",
msg: "你好,我想了解人工智能",
history: [
{ content: "你是谁啊", role: "user" },
{ content: "我是一个智能助手,可以帮助你解答各种问题", role: "assistant" },
],
});

// 流式获取推荐问题
for await (let question of res.textStream) {
console.log("推荐问题:", question);
}

createConversation

function createConversation(props: {
botId: string;
title?: string;
}): Promise<IConversation>;

创建与 Agent 的新对话,建立独立的对话会话。

  • 为指定的 Agent 创建新的对话会话
  • 支持自定义对话标题,便于管理和识别
  • 每个对话会话独立存储对话历史
  • 适用于多用户、多场景的对话管理需求

参数

props
object

创建对话的参数

返回

Promise
IConversation

创建的对话信息

示例

// 创建新的对话会话
const conversation = await ai.bot.createConversation({
botId: "botId-xxx",
title: "技术咨询对话",
});

console.log("对话创建成功:", conversation.conversationId);
console.log("对话标题:", conversation.title);

getConversation

function getConversation(props: {
botId: string;
pageSize?: number;
pageNumber?: number;
isDefault?: boolean;
}): Promise<ConversationListResult>;

获取 Agent 的对话列表,支持分页查询和条件筛选。

  • 查询指定 Agent 的所有对话记录
  • 支持分页查询,便于管理大量对话
  • 可筛选默认对话或所有对话
  • 适用于对话管理、历史记录查看等场景

参数

props
object

获取对话列表的参数

返回

Promise
ConversationListResult

对话列表查询结果

示例

// 获取对话列表
const result = await ai.bot.getConversation({
botId: "botId-xxx",
pageSize: 10,
pageNumber: 1,
isDefault: false,
});

console.log(`共有 ${result.total} 个对话`);
result.conversations.forEach((conversation, index) => {
console.log(
`${index + 1}. ${conversation.title} (${conversation.messageCount} 条消息)`
);
});

deleteConversation

function deleteConversation(props: {
botId: string;
conversationId: string;
}): Promise<void>;

删除指定的对话会话,清理对话历史记录。

  • 永久删除指定的对话会话
  • 清理对话中的所有消息记录
  • 释放存储空间,优化系统性能
  • 适用于对话管理、数据清理等场景

参数

props
object

删除对话的参数

返回

Promise
void

删除操作完成,无返回值

示例

// 删除指定的对话
await ai.bot.deleteConversation({
botId: "botId-xxx",
conversationId: "conv-123",
});

console.log("对话删除成功");

speechToText

function speechToText(props: {
botId: string;
engSerViceType: string;
voiceFormat: string;
url: string;
isPreview?: boolean;
}): Promise<SpeechToTextResult>;

将语音文件转换为文字,支持多种音频格式和语言识别。

  • 支持多种音频格式:MP3、WAV、AAC 等
  • 支持多种语言识别引擎
  • 可处理本地或远程音频文件
  • 适用于语音助手、会议记录、语音笔记等场景

参数

props
object

语音转文字的参数

返回

Promise
SpeechToTextResult

语音识别结果

示例

// 将语音文件转换为文字
const result = await ai.bot.speechToText({
botId: "speech-bot-id",
engSerViceType: "16k_zh",
voiceFormat: "mp3",
url: "https://example.com/audio.mp3",
});

console.log("识别结果:", result.text);
console.log("置信度:", result.confidence);
console.log("音频时长:", result.duration, "秒");
console.log("识别语言:", result.language);

textToSpeech

function textToSpeech(props: {
botId: string;
voiceType: number;
text: string;
isPreview?: boolean;
}): Promise<TextToSpeechResult>;

将文本转换为语音,支持多种语音类型和音色选择。

  • 支持多种语音类型和音色选择
  • 可调节语速、音调等参数
  • 支持长文本分段转换
  • 适用于语音播报、有声读物、语音助手等场景

参数

props
object

文字转语音的参数

返回

Promise
TextToSpeechResult

文字转语音的结果

示例

// 将文本转换为语音
const result = await ai.bot.textToSpeech({
botId: "tts-bot-id",
voiceType: 1, // 标准女声
text: "你好,我是AI语音助手,很高兴为您服务。",
});

console.log("语音合成完成:");
console.log("音频地址:", result.audioUrl);
console.log("音频时长:", result.duration, "秒");
console.log("文件格式:", result.format);
console.log("文件大小:", result.size, "字节");

getTextToSpeechResult

function getTextToSpeechResult(props: {
botId: string;
taskId: string;
isPreview?: boolean;
}): Promise<TextToSpeechResult>;

获取文字转语音任务的结果,查询语音合成任务的完成状态和生成的音频文件。

  • 查询异步语音合成任务的状态和结果
  • 获取生成的音频文件信息
  • 支持预览模式和正式模式
  • 适用于批量语音合成、长文本处理等异步场景

参数

props
object

获取语音合成结果的参数

返回

Promise
TextToSpeechResult

语音合成任务结果

示例

// 查询语音合成任务结果
const result = await ai.bot.getTextToSpeechResult({
botId: "tts-bot-id",
taskId: "task-123456",
});

console.log("任务状态:", result.status);
console.log("任务进度:", result.progress, "%");

if (result.status === "completed") {
console.log("音频地址:", result.audioUrl);
console.log("音频时长:", result.duration, "秒");
console.log("文件格式:", result.format);
console.log("文件大小:", result.size, "字节");
} else if (result.status === "processing") {
console.log("任务仍在处理中,请稍后重试");
} else if (result.status === "failed") {
console.log("任务处理失败");
}

完整类型定义

IBotCreateConversation

interface IBotCreateConversation {
botId: string;
title?: string;
}

IBotGetConversation

interface IBotGetConversation {
botId: string;
pageSize?: number;
pageNumber?: number;
isDefault?: boolean;
}

IBotDeleteConversation

interface IBotDeleteConversation {
botId: string;
conversationId: string;
}

IBotSpeechToText

interface IBotSpeechToText {
botId: string;
engSerViceType: string;
voiceFormat: string;
url: string;
isPreview?: boolean;
}

IBotTextToSpeech

interface IBotTextToSpeech {
botId: string;
voiceType: number;
text: string;
isPreview?: boolean;
}

IBotGetTextToSpeechResult

interface IBotGetTextToSpeechResult {
botId: string;
taskId: string;
isPreview?: boolean;
}

BaseChatModelInput

interface BaseChatModelInput {
model: string;
messages: Array<ChatModelMessage>;
temperature?: number;
topP?: number;
tools?: Array<FunctionTool>;
toolChoice?: "none" | "auto" | "custom";
maxSteps?: number;
onStepFinish?: (prop: IOnStepFinish) => unknown;
}
BaseChatModelInput 属性名类型说明
modelstring模型名称。
messagesArray<ChatModelMessage>消息列表。
temperaturenumber采样温度,控制输出的随机性。
topPnumber温度采样,即模型考虑概率质量为 top_p 的标记的结果。
toolsArray<FunctionTool>大模型可用的工具列表。
toolChoicestring指定大模型选择工具的方式。
maxStepsnumber请求大模型的最大次数。
onStepFinish(prop: IOnStepFinish) => unknown当对大模型的一次请求完成时,出发的回调函数。

BotInfo

interface BotInfo {
botId: string;
name: string;
introduction: string;
agentSetting: string;
welcomeMessage: string;
avatar: string;
background: string;
tags: Array<string>;
isNeedRecommend: boolean;
knowledgeBase: Array<string>;
type: string;
initQuestions: Array<string>;
enable: true;
}

IUserFeedback

interface IUserFeedback {
recordId: string;
type: string;
botId: string;
comment: string;
rating: number;
tags: Array<string>;
input: string;
aiAnswer: string;
}

ChatModelMessage

type ChatModelMessage =
| UserMessage
| SystemMessage
| AssistantMessage
| ToolMessage;

UserMessage

type UserMessage = {
role: "user";
content: string;
};

SystemMessage

type SystemMessage = {
role: "system";
content: string;
};

AssistantMessage

type AssistantMessage = {
role: "assistant";
content?: string;
tool_calls?: Array<ToolCall>;
};

ToolMessage

type ToolMessage = {
role: "tool";
tool_call_id: string;
content: string;
};

ToolCall

export type ToolCall = {
id: string;
type: string;
function: { name: string; arguments: string };
};

FunctionTool

工具定义类型。

type FunctionTool = {
name: string;
description: string;
fn: CallableFunction;
parameters: object;
};
FunctionTool 属性名类型说明
namestring工具名称。
descriptionstring工具的描述。清楚的工具描述有助于大模型认识工具的用途。
fnCallableFunction工具的执行函数。当 AI SDK 解析出大模型的响应需要该工具调用时,会调用此函数,并将结果返回给大模型。
parametersobject工具执行函数的入参。需要使用 JSON Schema 的格式定义入参。

IOnStepFinish

大模型响应后出发的回调函数的入参类型。

interface IOnStepFinish {
messages: Array<ChatModelMessage>;
text?: string;
toolCall?: ToolCall;
toolResult?: unknown;
finishReason?: string;
stepUsage?: Usage;
totalUsage?: Usage;
}
IOnStepFinish 属性名类型说明
messagesArray<ChatModelMessage>到当前步骤为止所有的消息列表。
textstring当前响应的文本。
toolCallToolCall当前响应调用的工具。
toolResultunknown对应的工具调用结果。
finishReasonstring大模型推理结束的原因。
stepUsageUsage当前步骤所花费的 token。
totalUsageUsage到当前步骤为止所花费的总 token。

Usage

type Usage = {
completion_tokens: number;
prompt_tokens: number;
total_tokens: number;
};

IConversation

Agent 会话。

interface IConversation {
id: string;
envId: string;
ownerUin: string;
userId: string;
conversationId: string;
title: string;
startTime: string; // date-time format
createTime: string;
updateTime: string;
}