Realtime WebSocket Integration Guide & Examples

Realtime models do not use /v1/chat/completions; they are called over a long-lived WebSocket connection, with live voice chat, interruption, and audio, image, and text input. The gateway relays the Qwen-Omni-Realtime protocol verbatim in both directions: you send and receive events in that protocol. The exact event and error schema is in the API reference.

Supported models

Whether a model supports this endpoint follows the protocols shown in the model marketplace, for example qwen3.8-omni-flash-realtime. Check the marketplace at https://console.modelgo.ai.

Connecting

ItemValue
Endpointwss://api.modelgo.ai/api-ws/v1/realtime
Querymodel=<logical model> (required)
AuthAuthorization: Bearer <mgk_ API Key>
Request IDrecommended X-Request-ID (A-Z a-z 0-9 - _ . :, up to 128 characters) for troubleshooting; when missing the gateway generates one and does not return it

Handshake failures come back as HTTP status codes (for example 401 for an invalid key, 402 for insufficient balance); see handshake errors.

Minimal example

The example runs on a server: it connects, configures the session, streams speech, commits it, requests a reply, and writes the returned audio to reply.pcm.

Input input.pcm is 16 kHz, 16-bit little-endian, mono, headerless PCM; output reply.pcm is 24 kHz, 16-bit, mono 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()

To check the link without audio, send one conversation.item.create (with input_text content) and then response.create to get a text-only reply.

Interruption

When turn_detection is not null, server VAD drives turns. When the user speaks again:

  1. The server emits input_audio_buffer.speech_started;
  2. The client stops playing buffered reply audio and sends response.cancel;
  3. The server emits response.done (status cancelled) and a new turn begins.

In manual mode (turn_detection: null) the client sends input_audio_buffer.commit and response.create after recording ends.

Billing

  • Metered by tokens per modality; prices are on the model page in the console.
  • An amount is held when the connection opens; if the balance cannot cover it, the handshake returns 402 and no connection is made.
  • After the connection closes, the total of every response.done usage is settled; a session with no usage is not charged.

A connection lasts at most 30 minutes; at the limit it is closed and settled.

Next steps