跳转至内容

语音(Audio)

client.audio 汇集语音合成(TTS)、语音识别(ASR)、实时 WebSocket 会话与 Qwen Live,以及音色/热词定制能力。

Audio 入口

Audio

Audio(client)

Sync audio surface.

Source code in dashscope/resources/audio/__init__.py
175
176
177
178
179
180
181
182
183
def __init__(self, client) -> None:
    self.asr = Asr(client)
    self.tts = Tts(client)
    self.realtime = Realtime(client)
    self.live = Live(client)
    self.vocabularies = Vocabularies(client)
    self.phrases = Phrases(client)
    self.voices = Voices(client)
    self.voice_design = VoiceDesign(client)

asr instance-attribute

asr = Asr(client)

tts instance-attribute

tts = Tts(client)

realtime instance-attribute

realtime = Realtime(client)

live instance-attribute

live = Live(client)

vocabularies instance-attribute

vocabularies = Vocabularies(client)

phrases instance-attribute

phrases = Phrases(client)

voices instance-attribute

voices = Voices(client)

voice_design instance-attribute

voice_design = VoiceDesign(client)

AsyncAudio

AsyncAudio(client)

Async audio surface.

Only batch transcription is exposed here; the ws realtime resources (asr.recognize, tts, realtime) are sync-only by design (design doc M3 3.5).

Source code in dashscope/resources/audio/__init__.py
194
195
196
197
198
199
200
def __init__(self, client) -> None:
    self.asr = AsyncAsr(client)
    self.tts = _AsyncTts(client)
    self.vocabularies = _AsyncResourceProxy(client, Vocabularies)
    self.phrases = _AsyncResourceProxy(client, Phrases)
    self.voices = _AsyncResourceProxy(client, Voices)
    self.voice_design = _AsyncResourceProxy(client, VoiceDesign)

asr instance-attribute

asr = AsyncAsr(client)

tts instance-attribute

tts = _AsyncTts(client)

vocabularies instance-attribute

vocabularies = _AsyncResourceProxy(client, Vocabularies)

phrases instance-attribute

phrases = _AsyncResourceProxy(client, Phrases)

voices instance-attribute

voices = _AsyncResourceProxy(client, Voices)

voice_design instance-attribute

voice_design = _AsyncResourceProxy(client, VoiceDesign)

语音合成(TTS)

Tts

Tts(client)

Speech synthesis (one-shot + streaming) over websocket.

Source code in dashscope/resources/audio/tts.py
291
292
293
def __init__(self, client) -> None:
    self._client = client
    self.http = HttpTts(client)

http instance-attribute

http = HttpTts(client)

connect

connect(
    *,
    model: str = "cosyvoice-v1",
    voice: str = "longxiaochun",
    format: str = "mp3",
    sample_rate: int = 22050,
    volume: Optional[int] = None,
    rate: Optional[float] = None,
    pitch: Optional[float] = None,
    language_hints: Optional[List[str]] = None,
    enable_ssml: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    connection: Optional[WsConnection] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
) -> SynthesisSession

Create a duplex session; enter its context or call start().

With connection= the session runs as one task on the shared socket and claims its binary downlink (one active synthesis per connection).

Source code in dashscope/resources/audio/tts.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
def connect(
    self,
    *,
    model: str = "cosyvoice-v1",
    voice: str = "longxiaochun",
    format: str = "mp3",  # pylint: disable=redefined-builtin
    sample_rate: int = 22050,
    volume: Optional[int] = None,
    rate: Optional[float] = None,
    pitch: Optional[float] = None,
    language_hints: Optional[List[str]] = None,
    enable_ssml: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    connection: Optional[WsConnection] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> SynthesisSession:
    """Create a duplex session; enter its context or call start().

    With ``connection=`` the session runs as one task on the shared
    socket and claims its binary downlink (one active synthesis per
    connection).
    """
    return SynthesisSession(
        self._client,
        model=model,
        voice=voice,
        format=format,
        sample_rate=sample_rate,
        volume=volume,
        rate=rate,
        pitch=pitch,
        language_hints=language_hints,
        enable_ssml=enable_ssml,
        parameters=parameters,
        ws_url=ws_url,
        connector=connector,
        connection=connection,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
    )

synthesize

synthesize(
    text: str,
    *,
    model: str = "cosyvoice-v1",
    voice: str = "longxiaochun",
    format: str = "mp3",
    sample_rate: int = 22050,
    volume: Optional[int] = None,
    rate: Optional[float] = None,
    pitch: Optional[float] = None,
    language_hints: Optional[List[str]] = None,
    enable_ssml: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
) -> bytes

Synthesize the whole text; returns the concatenated audio.

Source code in dashscope/resources/audio/tts.py
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def synthesize(
    self,
    text: str,
    *,
    model: str = "cosyvoice-v1",
    voice: str = "longxiaochun",
    format: str = "mp3",  # pylint: disable=redefined-builtin
    sample_rate: int = 22050,
    volume: Optional[int] = None,
    rate: Optional[float] = None,
    pitch: Optional[float] = None,
    language_hints: Optional[List[str]] = None,
    enable_ssml: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> bytes:
    """Synthesize the whole text; returns the concatenated audio."""
    return b"".join(
        self.stream(
            text,
            model=model,
            voice=voice,
            format=format,
            sample_rate=sample_rate,
            volume=volume,
            rate=rate,
            pitch=pitch,
            language_hints=language_hints,
            enable_ssml=enable_ssml,
            parameters=parameters,
            ws_url=ws_url,
            connector=connector,
            timeout=timeout,
            headers=headers,
            api_key=api_key,
            workspace=workspace,
        ),
    )

stream

stream(
    text: str,
    *,
    model: str = "cosyvoice-v1",
    voice: str = "longxiaochun",
    format: str = "mp3",
    sample_rate: int = 22050,
    volume: Optional[int] = None,
    rate: Optional[float] = None,
    pitch: Optional[float] = None,
    language_hints: Optional[List[str]] = None,
    enable_ssml: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
) -> Iterator[bytes]

Yield audio chunks as they arrive.

Source code in dashscope/resources/audio/tts.py
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def stream(
    self,
    text: str,
    *,
    model: str = "cosyvoice-v1",
    voice: str = "longxiaochun",
    format: str = "mp3",  # pylint: disable=redefined-builtin
    sample_rate: int = 22050,
    volume: Optional[int] = None,
    rate: Optional[float] = None,
    pitch: Optional[float] = None,
    language_hints: Optional[List[str]] = None,
    enable_ssml: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> Iterator[bytes]:
    """Yield audio chunks as they arrive."""
    with self.connect(
        model=model,
        voice=voice,
        format=format,
        sample_rate=sample_rate,
        volume=volume,
        rate=rate,
        pitch=pitch,
        language_hints=language_hints,
        enable_ssml=enable_ssml,
        parameters=parameters,
        ws_url=ws_url,
        connector=connector,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
    ) as session:
        session.send_text(text)
        session.stop()
        yield from session.audio_chunks()

SynthesisSession

SynthesisSession(
    client,
    *,
    model: str = "cosyvoice-v1",
    voice: str = "longxiaochun",
    format: str = "mp3",
    sample_rate: int = 22050,
    volume: Optional[int] = None,
    rate: Optional[float] = None,
    pitch: Optional[float] = None,
    language_hints: Optional[List[str]] = None,
    enable_ssml: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    connection: Optional[WsConnection] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
)

Duplex synthesis with concurrent text input and one result iterator.

Source code in dashscope/resources/audio/tts.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
def __init__(
    self,
    client,
    *,
    model: str = "cosyvoice-v1",
    voice: str = "longxiaochun",
    format: str = "mp3",  # pylint: disable=redefined-builtin
    sample_rate: int = 22050,
    volume: Optional[int] = None,
    rate: Optional[float] = None,
    pitch: Optional[float] = None,
    language_hints: Optional[List[str]] = None,
    enable_ssml: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    connection: Optional[WsConnection] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> None:
    config = client.config
    self._model = model
    self._parameters = _merged_parameters(
        voice=voice,
        format=format,
        sample_rate=sample_rate,
        volume=volume,
        rate=rate,
        pitch=pitch,
        language_hints=language_hints,
        enable_ssml=enable_ssml,
        parameters=parameters,
    )
    # A shared connection runs this synthesis as one task on it;
    # ws_url/connector/api_key/workspace/headers then belong to the
    # connection and the per-session values are ignored.
    self._connection = connection
    self._session_kwargs = {
        "url": ws_url,
        "api_key": api_key or config.api_key,
        "workspace": workspace or config.workspace,
        "region": config.region,
        "headers": with_client_user_agent(client, headers),
        "connector": connector,
        "module": MODULE,
        "timeout": config.timeout if timeout is None else timeout,
    }
    self._session: Union[WsSession, WsTask, None] = None
    self._closed = False
    self._reader_lock = threading.Lock()
    self._first_text_at: Optional[float] = None
    self.last_response: Optional[Dict[str, Any]] = None
    self.usage: Optional[Dict[str, Any]] = None
    self.first_package_delay: Optional[float] = None

last_response instance-attribute

last_response: Optional[Dict[str, Any]] = None

usage instance-attribute

usage: Optional[Dict[str, Any]] = None

first_package_delay instance-attribute

first_package_delay: Optional[float] = None

session property

session: Union[WsSession, WsTask]

Underlying websocket session, including its task_id.

start

start() -> 'SynthesisSession'

Open the connection and wait for the task-started handshake.

Source code in dashscope/resources/audio/tts.py
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def start(self) -> "SynthesisSession":
    """Open the connection and wait for the task-started handshake."""
    if self._closed:
        raise RuntimeError("synthesis session is closed")
    if self._session is not None:
        raise RuntimeError("synthesis session is already started")
    try:
        if self._connection is not None:
            self._session = self._connection.open_task(
                timeout=self._session_kwargs["timeout"],
            )
            # Synthesis output is binary audio, which carries no task
            # id on the wire; claim the downlink before it arrives.
            self._session.claim_binary_downlink()
        else:
            self._session = WsSession(**self._session_kwargs)
        response = self._session.run_task(
            task_group="audio",
            task="tts",
            function="SpeechSynthesizer",
            model=self._model,
            parameters=self._parameters,
            input={},
        )
        self._record_response(response)
    except BaseException as error:
        self._record_response(getattr(error, "body", None))
        self.close()
        raise
    return self

send_text

send_text(text: str) -> None

Send another text fragment; not allowed after stop or cancel.

Source code in dashscope/resources/audio/tts.py
189
190
191
192
193
194
195
196
197
198
199
200
def send_text(self, text: str) -> None:
    """Send another text fragment; not allowed after stop or cancel."""
    if not isinstance(text, str):
        raise TypeError("text must be a string")
    try:
        session = self.session
        if self._first_text_at is None:
            self._first_text_at = time.monotonic()
        session.continue_task({"text": text})
    except Exception:
        self.close()
        raise

flush

flush() -> None

Request synthesis of buffered text without ending input.

Source code in dashscope/resources/audio/tts.py
202
203
204
205
206
207
208
def flush(self) -> None:
    """Request synthesis of buffered text without ending input."""
    try:
        self.session.continue_task({"flush": True})
    except Exception:
        self.close()
        raise

stop

stop() -> None

End input without blocking for results; keep reading afterward.

Source code in dashscope/resources/audio/tts.py
210
211
212
213
214
215
216
def stop(self) -> None:
    """End input without blocking for results; keep reading afterward."""
    try:
        self.session.finish_task()
    except Exception:
        self.close()
        raise

cancel

cancel() -> None

Cancel once, even after stop, before a terminal event arrives.

Source code in dashscope/resources/audio/tts.py
218
219
220
221
222
223
224
def cancel(self) -> None:
    """Cancel once, even after stop, before a terminal event arrives."""
    try:
        self.session.finish_task({"directive": "cancel"})
    except Exception:
        self.close()
        raise

events

events() -> (
    Generator[Union[Dict[str, Any], bytes], None, None]
)

Yield JSON and audio through task-finished, raising on failure.

Source code in dashscope/resources/audio/tts.py
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def events(self) -> Generator[Union[Dict[str, Any], bytes], None, None]:
    """Yield JSON and audio through task-finished, raising on failure."""
    session = self.session
    # Non-blocking acquire, released in the finally below — no ``with``.
    # pylint: disable=consider-using-with
    if not self._reader_lock.acquire(blocking=False):
        raise RuntimeError(
            "only one events() or audio_chunks() iterator may read "
            "the synthesis session",
        )
    try:
        while not session.finished:
            frame = self.session.recv()
            if frame is None:
                return
            if isinstance(frame, bytes):
                if (
                    self.first_package_delay is None
                    and self._first_text_at is not None
                ):
                    self.first_package_delay = (
                        time.monotonic() - self._first_text_at
                    ) * 1000
            else:
                self._record_response(frame)
            yield frame
    except Exception as error:
        self._record_response(getattr(error, "body", None))
        self.close()
        raise
    finally:
        self._reader_lock.release()

audio_chunks

audio_chunks() -> Iterator[bytes]

Yield only audio, retaining JSON metadata on this session.

Source code in dashscope/resources/audio/tts.py
266
267
268
269
270
271
272
273
274
def audio_chunks(self) -> Iterator[bytes]:
    """Yield only audio, retaining JSON metadata on this session."""
    events = self.events()
    try:
        for frame in events:
            if isinstance(frame, bytes):
                yield frame
    finally:
        events.close()

close

close() -> None

Close the connection; a closed session cannot be restarted.

With a shared WsConnection this only detaches the task; the socket belongs to the connection and stays open.

Source code in dashscope/resources/audio/tts.py
276
277
278
279
280
281
282
283
284
285
def close(self) -> None:
    """Close the connection; a closed session cannot be restarted.

    With a shared ``WsConnection`` this only detaches the task; the
    socket belongs to the connection and stays open.
    """
    if not self._closed:
        self._closed = True
        if self._session is not None:
            self._session.close()

HttpTts

HttpTts(client)

client.audio.tts.http -- HTTP synthesis for both families.

Source code in dashscope/resources/audio/http_tts.py
642
643
def __init__(self, client) -> None:
    self._client = client

synthesize

synthesize(
    text: str,
    *,
    model: str,
    voice: str,
    format: Optional[str] = None,
    sample_rate: Optional[int] = None,
    language_type: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> HttpSynthesis
synthesize(
    text: str,
    *,
    model: str,
    voice: str,
    format: Optional[str] = None,
    sample_rate: Optional[int] = None,
    language_type: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
synthesize(
    text: str,
    *,
    model: str,
    voice: str,
    format: Optional[str] = None,
    sample_rate: Optional[int] = None,
    language_type: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[HttpSynthesis, "APIResponse"]

Synthesize in one POST; the audio comes back as a URL.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error. :meth:stream has no raw -- a streaming body is never materialized.

Source code in dashscope/resources/audio/http_tts.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
def synthesize(
    self,
    text: str,
    *,
    model: str,
    voice: str,
    format: Optional[str] = None,  # pylint: disable=redefined-builtin
    sample_rate: Optional[int] = None,
    language_type: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[HttpSynthesis, "APIResponse"]:
    """Synthesize in one POST; the audio comes back as a URL.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    :meth:`stream` has no ``raw`` -- a streaming body is never
    materialized.
    """
    resp = self._client.transport.request_api(
        "POST",
        _path_for(model),
        json=_build_body(
            text,
            model=model,
            voice=voice,
            format=format,
            sample_rate=sample_rate,
            language_type=language_type,
            parameters=parameters,
            extra_input=extra_input,
        ),
        headers=headers,
        timeout=timeout,
        sdk_module=MODULE,
        api_key=api_key,
        workspace=workspace,
        options=request_options(
            extra_headers,
            extra_query,
            extra_body,
            max_retries=max_retries,
        ),
        client=self._client,
    )
    if raw:
        return resp
    response = resp.http_response
    return _synthesis_from_response(
        response,
        raise_on_error=self._client.raise_on_error,
        strict=self._client.config.strict_validation,
    )

stream

stream(
    text: str,
    *,
    model: str,
    voice: str,
    format: Optional[str] = None,
    sample_rate: Optional[int] = None,
    language_type: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None
) -> HttpSynthesisStream

Stream the synthesis over SSE, one chunk per part.

Audio frames arrive base64-decoded on :attr:HttpSynthesisChunk.audio; the final chunk (is_final) carries the whole-audio URL reference. The envelope's raw HTTP headers are on :attr:HttpSynthesisStream.headers.

Source code in dashscope/resources/audio/http_tts.py
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def stream(
    self,
    text: str,
    *,
    model: str,
    voice: str,
    format: Optional[str] = None,  # pylint: disable=redefined-builtin
    sample_rate: Optional[int] = None,
    language_type: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
) -> HttpSynthesisStream:
    """Stream the synthesis over SSE, one chunk per part.

    Audio frames arrive base64-decoded on :attr:`HttpSynthesisChunk.audio`;
    the final chunk (``is_final``) carries the whole-audio URL reference.
    The envelope's raw HTTP headers are on
    :attr:`HttpSynthesisStream.headers`.
    """
    sse_headers = dict(_SSE_HEADER)
    if headers:
        sse_headers.update(headers)
    try:
        response = self._client.transport.open_stream(
            "POST",
            _path_for(model),
            json=_build_body(
                text,
                model=model,
                voice=voice,
                format=format,
                sample_rate=sample_rate,
                language_type=language_type,
                parameters=parameters,
                extra_input=extra_input,
            ),
            headers=sse_headers,
            timeout=timeout,
            sdk_module=MODULE,
            api_key=api_key,
            workspace=workspace,
            options=request_options(
                extra_headers,
                extra_query,
                extra_body,
                max_retries=max_retries,
            ),
        )
    except APIStatusError as error:
        # >=400 is raised (and closed) before open_stream returns a response.
        _with_audio_request_id(error)
        _log_audio_error(error)
        raise
    return HttpSynthesisStream(self._events(response), response)

AsyncHttpTts

AsyncHttpTts(client)

Async HTTP TTS using the AsyncClient's own connection pool.

Source code in dashscope/resources/audio/http_tts.py
479
480
def __init__(self, client) -> None:
    self._client = client

synthesize async

synthesize(
    text: str, **kwargs
) -> Union[HttpSynthesis, "APIResponse"]

Async twin of :meth:HttpTts.synthesize, raw included.

Source code in dashscope/resources/audio/http_tts.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
async def synthesize(
    self,
    text: str,
    **kwargs,
) -> Union[HttpSynthesis, "APIResponse"]:
    """Async twin of :meth:`HttpTts.synthesize`, ``raw`` included."""
    model = kwargs.pop("model")
    voice = kwargs.pop("voice")
    raw = kwargs.pop("raw", False)
    resp = await self._client.transport.request_api(
        "POST",
        _path_for(model),
        json=_build_body(
            text,
            model=model,
            voice=voice,
            **{
                key: kwargs.pop(key, None)
                for key in (
                    "format",
                    "sample_rate",
                    "language_type",
                    "parameters",
                    "extra_input",
                )
            },
        ),
        headers=kwargs.pop("headers", None),
        timeout=kwargs.pop("timeout", None),
        sdk_module=MODULE,
        api_key=kwargs.pop("api_key", None),
        workspace=kwargs.pop("workspace", None),
        options=request_options(
            kwargs.pop("extra_headers", None),
            kwargs.pop("extra_query", None),
            kwargs.pop("extra_body", None),
            max_retries=kwargs.pop("max_retries", None),
        ),
        client=self._client,
    )
    if raw:
        return resp
    response = resp.http_response
    return _synthesis_from_response(
        response,
        raise_on_error=self._client.raise_on_error,
        strict=self._client.config.strict_validation,
    )

stream async

stream(text: str, **kwargs) -> AsyncHttpSynthesisStream
Source code in dashscope/resources/audio/http_tts.py
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
async def stream(self, text: str, **kwargs) -> AsyncHttpSynthesisStream:
    model = kwargs.pop("model")
    voice = kwargs.pop("voice")
    headers = dict(_SSE_HEADER)
    headers.update(kwargs.pop("headers", None) or {})
    try:
        response = await self._client.transport.open_stream(
            "POST",
            _path_for(model),
            json=_build_body(
                text,
                model=model,
                voice=voice,
                **{
                    key: kwargs.pop(key, None)
                    for key in (
                        "format",
                        "sample_rate",
                        "language_type",
                        "parameters",
                        "extra_input",
                    )
                },
            ),
            headers=headers,
            timeout=kwargs.pop("timeout", None),
            sdk_module=MODULE,
            api_key=kwargs.pop("api_key", None),
            workspace=kwargs.pop("workspace", None),
            options=request_options(
                kwargs.pop("extra_headers", None),
                kwargs.pop("extra_query", None),
                kwargs.pop("extra_body", None),
                max_retries=kwargs.pop("max_retries", None),
            ),
        )
    except APIStatusError as error:
        _with_audio_request_id(error)
        _log_audio_error(error)
        raise

    async def events():
        decoder = _SSEDecoder()
        header_id = response.headers.get("x-request-id", "")
        request_id = request_id_from_headers(response.headers)
        try:
            media_type = response.headers.get("content-type", "")
            media_type = media_type.split(";", 1)[0].strip().lower()
            if media_type == "application/json" or media_type.endswith(
                "+json",
            ):
                # A 200 JSON envelope is a service failure, not audio
                # SSE; mirror _iter_audio_sse so the error surfaces
                # instead of yielding zero chunks silently.
                await response.aread()
                response_body(response)
                return
            async for line in response.aiter_lines():
                frame = decoder.feed(line)
                if frame is None:
                    continue
                is_error, status, data = frame
                request_id = (
                    _audio_body_request_id(_try_json(data)) or request_id
                )
                if is_error:
                    raise _audio_stream_error(
                        status,
                        data,
                        response.headers,
                    )
                yield _parse_stream_chunk(
                    data,
                    header_id,
                    request_id,
                    strict=self._client.config.strict_validation,
                    response=response,
                )
            frame = decoder.feed("")
            if frame is not None:
                is_error, status, data = frame
                request_id = (
                    _audio_body_request_id(_try_json(data)) or request_id
                )
                if is_error:
                    raise _audio_stream_error(
                        status,
                        data,
                        response.headers,
                    )
                yield _parse_stream_chunk(
                    data,
                    header_id,
                    request_id,
                    strict=self._client.config.strict_validation,
                    response=response,
                )
        except Exception as error:
            if isinstance(error, DashScopeError):
                _with_audio_request_id(error)
            _log_audio_error(error, request_id, response.headers)
            raise
        finally:
            await response.aclose()

    return AsyncHttpSynthesisStream(events(), response)

HttpSynthesis

Bases: ResponseBase

Non-streaming result: a URL reference to the rendered audio.

output class-attribute instance-attribute

output: Dict[str, Any] = {}

usage class-attribute instance-attribute

usage: Optional[Dict[str, Any]] = None

request_id class-attribute instance-attribute

request_id: str = ''

audio_url property

audio_url: Optional[str]

Temporary URL of the rendered audio.

audio_id property

audio_id: Optional[str]

expires_at property

expires_at: Optional[int]

Expiry timestamp of :attr:audio_url.

HttpSynthesisChunk

Bases: ResponseBase

One SSE part of a streaming synthesis.

output class-attribute instance-attribute

output: Dict[str, Any] = {}

audio class-attribute instance-attribute

audio: Optional[bytes] = None

usage class-attribute instance-attribute

usage: Optional[Dict[str, Any]] = None

request_id class-attribute instance-attribute

request_id: str = ''

sentence property

sentence: Optional[Dict[str, Any]]

Sentence metadata of cosyvoice sentence-* parts.

finish_reason property

finish_reason: Optional[str]

is_final property

is_final: bool

True on the closing part (finish_reason == "stop").

audio_url property

audio_url: Optional[str]

Temporary URL of the whole audio; final part only.

audio_id property

audio_id: Optional[str]

expires_at property

expires_at: Optional[int]

HttpSynthesisStream

HttpSynthesisStream(
    inner: Generator[HttpSynthesisChunk, None, None],
    response: Any,
)

Typed iterator over streaming synthesis parts, mirroring AppStream.

Source code in dashscope/resources/audio/http_tts.py
428
429
430
431
432
433
434
def __init__(
    self,
    inner: Generator[HttpSynthesisChunk, None, None],
    response: Any,
) -> None:
    self._inner = inner
    self._response = response

headers property

headers: Dict[str, str]

Raw HTTP response headers of the stream's envelope.

close

close() -> None
Source code in dashscope/resources/audio/http_tts.py
447
448
449
450
451
def close(self) -> None:
    try:
        self._inner.close()
    finally:
        self._response.close()

AsyncHttpSynthesisStream

AsyncHttpSynthesisStream(
    inner: AsyncIterator[HttpSynthesisChunk], response
)

Async typed iterator over HTTP synthesis SSE parts.

Source code in dashscope/resources/audio/http_tts.py
457
458
459
460
461
462
463
def __init__(
    self,
    inner: AsyncIterator[HttpSynthesisChunk],
    response,
) -> None:
    self._inner = inner
    self._response = response

headers property

headers: Dict[str, str]

aclose async

aclose() -> None
Source code in dashscope/resources/audio/http_tts.py
472
473
async def aclose(self) -> None:
    await self._response.aclose()

语音识别(ASR)

Asr

Asr(client)

client.audio.asr: batch transcription + realtime recognition.

Source code in dashscope/resources/audio/asr.py
771
772
773
def __init__(self, client) -> None:
    self._client = client
    self.jobs = TranscriptionJobs(client)

jobs instance-attribute

jobs = TranscriptionJobs(client)

transcribe

transcribe(
    file_urls: List[str],
    *,
    model: str = "qwen-audio-3.1-asr-flash-filetrans",
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: float = DEFAULT_WAIT_TIMEOUT,
    submit_timeout: Optional[float] = None,
    poll_interval: float = DEFAULT_POLL_INTERVAL,
    max_interval: float = DEFAULT_MAX_INTERVAL,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None
) -> Job

Submit and wait; output.results carries per-file transcripts.

timeout is the wait budget — the same timeout as jobs.wait. submit_timeout caps only the submit request.

Source code in dashscope/resources/audio/asr.py
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
def transcribe(
    self,
    file_urls: List[str],
    *,
    model: str = "qwen-audio-3.1-asr-flash-filetrans",
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: float = DEFAULT_WAIT_TIMEOUT,
    submit_timeout: Optional[float] = None,
    poll_interval: float = DEFAULT_POLL_INTERVAL,
    max_interval: float = DEFAULT_MAX_INTERVAL,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
) -> Job:
    """Submit and wait; output.results carries per-file transcripts.

    ``timeout`` is the wait budget — the same ``timeout`` as
    ``jobs.wait``. ``submit_timeout`` caps only the submit request.
    """
    job = self.jobs.create(
        model=model,
        file_urls=file_urls,
        parameters=parameters,
        phrase_id=phrase_id,
        timeout=submit_timeout,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    return self.jobs.wait(
        job,
        poll_interval=poll_interval,
        max_interval=max_interval,
        timeout=timeout,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )

recognize

recognize(
    *,
    model: str,
    format: str = "pcm",
    sample_rate: int = 16000,
    vocabulary_id: Optional[str] = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    input: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    connection: Optional[WsConnection] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
) -> Recognition

Open recognition; send audio and consume events concurrently.

With connection= the session runs as one task on the shared socket (binary uplink is single-owner per connection, so one active recognition per connection).

Source code in dashscope/resources/audio/asr.py
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
def recognize(
    self,
    *,
    model: str,
    format: str = "pcm",
    sample_rate: int = 16000,
    vocabulary_id: Optional[str] = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    input: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    connection: Optional[WsConnection] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> Recognition:
    """Open recognition; send audio and consume events concurrently.

    With ``connection=`` the session runs as one task on the shared
    socket (binary uplink is single-owner per connection, so one
    active recognition per connection).
    """
    return Recognition(
        self._client,
        model=model,
        format=format,
        sample_rate=sample_rate,
        vocabulary_id=vocabulary_id,
        disfluency_removal_enabled=disfluency_removal_enabled,
        diarization_enabled=diarization_enabled,
        parameters=parameters,
        input=input,
        phrase_id=phrase_id,
        ws_url=ws_url,
        connector=connector,
        connection=connection,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
    )

recognize_file

recognize_file(
    path: str,
    *,
    model: str,
    format: str = "pcm",
    sample_rate: int = 16000,
    vocabulary_id: Optional[str] = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
) -> Iterator[Dict[str, Any]]

Recognize a local audio file, yielding the same events as Recognition.events().

The file is auto-chunked and driven to completion in one session, the 1.x Recognition.call(file) equivalent. Validation happens eagerly; the session itself opens on first iteration.

Source code in dashscope/resources/audio/asr.py
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
def recognize_file(
    self,
    path: str,
    *,
    model: str,
    format: str = "pcm",  # pylint: disable=redefined-builtin
    sample_rate: int = 16000,
    vocabulary_id: Optional[str] = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> Iterator[Dict[str, Any]]:
    """Recognize a local audio file, yielding the same events as
    ``Recognition.events()``.

    The file is auto-chunked and driven to completion in one session,
    the 1.x ``Recognition.call(file)`` equivalent. Validation happens
    eagerly; the session itself opens on first iteration.
    """
    if not os.path.isfile(path):
        raise ValueError(f"audio file not found: {path}")
    if os.path.getsize(path) == 0:
        raise ValueError(f"audio file is empty: {path}")
    recognition = self.recognize(
        model=model,
        format=format,
        sample_rate=sample_rate,
        vocabulary_id=vocabulary_id,
        disfluency_removal_enabled=disfluency_removal_enabled,
        diarization_enabled=diarization_enabled,
        parameters=parameters,
        ws_url=ws_url,
        connector=connector,
        timeout=timeout,
        api_key=api_key,
        workspace=workspace,
    )
    return _stream_file_frames(recognition, path)

AsyncAsr

AsyncAsr(client)

Async client.audio.asr.

Realtime recognize sessions stay sync-only (design doc M3 3.5).

Source code in dashscope/resources/audio/asr.py
921
922
def __init__(self, client) -> None:
    self.jobs = AsyncTranscriptionJobs(client)

jobs instance-attribute

jobs = AsyncTranscriptionJobs(client)

transcribe async

transcribe(
    file_urls: List[str],
    *,
    model: str = "qwen-audio-3.1-asr-flash-filetrans",
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: float = DEFAULT_WAIT_TIMEOUT,
    submit_timeout: Optional[float] = None,
    poll_interval: float = DEFAULT_POLL_INTERVAL,
    max_interval: float = DEFAULT_MAX_INTERVAL,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None
) -> Job

Submit and wait; output.results carries per-file transcripts.

timeout is the wait budget — the same timeout as jobs.wait. submit_timeout caps only the submit request.

Source code in dashscope/resources/audio/asr.py
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
async def transcribe(
    self,
    file_urls: List[str],
    *,
    model: str = "qwen-audio-3.1-asr-flash-filetrans",
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: float = DEFAULT_WAIT_TIMEOUT,
    submit_timeout: Optional[float] = None,
    poll_interval: float = DEFAULT_POLL_INTERVAL,
    max_interval: float = DEFAULT_MAX_INTERVAL,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
) -> Job:
    """Submit and wait; output.results carries per-file transcripts.

    ``timeout`` is the wait budget — the same ``timeout`` as
    ``jobs.wait``. ``submit_timeout`` caps only the submit request.
    """
    job = await self.jobs.create(
        model=model,
        file_urls=file_urls,
        parameters=parameters,
        phrase_id=phrase_id,
        timeout=submit_timeout,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    return await self.jobs.wait(
        job,
        poll_interval=poll_interval,
        max_interval=max_interval,
        timeout=timeout,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )

Recognition

Recognition(
    client,
    *,
    model: str,
    format: str = "pcm",
    sample_rate: int = 16000,
    vocabulary_id: Optional[str] = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    input: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    connection: Optional[WsConnection] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
)

Duplex recognition; consume events on one thread while sending audio.

Source code in dashscope/resources/audio/asr.py
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
def __init__(
    self,
    client,
    *,
    model: str,
    format: str = "pcm",
    sample_rate: int = 16000,
    vocabulary_id: Optional[str] = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    parameters: Optional[Dict[str, Any]] = None,
    input: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    connection: Optional[WsConnection] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> None:
    config = client.config
    # Kept as the live config, not a snapshot of one flag: every other
    # resource reads ``strict_validation`` at parse time, and a session
    # can outlive the setting it was opened with.
    self._config = config
    self._model = model
    merged = {"format": format, "sample_rate": sample_rate}
    if parameters:
        merged.update(parameters)
    # Named kwargs win over the ``parameters=`` escape hatch; the keys
    # match the 1.x Recognition wire names.
    if vocabulary_id is not None:
        merged["vocabulary_id"] = vocabulary_id
    if disfluency_removal_enabled is not None:
        merged["disfluency_removal_enabled"] = disfluency_removal_enabled
    if diarization_enabled is not None:
        merged["diarization_enabled"] = diarization_enabled
    self._parameters = merged
    self._input = dict(input or {})
    # Phrases ride as top-level ``resources`` on the run-task payload
    # (verified against the service), not inside ``parameters``.
    self._resources = _phrase_resources(phrase_id)
    # A shared connection runs this recognition as one task on it;
    # ws_url/connector/api_key/workspace/headers then belong to the
    # connection and the per-session values are ignored.
    self._connection = connection
    self._session_kwargs = {
        "url": ws_url,
        "api_key": api_key or config.api_key,
        "workspace": workspace or config.workspace,
        "region": config.region,
        "connector": connector,
        "module": MODULE,
        "timeout": config.timeout if timeout is None else timeout,
        "headers": with_client_user_agent(client, headers),
    }
    self._session: Union[WsSession, WsTask, None] = None
    self.last_response: Optional[Dict[str, Any]] = None
    self.usage: Optional[Dict[str, Any]] = None
    self.first_package_delay: Optional[float] = None
    self.last_package_delay: Optional[float] = None
    self._first_sent_at: Optional[float] = None
    self._stopped_at: Optional[float] = None
    self._request_id: Optional[str] = None

last_response instance-attribute

last_response: Optional[Dict[str, Any]] = None

usage instance-attribute

usage: Optional[Dict[str, Any]] = None

first_package_delay instance-attribute

first_package_delay: Optional[float] = None

last_package_delay instance-attribute

last_package_delay: Optional[float] = None

session property

session: Union[WsSession, WsTask]

request_id property

request_id: Optional[str]

start

start() -> 'Recognition'
Source code in dashscope/resources/audio/asr.py
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
def start(self) -> "Recognition":
    if self._session is not None:
        raise RuntimeError("recognition session is already open")
    if self._connection is not None:
        self._session = self._connection.open_task(
            timeout=self._session_kwargs["timeout"],
        )
    else:
        self._session = WsSession(**self._session_kwargs)
    self.last_response = None
    self.usage = None
    self.first_package_delay = None
    self.last_package_delay = None
    self._first_sent_at = None
    self._stopped_at = None
    self._request_id = self._session.task_id
    try:
        self.last_response = self.session.run_task(
            task_group="audio",
            task="asr",
            function="recognition",
            model=self._model,
            parameters=self._parameters,
            input=self._input,
            resources=self._resources,
        )
        self._request_id = self.session.request_id
    except BaseException:
        self.close()
        raise
    return self

send_audio_frame

send_audio_frame(data: bytes) -> None
Source code in dashscope/resources/audio/asr.py
682
683
684
685
def send_audio_frame(self, data: bytes) -> None:
    if self._first_sent_at is None:
        self._first_sent_at = time.monotonic()
    self.session.send_binary(data)

update_context

update_context(context: Dict[str, Any]) -> None

Apply context to subsequent audio without restarting recognition.

Source code in dashscope/resources/audio/asr.py
687
688
689
690
691
def update_context(self, context: Dict[str, Any]) -> None:
    """Apply context to subsequent audio without restarting recognition."""
    if not isinstance(context, dict):
        raise TypeError("context must be a dict")
    self.session.continue_task(context)

stop

stop() -> None

End input; keep reading events through task-finished.

Source code in dashscope/resources/audio/asr.py
693
694
695
696
697
def stop(self) -> None:
    """End input; keep reading events through task-finished."""
    if self._stopped_at is None:
        self._stopped_at = time.monotonic()
    self.session.finish_task()

events

events() -> Iterator[Dict[str, Any]]
Source code in dashscope/resources/audio/asr.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
def events(self) -> Iterator[Dict[str, Any]]:
    session = self.session
    while not session.finished:
        event = session.recv_event()
        self.last_response = event
        self._request_id = session.request_id
        payload = event.get("payload")
        if not isinstance(payload, dict):
            payload = {}
        if payload.get("usage") is not None:
            self.usage = payload["usage"]
        # Metrics are best-effort: a frame whose ``output`` drifted to a
        # non-dict still gets yielded, it just has no sentence to time.
        output = payload.get("output")
        if not isinstance(output, dict):
            output = {}
        sentence = output.get("sentence")
        if not isinstance(sentence, dict):
            sentence = {}
        has_text = bool(
            sentence.get("text") and not sentence.get("heartbeat"),
        )
        if (
            has_text
            and self.first_package_delay is None
            and self._first_sent_at is not None
        ):
            self.first_package_delay = (
                time.monotonic() - self._first_sent_at
            ) * 1000
        if session.finished and self._stopped_at is not None:
            self.last_package_delay = (
                time.monotonic() - self._stopped_at
            ) * 1000
        yield event

close

close() -> None
Source code in dashscope/resources/audio/asr.py
735
736
737
738
739
740
def close(self) -> None:
    # With a shared connection this only detaches the task; the
    # socket belongs to the WsConnection and stays open.
    if self._session is not None:
        self._session.close()
        self._session = None

results

results() -> Iterator[RecognitionResult]

Yield typed results until the task finishes.

Non-result events (task-finished, ...) are skipped: 1.x reports them through on_complete instead of on_event. Heartbeat sentences are dropped too, as 1.x does before invoking callbacks.

Source code in dashscope/resources/audio/asr.py
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def results(self) -> Iterator[RecognitionResult]:
    """Yield typed results until the task finishes.

    Non-result events (task-finished, ...) are skipped: 1.x reports
    them through ``on_complete`` instead of ``on_event``. Heartbeat
    sentences are dropped too, as 1.x does before invoking callbacks.
    """
    for event in self.events():
        if event["header"].get("event") != EVENT_GENERATED:
            continue
        payload = event.get("payload")
        data = dict(payload) if isinstance(payload, dict) else {}
        data.setdefault("request_id", event["header"].get("request_id"))
        # No ``response``: this frame arrived over a websocket, so there
        # is no httpx.Response for a strict failure to carry.
        result = parse_model(
            RecognitionResult,
            data,
            strict=self._config.strict_validation,
        )
        sentence = result.get_sentence()
        if sentence and sentence.get("heartbeat"):
            continue
        yield result

TranscriptionJobs

TranscriptionJobs(client)

Async task facade over the batch transcription service.

Source code in dashscope/resources/audio/asr.py
126
127
128
def __init__(self, client) -> None:
    self._client = client
    self._jobs = Jobs(client, SERVICE, MODULE)

create

create(
    *,
    model: str,
    file_urls: List[str],
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Job
create(
    *,
    model: str,
    file_urls: List[str],
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
create(
    *,
    model: str,
    file_urls: List[str],
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Job, "APIResponse"]

Submit a batch transcription task over one or more audio files.

raw=True returns the :class:~dashscope.transport.APIResponse of the underlying call before any error check.

Source code in dashscope/resources/audio/asr.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def create(
    self,
    *,
    model: str,
    file_urls: List[str],
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Job, "APIResponse"]:
    """Submit a batch transcription task over one or more audio files.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    of the underlying call before any error check.
    """
    return self._jobs.create(
        model=model,
        input=_input_for(file_urls),
        parameters={} if parameters is None else parameters,
        resources=_phrase_resources(phrase_id),
        timeout=timeout,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
        raw=raw,
    )

fetch

fetch(
    task_id: str,
    *,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Job
fetch(
    task_id: str,
    *,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
fetch(
    task_id: str,
    *,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Job, "APIResponse"]

Fetch one task snapshot.

raw=True returns the :class:~dashscope.transport.APIResponse of the underlying call before any error check.

Source code in dashscope/resources/audio/asr.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def fetch(
    self,
    task_id: str,
    *,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Job, "APIResponse"]:
    """Fetch one task snapshot.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    of the underlying call before any error check.
    """
    return self._jobs.fetch(
        task_id,
        timeout=timeout,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
        raw=raw,
    )

wait

wait(
    job: Union[Job, str],
    *,
    poll_interval: float = DEFAULT_POLL_INTERVAL,
    max_interval: float = DEFAULT_MAX_INTERVAL,
    timeout: float = DEFAULT_WAIT_TIMEOUT,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    _sleep: Optional[Callable[[float], Any]] = None
) -> Job

Poll with backoff, without starting another poll after the deadline.

Source code in dashscope/resources/audio/asr.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def wait(
    self,
    job: Union[Job, str],
    *,
    poll_interval: float = DEFAULT_POLL_INTERVAL,
    max_interval: float = DEFAULT_MAX_INTERVAL,
    timeout: float = DEFAULT_WAIT_TIMEOUT,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    _sleep: Optional[Callable[[float], Any]] = None,
) -> Job:
    """Poll with backoff, without starting another poll after the deadline."""
    task_id = job.task_id if isinstance(job, Job) else job
    sleep_fn = _sleep or time.sleep
    deadline = time.monotonic() + timeout
    current = (
        job
        if isinstance(job, Job)
        else self.fetch(
            task_id,
            api_key=api_key,
            workspace=workspace,
            extra_headers=extra_headers,
            extra_query=extra_query,
            extra_body=extra_body,
            max_retries=max_retries,
        )
    )
    interval = poll_interval
    while not current.finished:
        # Compat-mode error envelopes have no terminal task status.
        if current.is_error:
            return current
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise DashScopeError(
                f"timed out after {timeout}s waiting for task {task_id}",
            )
        sleep_fn(min(interval, remaining))
        if time.monotonic() >= deadline:
            raise DashScopeError(
                f"timed out after {timeout}s waiting for task {task_id}",
            )
        interval = min(interval * 2, max_interval)
        current = self.fetch(
            task_id,
            api_key=api_key,
            workspace=workspace,
            extra_headers=extra_headers,
            extra_query=extra_query,
            extra_body=extra_body,
            max_retries=max_retries,
        )
    return _check_terminal(
        current,
        raise_on_error=self._client.raise_on_error,
    )

AsyncTranscriptionJobs

AsyncTranscriptionJobs(client)
Source code in dashscope/resources/audio/asr.py
330
331
332
def __init__(self, client) -> None:
    self._client = client
    self._jobs = AsyncJobs(client, SERVICE, MODULE)

create async

create(
    *,
    model: str,
    file_urls: List[str],
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Job
create(
    *,
    model: str,
    file_urls: List[str],
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
create(
    *,
    model: str,
    file_urls: List[str],
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Job, "APIResponse"]

Submit a batch transcription task over one or more audio files.

raw=True returns the :class:~dashscope.transport.APIResponse of the underlying call before any error check.

Source code in dashscope/resources/audio/asr.py
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
async def create(
    self,
    *,
    model: str,
    file_urls: List[str],
    parameters: Optional[Dict[str, Any]] = None,
    phrase_id: Optional[str] = None,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Job, "APIResponse"]:
    """Submit a batch transcription task over one or more audio files.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    of the underlying call before any error check.
    """
    return await self._jobs.create(
        model=model,
        input=_input_for(file_urls),
        parameters={} if parameters is None else parameters,
        resources=_phrase_resources(phrase_id),
        timeout=timeout,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
        raw=raw,
    )

fetch async

fetch(
    task_id: str,
    *,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Job
fetch(
    task_id: str,
    *,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
fetch(
    task_id: str,
    *,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Job, "APIResponse"]

Fetch one task snapshot.

raw=True returns the :class:~dashscope.transport.APIResponse of the underlying call before any error check.

Source code in dashscope/resources/audio/asr.py
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
async def fetch(
    self,
    task_id: str,
    *,
    timeout: Optional[float] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Job, "APIResponse"]:
    """Fetch one task snapshot.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    of the underlying call before any error check.
    """
    return await self._jobs.fetch(
        task_id,
        timeout=timeout,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
        raw=raw,
    )

wait async

wait(
    job: Union[Job, str],
    *,
    poll_interval: float = DEFAULT_POLL_INTERVAL,
    max_interval: float = DEFAULT_MAX_INTERVAL,
    timeout: float = DEFAULT_WAIT_TIMEOUT,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    _sleep: Optional[
        Callable[[float], Awaitable[None]]
    ] = None
) -> Job

Async twin of :meth:TranscriptionJobs.wait.

Source code in dashscope/resources/audio/asr.py
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
async def wait(
    self,
    job: Union[Job, str],
    *,
    poll_interval: float = DEFAULT_POLL_INTERVAL,
    max_interval: float = DEFAULT_MAX_INTERVAL,
    timeout: float = DEFAULT_WAIT_TIMEOUT,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    _sleep: Optional[Callable[[float], Awaitable[None]]] = None,
) -> Job:
    """Async twin of :meth:`TranscriptionJobs.wait`."""
    task_id = job.task_id if isinstance(job, Job) else job
    sleep_fn = _sleep or asyncio.sleep
    deadline = time.monotonic() + timeout
    current = (
        job
        if isinstance(job, Job)
        else await self.fetch(
            task_id,
            api_key=api_key,
            workspace=workspace,
            extra_headers=extra_headers,
            extra_query=extra_query,
            extra_body=extra_body,
            max_retries=max_retries,
        )
    )
    interval = poll_interval
    while not current.finished:
        # Compat-mode error envelopes have no terminal task status.
        if current.is_error:
            return current
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            raise DashScopeError(
                f"timed out after {timeout}s waiting for task {task_id}",
            )
        await sleep_fn(min(interval, remaining))
        if time.monotonic() >= deadline:
            raise DashScopeError(
                f"timed out after {timeout}s waiting for task {task_id}",
            )
        interval = min(interval * 2, max_interval)
        current = await self.fetch(
            task_id,
            api_key=api_key,
            workspace=workspace,
            extra_headers=extra_headers,
            extra_query=extra_query,
            extra_body=extra_body,
            max_retries=max_retries,
        )
    return _check_terminal(
        current,
        raise_on_error=self._client.raise_on_error,
    )

RecognitionResult

Bases: BaseModel

Typed view over one result-generated event payload.

Recognition.events() keeps yielding raw dicts; this model adds the 1.x RecognitionResult accessors (recognition.py:99-125) for callers that want them. Unknown payload fields stay readable as attributes (extra="allow").

output class-attribute instance-attribute

output: Dict[str, Any] = Field(default_factory=dict)

usage class-attribute instance-attribute

usage: Optional[Dict[str, Any]] = None

request_id class-attribute instance-attribute

request_id: Optional[str] = None

get_sentence

get_sentence() -> Optional[Dict[str, Any]]

The sentence dict of this result, or None.

Source code in dashscope/resources/audio/asr.py
548
549
550
551
552
def get_sentence(self) -> Optional[Dict[str, Any]]:
    """The sentence dict of this result, or None."""
    if self.output and "sentence" in self.output:
        return self.output["sentence"]
    return None

is_sentence_end

is_sentence_end() -> bool

True when the sentence carries its end marker (end_time).

Source code in dashscope/resources/audio/asr.py
554
555
556
557
def is_sentence_end(self) -> bool:
    """True when the sentence carries its end marker (``end_time``)."""
    sentence = self.get_sentence()
    return sentence is not None and sentence.get("end_time") is not None

get_usage

get_usage() -> Optional[Dict[str, Any]]
Source code in dashscope/resources/audio/asr.py
559
560
561
562
def get_usage(self) -> Optional[Dict[str, Any]]:
    # 1.x joins a usages list by the sentence's end_time; v2 events
    # carry usage on the payload itself, so it comes back directly.
    return self.usage

实时与 Qwen Live

client.audio.live 的完整接入流程参见 Qwen Live 指南。

Realtime

Realtime(client)

client.audio.realtime: Omni, Qwen-Audio and Livetranslate.

Source code in dashscope/resources/audio/realtime.py
886
887
def __init__(self, client) -> None:
    self._client = client

connect

connect(
    *,
    model: str,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
) -> RealtimeSession

Create a session; enter its context or call session.connect().

Source code in dashscope/resources/audio/realtime.py
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
def connect(
    self,
    *,
    model: str,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> RealtimeSession:
    """Create a session; enter its context or call session.connect()."""
    return RealtimeSession(
        self._client,
        model=model,
        ws_url=ws_url,
        connector=connector,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
    )

RealtimeSession

RealtimeSession(
    client,
    *,
    model: str,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
)

Bases: WsSessionBase

One realtime websocket session (context manager).

Usage::

with client.audio.realtime.connect(
    model="qwen3.8-omni-flash-realtime",
) as rt:
    rt.send_event({"type": "session.update", "session": {...}})
    for event in rt.events():
        ...

Unlike the run-task family (asr/tts/tingwu), the realtime protocol has no task id: one socket IS one session and the server closes it when the session ends, so connection reuse does not apply here -- every session opens its own socket (see WsConnection for the multiplexable family). Latency-sensitive callers can shave the handshake by connecting ahead of use rather than by pooling.

Source code in dashscope/resources/audio/realtime.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def __init__(
    self,
    client,
    *,
    model: str,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> None:
    super().__init__(
        client,
        model=model,
        ws_url=ws_url,
        connector=connector,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
    )
    wire_model = self._wire_model
    if wire_model.startswith("qwen3.8-omni-"):
        self._protocol = "omni_v38"
    elif wire_model.startswith("qwen-audio-"):
        self._protocol = "qwen_audio"
    elif wire_model.startswith("qwen3.8-livetranslate-"):
        self._protocol = "livetranslate_v38"
    elif wire_model.startswith(
        ("qwen3-livetranslate-", "qwen3.5-livetranslate-"),
    ):
        self._protocol = "livetranslate"
    else:
        self._protocol = "omni"

connect

connect() -> 'RealtimeSession'

Open the connection, either explicitly or on context entry.

Source code in dashscope/resources/audio/realtime.py
127
128
129
130
131
132
133
134
135
136
def connect(self) -> "RealtimeSession":
    """Open the connection, either explicitly or on context entry."""
    from websocket import (  # pylint: disable=import-outside-toplevel
        WebSocketTimeoutException,
    )

    try:
        return super().connect()
    except WebSocketTimeoutException as exc:
        raise APITimeoutError(detail=str(exc)) from exc

send_event

send_event(event: Dict[str, Any]) -> None

Send a raw event, assigning an event_id unless one is supplied.

Source code in dashscope/resources/audio/realtime.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
def send_event(self, event: Dict[str, Any]) -> None:
    """Send a raw event, assigning an event_id unless one is supplied."""
    with self._send_lock:
        with self._lock:
            ws, generation = self._ws, self._generation
            if ws is None:
                raise RuntimeError("realtime session is not open")
            if self._finish_requested:
                if event.get("type") == "session.finish":
                    return
                raise RuntimeError("realtime session is finishing")
            payload = dict(event)
            payload.setdefault("event_id", "event_" + uuid.uuid4().hex)
            raw = json.dumps(payload)
            if payload.get("type") == "session.finish":
                self._finish_requested = True
            if payload.get("type") == "response.create":
                # Register before I/O: a response may arrive before send returns.
                self._pending_response_ids.append(payload["event_id"])
        try:
            self._send_raw(ws, raw)
        except BaseException as exc:
            closing_ws = None
            with self._lock:
                if ws is self._ws and generation == self._generation:
                    _logger.error(
                        "Realtime send failed: %s, request_id=%s",
                        type(exc).__name__,
                        self._request_id_for_log(),
                    )
                    if payload.get("type") == "response.create" and (
                        payload["event_id"] in self._pending_response_ids
                    ):
                        self._pending_response_ids.remove(
                            payload["event_id"],
                        )
                    closing_ws = self._detach_socket()
            self._close_socket(closing_ws)
            raise

update_session

update_session(
    output_modalities: List[str] = cast(List[str], _UNSET),
    *,
    voice: Optional[str] = cast(Optional[str], _UNSET),
    input_audio_format: str = cast(str, _UNSET),
    output_audio_format: str = cast(str, _UNSET),
    enable_input_audio_transcription: bool = cast(
        bool, _UNSET
    ),
    input_audio_transcription_model: Optional[str] = cast(
        Optional[str], _UNSET
    ),
    enable_turn_detection: bool = cast(bool, _UNSET),
    turn_detection_type: str = cast(str, _UNSET),
    prefix_padding_ms: int = cast(int, _UNSET),
    turn_detection_threshold: float = cast(float, _UNSET),
    turn_detection_silence_duration_ms: int = cast(
        int, _UNSET
    ),
    turn_detection_param: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]], _UNSET
    ),
    translation_params: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]], _UNSET
    ),
    transcription_params: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]], _UNSET
    ),
    input_audio_config: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]], _UNSET
    ),
    output_audio_config: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]], _UNSET
    ),
    input_video_representation_compact: Optional[
        str
    ] = cast(Optional[str], _UNSET),
    **kwargs: Any
) -> None

Patch modern sessions; pre-3.8 Omni retains its legacy defaults.

**kwargs is the protocol-evolution escape hatch: extra keys merge into the wire session object after the named helpers, so on key overlap the kwargs value wins and falsey values are preserved as sent.

Source code in dashscope/resources/audio/realtime.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
def update_session(
    self,
    output_modalities: List[str] = cast(List[str], _UNSET),
    *,
    voice: Optional[str] = cast(Optional[str], _UNSET),
    input_audio_format: str = cast(str, _UNSET),
    output_audio_format: str = cast(str, _UNSET),
    enable_input_audio_transcription: bool = cast(bool, _UNSET),
    input_audio_transcription_model: Optional[str] = cast(
        Optional[str],
        _UNSET,
    ),
    enable_turn_detection: bool = cast(bool, _UNSET),
    turn_detection_type: str = cast(str, _UNSET),
    prefix_padding_ms: int = cast(int, _UNSET),
    turn_detection_threshold: float = cast(float, _UNSET),
    turn_detection_silence_duration_ms: int = cast(int, _UNSET),
    turn_detection_param: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]],
        _UNSET,
    ),
    translation_params: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]],
        _UNSET,
    ),
    transcription_params: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]],
        _UNSET,
    ),
    input_audio_config: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]],
        _UNSET,
    ),
    output_audio_config: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]],
        _UNSET,
    ),
    input_video_representation_compact: Optional[str] = cast(
        Optional[str],
        _UNSET,
    ),
    **kwargs: Any,
) -> None:
    """Patch modern sessions; pre-3.8 Omni retains its legacy defaults.

    ``**kwargs`` is the protocol-evolution escape hatch: extra keys
    merge into the wire ``session`` object after the named helpers,
    so on key overlap the kwargs value wins and falsey values are
    preserved as sent.
    """
    options = {
        key: value
        for key, value in {
            "output_modalities": output_modalities,
            "voice": voice,
            "input_audio_format": input_audio_format,
            "output_audio_format": output_audio_format,
            "enable_input_audio_transcription": (
                enable_input_audio_transcription
            ),
            "input_audio_transcription_model": (
                input_audio_transcription_model
            ),
            "enable_turn_detection": enable_turn_detection,
            "turn_detection_type": turn_detection_type,
            "prefix_padding_ms": prefix_padding_ms,
            "turn_detection_threshold": turn_detection_threshold,
            "turn_detection_silence_duration_ms": (
                turn_detection_silence_duration_ms
            ),
            "turn_detection_param": turn_detection_param,
            "translation_params": translation_params,
            "transcription_params": transcription_params,
            "input_audio_config": input_audio_config,
            "output_audio_config": output_audio_config,
            "input_video_representation_compact": (
                input_video_representation_compact
            ),
        }.items()
        if value is not _UNSET
    }
    if self._protocol == "omni":
        session = self._omni_session(**options, **kwargs)
    else:
        session = self._incremental_session(options, kwargs)
    self.send_event({"type": "session.update", "session": session})

append_audio

append_audio(audio_b64: Union[str, bytes]) -> None

Append base64 audio, or encode raw bytes before appending.

Source code in dashscope/resources/audio/realtime.py
554
555
556
557
558
559
560
561
def append_audio(self, audio_b64: Union[str, bytes]) -> None:
    """Append base64 audio, or encode raw bytes before appending."""
    self.send_event(
        {
            "type": "input_audio_buffer.append",
            "audio": _as_base64(audio_b64),
        },
    )

append_video

append_video(video_b64: Union[str, bytes]) -> None

Append a base64 image frame, or encode raw image bytes.

Source code in dashscope/resources/audio/realtime.py
563
564
565
566
567
568
569
570
def append_video(self, video_b64: Union[str, bytes]) -> None:
    """Append a base64 image frame, or encode raw image bytes."""
    self.send_event(
        {
            "type": "input_image_buffer.append",
            "image": _as_base64(video_b64),
        },
    )

commit

commit() -> None

Commit the appended audio and video.

Source code in dashscope/resources/audio/realtime.py
572
573
574
def commit(self) -> None:
    """Commit the appended audio and video."""
    self.send_event({"type": "input_audio_buffer.commit"})

clear_appended_audio

clear_appended_audio() -> None
Source code in dashscope/resources/audio/realtime.py
576
577
def clear_appended_audio(self) -> None:
    self.send_event({"type": "input_audio_buffer.clear"})

create_item

create_item(
    item: Dict[str, Any],
    *,
    previous_item_id: Optional[str] = None
) -> None
Source code in dashscope/resources/audio/realtime.py
579
580
581
582
583
584
585
586
587
588
def create_item(
    self,
    item: Dict[str, Any],
    *,
    previous_item_id: Optional[str] = None,
) -> None:
    event = {"type": "conversation.item.create", "item": item}
    if previous_item_id is not None:
        event["previous_item_id"] = previous_item_id
    self.send_event(event)

retrieve_item

retrieve_item(item_id: str) -> None
Source code in dashscope/resources/audio/realtime.py
590
591
592
593
594
595
596
def retrieve_item(self, item_id: str) -> None:
    self.send_event(
        {
            "type": "conversation.item.retrieve",
            "item_id": item_id,
        },
    )

delete_item

delete_item(item_id: str) -> None
Source code in dashscope/resources/audio/realtime.py
598
599
600
601
602
603
604
def delete_item(self, item_id: str) -> None:
    self.send_event(
        {
            "type": "conversation.item.delete",
            "item_id": item_id,
        },
    )

create_response

create_response(
    modalities: Optional[List[str]] = cast(
        Optional[List[str]], _UNSET
    ),
    instructions: Optional[str] = cast(
        Optional[str], _UNSET
    ),
    **kwargs: Any
) -> None

Send response.create.

**kwargs merges extra keys into the wire response object (e.g. temperature), applied after modalities/ instructions and preserved verbatim, including falsey values.

Source code in dashscope/resources/audio/realtime.py
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
def create_response(
    self,
    modalities: Optional[List[str]] = cast(Optional[List[str]], _UNSET),
    instructions: Optional[str] = cast(Optional[str], _UNSET),
    **kwargs: Any,
) -> None:
    """Send ``response.create``.

    ``**kwargs`` merges extra keys into the wire ``response`` object
    (e.g. ``temperature``), applied after ``modalities``/
    ``instructions`` and preserved verbatim, including falsey values.
    """
    response: Dict[str, Any] = {}
    if instructions is not _UNSET:
        response["instructions"] = instructions
    elif self._protocol == "omni":
        response["instructions"] = None
    if modalities is not _UNSET and (
        modalities is not None or self._protocol != "omni"
    ):
        response["modalities"] = modalities
    response.update(kwargs)
    event: Dict[str, Any] = {"type": "response.create"}
    if response or self._protocol != "omni_v38":
        event["response"] = response
    self.send_event(event)

cancel_response

cancel_response() -> None
Source code in dashscope/resources/audio/realtime.py
633
634
def cancel_response(self) -> None:
    self.send_event({"type": "response.cancel"})

end_session

end_session() -> None

Request finish for Omni/Live; Qwen-Audio must drain then close().

Source code in dashscope/resources/audio/realtime.py
636
637
638
639
640
641
642
643
def end_session(self) -> None:
    """Request finish for Omni/Live; Qwen-Audio must drain then close()."""
    if self._protocol == "qwen_audio":
        raise NotImplementedError(
            "Qwen-Audio does not define session.finish; "
            "read through response.done, then call close()",
        )
    self.send_event({"type": "session.finish"})

recv_event

recv_event() -> Optional[Dict[str, Any]]

Receive a raw event; unfinished responses cannot end silently.

Source code in dashscope/resources/audio/realtime.py
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def recv_event(self) -> Optional[Dict[str, Any]]:
    """Receive a raw event; unfinished responses cannot end silently."""
    from websocket import (  # pylint: disable=import-outside-toplevel
        WebSocketConnectionClosedException,
        WebSocketTimeoutException,
    )

    # Network reads must not hold the lock needed by send_event() or close().
    with self._recv_lock:
        with self._lock:
            ws, generation = self._ws, self._generation
            if ws is None:
                self._check_unfinished()
                if self._closed:
                    return None
                raise RuntimeError("realtime session is not open")
        failure = None
        closing_ws = None
        received_on_current_connection = False
        try:
            try:
                raw = self._recv_raw(ws, generation)
            except WebSocketConnectionClosedException:
                raw = None
            except WebSocketTimeoutException as exc:
                raise APITimeoutError(detail=str(exc)) from exc
            with self._lock:
                if generation != self._generation:
                    return None
                if ws is not self._ws:
                    self._check_unfinished()
                    return None
                received_on_current_connection = True
                try:
                    if raw is None or raw == "" or raw == b"":
                        closing_ws = self._detach_socket()
                        self._check_unfinished()
                        _logger.debug(
                            "Realtime connection closed, request_id=%s",
                            self._request_id_for_log(),
                        )
                        return None
                    if isinstance(raw, (bytes, bytearray)):
                        raw = raw.decode("utf-8")
                    event = json.loads(raw)
                    if not isinstance(event, dict):
                        raise ValueError("expected a JSON event object")
                    self.last_message = event
                    self._track_event(event)
                    if event.get("type") == "session.finished":
                        self._finished = True
                        closing_ws = self._detach_socket()
                        self._check_unfinished()
                    elif event.get("type") == "error":
                        error = event.get("error")
                        if error is None:
                            error = {}
                        if not isinstance(error, dict):
                            raise ValueError(
                                "expected a JSON error object",
                            )
                        code = error.get("code")
                        if code is not None and not isinstance(code, str):
                            raise ValueError(
                                "expected a string error code",
                            )
                        failure = error_from_business_code(
                            message=error.get("message")
                            or "realtime error",
                            code=code,
                            body=event,
                        )
                        # Only real IDs belong on exceptions; protocol fallbacks
                        # and "unknown" are strictly logging context.
                        explicit_request_id = _event_request_id(event)
                        if explicit_request_id is not None:
                            failure.request_id = explicit_request_id
                        _logger.error(
                            "Realtime business error, request_id=%s",
                            self._request_id_for_log(),
                        )
                        recoverable = (
                            error.get("type") == "invalid_request_error"
                        )
                        if recoverable:
                            # The nested event_id identifies the rejected request.
                            request_id = error.get("event_id")
                            if (
                                isinstance(request_id, str)
                                and request_id
                                in self._pending_response_ids
                            ):
                                self._pending_response_ids.remove(
                                    request_id,
                                )
                        if not recoverable or self._finish_requested:
                            closing_ws = self._detach_socket()
                except BaseException:
                    # Detach within the same state-lock hold so a concurrent
                    # send observes the closed session instead of racing the
                    # cleanup into _send_raw (lock inversion).
                    if ws is self._ws and generation == self._generation:
                        closing_ws = self._detach_socket()
                    raise
        except BaseException as exc:
            with self._lock:
                if generation == self._generation and (
                    ws is self._ws or received_on_current_connection
                ):
                    _logger.error(
                        "Realtime receive failed: %s, request_id=%s",
                        type(exc).__name__,
                        self._request_id_for_log(),
                    )
                if ws is self._ws and generation == self._generation:
                    closing_ws = self._detach_socket()
            raise
        finally:
            self._close_socket(closing_ws)
        # Malformed errors require cleanup; parsed request errors may recover.
        if failure is not None:
            raise failure
        return event

events

events() -> Iterator[Dict[str, Any]]

Yield through session.finished, or until a normal close.

Source code in dashscope/resources/audio/realtime.py
872
873
874
875
876
877
878
879
880
def events(self) -> Iterator[Dict[str, Any]]:
    """Yield through session.finished, or until a normal close."""
    while True:
        event = self.recv_event()
        if event is None:
            return
        yield event
        if event.get("type") == "session.finished":
            return

Live

Live(client)

client.audio.live: Qwen-Live delegated voice sessions.

Source code in dashscope/resources/audio/live.py
711
712
def __init__(self, client) -> None:
    self._client = client

connect

connect(
    *,
    model: str,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
) -> LiveSession

Create an unopened session; model routes the URL, not the front-end model.

Source code in dashscope/resources/audio/live.py
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def connect(
    self,
    *,
    model: str,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> LiveSession:
    """Create an unopened session; model routes the URL, not the front-end model."""
    return LiveSession(
        self._client,
        model=model,
        ws_url=ws_url,
        connector=connector,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
    )

LiveSession

LiveSession(
    client,
    *,
    model: str,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None
)

Bases: WsSessionBase

Live session; send helpers return request IDs, not acknowledgements.

events() yields recoverable error events; recv_event() raises them while leaving the connection open. Fatal errors and unexpected disconnects raise SDK exceptions in both forms. close() cancels locally, without draining.

Source code in dashscope/resources/audio/_ws_session.py
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
def __init__(
    self,
    client,
    *,
    model: str,
    ws_url: Optional[str] = None,
    connector: Optional[Connector] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
) -> None:
    config = client.config
    if timeout is not None and timeout <= 0:
        raise ValueError("timeout must be positive")
    # Keep the derived gateway and workspace header consistent.
    space = workspace or config.workspace
    url = ws_url or workspace_ws_url(
        space,
        WS_REALTIME_PATH,
        config.region,
    )
    parts = urlsplit(url)
    query = parse_qsl(parts.query, keep_blank_values=True)
    if not any(key == "model" for key, _ in query):
        query.append(("model", model))
    url = urlunsplit(parts._replace(query=urlencode(query)))
    # Inherit the client's agent (and any surface suffix on it) so the
    # realtime socket reports the same identity as its HTTP calls; the
    # dedup below still lets an explicit per-call header win. The
    # lookup is defensive for the same reason as
    # ``transport.ws.with_client_user_agent``.
    all_headers = {
        "user-agent": (
            getattr(
                getattr(client, "transport", None),
                "user_agent",
                None,
            )
            or default_user_agent()
        ),
        **sdk_headers(MODULE),
    }
    key = api_key or config.api_key
    if key:
        all_headers["Authorization"] = f"Bearer {key}"
    if space:
        all_headers["X-DashScope-WorkSpace"] = space
    user_headers = dict(headers or {})
    user_keys = {key.lower() for key in user_headers}
    all_headers = {
        key: value
        for key, value in all_headers.items()
        if key.lower() not in user_keys
    }
    all_headers.update(user_headers)
    self._model = model
    self._wire_model = next(
        value for key, value in query if key == "model"
    )
    self._url = url
    self._headers = all_headers
    self._connector = connector
    self._timeout = config.timeout if timeout is None else timeout
    self._lock = threading.RLock()
    self._send_lock = threading.RLock()
    self._recv_lock = threading.Lock()
    self._generation = 0
    self._ws = None
    self._closing = False
    self._reset_state()

connect

connect() -> LiveSession

Open the shared transport, mapping only Live's connection errors.

Source code in dashscope/resources/audio/live.py
192
193
194
195
196
197
198
199
200
def connect(self) -> LiveSession:
    """Open the shared transport, mapping only Live's connection errors."""
    try:
        return super().connect()
    except BaseException as exc:
        error = _transport_error(exc, "connect")
        if error is exc:
            raise
        raise error from exc

send_event

send_event(event: Dict[str, Any]) -> str

Send a raw event and return its supplied or generated event_id.

Source code in dashscope/resources/audio/live.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def send_event(self, event: Dict[str, Any]) -> str:
    """Send a raw event and return its supplied or generated event_id."""
    with self._send_lock:
        with self._lock:
            ws, generation = self._ws, self._generation
            if ws is None:
                raise RuntimeError("live session is not open")
            if self._finish_requested:
                if event.get("type") == EVENT_SESSION_CLOSE:
                    assert self._finish_event_id is not None
                    return self._finish_event_id
                raise RuntimeError("live session is finishing")
            payload = dict(event)
            kind = payload.get("type")
            if not isinstance(kind, str) or not kind.strip():
                raise ValueError("event type must be a nonempty string")
            payload.setdefault("event_id", "event_" + uuid.uuid4().hex)
            event_id = payload["event_id"]
            if (
                not isinstance(event_id, str)
                or not 1 <= len(event_id) <= 128
            ):
                raise ValueError(
                    "event_id must be a string of 1 to 128 characters",
                )
            raw = json.dumps(payload)
            if payload.get("type") == EVENT_SESSION_CLOSE:
                self._finish_requested = True
                self._finish_event_id = event_id
        try:
            self._send_raw(ws, raw)
        except BaseException as exc:
            error = _transport_error(exc, "send")
            closing_ws = None
            with self._lock:
                if ws is self._ws and generation == self._generation:
                    if isinstance(error, DashScopeError):
                        self._failure = error
                    closing_ws = self._detach_socket()
            self._close_socket(closing_ws)
            if error is exc:
                raise
            raise error from exc
        return event_id

recv_event

recv_event() -> Optional[Dict[str, Any]]

Receive an event; recoverable errors raise but leave the socket open.

Source code in dashscope/resources/audio/live.py
247
248
249
def recv_event(self) -> Optional[Dict[str, Any]]:
    """Receive an event; recoverable errors raise but leave the socket open."""
    return self._recv_event(raise_request_errors=True)

events

events() -> Iterator[Dict[str, Any]]

Yield recoverable errors; fatal failures raise, never becoming EOF.

Once started, an iterator belongs to that connection. Reconnecting requires a new iterator; audio and tasks are never replayed.

Source code in dashscope/resources/audio/live.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
def events(self) -> Iterator[Dict[str, Any]]:
    """Yield recoverable errors; fatal failures raise, never becoming EOF.

    Once started, an iterator belongs to that connection. Reconnecting
    requires a new iterator; audio and tasks are never replayed.
    """
    with self._lock:
        generation = self._generation
    while True:
        event = self._recv_event(
            raise_request_errors=False,
            expected_generation=generation,
        )
        if event is None:
            return
        yield event
        if event["type"] == EVENT_SESSION_CLOSED:
            return

cancel

cancel() -> None

Immediately abort the socket without a WebSocket close handshake.

Source code in dashscope/resources/audio/live.py
426
427
428
def cancel(self) -> None:
    """Immediately abort the socket without a WebSocket close handshake."""
    self._close(abort=True)

update_session

update_session(
    *,
    model: str,
    delegation: Dict[str, Any],
    instructions: str = cast(str, _UNSET),
    voice: str = cast(str, _UNSET),
    tts: Dict[str, Any] = cast(Dict[str, Any], _UNSET),
    input_audio_format: str = cast(str, _UNSET),
    output_audio_format: str = cast(str, _UNSET),
    tools: List[Dict[str, Any]] = cast(
        List[Dict[str, Any]], _UNSET
    ),
    transport: Dict[str, Any] = cast(
        Dict[str, Any], _UNSET
    ),
    modalities: List[str] = cast(List[str], _UNSET),
    context: Dict[str, Any] = cast(Dict[str, Any], _UNSET),
    turn_detection: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]], _UNSET
    ),
    input_audio_transcription: Optional[
        Dict[str, Any]
    ] = cast(Optional[Dict[str, Any]], _UNSET),
    parameters: Optional[Dict[str, Any]] = None,
    event_id: Optional[str] = None
) -> str

Configure the front end and delegation; confirmed by session.updated.

parameters merges extra keys into the session node for server fields this SDK does not type yet; it may not shadow a typed argument.

Source code in dashscope/resources/audio/live.py
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def update_session(
    self,
    *,
    model: str,
    delegation: Dict[str, Any],
    instructions: str = cast(str, _UNSET),
    voice: str = cast(str, _UNSET),
    tts: Dict[str, Any] = cast(Dict[str, Any], _UNSET),
    input_audio_format: str = cast(str, _UNSET),
    output_audio_format: str = cast(str, _UNSET),
    tools: List[Dict[str, Any]] = cast(List[Dict[str, Any]], _UNSET),
    transport: Dict[str, Any] = cast(Dict[str, Any], _UNSET),
    modalities: List[str] = cast(List[str], _UNSET),
    context: Dict[str, Any] = cast(Dict[str, Any], _UNSET),
    turn_detection: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]],
        _UNSET,
    ),
    input_audio_transcription: Optional[Dict[str, Any]] = cast(
        Optional[Dict[str, Any]],
        _UNSET,
    ),
    parameters: Optional[Dict[str, Any]] = None,
    event_id: Optional[str] = None,
) -> str:
    """Configure the front end and delegation; confirmed by session.updated.

    ``parameters`` merges extra keys into the ``session`` node for server
    fields this SDK does not type yet; it may not shadow a typed argument.
    """
    if not isinstance(delegation, dict):
        raise ValueError("delegation must be an object")
    kind = delegation.get("type")
    if kind not in ("none", "client", "responses"):
        raise ValueError(
            "delegation.type must be none, client or responses",
        )
    if kind == "responses":
        responses = delegation.get("responses")
        if not isinstance(responses, dict):
            raise ValueError("delegation.responses must be an object")
        backend_model = responses.get("model")
        if not isinstance(backend_model, str) or not backend_model.strip():
            raise ValueError(
                "delegation.responses.model must be a nonempty string",
            )
    elif "responses" in delegation:
        raise ValueError("delegation.responses requires responses mode")
    for value in (input_audio_format, output_audio_format):
        if value is not _UNSET and value != "pcm":
            raise ValueError("Live audio formats must be pcm")
    if parameters is not None:
        if not isinstance(parameters, dict):
            raise ValueError("parameters must be an object")
        shadowed = sorted(set(parameters) & _RESERVED_SESSION_FIELDS)
        if shadowed:
            raise ValueError(
                "parameters cannot override typed session fields: "
                + ", ".join(shadowed),
            )
    session = {
        key: value
        for key, value in (
            ("model", model),
            ("instructions", instructions),
            ("voice", voice),
            ("tts", tts),
            ("input_audio_format", input_audio_format),
            ("output_audio_format", output_audio_format),
            ("tools", tools),
            ("delegation", delegation),
            ("transport", transport),
            ("modalities", modalities),
            ("context", context),
            ("turn_detection", turn_detection),
            ("input_audio_transcription", input_audio_transcription),
        )
        if value is not _UNSET
    }
    if parameters:
        session.update(parameters)
    return self._send(
        {"type": EVENT_SESSION_UPDATE, "session": session},
        event_id,
    )

append_audio

append_audio(
    audio_b64: Union[str, bytes],
    *,
    event_id: Optional[str] = None
) -> str

Send raw or base64 16 kHz mono PCM16LE; AOQ input uses its own SDK.

Source code in dashscope/resources/audio/live.py
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def append_audio(
    self,
    audio_b64: Union[str, bytes],
    *,
    event_id: Optional[str] = None,
) -> str:
    """Send raw or base64 16 kHz mono PCM16LE; AOQ input uses its own SDK."""
    audio = _as_base64(audio_b64)
    pcm = (
        audio_b64
        if isinstance(audio_b64, bytes)
        else base64.b64decode(audio, validate=True)
    )
    if not pcm or len(pcm) % 2:
        raise ValueError(
            "audio must contain nonempty, even-length PCM16LE",
        )
    return self._send(
        {"type": EVENT_SESSION_INPUT_AUDIO_APPEND, "audio": audio},
        event_id,
    )

mute_input_audio

mute_input_audio(*, event_id: Optional[str] = None) -> str

Replace subsequent input with silence without stopping playback.

Source code in dashscope/resources/audio/live.py
543
544
545
def mute_input_audio(self, *, event_id: Optional[str] = None) -> str:
    """Replace subsequent input with silence without stopping playback."""
    return self._send({"type": EVENT_SESSION_INPUT_AUDIO_MUTE}, event_id)

unmute_input_audio

unmute_input_audio(
    *, event_id: Optional[str] = None
) -> str

Resume normal input without replaying muted audio.

Source code in dashscope/resources/audio/live.py
547
548
549
def unmute_input_audio(self, *, event_id: Optional[str] = None) -> str:
    """Resume normal input without replaying muted audio."""
    return self._send({"type": EVENT_SESSION_INPUT_AUDIO_UNMUTE}, event_id)

append_instruction

append_instruction(
    content: str,
    *,
    delegation_id: str,
    task_id: Optional[str] = None,
    start_ms: Optional[float] = None,
    end_ms: Optional[float] = None,
    event_id: Optional[str] = None
) -> str

Yield for user input; acknowledged by session.instructions.appended.

Source code in dashscope/resources/audio/live.py
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
def append_instruction(
    self,
    content: str,
    *,
    delegation_id: str,
    task_id: Optional[str] = None,
    start_ms: Optional[float] = None,
    end_ms: Optional[float] = None,
    event_id: Optional[str] = None,
) -> str:
    """Yield for user input; acknowledged by session.instructions.appended."""
    return self._append_task_event(
        "instruction",
        content,
        delegation_id=delegation_id,
        task_id=task_id,
        start_ms=start_ms,
        end_ms=end_ms,
        event_id=event_id,
    )

append_thinking

append_thinking(
    content: str,
    *,
    delegation_id: str,
    start_ms: Optional[float] = None,
    end_ms: Optional[float] = None,
    event_id: Optional[str] = None
) -> str

Report silent client-task progress without ending the execution.

Source code in dashscope/resources/audio/live.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
def append_thinking(
    self,
    content: str,
    *,
    delegation_id: str,
    start_ms: Optional[float] = None,
    end_ms: Optional[float] = None,
    event_id: Optional[str] = None,
) -> str:
    """Report silent client-task progress without ending the execution."""
    return self._append_task_event(
        "thinking",
        content,
        delegation_id=delegation_id,
        task_id=None,
        start_ms=start_ms,
        end_ms=end_ms,
        event_id=event_id,
    )

append_commentary

append_commentary(
    content: str = cast(str, _UNSET),
    *,
    delegation_id: Optional[str] = None,
    start_ms: Optional[float] = None,
    end_ms: Optional[float] = None,
    error: Optional[Dict[str, Any]] = None,
    event_id: Optional[str] = None
) -> str

Send user text or a client-task result; content may be omitted.

Source code in dashscope/resources/audio/live.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
def append_commentary(
    self,
    content: str = cast(str, _UNSET),
    *,
    delegation_id: Optional[str] = None,
    start_ms: Optional[float] = None,
    end_ms: Optional[float] = None,
    error: Optional[Dict[str, Any]] = None,
    event_id: Optional[str] = None,
) -> str:
    """Send user text or a client-task result; content may be omitted."""
    return self._append_task_event(
        "commentary",
        content,
        delegation_id=delegation_id,
        task_id=None,
        start_ms=start_ms,
        end_ms=end_ms,
        error=error,
        event_id=event_id,
    )

create_session_item

create_session_item(
    item: Dict[str, Any] = cast(Dict[str, Any], _UNSET),
    *,
    event_id: Optional[str] = None
) -> str

Send session.item.create with an optional front-end item.

Source code in dashscope/resources/audio/live.py
646
647
648
649
650
651
652
653
654
655
656
def create_session_item(
    self,
    item: Dict[str, Any] = cast(Dict[str, Any], _UNSET),
    *,
    event_id: Optional[str] = None,
) -> str:
    """Send session.item.create with an optional front-end item."""
    event: Dict[str, Any] = {"type": EVENT_SESSION_ITEM_CREATE}
    if item is not _UNSET:
        event["item"] = item
    return self._send(event, event_id)

submit_function_output

submit_function_output(
    call_id: str,
    output: Any,
    *,
    event_id: Optional[str] = None
) -> str

Reply to a front-end function from session.event, never a backend tool.

Source code in dashscope/resources/audio/live.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def submit_function_output(
    self,
    call_id: str,
    output: Any,
    *,
    event_id: Optional[str] = None,
) -> str:
    """Reply to a front-end function from session.event, never a backend tool."""
    return self.create_session_item(
        {
            "type": "function_call_output",
            "call_id": call_id,
            "output": (
                output
                if isinstance(output, str)
                else json.dumps(output, ensure_ascii=False)
            ),
        },
        event_id=event_id,
    )

create_response_item

create_response_item(
    item: Dict[str, Any], *, event_id: Optional[str] = None
) -> str

Buffer next-task input in Responses mode, not an active task's result.

Source code in dashscope/resources/audio/live.py
679
680
681
682
683
684
685
686
687
688
689
def create_response_item(
    self,
    item: Dict[str, Any],
    *,
    event_id: Optional[str] = None,
) -> str:
    """Buffer next-task input in Responses mode, not an active task's result."""
    return self._send(
        {"type": EVENT_RESPONSE_ITEM_CREATE, "item": item},
        event_id,
    )

create_response

create_response(
    response: Optional[Dict[str, Any]] = None,
    *,
    event_id: Optional[str] = None
) -> str

Start a new Responses task, or request a reply from a capable front end.

Source code in dashscope/resources/audio/live.py
691
692
693
694
695
696
697
698
699
700
701
def create_response(
    self,
    response: Optional[Dict[str, Any]] = None,
    *,
    event_id: Optional[str] = None,
) -> str:
    """Start a new Responses task, or request a reply from a capable front end."""
    event: Dict[str, Any] = {"type": EVENT_RESPONSE_CREATE}
    if response is not None:
        event["response"] = response
    return self._send(event, event_id)

end_session

end_session(*, event_id: Optional[str] = None) -> str

Send session.close; keep receiving until session.closed or disconnect.

Source code in dashscope/resources/audio/live.py
703
704
705
def end_session(self, *, event_id: Optional[str] = None) -> str:
    """Send session.close; keep receiving until session.closed or disconnect."""
    return self._send({"type": EVENT_SESSION_CLOSE}, event_id)

音色与热词定制

Voices

Voices(client)

Bases: _CustomizationBase

client.audio.voices -- voice cloning.

Source code in dashscope/resources/audio/customization.py
130
131
def __init__(self, client) -> None:
    self._client = client

PATH class-attribute instance-attribute

PATH = '/services/audio/tts/customization'

DEFAULT_MODEL class-attribute instance-attribute

DEFAULT_MODEL = 'voice-enrollment'

create

create(
    *,
    target_model: str,
    prefix: str,
    url: Optional[str] = None,
    audio: Optional[str] = None,
    language_hints: Optional[List[str]] = None,
    max_prompt_audio_length: Optional[float] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Voice
create(
    *,
    target_model: str,
    prefix: str,
    url: Optional[str] = None,
    audio: Optional[str] = None,
    language_hints: Optional[List[str]] = None,
    max_prompt_audio_length: Optional[float] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
create(
    *,
    target_model: str,
    prefix: str,
    url: Optional[str] = None,
    audio: Optional[str] = None,
    language_hints: Optional[List[str]] = None,
    max_prompt_audio_length: Optional[float] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Voice, "APIResponse"]

Clone a voice from audio (Data URI/URL) or a legacy url.

Provide exactly one source. The result carries voice_id.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
def create(
    self,
    *,
    target_model: str,
    prefix: str,
    url: Optional[str] = None,
    audio: Optional[str] = None,
    language_hints: Optional[List[str]] = None,
    max_prompt_audio_length: Optional[float] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Voice, "APIResponse"]:
    """Clone a voice from ``audio`` (Data URI/URL) or a legacy ``url``.

    Provide exactly one source. The result carries ``voice_id``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    if (audio is None) == (url is None):
        raise ValueError("provide exactly one of audio or url")
    if audio is not None and (
        not isinstance(audio, str) or not audio.strip()
    ):
        raise ValueError("audio must be a non-empty string")
    fields: Dict[str, Any] = dict(extra_input or {})
    # Named arguments win over the ``extra_input=`` escape hatch.
    fields.update({"target_model": target_model, "prefix": prefix})
    if audio is not None:
        fields.pop("url", None)
        fields["audio"] = audio
    else:
        fields.pop("audio", None)
        fields["url"] = url
    if language_hints is not None:
        fields["language_hints"] = language_hints
    if max_prompt_audio_length is not None:
        fields["max_prompt_audio_length"] = max_prompt_audio_length
    resp = self._call(
        "create_voice",
        fields,
        model=model,
        parameters=parameters,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(Voice, resp.http_response),
        resp.http_response,
    )

list

list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> VoiceList
list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[VoiceList, "APIResponse"]

List cloned voices, optionally narrowed to one prefix.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
def list(
    self,
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[VoiceList, "APIResponse"]:
    """List cloned voices, optionally narrowed to one ``prefix``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    fields: Dict[str, Any] = {
        "page_index": page_index,
        "page_size": page_size,
    }
    if prefix:
        fields["prefix"] = prefix
    resp = self._call(
        "list_voice",
        fields,
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(VoiceList, resp.http_response),
        resp.http_response,
    )

get

get(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Voice
get(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
get(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Voice, "APIResponse"]

Fetch one voice's details (1.x query_voice).

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
def get(
    self,
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Voice, "APIResponse"]:
    """Fetch one voice's details (1.x ``query_voice``).

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(voice_id, "voice_id")
    resp = self._call(
        "query_voice",
        {"voice_id": voice_id},
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(Voice, resp.http_response),
        resp.http_response,
    )

update

update(
    voice_id: str,
    *,
    url: str,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> JobStatus
update(
    voice_id: str,
    *,
    url: str,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
update(
    voice_id: str,
    *,
    url: str,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[JobStatus, "APIResponse"]

Re-clone one voice from the audio at url.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
def update(
    self,
    voice_id: str,
    *,
    url: str,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[JobStatus, "APIResponse"]:
    """Re-clone one voice from the audio at ``url``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(voice_id, "voice_id")
    resp = self._call(
        "update_voice",
        {"voice_id": voice_id, "url": url},
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(JobStatus, resp.http_response),
        resp.http_response,
    )

delete

delete(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> JobStatus
delete(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
delete(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[JobStatus, "APIResponse"]

Delete one cloned voice.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
def delete(
    self,
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[JobStatus, "APIResponse"]:
    """Delete one cloned voice.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(voice_id, "voice_id")
    resp = self._call(
        "delete_voice",
        {"voice_id": voice_id},
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(JobStatus, resp.http_response),
        resp.http_response,
    )

Voice

Bases: ResponseBase

One cloned voice; create/get return it.

voice_id class-attribute instance-attribute

voice_id: Optional[str] = None

status class-attribute instance-attribute

status: Optional[str] = None

preview_audio class-attribute instance-attribute

preview_audio: Optional[Dict[str, Any]] = None

VoiceList

Bases: ResponseBase

voices class-attribute instance-attribute

voices: List[Dict[str, Any]] = Field(
    default_factory=list,
    validation_alias=AliasChoices("voices", "voice_list"),
)

VoiceDesign

VoiceDesign(client)

Bases: _CustomizationBase

client.audio.voice_design -- voices described in words, not audio.

Shares the voice-enrollment registry with :class:Voices: same path, same model, same action words, same voice_id, one quota. Only create differs -- a text prompt where cloning has a sample url -- so list returns cloned voices as well as designed ones.

Source code in dashscope/resources/audio/customization.py
130
131
def __init__(self, client) -> None:
    self._client = client

PATH class-attribute instance-attribute

PATH = '/services/audio/tts/customization'

DEFAULT_MODEL class-attribute instance-attribute

DEFAULT_MODEL = 'voice-enrollment'

create

create(
    *,
    target_model: str,
    prefix: str,
    voice_prompt: str,
    preview_text: str,
    language_hints: Optional[List[str]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> DesignedVoice
create(
    *,
    target_model: str,
    prefix: str,
    voice_prompt: str,
    preview_text: str,
    language_hints: Optional[List[str]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
create(
    *,
    target_model: str,
    prefix: str,
    voice_prompt: str,
    preview_text: str,
    language_hints: Optional[List[str]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[DesignedVoice, "APIResponse"]

Design a voice from a text prompt; carries voice_id + preview.

prefix becomes part of the generated id, {target_model}-vd-{prefix}-{unique}. Only the first element of language_hints is honoured, and it must match the language of preview_text. The voice is unusable until its status leaves DEPLOYING.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
def create(
    self,
    *,
    target_model: str,
    prefix: str,
    voice_prompt: str,
    preview_text: str,
    language_hints: Optional[List[str]] = None,
    extra_input: Optional[Dict[str, Any]] = None,
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[DesignedVoice, "APIResponse"]:
    """Design a voice from a text prompt; carries ``voice_id`` + preview.

    ``prefix`` becomes part of the generated id,
    ``{target_model}-vd-{prefix}-{unique}``. Only the first element of
    ``language_hints`` is honoured, and it must match the language of
    ``preview_text``. The voice is unusable until its ``status`` leaves
    ``DEPLOYING``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    fields: Dict[str, Any] = dict(extra_input or {})
    # Named arguments win over the ``extra_input=`` escape hatch.
    fields.update(
        {
            "target_model": target_model,
            "prefix": prefix,
            "voice_prompt": voice_prompt,
            "preview_text": preview_text,
        },
    )
    if language_hints is not None:
        fields["language_hints"] = language_hints
    resp = self._call(
        "create_voice",
        fields,
        model=model,
        parameters=parameters,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(DesignedVoice, resp.http_response),
        resp.http_response,
    )

list

list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> DesignedVoiceList
list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[DesignedVoiceList, "APIResponse"]

List voices, optionally narrowed to one prefix.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
def list(
    self,
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[DesignedVoiceList, "APIResponse"]:
    """List voices, optionally narrowed to one ``prefix``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    fields: Dict[str, Any] = {
        "page_index": page_index,
        "page_size": page_size,
    }
    if prefix:
        fields["prefix"] = prefix
    resp = self._call(
        "list_voice",
        fields,
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(DesignedVoiceList, resp.http_response),
        resp.http_response,
    )

get

get(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> DesignedVoice
get(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
get(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[DesignedVoice, "APIResponse"]

Fetch one voice's details, including its review status.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
def get(
    self,
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[DesignedVoice, "APIResponse"]:
    """Fetch one voice's details, including its review ``status``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(voice_id, "voice_id")
    resp = self._call(
        "query_voice",
        {"voice_id": voice_id},
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(DesignedVoice, resp.http_response),
        resp.http_response,
    )

delete

delete(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> JobStatus
delete(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
delete(
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[JobStatus, "APIResponse"]

Delete one designed voice, freeing its quota.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
def delete(
    self,
    voice_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[JobStatus, "APIResponse"]:
    """Delete one designed voice, freeing its quota.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(voice_id, "voice_id")
    resp = self._call(
        "delete_voice",
        {"voice_id": voice_id},
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(JobStatus, resp.http_response),
        resp.http_response,
    )

DesignedVoice

Bases: ResponseBase

One designed voice.

The same registry entry as a cloned :class:Voice -- one endpoint, one voice_id, one shared quota -- plus the two texts it was designed from.

voice_id class-attribute instance-attribute

voice_id: Optional[str] = None

status class-attribute instance-attribute

status: Optional[str] = None

preview_audio class-attribute instance-attribute

preview_audio: Optional[Dict[str, Any]] = None

target_model class-attribute instance-attribute

target_model: Optional[str] = None

voice_prompt class-attribute instance-attribute

voice_prompt: Optional[str] = None

preview_text class-attribute instance-attribute

preview_text: Optional[str] = None

gmt_create class-attribute instance-attribute

gmt_create: Optional[str] = None

gmt_modified class-attribute instance-attribute

gmt_modified: Optional[str] = None

DesignedVoiceList

Bases: ResponseBase

voices class-attribute instance-attribute

voices: List[Dict[str, Any]] = Field(
    default_factory=list,
    validation_alias=AliasChoices("voices", "voice_list"),
)

Vocabularies

Vocabularies(client)

Bases: _CustomizationBase

client.audio.vocabularies -- asr hot-word tables.

Source code in dashscope/resources/audio/customization.py
130
131
def __init__(self, client) -> None:
    self._client = client

PATH class-attribute instance-attribute

PATH = '/services/audio/asr/customization'

DEFAULT_MODEL class-attribute instance-attribute

DEFAULT_MODEL = 'speech-biasing'

create

create(
    *,
    target_model: str,
    prefix: str,
    vocabulary: List[Dict[str, Any]],
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Vocabulary
create(
    *,
    target_model: str,
    prefix: str,
    vocabulary: List[Dict[str, Any]],
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
create(
    *,
    target_model: str,
    prefix: str,
    vocabulary: List[Dict[str, Any]],
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Vocabulary, "APIResponse"]

Create a table; the result carries vocabulary_id.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def create(
    self,
    *,
    target_model: str,
    prefix: str,
    vocabulary: List[Dict[str, Any]],
    model: Optional[str] = None,
    parameters: Optional[Dict[str, Any]] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Vocabulary, "APIResponse"]:
    """Create a table; the result carries ``vocabulary_id``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    resp = self._call(
        "create_vocabulary",
        {
            "target_model": target_model,
            "prefix": prefix,
            "vocabulary": vocabulary,
        },
        model=model,
        parameters=parameters,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(Vocabulary, resp.http_response),
        resp.http_response,
    )

list

list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> VocabularyList
list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
list(
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[VocabularyList, "APIResponse"]

List tables, optionally narrowed to one prefix.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
def list(
    self,
    *,
    prefix: Optional[str] = None,
    page_index: int = 0,
    page_size: int = 10,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[VocabularyList, "APIResponse"]:
    """List tables, optionally narrowed to one ``prefix``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    fields: Dict[str, Any] = {
        "page_index": page_index,
        "page_size": page_size,
    }
    if prefix:
        fields["prefix"] = prefix
    resp = self._call(
        "list_vocabulary",
        fields,
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(VocabularyList, resp.http_response),
        resp.http_response,
    )

get

get(
    vocabulary_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Vocabulary
get(
    vocabulary_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
get(
    vocabulary_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Vocabulary, "APIResponse"]

Fetch one table's contents (1.x query_vocabulary).

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
def get(
    self,
    vocabulary_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Vocabulary, "APIResponse"]:
    """Fetch one table's contents (1.x ``query_vocabulary``).

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(vocabulary_id, "vocabulary_id")
    resp = self._call(
        "query_vocabulary",
        {"vocabulary_id": vocabulary_id},
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(Vocabulary, resp.http_response),
        resp.http_response,
    )

update

update(
    vocabulary_id: str,
    *,
    vocabulary: List[Dict[str, Any]],
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> JobStatus
update(
    vocabulary_id: str,
    *,
    vocabulary: List[Dict[str, Any]],
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
update(
    vocabulary_id: str,
    *,
    vocabulary: List[Dict[str, Any]],
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[JobStatus, "APIResponse"]

Replace one table's contents.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
def update(
    self,
    vocabulary_id: str,
    *,
    vocabulary: List[Dict[str, Any]],
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[JobStatus, "APIResponse"]:
    """Replace one table's contents.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(vocabulary_id, "vocabulary_id")
    resp = self._call(
        "update_vocabulary",
        {"vocabulary_id": vocabulary_id, "vocabulary": vocabulary},
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(JobStatus, resp.http_response),
        resp.http_response,
    )

delete

delete(
    vocabulary_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> JobStatus
delete(
    vocabulary_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
delete(
    vocabulary_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[JobStatus, "APIResponse"]

Delete one table.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/customization.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
def delete(
    self,
    vocabulary_id: str,
    *,
    model: Optional[str] = None,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[JobStatus, "APIResponse"]:
    """Delete one table.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(vocabulary_id, "vocabulary_id")
    resp = self._call(
        "delete_vocabulary",
        {"vocabulary_id": vocabulary_id},
        model=model,
        timeout=timeout,
        headers=headers,
        api_key=api_key,
        workspace=workspace,
        extra_headers=extra_headers,
        extra_query=extra_query,
        extra_body=extra_body,
        max_retries=max_retries,
    )
    if raw:
        return resp
    return with_headers(
        self._parse_model(JobStatus, resp.http_response),
        resp.http_response,
    )

Vocabulary

Bases: ResponseBase

One hot-word table; create/get return it.

vocabulary_id class-attribute instance-attribute

vocabulary_id: Optional[str] = None

vocabulary class-attribute instance-attribute

vocabulary: Optional[List[Dict[str, Any]]] = None

VocabularyList

Bases: ResponseBase

vocabularies class-attribute instance-attribute

vocabularies: List[Dict[str, Any]] = Field(
    default_factory=list,
    validation_alias=AliasChoices(
        "vocabularies", "vocabulary_list"
    ),
)

Phrases

Phrases(client)

client.audio.phrases -- paraformer hot phrases.

Source code in dashscope/resources/audio/phrases.py
119
120
def __init__(self, client) -> None:
    self._client = client

create

create(
    *,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Phrase
create(
    *,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
create(
    *,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Phrase, "APIResponse"]

Compile a new phrase set; the result carries phrase_id.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/phrases.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def create(
    self,
    *,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Phrase, "APIResponse"]:
    """Compile a new phrase set; the result carries ``phrase_id``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_phrases(phrases)
    resp = self._client.transport.request_api(
        "POST",
        _CREATE_PATH,
        json=_compile_body(
            model=model,
            phrases=phrases,
            training_type=training_type,
            finetuned_output=None,
        ),
        headers=headers,
        timeout=timeout,
        sdk_module=MODULE,
        api_key=api_key,
        workspace=workspace,
        options=request_options(
            extra_headers,
            extra_query,
            extra_body,
            max_retries=max_retries,
        ),
        client=self._client,
    )
    if raw:
        return resp
    body = response_body(
        resp.http_response,
        raise_on_error=self._client.raise_on_error,
    )
    return with_headers(
        self._parse(Phrase, body, resp.http_response),
        resp.http_response,
    )

update

update(
    phrase_id: str,
    *,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Phrase
update(
    phrase_id: str,
    *,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
update(
    phrase_id: str,
    *,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Phrase, "APIResponse"]

Recompile the phrase set behind phrase_id.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/phrases.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def update(
    self,
    phrase_id: str,
    *,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Phrase, "APIResponse"]:
    """Recompile the phrase set behind ``phrase_id``.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(phrase_id, "phrase_id")
    _require_phrases(phrases)
    resp = self._client.transport.request_api(
        "POST",
        _CREATE_PATH,
        json=_compile_body(
            model=model,
            phrases=phrases,
            training_type=training_type,
            finetuned_output=phrase_id,
        ),
        headers=headers,
        timeout=timeout,
        sdk_module=MODULE,
        api_key=api_key,
        workspace=workspace,
        options=request_options(
            extra_headers,
            extra_query,
            extra_body,
            max_retries=max_retries,
        ),
        client=self._client,
    )
    if raw:
        return resp
    body = response_body(
        resp.http_response,
        raise_on_error=self._client.raise_on_error,
    )
    return with_headers(
        self._parse(Phrase, body, resp.http_response),
        resp.http_response,
    )

get

get(
    phrase_id: str,
    *,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> Phrase
get(
    phrase_id: str,
    *,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
get(
    phrase_id: str,
    *,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[Phrase, "APIResponse"]

Fetch one compiled phrase set (1.x query_phrases).

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/phrases.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
def get(
    self,
    phrase_id: str,
    *,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[Phrase, "APIResponse"]:
    """Fetch one compiled phrase set (1.x ``query_phrases``).

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(phrase_id, "phrase_id")
    resp = self._client.transport.request_api(
        "GET",
        f"{_OUTPUTS_PATH}/{phrase_id}",
        headers=headers,
        timeout=timeout,
        sdk_module=MODULE,
        api_key=api_key,
        workspace=workspace,
        options=request_options(
            extra_headers,
            extra_query,
            extra_body,
            max_retries=max_retries,
        ),
        client=self._client,
    )
    if raw:
        return resp
    body = response_body(
        resp.http_response,
        raise_on_error=self._client.raise_on_error,
    )
    return with_headers(
        self._parse(Phrase, body, resp.http_response),
        resp.http_response,
    )

list

list(
    *,
    page_no: int = 1,
    page_size: int = 10,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> PhraseList
list(
    *,
    page_no: int = 1,
    page_size: int = 10,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
list(
    *,
    page_no: int = 1,
    page_size: int = 10,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[PhraseList, "APIResponse"]

List compiled phrase sets.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/phrases.py
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
def list(
    self,
    *,
    page_no: int = 1,
    page_size: int = 10,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[PhraseList, "APIResponse"]:
    """List compiled phrase sets.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    resp = self._client.transport.request_api(
        "GET",
        _OUTPUTS_PATH,
        params={"page_no": page_no, "page_size": page_size},
        headers=headers,
        timeout=timeout,
        sdk_module=MODULE,
        api_key=api_key,
        workspace=workspace,
        options=request_options(
            extra_headers,
            extra_query,
            extra_body,
            max_retries=max_retries,
        ),
        client=self._client,
    )
    if raw:
        return resp
    body = response_body(
        resp.http_response,
        raise_on_error=self._client.raise_on_error,
    )
    return with_headers(
        self._parse(PhraseList, body, resp.http_response),
        resp.http_response,
    )

delete

delete(
    phrase_id: str,
    *,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[False] = False
) -> JobStatus
delete(
    phrase_id: str,
    *,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: Literal[True]
) -> "APIResponse"
delete(
    phrase_id: str,
    *,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False
) -> Union[JobStatus, "APIResponse"]

Delete one compiled phrase set.

raw=True returns the :class:~dashscope.transport.APIResponse before any error check, so a caller can read the status, headers and elapsed of the response or re-parse it itself. The non-raw path keeps response_body's envelope: it preserves non-JSON failure bodies and injects status_code/request_id/is_error.

Source code in dashscope/resources/audio/phrases.py
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
def delete(
    self,
    phrase_id: str,
    *,
    timeout: Optional[float] = None,
    headers: Optional[Mapping[str, str]] = None,
    api_key: Optional[str] = None,
    workspace: Optional[str] = None,
    extra_headers: Optional[Mapping[str, str]] = None,
    extra_query: Optional[Mapping[str, Any]] = None,
    extra_body: Optional[Mapping[str, Any]] = None,
    max_retries: Optional[int] = None,
    raw: bool = False,
) -> Union[JobStatus, "APIResponse"]:
    """Delete one compiled phrase set.

    ``raw=True`` returns the :class:`~dashscope.transport.APIResponse`
    before any error check, so a caller can read the status, headers and
    ``elapsed`` of the response or re-parse it itself. The non-raw path
    keeps ``response_body``'s envelope: it preserves non-JSON failure
    bodies and injects ``status_code``/``request_id``/``is_error``.
    """
    _require_id(phrase_id, "phrase_id")
    resp = self._client.transport.request_api(
        "DELETE",
        f"{_OUTPUTS_PATH}/{phrase_id}",
        headers=headers,
        timeout=timeout,
        sdk_module=MODULE,
        api_key=api_key,
        workspace=workspace,
        options=request_options(
            extra_headers,
            extra_query,
            extra_body,
            max_retries=max_retries,
        ),
        client=self._client,
    )
    if raw:
        return resp
    body = response_body(
        resp.http_response,
        raise_on_error=self._client.raise_on_error,
    )
    return with_headers(
        self._parse(JobStatus, body, resp.http_response),
        resp.http_response,
    )

Phrase

Bases: ResponseBase

One compiled phrase set; prefer its resource ID over the compile job ID.

phrase_id class-attribute instance-attribute

phrase_id: Optional[str] = Field(
    None,
    validation_alias=AliasChoices(
        "phrase_id", "finetuned_output", "job_id"
    ),
)

status class-attribute instance-attribute

status: Optional[str] = None

PhraseList

Bases: ResponseBase

page_no class-attribute instance-attribute

page_no: int = 1

page_size class-attribute instance-attribute

page_size: int = 10

total_count class-attribute instance-attribute

total_count: int = Field(
    0, validation_alias=AliasChoices("total_count", "total")
)

phrases class-attribute instance-attribute

phrases: List[Phrase] = Field(
    default_factory=list,
    validation_alias=AliasChoices(
        "phrases", "jobs", "outputs", "finetuned_outputs"
    ),
)