# 接口文档 ## 概述 前后端通信接口定义。以 WebSocket 承载实时对话,REST 端点支撑基础运维。**暂不实现持久化**,但通过 Repository 接口模式为后续扩展预留接入点。 **设计原则**: - WebSocket 为主:所有对话数据走 WebSocket - REST 为辅:仅用于健康检查、会话管理等低频操作 - 接口先行:先定义契约,再填充实现——前后端可并行开发 ## 接口全景 ``` 浏览器 Go Gateway :8080 WebSocket Client <--> /ws (实时对话) HTTP Client --> GET /api/health HTTP Client <--> POST/DELETE /api/sessions ``` --- ## 一、WebSocket 协议 连接地址:`ws://localhost:8080/ws` ### 消息格式约定 所有 WebSocket 消息均为 JSON 文本帧,统一结构: ```typescript interface WsMessage { type: string; // 消息类型,必填 request_id?: string; // 可选,用于请求-响应关联 timestamp?: number; // 可选,毫秒时间戳 [key: string]: any; // 类型特定字段 } ``` ### 客户端 → 服务端消息 #### `query` — 发起一次视觉对话 用户说完话后,客户端同时发送当前图像帧和语音片段: ```typescript interface QueryMessage { type: "query"; request_id: string; // 客户端生成的 UUID image: string; // Base64 编码的 JPEG 图像(不含 data: 前缀) audio: string; // Base64 编码的音频片段(PCM 16kHz) mime_type?: string; // 音频格式,默认 "audio/pcm" } ``` > 为什么图像和音频放在同一条消息里?因为 VAD 检测到用户说完话时,需要同时捕获"此刻的画面"和"说的话",拆成两条消息会增加时序同步的复杂度。 #### `config` — 更新会话配置 ```typescript interface ConfigMessage { type: "config"; payload: { tts_enabled?: boolean; // 是否开启语音合成,默认 true detail_level?: "low" | "high"; // 图像精度,默认 "low" language?: string; // 交互语言,默认 "zh-CN" }; } ``` #### `interrupt` — 打断当前回复 ```typescript interface InterruptMessage { type: "interrupt"; request_id?: string; // 可选,指定打断哪次请求 } ``` #### `ping` — 心跳保活 ```typescript interface PingMessage { type: "ping"; } ``` ### 服务端 → 客户端消息 #### `connected` — 连接建立确认 ```typescript interface ConnectedMessage { type: "connected"; session_id: string; // 服务端生成的会话 ID server_version: string; // 服务端版本号,如 "0.1.0" } ``` #### `stt_result` — 语音识别结果 ```typescript interface STTResultMessage { type: "stt_result"; request_id: string; text: string; // 识别出的用户语音文本 is_final: boolean; // 是否为最终结果 } ``` #### `llm_chunk` — LLM 流式输出片段 ```typescript interface LLMChunkMessage { type: "llm_chunk"; request_id: string; delta: string; // 本次增量文本 role: "assistant"; } ``` #### `llm_done` — LLM 输出完成 ```typescript interface LLMDoneMessage { type: "llm_done"; request_id: string; full_text: string; // 完整回复文本 tokens_used: { prompt: number; completion: number; total: number; }; model: string; // 实际使用的模型名 latency_ms: number; // 端到端延迟(毫秒) } ``` #### `tts_audio` — TTS 音频流片段 ```typescript interface TTSAudioMessage { type: "tts_audio"; request_id: string; audio: string; // Base64 编码的音频片段 mime_type: string; // "audio/mpeg" is_last: boolean; // 是否为最后一片 } ``` **音频格式规范**(前端播放依赖此约定): | 属性 | 值 | 说明 | |------|------|------| | 编码 | `audio/mpeg`(MP3) | 浏览器 `