All Products
Search
Document Center

Alibaba Cloud Model Studio:Qwen-Audio-ASR / Fun-ASR Python SDK

Last Updated:Nov 20, 2026

Prerequisites

API endpoint — Qwen-Audio-ASR-Streaming / Fun-ASR-Realtime

Realtime recognition in the SDK uses the WebSocket interface, and the endpoint is automatically determined by the Client's workspace and region (including the WorkspaceId). To switch to another region, set the region to the corresponding region when constructing the Client.

Singapore

wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference

When making calls, replace {WorkspaceId} with your actual Workspace ID.

China (Beijing)

wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference

When making calls, replace {WorkspaceId} with your actual Workspace ID.

ImportantAlibaba Cloud Model Studio has launched workspace-specific domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:

  • China (Beijing) region: migrate from dashscope.aliyuncs.com to {WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore region: migrate from dashscope-intl.aliyuncs.com to {WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

API endpoint — Qwen-Audio-ASR-Message

Realtime recognition in the SDK uses the WebSocket interface, and the endpoint is automatically determined by the Client's workspace and region (including the WorkspaceId). To switch to another region, set the region to the corresponding region when constructing the Client.

Singapore

wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/inference

When making calls, replace {WorkspaceId} with your actual Workspace ID.

China (Beijing)

wss://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api-ws/v1/inference

When making calls, replace {WorkspaceId} with your actual Workspace ID.

ImportantAlibaba Cloud Model Studio has launched workspace-specific domains for the China (Beijing) and Singapore regions, which deliver superior performance and higher stability for inference requests. We recommend migrating to the new domains:

  • China (Beijing) region: migrate from dashscope.aliyuncs.com to {WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapore region: migrate from dashscope-intl.aliyuncs.com to {WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

QuickStart

The following call examples are shared. Replace the model ID in the examples according to the table below.

ModelModel ID in the examples
Qwen-Audio-ASR-Streamingqwen-audio-3.1-asr-flash-streaming
The microphone example uses qwen-audio-3.0-asr-flash-streaming.
Qwen-Audio-ASR-Messageqwen-audio-3.1-asr-flash-message
Only a sample rate of 16000 Hz is supported.
Fun-ASR-Realtimefun-asr-realtime

The core resource (client.audio.asr) provides interfaces such as non-streaming calls and bidirectional streaming calls. Choose the appropriate calling method based on your actual needs:

  • Non-streaming call (recognize_file): performs recognition on local files; the SDK automatically sends the audio in chunks and drives the task to completion. Suitable for processing recorded audio.
  • Bidirectional streaming call (recognize session): performs recognition directly on audio streams and outputs results in real time. The audio stream can come from an external device (such as a microphone) or be read from a local file. Suitable for scenarios that require immediate feedback.

Non-streaming call

Submit a single realtime speech transcription task and obtain the transcription result synchronously in a blocking manner by passing in a local file.

Call the recognize_file method of the core resource (client.audio.asr) to bind request parameters and pass in a local file path, and iterate server-side events to obtain recognition results.

import os
import dashscope

# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
    api_key=os.environ.get('DASHSCOPE_API_KEY'),
    # The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

# Recognize a local audio file: recognize_file automatically sends the audio in chunks and drives the task to completion
for event in client.audio.asr.recognize_file(
        '{YOUR_AUDIO_FILE}',
        model='qwen-audio-3.1-asr-flash-streaming',
        format='wav',
        sample_rate=16000):
    payload = event.get('payload') or {}
    sentence = (payload.get('output') or {}).get('sentence') or {}
    if sentence.get('text') and not sentence.get('heartbeat'):
        print('识别结果:', sentence['text'])

Bidirectional streaming call

Submit a single realtime speech transcription task, with realtime recognition results streamed out by iterating events.

  1. Start streaming speech recognition

    Call the recognize method of the core resource (client.audio.asr) to create a recognition session and bind request parameters, then enter the with context (which automatically calls the start method to establish the connection and send the task) to start streaming speech recognition.

  2. Streaming

    Call the session's send_audio_frame method in a loop to send the binary audio stream read from a local file or a device (such as a microphone) to the server in segments. Sending and receiving must proceed concurrently: the receiving thread iterates server-side events through the session's events() method and returns recognition results to the client in real time.

    We recommend that the audio sent each time be about 100 milliseconds in duration, with the data size kept between 1 KB and 16 KB.

  3. Finish processing

    Call the session's stop method to end the speech recognition.

    This method only notifies the server that the input has ended; the receiving thread must continue consuming events() until the task-finished event to obtain the final recognition results and statistics. Errors at the ws layer are raised as DashScopeError exceptions, which you can catch with try/except where you send or receive.

import os
import signal  # for keyboard events handling (press "Ctrl+C" to terminate recording)
import sys

import dashscope
import pyaudio
from concurrent.futures import ThreadPoolExecutor

mic = None
stream = None

# Set recording parameters
sample_rate = 16000  # 麦克风与请求使用相同的采样率。Qwen-Audio-ASR-Message 仅支持 16000 Hz。
channels = 1  # mono channel
dtype = 'int16'  # data type
format_pcm = 'pcm'  # the format of the audio data
block_size = 3200  # number of frames per buffer

# Real-time speech recognition event receiver
def receive_events(rec):
    for event in rec.events():
        payload = event.get('payload') or {}
        sentence = (payload.get('output') or {}).get('sentence') or {}
        if sentence.get('text') and not sentence.get('heartbeat'):
            print('Recognition text: ', sentence['text'])
            if sentence.get('sentence_end'):
                print(
                    'Recognition sentence end, request_id:%s, usage:%s'
                    % (rec.request_id, rec.usage))

def signal_handler(sig, frame):
    print('Ctrl+C pressed, stop recognition ...')
    # Stop recognition
    recognition.stop()
    print('Recognition stopped.')
    print(
        '[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
        .format(
            recognition.request_id,
            recognition.first_package_delay,
            recognition.last_package_delay,
        ))
    # Forcefully exit the program
    sys.exit(0)

# main function
if __name__ == '__main__':
    # The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
    client = dashscope.Client(
        api_key=os.environ.get('DASHSCOPE_API_KEY'),
        # The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
        workspace="{WorkspaceId}",
        region="ap-southeast-1",
    )

    # Call recognition service, you can customize the recognition parameters, like model, format,
    # sample_rate
    with client.audio.asr.recognize(
            model='qwen-audio-3.0-asr-flash-streaming',
            format=format_pcm,
            # 'pcm'、'wav'、'opus'、'speex'、'aac'、'amr', you can check the supported formats in the document
            sample_rate=sample_rate,
    ) as recognition:
        # Open the microphone
        mic = pyaudio.PyAudio()
        stream = mic.open(format=pyaudio.paInt16,
                          channels=1,
                          rate=sample_rate,
                          input=True)
        with ThreadPoolExecutor(max_workers=1) as pool:
            receiver = pool.submit(receive_events, recognition)
            try:
                # Send audio from the microphone until "Ctrl+C" is pressed
                while stream:
                    data = stream.read(3200, exception_on_overflow=False)
                    recognition.send_audio_frame(data)
                recognition.stop()
                receiver.result()
            finally:
                # close must run inside the pool context to unblock the receiver
                recognition.close()
        stream.stop_stream()
        stream.close()
        mic.terminate()
        stream = None
        mic = None
import os
import time
import dashscope
from concurrent.futures import ThreadPoolExecutor

# The API Key differs between the Singapore and Beijing regions. Get an API Key: https://www.alibabacloud.com/help/model-studio/get-api-key
# If you have not configured the environment variable, replace the following line with your Model Studio API Key: api_key="sk-xxx"
client = dashscope.Client(
    api_key=os.environ.get('DASHSCOPE_API_KEY'),
    # The following is the configuration for the Singapore (ap-southeast-1) region. When calling, replace "{WorkspaceId}" with your actual workspace ID. The configuration differs by region.
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

from datetime import datetime

def get_timestamp():
    now = datetime.now()
    formatted_timestamp = now.strftime("[%Y-%m-%d %H:%M:%S.%f]")
    return formatted_timestamp

# Real-time speech recognition event receiver
def receive_events(rec):
    for event in rec.events():
        payload = event.get('payload') or {}
        sentence = (payload.get('output') or {}).get('sentence') or {}
        if sentence.get('text') and not sentence.get('heartbeat'):
            print(get_timestamp() + ' Recognition text: ', sentence['text'])
        if sentence.get('sentence_end'):
            print(get_timestamp() +
                  'Recognition sentence end, request_id:%s, usage:%s'
                  % (rec.request_id, rec.usage))

with client.audio.asr.recognize(
        model='qwen-audio-3.1-asr-flash-streaming',
        format='wav',
        sample_rate=16000,
) as recognition:
    with ThreadPoolExecutor(max_workers=1) as pool:
        receiver = pool.submit(receive_events, recognition)
        try:
            audio_data: bytes = None
            f = open("{YOUR_AUDIO_FILE}", 'rb')
            if os.path.getsize("{YOUR_AUDIO_FILE}"):
                # Read all the file data into the buffer at once
                file_buffer = f.read()
                f.close()
                print("Start Recognition")

                # Send 3200 bytes from the buffer at a time
                buffer_size = len(file_buffer)
                offset = 0
                chunk_size = 3200

                while offset < buffer_size:
                    # Calculate the size of the data chunk to send this time
                    remaining_bytes = buffer_size - offset
                    current_chunk_size = min(chunk_size, remaining_bytes)

                    # Extract the current data chunk from the buffer
                    audio_data = file_buffer[offset:offset + current_chunk_size]

                    # Send the audio data frame
                    recognition.send_audio_frame(audio_data)
                    # Update the offset
                    offset += current_chunk_size

                    # Add a delay to simulate real-time transmission
                    time.sleep(0.1)

                recognition.stop()
                receiver.result()
            else:
                raise Exception(
                    'The supplied file was empty (zero bytes long)')
        finally:
            # close must run inside the pool context to unblock the receiver
            recognition.close()

print(
    '[Metric] requestId: {}, first package delay ms: {}, last package delay ms: {}'
    .format(
        recognition.request_id,
        recognition.first_package_delay,
        recognition.last_package_delay,
    ))

Request parameters

Qwen-Audio-ASR-Streaming

Shared notes

For details, see the new Qwen-Audio-ASR-Streaming Python SDK.

Request parameters are set through the recognize/recognize_file methods of the core resource (client.audio.asr): model, format, sample_rate, and vocabulary_id can be passed in directly. Pass language_hints in through the parameters dictionary.

ParameterTypeRequiredDescription
modelstrYesModel name.
sample_rateintYes

Sampling rate (Hz). Any sampling rate is supported.

formatstrYesAudio format.

Valid values:

  • pcm
  • wav
  • mp3
  • opus
  • speex
  • aac
  • amr

Importantopus/speex: must use Ogg encapsulation;

wav: must use PCM encoding;

amr: only the AMR-NB type is supported.

keep_dialectboolNoOnly supported by qwen-audio-3.1-asr-flash-streaming. Defaults to false, which transcribes dialects into Standard Mandarin; when set to true, dialect expressions are retained. Pass it in through the parameters dictionary. For the complete parameter description, seeclient events。
vad_modelstrNoOnly supported by qwen-audio-3.1-asr-flash-streaming. You can select near_meeting_16k (near-field) or far_field_meeting_16k (far-field, default). Pass it in through the parameters dictionary. For the complete parameter description, seeclient events。
vocabulary_idstrNoThe ID of a precompiled hotword list.

You must call the hotword list creation API in advance to generate it; pass this ID during recognition to use the hotwords in the list.

This is suitable for scenarios where the vocabulary is known and relatively stable and the same vocabulary needs to be reused across requests.

For usage instructions, see precompiled hotwords.

vocabularydictNoInstant hotwords.

Passed in as key-value pairs, where the key is the hotword text (string) and the value is the hotword weight (integer); no hotword list needs to be created in advance. The weight range is [1, 5] or 50: within [1, 5], the larger the value, the more likely the model is to output the word; 50 indicates a super hotword, which greatly improves recall, but the number of super hotwords cannot exceed 50.

This is suitable for temporary, session-level hotword optimization.

When configured together with precompiled hotwords, the system merges the two types of hotwords; if the merged total exceeds 2,000, 2,000 are randomly selected for use. For usage instructions, see instant hotwords.

Example:

import os
import dashscope

client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))

# Instant hot words are passed in through parameters
vocab = {"张三": 5, "李四": 5}
recognition = client.audio.asr.recognize(
    model='qwen-audio-3.1-asr-flash-streaming',
    format='wav',
    sample_rate=16000,
    parameters={"vocabulary": vocab},
)
max_sentence_silenceintNoVAD silence threshold for sentence segmentation (ms). When the silence after a segment of speech exceeds this threshold, the system determines that the sentence has ended.

Default value: 800.

Value range: [200, 6000].

multi_threshold_mode_enabledboolNo

Whether to enable multi-threshold mode. When enabled, it prevents VAD sentence segmentation from cutting overly long segments.

Default value: False.

punctuation_prediction_enabledboolNoSet whether to automatically add punctuation to recognition results:
  • True (default): Yes, and it cannot be modified.
heartbeatboolNoWhether to enable heartbeat packets.

Default value: False.

  • True: The connection to the server remains uninterrupted when silent audio is continuously sent.
  • False (default): Even if silent audio is continuously sent, the connection will still be closed due to timeout after a certain period.

Silent audio refers to content with no sound signal in an audio file or data stream. Silent audio can be generated in multiple ways, for example using audio editing software such as Audacity or Adobe Audition, or command-line tools such as FFmpeg.

When using this field, the SDK version must be 2.0.1 or later.

language_hintslist[str]NoThe language of the audio to be recognized. There is no default value; the model automatically recognizes the language when it is not set.

You can set up to 4 values; when more are set, only the first 4 take effect.

Click to view supported language codes

  • zh: Chinese
  • en: English
  • ja: Japanese
  • ko: Korean
  • vi: Vietnamese
  • th: Thai
  • id: Indonesian
  • ms: Malay
  • tl: Filipino
  • hi: Hindi
  • ar: Arabic
  • fr: French
  • de: German
  • es: Spanish
  • pt: Portuguese
  • ru: Russian
  • it: Italian
  • nl: Dutch
  • sv: Swedish
  • da: Danish
  • fi: Finnish
  • no: Norwegian
  • el: Greek
  • pl: Polish
  • cs: Czech
  • hu: Hungarian
  • ro: Romanian
  • bg: Bulgarian
  • hr: Croatian
  • sk: Slovak
speech_noise_thresholdfloatNoThe threshold for distinguishing speech from noise, used to adjust the sensitivity of Voice Activity Detection (VAD).

Value range: [-1.0, 1.0].

Value description:

  • The closer the value is to -1: the noise determination threshold is lowered, increasing the probability that noise is recognized as speech, which may cause more noise to be transcribed
  • The closer the value is to +1: the noise determination threshold is raised, increasing the probability that speech is misjudged as noise, which may cause some speech to be filtered out

This is an advanced configuration parameter; adjusting it may significantly affect recognition performance. Recommendations:

  • Fully test and verify the effect before adjusting
  • Make small adjustments based on your actual audio environment (a step of 0.1 is recommended)
special_word_filterstrNoSpecifies the sensitive words to be handled during speech recognition, and supports setting different handling methods for different sensitive words. For details, seeSensitive word filtering。

When creating a recognition session with recognize, pass in the context via input.

ParameterTypeRequiredDescription
inputdictNoThe input object, used to pass in the conversation context. The context assists recognition and improves recognition accuracy for proper nouns. For usage details, seeQuickStart。

The dict must contain a context key whose value is a list of messages (list[dict]). Each message contains the following fields:

  • role (str, required): The message role. user indicates the recognition results of the user's speech in previous turns or a domain-specific vocabulary; assistant indicates the LLM's replies in previous turns.
  • content (list[dict], required): The list of message contents. Each element contains type (str, set to input_text when role is user, and text when role is assistant) and text (str, the text content).

ImportantContext messages (input_text and text types) are limited to 5 each; when exceeded, only the most recent 5 are kept. The total length of the context text per turn must not exceed 400 characters; the excess is truncated from the end.

ImportantWhen carrying context, the message order in context is subject to requirements: context messages must be arranged by conversation turn, and within each turn, user (input_text type) must precede the corresponding assistant (text type).

NoteWhen using this field, the SDK version must be 2.0.1 or later.

# Build the input to pass in
input_context = {
    "context": [
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "你好啊"
                }
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "你好啊,我是通义千问,有什么可以帮助你的?"
                }
            ]
        }
    ]
}

# Pass it in through the input parameter when creating the recognition session
recognition = client.audio.asr.recognize(
    model='qwen-audio-3.1-asr-flash-streaming',
    format='wav',
    sample_rate=16000,
    input=input_context,
)

Qwen-Audio-ASR-Message

Shared notes

See the new version of the Qwen-Audio-ASR-Message Python SDK.

Request parameters are set via the core resource (client.audio.asr) recognize/recognize_file methods: model, format, sample_rate, vocabulary_id can be passed in directly. Pass language_hints via the parameters dictionary.

ParameterTypeRequiredDescription
modelstrYesThe model name, set to qwen-audio-3.1-asr-flash-message.
sample_rateintYes

Sampling rate (Hz).

Only 16000 Hz is supported.

formatstrYes

Audio format.

Valid values:

  • pcm
  • wav
  • mp3
  • opus
  • speex
  • aac
  • amr

Importantopus/speex: must use Ogg encapsulation;

wav: must use PCM encoding;

amr: only the AMR-NB type is supported.

disfluency_removal_enabledboolNoWhether to filter filler words and polish the output results, with a default value of false. Enabled when set to true. Passed in as a keyword argument of the same name.
intermediate_result_enabledboolNoWhether to return streaming intermediate results, with a default value of false. When set to true, streaming intermediate results are returned. Passed in via the parameters dictionary.
keep_dialectboolNoDefaults to false, transcribing dialects into Mandarin; when set to true, dialect expressions are preserved. Passed in via the parameters dictionary. For complete parameter descriptions, seeclient events。

Only effective for the final result (sentence_end=true); not supported for intermediate results (sentence_end=false).

vad_modelstrNoOptional: near_meeting_16k (near-field) or far_field_meeting_16k (far-field, default value). Passed in via the parameters dictionary. For complete parameter descriptions, seeclient events。
vocabulary_idstrNo

Precompiled hotword list ID.

You must call the hotword list creation API in advance to generate it; pass this ID during recognition to use the hotwords in the list.

This is suitable for scenarios where the vocabulary is known and relatively stable and the same vocabulary needs to be reused across requests.

For usage instructions, see precompiled hotwords.

vocabularydictNo

Instant hotwords.

Passed in as key-value pairs, where the key is the hotword text (string) and the value is the hotword weight (integer); no hotword list needs to be created in advance. The weight range is [1, 5] or 50: within [1, 5], the larger the value, the more likely the model is to output the word; 50 indicates a super hotword, which greatly improves recall, but the number of super hotwords cannot exceed 50.

This is suitable for temporary, session-level hotword optimization.

When configured together with precompiled hotwords, the system merges the two types of hotwords; if the merged total exceeds 2,000, 2,000 are randomly selected for use. For usage instructions, see instant hotwords.

Example:

import os
import dashscope

client = dashscope.Client(api_key=os.getenv("DASHSCOPE_API_KEY"))

# Instant vocabulary is passed in through parameters
vocab = {"张三": 5, "李四": 5}
recognition = client.audio.asr.recognize(
    model='qwen-audio-3.1-asr-flash-message',
    format='wav',
    sample_rate=16000,
    parameters={"vocabulary": vocab},
)
language_hintslist[str]NoThe language of the audio to be recognized. There is no default value; the model automatically recognizes the language when it is not set.

You can set up to 4 values; when more are set, only the first 4 take effect.

Click to view supported language codes

  • zh: Chinese
  • en: English
  • ja: Japanese
  • ko: Korean
  • vi: Vietnamese
  • th: Thai
  • id: Indonesian
  • ms: Malay
  • tl: Filipino
  • hi: Hindi
  • ar: Arabic
  • fr: French
  • de: German
  • es: Spanish
  • pt: Portuguese
  • ru: Russian
  • it: Italian
  • nl: Dutch
  • sv: Swedish
  • da: Danish
  • fi: Finnish
  • no: Norwegian
  • el: Greek
  • pl: Polish
  • cs: Czech
  • hu: Hungarian
  • ro: Romanian
  • bg: Bulgarian
  • hr: Croatian
  • sk: Slovak

Passed in via the parameters dictionary, for example parameters={"language_hints": ["zh"]}.

Only effective for the final result (sentence_end=true); not supported for intermediate results (sentence_end=false).

max_sentence_silenceintNo

VAD sentence-break silence threshold (ms). When the silence after a speech segment exceeds this threshold, the system determines that the sentence has ended.

Default value: 800.

Value range: [200, 6000].

heartbeatboolNo

Whether to enable heartbeat packets.

Default value: False.

  • True: The connection to the server remains uninterrupted when silent audio is continuously sent.
  • False (default): Even if silent audio is continuously sent, the connection will still be closed due to timeout after a certain period.

Silent audio refers to content with no sound signal in an audio file or data stream. Silent audio can be generated in multiple ways, for example using audio editing software such as Audacity or Adobe Audition, or command-line tools such as FFmpeg.

This field was introduced in SDK 1.23.1 and is already included in version 2.0.1 and later.

speech_noise_thresholdfloatNo

The threshold for distinguishing speech from noise, used to adjust the sensitivity of voice activity detection (VAD).

Value range: [-1.0, 1.0].

Value description:

  • The closer the value is to -1: the noise determination threshold is lowered, increasing the probability that noise is recognized as speech, which may cause more noise to be transcribed
  • The closer the value is to +1: the noise determination threshold is raised, increasing the probability that speech is misjudged as noise, which may cause some speech to be filtered out

This is an advanced configuration parameter; adjusting it may significantly affect recognition performance. Recommendations:

  • Fully test and verify the effect before adjusting
  • Make small adjustments based on your actual audio environment (a step of 0.1 is recommended)

When creating a recognition session with recognize, pass in the context via input.

ParameterTypeRequiredDescription
inputdictNo

The input object, used to pass in the conversation context. The context assists recognition and improves recognition accuracy for proper nouns. For usage details, seeQuickStart。

The dict must contain a context key whose value is a list of messages (list[dict]). Each message contains the following fields:

  • role (str, required): The message role. user indicates the recognition results of the user's speech in previous turns or a domain-specific vocabulary; assistant indicates the LLM's replies in previous turns.
  • content (list[dict], required): The list of message contents. Each element contains type (str, set to input_text when role is user, and text when role is assistant) and text (str, the text content).

ImportantContext messages (input_text and text types) are limited to 5 each; when exceeded, only the most recent 5 are kept. The total length of the context text per turn must not exceed 400 characters; the excess is truncated from the end.

ImportantWhen carrying context, the message order in context is subject to requirements: context messages must be arranged by conversation turn, and within each turn, user (input_text type) must precede the corresponding assistant (text type).

NoteThis field was introduced in SDK 1.25.23 and is already included in version 2.0.1 and later.

# Build the input data
input_context = {
    "context": [
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "你好啊"
                }
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "你好啊,我是通义千问,有什么可以帮助你的?"
                }
            ]
        }
    ]
}

# 通过 input 参数传入
recognition = client.audio.asr.recognize(
    model='qwen-audio-3.1-asr-flash-message',
    format='wav',
    sample_rate=16000,
    input=input_context,
)

Fun-ASR-Realtime

Shared notes

See the new Fun-ASR-Realtime Python SDK.

Request parameters are set via the core resource (client.audio.asr) recognize/recognize_file methods: model, format, sample_rate, vocabulary_id can be passed in directly. Pass max_sentence_silence and language_hints via the parameters dictionary.

ParameterTypeRequiredDescription
modelstrYesModel name.
sample_rateintYesSampling rate (Hz).

Value range: 8k models support only 8000 Hz; other models support any sampling rate.

formatstrYesAudio format.

Valid values:

  • pcm
  • wav
  • mp3
  • opus
  • speex
  • aac
  • amr

Importantopus/speex: must use Ogg encapsulation;

wav: must use PCM encoding;

amr: only the AMR-NB type is supported.

vocabulary_idstrNoThe ID of a precompiled hotword list.

You must call the hotword list creation API in advance to generate it; pass this ID during recognition to use the hotwords in the list.

This is suitable for scenarios where the vocabulary is known and relatively stable and the same vocabulary needs to be reused across requests.

For usage instructions, see precompiled hotwords.

max_sentence_silenceintNoVAD silence threshold for sentence segmentation (ms). When the silence after a segment of speech exceeds this threshold, the system determines that the sentence has ended.

Default value: 1300.

Value range: [200, 6000].

multi_threshold_mode_enabledboolNo

Whether to enable multi-threshold mode. When enabled, it prevents VAD sentence segmentation from cutting overly long segments.

Default value: False.

punctuation_prediction_enabledboolNoSet whether to automatically add punctuation to recognition results:
  • True (default): Yes, and it cannot be modified.
heartbeatboolNoWhether to enable heartbeat packets.

Default value: False.

  • True: The connection to the server remains uninterrupted when silent audio is continuously sent.
  • False (default): Even if silent audio is continuously sent, the connection will still be closed due to timeout after a certain period.

Silent audio refers to content with no sound signal in an audio file or data stream. Silent audio can be generated in multiple ways, for example using audio editing software such as Audacity or Adobe Audition, or command-line tools such as FFmpeg.

When using this field, the SDK version must be 2.0.1 or later.

language_hintslist[str]NoThe language of the audio to be recognized. There is no default value; the model automatically recognizes the language when it is not set.

Only one value can be set; when multiple values are set, only the first one takes effect.

Click to view supported language codes

  • fun-asr-realtime:

    • zh: Chinese
    • en: English
    • ja: Japanese
    • ko: Korean
    • vi: Vietnamese
    • th: Thai
    • id: Indonesian
    • ms: Malay
    • tl: Filipino
    • hi: Hindi
    • ar: Arabic
    • fr: French
    • de: German
    • es: Spanish
    • pt: Portuguese
    • ru: Russian
    • it: Italian
    • nl: Dutch
    • sv: Swedish
    • da: Danish
    • fi: Finnish
    • no: Norwegian
    • el: Greek
    • pl: Polish
    • cs: Czech
    • hu: Hungarian
    • ro: Romanian
    • bg: Bulgarian
    • hr: Croatian
    • sk: Slovak
  • fun-asr-realtime-2026-02-28:

    • zh: Chinese
    • en: English
    • ja: Japanese
  • fun-asr-flash-8k-realtime、fun-asr-flash-8k-realtime-2026-01-28:

    • zh: Chinese
speech_noise_thresholdfloatNoThe threshold for distinguishing speech from noise, used to adjust the sensitivity of Voice Activity Detection (VAD).

Value range: [-1.0, 1.0].

Value description:

  • The closer the value is to -1: the noise determination threshold is lowered, increasing the probability that noise is recognized as speech, which may cause more noise to be transcribed
  • The closer the value is to +1: the noise determination threshold is raised, increasing the probability that speech is misjudged as noise, which may cause some speech to be filtered out

This is an advanced configuration parameter; adjusting it may significantly affect recognition performance. Recommendations:

  • Fully test and verify the effect before adjusting
  • Make small adjustments based on your actual audio environment (a step of 0.1 is recommended)
special_word_filterstrNoSpecifies the sensitive words to be handled during speech recognition, and supports setting different handling methods for different sensitive words. For details, seeSensitive word filtering。

When creating a recognition session with recognize, pass in the context via input.

ParameterTypeRequiredDescription
inputdictNoThe input object, used to pass in the conversation context. The context assists recognition and improves recognition accuracy for proper nouns. For usage details, seeImproves recognition accuracy。

ImportantOnly the fun-asr-realtime model supports the context parameter.

The dict must contain a context key whose value is a list of messages (list[dict]). Each message contains the following fields:

  • role (str, required): The message role. user indicates the recognition results of the user's speech in previous turns or a domain-specific vocabulary; assistant indicates the LLM's replies in previous turns.
  • content (list[dict], required): The list of message contents. Each element contains type (str, set to input_text when role is user, and text when role is assistant) and text (str, the text content).

ImportantContext messages (input_text and text types) are limited to 5 each; when exceeded, only the most recent 5 are kept. The total length of the context text per turn must not exceed 400 characters; the excess is truncated from the end.

ImportantWhen carrying context, the message order in context is subject to requirements: context messages must be arranged by conversation turn, and within each turn, user (input_text type) must precede the corresponding assistant (text type).

NoteWhen using this field, the SDK version must be 2.0.1 or later.

# 构建 input 传入数据
input_context = {
    "context": [
        {
            "role": "user",
            "content": [
                {
                    "type": "input_text",
                    "text": "你好啊"
                }
            ]
        },
        {
            "role": "assistant",
            "content": [
                {
                    "type": "text",
                    "text": "你好啊,我是通义千问,有什么可以帮助你的?"
                }
            ]
        }
    ]
}

# 创建识别会话时通过 input 参数传入
recognition = client.audio.asr.recognize(
    model='fun-asr-realtime',
    format='wav',
    sample_rate=16000,
    input=input_context,
)

API reference

Qwen-Audio-ASR-Streaming / Fun-ASR-Realtime

Recognition result (RecognitionResult)

RecognitionResult represents a single recognition result frame iterated from the session's results() output (usable in both bidirectional streaming calls and non-streaming calls; events() yields raw event dicts—use results() instead if you need this typed view).

Member methodsMethod signatureDescription
get_sentence
def get_sentence(self) -> Union[Dict[str, Any], List[Any]]
Obtains the currently recognized sentence and its timestamp information. This method returns a Dict[str, Any] (single sentence information).

For details, see Single sentence information (Sentence).

request_id
result.request_id
The request_id of the request corresponding to the current event.
is_sentence_end
def is_sentence_end(self) -> bool
Determines whether the current sentence has ended. This method checks whether the end_time field in the single sentence information returned by get_sentence() is None—when end_time is not None, the sentence has ended.

Single sentence information (Sentence)

The Sentence class members are as follows:

ParameterTypeDescription
begin_timeintSentence start time, in ms.
end_timeintSentence end time, in ms.
textstrRecognized text.
wordsWord timestamp information (Word)list collectionWord timestamp information.

Word timestamp information (Word)

The Word class members are as follows:

ParameterTypeDescription
begin_timeintWord start time, in ms.
end_timeintWord end time, in ms.
textstrWord.
punctuationstrPunctuation.

Qwen-Audio-ASR-Streaming

Key interfaces

Core resources (client.audio.asr)

Real-time speech recognition capabilities are mounted on the client.audio.asr resource: recognize creates a bidirectional streaming recognition session (Recognition), and recognize_file performs one-shot recognition on local files.

Member methodsMethod signatureDescription

recognize

def recognize(self,
              *,
              model: str,
              format: str = "pcm",
              sample_rate: int = 16000,
              vocabulary_id: str = None,
              disfluency_removal_enabled: bool = None,
              diarization_enabled: bool = None,
              parameters: Dict = None,
              input: Dict = None,
              phrase_id: str = None,
              ...) -> Recognition

Creates a bidirectional streaming recognition session; when entering the with context, it automatically calls start to establish the connection and send the task.

Sending audio and consuming events must proceed concurrently (use together with send_audio_frame, events()/results(), and stop).

recognize_file

def recognize_file(self,
                   path: str,
                   *,
                   model: str,
                   format: str = "pcm",
                   sample_rate: int = 16000,
                   ...) -> Iterator[Dict]

Non-streaming call based on a local file: automatically sends audio in chunks and drives the task to completion, yielding server-side events one by one. This method requires the file to be recognized to have readable permission.

start
def start(self)
Starts speech recognition: establishes the connection, sends the task, and waits for task-started. Automatically called when entering the with context; audio can only be sent after a successful start.
send_audio_frame
def send_audio_frame(self, buffer: bytes)
Pushes audio. Each pushed audio stream should not be too large or too small; it is recommended that each audio packet be around 100ms in duration and between 1KB and 16KB in size.

Recognition results are obtained via event iteration (events()/results()).

stop
def stop(self)
Stops speech recognition: only notifies the server that input has ended; the receiving thread must continue consuming events() until the task-finished event.

events / results

def events(self) -> Iterator[Dict]
def results(self) -> Iterator[RecognitionResult]

Iterates server-side events: events() yields raw event dicts (recognition text is located in payload.output.sentence); results() only yields recognition result frames, returning typed Recognition Result (RecognitionResult) objects (heartbeat frames already filtered).

close

def close(self)

Closes the recognition session. Automatically called when exiting the with context.

request_id / first_package_delay / last_package_delay / last_response

rec.request_id
rec.first_package_delay
rec.last_package_delay
rec.last_response

Obtains the request_id, first-packet latency (the delay from sending the first audio packet to receiving the first recognition result), and last-packet latency (the time from sending the stop command to the delivery of the last recognition result); use after the task completes. last_response is the most recently successfully read raw message and can be used to obtain task-failed errors. It can still be read after the session is closed.

Event iteration (events()/results())

In bidirectional streaming calls, the server returns key process information and data to the client as events. You need to iterate the session's events() (raw event dicts) or results() (typed recognition result frames) in a receiving thread to process the information or data returned by the server.

# Iterate raw events: recognition text is in payload.output.sentence
def receive_events(rec):
    for event in rec.events():
        payload = event.get('payload') or {}
        sentence = (payload.get('output') or {}).get('sentence') or {}
        if sentence.get('text') and not sentence.get('heartbeat'):
            print('识别文本:', sentence['text'])


# Or iterate recognition result frames only (returns RecognitionResult, heartbeat frames filtered out)
def receive_results(rec):
    for result in rec.results():
        sentence = result.get_sentence()
        if sentence and 'text' in sentence:
            print('识别文本:', sentence['text'])
Event/iteration methodOutputReturn valueDescription
event["header"]["event"] == "task-started"

task-started event

None

Read internally by start() and saved in last_response when the start returns; it will not be yielded again by events().

def events(self) -> Iterator[Dict]

event: server-side event dict

Iterator

Yields events when the server has a response. Recognition results are located in payload.output.sentence and may be heartbeat or empty-text events, which applications can ignore as needed. Consume continuously from a single receiving thread; do not create multiple concurrent readers.

def results(self) -> Iterator[RecognitionResult]

result: recognition result (RecognitionResult)

Iterator

Only yields recognition result frames (heartbeat frames already filtered); the iteration ends after all recognition results have been returned.

try:
    ...
except DashScopeError as e:
    print(e.code, e.message, e.request_id)

DashScopeError exception

None

Raised in the sending/receiving thread when an exception occurs; can be caught with try/except.

event["header"]["event"] == "task-finished"

task-finished event

None

Yielded by events() after the server has completed all recognition, after which the iteration ends; this event must still be read after stop() is sent.

Response results

Qwen-Audio-ASR-Message

Key interfaces

Core resources (client.audio.asr)

Real-time speech recognition capabilities are mounted on the client.audio.asr resource: recognize creates a bidirectional streaming recognition session (Recognition), and recognize_file performs one-shot recognition on local files.

Member methodsMethod signatureDescription
recognize
def recognize(self,
              *,
              model: str,
              format: str = "pcm",
              sample_rate: int = 16000,
              vocabulary_id: str = None,
              disfluency_removal_enabled: bool = None,
              diarization_enabled: bool = None,
              parameters: Dict = None,
              input: Dict = None,
              phrase_id: str = None,
              ...) -> Recognition

Creates a bidirectional streaming recognition session; when entering the with context, it automatically calls start to establish the connection and send the task.

Sending audio and consuming events must proceed concurrently (use together with send_audio_frame, events()/results(), and stop).

recognize_file
def recognize_file(self,
                   path: str,
                   *,
                   model: str,
                   format: str = "pcm",
                   sample_rate: int = 16000,
                   ...) -> Iterator[Dict]

Non-streaming call based on a local file: automatically sends audio in chunks and drives the task to completion, yielding server-side events one by one. This method requires the file to be recognized to have readable permission.

start
def start(self)

Start speech recognition: establishes the connection, sends the task, and waits for task-started. It is called automatically when entering the with context; audio can only be sent after a successful start.

send_audio_frame
def send_audio_frame(self, buffer: bytes)

Push audio. Each pushed audio chunk should not be too large or too small; an audio duration of about 100ms per chunk is recommended, with a size between 1KB and 16KB.

Recognition results are obtained through event iteration (events()/results()).

stop
def stop(self)
Stops speech recognition: only notifies the server that input has ended; the receiving thread must continue consuming events() until the task-finished event.
events / results
def events(self) -> Iterator[Dict]
def results(self) -> Iterator[RecognitionResult]

Iterates over server-side events: events() yields raw event dicts (recognition text is located in payload.output.sentence); results() yields only recognition result frames, returning typed Recognition result (RecognitionResult) objects (heartbeat frames are filtered out).

close
def close(self)

Closes the recognition session. Automatically called when exiting the with context.

request_id / first_package_delay / last_package_delay / last_response
rec.request_id
rec.first_package_delay
rec.last_package_delay
rec.last_response

Obtains the request_id, first-packet latency (the delay from sending the first audio packet to receiving the first recognition result), and last-packet latency (the time from sending the stop command to the delivery of the last recognition result); use after the task completes. last_response is the most recently successfully read raw message and can be used to obtain task-failed errors. It can still be read after the session is closed.

Update conversation context

Call update_context to update the conversation context while a recognition task is running, to assist in recognizing subsequent audio. This method requires DashScope Python SDK 2.0.1 or later.

def update_context(self, context: dict)
  • When to call:after entering the with context (which automatically calls start) to start streaming recognition and before calling stop.
  • Parameters:context is a dictionary; pass in the payload.input object of the continue-task event, which contains the context field. Do not wrap it with additional payload or input layers.
  • Scope and parameter constraints:see continue-task.

The following example reuses an already started recognition instance.

payload_input = {
    "context": [
        {
            "role": "user",
            "content": [{"type": "input_text", "text": "你好啊"}]
        },
        {
            "role": "assistant",
            "content": [{"type": "text", "text": "你好啊,我是通义千问,有什么可以帮助你的?"}]
        }
    ]
}
recognition.update_context(context=payload_input)
Event iteration (events()/results())

During bidirectional streaming calls, the server returns key process information and data to the client as events. You need to iterate the session's events() (raw event dicts) or results() (typed recognition result frames) in the receiving thread to process the information or data returned by the server.

# 迭代原始事件:识别文本位于 payload.output.sentence
def receive_events(rec):
    for event in rec.events():
        payload = event.get('payload') or {}
        sentence = (payload.get('output') or {}).get('sentence') or {}
        if sentence.get('text') and not sentence.get('heartbeat'):
            print('识别文本:', sentence['text'])


# 或只迭代识别结果帧(返回 RecognitionResult,心跳帧已过滤)
def receive_results(rec):
    for result in rec.results():
        sentence = result.get_sentence()
        if sentence and 'text' in sentence:
            print('识别文本:', sentence['text'])
Event/iteration methodOutputReturn valueDescription
event["header"]["event"] == "task-started"

task-started event

None

Read internally by start() and saved in last_response when the start returns; it will not be yielded again by events().

def events(self) -> Iterator[Dict]

event: server-side event dict

Iterator

Yields events when the server has a response. Recognition results are located in payload.output.sentence and may be heartbeat or empty-text events, which applications can ignore as needed. Consume continuously from a single receiving thread; do not create multiple concurrent readers.

def results(self) -> Iterator[RecognitionResult]

result: recognition result (RecognitionResult)

Iterator

Only yields recognition result frames (heartbeat frames already filtered); the iteration ends after all recognition results have been returned.

try:
    ...
except DashScopeError as e:
    print(e.code, e.message, e.request_id)

DashScopeError exception

None

Raised in the sending/receiving thread when an exception occurs; can be caught with try/except.

event["header"]["event"] == "task-finished"

task-finished event

None

Yielded by events() after the server has completed all recognition, after which the iteration ends; this event must still be read after stop() is sent.

Response results

Recognition result (RecognitionResult)

RecognitionResult represents a recognition result frame yielded by iterating the session's results() (usable in both bidirectional streaming calls and non-streaming calls; events() yields raw event dicts, so use results() instead if you need this typed view).

Member methodsMethod signatureDescription
get_sentence
def get_sentence(self) -> Union[Dict[str, Any], List[Any]]

Obtains the currently recognized sentence and its timestamp information. This method returns a Dict[str, Any] (sentence information).

For details, see Sentence information (Sentence).

request_id
result.request_id
The request_id of the request corresponding to the current event.
is_sentence_end
def is_sentence_end(self) -> bool
Determines whether the current sentence has ended. This method checks whether the end_time field in the single sentence information returned by get_sentence() is None—when end_time is not None, the sentence has ended.
Sentence information (Sentence)

The Sentence class members are as follows:

ParameterTypeDescription
begin_timeintSentence start time, in ms.
end_timeintSentence end time, in ms.
textstrRecognized text.
wordsWord timestamp information (Word)list collectionWord timestamp information.
Word timestamp information (Word)

The Word class members are as follows:

ParameterTypeDescription
begin_timeintWord start time, in ms.
end_timeintWord end time, in ms.
textstrWord.
punctuationstrPunctuation.

Fun-ASR-Realtime

Key interfaces

Core resources (client.audio.asr)

Real-time speech recognition capabilities are mounted on the client.audio.asr resource: recognize creates a bidirectional streaming recognition session (Recognition), and recognize_file performs one-shot recognition on local files.

Member methodsMethod signatureDescription

recognize

def recognize(self,
              *,
              model: str,
              format: str = "pcm",
              sample_rate: int = 16000,
              vocabulary_id: str = None,
              disfluency_removal_enabled: bool = None,
              diarization_enabled: bool = None,
              parameters: Dict = None,
              input: Dict = None,
              phrase_id: str = None,
              ...) -> Recognition
Creates a bidirectional streaming recognition session. When entering the with context, start is automatically called to establish the connection and send the task.

Sending audio and consuming events must proceed concurrently (use together with send_audio_frame, events()/results(), and stop).

recognize_file

def recognize_file(self,
                   path: str,
                   *,
                   model: str,
                   format: str = "pcm",
                   sample_rate: int = 16000,
                   ...) -> Iterator[Dict]
Non-streaming call based on a local file: automatically sends the audio in chunks and drives the task to completion, yielding server-side events one by one. This method requires read permission on the file to be recognized.

start

def start(self)
Starts speech recognition: establishes the connection, sends the task, and waits for task-started. Automatically called when entering the with context; audio can only be sent after a successful start.

send_audio_frame

def send_audio_frame(self, buffer: bytes)
Pushes audio. Each pushed audio stream should not be too large or too small; it is recommended that each audio packet be around 100ms in duration and between 1KB and 16KB in size.

Recognition results are obtained by iterating events()/results().

stop

def stop(self)
Stops speech recognition: only notifies the server that input has ended; the receiving thread must continue consuming events() until the task-finished event.

events / results

def events(self) -> Iterator[Dict]
def results(self) -> Iterator[RecognitionResult]
Iterates over server-side events: events() yields raw event dicts (recognition text is located in payload.output.sentence); results() yields only recognition result frames, returning typed Recognition result (RecognitionResult) objects (heartbeat frames are filtered out).

close

def close(self)
Closes the recognition session. Called automatically when exiting the with context.

request_id / first_package_delay / last_package_delay / last_response

rec.request_id
rec.first_package_delay
rec.last_package_delay
rec.last_response
Obtains request_id, first-packet latency (the delay from sending the first audio chunk to receiving the first recognition result), and last-packet latency (the time from sending the stop command to the delivery of the last recognition result); use these after the task completes. last_response is the most recently successfully read raw message and can be used to retrieve task-failed errors. It remains readable after the session is closed.
Event iteration (events()/results())

During bidirectional streaming calls, the server returns key process information and data to the client as events. You need to iterate the session's events() (raw event dicts) or results() (typed recognition result frames) in the receiving thread to process the information or data returned by the server.

# 迭代原始事件:识别文本位于 payload.output.sentence
def receive_events(rec):
    for event in rec.events():
        payload = event.get('payload') or {}
        sentence = (payload.get('output') or {}).get('sentence') or {}
        if sentence.get('text') and not sentence.get('heartbeat'):
            print('识别文本:', sentence['text'])


# 或只迭代识别结果帧(返回 RecognitionResult,心跳帧已过滤)
def receive_results(rec):
    for result in rec.results():
        sentence = result.get_sentence()
        if sentence and 'text' in sentence:
            print('识别文本:', sentence['text'])
Event/iteration methodOutputReturn valueDescription
event["header"]["event"] == "task-started"

task-started event

None

Read internally by start() and saved in last_response when the start returns; it will not be yielded again by events().

def events(self) -> Iterator[Dict]

event: server-side event dict

Iterator

Yields events when the server has a response. Recognition results are located in payload.output.sentence and may be heartbeat or empty-text events, which applications can ignore as needed. Consume continuously from a single receiving thread; do not create multiple concurrent readers.

def results(self) -> Iterator[RecognitionResult]

result: recognition result (RecognitionResult)

Iterator

Only yields recognition result frames (heartbeat frames already filtered); the iteration ends after all recognition results have been returned.

try:
    ...
except DashScopeError as e:
    print(e.code, e.message, e.request_id)

DashScopeError exception

None

Raised in the sending/receiving thread when an exception occurs; can be caught with try/except.

event["header"]["event"] == "task-finished"

task-finished event

None

Yielded by events() after the server has completed all recognition, after which the iteration ends; this event must still be read after stop() is sent.

Response results

Error codes

If you encounter errors, see Error codes for troubleshooting.

If the issue persists, join the developer group listed in the Speech SDK sample repository to report the issue, and provide the Request ID for further troubleshooting.