Skip to main content

Qwen-Omni-Realtime

Use Qwen-Omni-Realtime over WebSocket and WebRTC to understand text, images, audio, and video, and generate voice replies. It is suitable for scenarios such as voice chat and intelligent customer service.

Supported regions: Singapore and Beijing. You must use the API Key of the corresponding region.

Models and access methods

For real-time audio and video conversations, use Qwen3.8-Omni-Flash-Realtime first. The model supports full-duplex audio and video interaction, accepts text, image, streaming audio, and video input, and returns text and audio.
  • Tool calling and web search: Supports custom Function Calling and remote MCP tools, or you can enable web search.
  • Voice turn detection: Supports semantic_vad, which filters out meaningless sounds such as backchannel acknowledgments and background noise, reducing false triggers of voice turns.
  • Multi-channel audio and video aggregation: WebSocket access supports 1, 2, and 4-channel audio; video aggregation reduces compute overhead when fine-grained visual information is not needed. For more information, see Input and output capabilities.
  • Languages: Supports speech recognition in 113 languages and dialects and speech generation in 36 languages and dialects.
  • Voices and Voice Cloning: The default voice is Tina; for available voices and samples, see the voice list. For how to use custom voices, see Voice Cloning.
For model names, context, pricing, snapshot versions, and other information, see the Model Studio console. For concurrency rate limit conditions, see Rate limits.
Qwen-Omni-Realtime models can be accessed through three protocols: WebSocket, WebRTC, and AOQ. WebSocket is suitable for server-side integration and quick access; WebRTC is suitable for browser-based, low-latency voice scenarios, where audio is transmitted directly over UDP with built-in echo cancellation and noise reduction. If you are integrating on the client side and value stable latency, interaction capability under weak networks, and real-time full-duplex noise reduction and echo cancellation, consider AOQ first. For protocol comparison and selection, see the API reference. Select an entry point based on your current task:

Preparation

Obtain the API Key and workspace ID for the selected region and workspace, and configure the API Key in environment variables. qwen3.8-omni-flash-realtime must use the workspace-bound endpoint below.
  • WebSocket
  • WebRTC
  • AOQ
Configuration itemDescription
EndpointSingapore region: wss://WorkspaceId.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtimeWhen making a call, replace WorkspaceId in the address with the actual workspace ID.
Query parameterThe query parameter is model, which must be set to the name of the model to access. Example: ?model=qwen3.8-omni-flash-realtime
Request headerUse Bearer Token authentication: Authorization: Bearer DASHSCOPE_API_KEY
DASHSCOPE_API_KEY is the API Key you applied for on Model Studio.

QuickStart: minimal audio Q&A

This example uses WebSocket and Manual mode to complete one Q&A round from a local audio file. If you need continuous recording or browser interaction, see Real-time conversation examples. First, configure the API Key and install websocket-client. In the Python example below, select a region (cn-beijing or ap-southeast-1) and fill in the Workspace ID for the corresponding endpoint. Set PCM_FILE to the path of a short 16 kHz, 16-bit little-endian, mono, headerless PCM speech file. The example uses Manual mode: wait for the session configuration to take effect, send the audio, commit the buffer, and then request a reply. Text is printed to the terminal, and audio is written to reply.pcm (24 kHz PCM, not a WAV file). Run the following commands in a macOS or Linux terminal.
python3 -m pip install websocket-client
export PCM_FILE="./input.pcm"
If you already have an input.wav encoded as mono, 16 kHz, 16-bit PCM, you can use Python to extract the PCM audio. This step checks the format and does not resample.
import wave
from pathlib import Path

with wave.open("input.wav", "rb") as source:
    if (source.getnchannels(), source.getframerate(), source.getsampwidth(),
            source.getcomptype()) != (1, 16000, 2, "NONE"):
        raise ValueError("Expected mono 16 kHz, 16-bit PCM WAV audio.")
    Path("input.pcm").write_bytes(source.readframes(source.getnframes()))
Once the input is ready, run the following client. The example uses the "Longanlingxin" voice (longanlingxin):
import base64
import json
import os
from pathlib import Path
import websocket

url = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime?model=qwen3.8-omni-flash-realtime"
audio = Path(os.environ["PCM_FILE"]).read_bytes()
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 " + os.environ["DASHSCOPE_API_KEY"]],
    timeout=30,
)

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

try:
    while receive()["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,
                    "sample_format": "s16le", "channels": 1,
                    "packing": "interleaved", "channel_layout": "mono",
                }},
                "output": {
                    "voice": "longanlingxin",
                    "format": {"type": "pcm", "sample_rate": 24000},
                },
            },
        },
    }))
    while receive()["type"] != "session.updated":
        pass
    for offset in range(0, len(audio), 3200):
        ws.send(json.dumps({
            "type": "input_audio_buffer.append",
            "audio": base64.b64encode(audio[offset:offset + 3200]).decode("ascii"),
        }))
    ws.send(json.dumps({"type": "input_audio_buffer.commit"}))
    while receive()["type"] != "input_audio_buffer.committed":
        pass
    ws.send(json.dumps({"type": "response.create"}))
    with open("reply.pcm", "wb") as output:
        while True:
            event = receive()
            if event["type"] == "response.audio.delta":
                output.write(base64.b64decode(event["delta"]))
            elif event["type"] in ("response.audio_transcript.delta", "response.text.delta"):
                print(event["delta"], end="", flush=True)
            elif event["type"] == "response.done":
                print("\nResponse status:", event["response"]["status"])
                break
finally:
    ws.close()
After successfully receiving the reply, wrap reply.pcm into a WAV file, then play it with an audio player:
import wave
from pathlib import Path

with wave.open("reply.wav", "wb") as target:
    target.setnchannels(1)
    target.setsampwidth(2)
    target.setframerate(24000)
    target.writeframes(Path("reply.pcm").read_bytes())

Real-time conversation examples

The WebSocket examples provide two modes: VAD and Manual; WebRTC uses VAD.
  • WebSocket
  • WebRTC
  • AOQ
  • DashScope Python SDK
  • DashScope Java SDK
  • Native Python WebSocket
  • Prepare the runtime environment
Your Python version must be 3.10 or later.First, install pyaudio according to your operating system.
  • macOS
  • Debian/Ubuntu
  • CentOS
  • Windows
brew install portaudio && pip install pyaudio
After the installation is complete, install the dependencies with pip:
pip install websocket-client dashscope
  • Select the interaction mode
    • VAD mode (Voice Activity Detection, automatically detects speech start and end) The server automatically determines when the user starts and stops speaking and responds accordingly.
    • Manual mode (manually control speech start and end) The client controls the speech start and end. After the user finishes speaking, the client must proactively send a message to the server.
    • VAD mode
    • Manual mode
    Create a new Python file named vad_dash.py, and copy the following code into the file:
    # Dependencies: dashscope >= 2.0.1, pyaudio
    import os
    import base64
    import time
    
    import pyaudio
    from concurrent.futures import ThreadPoolExecutor
    
    import dashscope
    
    # The following configuration is for the Singapore (ap-southeast-1) region. Enter your workspace ID in the example. The region value varies by region.
    client = dashscope.Client(
        # If you have not set an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
        # API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        workspace="{WorkspaceId}",
        region="ap-southeast-1",
    )
    # Specify the voice
    voice = 'Tina'
    # Specify the model
    model = 'qwen3.8-omni-flash-realtime'
    # Specify the model persona
    instructions = "你是个人助理小云,请用幽默风趣的方式回答用户的问题"
    
    # 1. Initialize the audio device and output stream
    pya = pyaudio.PyAudio()
    out = pya.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
    
    # 2. Receiver thread: iterate server events, play audio and print text
    def receive_events(session):
        for response in session.events():
            if response['type'] == 'response.audio.delta':
                # Play the audio
                out.write(base64.b64decode(response['delta']))
            elif response['type'] == 'conversation.item.input_audio_transcription.delta':
                # Streaming preview: text is the confirmed prefix, stash is the pending suffix
                preview = response.get('text', '') + response.get('stash', '')
                print(f"\r[User] {preview}", end='', flush=True)
            elif response['type'] == 'conversation.item.input_audio_transcription.completed':
                # Transcription completed: print the final text and a newline
                print(f"\r[User] {response['transcript']}")
            elif response['type'] == 'response.audio_transcript.done':
                # Print the assistant reply text
                print(f"[LLM] {response['transcript']}")
    
    # 3. Create the session (the connection is established automatically on entering the with context) and configure it
    with client.audio.realtime.connect(model=model) as session:
        session.update_session(
            output_modalities=['audio', 'text'],
            voice=voice,
            instructions=instructions,
        )
        # 4. Initialize the audio input stream
        mic = pya.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
        # 5. Main loop for audio input
        print("对话已开始,对着麦克风说话 (Ctrl+C 退出)...")
        try:
            with ThreadPoolExecutor(max_workers=1) as pool:
                receiver = pool.submit(receive_events, session)
                while True:
                    audio_data = mic.read(3200, exception_on_overflow=False)
                    session.append_audio(audio_data)
                    time.sleep(0.01)
        except KeyboardInterrupt:
            # Clean up resources
            session.close()
            mic.close()
            out.close()
            pya.terminate()
            print("\n对话结束")
    
    Run vad_dash.py to have a real-time conversation with the Qwen-Omni-Realtime model through your microphone. The system detects where your audio starts and automatically sends it to the server, so you do not need to send it manually.

Invocation process and session management

A single call completes connection establishment, session configuration, input, response triggering, and result retrieval in sequence.

Establish a connection

The following WebSocket and WebRTC connection examples use qwen3.8-omni-flash-realtime.
  • WebSocket
  • WebRTC
  • AOQ
  • Native WebSocket connection
  • DashScope Python SDK
  • DashScope Java SDK
For the API endpoint and authentication, see Prerequisites.
# pip install websocket-client
import json
import websocket
import os

API_KEY=os.getenv("DASHSCOPE_API_KEY")
# The following URL is for the Singapore region. Enter your workspace ID in the example. URLs vary by region.
API_URL = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime?model=qwen3.8-omni-flash-realtime"

headers = [
    "Authorization: Bearer " + API_KEY
]

def on_open(ws):
    print(f"Connected to server: {API_URL}")
def on_message(ws, message):
    data = json.loads(message)
    print("Received event:", json.dumps(data, indent=2))
def on_error(ws, error):
    print("Error:", error)

ws = websocket.WebSocketApp(
    API_URL,
    header=headers,
    on_open=on_open,
    on_message=on_message,
    on_error=on_error
)

ws.run_forever()

Configure the session

In the session object of session.update, use instructions to set the business context and response requirements. Use the client event session.update to configure output modality, voice, audio format, and VAD. The following is a WebSocket Manual mode configuration for Qwen3.8-Omni-Flash-Realtime, consistent with the minimal audio Q&A example. This example uses the "Longanlingxin" voice (longanlingxin):
{
  "type": "session.update",
  "session": {
    "modalities": [
      "text",
      "audio"
    ],
    "turn_detection": null,
    "audio": {
      "input": {
        "format": {
          "type": "pcm",
          "sample_rate": 16000,
          "sample_format": "s16le",
          "channels": 1,
          "packing": "interleaved",
          "channel_layout": "mono"
        }
      },
      "output": {
        "voice": "longanlingxin",
        "format": {
          "type": "pcm",
          "sample_rate": 24000
        }
      }
    }
  }
}
The following example uses Qwen3.5-Omni-Realtime, the Ethan voice, and semantic_vad mode.
{
    // 该事件的id,由客户端生成
    "event_id": "event_ToPZqeobitzUJnt3QqtWg",
    // 事件类型,固定为session.update
    "type": "session.update",
    // 会话配置
    "session": {
        // 输出模态,支持设置为["text"](仅输出文本)或["text","audio"](输出文本与音频)。
        "modalities": [
            "text",
            "audio"
        ],
        // 输出音频的音色
        "voice": "Ethan",
        // 推荐写法:同时配置音频格式和采样率(仅 qwen3.5-omni-plus-realtime / qwen3.5-omni-flash-realtime 支持)
        // 输入格式:pcm / wav,默认 pcm;采样率:8000/16000/24000/48000,默认 16000
        // 输出格式:pcm / wav,默认 pcm;采样率:8000/16000/24000/48000,默认 24000
        "audio": {
            "input": {
                "format": {
                    "type": "pcm",
                    "sample_rate": 16000
                }
            },
            "output": {
                "format": {
                    "type": "pcm",
                    "sample_rate": 24000
                }
            }
        },
        // 系统消息,用于设定模型的目标或角色。
        "instructions": "你是某五星级酒店的AI客服专员,请准确且友好地解答客户关于房型、设施、价格、预订政策的咨询。请始终以专业和乐于助人的态度回应,杜绝提供未经证实或超出酒店服务范围的信息。",
        // 是否开启语音活动检测。若需启用,需传入一个配置对象,服务端将据此自动检测语音起止。
        // 设置为null表示由客户端决定何时发起模型响应。
        "turn_detection": {
            // VAD类型,取值为server_vad或semantic_vad。使用qwen3.5-omni-realtime系列模型时推荐设为semantic_vad。
            "type": "semantic_vad",
            // VAD检测阈值。建议在嘈杂的环境中增加,在安静的环境中降低。
            "threshold": 0.5,
            // 检测语音停止的静音持续时间,超过此值后会触发模型响应。取值范围 200-6000,默认 800。金融核实等短回答场景建议 500-600。
            "silence_duration_ms": 800
        }
    }
}
The audio formats and sampling rate options listed in this section apply to the qwen3.5-omni-plus-realtime and qwen3.5-omni-flash-realtime models. The legacy compatibility fields input_audio_format / output_audio_format remain valid, but we recommend using audio.input.format / audio.output.format.
For media formats and multi-channel configuration, see Input and output capabilities. For tool configuration, see Tool calling and web search.

Turn control and event timing

  • VAD mode
  • Manual mode
Set the session.turn_detection.type field of the session.update event to "server_vad" or "semantic_vad" to enable VAD mode. This is suitable for voice call scenarios. Both WebSocket and WebRTC support VAD mode; however, audio and images are transmitted differently, and some server events differ.When using Qwen3.8-Omni-Flash-Realtime series models for customer service or business conversations, you can set session.turn_detection.type to "semantic_vad_ec". Compared with semantic_vad, this mode makes it easier to detect user speech and interrupt model responses, while still filtering out meaningless sounds such as background noise.
WebRTC supports only VAD mode, not Manual mode. WebRTC audio is transmitted directly via RTP, so there is no need to send the input_audio_buffer.append event; images are transmitted over the video track, and the input_image_buffer.append event is not supported. Control commands and server events are transmitted over the DataChannel. For specific events, see Server events.
The interaction flow is as follows:
  1. The client sends audio data. WebSocket sends it via the input_audio_buffer.append event; WebRTC transmits it automatically over the audio track (RTP), with no manual event required.
  2. The server detects that speech has started and sends the input_audio_buffer.speech_started event via DataChannel (WebRTC) or WebSocket.
  3. The server detects that speech has ended and sends the input_audio_buffer.speech_stopped event.
  4. The server automatically commits the audio buffer and sends the input_audio_buffer.committed event.
  5. The server starts generating the response, sending events such as response.created and conversation.item.created. The model's audio response is returned incrementally via the response.audio.delta event over WebSocket, or transmitted directly over the WebRTC audio track (RTP).
  6. During the response, the server incrementally returns the text transcript via response.audio_transcript.delta events, and finally sends the response.done event to signal that the response is complete.
LifecycleClient eventsServer events
Session initializationsession.update
Session configuration
session.created
Session created
session.updated
Session configuration updated
User audio inputinput_audio_buffer.append
WebSocket: Use this event to append audio to the buffer
input_image_buffer.append
WebSocket: Adds images to the buffer via this event
WebRTC: Audio is automatically transmitted via the RTP audio track and images via the video track, so the above events are not required.
input_audio_buffer.speech_started
Speech start detected
input_audio_buffer.speech_stopped
Speech end detected
input_audio_buffer.committed
The server has received the committed audio
Server audio outputNoneresponse.created
The server starts generating a response
response.output_item.added
New output content during the response
conversation.item.created
Conversation item created
response.content_part.added
New output content is added to the assistant message
response.audio_transcript.delta
Incrementally generated transcription text
response.audio.delta
WebSocket: Audio incrementally generated by the model is returned via this event. WebRTC: Audio is transmitted directly via the RTP audio track, and this event is not returned.
response.audio_transcript.done
Text transcription completed
response.audio.done
Audio generation completed
response.content_part.done
Streaming output of the text or audio content of the Assistant message is completed
response.output_item.done
Streaming of the entire output item of the Assistant message is completed
response.done
Response completed
conversation.item.input_audio_transcription.delta
Streaming transcription of the text of user speech input (requires enabling input_audio_transcription in session.update)
conversation.item.input_audio_transcription.completed
Transcription of the text of user speech input completed (requires enabling input_audio_transcription in session.update)

End the session

After each session ends, you should disconnect. For WebSocket access, you can call close() to close the connection; for WebRTC access, you need to stop the media and close the PeerConnection. For detailed steps, see Ending the session and cleaning up resources. Keeping the same session open causes the context to keep accumulating. When calling close() to close a WebSocket connection, if the connection is closed right after it is established (with no session interaction), closing takes about 5-10 seconds. This is normal. The server must finish processing the audio stream, caching the context, and initializing inference resources before it can respond to the close request. We recommend executing close() asynchronously to avoid blocking the main flow.

Session duration and context limits

The total input token limit for qwen3.8-omni-flash-realtime is 196608, and the input length calculation rules are the same as those for Qwen3.5-Omni-Realtime.
  • When the total number of tokens of the conversation history plus the current turn of input exceeds the maximum input length, the server automatically truncates the conversation history and continues the conversation. Text and tool call results also count toward the input length.
  • If the current turn of input itself exceeds the maximum input length, the server returns an error.
  • A single session can last up to 120 minutes; once this limit is reached, the service proactively closes the connection.
  • The model maintains the conversation history context. When the number of conversation turns or the cumulative duration exceeds the limits below, earlier history is automatically discarded. Maximum duration refers to the upper limit on the cumulative duration of audio or video (image frames) that can be retained in the model context. This duration is not the total duration of the session.
    Because video is input by frame extraction (1 frame per second recommended), the maximum video duration is the cumulative duration of image frames the model can retain. For example, 240 seconds means the model retains at most the frames received within the most recent 240 seconds; beyond that, earlier frames are discarded.

    Model

    Maximum audio turns

    Maximum video turns

    Maximum audio duration

    Maximum video duration

    qwen3.8-omni-flash-realtime

    100 turns

    50 turns

    600 s

    240 s

    qwen3.5-omni-plus-realtime

    100 turns

    50 turns

    600 s

    240 s

    qwen3.5-omni-flash-realtime

    80 turns

    50 turns

    480 s

    120 s

Input and output capabilities

Choose audio input, images and video, multichannel audio, or voice based on your task. Tool calling describes Function Calling, MCP, and web search configuration.

Audio input

Audio is the recommended primary input method and can be combined with images as needed. With WebSocket, append Base64-encoded audio via input_audio_buffer.append; with WebRTC, audio is transmitted automatically through the audio track (RTP) added when establishing the connection, so this event is not needed. For audio formats, see Session configuration; for recording and sending implementation, see Real-time conversation examples.

Image and video input

Images can come from local files or be captured in real time from a video stream. Choose the sending method based on your protocol:
  • WebSocket
  • WebRTC
Send Base64-encoded images to the server-side buffer via input_image_buffer.append. Before sending an image, send input_audio_buffer.append at least once.
  • VAD mode: The server automatically commits the audio and images and triggers a response when it detects the end of speech. Images for the current turn should be sent before input_audio_buffer.speech_stopped.
  • Manual mode: After appending the audio and images for the current turn, send input_audio_buffer.commit. After receiving input_audio_buffer.committed, send response.create to request a response. See Event sequence.
Local image example: Go to Real-time conversation examples, select "WebSocket → Python native WebSocket → Manual mode", expand manual_mode.py, and uncomment the two sections of code for image input and sending.In video call scenarios, you can extract frames from the video. We recommend sending images at a rate of 1 frame per second via input_image_buffer.append. For DashScope SDK code, see Omni-Realtime sample code.

Optional: Video aggregation

For Qwen3.8-Omni-Flash-Realtime, session.video.input.representation_compact defaults to none; setting it to normal aggregates video representations to reduce computational overhead, suitable for scenarios that do not rely on fine-grained visual information. It must be configured before the first audio segment and cannot be changed after input starts. The following configuration uses Manual mode, text and audio output, the Tina voice, and disables input transcription. conversation is the connected SDK session. The SDK sends the voice, VAD, and other configurations at the same time; if you need to adjust them, set them in full in the same call.
  • Python
  • Java
Use DashScope Python SDK 2.0.1 or later, and select "WebSocket → DashScope Python SDK → Manual mode" in Real-time conversation examples:
  1. In manual_dash.py, set the model to qwen3.8-omni-flash-realtime.
  2. Replace the original update_session call with the call below (input_video_representation_compact is the video aggregation configuration), calling it once before the first audio segment.
  3. Because this example disables input transcription, skip ctx['transcription_done'].wait(timeout=10) after the commit, and continue with the existing commit and response initiation flow.
Python
session.update_session(
    output_modalities=['audio', 'text'],
    voice="Tina",
    enable_turn_detection=False,
    enable_input_audio_transcription=False,
    input_video_representation_compact="normal",
)
After configuration, send frames following the steps in Image and video input. For video token metering, see Billing rules.

Multichannel audio

The following configuration applies to WebSocket access for Qwen3.8-Omni-Flash-Realtime. Set session.audio.input.format before the first audio segment. 1, 2, and 4 channels are supported; multichannel must be PCM, 16000 Hz, s16le, interleaved. Use raw_mic_array for 2 channels and foa_ambix for 4 channels. For field constraints and JSON snippets, see Client events. For the input token multiplier, see Billing rules.

Receiving text and audio

The model's response format depends on the configured output modality.
  • WebSocket
  • WebRTC

Voices and voice cloning

The following configuration applies to Qwen3.8-Omni-Flash-Realtime. The default voice is Tina. New integrations use session.audio.output.voice; if both it and the legacy field session.voice are set, the output audio uses the voice specified by session.audio.output.voice. For available voices and demos, see Qwen3.8 voices. For custom voices, see Voice Cloning. For other models, see the complete voice list.
  • Web search and tool calling are mutually exclusive and cannot be enabled at the same time.
To use custom tools, see Function Calling; to connect to remote services, use the MCP entry below; to obtain up-to-date information, use web search. Tool results from Function Calling are sent back via conversation.item.create, with item.type set to function_call_output.

MCP

The following configuration applies to Qwen3.8-Omni-Flash-Realtime. Configure public HTTPS MCP Streamable HTTP services in session.tools; update the MCP configuration only when there is no active Response. Approval is required by default. Confirm that tool discovery is complete before initiating a Response that requires the tool. For execution results, rejection and failure handling, and follow-up steps, see MCP interaction process. The web search feature enables the model to respond based on real-time retrieved data, making it suitable for scenarios that require up-to-date information, such as stock prices and weather forecasts. The model can autonomously decide whether to search in order to answer the user's time-sensitive questions.
The Qwen3.8-Omni-Flash-Realtime and Qwen3.5-Omni-Realtime series models support web search, which is disabled by default and must be enabled via the session.update event.
For billing, see the agent policy in Billing details.

How to enable

Add the following parameters to the session.update event:
  • enable_search: set to true to enable web search.
  • search_options.enable_source: set to true to return the list of search result sources.
For parameter details, see session.update.

Responses and search execution

Responses are still received via text and audio events. The example below reads count and strategy from the search usage after receiving response.done, and prints the search count and strategy; for usage fields, see Search usage.

Sample code

The following example shows how to enable web search in a real-time conversation.
  • DashScope Python SDK
  • DashScope Java SDK
  • WebSocket(Python)
Pass the enable_search and search_options parameters in the update_session call:
import os
import base64
import time

import pyaudio
from concurrent.futures import ThreadPoolExecutor

import dashscope

# The following configuration is for the Singapore (ap-southeast-1) region. Enter your workspace ID in the example. The region value varies by region.
client = dashscope.Client(
    # If you have not set an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
    # API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)
model = 'qwen3.8-omni-flash-realtime'
voice = 'Tina'

pya = pyaudio.PyAudio()
out = pya.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)

# Receiver thread: iterate server events
def receive_events(session):
    for response in session.events():
        if response['type'] == 'response.audio.delta':
            out.write(base64.b64decode(response['delta']))
        elif response['type'] == 'conversation.item.input_audio_transcription.delta':
            preview = response.get('text', '') + response.get('stash', '')
            print(f"\r[User] {preview}", end='', flush=True)
        elif response['type'] == 'conversation.item.input_audio_transcription.completed':
            print(f"\r[User] {response['transcript']}")
        elif response['type'] == 'response.audio_transcript.done':
            print(f"[LLM] {response['transcript']}")
        elif response['type'] == 'response.done':
            usage = response.get('response', {}).get('usage', {})
            plugins = usage.get('plugins', {})
            if plugins.get('search'):
                print(f"[Search] count={plugins['search']['count']}, strategy={plugins['search']['strategy']}")

with client.audio.realtime.connect(model=model) as session:
    session.update_session(
        output_modalities=['audio', 'text'],
        voice=voice,
        instructions="你是个人助理小云",
        enable_search=True,
        search_options={'enable_source': True}
    )
    mic = pya.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
    print("联网搜索已启用,对着麦克风说话 (Ctrl+C 退出)...")
    try:
        with ThreadPoolExecutor(max_workers=1) as pool:
            receiver = pool.submit(receive_events, session)
            while True:
                audio_data = mic.read(3200, exception_on_overflow=False)
                session.append_audio(audio_data)
                time.sleep(0.01)
    except KeyboardInterrupt:
        session.close()
        mic.close()
        out.close()
        pya.terminate()
        print("\n对话结束")

Search usage

After web search is enabled, a new plugins field is added to usage in the response.done event to record search usage information:
{
    "usage": {
        "total_tokens": 2937,
        "input_tokens": 2554,
        "output_tokens": 383,
        "input_tokens_details": {
            "text_tokens": 2512,
            "audio_tokens": 42
        },
        "output_tokens_details": {
            "text_tokens": 90,
            "audio_tokens": 293
        },
        "plugins": {
            "search": {
                "count": 1,
                "strategy": "agent"
            }
        }
    }
}

Billing and rate limits

Billing rules

Qwen-Omni-Realtime models are billed based on the token counts of different modalities (audio and image). For billing details, see the Bailian console. When generating speech output, the audio and corresponding text of qwen3.8-omni-flash-realtime are billed separately at the audio output and text output unit prices; the Qwen3.5-Omni-Realtime series is billed only for audio, and the corresponding text is not billed. MCP tool calls incur no additional charge; model inference is still billed at the model price. For the MCP invocation process and usage limits, see MCP interaction process.
In multi-turn real-time conversations, each time the model generates a response, it processes all historical conversation content within the context window (including audio, images, and text from previous turns) together with the new input of the current turn as input tokens. Therefore, input tokens accumulate turn by turn as the number of conversation turns increases, rather than only counting the new input of the current turn.For example, suppose a 10-second audio input is converted into 70 tokens (Qwen3.5-Omni-Realtime series models). In the 3rd turn of the conversation, if that audio is still within the context window, it is still counted as part of the input tokens for the 3rd turn. The actual billed input token count = token count of all historical turns' content within the context window + token count of the new input in the current turn.
  • Audio
  • Image
  • Video
  • Qwen3.8-Omni-Flash-Realtime and Qwen3.5-Omni-Realtime series models:
    • Input audio calculation formula: Total token count = Audio duration (in seconds) * 7
    • Output audio calculation formula: Total Tokens count = Audio duration (in seconds) * 12.5
  • qwen3-omni-flash-realtime-2025-09-15: The calculation formula for both input and output audio is Total token count = Audio duration (in seconds) * 12.5 If the audio duration is less than 1 second, it is counted as 1 second.
When qwen3.8-omni-flash-realtime enables spatial audio input, the audio input Token count is 2 times that of regular audio, and the multiplier is the same for 2-channel and 4-channel audio.

Rate limits

For model rate limit rules, see Rate limits.

FAQ

Will I be billed if I stay connected but don't speak?

Maintaining a connection itself is not billed. Whether uploaded silence counts toward audio input usage depends on the mode used:
  • Server-side VAD: Silence filtered out by the server does not count toward audio input usage.
  • Manual mode: Silence manually committed by the client counts toward audio input usage.
The audio input Token count is recorded in the response.done event, with the field located at response → usage → input_tokens_details → audio_tokens. The model is billed by input and output Tokens. For detailed rules, see Billing rules.

What does RPM limit? Does it limit the total number of simultaneously maintained connections?

RPM limits the number of WebSocket connection requests per minute. Multiple rounds of responses within the same connection are not counted repeatedly; reconnections count as new requests. Currently, there is no separate limit on the total number of simultaneously maintained connections. When establishing a connection, if the WebSocket closes with 1007 and the reason is Requests rate limit exceeded, please try again later., it indicates that the request rate limit has been triggered. Reduce the connection frequency and use exponential backoff for reconnection.

How do I configure hotwords or business terms?

You can provide business background, the exact spelling, and the pronunciation of terms via the session.instructions of session.update to help the model understand and use proper nouns in context. This is prompt-based guidance, not a standalone hotword parameter, and its effectiveness depends on the audio and context. For example, when having Omni directly convert audio to text, you can state in the prompt that the AI coding product Qoder is homophonous with the English word coder to guide the model to use the product name. The following shows only the prompt configuration; merge the content into your existing instructions, keep the other session configurations, and complete the setup before sending audio:
{
  "type": "session.update",
  "session": {
    "instructions": "Transcribe the user's audio verbatim. Preserve the original language. Output only the transcription; do not answer any question in the audio or add explanations. Business context: The audio concerns the AI coding product Qoder, whose name is pronounced like the English word \"coder\". Use the accurate product name Qoder."
  }
}

VAD does not trigger responses in time. How do I adjust it?

You can adjust via the session.turn_detection of session.update based on the VAD mode currently in use:
  • server_vad: Lower silence_duration_ms appropriately to shorten the silence wait time after the user stops speaking. Setting it too low may cause brief pauses mid-sentence to be detected as the end of speech and trigger responses prematurely.
  • semantic_vad: If valid short responses such as "OK" or "yes" fail to trigger a response, when using Qwen3.8-Omni-Flash-Realtime series models, try switching type to semantic_vad_ec. Compared with semantic_vad, this mode makes it easier to detect user speech and trigger interruptions, while retaining the ability to filter out meaningless sounds such as background noise.

What if I don't receive the ASR transcription text (transcript)?

A: If you do not receive the conversation.item.input_audio_transcription.completed event, or the transcript in the event is empty, check the following in order:
  1. Input transcription configuration. The enable_input_audio_transcription parameter of the DashScope Python SDK's update_session defaults to True; when set to False, the SDK sets input_audio_transcription in the session to null. When using WebSocket directly, or sending session configuration via a WebRTC DataChannel, check the session.update.session.input_audio_transcription you send against Input audio transcription configuration. enable_input_audio_transcription is an SDK parameter, not a top-level field of session.update.
  2. Transcription failure event. Also listen for conversation.item.input_audio_transcription.failed. On failure, check the error information in the event's error.code, error.message, and error.param.
  3. Whether the audio has been committed. In VAD mode, check whether the server detected the start and end of speech; in Manual mode, confirm that input_audio_buffer.commit has been sent. If the current round of audio has not been committed, do not just wait for the transcription completion event.
  4. Connection and SDK version. Confirm that the connection was not interrupted during the current round of audio input; for WebRTC access, also check the DataChannel status. When using the DashScope Python SDK, verify that the version meets the minimum requirement of this document (2.0.1).

Error codes

If a model call fails and returns an error message, see Error codes for troubleshooting.

API and SDK reference

For the process and examples of connecting via AOQ, see AOQ access. For protocol selection and reference entry points, see API reference.