Qwen-Audio-3.1-Live

NEW
Copy success!
Add to Compare

Overview

Qwen-Audio-3.1-Live is a next-generation, real-time, full-duplex voice service for live interactions. It combines a foreground voice model with a configurable background reasoning model, bringing advanced reasoning to a natural, full-duplex conversational experience. The foreground model interprets user intent, responds naturally, and manages turn-taking, while the background model handles complex reasoning, task planning, and tool invocation. As tasks run in the background, the assistant can continue the conversation and smoothly incorporate progress updates and results—so it can listen, reason, speak, and act concurrently. The service supports two task collaboration modes: Client mode and Responses mode. In Client mode, the client application manages conversation context, invokes its own agents or business workflows, and returns their results to the foreground model. In Responses mode, the service invokes the background reasoning model based on the specified configuration, provides relevant conversation context, and integrates the results into the ongoing voice interaction. Both modes support function calling, allowing customers to connect business tools for knowledge retrieval, order processing, travel planning, and other use cases. With configurable models, prompts, and tools, Qwen-Audio-3.1-Live connects real-time voice conversations with complex task execution, extending voice assistants beyond conversation to task completion.

Input

TextAudio

Output

TextAudio

Features

Prefix Completion

Enable Partial Mode when calling the Qwen API to make the model continue strictly from your provided prefix text.View docs

Function Calling

Use function calling to connect large language models with external tools and systems.View docs

Cache

Context Cache stores shared prefixes for long-context requests to reduce repeated computation, improve latency, and lower cost.View docs

Structured Outputs

Structured Outputs help ensure the model returns a JSON string in the expected format.View docs

Batches

Asynchronously process requests in batches to reduce costs.View docs

Web Search

Enable web search so the model can answer with real-time retrieved data.View docs

Fine-tuning

Train models on sample data to better adapt them to specific tasks.View docs

Pricing

  • Audio Duration
    $0.00071Per second

Rate Limits & Context

  • Max Output
    64K
  • TPMTokens Per Minute
    100000
  • RPMRequests Per Minute
    60

API Reference

Call API
Copy success!
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
# Install: python -m pip install "websockets>=15"
# Prepare input: ffmpeg -i input.wav -ar 16000 -ac 1 -f s16le input.pcm
# Set DASHSCOPE_API_KEY and enter the WORKSPACE_ID for the same region.
# Save as live_quickstart.py. Specify cn-beijing or ap-southeast-1 when running it.
# Example: python live_quickstart.py input.pcm cn-beijing
# The audio reply is saved to reply.wav.

import base64
import json
import os
import sys
import time
import uuid
import wave
from pathlib import Path

from websockets.sync.client import connect

WORKSPACE_ID = "WorkspaceId"
SESSION_MODEL = "qwen-audio-4.0-realtime-preview"
REGIONS = ("cn-beijing", "ap-southeast-1")
REPLY_TIMEOUT_SECONDS = 12


def main():
    if len(sys.argv) != 3 or sys.argv[2] not in REGIONS:
        raise SystemExit("Usage: python live_quickstart.py input.pcm {cn-beijing|ap-southeast-1}")
    region = sys.argv[2]
    url = (
        f"wss://{WORKSPACE_ID}.{region}.maas.aliyuncs.com/api-ws/v1/realtime"
        "?model=qwen-audio-3.1-live"
    )
    audio = Path(sys.argv[1]).read_bytes()
    if not audio or len(audio) % 2:
        raise ValueError("Provide a non-empty 16-bit PCM file.")
    headers = {"Authorization": f"Bearer {os.environ['DASHSCOPE_API_KEY']}"}
    with connect(
        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 response received.")


main()