小程序/小组件从基础库从 x.x.x 版本开始内置了 Agent 对话能力,开发者可以直接通过小程序/小组件内,通过 xhs.cloud.AI 调用 agent 进行对话
... existing code ...
async onLoad() {
console.log("页面加载");
await this.initAgent();
},
// 初始化agent
async initAgent() {
try {
const agentId = "921e2e0eaf004d7aa376ee8985e929bb";
this.agent = xhs.cloud.AI.createAgent({
agentId,
env: 'production',
version: 'latest'
});
console.log("Agent初始化成功");
} catch (error) {
console.error("Agent初始化失败:", error);
xhs.showToast({
title: "Agent初始化失败",
icon: "none",
});
}
}
... existing code ...
开发者调用 xhs.cloud.AI.createAgent 可以得到一个智能体 Agent。Agent 上一共挂载了3个实例属性和7个实例方法,方法的具体参数见JS API文档。
使用示例
... existing code ...
async onLoad() {
console.log("页面加载");
await this.initAgent();
},
// 初始化agent
async initAgent() {
try {
const agentId = "921e2e0eaf004d7aa376ee8985e929bb";
this.agent = xhs.cloud.AI.createAgent({
agentId,
env: 'production',
version: 'latest'
});
console.log("Agent初始化成功");
} catch (error) {
console.error("Agent初始化失败:", error);
xhs.showToast({
title: "Agent初始化失败",
icon: "none",
});
}
}
... existing code ...
开发者调用 xhs.cloud.AI.createAgent 可以得到一个智能体 Agent
xhs.cloud.AI.createAgent({
agentId,
accessToken,
env: 'production',
version: 'latest'
});
属性名 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|
| agent | Agent | Agent实例 | x.x.x |
| agentId | 属性 | 智能体ID | x.x.x |
| agentVersion | 属性 | 智能体版本 | x.x.x |
| env | 属性 | 环境 | x.x.x |
| sendMessage | 同步方法 | 与智能体进行对话 | x.x.x |
| getAgentInfo | 异步方法 | 获取智能体信息 | x.x.x |
| getHistoryMessages | 异步方法 | 获取历史对话信息 | x.x.x |
| getConversations | 异步方法 | 获取当前智能体会话 | x.x.x |
属性名 | 是否必传 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|---|
| agentId | 是 | string | 智能体agentid开放平台获取 | x.x.x |
| env | 是 | string | 环境变量,可选值:development 开发环境智能体、production 生产环境智能体 | x.x.x |
| version | 当 env 为 development 必传、当 env 为 production,默认 latest | string | 智能体函数版本:development - 可能存在多个开发版本,不同智能体存在差异、production - 仅存在一个版本,默认 latest | x.x.x |
使用示例
async sendMessage() {
const agent = this.getAgent();
if (!agent) return;
// 重置状态
this.setData({
thinkingText: "",
streamText: "",
isThinkingCollapsed: false,
thinkingScrollIntoView: "",
replyScrollIntoView: "",
});
// 显示加载中
xhs.showLoading({
title: "正在调酒中...",
});
const content = '{"user_taste": "酸", "user_mood": "开心"}';
console.log("准备调用 Agent AI API,参数:", content);
let thinkingText = "";
let result = "";
// 使用回调方式发送消息
const { message, onMessage, onSuccess, onError } = agent.sendMessage({
msg: content,
history: [],
});
onSuccess((result) => {
console.log("请求成功:", result);
console.log("API调用成功,返回结果:", result);
xhs.hideLoading();
// 检查是否需要自动折叠思考卡片
this.checkAutoCollapse();
});
// 监听流式消息
onMessage((chunkStr) => {
console.log("收到消息块:", chunkStr, "api-message", message);
xhs.hideLoading();
if (chunkStr === "[DONE]") {
return;
}
let chunk = "";
try {
chunk = JSON.parse(chunkStr);
} catch (error) {
console.error("解析消息块失败:", error);
return;
}
// 解析消息块
if (chunk.choices && chunk.choices[0] && chunk.choices[0].message) {
const message = chunk.choices[0].message;
// 处理思考内容
if (message.reasoning_content) {
thinkingText += message.reasoning_content;
this.setData({
thinkingText: thinkingText,
});
this.scrollThinkingToBottom();
}
// 处理回复内容
if (message.content) {
result += message.content;
this.setData({
streamText: result,
});
this.scrollReplyToBottom();
}
}
});
// 监听错误回调
onError((error) => {
console.error("请求失败:", error);
xhs.hideLoading();
xhs.showToast({
title: "生成失败,请重试",
icon: "none",
});
});
},
function sendMessage(props: {
botId: string;
msg: string;
history?: Array<{
role: string;
content: string;
}>;
});
属性名 | 类型 | 说明 |
|---|---|---|
| onMessage | function | 消息回调 |
| onError | function | 失败回调 |
| onSuccess | function | 成功回调 |
| abort | function | 中断消息收发 |
| message | object | 当前发送的消息 |
// 使用回调方式发送消息
const { message, onMessage, onSuccess, onError, abort } = agent.sendMessage({
msg: content,
history: [],
});
abort()
使用示例
const agent = this.getAgent();
if (!agent) return;
const agentInfo = await agent.getAgentInfo();
console.log("res", agentInfo);
const agentInfo = await agent.getAgentInfo();
属性名 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|
| agentInfo | object | 智能体信息 | x.x.x |
| hasConversation | boolean | 是否存在会话 | x.x.x |
属性名 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|
| agent_name | string | 智能体名称 | x.x.x |
| agent_id | string | 智能体id | x.x.x |
| agent_icon | string | 智能体图标 | x.x.x |
使用示例
// 获取历史记录
async getChatRecords() {
const agent = this.getAgent();
if (!agent) return;
const response = await agent.getConversations();
console.log("=== conversations", response);
if (response.code !== 0) {
xhs.showToast({
title: "获取历史记录失败",
icon: "none",
});
return;
}
const conversations = response.data.conversations;
if (conversations && conversations.length > 0) {
const res = await agent.getHistoryMessages({
conversation_id: conversations[0].id,
cursor: 1,
count: 10,
sort: "desc",
});
console.log("=== getHistoryMessages", res);
}
},
const agentInfo = await agent.getHistoryMessages({
conversation_id: conversations[0].id,
cursor: 1,
count: 10,
sort: "desc"
});
属性名 | 类型 | 字段描述及类型 | 最低支持版本 |
|---|---|---|---|
| conversation_id | string | 会话 id | x.x.x |
| cursor | string | 请求的游标 | x.x.x |
| count | number | 分页大小 | x.x.x |
| sort | string | 历史记录排序 | x.x.x |
export interface UserRecord {
content: string;
role: 'user';
}
export interface AssistantRecord {
content: string;
role: 'assistant';
reasoningContent: string;
type: MessageType;
}
export type CreateRecordPairResponse = BaseResponse;
export interface ParticipantInfo {
id: string;
name: string;
desc: string;
avatar_url: string;
}
export interface GetHistoryMessagesData {
message_list: (UserRecord | AssistantRecord)[];
conversation_id: string;
participant_info_map: Record<string, ParticipantInfo>;
next_cursor: number;
has_more: boolean;
}
使用示例
const agent = this.getAgent();
if (!agent) return;
const agentInfo = await agent.getConversations();
console.log("res", agentInfo);
const agentInfo = await agent.getConversations();
export interface Conversation {
id: string;
createAt: string;
}
export interface GetConversationsData {
conversations: Conversation[];
}
属性名 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|
| conversations | 数组 | 会话列表 | x.x.x |
属性名 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|
| id | string | 会话 id | x.x.x |
| createAt | string | 会话创建时间 | x.x.x |
使用示例
用于多模态模型「文生图」异步任务查询
const agent = this.getAgent();
if (!agent) return;
const taskInfo = await agent.taskInfo();
console.log("res", agentInfo);
this.pollingTimers[taskId] = setInterval(async () => {
this.pollingCounts[taskId]++;
console.log(
`轮询第${this.pollingCounts[taskId]}次,任务ID: ${taskId},图片索引: ${imageIndex}`
);
try {
const result = await agent.queryTasks({ taskId });
console.log(`taskId: ${taskId} 轮询结果:`, result);
// 根据任务状态处理结果
if (
this.handleTaskResult(result, taskId, imageIndex)
) {
// 任务完成,停止轮询
console.log(
`taskId: ${taskId} 任务完成,停止轮询`
);
this.clearPollingTimer(taskId);
return;
}
// 检查是否超过最大轮询次数
if (
this.pollingCounts[taskId] >= this.maxPollingCount
) {
console.warn(
`taskId: ${taskId} 轮询超时,停止轮询`
);
this.clearPollingTimer(taskId);
this.handlePollingTimeout(taskId, imageIndex);
return;
}
} catch (error) {
console.error(
`taskId: ${taskId} 轮询请求失败:`,
error
);
this.pollingCounts[taskId]++;
// 连续失败3次则停止轮询
if (this.pollingCounts[taskId] >= 3) {
console.error(
`taskId: ${taskId} 轮询连续失败,停止轮询`
);
this.clearPollingTimer(taskId);
this.handlePollingError(
error,
taskId,
imageIndex
);
return;
}
}
}, 3000); // 3秒轮询一次
const agentInfo = await agent.queryTasks();
属性名 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|
| taskId | string | 任务id | 文生图: 0.3.0, 其他任务: < 0.3.0 |
属性名 | 类型 | 说明 | 最低支持版本 |
|---|---|---|---|
| request_id | string | 请求id | 文生图: 0.3.0, 其他任务: < 0.3.0 |
| output | 见下方代码块 | 任务输出信息 | 文生图: 0.3.0, 其他任务: < 0.3.0 |
| usage | { image_count?: number } | 输出信息 | 文生图: 0.3.0, 其他任务: < 0.3.0 |
/** 任务输出信息 */
output: {
task_id: string;
task_status: "PENDING" | "RUNNING" | "SUCCEEDED" | "FAILED" | "CANCELED" | "UNKNOWN";
results?: Array<{
url?: string;
[key: string]: any;
}>;
task_metrics?: {
TOTAL: number;
SUCCEEDED: number;
FAILED: number;
};
};