Qwen-Audio-Live

Updated at:

Start a full-duplex voice session and delegate tasks to an external agent or a backend model.

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.

Quickstart

For a live conversation using a microphone, run the WebRTC browser example.

Establish your first session

Send a short audio clip over WebSocket and save the reply as a WAV file. Set DASHSCOPE_API_KEY to an API key with access to the service. Record a short request, such as “Please count from one to three.”

Install the dependency and convert your 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

Qwen-Audio-Live supports only workspace-specific domains. Save the code as live_quickstart.py. This example uses the China (Beijing) region. Replace {WorkspaceId} in the URL with your workspace ID and use an API key from the same region. For the Singapore endpoint, see WebSocket access.

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/realtime?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")
            if not reply.getnframes():
                raise RuntimeError("No audio reply received")


main()
python live_quickstart.py input.pcm

The script prints the reply transcript and saves the reply as a 24 kHz, 16-bit, mono reply.wav file.

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.

    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.

For settings and event references, see Choose a transport.

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

When modalities includes both text and audio, the service returns both speech and subtitles.

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.

Session billing and usage

A single session has no time limit. Once the connection is established, each session is billed for at least 3 seconds. Sessions longer than 3 seconds are billed for their actual duration. The session duration includes time spent sending text messages, muted, or idle. If Model Studio calls a backend model, its token usage is billed separately. See billing.

After the session becomes active, session.usage.updated reports the cumulative billable duration every 5 seconds. Use the latest usage.seconds during the session and the value in session.closed after the session ends. See server events.

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 evaluating conditions or calling multiple tools in sequence. To reschedule a trip, for example, the backend checks the booking and the change rules, then looks up available departures. The frontend model presents 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?Model Studio starts the backend request from the session. Your application configures the backend model and its instructions.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.

For example, use Responses mode to calculate a total from a unit price and quantity. Use Client mode to look up stock in an internal system when your application needs to check store permissions and verify the result.

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

Save the original script from Quickstart as live_responses.py, starting from the original event loop. Set REPLY_TIMEOUT_SECONDS to 30 seconds to allow time for backend processing and speech playback. Before sending session.update, replace the delegation configuration in session and set the frontend instruction.

Model Studio passes the model, instructions, and tools settings in session.delegation.responses to the selected backend model.

session["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."
)
session["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."
        ),
    },
}

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.

In the audio reception loop, add these two branches immediately after session.output_transcript.delta. A nested response.completed marks the end of that backend generation. Continue handling frontend transcript and audio events to receive the spoken reply.

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 model finished generating", flush=True)
    elif backend_event["type"] == "response.failed":
        print("\nBackend generation failed", backend_event.get("response", {}).get("error"), flush=True)

Test delegation and playback

Record the phrase '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 preceding example as live_responses_text.py. Keep the Responses session configuration and remove the lines at the start of main() that read and validate the PCM file. After the code that waits for session.updated, replace the audio processing code starting at audio += with this snippet. Use the same indentation as send("session.update", session=session) and keep the final call to main().

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")

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

Connect your application in Client mode

Before you begin

Use the fixed result below to test task feedback and spoken playback. When connecting to a real inventory API, make sure your application can call it, map the product name to the ID the API expects, and include the product name in the result.

Configure the session

Save the original script from Quickstart as live_client.py to verify fixed-result return and announcement. Retain "type": "client" in delegation, and set REPLY_TIMEOUT_SECONDS to 30 seconds to allow time for task processing and announcement. Before sending session.update, add the following instruction to session.

session["instructions"] = "Delegate inventory checks to the application and speak the result when it arrives."
seen_delegation_events = set()

Receive the task and prepare context

When you receive session.delegation.created, save delegation_id. Deduplicate events by event_id and group updates for the same task by delegation_id. Read summary and context when present, and combine them with your application's business state to prepare the input for your API or agent. For an inventory check, your application can take the product name from the task and map it to the product ID for the current store.

If a detail is missing, such as the product to look up, ask the frontend model to clarify. Match a later session.delegation.created event by the same delegation_id and read any supplements before running the lookup.

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.

In the audio reception loop from Quickstart, add the following two branches immediately after the session.output_transcript.delta branch. They reuse the send function from the example.

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)

Test task delegation and spoken results

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

When requiring the frontend model to supply function parameters in a fixed structure, declare the function in session.tools. For example, after registering an inventory API, the frontend model can extract the product name from the user’s question and pass it as a function parameter to the application. Add the following fields to the session object within session.update, preserving all other session configurations.

{
  "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 populate item.call_id with the current invocation’s ID. Session-level task results are still returned via session.commentary.append according to delegation_id.

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.

For audio over AOQ, see AOQ access. For event fields and examples, see the API overview.