跳转到主要内容

简介

Realtime API 提供低时延的文本/语音实时对话能力,通过 WebSocket 建立长连接,按事件流交互。
WSS wss://llm.ai-nebula.com/v1/realtime?model={model}

认证

Authorization
string
required
Bearer Token,如 Bearer sk-xxxxxxxxxx

连接参数

model
string
required
模型名称:gpt-realtimegpt-realtime-mini

基础信息

项目内容
Base URLwss://llm.ai-nebula.com
接口地址/v1/realtime?model={model}
协议WebSocket(JSON 事件流)
音频格式PCM16 单声道,采样率 24000Hz

事件类型

客户端发送

事件说明
session.update设置/更新会话配置
conversation.item.create发送对话消息
input_audio_buffer.append流式推送音频
input_audio_buffer.commit提交音频缓冲
response.create请求生成回复

服务端返回

事件说明
session.created / session.updated会话就绪或已更新
response.text.delta / response.text.done文本增量与完成
response.audio.delta / response.audio.done音频增量与完成
response.done本轮结束,包含 usage
error错误事件

会话配置示例

{
  "event_id": "evt_001",
  "type": "session.update",
  "session": {
    "modalities": ["text", "audio"],
    "instructions": "你是一个友好的助手",
    "voice": "alloy",
    "temperature": 0.8,
    "input_audio_format": "pcm16",
    "output_audio_format": "pcm16"
  }
}

文本消息示例

{
  "event_id": "evt_002",
  "type": "conversation.item.create",
  "item": {
    "type": "message",
    "role": "user",
    "content": [
      { "type": "input_text", "text": "你好,请简单介绍一下你自己。" }
    ]
  }
}

Python 示例

import json, websocket

API_BASE = "wss://llm.ai-nebula.com"
API_KEY = "sk-XyLy**************************mIqSt"
MODEL = "gpt-realtime"

ws = websocket.WebSocketApp(
    f"{API_BASE}/v1/realtime?model={MODEL}",
    header={"Authorization": f"Bearer {API_KEY}"},
    on_message=lambda ws, msg: print("[recv]", msg)
)

ws.on_open = lambda ws: (
    ws.send(json.dumps({"type": "session.update", "session": {
        "modalities": ["text"],
        "instructions": "你是一个简洁的助手"
    }}, ensure_ascii=False)),
    ws.send(json.dumps({"type": "conversation.item.create", "item": {
        "type": "message", "role": "user",
        "content": [{"type": "input_text", "text": "用一句话介绍 Nebula。"}]
    }}, ensure_ascii=False)),
    ws.send(json.dumps({"type": "response.create"}))
)

ws.run_forever()
{ "type": "session.created", "session": { "id": "sess_xxx" } }
{ "type": "response.created", "response": { "id": "resp_xxx" } }
{ "type": "response.text.delta", "delta": "你好!我是" }
{ "type": "response.text.delta", "delta": " Nebula 的实时助手。" }
{
  "type": "response.done",
  "response": {
    "usage": {
      "total_tokens": 123,
      "input_tokens": 45,
      "output_tokens": 78
    }
  }
}

错误处理

异常类型触发场景返回信息
认证失败API Key 无效或未授权确认 Authorization 头中 API Key 有效
模型不存在模型名称错误仅支持 gpt-realtime / gpt-realtime-mini
音频解码错误音频格式不正确确保 PCM16 单声道、采样率 24000Hz
连接断开WebSocket 断连检查网络或重新建立连接

注意事项

  • 建立连接后先发送 session.update 配置会话
  • 发送消息后需调用 response.create 触发生成
  • 音频需为 PCM16 单声道 24000Hz,base64 编码
  • 依赖 websocket-client 库:pip install websocket-client