概述
提供云开发 AI 接入能力,快速接入大模型和 Agent。
基础使用示例
- 初始化配置
- 基础文本生成
- 流式文本生成
- 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();
// 基础文本生成示例
async function generateText() {
const model = ai.createModel("cloudbase");
const result = await model.generateText({
model: "hy3-preview",
messages: [{ role: "user", content: "你好,请你介绍一下李白" }],
});
console.log("生成的文本:", result.text);
console.log("消耗的token:", result.usage);
}
// 流式文本生成示例
async function streamText() {
const model = ai.createModel("cloudbase");
const result = await model.streamText({
model: "hy3-preview",
messages: [{ role: "user", content: "1+1等于多少" }],
});
for await (let chunk of result.textStream) {
console.log("收到文本块:", chunk);
}
}
// Agent 对话示例
async function chatWithAgent() {
const res = await ai.bot.sendMessage({
botId: "botId-xxx",
msg: "你好,请介绍一下你自己",
history: [],
});
for await (let text of res.textStream) {
console.log("Agent 回复:", text);
}
}
AI
用于创建 AI 模型的类。
createModel
function createModel(model: string): ChatModel;
创建指定的 AI 模型。
- 创建一个新的 AI 模型实例
- 返回一个实现了 ChatModel 抽象类的模型实例
- 该实例提供 AI 生成文本相关能力
参数
model
string
模型标识符,如 'cloudbase'
返回
ChatModel
ChatModel
实现了 ChatModel 抽象类的模型实例,提供 AI 生成文本相关能力
示例
- 基础使用
const model = ai.createModel("cloudbase");
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("cloudbase");
const result = await model.generateText({
model: "hy3-preview",
tools: [getWeatherTool],
messages: [
{
role: "user",
content: "请告诉我北京的天气状况",
},
],
});
console.log(result.text);
// 多工具集成系统
class ToolIntegrationSystem {
private registeredTools: Map<string, FunctionTool> = new Map();
// 注册多个工具
registerTools(tools: FunctionTool[]): void {
tools.forEach((tool) => {
ai.registerFunctionTool(tool);
this.registeredTools.set(tool.name, tool);
console.log(`✓ 工具注册成功: ${tool.name}`);
});
}
// 获取所有可用工具
getAvailableTools(): FunctionTool[] {
return Array.from(this.registeredTools.values());
}
// 智能对话助手
async smartAssistant(question: string): Promise<string> {
const model = ai.createModel("cloudbase");
const result = await model.generateText({
model: "hy3-preview",
tools: this.getAvailableTools(),
messages: [
{
role: "user",
content: question,
},
],
});
return result.text;
}
// 工具使用统计
getToolUsageStats(): Map<string, number> {
const stats = new Map<string, number>();
// 在实际应用中,这里可以记录工具调用次数
return stats;
}
}
// 定义多个工具
const tools = [
{
name: "get_weather",
description: "获取城市天气信息",
fn: ({ city }) => `${city}的天气:晴,25℃`,
parameters: {
type: "object",
properties: { city: { type: "string", description: "城市名称" } },
required: ["city"],
},
},
{
name: "calculate",
description: "执行数学计算",
fn: ({ expression }) => `计算结果:${eval(expression)}`,
parameters: {
type: "object",
properties: { expression: { type: "string", description: "数学表达式" } },
required: ["expression"],
},
},
{
name: "search_info",
description: "搜索信息",
fn: ({ keyword }) => `搜索结果:关于${keyword}的信息`,
parameters: {
type: "object",
properties: { keyword: { type: "string", description: "搜索关键词" } },
required: ["keyword"],
},
},
];
// 使用示例
const toolSystem = new ToolIntegrationSystem();
toolSystem.registerTools(tools);
// 智能对话
const answer = await toolSystem.smartAssistant(
"计算一下 15*8+20 的结果,并告诉我北京的天气"
);
console.log("助手回答:", answer);
// 动态工具管理系统
class DynamicToolManager {
private toolRegistry: Map<string, FunctionTool> = new Map();
// 动态注册工具
registerTool(tool: FunctionTool): void {
ai.registerFunctionTool(tool);
this.toolRegistry.set(tool.name, tool);
console.log(`工具注册: ${tool.name}`);
}
// 动态卸载工具
unregisterTool(toolName: string): boolean {
if (this.toolRegistry.has(toolName)) {
this.toolRegistry.delete(toolName);
console.log(`工具卸载: ${toolName}`);
return true;
}
return false;
}
// 根据上下文动态选择工具
async contextualAssistant(
context: string,
question: string
): Promise<string> {
const relevantTools = this.selectRelevantTools(context, question);
const model = ai.createModel("cloudbase");
const result = await model.generateText({
model: "hy3-preview",
tools: relevantTools,
messages: [
{
role: "system",
content: `当前上下文:${context}`,
},
{
role: "user",
content: question,
},
],
});
return result.text;
}
// 根据上下文选择相关工具
private selectRelevantTools(
context: string,
question: string
): FunctionTool[] {
const tools = Array.from(this.toolRegistry.values());
// 简单的关键词匹配算法
const keywords = [...context.split(" "), ...question.split(" ")];
return tools.filter((tool) => {
return keywords.some((keyword) =>
tool.description.toLowerCase().includes(keyword.toLowerCase())
);
});
}
// 热更新工具
updateTool(toolName: string, updatedTool: FunctionTool): boolean {
if (this.toolRegistry.has(toolName)) {
this.unregisterTool(toolName);
this.registerTool(updatedTool);
console.log(`工具更新: ${toolName}`);
return true;
}
return false;
}
// 获取工具列表
listTools(): string[] {
return Array.from(this.toolRegistry.keys());
}
}
// 使用示例
const toolManager = new DynamicToolManager();
// 注册初始工具
toolManager.registerTool({
name: "weather",
description: "获取天气信息",
fn: ({ city }) => `${city}天气:晴`,
parameters: {
type: "object",
properties: { city: { type: "string" } },
required: ["city"],
},
});
// 动态添加新工具
toolManager.registerTool({
name: "translate",
description: "翻译文本",
fn: ({ text, to }) => `${text} 翻译为 ${to}:示例翻译结果`,
parameters: {
type: "object",
properties: {
text: { type: "string" },
to: { type: "string" },
},
required: ["text", "to"],
},
});
// 上下文感知对话
const answer = await toolManager.contextualAssistant(
"天气和翻译相关的问题",
"把'你好'翻译成英语,并告诉我上海的天气"
);
console.log("智能回答:", answer);
// 查看可用工具
console.log("可用工具:", toolManager.listTools());
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("cloudbase");
const result = await model.generateText({
model: "hy3-preview",
messages: [{ role: "user", content: "你好,请你介绍一下李白" }],
});
console.log("生成的文本:", result.text);
console.log("消耗的token:", result.usage);
const model = ai.createModel("cloudbase");
// 多轮对话示例
const messages = [
{ role: "user", content: "你好,我想了解中国古代文学" },
{
role: "assistant",
content:
"中国古代文学源远流长,从诗经楚辞到唐诗宋词,都有着丰富的文化内涵。",
},
{ role: "user", content: "那你 能介绍一下唐诗的特点吗?" },
];
const result = await model.generateText({
model: "hy3-preview",
messages: messages,
temperature: 0.7,
topP: 0.9,
});
console.log("唐诗介绍:", result.text);
// 注册天气查询工具
ai.registerFunctionTool({
name: "get_weather",
description: "查询城市天气信息",
fn: ({ city }) => `${city}的天气是:晴朗,25℃`,
parameters: {
type: "object",
properties: {
city: {
type: "string",
description: "要查询的城市名称",
},
},
required: ["city"],
},
});
const model = ai.createModel("cloudbase");
const result = await model.generateText({
model: "hy3-preview",
messages: [{ role: "user", content: "请告诉我北京的天气状况" }],
tools: [getWeatherTool],
toolChoice: "auto",
});
console.log("大模型响应:", result.text);
streamText
function streamText(data: BaseChatModelInput): Promise<StreamTextResult>;
以流式调用大模型生成文本。
- 流式调用时,生成的文本及其他响应数据会通过 SSE 返回,该接口的返回值对 SSE 做了不同程度的封装,开发者能根据实际需求获取到文本流和完整数据流。
- 以流式方式调用大模型生成文本,支持实时获取增量内容
参数
data
BaseChatModelInput
大模型输入参数,包含模型配置和消息内容
返回
Promise
StreamTextResult
流式文本生成的结果,包含文本流和数据流
示例
- 基础流式调用
- 实时显示应用
- 进度监控
const model = ai.createModel("cloudbase");
const result = await model.streamText({
model: "hy3-preview",
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: "hy3-preview", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hy3-preview", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hy3-preview", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hy3-preview", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hy3-preview", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hy3-preview", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hy3-preview", version: "202404011000", choices: Array(1), …}
// {created: 1723013866, id: "a95a54b5c5d2144eb700e60d0dfa5c98", model: "hy3-preview", version: "202404011000", choices: Array(1), …}
// 在网页中实时显示流式内容
async function displayStreamingText(question: string) {
const model = ai.createModel("cloudbase");
const result = await model.streamText({
model: "hy3-preview",
messages: [{ role: "user", content: question }],
});
const outputElement = document.getElementById("output");
outputElement.innerHTML = "";
for await (let chunk of result.textStream) {
outputElement.innerHTML += chunk;
// 滚动到最新内容
outputElement.scrollTop = outputElement.scrollHeight;
}
}
// 使用示例
displayStreamingText("请详细介绍一下唐诗的发展历程");
// 监控流式生成进度
async function monitorStreamProgress(question: string) {
const model = ai.createModel("cloudbase");
const result = await model.streamText({
model: "hy3-preview",
messages: [{ role: "user", content: question }],
});
let totalChunks = 0;
let startTime = Date.now();
for await (let chunk of result.textStream) {
totalChunks++;
console.log(`第${totalChunks}个文本块: ${chunk}`);
}
const endTime = Date.now();
console.log(
`生成完成,共${totalChunks}个文本块,耗时${endTime - startTime}ms`
);
// 获取完整消息和token统计
const messages = await result.messages;
const usage = await result.usage;
console.log("完整对话:", messages);
console.log("Token消耗:", usage);
}
Bot
用于与 Agent 交互的类。
get
function get(props: { botId: string }): Promise<BotInfo>;
获取某个 Agent 的信息。
- 根据 Agent ID 获取详细的 Agent 信息
- 返回 Agent 的基本配置、欢迎语、头像等完整信息
参数
props
object
获取 Agent 信息的参数
返回
Promise
BotInfo
Agent 的详细信息
示例
- 基础使用
- 应用启动配置
- 多 Agent 管理
const res = await ai.bot.get({ botId: "botId-xxx" });
console.log("Agent 信息:", res);
// 应用启动时加载 Agent 配置
async function initializeAgent(botId: string) {
try {
const agentInfo = await ai.bot.get({ botId });
// 设置应用界面
document.title = `${agentInfo.name} - AI助手`;
// 显示欢迎信息
const welcomeElement = document.getElementById("welcome");
welcomeElement.innerHTML = `
<div class="agent-header">
<img src="${agentInfo.avatar}" alt="${agentInfo.name}" class="avatar" />
<h2>${agentInfo.name}</h2>
<p>${agentInfo.introduction}</p>
</div>
`;
// 设置聊天背景
if (agentInfo.background) {
document.body.style.backgroundImage = `url(${agentInfo.background})`;
}
return agentInfo;
} catch (error) {
console.error("加载 Agent 配置失败:", error);
throw error;
}
}
// 使用示例
initializeAgent("bot-27973647");
// 管理多个 Agent 的配置
class AgentManager {
private agents: Map<string, BotInfo> = new Map();
async loadAgent(botId: string) {
if (this.agents.has(botId)) {
return this.agents.get(botId);
}
const agentInfo = await ai.bot.get({ botId });
this.agents.set(botId, agentInfo);
return agentInfo;
}
getAgentList() {
return Array.from(this.agents.values());
}
async switchAgent(botId: string) {
const agentInfo = await this.loadAgent(botId);
// 更新界面显示
this.updateUI(agentInfo);
return agentInfo;
}
private updateUI(agentInfo: BotInfo) {
// 更新界面元素
console.log("切换到 Agent:", agentInfo.name);
}
}
// 使用示例
const agentManager = new AgentManager();
await agentManager.loadAgent("bot-27973647");
await agentManager.loadAgent("bot-27973648");
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 列表查询结果
示例
- 基础查询
- 条件筛选
- 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);
// 根据条件筛选 Agent
async function searchAgents(keyword: string, page: number = 1) {
const result = await ai.bot.list({
pageNumber: page,
pageSize: 20,
name: keyword,
enable: true,
information: keyword,
introduction: keyword,
});
console.log(`找到 ${result.total} 个匹配的 Agent`);
result.botList.forEach((agent) => {
console.log(`- ${agent.name}: ${agent.introduction}`);
});
return result;
}
// 使用示例
await searchAgents("翻译"); // 搜索翻译相关的 Agent
await searchAgents("客服", 2); // 搜索客服相关的 Agent,第二页
// 构建 Agent 选择器界面
class AgentSelector {
private currentPage: number = 1;
private pageSize: number = 12;
async loadAgents(keyword: string = "") {
const result = await ai.bot.list({
pageNumber: this.currentPage,
pageSize: this.pageSize,
name: keyword,
enable: true,
information: keyword,
introduction: keyword,
});
this.displayAgents(result.botList);
this.updatePagination(result.total);
return result;
}
private displayAgents(agents: any[]) {
const container = document.getElementById("agent-list");
container.innerHTML = "";
agents.forEach((agent) => {
const agentCard = document.createElement("div");
agentCard.className = "agent-card";
agentCard.innerHTML = `
<img src="${agent.avatar}" alt="${agent.name}" class="agent-avatar" />
<div class="agent-info">
<h3>${agent.name}</h3>
<p>${agent.introduction}</p>
<button onclick="selectAgent('${agent.botId}')">选择</button>
</div>
`;
container.appendChild(agentCard);
});
}
private updatePagination(total: number) {
const pagination = document.getElementById("pagination");
const totalPages = Math.ceil(total / this.pageSize);
pagination.innerHTML = `
<button onclick="prevPage()" ${
this.currentPage <= 1 ? "disabled" : ""
}>上一页</button>
<span>第 ${this.currentPage} 页,共 ${totalPages} 页</span>
<button onclick="nextPage()" ${
this.currentPage >= totalPages ? "disabled" : ""
}>下一页</button>
`;
}
async nextPage() {
this.currentPage++;
await this.loadAgents();
}
async prevPage() {
if (this.currentPage > 1) {
this.currentPage--;
await this.loadAgents();
}
}
selectAgent(botId: string) {
console.log("选择的 Agent ID:", botId);
// 开始与选中的 Agent 对话
this.startChat(botId);
}
private startChat(botId: string) {
// 实现与 Agent 开始对话的逻辑
console.log("开始与 Agent 对话:", botId);
}
}
// 使用示例
const selector = new AgentSelector();
await selector.loadAgents(); // 加载第一页 Agent
// 搜索特定类型的 Agent
await selector.loadAgents("写作助手");
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);
}
// 多轮对话示例
class ChatSession {
private history: Array<{ role: string; content: string }> = [];
async sendMessage(botId: string, message: string) {
const res = await ai.bot.sendMessage({
botId: botId,
history: this.history,
msg: message,
});
let fullResponse = "";
// 实时显示 回复
for await (let chunk of res.textStream) {
fullResponse += chunk;
this.updateDisplay(fullResponse);
}
// 记录对话历史
this.history.push({ role: "user", content: message });
this.history.push({ role: "assistant", content: fullResponse });
return fullResponse;
}
private updateDisplay(text: string) {
const chatArea = document.getElementById("chat-area");
chatArea.innerHTML = text;
chatArea.scrollTop = chatArea.scrollHeight;
}
clearHistory() {
this.history = [];
}
getHistory() {
return this.history;
}
}
// 使用示例
const chatSession = new ChatSession();
await chatSession.sendMessage("botId-xxx", "你好,请介绍一下你自己");
await chatSession.sendMessage("botId-xxx", "你能帮我写一首诗吗?");
// 构建实时聊天应用
class ChatApp {
private botId: string;
private conversationId: string;
constructor(botId: string) {
this.botId = botId;
this.setupEventListeners();
}
private setupEventListeners() {
const sendBtn = document.getElementById("send-btn");
const input = document.getElementById("message-input") as HTMLInputElement;
sendBtn.addEventListener("click", () => {
this.sendMessage(input.value);
input.value = "";
});
input.addEventListener("keypress", (e) => {
if (e.key === "Enter") {
this.sendMessage(input.value);
input.value = "";
}
});
}
async sendMessage(message: string) {
if (!message.trim()) return;
// 显示用户消息
this.displayMessage("user", message);
try {
const res = await ai.bot.sendMessage({
botId: this.botId,
history: this.getChatHistory(),
msg: message,
});
// 显示流式回复
const assistantDiv = this.displayMessage("assistant", "");
for await (let chunk of res.textStream) {
assistantDiv.innerHTML += chunk;
assistantDiv.scrollIntoView({ behavior: "smooth" });
}
} catch (error) {
this.displayMessage("error", "发送消息失败: " + error.message);
}
}
private displayMessage(role: string, content: string): HTMLDivElement {
const chatContainer = document.getElementById("chat-container");
const messageDiv = document.createElement("div");
messageDiv.className = `message ${role}`;
messageDiv.innerHTML = content;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
return messageDiv;
}
private getChatHistory() {
const messages = document.querySelectorAll(".message");
const history = [];
for (let message of messages) {
const role = message.classList.contains("user") ? "user" : "assistant";
const content = message.innerHTML;
history.push({ role, content });
}
return history;
}
}
// 使用示例
const chatApp = new ChatApp("botId-xxx");
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);
// 分页查询聊天记录
class ChatHistoryManager {
private botId: string;
private currentPage: number = 1;
private pageSize: number = 20;
constructor(botId: string) {
this.botId = botId;
}
async loadPage(pageNumber: number) {
const records = await ai.bot.getChatRecords({
botId: this.botId,
pageNumber: pageNumber,
pageSize: this.pageSize,
sort: "desc", // 按时间倒序排列
});
this.currentPage = pageNumber;
return records;
}
async nextPage() {
return this.loadPage(this.currentPage + 1);
}
async previousPage() {
if (this.currentPage > 1) {
return this.loadPage(this.currentPage - 1);
}
return null;
}
getTotalPages(totalRecords: number) {
return Math.ceil(totalRecords / this.pageSize);
}
}
// 使用示例
const historyManager = new ChatHistoryManager("botId-xxx");
const firstPage = await historyManager.loadPage(1);
console.log("第1页记录:", firstPage.recordList);
const secondPage = await historyManager.nextPage();
console.log("第2页记录:", secondPage.recordList);
// 构建聊天历史查看界面
class ChatHistoryViewer {
private botId: string;
constructor(botId: string) {
this.botId = botId;
this.setupUI();
}
private setupUI() {
const historyContainer = document.getElementById("history-container");
const prevBtn = document.getElementById("prev-btn");
const nextBtn = document.getElementById("next-btn");
const pageInfo = document.getElementById("page-info");
prevBtn.addEventListener("click", () => this.previousPage());
nextBtn.addEventListener("click", () => this.nextPage());
}
async loadHistory(pageNumber: number = 1) {
const records = await ai.bot.getChatRecords({
botId: this.botId,
pageNumber: pageNumber,
pageSize: 10,
sort: "desc",
});
this.displayRecords(records.recordList);
this.updatePageInfo(pageNumber, records.total);
}
private displayRecords(records: any[]) {
const container = document.getElementById("records-container");
container.innerHTML = "";
records.forEach((record) => {
const recordDiv = document.createElement("div");
recordDiv.className = "chat-record";
recordDiv.innerHTML = `
<div class="record-header">
<span class="role">${record.role}</span>
<span class="time">${record.createTime}</span>
</div>
<div class="content">${record.content}</div>
`;
container.appendChild(recordDiv);
});
}
private updatePageInfo(currentPage: number, total: number) {
const pageInfo = document.getElementById("page-info");
const totalPages = Math.ceil(total / 10);
pageInfo.textContent = `第${currentPage}页,共${totalPages}页,总计${total}条记录`;
}
async nextPage() {
const currentPage = parseInt(
document.getElementById("page-info").textContent.match(/第(\d+)页/)[1]
);
await this.loadHistory(currentPage + 1);
}
async previousPage() {
const currentPage = parseInt(
document.getElementById("page-info").textContent.match(/第(\d+)页/)[1]
);
if (currentPage > 1) {
await this.loadHistory(currentPage - 1);
}
}
}
// 使用示例
const historyViewer = new ChatHistoryViewer("botId-xxx");
await historyViewer.loadHistory(1);
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("反馈发送成功");
// 构建用户反馈系统
class FeedbackSystem {
private botId: string;
constructor(botId: string) {
this.botId = botId;
this.setupFeedbackUI();
}
private setupFeedbackUI() {
const feedbackButtons = document.querySelectorAll(".feedback-btn");
feedbackButtons.forEach((button) => {
button.addEventListener("click", (e) => {
const recordId = e.target.dataset.recordId;
const type = e.target.dataset.type; // upvote 或 downvote
this.showFeedbackDialog(recordId, type);
});
});
}
private showFeedbackDialog(recordId: string, type: string) {
const dialog = document.getElementById("feedback-dialog");
const submitBtn = document.getElementById("submit-feedback");
const ratingInput = document.getElementById("rating") as HTMLInputElement;
const commentInput = document.getElementById(
"comment"
) as HTMLTextAreaElement;
const tagsInput = document.getElementById("tags") as HTMLInputElement;
dialog.style.display = "block";
submitBtn.onclick = async () => {
await this.submitFeedback(recordId, type, {
rating: parseInt(ratingInput.value),
comment: commentInput.value,
tags: tagsInput.value.split(",").map((tag) => tag.trim()),
});
dialog.style.display = "none";
};
}
async submitFeedback(
recordId: string,
type: string,
feedback: {
rating: number;
comment: string;
tags: string[];
}
) {
try {
await ai.bot.sendFeedback({
userFeedback: {
botId: this.botId,
recordId: recordId,
comment: feedback.comment,
rating: feedback.rating,
tags: feedback.tags,
aiAnswer: this.getCurrentAnswer(),
input: this.getCurrentQuestion(),
type: type,
},
botId: this.botId,
});
this.showSuccessMessage("感谢您的反馈!");
} catch (error) {
this.showErrorMessage("