Real-time speech recognition WebSocket API

Updated at:

The real-time speech recognition API provides streaming transcription over a single WebSocket connection, so you can send audio and receive text results simultaneously.

Endpoint

The WebSocket endpoint is:

wss://convai-platform.aliyuncs.com/api-ws/v1/convai-asr/inference

Use the exact endpoint provided. The path is case-sensitive and must not end with /.

Supported models

Model

Sampling rate

Values for language_hints

Use cases

Qwen-Audio-ASR-VoicePica

8000 / 16000. Must match the actual audio sampling rate.

zh

Real-time recognition for Chinese. Supports task-level hotwords and context enhancement. See run-task for parameter descriptions.

Authentication

Client type

Authentication method

Example

Server-side (Java, Python, Node, Go, etc.)

Handshake request header Authorization: Bearer <api_key>

Authorization: Bearer <VOICE_STUDIO_API_KEY>

Browser

URL query parameter ?token=<api_key>

wss://.../api-ws/v1/convai-asr/inference?token=<VOICE_STUDIO_API_KEY>

  • An API key from Voice Studio is a 32-character hexadecimal string prefixed with sk-. This key is also used for real-time speech synthesis. Native keys from Model Studio are not valid for authentication and cause an HTTP 401 error.

  • A valid API key does not guarantee service access. If the service is not enabled for your account or has been suspended, the handshake will be rejected with an HTTP 403 error.

  • Authentication occurs during the handshake. If the handshake is rejected, the connection is not upgraded to a WebSocket, and no application layer close frame is sent. Browsers typically observe only a close code of 1006.

Request headers

During the handshake, only authentication and tracing information are sent. You specify the recognition model, audio format, sample rate, and recognition feature parameters in the run-task for each task. This allows you to use different parameters for different tasks on the same connection.

Request header

Required

Value

Description

Authorization

Required for server-side applications

Bearer <api_key>

The API key issued by Voice Studio.

X-Request-Id

Optional (strongly recommended)

A non-empty string, preferably 64 characters or fewer.

The server writes the trace ID that you provide back to the X-Request-Id handshake response header without changes. If you do not provide a trace ID, the server generates a UUID. This ID is used only for troubleshooting and not for authentication, task association, or deduplication.

User-Agent

Optional

A client identifier.

Include the application name and version to aid troubleshooting.

URL query parameters

Parameter

Required

Default

Description

token

Required for browsers.

-

An authentication credential for browser connections. For server-side connections, use the Authorization request header.

For troubleshooting, record the connection time (to the second, including the time zone), the client-side-generated task_id, and the received task_uuid.

Handshake example (server-side):

GET /api-ws/v1/convai-asr/inference HTTP/1.1
Host: convai-platform.aliyuncs.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: <WEBSOCKET_KEY>
Authorization: Bearer <VOICE_STUDIO_API_KEY>
X-Request-Id: svc-example-0001

Handshake example (browser, parameter values must be URL-encoded):

wss://convai-platform.aliyuncs.com/api-ws/v1/convai-asr/inference?token=<URL_ENCODED_API_KEY>

Interaction flow

  1. Connection establishment: You establish a connection by initiating a WebSocket handshake with authentication information and receiving a 101 Switching Protocols response. The server does not send application-layer readiness events, such as connected. A successful handshake does not mean the task has started, and the connection can still be closed due to exceeding the concurrency limit, inactivity, or service maintenance.

  2. Send run-task: Use a TEXT frame to specify the recognition model and audio parameters to start a task. Pass payload.parameters.hotwords for hotwords and payload.input.context for context enhancement. You must generate the task_id as a UUID, and all commands for the same task must be consistent.

  3. Wait for the task-started event before you send audio. Save header.task_uuid if available for troubleshooting.

  4. Stream audio data: Send audio in BINARY frames. Stream audio at approximately 1x speed by sending one audio frame every 100 ms. Send the audio as raw binary data, not wrapped in JSON or encoded in Base64.

  5. result-generated: For the same sentence, intermediate results are returned multiple times to overwrite and refresh the content. sentence_end=true indicates the final result for that sentence. While the task is in progress, you can send continue-task as needed to update the context. After the update, streaming continues without waiting for an acknowledgment.

  6. Send the finish-task command: After you send all audio data, including the final segment (even if it is smaller than a full frame), send the finish-task command. This step is mandatory.

  7. Wait for task-finished: After sending the finish-task command, the service may still return the result for the final utterance. If you close the connection too early, you will lose this result. The task-finished event contains the total audio usage for the task.

  8. Reuse or close: When a task finishes normally and the connection is still available, you can use a new task_id to initiate the next run-task, or you can directly close the connection. During service maintenance, you may still receive a 1001 close notification after the task is finished. In this case, you must reconnect for subsequent tasks.

If you receive a task-failed event at any stage, stop sending data and save the error information. The server will then close the connection. To retry, you must establish a new connection.

State constraints

Constraint

Consequence

You must send a run-task command and receive a task-started event before you can send audio.

If you send audio, continue-task, or finish-task before run-task, the server returns a task-failed(CLIENT_ERROR) message and closes the connection.

The task_id must be identical for all commands within the same task.

Mismatched IDs may cause the task to fail or prevent results from being correctly associated with the task.

Only one task can be active on a single connection at a time.

If you send a run-task command while another task is still running, the server returns task-failed(CLIENT_ERROR: run-task while a task is already running) and closes the connection.

Commands must be sent in TEXT frames, and audio must be sent in BINARY frames.

Using incorrect frame types results in a parameter error or protocol error.

You must send the finish-task command.

Omitting this command may prevent the service from returning the complete result for the final utterance or from reaching a normal final state. The task might eventually fail due to a timeout.

After sending finish-task, you must continue receiving data until you get a task-finished or task-failed event.

Closing the connection prematurely means you may lose the result for the final utterance. If you receive task-failed, treat the task as failed and do not wait for task-finished.

Do not reuse a connection after receiving a task-failed event.

The server will close the connection. To retry, you must reconnect.

Client events (upstream)

Upstream communication consists of JSON commands (TEXT frames) and audio (BINARY frames). All JSON commands use the following envelope:

{
  "header": {
    "action": "<event_name>",
    "task_id": "<your_generated_UUID>",
    "streaming": "duplex"
  },
  "payload": {}
}

Header field

Type

Required

Value

Description

action

String

Yes

run-task / continue-task / finish-task

continue-task is an optional command for updating context. If this field is missing, the server returns CLIENT_ERROR: missing header.action. If the event name is unknown, it returns CLIENT_ERROR: unknown action: xxx.

task_id

String

Yes

A UUID string, either 32 characters or with hyphens.

Generate a unique UUID for each new task. All commands for the same task must use the same ID.

streaming

String

Yes

Fixed value: duplex

Indicates duplex streaming.

The header and payload fields must be JSON objects; otherwise, the server returns CLIENT_ERROR: header and payload must be JSON objects. For an invalid JSON message, the server returns CLIENT_ERROR: invalid JSON message. Event and parameter names are case-sensitive.

1. run-task — Start a task

When to send: Send this as the first application-layer command after a connection is established, or after the previous task has completed (indicated by a task-finished event) and the connection remains usable.

Response events: On success, the server returns a task-started event. On failure, it returns a task-failed event and closes the connection.

Only one task can run on a connection at a time. If the connection is reusable after a task finishes, you can start a new one by sending another run-task command with a new task_id.

Top-level payload fields

Parameter

Type

Required

Description

task_group

String

Yes

Fixed value: audio

task

String

Yes

Fixed value: asr

function

String

Yes

Fixed value: recognition

model

String

Yes

The value is fixed as Qwen-Audio-ASR-VoicePica and is case-sensitive. If you use a model that you are not authorized to use, MODEL_NOT_ALLOWED is returned.

parameters

Object

Yes

Recognition parameters. See the two tables below.

input

Object

Yes

To enable contextual biasing, include the context field. Otherwise, send {}. See "Context parameters" for the required structure.

parameters — Audio parameters

Parameter

Type

Required

Default

Value range

Description

format

String

Yes

-

pcm / wav / opus

The audio encoding format. pcm is recommended for real-time scenarios. For packaging requirements, see "BINARY audio frames — Upstream audio".

sample_rate

Integer

Yes

-

8000 / 16000 (in Hz)

Must match the actual audio. The server does not perform audio resampling.

parameters — Functional parameters

Parameter

Type

Required

Default

Value / constraint

Description

hotwords

Object

No

-

{"hotword": weight}, where the weight is an integer from 1 to 5.

Task-level hotwords that apply only to the current task. For count and length limits, see "Task-level hotwords".

language_hints

Array[String]

No

Auto-detect

Example: ["zh"]. For available values, see "Supported Models".

A hint for the target language. Only the first element in the array is used.

max_sentence_silence

Integer

No

Engine default

[200, 6000] (in ms)

The VAD sentence-end silence threshold.

speech_noise_threshold

Float

No

Engine default

[-1.0, 1.0]

A value closer to -1.0 is more likely to classify noise as speech. A value closer to +1.0 is more likely to classify speech as noise. We recommend adjusting this value in small increments (e.g., 0.1) and testing the results.

special_word_filter

String

No

-

A JSON string, not a JSON object.

Custom sensitive word filtering. See the description below.

The value of special_word_filter is a JSON object, serialized into a string, that contains the following fields:

Inner field

Type

Description

filter_with_signed.word_list

Array[String]

Replaces matched words with an equal number of asterisks (*).

filter_with_empty.word_list

Array[String]

Removes matched words from the recognition text.

Custom word filtering applies to both intermediate and final results. An invalid JSON string may be ignored. We recommend validating the JSON on the client side and verifying the actual filtering effect.

Context parameters

Contextual biasing helps the service recognize domain-specific vocabulary by using the most recent conversation turn as a hint for the recognition engine. Only the latest turn is supported, not the full conversation history. This hint supplements the audio input but does not replace it or guarantee recognition of any specific word. You can use this feature with task-level hotwords.

Input field

Type

Required

Description

context

Array[Object]

No

This array must contain only one object, representing the most recent conversation turn. Set the initial context in run-task or update it with continue-task.

context[].role

String

Required within each context object.

user or assistant

context[].content

Array[Object]

Required within each context object.

A list of text content objects.

context[].content[].type

String

Required within each content object.

Use input_text for the user role and text for the assistant role.

context[].content[].text

String

Required within each content object.

The context text.

  • The field path is payload.input.context. Send this as a JSON array, not serialized into a string.

  • When using context, send only the most recent message, not the full conversation history. Context is not retained across tasks on a reused connection; you must provide it for each new task that requires it. If context is not needed, send input: {} in the run-task command.

Example (using both task-level hotwords and initial context)

{
  "header": {
    "action": "run-task",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "streaming": "duplex"
  },
  "payload": {
    "task_group": "audio",
    "task": "asr",
    "function": "recognition",
    "model": "Qwen-Audio-ASR-VoicePica",
    "parameters": {
      "format": "pcm",
      "sample_rate": 16000,
      "hotwords": {"语音实验室": 4, "Tongyi Qianwen": 5},
      "language_hints": ["zh"],
      "max_sentence_silence": 800,
      "special_word_filter": "{\"filter_with_signed\":{\"word_list\":[\"示例敏感词\"]},\"filter_with_empty\":{\"word_list\":[\"示例删除词\"]}}"
    },
    "input": {
      "context": [
        {"role": "assistant", "content": [{"type": "text", "text": "Which capability of the Tongyi Qianwen model would you like to know about?"}]}
      ]
    }
  }
}

2. Binary audio frames — upstream audio

When to send: After receiving a task-started event and before sending a finish-task command. You can send multiple audio frames.

Response events: The server continuously returns result-generated events during recognition. A single audio frame does not necessarily correspond to a single result event.

Item

Requirement

Message type

BINARY. Send the raw audio bytes directly, without JSON or Base64 encoding.

Channels

mono

PCM bit depth

16-bit signed integer, little-endian. Each sample is 2 bytes, so the frame length must be a multiple of 2.

Single audio message size

≤ 65,536 bytes (64 KiB). If this limit is exceeded, the connection is closed with code 1009. Fragmentation at the underlying protocol level does not increase this message size limit.

Recommended framing

One 100 ms frame: 1,600 bytes for 8 kHz PCM, 3,200 bytes for 16 kHz PCM.

Sending pace

Stream the audio as it is generated in real time or at approximately 1x speed. Send offline files at the same 1x pace.

Frame interval

Less than 20 seconds, with an interval of approximately 100 ms recommended. Continue to send silent frames during long pauses in speech.

Format and packaging

Format

Audio requirement

pcm

Raw 16-bit mono PCM without a WAV header. For silence, you can use samples with a value of 0.

wav

16-bit mono PCM in a WAV container. The WAV header must be sent only once at the beginning of the audio stream. Do not add a header to each network packet.

opus

Ogg container format, including the stream header and audio pages. Raw Opus packets sent without the Ogg container are not accepted.

Constraints

  • The format and sample_rate parameters must match the actual audio. The server does not perform audio transcoding, mixing, or resampling. An incorrect sample rate will lead to severe recognition errors.

  • Send compressed audio at a pace that matches its duration. You cannot use the byte-count formula for PCM to estimate the duration of compressed audio. Do not concatenate different audio files into a single continuous container stream.

  • The WebM/Opus format commonly produced by a browser's MediaRecorder API is not the same as the Ogg/Opus format required by the service. For real-time browser capture, convert the audio to 16-bit mono PCM before sending it.

  • The server maintains a backlog limit for unprocessed upstream frames on a single connection. Sending an entire file at once exceeds this limit, causing the server to return a task-failed(CLIENT_ERROR: client input overflow ...) error and close the connection with code 1011.

  • Handle sending and receiving operations separately and continuously read downstream messages. Failure to do so for an extended period will cause the connection to close.

3. continue-task — Update context (optional)

When to send: As needed while a task is in progress, after you receive a task-started event and before you send a finish-task command.

This command provides the most recent conversation turn as context, using the same structure as payload.input.context in run-task (see "Context parameters"). It does not send audio, act as a heartbeat, or end the task. Use it only when you need to update the context.

Payload field

Type

Required

Description

input

Object

Yes

Must contain the context field.

input.context

Array[Object]

Yes

Currently, only the most recent context turn is supported. When updating, the array must contain only one object. To clear the context hint for the current task, send [].

{
  "header": {
    "action": "continue-task",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "streaming": "duplex"
  },
  "payload": {
    "input": {
      "context": [
        {"role": "user", "content": [{"type": "input_text", "text": "I want to confirm how to configure hotwords for the Tongyi Qianwen model."}]}
      ]
    }
  }
}

Constraints

  • Use the original task_id for the current task. The service does not return a task-continued acknowledgment for context updates. After sending a continue-task command, continue sending audio and reading recognition results. Do not wait for an acknowledgment or treat its absence as a failure.

  • The input.context field is mandatory and must be an array. If it is missing, the context is not updated, and no acknowledgment is sent. To clear the context, send []; do not use null or input: {}.

  • Do not include payload.parameters in a continue-task command. Audio parameters and hotwords can only be set in the run-task command.

  • Invalid context content or parameters may cause the recognition engine to return a task-failed event. If this occurs, correct the request based on the error message and establish a new connection.

4. finish-task — End the task (required)

When to send: After all audio has been sent.

Response events: Any remaining result-generated events, followed by a final task-finished event.

Payload field

Type

Required

Value

Description

input

Object

Yes

{}

For a normal termination, send an empty object.

{
  "header": {
    "action": "finish-task",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "streaming": "duplex"
  },
  "payload": {"input": {}}
}
  • Ensure all audio data has been sent before sending this command, including any final audio buffer. After sending finish-task, do not send any more audio or continue-task commands. Send this command only once per task.

  • After sending, you must continue to read messages. A task is considered successful only upon receiving the task-finished event. If you receive a task-failed event or the connection closes first, treat the task as failed and do not wait for task-finished.

Server-side events (downstream)

Downstream recognition results are sent as text messages; audio is not sent in binary messages. The client should handle the following four main event types. All events use a unified header / payload envelope. Dispatch messages based on the header.event field. For an in-flight task, the header.task_id field echoes your original task ID.

Event

Occurrence

Key fields

task-started

When run-task is accepted.

header.task_id, header.task_uuid

result-generated

Multiple times during recognition.

payload.output.sentence, payload.usage

task-finished

When a task finishes normally after finish-task.

payload.usage.duration

task-failed

When a task fails. The connection is then closed.

header.error_code, header.error_message

1. task-started — Task confirmation

{
  "header": {
    "event": "task-started",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "task_uuid": "1008340206f44c8eabd587930b125614",
    "attributes": {}
  },
  "payload": {}
}

Parameter

Type

Description

header.event

String

Fixed value: task-started

header.task_id

String

Echoes your task_id.

header.task_uuid

String / Absent

The task ID from the recognition engine. If present, save it and provide it when reporting issues. Do not use this value as the task_id in subsequent upstream requests.

header.attributes

Object

The example shows an empty object. Do not rely on any extension fields.

payload

Object

The example shows an empty object.

Send audio only after you receive this event.

2. result-generated — Recognition result

For a single sentence, you will receive multiple results: the first result has sentence_begin=true (text is usually empty); a series of interim results have sentence_end=false (text may be rewritten); and the final result for the sentence has sentence_end=true.

Result types (Based on payload.output.sentence, evaluate conditions in the order shown and treat missing boolean fields as false.)

Condition

Description

Client handling

sentence_end=true

The final result for the sentence.

Finalize the result and pass it to downstream services.

sentence_end=false and sentence_begin=true

A new sentence is starting. The text is usually empty.

Initialize the display state for the new sentence.

sentence_end=false and sentence_begin=false

An interim result. The text may be rewritten.

Use the sentence_id to overwrite the current sentence. Do not append each result.

Final result example

{
  "header": {
    "event": "result-generated",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "attributes": {}
  },
  "payload": {
    "output": {
      "sentence": {
        "sentence_id": 1,
        "begin_time": 240,
        "end_time": 1620,
        "text": "你好,我是银行的,",
        "channel_id": 0,
        "speaker_id": null,
        "sentence_end": true,
        "words": [
          {"begin_time": 240, "end_time": 1620, "text": "你好,我是银行的", "punctuation": ",", "fixed": false, "speaker_id": null}
        ]
      }
    },
    "usage": {"duration": 2}
  }
}

Interim results have the same structure as the final result, except that sentence_end is false, end_time is null, and the usage field is typically not included. This model does not provide word-level timestamps; the words field in the example uses the full sentence text and sentence-level time.

Field descriptions

Parameter

Type

Presence

Description

output.sentence.sentence_id

Integer

Always

The sentence index, incrementing from 1.

output.sentence.begin_time

Integer

Always

The sentence start time in milliseconds (ms), relative to the start of the audio for this task. May be adjusted in interim results.

output.sentence.end_time

Integer / null

Always

The sentence end time in milliseconds (ms). The value is null for interim results.

output.sentence.text

String

Always

The recognized text, including punctuation. Can be an empty string at the beginning of a sentence or during silence.

output.sentence.channel_id

Integer

Always

The channel ID. Fixed to 0 for mono audio.

output.sentence.speaker_id

Integer / null

Always

The speaker ID. Currently always null.

output.sentence.sentence_begin

Boolean

Only in the first result for a new sentence.

true indicates the start of a new sentence.

output.sentence.sentence_end

Boolean

Always

true for the final result of the sentence; false for an interim result.

output.sentence.words[ ].text

String

Conditional

The full sentence text; trailing punctuation is in a separate field. words can be an empty array if the text is empty.

output.sentence.words[ ].punctuation

String

Conditional

Punctuation. Can be an empty string if there is no punctuation.

output.sentence.words[ ].begin_time / end_time

Integer

Conditional

The start and end times for the entire sentence in milliseconds (ms), relative to the start of the audio for this task. Does not represent a word-level timestamp.

output.sentence.words[ ].fixed

Boolean

Conditional

Do not rely on this field to determine stability. Use sentence_end=true to confirm that a sentence is finalized.

payload.usage.duration

Integer / null

Always present if sentence_end is true; may be present in other results.

A snapshot of the cumulative audio usage for the task, in seconds. Do not sum these values, as they are not deltas. The task-finished event provides the final total.

Client handling recommendations

  • Real-time captions: Use interim results with the same sentence_id to overwrite and refresh the current line. Finalize the line and start a new one when sentence_end=true.

  • Conversational AI/Outbound calls: Send only the text from results where sentence_end=true to downstream services, such as a large model. Use interim results only for UI display or interruption detection.

  • Full transcription: Concatenate the text from all results where sentence_end=true, in order of their sentence_id.

3. task-finished — Task finished

{
  "header": {
    "event": "task-finished",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "attributes": {}
  },
  "payload": {
    "output": {},
    "usage": {"duration": 8}
  }
}

Parameter

Type

Description

header.event

String

Fixed value: task-finished

header.task_id

String

Echoes your task_id.

header.attributes

Object

The example shows an empty object.

payload.usage.duration

Integer / null

The final audio usage for this task in integer seconds. For details, see "Audio Usage".

This event indicates that the task finished successfully and all results have been sent. You can now close the connection or start a new task with a new task_id on the same connection. During service maintenance, the server may close the connection with code 1001 after this event. If this happens, you must establish a new connection for subsequent tasks. You do not need to redo the completed task.

4. task-failed — Task failed

{
  "header": {
    "event": "task-failed",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "error_code": "CLIENT_ERROR",
    "error_message": "not supported by model Qwen-Audio-ASR-VoicePica: heartbeat=true",
    "attributes": {}
  },
  "payload": {}
}

In this example, the unsupported parameter heartbeat=true is passed to the parameters of run-task before the task starts, which results in no audio usage.

Parameter

Type

Description

header.event

String

Fixed value: task-failed

header.task_id

String

The associated task ID. If an error occurs before run-task, this is the task_id from the frame that caused the error. If the field is missing or the JSON is unparsable, the service returns an empty string.

header.error_code

String

An error code for programmatic handling. For details, see "Error Codes and Close Codes".

header.error_message

String

A human-readable description of the error. Provide the full original message when reporting an issue.

header.attributes

Object

The example shows an empty object.

payload.usage.duration

Integer / null / Absent

If an in-flight task fails, this is the final confirmed audio usage based on audio the service has acknowledged. This field is not included for errors that occur before a task starts.

  • After a task-failed event, the server immediately closes the connection. Do not send any more data on this connection. To retry, establish a new connection and use a new task_id.

  • This API does not send a payload.error.type field. Use the header.error_code and the error code table to determine how to handle the error.

  • The duration in a failure response represents audio usage and is not a final billing determination.

Task-level hotwords

You can provide hotwords directly in the payload.parameters.hotwords field of a run-task request to improve the recognition of homophones or similar-sounding words, such as proper nouns, product names, and domain-specific terms. These settings are task-specific and do not require you to create resources in advance.

Rule

Description

Format

A JSON object that maps hotwords to their integer weights. Do not pass an array or a JSON string.

Weight

An integer from 1 to 5. A higher value makes the word more likely to be recognized.

Number and length

Up to 1,024 hotwords. Each hotword must not exceed 20 characters.

Scope

Applies only to the current task. Hotwords must be declared in a run-task request. They cannot be updated in a continue-task request.

Example of the parameters field in a run-task request (other required fields are omitted):

{
  "format": "pcm",
  "sample_rate": 16000,
  "hotwords": {"Speech Lab": 4, "Tongyi Qianwen": 5}
}

The complete run-task message must also adhere to the overall message size constraints.

Hotwords increase recognition probability but do not guarantee their inclusion in the output. Include only words that are essential for your business needs. Before deploying to production, test with real audio to compare recognition results with and without hotwords.

Key concepts and limitations

Constraints at a glance

Constraint

Value

Upstream command frame type

TEXT

Upstream audio frame type

BINARY, mono; PCM must be 16-bit little-endian.

Single audio message size

≤ 65,536 bytes (64 KiB). Exceeding this limit closes the connection with close code 1009. We recommend sending one frame every 100 ms.

Single command message size

The server-side limit for a TEXT message is 65,536 UTF-16 code units. Exceeding this limit closes the connection with close code 1009. We also recommend keeping the complete JSON object within 64 KiB after it is UTF-8 encoded.

Sending pace

Approximately 1x real time. A sudden influx of audio triggers upstream backpressure protection.

In-task audio interval

Less than 20 seconds. We recommend an interval of approximately 100 ms.

Connection idle (no upstream or downstream frames, including ping/pong)

The connection has a 60-second idle timeout. To prevent timeouts, send a protocol-level ping every 15 to 30 seconds.

Concurrent tasks on a single connection

1. The connection can be serially reused for a new task if the previous one finishes successfully and the connection remains active.

Connection after a task fails

The connection is closed and cannot be reused.

Concurrency

The number of active WebSocket connections in a workspace.

The preceding size limits apply to the entire WebSocket message. Fragmentation at the underlying protocol layer does not relax these limits. The number of UTF-16 code units generally corresponds to the number of Chinese or English characters, but supplementary plane characters, such as some emoji, occupy two code units. This is different from the number of UTF-8 bytes.

Audio usage

The payload.usage.duration field represents the audio usage for a task in seconds. It is not the connection duration, the length of the recognized transcript, or the speaking duration of the current sentence.

  • This value represents the total duration of audio samples successfully delivered to the recognition engine, including leading, inter-sentence, and trailing silence. It does not include connection wait time, audio that failed to send, or buffered audio that has not yet been sent.

  • For PCM, usage is calculated based on the declared sample rate. For WAV, it is based on the actual sample rate and counts only the audio data. For compressed formats, usage is calculated based on the complete encoded frames or container sample information, not estimated from the compressed byte size.

  • The service rounds the cumulative duration for each task to the nearest integer second using the HALF_UP rounding mode. It does not perform rounding on each network frame, and there is no minimum usage charge. The service rounds the usage for different tasks separately before aggregating them.

  • The duration in a result-generated event is a cumulative snapshot; do not sum it across events. For a successfully completed task, the final value in the task-finished event is the definitive usage.

Cumulative duration

Final usage.duration

0 seconds

0

0.49 seconds

0

0.5 seconds

1

2.5 seconds

3

8.245 seconds

8

For example, if two tasks each have a duration of 2.5 seconds, each is rounded to 3 seconds individually, for a total of 6 seconds. You cannot combine them to 5 seconds before rounding.

A usage report from the service is not a confirmation of successful billing. The following scenarios are billable based on the valid audio usage successfully delivered to the recognition engine: normal completion, client-initiated interruptions (including but not limited to close code 1000), client-side transport-level interruptions, and client-side timeouts caused by not maintaining a continuous push stream or by an idle connection. A mid-task closure, a network disconnection, or not receiving a final usage value does not imply that the service is free of charge. Failures caused by the platform or recognition engine and interruptions due to service maintenance are not billed. You cannot determine billability solely based on the close code or the duration value in the response. Tasks with zero seconds of usage or where usage cannot be metered do not generate billable seconds. The final price and settlement are subject to your service agreement and official bill.

Timeout matrix

Timeout item

Threshold / requirement

Trigger / phase

Result

In-task audio interval

20 seconds

You must continuously push stream before sending finish-task. The interval between audio frames must be less than 20 seconds.

A prolonged pause in streaming may result in a task-failed event and connection closure. Do not use pings as a substitute for audio.

Connection idle

60 seconds

No WebSocket frames of any kind (TEXT, BINARY, ping/pong) are sent or received.

The connection may be closed with close code 1001, with a possible reason of idle timeout expired. Do not rely on the connection closing at exactly 60 seconds.

Service maintenance wait for in-flight tasks

Up to 5 minutes

A task is in progress during an instance deployment or scale-in.

Idle connections are closed immediately with close code 1001. For in-flight tasks, the connection is closed with code 1001 after task-finished. If the timeout is exceeded, the server sends task-failed(SERVICE_DRAINING) and then closes the connection with code 1001.

Upstream backpressure

Server backpressure threshold

A burst of audio is sent.

A task-failed(CLIENT_ERROR: client input overflow ...) event is returned, and the connection is subsequently closed with close code 1011.

Connection keep-alive

Send a WS ping every 15-30 seconds.

Client proactively sends a protocol-level ping.

Resets the connection idle timer. The server automatically responds with a pong.

  • When a protocol-level WebSocket ping reaches the server, it resets the connection idle timer. Do not set your keep-alive interval to the 60-second threshold. Before using this feature, confirm that your client library and any intermediate proxies support ping/pong. NAT devices, load balancing services, and proxies in the connection path may have their own, shorter idle timeouts. The keep-alive interval must be shorter than the minimum timeout of all components in the path.

  • Pings are used for connection keep-alive but do not prevent the connection from closing due to network issues, service maintenance, or task failures. They are not a substitute for audio. You must continue to push stream while a task is in progress. For scenarios with long silences, continue to send silent audio frames.

  • The native WebSocket API in browsers does not provide a method for sending protocol-level pings. Reconnect as needed between tasks. Do not send custom action=ping commands or empty TEXT frames as a fake heartbeat.

Concurrency limit

  • The concurrency limit applies to the number of active WebSocket connections per workspace. A connection consumes one concurrency slot when established and releases it when closed.

  • Idle connections also count towards your quota. Connections that are open but not actively used for recognition do not automatically release their slots. Proactively close connections when they are no longer needed.

  • A single connection cannot execute multiple tasks in parallel. To run recognition tasks in parallel, use multiple connections.

  • The service immediately closes new connections that exceed the limit with close code 4429 and the reason CONCURRENCY_LIMIT_EXCEEDED. It does not send a task-failed event, and existing connections are not affected.

  • Your service agreement determines your concurrency quota. To request an increase, please contact the platform.

Error codes and close codes

Business error codes (task-failed)

Error code

Error message

Close code

Description and action

CLIENT_ERROR

invalid JSON message, header and payload must be JSON objects, missing header.action, unknown action: xxx

1000

Invalid command format. Correct the format and retry. Retrying with the original command will fail.

CLIENT_ERROR

binary audio before run-task / upstream not ready, continue-task before run-task / upstream not ready, finish-task before run-task / upstream not ready

1000

Audio or a command was sent before starting a task. Send a run-task command and wait for the task-started response before streaming audio.

CLIENT_ERROR

run-task while a task is already running

1000

The server has terminated this connection. Establish a new connection. For the standard workflow, wait for the task-finished response from the previous task before sending a new run-task command. For parallel recognition, use separate connections.

CLIENT_ERROR

format xxx is not supported by model Qwen-Audio-ASR-VoicePica, use pcm, wav or opus, not supported by model Qwen-Audio-ASR-VoicePica: ...

1000

The model does not support the specified format or capability. Remove the unsupported parameter or convert the audio format as indicated in the error message.

CLIENT_ERROR

commercial access denied or unavailable

1000

Your access to the service for this task was denied or is temporarily unavailable. Check your account's service status and contact the platform. Avoid unconditional retries.

CLIENT_ERROR

client input overflow: too many pending frames, please send audio at real-time pace

1011

Sending audio data too quickly caused a backlog. Stream audio at a real-time pace. Establish a new connection and restart the task.

MODEL_NOT_ALLOWED

model not allowed: xxx

1000

The model parameter must be set to Qwen-Audio-ASR-VoicePica. If the request still fails with the correct model, check your account's service activation status and contact the platform.

CONFIG_MISSING

no available apiKey ...

1000

A platform-side configuration is not ready. Contact the platform for assistance. Retrying will not resolve the issue.

UPSTREAM_ERROR

failed to establish upstream connection

1000

The connection to the recognition engine is temporarily unavailable. Establish a new connection after an exponential backoff.

UPSTREAM_ERROR

Recognition engine connection error / interruption

1011

Establish a new connection after an exponential backoff.

SERVICE_DRAINING

server draining, please reconnect and retry

1001

The service is undergoing maintenance, which interrupted the in-flight task. Establish a new connection after a short backoff. Rerun unfinished tasks as required by your business logic.

Other (e.g., InvalidParameter)

Original message from the recognition engine

1011

The recognition engine rejected the parameters or an engine-side error occurred. This can happen if parameters such as format, sample_rate, language_hints, hotwords, or context are invalid, or if parameters are passed in a continue-task command. Correct the parameters according to the error message. If you cannot determine the cause, contact the platform.

WebSocket close codes

Close code

Description

Action

1000

Normal closure. This code is also sent after a platform validation failure (e.g., CLIENT_ERROR, MODEL_NOT_ALLOWED, or CONFIG_MISSING).

A 1000 close code does not guarantee task success. The final status depends on receiving a task-finished message or a preceding task-failed message.

1001

Service maintenance or connection idle timeout (the timeout is 60 seconds).

If closed due to idle timeout, reconnect as needed. If due to service maintenance, reconnect after a short backoff (connection to a new instance is not guaranteed). Do not rerun tasks that have already completed with a task-finished message.

1006

The connection was closed due to a network error, or a browser-side handshake was rejected (the actual status code cannot be read).

Check your network and credentials, then reconnect. Refer to the Handshake errors section below for troubleshooting.

1009

An upstream message exceeded the server-side size limit. See the "Constraints" section for details.

Reduce the size of the entire command or individual audio messages. Splitting the message into underlying protocol fragments is not a valid workaround. For audio, we recommend sending one frame every 100 ms.

1011

An internal server error occurred, caused by a recognition engine task failure, a connection interruption, or an upstream backlog overflow. A task-failed message is usually sent before the connection closes.

Handle the error based on the preceding error_code. For engine or internal errors, establish a new connection with exponential backoff.

4429

Your workspace has reached its concurrent connection limit. The connection is closed immediately after establishment, and no task-failed message is sent.

Close idle connections and retry after a delay, or request a quota increase.

During network or transport errors, a task-failed message may not be delivered. Do not consider a task complete solely based on a normal close code; successful completion requires receiving a task-finished message.

Handshake errors

If the handshake phase fails, the connection is not upgraded to a WebSocket. Consequently, no task-failed message or application-layer close frame is sent.

HTTP status code

Description

Action

401

The credential is missing, invalid, or expired, or a key from Model Studio was used.

Check the source of the key and the Bearer prefix, reconnect after refreshing your credential, and do not repeatedly retry with the original credential.

403

Your access to the service was denied. For example, the service is not enabled for your account or has been suspended.

Verify your account's service status. Save the response details and contact the platform.

404

Incorrect API endpoint (spelling error, incorrect case, or an extra trailing /)

Use the complete API endpoint provided in this document.

503

The service is temporarily unavailable.

Establish a new connection after a short backoff. If the issue persists, contact technical support.