文档/API 参考

API 参考

按能力查方法、事件、类型定义与参数说明。

API 参考

配置表、方法、事件、类型定义一览。

建议阅读顺序

1.先看 ChatConfig(必填与鉴权)2.再看 Methods(你会调用的函数)3.最后查 Events/Types(联调与排错)

ChatConfig(核心配置)

参数类型必填说明
appIdstring项目 ID
apiKeystringAPI Key 或 tokenProvider 二选一
tokenProvider() => Promise<string>临时 Token 动态获取函数,生产环境推荐,与 apiKey 二选一
baseUrlstringAPI 基础地址(默认 https://pinyou.xin/api)
timeoutnumber请求超时(默认 30000ms)
debugboolean调试模式,打印日志
userIdstring终端用户标识
sessionIdstring会话标识(不传则自动生成)
ttsMode'stream' | 'websocket'TTS 模式(默认 websocket)
ttsWebSocketTtsWebSocketConfigTTS WebSocket 高级配置(wsUrl, forceWebSocket)

WidgetConfig(预制组件配置)

展开 WidgetConfig 全部参数表(按需查阅)
参数类型默认值说明
theme'minimal' | 'glass' | 'bubble' | 'light' | 'dark' | 'custom''minimal'主题(light/dark/custom 为旧版兼容)
draggablebooleantrue悬浮球可拖拽
defaultOpenbooleanfalse默认打开窗口
position'bottom-right' | 'bottom-left' | 'top-right' | 'top-left''bottom-right'悬浮球位置
titlestring'AI 助手'窗口标题
welcomeMessagestring-欢迎消息
widthnumber380窗口宽度
heightnumber600窗口高度
themeConfigThemeConfig-主题颜色配置
placeholderstring-输入框占位符文本
subtitlestring-窗口副标题
logoUrlstring-Logo 图片 URL
showCloseButtonbooleantrue显示关闭按钮
zIndexnumber9999窗口层级
offset{ x: number; y: number }-位置偏移量

ChatClient 方法

分类方法说明
消息send(content)发送纯文本消息。阻塞至 AI 完全回复(非流式)。
sendMessage(opts)发送消息,支持指定会话 ID、流式/非流式模式、附加上下文。
sendImage(file, content?)上传图片文件并发送为消息。可选附加文字说明。
sendVoice(file, content?)上传语音文件并发送为消息。
sendVideo(file, content?)上传视频文件并发送为消息。
sendWithAttachments(content, attachments)发送带多模态附件的消息,attachments 中的 URL 必须可公开访问。
uploadFile(file, type)仅上传文件到平台存储,返回公网 URL 和 objectName。
会话getConversations()获取当前用户的所有会话列表(分页)。
getConversation(id)获取指定会话的详细信息和消息历史。
deleteConversation(id)删除指定会话,消息历史清除。
newConversation()开启新会话(前端切换,无需清空消息列表)。
switchConversation(id)切换到指定会话,加载其历史消息。
getCurrentConversationId()获取当前会话 ID。
TTS 语音playTts(messageId, text)播放指定消息的 TTS 语音。默认使用 WebSocket 模式(低延迟流式)。
generateTts(text, options?)仅合成 TTS 音频,不自动播放。返回音频 URL。
setTtsMuted(muted)开关流式自动播报(true = 静音,false = 开启)。
pauseTts() / resumeTts()暂停 / 恢复 TTS 播放。
stopTts()停止当前 TTS 播放。
getTtsVoices()获取可用音色列表(含 ID、名称、描述)。
setTtsVoice(voiceId)设置默认 TTS 音色,覆盖初始化配置。
getTtsPlayState()返回 TTS 播放状态:idle | loading | playing | paused | error
控制abortMessage(messageId)中止指定消息的流式响应。
abortAll()中止所有进行中的流式响应。
destroy()销毁客户端实例,断开所有连接,清除状态。
subscribe(listener)订阅状态变化(messages、loading、error 等)。返回取消订阅函数。
on/once/off(event, handler)事件监听:on(持续)、once(一次)、off(取消)。
1// 创建客户端(推荐使用 tokenProvider 动态获取临时Token)
2const client = new ChatClient({
3 appId: 'your-project-id',
4 tokenProvider: async () => {
5 // ⭐ 每次请求前自动调用,安全且支持 Token 自动刷新
6 const res = await fetch('/api/auth/temp-token', { method: 'POST' });
7 return (await res.json()).tempToken;
8 },
9});
10
11// === 消息 ===
12await client.send('你好'); // 纯文本,非流式
13await client.sendMessage({ content: '你好', stream: true }); // 流式响应
14await client.sendImage(fileInput.files[0], '请描述这张图'); // 图片 + 文字
15
16// === 会话 ===
17await client.getConversations(); // 获取会话列表
18await client.switchConversation('conv_xxx'); // 切换会话
19client.newConversation(); // 新会话
20
21// === TTS ===
22client.setTtsMuted(false); // 开启流式播报
23await client.playTts(msg.id, msg.content); // 播放单条消息
24await client.generateTts('你好', { voice: 'longxiaochun_v3' }); // 仅合成
25
26// === 控制 ===
27client.abortAll(); // 中止所有请求
28client.destroy(); // 销毁实例

AG-UI / HITL 方法

以下方法用于“AI 可见操作”:前端声明状态和动作,AI 调用动作执行页面操作;高风险动作通过 HITL 确认卡片完成审批。

说明:这里侧重“方法清单”。完整业务流程示例请看「框架集成 → AG-UI 可见操作」或「UniApp / 小程序 → AG-UI 可见操作」。

方法说明
registerAgentState(declaration)注册 AI 可读状态(页面数据、筛选条件、当前上下文)
updateAgentState(key, value)更新已注册状态值
registerAgentAction(declaration)注册 AI 可调用动作。返回 unregister 函数
approveAction(confirmId)批准确认卡片中的待执行动作
rejectAction(confirmId, reason?)拒绝待执行动作
editAndApproveAction(confirmId, editedParams)编辑参数后批准执行
getPendingConfirms()读取当前待确认动作列表
最小可用示例(全局 + 页面)typescript
1// 全局:注册跨页面通用动作
2const offGlobal = client.registerAgentAction({
3 name: 'openProjectsPage',
4 description: '打开项目列表页',
5 parameters: [],
6 handler: async () => ({ success: true, message: '已打开项目列表页' }),
7});
8
9// 页面:注册当前页面专属动作(组件卸载时注销)
10const offPage = client.registerAgentAction({
11 name: 'submitOrderForm',
12 description: '提交当前订单表单',
13 parameters: [],
14 needsConfirmation: true,
15 confirmMessage: '确认提交订单?',
16 handler: async () => ({ success: true, message: '订单已提交' }),
17});
18
19// cleanup
20offPage();
21offGlobal();
UniApp 自定义 UI 对等能力(useChat)typescript
1import { useChat } from '@lingshuai/chat-uniapp';
2
3const chat = useChat({
4 apiKey: 'tmp_live_xxx',
5 appId: 'your-app-id',
6});
7
8const off = chat.registerAgentAction({
9 name: 'deleteProjectsBatch',
10 description: '批量删除项目',
11 parameters: [{ name: 'projectIds', type: 'array', required: true, description: '项目ID数组' }],
12 needsConfirmation: true,
13 confirmMessage: '确认批量删除这些项目?',
14 handler: async (params) => ({ success: true, message: '已执行删除', data: params }),
15});
16
17chat.on('agent:action_execute', (e) => console.log('action_execute', e));
18chat.on('agent:action_confirm', (e) => console.log('action_confirm', e));
19
20const pending = chat.getPendingConfirms();
21if (pending.length > 0) {
22 await chat.approveAction(pending[0].confirmId);
23}
24
25off();

事件类型

事件说明
connected连接建立
disconnected断开连接
message:sending消息发送中
message:sent消息已发送
message:received收到回复
message:stream:start流式响应开始
message:stream:chunk流式数据块
message:stream:delta流式增量文本
message:stream:end流式响应结束
message:stream:usageToken 用量统计(promptTokens, completionTokens, totalTokens)
message:stream:aborted流式传输被中止
message:error消息错误
conversation:created会话创建
conversation:updated会话更新
tts:startTTS 开始播放
tts:playTTS 音频片段播放
tts:endTTS 播放结束
tts:errorTTS 错误
tts:pauseTTS 暂停
tts:stopTTS 停止
tts:audioTTS 音频数据
error全局错误

类型定义

1interface Message {
2 id: string;
3 conversationId: string;
4 role: 'user' | 'assistant' | 'system';
5 content: string;
6 status: 'pending' | 'sending' | 'streaming' | 'success' | 'error' | 'aborted';
7 createdAt: Date;
8 attachments?: MediaAttachment[];
9 metadata?: Record<string, unknown>;
10}
11
12type MediaType = 'image' | 'audio' | 'video' | 'file';
13
14interface MediaAttachment {
15 type: MediaType;
16 url: string;
17 mimeType?: string;
18 name?: string;
19 size?: number;
20 duration?: number; // 秒,音视频
21}
22
23interface UploadResult {
24 url: string;
25 objectName: string;
26 mimeType: string;
27 size: number;
28 name?: string;
29}
30
31interface TtsOptions {
32 voice?: string; // 音色 ID
33 projectId?: string; // 项目 ID
34 conversationId?: string; // 对话 ID
35 mode?: 'api' | 'websocket'; // 播放模式
36}
37
38interface TtsResult {
39 audioUrl: string;
40 characters: number;
41 model: string;
42 voice: string;
43}
43

媒体上传 API

方法参数说明
uploadFile(file, type)File/Blob, 'image'|'audio'|'video'|'file'上传文件,返回 UploadResult
sendImage(file, content?)File/Blob, string?上传并发送图片消息
sendVoice(file, content?)File/Blob, string?上传并发送语音消息
sendVideo(file, content?)File/Blob, string?上传并发送视频消息
sendWithAttachments(content, attachments)string, MediaAttachment[]发送带附件的消息

文件限制

图片

最大 10MB

jpeg, png, gif, webp, bmp

音频

最大 25MB

mp3, wav, ogg, aac, webm, flac, amr, opus, silk

视频

最大 50MB

mp4, webm, quicktime

文件

最大 30MB

pdf, doc/docx, xls/xlsx, ppt/pptx, txt, csv, md, json, zip