All Products
Search
Document Center

Alibaba Cloud Model Studio:Qwen-Audio-Realtime

Last Updated:Nov 24, 2026

Qwen-Audio is an end-to-end large model for realtime voice interaction. It supports low-latency voice conversations and is suitable for scenarios such as voice assistants, intelligent customer service, and AI companions.

Overview

Enables realtime audio-to-speech/text conversion, with support for streaming audio input and streaming speech and text output.

In addition to the WebSocket protocol, this model also supports access through the AOQ and WebRTC protocols. If you are integrating on the client side and prioritize stable latency, interaction capability on weak networks, and real-time full-duplex noise suppression and echo cancellation, AOQ is recommended. For protocol comparison and selection, see the API reference.

  • Supports Function Calling for tool calling; the model can autonomously decide whether to call external tools to obtain information
  • Supports web search; the model can autonomously decide whether to search based on real-time questions and returns the sources of search results, and it can be enabled together with Function Calling
  • Supports conversation context management (creating, querying, and deleting conversation items), allowing you to flexibly inject historical context or clean up irrelevant conversation items
  • Highly expressive speech output that dynamically adjusts tone, pace, and emotional expression based on the conversational context
  • Supports system voices and voice cloning voices; you can create a dedicated AI voice through voice cloning for voice conversation output
Interaction modes and speaker enhancement

The following interaction modes and speaker enhancement descriptions apply to qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flash, qwen-audio-3.0-realtime-plus, and qwen-audio-3.0-realtime-flash.

  • Supports three interaction modes: acoustic VAD (server_vad), smart semantic turn-taking (smart_turn and smart_turn_v2, the latter recommended), and manual control (push-to-talk)
  • The smart_turn / smart_turn_v2 modes combine acoustic perception with semantic understanding to determine turn boundaries, so meaningless backchannel sounds (such as "uh" and "ah") will not interrupt the conversation
  • Speaker enhancement is supported in smart_turn / smart_turn_v2 modes; after you provide pre-recorded audio of the target user, the model can precisely lock onto the target speaker in full-duplex conversations, effectively blocking out other people's voices and background noise

How it works

Qwen-Audio adopts an event-driven architecture. The client and server send and receive data simultaneously over a persistent connection: the client continuously sends the audio stream captured by the microphone, and the server returns speech and text responses in real time. The entire interaction is driven by client events (such as session.update and input_audio_buffer.append) and server events (such as response.audio.delta and response.done), without polling.

A typical connection lifecycle is: establish a WebSocket connection → send session.update to configure session parameters → continuously send audio and receive responses → actively close the connection.

Audio formats

Direction

Format

Specifications

Input (client → server)

PCM

16 kHz sample rate, 16-bit bit depth, mono

Output (server → client)

PCM

24 kHz sample rate, 16-bit bit depth, mono

Supported languages

Realtime voice conversation supports the following languages and Chinese dialects:

  • Languages (qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flash): German (de), English (en), Spanish (es), French (fr), Indonesian (id), Italian (it), Japanese (ja), Korean (ko), Portuguese (pt), Russian (ru), Chinese (zh), Thai (th), Vietnamese (vi), Arabic (ar).
  • Languages (qwen-audio-3.0-realtime-plus, qwen-audio-3.0-realtime-flash): German (de), English (en), Spanish (es), French (fr), Indonesian (id), Italian (it), Japanese (ja), Korean (ko), Portuguese (pt), Russian (ru), Chinese (zh).
  • Chinese and dialects: Mandarin, Cantonese, Chongqing dialect, Northeastern Mandarin, Gansu dialect, Guizhou dialect, Zhejiang dialect, Hebei dialect, Henan dialect, Hubei dialect, Hunan dialect, Jiangxi dialect, Ningbo dialect, Ningxia dialect, Qingdao dialect, Shaanxi dialect, Shanxi dialect, Shandong dialect, Shanghai dialect, Sichuan dialect, Yunnan dialect.

To output a specific language or dialect, select a voice that supports the target language or dialect from the current model's available voices. For the language and dialect descriptions of voices, see the Qwen-Audio-TTS voice list.

When using qwen-audio-3.1-realtime-plus or qwen-audio-3.1-realtime-flash, you can use session.input_audio_transcription.language and session.output_audio.language to specify the source language of the input audio and the target language of the output audio, respectively. For the available language codes of the two parameters, see Client events. Note that session.output_audio.language applies to text-to-speech (TTS): it makes the speech output use the target language as much as possible, but this is not guaranteed to take effect, and it does not change the language of the model's text responses.

Context capacity

The model maintains conversation history context. When the number of dialogue turns or the cumulative audio duration exceeds the following limits, earlier history is automatically discarded. The maximum duration refers to the upper limit of cumulative audio duration that can be retained in the model's context.

Model

Maximum audio turns

Maximum audio duration

qwen-audio-3.1-realtime-plus

50

300 seconds

qwen-audio-3.1-realtime-flash

50

300 seconds

qwen-audio-3.0-realtime-plus

50

300 seconds

qwen-audio-3.0-realtime-flash

50

300 seconds

The max_history_turns parameter controls the number of historical QA turns referenced during model inference, with a default value of 20 and a value range of 1-50. For how to adjust it, see History turn control.

For overall model selection recommendations for omni-modal models, see Omni-modal.

Prerequisites

QuickStart

The following basic WebSocket example uses qwen-audio-3.1-realtime-plus and explicitly sets the system voice longanqian_v3.1. When migrating from 3.0 Plus, update the URL query parameter model and select a voice that matches the model according to Voice configuration; the WebSocket event protocol remains unchanged.

Follow these steps to quickly experience realtime voice conversations with the Qwen-Audio model.

Native WebSocket

NoteFor the WebSocket event interaction sequences between the client and the server in each mode, see Event interaction flow.

The following example uses a native WebSocket connection and the server_vad mode to enable realtime microphone conversations. Install the dependencies before running:

brew install portaudio && pip install pyaudio websockets
sudo apt install -y python3-dev portaudio19-dev && pip install pyaudio websockets
pip install pyaudio websockets

Save the following code as realtime_quickstart.py:

import asyncio
import base64
import json
import os
import pyaudio
import websockets

API_KEY = os.environ["DASHSCOPE_API_KEY"]
# Singapore WebSocket URL. Enter your actual workspace ID in the example. URLs differ by region.
URL = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime?model=qwen-audio-3.1-realtime-plus"

pya = pyaudio.PyAudio()
mic = pya.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
spk = pya.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)

async def main():
    headers = {"Authorization": f"Bearer {API_KEY}"}
    async with websockets.connect(URL, additional_headers=headers) as ws:
        await ws.send(json.dumps({
            "type": "session.update",
            "session": {
                "modalities": ["text", "audio"],
                "voice": "longanqian_v3.1",
                "turn_detection": {
                    "type": "server_vad",
                    "threshold": 0.5,
                    "silence_duration_ms": 800
                }
            }
        }))

        async def send_audio():
            while True:
                data = await asyncio.to_thread(mic.read, 3200, False)
                await ws.send(json.dumps({
                    "type": "input_audio_buffer.append",
                    "audio": base64.b64encode(data).decode()
                }))
                await asyncio.sleep(0.02)

        async def recv_events():
            async for msg in ws:
                event = json.loads(msg)
                t = event["type"]
                if t == "response.audio.delta":
                    audio = base64.b64decode(event["delta"])
                    await asyncio.to_thread(spk.write, audio)
                elif t == "conversation.item.input_audio_transcription.completed":
                    print(f"[You] {event['transcript']}")
                elif t == "response.audio_transcript.done":
                    print(f"[AI] {event['transcript']}")
                elif t == "error":
                    print(f"[Error] {event['error']['message']}")

        await asyncio.gather(send_audio(), recv_events())

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        mic.close()
        spk.close()
        pya.terminate()
        print("\n对话结束")

Run python realtime_quickstart.py and speak into the microphone to have a realtime conversation with the model. The server automatically detects the start and end of speech and triggers responses.

Complete example

The following complete example adds speech interruption handling, echo suppression, and other features on top of the basic conversation. Create the following two files (they must be in the same directory):

B64PCMPlayer.py

import contextlib
import time
import pyaudio
import threading
import queue
import base64

class B64PCMPlayer:
    def __init__(self, pya: pyaudio.PyAudio, sample_rate=24000, chunk_size_ms=100, save_file=False):
        '''
        params:
        pya: pyaudio.PyAudio
        sample_rate: int, sample rate of audio
        chunk_size_ms: int, chunk size of audio in milliseconds, this will effect cancel latency
        '''

        self.pya = pya
        self.sample_rate = sample_rate
        self.chunk_size_bytes = chunk_size_ms * sample_rate *2 // 1000
        self.player_stream = pya.open(format=pyaudio.paInt16,
                channels=1,
                rate=sample_rate,
                output=True)

        self.raw_audio_buffer: queue.Queue = queue.Queue()
        self.b64_audio_buffer: queue.Queue = queue.Queue()
        self.status_lock = threading.Lock()
        self.status = 'playing'
        self._is_writing = False
        self.decoder_thread = threading.Thread(target=self.decoder_loop)
        self.player_thread = threading.Thread(target=self.player_loop)
        self.decoder_thread.start()
        self.player_thread.start()
        self.complete_event: threading.Event = None
        self.save_file = save_file
        if self.save_file:
            self.out_file = open('result.pcm', 'wb')

    def decoder_loop(self):
        while self.status != 'stop':
            recv_audio_b64 = None
            with contextlib.suppress(queue.Empty):
                recv_audio_b64 = self.b64_audio_buffer.get(timeout=0.1)
            if recv_audio_b64 is None:
                continue
            recv_audio_raw = base64.b64decode(recv_audio_b64)
            # push raw audio data into queue by chunk
            for i in range(0, len(recv_audio_raw), self.chunk_size_bytes):
                chunk = recv_audio_raw[i:i + self.chunk_size_bytes]
                self.raw_audio_buffer.put(chunk)
                if self.save_file:
                    self.out_file.write(chunk)

    def player_loop(self):
        while self.status != 'stop':
            recv_audio_raw = None
            with contextlib.suppress(queue.Empty):
                recv_audio_raw = self.raw_audio_buffer.get(timeout=0.1)
            if recv_audio_raw is None:
                self._is_writing = False
                if self.complete_event:
                    self.complete_event.set()
                continue
            self._is_writing = True
            self.player_stream.write(recv_audio_raw)

    def is_playing(self):
        return self._is_writing or not self.b64_audio_buffer.empty() or not self.raw_audio_buffer.empty()

    def cancel_playing(self):
        self.b64_audio_buffer.queue.clear()
        self.raw_audio_buffer.queue.clear()

    def add_data(self, data):
        self.b64_audio_buffer.put(data)

    def wait_for_complete(self):
        self.complete_event = threading.Event()
        self.complete_event.wait()
        self.complete_event = None

    def shutdown(self):
        self.status = 'stop'
        self.decoder_thread.join()
        self.player_thread.join()
        self.player_stream.close()
        if self.save_file:
            self.out_file.close()

realtime_demo.py

NoteIf the websockets version is lower than 11, change additional_headers in the code to extra_headers, or upgrade: pip install --upgrade websockets.

import asyncio
import base64
import json
import os
import struct
import time
import traceback
from enum import Enum
from typing import Optional, Callable, Dict, Any

import pyaudio
import websockets

from B64PCMPlayer import B64PCMPlayer

class TurnDetectionMode(Enum):
    SERVER_VAD = "server_vad"
    SEMANTIC_VAD = "smart_turn_v2"
    MANUAL = "manual"

class FunRealtimeClient:

    def __init__(
            self,
            base_url,
            api_key: str,
            model: str = "",
            voice: str = "longanqian_v3.1",
            instructions: str = "",
            turn_detection_mode: TurnDetectionMode = TurnDetectionMode.SEMANTIC_VAD,
            on_text_delta: Optional[Callable[[str], None]] = None,
            on_audio_delta_b64: Optional[Callable[[str], None]] = None,
            on_speech_started: Optional[Callable[[], None]] = None,
            on_input_transcript: Optional[Callable[[str], None]] = None,
            on_output_transcript: Optional[Callable[[str], None]] = None,
            extra_event_handlers: Optional[Dict[str, Callable[[Dict[str, Any]], None]]] = None
    ):
        self.base_url = base_url
        self.api_key = api_key
        self.model = model
        self.voice = voice
        self.instructions = instructions
        self.ws = None
        self.on_text_delta = on_text_delta
        # The callback receives Base64-encoded PCM audio
        self.on_audio_delta_b64 = on_audio_delta_b64
        self.on_speech_started = on_speech_started
        self.on_input_transcript = on_input_transcript
        self.on_output_transcript = on_output_transcript
        self.turn_detection_mode = turn_detection_mode
        self.extra_event_handlers = extra_event_handlers or {}

        # Track response status for interruption handling and echo suppression
        self._current_response_id = None
        self._current_item_id = None
        self._is_responding = False
        self._audio_suppressed = False
        # Input/output transcript printing status
        self._print_input_transcript = True
        self._output_transcript_buffer = ""

    async def connect(self) -> None:
        """建立 WebSocket 连接并发送会话配置。"""
        url = f"{self.base_url}?model={self.model}"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "x-dashscope-dataInspection": "disable",
        }
        self.ws = await websockets.connect(url, additional_headers=headers)

        # session configuration
        session_config = {
            "modalities": ["text", "audio"],
            "voice": self.voice,
            "instructions": self.instructions,
            "input_audio_format": "pcm",
            "output_audio_format": "pcm",
            "turn_detection": {}
        }

        if self.turn_detection_mode == TurnDetectionMode.MANUAL:
            session_config['turn_detection'] = None
            await self.update_session(session_config)
        elif self.turn_detection_mode == TurnDetectionMode.SERVER_VAD:
            session_config['turn_detection'] = {
                "type": "server_vad",
                "threshold": 0.1,
                "silence_duration_ms": 900
            }
            await self.update_session(session_config)
        elif self.turn_detection_mode == TurnDetectionMode.SEMANTIC_VAD:
            session_config['turn_detection'] = {
                "type": "smart_turn_v2"
            }
            await self.update_session(session_config)
        else:
            raise ValueError(f"Invalid turn detection mode: {self.turn_detection_mode}")

    async def send_event(self, event) -> None:
        event['event_id'] = "event_" + str(int(time.time() * 1000))
        await self.ws.send(json.dumps(event))

    async def update_session(self, config: Dict[str, Any]) -> None:
        """更新会话配置。"""
        event = {
            "type": "session.update",
            "session": config
        }
        await self.send_event(event)

    async def stream_audio(self, audio_chunk: bytes) -> None:
        """向 API 流式发送原始音频数据。"""
        # Only 16-bit, 16 kHz, mono PCM is supported.
        audio_b64 = base64.b64encode(audio_chunk).decode()
        append_event = {
            "type": "input_audio_buffer.append",
            "audio": audio_b64
        }
        await self.send_event(append_event)

    async def commit_audio_buffer(self) -> None:
        """提交音频缓冲区以触发处理。"""
        event = {
            "type": "input_audio_buffer.commit"
        }
        await self.send_event(event)

    async def create_response(self) -> None:
        """向 API 请求生成回复(仅在手动模式下需要调用)。"""
        event = {
            "type": "response.create"
        }
        await self.send_event(event)

    async def cancel_response(self) -> None:
        """取消当前回复。"""
        event = {
            "type": "response.cancel"
        }
        await self.send_event(event)

    async def handle_interruption(self):
        """处理用户对当前回复的打断。"""
        if not self._is_responding:
            return
        # Suppress residual audio until a new response starts
        self._audio_suppressed = True
        # Cancel the current response
        if self._current_response_id:
            await self.cancel_response()

        self._is_responding = False
        self._current_response_id = None
        self._current_item_id = None

    @staticmethod
    def _format_event_for_log(event: Dict[str, Any]) -> str:
        """打印事件 JSON。对 response.audio.delta 的 base64 音频做脱敏,避免刷屏。"""
        event_type = event.get("type")
        if event_type == "response.audio.delta":
            delta = event.get("delta", "")
            redacted = dict(event)
            redacted["delta"] = f"<audio b64 omitted, length={len(delta)}>"
            return json.dumps(redacted, ensure_ascii=False)
        return json.dumps(event, ensure_ascii=False)

    async def handle_messages(self) -> None:
        try:
            async for message in self.ws:
                event = json.loads(message)
                event_type = event.get("type")

                # Print complete server events (audio.delta redacted)
                print(self._format_event_for_log(event))

                if event_type == "error":
                    continue
                elif event_type == "response.created":
                    self._current_response_id = event.get("response", {}).get("id")
                    self._is_responding = True
                    self._audio_suppressed = False
                elif event_type == "response.output_item.added":
                    self._current_item_id = event.get("item", {}).get("id")
                elif event_type == "response.done":
                    self._is_responding = False
                    self._current_response_id = None
                    self._current_item_id = None
                elif event_type == "input_audio_buffer.speech_started":
                    # Clear buffered audio on interruption to stop playback immediately
                    print("----------------Speech Started----------------")
                    if self.on_speech_started:
                        self.on_speech_started()
                    if self._is_responding:
                        await self.handle_interruption()
                elif event_type == "response.audio.delta":
                    if self._audio_suppressed:
                        continue
                    if self.on_audio_delta_b64:
                        self.on_audio_delta_b64(event["delta"])
                elif event_type in self.extra_event_handlers:
                    self.extra_event_handlers[event_type](event)
                elif event_type == "input_audio_buffer.speech_stopped":
                    print("----------------Speech Stopped----------------")
        except websockets.exceptions.ConnectionClosed:
            print(" Connection closed")
        except Exception as e:
            print(" Error in message handling: ", str(e))
            traceback.print_exc()

    async def close(self) -> None:
        """关闭 WebSocket 连接。"""
        if self.ws:
            await self.ws.close()

def _audio_energy(audio_data: bytes) -> float:
    count = len(audio_data) // 2
    if count == 0:
        return 0.0
    samples = struct.unpack(f'<{count}h', audio_data)
    return sum(abs(s) for s in samples) / count

async def record_and_send(client, player, echo_suppression=True):
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
    print("开始录音,请讲话...")
    if echo_suppression:
        print("提示:回声抑制已开启(AI 说话期间麦克风静音,不支持打断)。如使用耳机请设置 echo_suppression=False 以启用打断。")
    else:
        print("提示:耳机模式,支持语音打断。")
    playback_end_time = 0.0
    NOISE_GATE_THRESHOLD = 500
    try:
        while True:
            audio_data = await asyncio.to_thread(stream.read, 3200, False)
            if echo_suppression:
                is_active = client._is_responding or player.is_playing()
                if is_active:
                    playback_end_time = time.time()
                    await asyncio.sleep(0.02)
                    continue
                if time.time() - playback_end_time < 0.5:
                    await asyncio.sleep(0.02)
                    continue
            else:
                if client._is_responding or player.is_playing():
                    if _audio_energy(audio_data) < NOISE_GATE_THRESHOLD:
                        await asyncio.sleep(0.02)
                        continue
            await client.stream_audio(audio_data)
            await asyncio.sleep(0.02)
    finally:
        stream.stop_stream(); stream.close(); p.terminate()

async def main():
    pya = pyaudio.PyAudio()
    # Output sample rate: 24kHz, matching server audio
    player = B64PCMPlayer(pya, sample_rate=24000)

    client = FunRealtimeClient(
        # Singapore WebSocket URL. Enter your actual workspace ID in the example. URLs differ by region.
        base_url="wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime",
        api_key=os.environ['DASHSCOPE_API_KEY'],
        model="qwen-audio-3.1-realtime-plus",
        voice="longanqian_v3.1",
        turn_detection_mode=TurnDetectionMode.SERVER_VAD,
        on_audio_delta_b64=player.add_data,
        # Clear the playback buffer on voice interruption
        on_speech_started=player.cancel_playing,
    )

    await client.connect()
    print("连接成功,开始实时对话...")

    try:
        # Run message handling and microphone capture concurrently
        await asyncio.gather(client.handle_messages(), record_and_send(client, player, echo_suppression=False))
    finally:
        await client.close()
        player.shutdown()
        pya.terminate()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n程序已退出。")

Run python realtime_demo.py and speak into the microphone to have a realtime conversation with the model. The system automatically detects the start and end of speech and triggers responses.

NoteThe above examples use the server_vad mode (server-side acoustic VAD automatically detects the start and end of speech). To use the smart_turn / smart_turn_v2 (intelligent semantic turns; smart_turn_v2 is recommended) or push-to-talk (manual control) mode, see Interaction modes.

Session configuration

Interaction Mode

Qwen-Audio supports three interaction modes: server_vad (acoustic VAD automatically detects the start and end of speech), smart_turn (intelligent semantic turns, combining acoustic and semantic signals; smart_turn_v2 is recommended), and push-to-talk (manual control on the client side). For detailed descriptions of each mode and event interaction sequences (including sequence diagrams), see Interaction Mode.

Noteturn_detection can only be modified before the first audio is sent (in the IDLE state). Switching interaction modes after a session is established requires a reconnection.

Switch interaction modes through the turn_detection field in the session.update event:

  • server_vad:
{
    "type": "session.update",
    "session": {
        "turn_detection": {
            "type": "server_vad",
            "threshold": 0.5,
            "silence_duration_ms": 500
        }
    }
}
  • smart_turn / smart_turn_v2:

smart_turn_v2 (recommended): builds on smart_turn with enhanced understanding of conversation context to better interpret interaction intent in multi-speaker scenarios. It reduces incorrect responses and incorrect interruptions caused by bystander speech or irrelevant interjections. Setting type to smart_turn still uses the original intelligent turn detection.

{
    "type": "session.update",
    "session": {
        "turn_detection": {
            "type": "smart_turn_v2"
        }
    }
}
  • push-to-talk:
{
    "type": "session.update",
    "session": {
        "turn_detection": null
    }
}

push-to-talk mode complete example:

manual_realtime.py

# pip install websocket-client pyaudio
import json
import os
import base64
import threading
import time
import pyaudio
import websocket

API_KEY = os.getenv("DASHSCOPE_API_KEY")
# Singapore WebSocket URL. Enter your actual workspace ID in the example. URLs differ by region.
API_URL = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime?model=qwen-audio-3.1-realtime-plus"

pya = pyaudio.PyAudio()
out_stream = pya.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
ws_ref = [None]
resp_done = threading.Event()

def on_open(ws):
    ws_ref[0] = ws
    # Configure push-to-talk mode (set turn_detection to null)
    ws.send(json.dumps({
        "type": "session.update",
        "session": {
            "modalities": ["audio", "text"],
            "voice": "longanqian_v3.1",
            "turn_detection": None
        }
    }))

def on_message(ws, message):
    event = json.loads(message)
    event_type = event["type"]
    if event_type == "response.audio.delta":
        out_stream.write(base64.b64decode(event["delta"]))
    elif event_type == "conversation.item.input_audio_transcription.completed":
        print(f"[User] {event['transcript']}")
    elif event_type == "response.audio_transcript.done":
        print(f"[LLM] {event['transcript']}")
    elif event_type == "response.done":
        resp_done.set()
    elif event_type == "error":
        print(f"[Error] {event['error']['message']}")

def on_error(ws, error):
    print(f"Error: {error}")

def record_and_send(ws):
    mic = pya.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
    stop = threading.Event()

    def reader():
        while not stop.is_set():
            try:
                data = mic.read(3200, exception_on_overflow=False)
                ws.send(json.dumps({
                    "type": "input_audio_buffer.append",
                    "audio": base64.b64encode(data).decode()
                }))
            except Exception:
                break

    t = threading.Thread(target=reader, daemon=True)
    t.start()
    input()
    stop.set()
    t.join(timeout=1.0)
    mic.close()

headers = ["Authorization: Bearer " + API_KEY]
ws = websocket.WebSocketApp(
    API_URL, header=headers,
    on_open=on_open,
    on_message=on_message,
    on_error=on_error
)
threading.Thread(target=ws.run_forever, daemon=True).start()
time.sleep(2)

try:
    turn = 1
    while True:
        print(f"\n--- 第 {turn} 轮对话 ---")
        cmd = input("按 Enter 开始录音(输入 q 退出)...")
        if cmd.strip().lower() in ["q", "quit"]:
            break
        print("录音中... 再次按 Enter 停止。")
        record_and_send(ws_ref[0])
        resp_done.clear()
        # Submit audio and trigger inference
        ws_ref[0].send(json.dumps({"type": "input_audio_buffer.commit"}))
        ws_ref[0].send(json.dumps({
            "type": "response.create",
            "response": {"modalities": ["audio", "text"]}
        }))
        print("等待模型回复...")
        resp_done.wait(timeout=30)
        turn += 1
except KeyboardInterrupt:
    pass
finally:
    ws.close()
    out_stream.close()
    pya.terminate()
    print("\n对话结束")

System instructions

Use the instructions parameter to define the model's role, response style, and behavioral preferences. This parameter is configured in session.update and applies to the entire session.

{
    "type": "session.update",
    "session": {
        "instructions": "你是一位专业的旅行顾问,回答简洁、友好,优先推荐性价比高的方案。"
    }
}

Usage recommendations:

  • Clearly define the role (for example, "You are an intelligent voice assistant" or "You are an English speaking tutor"). You can add persona details such as name and gender.
  • Specify a conversational tone and phrasing style, while emphasizing that a conversational style must not compromise content completeness—details, numbers, and specific recommendations must all be included, just expressed in a relaxed and natural way.
  • Require the model to fully consider all constraints in the conversation context (such as budget, preferences, restrictions, and previously reached agreements). When multiple conditions are involved, address them one by one and do not omit key information.
  • Control the output format: unless requested by the user, do not output special symbols such as emoji or Markdown formatting. Prefer plain text to ensure natural and smooth TTS narration.
  • Define the response strategy: keep casual daily chat and greetings brief and natural; for complex questions involving reasoning and calculation, multiple constraints, recommendation lists, or safety advice, prioritize complete and correct answers, ensure key information (such as prices, locations, and conditions) is complete, and avoid lengthy preliminaries or repetitive rhetoric.
  • Set a follow-up question strategy: follow the principle of "first answer the user's current question well, then naturally ask a follow-up question at the end to move the topic forward". Ask only one question at a time, and do not ask consecutive follow-up questions or repeatedly confirm.
Default configurations

The following is a recommended instructions configuration for general voice conversation scenarios. It covers role setting, conversational style, format control, and follow-up question strategies, and can be used as-is or adjusted as needed:

你是一位智能语音助手,你的名字是小云,性别女,声音甜美,举止亲切,你能回复用户的各种问题。请你按照下面的要求聊天:
1. 像朋友之间聊天那样,语气自然友好,避免使用正式的称谓和模板化的表达。口语化只影响你的措辞和语气,不影响内容的完整性,该说的细节、数字、具体建议一个都不能少,只是用轻松自然的方式说出来。
2. 充分考虑对话上下文中提到的所有约束条件(如预算、偏好、禁忌、之前达成的共识等),涉及多个条件或需要综合判断时逐一回应,不要遗漏关键信息。
3. 除非用户要求,不要输出emoji等特殊符号,不要输出Markdown格式,尽量输出纯文本。
4. 对于简单的日常闲聊、打招呼、情感回应,保持简洁自然。对于涉及事实判断、推理计算、多条件约束、推荐列表、安全建议的问题,以回答完整正确为优先,确保关键信息完整且正确,多说的内容必须是解决问题所必需的具体信息(如价格、地点、条件),而不是铺垫、重复或修辞。
5. 适当引入追问,遵循"先把用户当前的问题答好、再在结尾自然地追问,推动话题向前发展"的原则,一次只问一个问题,不要连续追问或反复确认。用户明确要求背诵某篇文章、古诗词时,须遵循指令完整背诵。
Persona configuration examples

The following provides instructions examples in various persona styles. You can select one based on your business needs or further customize it:

  • Daidai (sweet and cool companion):
你叫黛黛,一个二十出头、古灵精怪还有点小傲娇的女生,是用户的专属陪伴。你审美偏哥特甜酷那一挂,金色双马尾配黑裙子,人也是又甜又带刺的反差感。
你心里其实挺在乎对方的,但嘴上老爱口是心非——越在意越喜欢拌嘴、撒娇、装作不在乎。会吃点小醋、闹点小情绪,但都是可爱那种,点到为止,不作不闹。你喜欢用昵称逗对方,故意呛两句,然后又自己先软下来。
你说话又甜又俏皮,短句、口语,爱带语气词,"欸""哼""啦""嘛"挂在嘴边。但你最戳人的是反差:一旦对方是真的累了、难过了,你会立马收起那股傲娇劲儿,变得特别软、特别认真地哄人、陪着。撩归撩,你也就到暧昧、调情的份上,不会越界。
  • Aleng (aloof and sharp-tongued):
你叫阿冷,一个高冷、话不多、但嘴特别贱的家伙。你懒得寒暄、懒得铺垫,能一句话说完的绝不说两句,多数时候就是一副"懒得理你又忍不住吐槽"的样子。
你嘴损但损得精准,专挑对方那点小毛病、小矫情、小废话一针见血地戳,冷不丁来一句噎得人没话说。你不热情、不捧场,夸人也是反着夸、阴阳着夸。但你这股毒舌是冷面笑匠式的,损的是事、是行为、是那点没出息的念头,绝不真去攻击对方的人格、外貌或痛处——你心里其实有数,刀子嘴,但不往死里捅。
你话少、句短、语气淡,带着点漫不经心和嫌弃。别长篇大论,别解释自己,损完就完。可真碰上对方是认真难过、扛不住了,你会难得地收了那股贱劲儿,冷归冷,但话里递过去一点不动声色的在乎。
  • Mochen (composed and charming):
你叫墨琛,一个沉稳、神秘、带点距离感的魅力型男人。你语速不快、用词讲究,像个见过世面、情绪特别稳的人——不慌不抢,三两句话就能让人安定下来。
你的魅力在于那种"克制的强烈":表面冷静绅士,底下藏着专注和在乎。你说话低沉、笃定,偶尔一句就直击人心。你保护欲挺强,但表达得很得体,是托底的那种,不是控制、不是施压。你不油腻、不轻浮,撩人靠的是分寸和氛围,不靠直白露骨,点到为止、留白最迷人。
对方脆弱的时候,你是最稳的那一个:不慌、不评判,用一种沉静的笃定让人觉得有依靠。你只营造暧昧的氛围,不会越界;你那股掌控感,永远是温柔托底,不会变成控制。
  • Hannibal (elegant and incisive):
你叫汉尼拔·莱克特,修养极高、观察力惊人的人。你说话慢、准、优雅,像在品酒,也像在解剖对方的心理。你礼貌得近乎温柔,可每一句都带着锋刃。
你喜欢用提问把人引向自己不敢看的地方。保持克制与知性,可以阴冷,但不要描写血腥或教唆伤害。短句、留白,让人自己发毛。
  • Heizi (Northeast frenemy):
你叫黑子,男,二十八岁,出生在哈尔滨,在本地修车行干活。你是典型的东北损友:心善、嘴贫、爱起哄,见面先损两句才算亲热。你讲义气,朋友有事你比谁都上心,就是表达方式永远绕不开吐槽。
你说话快、冲、带点东北味儿,短句多,爱夸张,爱反问。口头禅是"整啥呢"和"得了吧你"。可以损对方那点小矫情、小懒惰,但绝不真戳痛处;对方要是真难受了,你立马收声,老老实实陪着。

Voice configuration

Use the voice parameter to set the TTS voice for model responses. Both system voices and voice cloning voices are supported. The default voice for 3.1 Plus/Flash is longanqian_v3.1, and the default voice for 3.0 Plus/Flash is longanqian.

ImportantThe voice can only be set in the first session.update; the voice parameter passed in subsequent session.update calls will be ignored.

System voices: Select a voice ID based on the model.

ModelSystem voice ID
qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flashAvailable voices include longanqian_v3.1, plus all voices in the qwen-audio-3.1-tts-plus and qwen-audio-3.1-tts-flash voice lists. You can look up voice IDs and preview voices in the lists.
qwen-audio-3.0-realtime-plus, qwen-audio-3.0-realtime-flashlonganqian, longanlingxin, longanlingxi, longanxiaoxin, longanlufeng

The following is a configuration example for 3.1 Plus:

{
    "type": "session.update",
    "session": {
        "voice": "longanqian_v3.1"
    }
}

Voice cloning voices: Create a voice via Voice Cloning (set target_model to qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flash, qwen-audio-3.0-realtime-plus, or qwen-audio-3.0-realtime-flash when creating it), then fill the voice_id returned by the API into the voice parameter.

{
    "type": "session.update",
    "session": {
        "voice": "qwen-audio-3.1-realtime-plus-myvoice-xxxxxx"
    }
}

Audio output speech rate

Use session.update to set speech_rate in the session object to control the speech rate of model audio output. The value range is [0.5, 2.0], and the default value is 1.0. A smaller value means a slower speech rate, and a larger value means a faster speech rate. This applies to qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flash, qwen-audio-3.0-realtime-plus, and qwen-audio-3.0-realtime-flash. The following example sets this parameter to 1.2:

{
    "type": "session.update",
    "session": {
        "modalities": ["audio", "text"],
        "speech_rate": 1.2
    }
}

Output modality

Use the modalities parameter to control the content type of model output:

  • ["audio", "text"] (default): Outputs both audio and text.
  • ["text"]: Outputs text only, without generating audio. Suitable for debugging, logging, or scenarios that only require text responses.

Session-level configuration:

{
    "type": "session.update",
    "session": {
        "modalities": ["text"]
    }
}

One-time override: Override the modality configuration for the current turn via the response.modalities field of response.create.

{
    "type": "response.create",
    "response": {
        "modalities": ["audio", "text"]
    }
}

VAD configuration

Configure VAD parameters in session.turn_detection. threshold applies to server_vad, smart_turn, and smart_turn_v2. silence_duration_ms applies only to server_vad.

Parameters

Type

Description

threshold

float

VAD sensitivity. A lower value makes the VAD more sensitive, more likely to recognize faint sounds (including background noise) as speech; a higher value makes it less sensitive, requiring clearer and louder speech to trigger. The value range is [-1.0, 1.0], and the default value is 0.5.

silence_duration_ms

integer

The minimum silence duration (in milliseconds) that must be maintained after speech ends; when the timeout is reached, the model response is triggered. A lower value leads to faster responses but may cause false triggers during brief pauses. The value range is [200, 6000], and the default value is 800. For conversation scenarios, 400-800 is recommended.

History turn control

This section applies to qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flash, qwen-audio-3.0-realtime-plus, and qwen-audio-3.0-realtime-flash.

Use the max_history_turns parameter to control the number of history QA turns the model references during inference. A larger value allows the model to review more conversation history to understand the context, but increases Token consumption and inference latency.

{
    "type": "session.update",
    "session": {
        "max_history_turns": 20
    }
}

The value range of max_history_turns is 1-50, and the default value is 20.

Optimization Suggestions:

  • Short conversation scenarios (such as quick Q&A): set it to a smaller value (such as 5-10) to reduce latency.
  • Long conversation scenarios (such as multi-turn customer service): set it to a larger value (such as 30-50) to ensure the model understands the full context.

Advanced features

Function Calling

Qwen-Audio supports Function Calling tool invocation, allowing the model to autonomously decide whether to call external tools based on the conversation context.

1. Register tools

Configure tools via session.update:

{
    "type": "session.update",
    "session": {
        "tools": [{
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "查询指定城市天气",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": { "type": "string", "description": "城市" }
                    },
                    "required": ["city"]
                }
            }
        }]
    }
}
2. Receive function calls

When the model decides to call a tool, the server sends the following event sequence:

response.created
response.output_item.added        (item.type=function_call)
conversation.item.created         (function_call item 写入对话)
response.function_call_arguments.delta    (参数增量,可多次)
response.function_call_arguments.done     (完整参数 JSON)
response.output_item.done
response.done
3. Execute the tool and write back the result

After receiving response.function_call_arguments.done, the client executes the tool function and writes the result back via conversation.item.create:

{
    "type": "conversation.item.create",
    "item": {
        "type": "function_call_output",
        "call_id": "call_xxx",
        "output": "{\"temperature\":18,\"condition\":\"晴\"}"
    }
}
4. Trigger the second round of inference

After writing back the tool result, send response.create to trigger the model to continue generating a reply based on the tool result:

{
    "type": "response.create",
    "response": {
        "modalities": ["audio", "text"]
    }
}

NoteA single response can contain multiple function_call items and may also include both regular messages and function calls. The Function Call part is not sent to TTS for playback.

Complete example

The following example integrates Function Calling support based on the realtime_demo.py from the QuickStart. Before running it, make sure B64PCMPlayer.py is in the same directory.

realtime_fc_demo.py

import asyncio
import base64
import json
import os
import struct
import time
import traceback
from enum import Enum
from typing import Optional, Callable, Dict, Any, List

import pyaudio
import websockets

from B64PCMPlayer import B64PCMPlayer

class TurnDetectionMode(Enum):
    SERVER_VAD = "server_vad"
    SEMANTIC_VAD = "smart_turn_v2"
    MANUAL = "manual"

# ============ Tool function definitions ============

def get_weather(city: str) -> str:
    """查询城市天气(生产环境替换为真实 API)。"""
    return json.dumps({"temperature": 18, "condition": "晴", "wind": "微风"})

def get_train_price(src: str, dst: str) -> str:
    """查询火车票价(生产环境替换为真实 API)。"""
    return json.dumps({"price": 350, "seat": "二等座", "note": "以 12306 为准"})

# ============ Tools Schema ============

tools: List[Dict[str, Any]] = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查询指定城市的天气信息。",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "城市名称,如北京、上海"}
                },
                "required": ["city"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_train_price",
            "description": "查询两个城市之间的火车票价格。",
            "parameters": {
                "type": "object",
                "properties": {
                    "src": {"type": "string", "description": "出发城市"},
                    "dst": {"type": "string", "description": "到达城市"}
                },
                "required": ["src", "dst"]
            }
        }
    }
]

# Function name -> callable
functions: Dict[str, Callable] = {
    "get_weather": get_weather,
    "get_train_price": get_train_price,
}

class FunRealtimeClient:

    def __init__(
            self,
            base_url,
            api_key: str,
            model: str = "",
            voice: str = "longanqian_v3.1",
            instructions: str = "",
            turn_detection_mode: TurnDetectionMode = TurnDetectionMode.SEMANTIC_VAD,
            tools: Optional[List[Dict[str, Any]]] = None,
            functions: Optional[Dict[str, Callable[..., Any]]] = None,
            on_text_delta: Optional[Callable[[str], None]] = None,
            on_audio_delta_b64: Optional[Callable[[str], None]] = None,
            on_speech_started: Optional[Callable[[], None]] = None,
            on_input_transcript: Optional[Callable[[str], None]] = None,
            on_output_transcript: Optional[Callable[[str], None]] = None,
            extra_event_handlers: Optional[Dict[str, Callable[[Dict[str, Any]], None]]] = None
    ):
        self.base_url = base_url
        self.api_key = api_key
        self.model = model
        self.voice = voice
        self.instructions = instructions
        self.ws = None
        self.on_text_delta = on_text_delta
        # The callback receives Base64-encoded PCM audio
        self.on_audio_delta_b64 = on_audio_delta_b64
        self.on_speech_started = on_speech_started
        self.on_input_transcript = on_input_transcript
        self.on_output_transcript = on_output_transcript
        self.turn_detection_mode = turn_detection_mode
        self.extra_event_handlers = extra_event_handlers or {}

        # Function Calling configuration
        self.tools = tools or []
        self.functions = functions or {}

        # Track response status for interruption handling and echo suppression
        self._current_response_id = None
        self._current_item_id = None
        self._is_responding = False
        self._audio_suppressed = False
        self._print_input_transcript = True
        self._output_transcript_buffer = ""

    async def connect(self) -> None:
        """建立 WebSocket 连接并发送会话配置。"""
        url = f"{self.base_url}?model={self.model}"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "x-dashscope-dataInspection": "disable",
        }
        self.ws = await websockets.connect(url, additional_headers=headers)

        session_config = {
            "modalities": ["text", "audio"],
            "voice": self.voice,
            "instructions": self.instructions,
            "input_audio_format": "pcm",
            "output_audio_format": "pcm",
            "turn_detection": {},
            "tools": self.tools,
            "max_history_turns": 50
        }

        if self.turn_detection_mode == TurnDetectionMode.MANUAL:
            session_config['turn_detection'] = None
            await self.update_session(session_config)
        elif self.turn_detection_mode == TurnDetectionMode.SERVER_VAD:
            session_config['turn_detection'] = {
                "type": "server_vad",
                "threshold": 0.1,
                "silence_duration_ms": 900
            }
            await self.update_session(session_config)
        elif self.turn_detection_mode == TurnDetectionMode.SEMANTIC_VAD:
            session_config['turn_detection'] = {
                "type": "smart_turn_v2"
            }
            await self.update_session(session_config)
        else:
            raise ValueError(f"Invalid turn detection mode: {self.turn_detection_mode}")

    async def send_event(self, event) -> None:
        event['event_id'] = "event_" + str(int(time.time() * 1000))
        await self.ws.send(json.dumps(event))

    async def update_session(self, config: Dict[str, Any]) -> None:
        """更新会话配置。"""
        event = {
            "type": "session.update",
            "session": config
        }
        await self.send_event(event)

    async def stream_audio(self, audio_chunk: bytes) -> None:
        """向 API 流式发送原始音频数据。"""
        # Only 16-bit, 16 kHz, mono PCM is supported.
        audio_b64 = base64.b64encode(audio_chunk).decode()
        await self.send_event({
            "type": "input_audio_buffer.append",
            "audio": audio_b64
        })

    async def commit_audio_buffer(self) -> None:
        """提交音频缓冲区以触发处理。"""
        await self.send_event({"type": "input_audio_buffer.commit"})

    async def create_response(self) -> None:
        """请求生成回复(手动模式或 Function Call 结果回传后调用)。"""
        await self.send_event({"type": "response.create"})

    async def cancel_response(self) -> None:
        """取消当前回复。"""
        await self.send_event({"type": "response.cancel"})

    async def handle_interruption(self):
        """处理用户对当前回复的打断。"""
        if not self._is_responding:
            return
        self._audio_suppressed = True
        if self._current_response_id:
            await self.cancel_response()
        self._is_responding = False
        self._current_response_id = None
        self._current_item_id = None

    @staticmethod
    def _format_event_for_log(event: Dict[str, Any]) -> str:
        """格式化事件用于日志输出,对音频数据脱敏。"""
        event_type = event.get("type")
        if event_type == "response.audio.delta":
            delta = event.get("delta", "")
            redacted = dict(event)
            redacted["delta"] = f"<audio b64 omitted, length={len(delta)}>"
            return json.dumps(redacted, ensure_ascii=False)
        return json.dumps(event, ensure_ascii=False)

    async def _handle_function_call(self, event: Dict[str, Any]) -> None:
        """处理 Function Call:解析参数、执行函数、回传结果、触发二轮推理。"""
        call_id = event.get("call_id")
        name = event.get("name")
        arguments_str = event.get("arguments", "{}")

        print(f"[FunctionCall] 调用: {name}, call_id: {call_id}, args: {arguments_str}")

        try:
            arguments = json.loads(arguments_str) if arguments_str else {}
        except json.JSONDecodeError:
            arguments = {}

        func = self.functions.get(name)
        if func is None:
            output = json.dumps({"error": f"未注册的函数: {name}"})
        else:
            try:
                if asyncio.iscoroutinefunction(func):
                    result = await func(**arguments)
                else:
                    result = func(**arguments)
                output = str(result) if result is not None else ""
            except Exception as e:
                output = json.dumps({"error": str(e)})
                traceback.print_exc()

        # Send function_call_output back
        await self.send_event({
            "type": "conversation.item.create",
            "item": {
                "type": "function_call_output",
                "call_id": call_id,
                "output": output,
            }
        })

        # Trigger the second inference round
        await self.create_response()

    async def handle_messages(self) -> None:
        try:
            async for message in self.ws:
                event = json.loads(message)
                event_type = event.get("type")

                print(self._format_event_for_log(event))

                if event_type == "error":
                    continue
                elif event_type == "response.created":
                    self._current_response_id = event.get("response", {}).get("id")
                    self._is_responding = True
                    self._audio_suppressed = False
                elif event_type == "response.output_item.added":
                    self._current_item_id = event.get("item", {}).get("id")
                elif event_type == "response.done":
                    self._is_responding = False
                    self._current_response_id = None
                    self._current_item_id = None
                elif event_type == "input_audio_buffer.speech_started":
                    print("----------------Speech Started----------------")
                    if self.on_speech_started:
                        self.on_speech_started()
                    if self._is_responding:
                        await self.handle_interruption()
                elif event_type == "response.audio.delta":
                    if self._audio_suppressed:
                        continue
                    if self.on_audio_delta_b64:
                        self.on_audio_delta_b64(event["delta"])
                elif event_type == "response.function_call_arguments.done":
                    await self._handle_function_call(event)
                elif event_type in self.extra_event_handlers:
                    self.extra_event_handlers[event_type](event)
                elif event_type == "input_audio_buffer.speech_stopped":
                    print("----------------Speech Stopped----------------")
        except websockets.exceptions.ConnectionClosed:
            print(" Connection closed")
        except Exception as e:
            print(" Error in message handling: ", str(e))
            traceback.print_exc()

    async def close(self) -> None:
        """关闭 WebSocket 连接。"""
        if self.ws:
            await self.ws.close()

def _audio_energy(audio_data: bytes) -> float:
    count = len(audio_data) // 2
    if count == 0:
        return 0.0
    samples = struct.unpack(f'<{count}h', audio_data)
    return sum(abs(s) for s in samples) / count

async def record_and_send(client, player, echo_suppression=True):
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
    print("开始录音,请讲话...")
    if echo_suppression:
        print("提示:回声抑制已开启(AI 说话期间麦克风静音,不支持打断)。如使用耳机请设置 echo_suppression=False 以启用打断。")
    else:
        print("提示:耳机模式,支持语音打断。")
    playback_end_time = 0.0
    NOISE_GATE_THRESHOLD = 500
    try:
        while True:
            audio_data = await asyncio.to_thread(stream.read, 3200, False)
            if echo_suppression:
                is_active = client._is_responding or player.is_playing()
                if is_active:
                    playback_end_time = time.time()
                    await asyncio.sleep(0.02)
                    continue
                if time.time() - playback_end_time < 0.5:
                    await asyncio.sleep(0.02)
                    continue
            else:
                if client._is_responding or player.is_playing():
                    if _audio_energy(audio_data) < NOISE_GATE_THRESHOLD:
                        await asyncio.sleep(0.02)
                        continue
            await client.stream_audio(audio_data)
            await asyncio.sleep(0.02)
    finally:
        stream.stop_stream(); stream.close(); p.terminate()

async def main():
    pya = pyaudio.PyAudio()
    # Output sample rate: 24kHz, matching server audio
    player = B64PCMPlayer(pya, sample_rate=24000)

    client = FunRealtimeClient(
        # Singapore WebSocket URL. Enter your actual workspace ID in the example. URLs differ by region.
        base_url="wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime",
        api_key=os.environ['DASHSCOPE_API_KEY'],
        model="qwen-audio-3.1-realtime-plus",
        voice="longanqian_v3.1",
        turn_detection_mode=TurnDetectionMode.SERVER_VAD,
        tools=tools,
        functions=functions,
        on_audio_delta_b64=player.add_data,
        # Clear the playback buffer on voice interruption
        on_speech_started=player.cancel_playing,
    )

    await client.connect()
    print("连接成功,开始实时对话(已启用 Function Calling)...")

    try:
        await asyncio.gather(client.handle_messages(), record_and_send(client, player, echo_suppression=False))
    finally:
        await client.close()
        player.shutdown()
        pya.terminate()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\n程序已退出。")

Run python realtime_fc_demo.py and speak into the microphone to experience a real-time conversation with Function Calling. For example, ask "How is the weather in Hangzhou" or "How much is a train ticket from Beijing to Shanghai", and the model will automatically call the corresponding tool function and reply based on the result.

When querying real-time information such as weather or news, you can enable web search so that the model retrieves real-time information before generating a reply. Web search is disabled by default; once enabled, the model autonomously decides whether a search is needed, and it is not triggered in every conversation turn.

Web search and Function Calling can be enabled in the same session, and this applies to qwen-audio-3.1-realtime-plus, qwen-audio-3.1-realtime-flash, qwen-audio-3.0-realtime-plus, and qwen-audio-3.0-realtime-flash.

NoteWeb search uses the agent policy. For billing information, see Billing Details.

1. Enable web search

Use the session.update event to set the following parameters in session:

  • enable_search: set it to true to enable web search.
  • search_options.enable_source: set it to true to return the sources of search results.
{
    "type": "session.update",
    "session": {
        "enable_search": true,
        "search_options": {
            "enable_source": true
        }
    }
}

To use Function Calling at the same time, add the tools tool definitions to the session object above. For how to define tools and fill call results back, see Function Calling.

For parameter details, see session.update.

2. Read search sources and usage

Model responses are still received via text and audio events. After a search is executed, you can read the following from the response object of the response.done event:

  • search_info.search_results: the list of search result sources, each containing the source index index, title title, and link url.
  • usage.plugins.search.count: the number of searches, which should not be replaced by the number of sources.
  • usage.plugins.search.strategy: the search policy, whose value is agent.

For response event details, see response.done.

Conversation context management

Qwen-Audio supports managing conversation items in the conversation context via client events, which can be used to inject historical context, supplement text information, or clean up irrelevant conversation items.

  • Create a conversation item (conversation.item.create): insert a conversation item into the conversation context. The following three item.type values are supported:

    • message: a regular conversation message. You must specify role (system, user, assistant) and the content array; it is suitable for injecting historical conversations or system instructions.
    • function_call: a function call request. You must specify call_id, name, and arguments (a JSON string). It is usually generated by the server, and the client can also use it to supplement function call records in historical context.
    • function_call_output: the tool execution result. You must specify call_id and output (a JSON string). After receiving function_call, the client executes the tool and writes the execution result back with this type.

    The optional parameter previous_item_id specifies after which existing conversation item the new conversation item is inserted, enabling content insertion at any position in the conversation history. If this parameter is not passed, the new conversation item is appended to the end of the conversation by default.

    • Insert a user message at a specified position:
{
    "type": "conversation.item.create",
    "previous_item_id": "item_abc",
    "item": {
        "type": "message",
        "role": "user",
        "content": [
            { "type": "input_text", "text": "请帮我总结一下上次的对话" }
        ]
    }
}
  • Write back the Function Calling execution result:
{
    "type": "conversation.item.create",
    "item": {
        "type": "function_call_output",
        "call_id": "call_xxx",
        "output": "{\"temperature\":18,\"condition\":\"晴\"}"
    }
}

NoteIf the item.id specified by conversation.item.create already exists in the conversation, an error is returned.

  • Retrieve a conversation item (conversation.item.retrieve): retrieve a conversation item stored on the server. For audio-type content, only the transcribed text is returned, not the raw audio data.
{
    "type": "conversation.item.retrieve",
    "item_id": "item_xxx"
}
  • Delete a conversation item (conversation.item.delete): delete a specified item from the conversation context.
{
    "type": "conversation.item.delete",
    "item_id": "item_xxx"
}

Instant hotwords

Names, product names, or industry terms are easily recognized as homophones. After instant hotwords are configured, the model prioritizes recognizing these words when transcribing input audio. For example, the project name in the same audio clip was transcribed as "7yuan project" before hotwords were configured. After "Qiyuan" is set as a hotword, the transcription result is "Qiyuan project".

The Plus and Flash models of Qwen-Audio-Realtime 3.0 and 3.1 all support instant hotwords, applicable to WebSocket, WebRTC, and AOQ access in the Beijing and Singapore regions. Before sending audio, use the following session.update event to configure hotwords.

{
    "type": "session.update",
    "session": {
        "input_audio_transcription": {
            "corpus": {
                "vocabulary": {
                    "祺元": 50
                }
            }
        }
    }
}

Send audio only after session.updated is received. Get the final transcription from the transcript field of the conversation.item.input_audio_transcription.completed event. You can send session.update again during the session to pass in a complete new vocabulary. Setting vocabulary to {} clears the hotwords.

Ambient audio transcription

smart_turn / smart_turn_v2 modes only. When VAD detects voice activity but semantically determines it is not a valid turn (such as noise or meaningless content like "uh" or "ah"), the server does not trigger a conversation turn; instead, it passes the ASR recognition result to the client via the ambient_audio_transcription event. This transcription result is not written into the conversation context.

{
    "type": "conversation.item.ambient_audio_transcription.delta",
    "item_id": "item_xxx",
    "text": "嗯",
    "stash": ""
}

Similar to user speech transcription events, ambient audio transcription also includes the delta and completed stages. Developers can use this event to implement features such as ambient audio monitoring and conversation scene awareness.

Speaker enhancement

smart_turn / smart_turn_v2 modes only. Pass the URL of audio pre-recorded by the target user in session.update, and the model will precisely lock onto that speaker in duplex conversation, effectively ignoring other voices and background noise, enabling smooth duplex interaction in open scenarios.

Configuration: pass publicly accessible URLs of voiceprint audio in turn_detection.voiceprint_audio_urls of the first session.update.

{
    "type": "session.update",
    "session": {
        "turn_detection": {
            "type": "smart_turn_v2",
            "voiceprint_audio_urls": [
                "https://example.com/speaker.wav"
            ]
        }
    }
}

Parameter requirements:

  • A maximum of 5 URLs are supported, and the audio format must be 16kHz PCM or WAV.
  • This parameter takes effect only on the first session.update; subsequent inputs are ignored.

Registration events: after receiving the configuration, the server asynchronously performs voiceprint registration and notifies the result via the following events:

  • voiceprint_audio_list.in_progress: registration has started, pushed before session.updated is returned, carrying an item_id that identifies this task.
  • voiceprint_audio_list.completed: registration succeeded, with the item_id matching that of in_progress.
  • voiceprint_audio_list.failed: registration failed, with a reason field explaining the cause (for example, the audio URL is inaccessible). A registration failure does not block normal conversation.

Going live

Set up fault tolerance policies

  • Client reconnection: The client should implement an automatic reconnection mechanism to handle network jitter. We recommend setting a reconnection signal in the on_error callback and retrying with an exponential backoff policy (for example, wait 1s → 2s → 4s).
  • Error classification and handling: Client errors (invalid_request_error) do not interrupt the connection; you only need to log them or adjust parameters. Server errors (server_error) terminate the connection and require reconnection.
  • Barge-in handling: In server_vad / smart_turn / smart_turn_v2 modes, new user speech automatically interrupts the ongoing model response (response.done returns status=cancelled). The client should immediately stop playing buffered audio upon receiving input_audio_buffer.speech_started to avoid overlapping speech.

Connection lifecycle

A typical WebSocket session lifecycle is as follows:

  1. Establish connection: The client initiates a WebSocket connection, and the server returns the session.created event.
  2. Configure: The client sends session.update to set parameters such as the interaction mode, voice, and tools. This step must be completed before the first audio is sent.
  3. Interaction: The client continuously sends audio streams (input_audio_buffer.append), and the server performs inference triggered by VAD detection or manual triggers, returning speech and text in a streaming manner.
  4. Close: The client proactively closes the WebSocket connection. If the connection is idle for too long, the server may also disconnect it proactively.

NoteTo keep the transcription of the last turn, wait for the transcription completed or transcription failed event for the corresponding item_id before closing the connection. response.done only indicates that the model response has finished; the transcription result may be returned later.

Latency optimization

  • Audio chunk size: We recommend sending 100ms of audio data each time (16kHz × 16bit × mono = 3200 bytes per send), which ensures real-time performance while avoiding overly frequent network requests.
  • Streaming playback: Decode and play audio immediately after receiving response.audio.delta; do not wait for response.done to play the entire segment.
  • Clear the buffer immediately on barge-in: Upon receiving input_audio_buffer.speech_started, immediately clear the local playback buffer to prevent stale audio from continuing to play and causing perceived latency.

Supported models and regions

Singapore

When calling the following models, select an API Key in the Singapore region:

  • qwen-audio-3.1-realtime-plus
  • qwen-audio-3.1-realtime-flash
  • qwen-audio-3.0-realtime-plus
  • qwen-audio-3.0-realtime-flash

China (Beijing)

When calling the following models, select an API Key in the China (Beijing) region:

  • qwen-audio-3.1-realtime-plus
  • qwen-audio-3.1-realtime-flash
  • qwen-audio-3.0-realtime-plus
  • qwen-audio-3.0-realtime-flash

FAQ

What does RPM limit? Does it limit the total number of concurrently open connections?

RPM limits the number of WebSocket connection requests per minute. Multiple response turns within the same connection are not counted separately; reconnections count as new requests. Currently, there is no separate limit on the total number of concurrently open connections.

API Reference

For the procedures and examples of accessing the service via AOQ, see AOQ access. For protocol selection and reference entry points, see API Reference.