实时对话 (Realtime)
实时对话(Realtime API)支持以低延迟的实时双向流方式在客户端与大模型之间进行语音和文本交互。该接口基于 WebSocket 协议,适合构建实时语音通话、游戏互动、实时同声传译等场景。
连接协议为 WebSocket (WSS),地址格式如下:
wss://api.easytakeai.com/v1/realtime?model={model_id}注意:连接时必须通过 Query 参数指定 model,例如 ?model=gpt-4o-realtime-preview。
连接握手头部
Section titled “连接握手头部”在发起 WebSocket 连接握手时,必须传递以下 HTTP 标头:
| 标头名称 | 必填 | 值 |
|---|---|---|
Authorization | ✅ | Bearer YOUR_API_KEY |
Content-Type | ❌ | application/json |
事件驱动机制
Section titled “事件驱动机制”连接成功后,客户端与服务端之间采用事件(JSON 格式)进行通信。
客户端常用发送事件
Section titled “客户端常用发送事件”session.update: 配置会话属性(如音频输入/输出格式、工具声明、语音激活检测等)。input_audio_buffer.append: 持续向缓冲区追加客户端录制的 PCM 原始音频切片。response.create: 强制让模型立即生成响应。
服务端接收事件
Section titled “服务端接收事件”session.created: 会话连接建立成功通知。response.audio_transcript.delta: 模型的语音响应文本的流式增量。response.audio.delta: 模型语音的流式 PCM 音频增量数据(Base64 编码)。
调用示例 (Node.js/JS)
Section titled “调用示例 (Node.js/JS)”import WebSocket from 'ws';
const apiKey = "YOUR_API_KEY";const model = "gpt-4o-realtime-preview";const wsUrl = `wss://api.easytakeai.com/v1/realtime?model=${model}`;
const ws = new WebSocket(wsUrl, { headers: { "Authorization": `Bearer ${apiKey}` }});
ws.on('open', () => { console.log('连接成功,已建立实时会话!');
// 发送会话更新事件,设定音频输出配置 const sessionUpdate = { type: "session.update", session: { modalities: ["text", "audio"], instructions: "你是一个热情、简短回答的语音助理。" } }; ws.send(JSON.stringify(sessionUpdate));});
ws.on('message', (data) => { const event = JSON.parse(data.toString());
// 打印流式返回的文本 if (event.type === 'response.audio_transcript.delta') { process.stdout.write(event.delta); }
// 处理接收到的流式音频增量 if (event.type === 'response.audio.delta') { const audioChunk = Buffer.from(event.delta, 'base64'); // 写入播放器或音频文件缓冲区... }});