Realtime WebSocket 接入指南与示例

Realtime 类模型不走 /v1/chat/completions,只能通过 WebSocket 长连接调用,支持边说边回、语音打断,以及音频、图片、文本输入。网关原样双向转发 Qwen-Omni-Realtime 协议:你按该协议发事件,也按该协议收事件。逐字段的事件与错误说明见API 参考。

适用模型

模型是否支持本入口以模型广场标注的协议为准,例如 qwen3.8-omni-flash-realtime。可在 https://console.modelgo.ai 的模型广场确认。

接入

项值
Endpointwss://api.modelgo.ai/api-ws/v1/realtime
Querymodel=<逻辑模型名>(必填)
鉴权Authorization: Bearer <mgk_ API Key>
请求 ID建议携带 X-Request-ID(A-Z a-z 0-9 - _ . :,≤128 字符)作为排障凭据;未携带时网关自动生成且不回传

握手阶段的失败直接返回 HTTP 状态码(如 Key 无效 401、余额不足 402),见握手错误。

最小示例

下面示例在服务端运行:建连、配置会话、推送一段语音,提交后请求回复,并把返回的音频写入 reply.pcm。

输入 input.pcm 为 16 kHz、16-bit 小端、单声道、无文件头的 PCM;输出 reply.pcm 为 24 kHz、16-bit、单声道 PCM。

Python(pip install websocket-client):

python
import base64
import json
import os
from pathlib import Path
import websocket

API_KEY = os.environ["MODELGO_API_KEY"]
MODEL = "qwen3.8-omni-flash-realtime"
URL = "wss://api.modelgo.ai/api-ws/v1/realtime?model=" + MODEL

audio = Path("input.pcm").read_bytes()  # 16 kHz / 16-bit LE / mono / headerless
if not audio or len(audio) % 2:
    raise ValueError("provide non-empty 16-bit mono PCM audio")

ws = websocket.create_connection(
    URL, header=["Authorization: Bearer " + API_KEY], timeout=30
)

def recv():
    ev = json.loads(ws.recv())
    if ev["type"] == "error":
        raise RuntimeError(ev["error"])
    return ev

try:
    while recv()["type"] != "session.created":
        pass
    ws.send(json.dumps({
        "type": "session.update",
        "session": {
            "modalities": ["text", "audio"],
            "turn_detection": None,
            "audio": {
                "input": {"format": {"type": "pcm", "sample_rate": 16000}},
                "output": {"format": {"type": "pcm", "sample_rate": 24000}},
            },
        },
    }))
    while recv()["type"] != "session.updated":
        pass
    for i in range(0, len(audio), 3200):  # 100ms per frame
        ws.send(json.dumps({
            "type": "input_audio_buffer.append",
            "audio": base64.b64encode(audio[i:i + 3200]).decode("ascii"),
        }))
    ws.send(json.dumps({"type": "input_audio_buffer.commit"}))
    while recv()["type"] != "input_audio_buffer.committed":
        pass
    ws.send(json.dumps({"type": "response.create"}))
    with open("reply.pcm", "wb") as out:  # 24 kHz / 16-bit LE / mono
        while True:
            ev = recv()
            if ev["type"] == "response.audio.delta":
                out.write(base64.b64decode(ev["delta"]))
            elif ev["type"] in ("response.audio_transcript.delta", "response.text.delta"):
                print(ev["delta"], end="", flush=True)
            elif ev["type"] == "response.done":
                print("\nusage:", ev["response"].get("usage"))
                break
finally:
    ws.close()

只想验证链路时,也可以不传音频:发送一条 conversation.item.create(content 为 input_text),再发 response.create,即可只拿文本回复。

打断

turn_detection 非 null 时由服务端 VAD 驱动轮次。用户再次开口时:

  1. 服务端下发 input_audio_buffer.speech_started;
  2. 客户端停止播放已缓冲的回复音频,并发送 response.cancel;
  3. 服务端下发 response.done(状态为 cancelled),开始新一轮。

手动模式(turn_detection: null)下,客户端在录音结束后发送 input_audio_buffer.commit 与 response.create。

计费

  • 按 token 分模态计量,价格以控制台模型页为准。
  • 建连时冻结一笔余额,余额不足时握手返回 402,不建立连接。
  • 关闭连接后按本次连接内所有 response.done 的 usage 累计结算;整段会话没有用量时不扣费。

单连接最长 30 分钟,到达上限即关闭连接并结算。

下一步