Skip to main content

Qwen-Audio-Live

Build voice assistants and customer service apps that can talk and use tools at the same time.

The old WebSocket path for Qwen-Audio-Live, /api-ws/v1/realtime, remains available but will no longer be maintained. If your application uses this path, switch to /api-ws/v1/live as soon as possible.
The Qwen-Audio-Live frontend model listens, asks questions, and responds in speech. When a request needs a business API or more reasoning, the frontend can delegate the task and keep talking with the user. During an order lookup, the frontend model can take an order number from the user and share progress or results in speech. In Client mode, your application handles the task and returns the result. In Responses mode, Model Studio calls the configured backend model and returns its result to the frontend.
The frontend model keeps talking during an order lookup. The app or the configured backend model handles the task and returns the result.
For session settings, audio, transcripts, and usage, see Manage sessions. To connect a backend model or your business system, see Task delegation and tools.

Quickstart

Establish your first session

This example sends a recorded audio clip to the model via WebSocket and saves the voice response to reply.wav.

Prepare the audio recording and credentials

  • Qwen-Audio-Live requires a workspace-specific domain. For this example, obtain a China (Beijing) workspace ID and an API key for that workspace. Keep the API key on your application server. For the Singapore endpoint, see WebSocket access.
  • Install Python and FFmpeg. Record the phrase 'Please count from one to three' and save it as input.wav.
Set the DASHSCOPE_API_KEY environment variable to your API key. Install the dependency and convert the recording to 16 kHz, 16-bit, mono PCM.
python -m pip install "websockets>=15"
ffmpeg -i input.wav -ar 16000 -ac 1 -f s16le input.pcm

Send the recording and receive the response

Save the following code as live_quickstart.py and enter your workspace ID in the connection URL. You can use the model values in the example.
import base64
import json
import os
import sys
import time
import uuid
import wave
from pathlib import Path

from websockets.sync.client import connect

WEBSOCKET_URL = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/live?model=qwen-audio-3.1-live"
SESSION_MODEL = "qwen-audio-4.0-realtime-preview"
REPLY_TIMEOUT_SECONDS = 12


def main():
    audio = Path(sys.argv[1]).read_bytes()
    if not audio or len(audio) % 2:
        raise ValueError("Provide a nonempty 16-bit PCM file")
    headers = {"Authorization": f"Bearer {os.environ['DASHSCOPE_API_KEY']}"}
    with connect(
        WEBSOCKET_URL,
        additional_headers=headers,
        close_timeout=2,
    ) as ws:
        def send(event_type, **payload):
            ws.send(json.dumps({
                "type": event_type,
                "event_id": uuid.uuid4().hex,
                **payload,
            }))

        session = {
            "model": SESSION_MODEL,
            "modalities": ["text", "audio"],
            "turn_detection": {"type": "duplex"},
            "delegation": {"type": "client"},
        }
        send("session.update", session=session)

        deadline = time.monotonic() + 20
        while True:
            event = json.loads(ws.recv(timeout=max(0, deadline - time.monotonic())))
            if event["type"] == "session.updated":
                break
            if event["type"] in ("error", "session.closed"):
                raise RuntimeError(event)

        audio += bytes(32000 * 3)
        with wave.open("reply.wav", "wb") as reply:
            reply.setparams((1, 2, 24000, 0, "NONE", "not compressed"))
            start = time.monotonic()
            offset = 0
            deadline = start + len(audio) / 32000 + REPLY_TIMEOUT_SECONDS
            while time.monotonic() < deadline:
                if offset < len(audio) and time.monotonic() >= start + offset / 32000:
                    frame = audio[offset:offset + 640]
                    send("session.input_audio.append",
                         audio=base64.b64encode(frame).decode("ascii"))
                    offset += len(frame)
                try:
                    event = json.loads(ws.recv(timeout=0.02 if offset < len(audio) else 0.25))
                except TimeoutError:
                    continue
                event_type = event["type"]
                if event_type == "session.output_audio.delta":
                    reply.writeframesraw(base64.b64decode(event["delta"]))
                elif event_type == "session.output_transcript.delta":
                    print(event["delta"], end="", flush=True)
                elif event_type == "session.closed":
                    break
                elif event_type == "error":
                    raise RuntimeError(event["error"])
            else:
                send("session.close")
                close_deadline = time.monotonic() + 2
                while time.monotonic() < close_deadline:
                    try:
                        event = json.loads(ws.recv(timeout=max(0, close_deadline - time.monotonic())))
                    except TimeoutError:
                        break
                    if event["type"] == "session.closed":
                        break
            if not reply.getnframes():
                raise RuntimeError("No audio reply received")


main()
Run the script with the recording you prepared earlier:
python live_quickstart.py input.pcm
Read the transcript in your terminal and open reply.wav to hear the model count. The file contains 24 kHz, 16-bit, mono audio. To change the model, voice, or audio transport, see Configure a session. If no response is received, first verify that the API Key, Workspace ID, and connection URL all belong to the same region. Audio transmission begins only after receiving session.updated. For troubleshooting audio, captions, and errors, see Troubleshoot integration issues.

Choose how to connect

Both setups start with a WebSocket connection. Choose a setup based on how you want to send and receive audio.
  • WebSocket only. One connection carries audio, transcripts, and task events. Use it to test with a recording or to stream audio from a server. You can connect with the C# SDK or the Ruby SDK.
    One WebSocket connection carries audio and events between the application and Model Studio.
  • WebSocket + WebRTC or AOQ. Keep the control WebSocket open to configure the session, set up the media connection, and send task requests. Once the media connection is ready, use it to send and receive audio. Receive server events over either connection.
    The control WebSocket is the primary connection. The WebRTC or AOQ media connection carries two-way audio and can receive server events.
    • WebRTC. Use media tracks to capture and play live audio in a browser or app. Exchange SDP over the control WebSocket.
    • AOQ. If your app uses the AOQ Client SDK, get temporary credentials over the control WebSocket, then use the SDK to connect to the Relay.
API Reference provides entry points for request and response events by operation. Model Details lists regions, rate limits, and pricing.

Write prompts

Write the frontend conversation prompt

Use session.instructions to define the frontend role, tone, when to ask for missing information, when to delegate, and how to present the result. If you omit session.instructions in the initial session configuration, the frontend model uses its built-in instructions. Providing session.instructions replaces them. Include all the conversation rules you need in your custom instructions. To make the customer service agent first give a brief answer and then ask whether the user needs further assistance, add the following field to the session object in session.update while retaining existing settings such as model and delegation.
{
  "instructions": "Act as a store support agent. Answer in one sentence, then ask if the user needs anything else."
}

Define task instructions

Define task steps, input checks, and result formats where the task runs. In Client mode, put those rules in your application or agent. In Responses mode, use session.delegation.responses.instructions. Model Studio supplies no built-in backend instructions.

Split the prompts for a calculation

In this Responses mode example, the frontend asks for missing inputs and the backend calculates the total.
  • Frontend prompt. Ask for the unit price or quantity if either is missing. When you have both, delegate the calculation to the backend model. Read the result aloud in one sentence.
  • Backend prompt. Calculate the total from the unit price and quantity. Return the amount and currency.
For the complete session configuration and validation steps, see the Responses mode example.

Manage sessions

After connecting, configure the session to choose the frontend model, voice, audio transport, and task delegation mode.

Configure a session

SettingWhat to configure
Frontend modelIn the connection URL, model=qwen-audio-3.1-live selects the service. In the session, session.model selects the model that speaks with the user. The quickstart uses qwen-audio-4.0-realtime-preview and sets session.turn_detection.type to duplex for full-duplex conversation. The model can keep listening while it speaks.
Conversation instructions and voiceSet instructions and voice. See Write prompts and Set the voice.
Output typesWhen modalities includes both text and audio, the service returns both speech and subtitles.
Audio transportOmit session.transport to send and receive audio over the control WebSocket. To use WebRTC or AOQ, configure session.transport and follow the connection instructions to establish a media connection.
Task delegation modeSet session.delegation. See Task delegation and tools.
For all configuration fields, see session.update. After sending session.update, check session.updated for the effective configuration. With WebSocket only, you can send audio as soon as you receive this event. With WebRTC or AOQ, also wait for the media connection to become ready.

Set the voice

Set the voice ID in the session object in session.update and keep your other session settings.
{
  "voice": "qingyou"
}
In the example, qingyou corresponds to 'Qing You', and the default value is yunshu ('Yun Shu'). The full list is available in Client Events.

Send and receive speech and subtitles

The method of sending and receiving audio depends on the protocol selected during connection establishment.
  • WebRTC sends and receives audio via media tracks. Browsers deliver remote audio tracks to the player.
  • AOQ sends and receives audio via the SDK. Uplink audio must be sent through AOQ. After setting session.transport.aoq.ws_audio to true, the WebSocket control channel also receives a copy of downlink audio. See AOQ access for details.
  • WebSocket transmits audio via JSON events. Both input and output use mono PCM, but with different sampling rates.
The audio events in the table apply to WebSocket-only sessions. With any audio transport, you can use the transcript events to display both sides of the conversation.
DataEventProcessing method
Microphone audio or recordingSend session.input_audio.appendSplit the 16 kHz, 16-bit, mono PCM audio into frames and Base64-encode each frame. The quickstart uses 20 ms frames.
Model audio responseReceive session.output_audio.deltaDecode the delta in the event and play the 24 kHz, 16-bit, mono PCM audio in arrival order.
TranscriptsReceive session.input_transcript.delta and session.output_transcript.deltaThe first event carries the user’s speech transcript. The second carries the model’s response transcript.
If a user speaks while the model is talking, both transcripts can update at once. Append each transcript to its own message bubble. Use the player’s actual playback state for the speaking indicator. Once the WebRTC or AOQ media connection is ready, you can receive transcripts over the control WebSocket or the media connection. If your app listens on both, deduplicate events by event_id before appending text. If the UI has a microphone switch, send session.input_audio.mute or session.input_audio.unmute when the user toggles it. Update the switch after the service confirms the change. The session stays connected while muted.

Send text messages

In addition to voice, users can supplement information with text during a call—for example, typing a product name to look up. The application sends this text as a user message to the model via session.item.create.
{
  "type": "session.item.create",
  "event_id": "evt_user_message",
  "item": {
    "role": "user",
    "type": "message",
    "content": [
      {"type": "input_text", "text": "Check whether black folding umbrellas are in stock."}
    ]
  }
}

End a session and view usage

When the user hangs up or selects End, send session.close and stop capturing microphone audio. After you receive session.closed, close the connection and release resources. Once the session is active, the service reports usage.seconds in session.usage.updated every 5 seconds. This value is the cumulative billable session duration in seconds. Use the latest value during the call and the value in session.closed for final usage. A session has no maximum duration. Qwen-Audio-Live charges for session time in seconds, with a 3-second minimum once the connection is established. Sessions longer than 3 seconds are billed for their actual duration. Text messages, silence, and idle time all count toward the session duration. When Model Studio calls a backend model, its actual token usage is billed separately. See Model pricing.

Troubleshooting integration issues

SymptomTroubleshooting method
No response after uploading audioFirst confirm receipt of session.updated. For pure WebSocket integration, verify that the upstream audio is mono PCM at 16 kHz and 16 bits. For WebRTC or AOQ integrations, ensure the media connection is ready and audio is being sent over it.
Subtitles received but no audio response heardFor pure WebSocket integration, verify receipt of session.output_audio.delta and playback at 24 kHz. For WebRTC or AOQ integrations, verify the player is receiving downstream audio on the selected channel.
Words or whole sentences appear twice in the transcriptWith WebRTC or AOQ, the same transcript event can arrive over both the control WebSocket and the media connection. Update the transcript from one connection, or deduplicate events by event_id across both connections before appending text.
Task processed but no voice announcement heardVerify whether the application receives and plays the frontend model’s voice. In Client mode, confirm the returned delegation_id matches the task.
Receive error or session.closedUpon receiving error, refer to the Error Events for request diagnostics. After session closure, reestablish the connection and reconfigure the session to continue the conversation.

Task delegation and tools

The examples in this section use the WebSocket-only connection from Quickstart. With WebRTC or AOQ, use the control WebSocket to configure the session and send task requests. Send and receive audio over the media connection.

Choose where to configure tools

When a user makes a request during a conversation, the frontend model can call a function directly or delegate the task to the backend. Choose where to configure each tool based on the steps involved and how quickly the user needs a response.
  • Frontend tools suit straightforward actions that need a quick response. For example, when a user says “Play music,” the frontend model calls a function registered in session.tools, and your application plays the music.
  • Backend tools suit tasks that require checking conditions or calling several tools in sequence. For example, if the backend model has the tools to look up a booking, change rules, and departures, it can use them to find eligible departures. The frontend model reads the options to the user.

Choose a task delegation mode

Choose Responses mode if you want Model Studio to call a backend model and pass its result to the frontend model. Choose Client mode if you already have a business API, workflow, or agent, or if your application needs to verify the result before deciding what the user hears. Set session.delegation.type in session.update. Set it to responses for Responses mode or client for Client mode.
DecisionResponses modeClient mode
Who handles the task?Model Studio calls the configured backend Responses model.Your application calls a business API, workflow, agent, or model.
Who prepares the input?Your application configures the backend model and its instructions in advance. When the frontend delegates a task, Model Studio prepares the input from the current conversation and sends the request.Your application combines the task summary and context from the delegation event with its business data.
Who decides what to return?Model Studio passes the backend result to the frontend model.Your application can validate, combine, or filter the result before returning the information to speak.
Consider the same request to find eligible departures. Choose Responses mode when you want Model Studio to call a backend model that can use its configured tools for the lookup. Choose Client mode when an existing booking workflow runs the lookup and your application needs to verify the departures before the frontend presents them. Both modes can configure frontend functions. A frontend function uses call_id to match a call to its result. Client delegation uses delegation_id to match a task to its updates. Before connecting a business system, check your application's API permissions, required inputs, and response format.

Call a backend model in Responses mode

Before you begin

Choose a backend Responses model your workspace can call. This example uses qwen4-max to calculate a total, which the frontend model reads aloud.

Configure the session

Set session.delegation.type to responses and select the backend model in session.delegation.responses.model. You can also set backend task instructions in instructions and configure tools in tools within the same object. For example, to calculate a total, the frontend prompt can say, “If the unit price or quantity is missing, ask the user for it. Once you have both, delegate the calculation to the backend.” The backend prompt can say, “Calculate the total from the unit price and quantity. Return the amount and currency.”

Receive backend events

When automatic delegation starts, the service sends session.delegation.created. During backend generation, it forwards backend events in response.event. Use the outer delegation_id, when present, to match events to a task, and use event.type to distinguish backend events. A nested response.completed means the backend has finished generating. The frontend model delivers the spoken reply. The script displays its transcript and saves the audio to reply.wav.

Test delegation and playback

Save the following complete example as live_responses.py and enter your workspace ID in the connection URL. The script allows 30 seconds for backend processing and speech output.
import base64
import json
import os
import sys
import time
import uuid
import wave
from pathlib import Path

from websockets.sync.client import connect

WEBSOCKET_URL = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/live?model=qwen-audio-3.1-live"
SESSION_MODEL = "qwen-audio-4.0-realtime-preview"
REPLY_TIMEOUT_SECONDS = 30


def main():
    audio = Path(sys.argv[1]).read_bytes()
    if not audio or len(audio) % 2:
        raise ValueError("Provide a nonempty 16-bit PCM file")
    headers = {"Authorization": f"Bearer {os.environ['DASHSCOPE_API_KEY']}"}
    with connect(
        WEBSOCKET_URL,
        additional_headers=headers,
        close_timeout=2,
    ) as ws:
        def send(event_type, **payload):
            ws.send(json.dumps({
                "type": event_type,
                "event_id": uuid.uuid4().hex,
                **payload,
            }))

        session = {
            "model": SESSION_MODEL,
            "modalities": ["text", "audio"],
            "turn_detection": {"type": "duplex"},
            "instructions": (
                "Act as a voice support agent. "
                "When calculating a total, ask for the unit price or quantity if it is missing. "
                "When you have all the inputs, delegate the calculation to the backend model. "
                "Read the result aloud in one sentence."
            ),
            "delegation": {
                "type": "responses",
                "responses": {
                    "model": "qwen4-max",
                    "instructions": (
                        "Calculate the total from the unit price and quantity. Return the amount and currency. "
                        "If a required input is missing, identify it."
                    ),
                },
            },
        }
        send("session.update", session=session)

        deadline = time.monotonic() + 20
        while True:
            event = json.loads(ws.recv(timeout=max(0, deadline - time.monotonic())))
            if event["type"] == "session.updated":
                break
            if event["type"] in ("error", "session.closed"):
                raise RuntimeError(event)

        audio += bytes(32000 * 3)
        with wave.open("reply.wav", "wb") as reply:
            reply.setparams((1, 2, 24000, 0, "NONE", "not compressed"))
            start = time.monotonic()
            offset = 0
            deadline = start + len(audio) / 32000 + REPLY_TIMEOUT_SECONDS
            while time.monotonic() < deadline:
                if offset < len(audio) and time.monotonic() >= start + offset / 32000:
                    frame = audio[offset:offset + 640]
                    send("session.input_audio.append",
                         audio=base64.b64encode(frame).decode("ascii"))
                    offset += len(frame)
                try:
                    event = json.loads(ws.recv(timeout=0.02 if offset < len(audio) else 0.25))
                except TimeoutError:
                    continue
                event_type = event["type"]
                if event_type == "session.output_audio.delta":
                    reply.writeframesraw(base64.b64decode(event["delta"]))
                elif event_type == "session.output_transcript.delta":
                    print(event["delta"], end="", flush=True)
                elif event_type == "session.delegation.created":
                    print(f"\nTask delegated: {event['delegation_id']}", flush=True)
                elif event_type == "response.event":
                    backend_event = event["event"]
                    if backend_event["type"] == "response.completed":
                        print("\nBackend generation completed", flush=True)
                    elif backend_event["type"] == "response.failed":
                        print("\nBackend generation failed:", backend_event.get("response", {}).get("error"), flush=True)
                elif event_type == "session.closed":
                    break
                elif event_type == "error":
                    raise RuntimeError(event["error"])
            else:
                send("session.close")
                close_deadline = time.monotonic() + 2
                while time.monotonic() < close_deadline:
                    try:
                        event = json.loads(ws.recv(timeout=max(0, close_deadline - time.monotonic())))
                    except TimeoutError:
                        break
                    if event["type"] == "session.closed":
                        break
            if not reply.getnframes():
                raise RuntimeError("No audio response received")


main()
Record “Each item costs 327 yuan. How much for thirteen items?” and save it as responses.wav. Convert the recording and run the script.
ffmpeg -i responses.wav -ar 16000 -ac 1 -f s16le responses.pcm
python live_responses.py responses.pcm
Confirm that the terminal logs both task dispatch and backend generation completion, then open reply.wav to verify that the model announces the total amount of 4,251 yuan. Backend generation completion is marked by response.completed in response.event. Playback progress is tracked by the player. Record a second request that gives only the unit price, such as “Each item costs 327 yuan. What is the total?” Convert it and run the script again. Check the transcript or the new reply.wav to see whether the model asks for the quantity.

Configure and monitor backend tools

Declare tools for the backend model in session.delegation.responses.tools. See the Responses API for the tool definition format. For automatic delegation, the service runs supported backend tools and handles their results. Your application can monitor tool execution through response.event. When the nested event is response.output_item.done and event.item.type is function_call, read the function name (name), arguments (arguments), and call ID (call_id) from event.item. If your application needs to run and verify a business operation, use Client mode to receive the task, or declare a frontend function to receive structured arguments.

Start backend generation from your application

If your application already has the input, send response.item.create to provide text and then send response.create to start a separate backend task. Read its output from response.event. Save the following complete example as live_responses_text.py and enter your workspace ID in the connection URL. The script sends text and prints the backend model’s result in your terminal.
import json
import os
import time
import uuid

from websockets.sync.client import connect

WEBSOCKET_URL = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/live?model=qwen-audio-3.1-live"
SESSION_MODEL = "qwen-audio-4.0-realtime-preview"
REPLY_TIMEOUT_SECONDS = 30


def main():
    headers = {"Authorization": f"Bearer {os.environ['DASHSCOPE_API_KEY']}"}
    with connect(
        WEBSOCKET_URL,
        additional_headers=headers,
        close_timeout=2,
    ) as ws:
        def send(event_type, **payload):
            ws.send(json.dumps({
                "type": event_type,
                "event_id": uuid.uuid4().hex,
                **payload,
            }))

        session = {
            "model": SESSION_MODEL,
            "modalities": ["text", "audio"],
            "turn_detection": {"type": "duplex"},
            "instructions": (
                "Act as a voice support agent. "
                "When calculating a total, ask for the unit price or quantity if it is missing. "
                "When you have all the inputs, delegate the calculation to the backend model. "
                "Read the result aloud in one sentence."
            ),
            "delegation": {
                "type": "responses",
                "responses": {
                    "model": "qwen4-max",
                    "instructions": (
                        "Calculate the total from the unit price and quantity. Return the amount and currency. "
                        "If a required input is missing, identify it."
                    ),
                },
            },
        }
        send("session.update", session=session)

        deadline = time.monotonic() + 20
        while True:
            event = json.loads(ws.recv(timeout=max(0, deadline - time.monotonic())))
            if event["type"] == "session.updated":
                break
            if event["type"] in ("error", "session.closed"):
                raise RuntimeError(event)

        send("response.item.create", item={
            "type": "message",
            "role": "user",
            "content": [{"type": "input_text", "text": "Calculate the total for 13 items at 327 yuan each."}],
        })
        send("response.create")

        deadline = time.monotonic() + REPLY_TIMEOUT_SECONDS
        while True:
            event = json.loads(ws.recv(timeout=max(0, deadline - time.monotonic())))
            if event["type"] in ("error", "session.closed"):
                raise RuntimeError(event)
            if event["type"] != "response.event":
                continue

            backend_event = event["event"]
            kind = backend_event["type"]
            if kind == "response.output_text.delta":
                print(backend_event["delta"], end="", flush=True)
            elif kind == "response.completed":
                print()
                break
            elif kind == "response.failed":
                raise RuntimeError(backend_event)

        send("session.close")


main()
Run python live_responses_text.py. The terminal prints the amount returned by the backend model.

Connect your application in Client mode

In Client mode, the frontend model delegates tasks to your application. The application performs the business operation and returns the result for the frontend model to share with the user.

Before you begin

  • Run the example. Follow the quickstart to prepare your workspace ID, API key, and runtime. Record a spoken inventory request. When the application receives the task, it returns the preset answer “Seven black folding umbrellas are in stock” for the frontend to read aloud. You can run this example without an inventory API.
  • Connect your own business system. Check that your application can call the API, knows its required inputs, and can identify the data to share with the user. For example, if an inventory API takes a product ID, the application looks up the ID from the name the user provided, queries the stock, and returns both the name and the quantity available.

Configure the session

Set session.delegation.type to client. In the frontend prompt, specify which tasks to delegate and how to respond when results arrive. The inventory example uses “Delegate inventory checks to the application and speak the result when it arrives.”

Receive the task and prepare context

When you receive session.delegation.created, deduplicate by event_id and save the delegation_id to track updates for the same task. Read the task information from summary and context, if present, and combine it with your application’s business data. For example, your application can use the product name and the current store to find the product ID for an inventory lookup. If required information is missing, have the frontend model ask the user for it. For example, if the user asks about stock without naming a product, ask which product they mean. Match subsequent session.delegation.created events to the task by delegation_id. Read any additional details from supplements when present, and run the lookup once you have the required inputs.

Send progress, clarification requests, and results

Include the current task's delegation_id and choose the event for the content you want to send.
What to sendEventExample content
Progress to share without speaking itsession.thinking.appendChecking stock at the selected store.
A detail to ask the user forsession.instruction.appendAsk the user which product to look up.
A result for the frontend model to speaksession.commentary.appendSeven black folding umbrellas are in stock.
Run slow business calls in a background task so the main loop can continue handling audio and events. Verify the result and return the facts the frontend model needs to speak.

Test task delegation and spoken results

Save the following complete example as live_client.py and enter your workspace ID in the connection URL.
import base64
import json
import os
import sys
import time
import uuid
import wave
from pathlib import Path

from websockets.sync.client import connect

WEBSOCKET_URL = "wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/live?model=qwen-audio-3.1-live"
SESSION_MODEL = "qwen-audio-4.0-realtime-preview"
REPLY_TIMEOUT_SECONDS = 30


def main():
    audio = Path(sys.argv[1]).read_bytes()
    if not audio or len(audio) % 2:
        raise ValueError("Provide a nonempty 16-bit PCM file")
    headers = {"Authorization": f"Bearer {os.environ['DASHSCOPE_API_KEY']}"}
    with connect(
        WEBSOCKET_URL,
        additional_headers=headers,
        close_timeout=2,
    ) as ws:
        def send(event_type, **payload):
            ws.send(json.dumps({
                "type": event_type,
                "event_id": uuid.uuid4().hex,
                **payload,
            }))

        session = {
            "model": SESSION_MODEL,
            "modalities": ["text", "audio"],
            "turn_detection": {"type": "duplex"},
            "delegation": {"type": "client"},
            "instructions": "Delegate inventory checks to the application and speak the result when it arrives.",
        }
        seen_delegation_events = set()
        send("session.update", session=session)

        deadline = time.monotonic() + 20
        while True:
            event = json.loads(ws.recv(timeout=max(0, deadline - time.monotonic())))
            if event["type"] == "session.updated":
                break
            if event["type"] in ("error", "session.closed"):
                raise RuntimeError(event)

        audio += bytes(32000 * 3)
        with wave.open("reply.wav", "wb") as reply:
            reply.setparams((1, 2, 24000, 0, "NONE", "not compressed"))
            start = time.monotonic()
            offset = 0
            deadline = start + len(audio) / 32000 + REPLY_TIMEOUT_SECONDS
            while time.monotonic() < deadline:
                if offset < len(audio) and time.monotonic() >= start + offset / 32000:
                    frame = audio[offset:offset + 640]
                    send("session.input_audio.append",
                         audio=base64.b64encode(frame).decode("ascii"))
                    offset += len(frame)
                try:
                    event = json.loads(ws.recv(timeout=0.02 if offset < len(audio) else 0.25))
                except TimeoutError:
                    continue
                event_type = event["type"]
                if event_type == "session.output_audio.delta":
                    reply.writeframesraw(base64.b64decode(event["delta"]))
                elif event_type == "session.output_transcript.delta":
                    print(event["delta"], end="", flush=True)
                elif event_type == "session.delegation.created":
                    if event["event_id"] in seen_delegation_events:
                        continue
                    seen_delegation_events.add(event["event_id"])
                    task_id = event["delegation_id"]
                    print(f"\nTask received: {task_id}", flush=True)
                    send("session.commentary.append",
                         delegation_id=task_id,
                         content="Seven black folding umbrellas are in stock.")
                elif event_type == "session.commentary.appended":
                    print("\nThe service accepted the task result", flush=True)
                elif event_type == "session.closed":
                    break
                elif event_type == "error":
                    raise RuntimeError(event["error"])
            else:
                send("session.close")
                close_deadline = time.monotonic() + 2
                while time.monotonic() < close_deadline:
                    try:
                        event = json.loads(ws.recv(timeout=max(0, close_deadline - time.monotonic())))
                    except TimeoutError:
                        break
                    if event["type"] == "session.closed":
                        break
            if not reply.getnframes():
                raise RuntimeError("No audio response received")


main()
Record “Please check whether black folding umbrellas are in stock” and save it as client.wav. Convert the recording and run the script.
ffmpeg -i client.wav -ar 16000 -ac 1 -f s16le client.pcm
python live_client.py client.pcm
Confirm that the terminal logs show task dispatch and result acknowledgment, then open reply.wav to verify the speech includes the returned inventory result. When integrating with a real inventory API, replace the fixed result with the API’s actual response.

Configure and handle the frontend function

The previous example delegates the entire inventory lookup to the application, which prepares the query. If you already have a function that looks up stock by product name, the frontend model can call it directly. Declare the function and its parameters in session.tools so the frontend model can extract the name from the conversation and pass it to your application. Frontend functions work in both Client and Responses modes. Add the following fields to the session object in session.update and retain your other session settings.
{
  "tools": [
    {
      "type": "function",
      "name": "lookup_stock",
      "description": "Look up the quantity in stock for a product",
      "parameters": {
        "type": "object",
        "properties": {
          "item": {"type": "string", "description": "Product name"}
        },
        "required": ["item"]
      }
    }
  ]
}
  1. Upon receiving session.event, read the invocation entry in event.item where type equals function_call.
  2. Locate the function per name, parse arguments from its JSON string into parameters, validate them, then execute. Each call_id executes only once.
  3. Send session.item.create to return the result. Set item.type to function_call_output and set item.call_id to the call_id from the function call.
{
  "type": "session.item.create",
  "event_id": "evt_function_result",
  "item": {
    "type": "function_call_output",
    "call_id": "call_stock",
    "output": "{\"stock\":7}"
  }
}
In Client mode, the frontend model continues accepting user speech and replying while waiting for function results. The application may keep sending/receiving audio and handling events. When querying web pages or other real-time information, register a search service—or have the application invoke it directly under Client mode.

Migrate from Qwen-Audio-Realtime

If your application already uses Qwen-Audio-Realtime, retain your existing business interfaces and tool implementations. First validate audio send/receive functionality with Quickstart for Qwen-Audio-Live, then migrate event handling and task logic.
Migration ItemsHandling Method in Qwen-Audio-Live
WebSocket ConnectionUse Qwen-Audio-Live request URL and configure the frontend model and task processing mode in session.update.
WebSocket AudioSwitch upstream to session.input_audio.append and downstream to reading session.output_audio.delta. When using duplex conversation as shown on this page, continuously send audio—no need to retain the manual-mode input_audio_buffer.commit and response.create. See Audio and Subtitle Transmission for format and sampling rate details.
WebRTC SignalingPreviously, SDP was exchanged over HTTP. When integrating with Live, send the Offer via the control WebSocket and read the Answer from session.transport.sdp in session.updated. See WebRTC access.
Frontend FunctionsRead function invocations from session.event. After execution, return results via session.item.create following call_id. The legacy flow used response.create to resume frontend replies. Live’s response.create explicitly initiates backend tasks.
Time-Consuming Business TasksChoose Client or Responses per Task Delegation and Tools. Validate task results and speech playback using a voice request requiring tool invocation.