OpenAI Realtime

通过一条 WebSocket 长连接与 Realtime 模型实时收发音频和文本,适合语音助手、同声传译、实时客服等低延迟场景。平台不改写事件内容,你发送和接收的事件与 OpenAI Realtime 协议一致。

项 值
方法与路径 GET /v1/realtime?model=<模型名>(升级为 WebSocket)
连接地址 wss://www.nextai-code.com/v1/realtime?model=<模型名>
鉴权 服务端:Authorization: Bearer YOUR_API_KEY;浏览器:WebSocket 子协议 openai-insecure-api-key.YOUR_API_KEY
消息格式 每条 WebSocket 文本消息是一个 JSON 事件

model 通过 URL 查询参数 传入,不传会在握手时返回 400(未指定模型名称)。可用的 Realtime 模型以 模型列表(GET /v1/models)为准。

快速示例

Python(websockets)

服务端/脚本环境用请求头鉴权。

PYTHON
# pip install websockets
import asyncio, json, os
import websockets

URL = "wss://www.nextai-code.com/v1/realtime?model=YOUR_MODEL"
HEADERS = {"Authorization": f"Bearer {os.environ['NEXTAI_API_KEY']}"}

async def main():
    # websockets >= 13 使用 additional_headers;旧版本参数名为 extra_headers
    async with websockets.connect(URL, additional_headers=HEADERS) as ws:
        # 1. 配置会话:只要文本输出
        await ws.send(json.dumps({
            "type": "session.update",
            "session": {"modalities": ["text"], "instructions": "用中文简短回答。"},
        }))
        # 2. 写入一条用户消息
        await ws.send(json.dumps({
            "type": "conversation.item.create",
            "item": {
                "type": "message",
                "role": "user",
                "content": [{"type": "input_text", "text": "你好,介绍一下你自己"}],
            },
        }))
        # 3. 请求模型生成回复
        await ws.send(json.dumps({"type": "response.create"}))

        async for raw in ws:
            event = json.loads(raw)
            if event["type"] == "response.text.delta":
                print(event["delta"], end="", flush=True)
            elif event["type"] == "response.done":
                print("\nusage:", event["response"].get("usage"))
                break
            elif event["type"] == "error":
                print("error:", event["error"])
                break

asyncio.run(main())

浏览器(JavaScript)

浏览器的 WebSocket 不能自定义请求头,需把 API Key 放进子协议列表。子协议列表里必须包含 realtime,否则握手会失败。

JAVASCRIPT
const ws = new WebSocket(
  "wss://www.nextai-code.com/v1/realtime?model=YOUR_MODEL",
  ["realtime", "openai-insecure-api-key.YOUR_API_KEY", "openai-beta.realtime-v1"]
);

ws.onopen = () => {
  ws.send(JSON.stringify({ type: "session.update", session: { modalities: ["text"] } }));
  ws.send(JSON.stringify({
    type: "conversation.item.create",
    item: { type: "message", role: "user", content: [{ type: "input_text", text: "你好" }] },
  }));
  ws.send(JSON.stringify({ type: "response.create" }));
};

ws.onmessage = (e) => {
  const event = JSON.parse(e.data);
  if (event.type === "response.text.delta") console.log(event.delta);
};

子协议方式会把 API Key 暴露在前端代码中,仅建议用于本地调试或内部工具。面向公众的网页应由自己的服务端连接本接口并转发。

连接与鉴权

方式 写法 适用
请求头 Authorization: Bearer YOUR_API_KEY 服务端、脚本、App
子协议 Sec-WebSocket-Protocol: realtime, openai-insecure-api-key.YOUR_API_KEY, openai-beta.realtime-v1 浏览器
  • 请求带了 Sec-WebSocket-Protocol 头时,平台只从其中的 openai-insecure-api-key. 读取 API Key,Authorization 头会被忽略。
  • 两种方式都无需额外发送 OpenAI-Beta 头。
  • 鉴权失败、API Key 额度用尽、model 缺失、API Key 无权访问该模型等错误在握手阶段以普通 HTTP 错误返回;连接建立后、会话开始前的错误(如账户余额不足)以 error 事件下发,随后连接关闭,见 错误。

事件

协议与 OpenAI Realtime beta(realtime=v1)一致,完整事件定义参考 OpenAI 官方文档。下面列出最常用的事件。

常用客户端事件(你发送)

type 作用
session.update 更新会话配置:modalities、instructions、voice、input_audio_format、output_audio_format、input_audio_transcription、turn_detection、tools、tool_choice、temperature
input_audio_buffer.append 追加一段 Base64 音频(字段 audio)
input_audio_buffer.commit 提交音频缓冲区(关闭服务端 VAD 时使用)
conversation.item.create 写入一条对话项(文本消息、函数调用结果等)
response.create 请求模型生成回复
response.cancel 取消正在生成的回复

每条客户端消息都必须是合法 JSON,否则平台会结束本次会话。

常用服务端事件(你接收)

type 说明
session.created / session.updated 会话建立 / 配置生效
conversation.item.created 对话项已写入
response.text.delta 文本增量(delta)
response.audio.delta 音频增量(Base64,delta)
response.audio_transcript.delta 模型语音输出对应的文字(delta)
response.function_call_arguments.delta / .done 函数调用参数增量 / 完成
response.done 一轮回复结束,response.usage 携带本轮用量
error 错误

response.done 中的用量结构:

JSON
{
  "type": "response.done",
  "response": {
    "usage": {
      "total_tokens": 1520,
      "input_tokens": 1200,
      "output_tokens": 320,
      "input_token_details": { "cached_tokens": 0, "text_tokens": 200, "audio_tokens": 1000 },
      "output_token_details": { "text_tokens": 80, "audio_tokens": 240 }
    }
  }
}

计费

  • 按 Token 计费,文本和音频分开计价:输入文本、输出文本、输入音频、输出音频四类 Token 分别计价,单价以控制台模型价格为准。
  • 用量来源:以 response.done 中的 usage 为准;未返回 usage 时,平台按会话中收发的文本和音频时长估算。
  • 分段扣费:长连接期间每收到一次 response.done 就结算一次,而不是等连接关闭才扣费。会话中途余额不足时,平台会直接关闭连接(不另发 error 事件),请在客户端处理连接断开。
  • 按次计价的模型,一次连接只扣一次。

错误

连接建立后,平台产生的错误以如下事件下发(error 字段结构同 OpenAI 错误对象):

JSON
{
  "type": "error",
  "event_id": "evt_...",
  "error": { "message": "...", "type": "...", "param": "", "code": "..." }
}

模型服务商返回的 error 事件原样转发。握手阶段的 HTTP 错误码见 错误码。

相关文档