Skip to content

Legacy 1.x API

The 1.x API classes are archived under dashscope.legacy_1x and remain importable from the dashscope root module for backward compatibility (from dashscope import Generation still works). The layer is frozen: it receives no new features. New code should use the new Client.

Frozen layer

The 1.x surface receives no new features. Assistants / Threads additionally emit DeprecationWarning on access.

Text generation

Generation

Bases: BaseApi

task class-attribute instance-attribute

task = 'text-generation'

API for AI-Generated Content(AIGC) models.

Models

@deprecated, use qwen_turbo instead

qwen_v1 class-attribute instance-attribute
qwen_v1 = 'qwen-v1'

@deprecated, use qwen_plus instead

qwen_plus_v1 class-attribute instance-attribute
qwen_plus_v1 = 'qwen-plus-v1'
bailian_v1 class-attribute instance-attribute
bailian_v1 = 'bailian-v1'
dolly_12b_v2 class-attribute instance-attribute
dolly_12b_v2 = 'dolly-12b-v2'
qwen_turbo class-attribute instance-attribute
qwen_turbo = 'qwen-turbo'
qwen_plus class-attribute instance-attribute
qwen_plus = 'qwen-plus'
qwen_max class-attribute instance-attribute
qwen_max = 'qwen-max'

call classmethod

call(
    model: str,
    prompt: Any = None,
    history: list | None = None,
    api_key: str | None = None,
    messages: List[Message] | None = None,
    plugins: Union[str, Dict[str, Any], None] = None,
    workspace: str | None = None,
    stream: bool | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: int | None = None,
    max_tokens: int | None = None,
    seed: int | None = None,
    stop: Union[str, List[str], None] = None,
    repetition_penalty: float | None = None,
    presence_penalty: float | None = None,
    result_format: str | None = None,
    incremental_output: bool | None = None,
    enable_search: bool | None = None,
    tools: List[Dict[str, Any]] | None = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    enable_thinking: bool | None = None,
    thinking_budget: int | None = None,
    n: int | None = None,
    logprobs: bool | None = None,
    top_logprobs: int | None = None,
    search_options: Dict[str, Any] | None = None,
    parallel_tool_calls: bool | None = None,
    response_format: Dict[str, Any] | None = None,
    output_format: str | None = None,
    **kwargs: Any
) -> Union[
    GenerationResponse,
    Generator[GenerationResponse, None, None],
]

Call generation model service.

Parameters:

Name Type Description Default
model str

The requested model, such as qwen-turbo.

required
prompt Any

The input prompt.

None
history list

The user provided history, deprecated.

None
api_key str

The api api_key, can be None.

None
messages list

The generation messages.

None
plugins Any

The plugin config, str or dict.

None
workspace str

The dashscope workspace id.

None
stream bool

Enable streaming output.

None
temperature float

Controls randomness, range [0, 2).

None
top_p float

Nucleus sampling, range (0, 1.0].

None
top_k int

Size of candidate token set for sampling.

None
max_tokens int

Maximum output token count.

None
seed int

Random seed for reproducibility.

None
stop str or list

Stop sequences.

None
repetition_penalty float

Penalizes repeated sequences. 1.0 means no penalty.

None
presence_penalty float

Controls content repetition, range [-2.0, 2.0].

None
result_format str

"message" or "text".

None
incremental_output bool

In streaming mode, output only new tokens (True) vs. cumulative output (False).

None
enable_search bool

Enable web search.

None
tools list

Tool definitions for function calling.

None
tool_choice str or dict

Tool selection strategy.

None
enable_thinking bool

Enable thinking mode for hybrid thinking models.

None
thinking_budget int

Maximum token budget for thinking mode. Controls the maximum length of thinking process.

None
n int

Number of responses to generate (1-4).

None
logprobs bool

Whether to return log probabilities of the output tokens.

None
top_logprobs int

Number of most likely tokens to return at each token position when logprobs is enabled.

None
search_options dict

Configuration options for web search feature.

None
parallel_tool_calls bool

Enable parallel tool calls for function calling.

None
response_format dict

Format constraint for response, e.g., {"type": "json_object"} for JSON mode.

None
output_format str

Output format for qwen-deep-research model. Options: "model_detailed_report" (default), "model_summary_report".

None
**kwargs Any

Additional parameters passed to the API.

{}

Returns:

Type Description
Union[GenerationResponse, Generator[GenerationResponse, None, None]]

Union[GenerationResponse, Generator[GenerationResponse, None, None]]: If

Union[GenerationResponse, Generator[GenerationResponse, None, None]]

stream is True, return Generator, otherwise GenerationResponse.

Source code in dashscope/legacy_1x/aigc/generation.py
 47
 48
 49
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
@classmethod
# type: ignore[override]
def call(  # pylint: disable=arguments-renamed,too-many-branches,too-many-statements  # type: ignore[override]  # noqa: E501
    cls,
    model: str,
    prompt: Any = None,
    history: list = None,
    api_key: str = None,
    messages: List[Message] = None,
    plugins: Union[str, Dict[str, Any]] = None,
    workspace: str = None,
    stream: bool = None,
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    max_tokens: int = None,
    seed: int = None,
    stop: Union[str, List] = None,
    repetition_penalty: float = None,
    presence_penalty: float = None,
    result_format: str = None,
    incremental_output: bool = None,
    enable_search: bool = None,
    tools: List[Dict[str, Any]] = None,
    tool_choice: Union[str, Dict[str, Any]] = None,
    enable_thinking: bool = None,
    thinking_budget: int = None,
    n: int = None,
    logprobs: bool = None,
    top_logprobs: int = None,
    search_options: Dict[str, Any] = None,
    parallel_tool_calls: bool = None,
    response_format: Dict[str, Any] = None,
    output_format: str = None,  # pylint: disable=unused-argument
    **kwargs,
) -> Union[GenerationResponse, Generator[GenerationResponse, None, None]]:
    """Call generation model service.

    Args:
        model (str): The requested model, such as qwen-turbo.
        prompt (Any): The input prompt.
        history (list): The user provided history, deprecated.
        api_key (str, optional): The api api_key, can be None.
        messages (list): The generation messages.
        plugins (Any): The plugin config, str or dict.
        workspace (str): The dashscope workspace id.
        stream (bool, optional): Enable streaming output.
        temperature (float, optional): Controls randomness, range [0, 2).
        top_p (float, optional): Nucleus sampling, range (0, 1.0].
        top_k (int, optional): Size of candidate token set for sampling.
        max_tokens (int, optional): Maximum output token count.
        seed (int, optional): Random seed for reproducibility.
        stop (str or list, optional): Stop sequences.
        repetition_penalty (float, optional): Penalizes repeated sequences.
            1.0 means no penalty.
        presence_penalty (float, optional): Controls content repetition,
            range [-2.0, 2.0].
        result_format (str, optional): "message" or "text".
        incremental_output (bool, optional): In streaming mode, output only
            new tokens (True) vs. cumulative output (False).
        enable_search (bool, optional): Enable web search.
        tools (list, optional): Tool definitions for function calling.
        tool_choice (str or dict, optional): Tool selection strategy.
        enable_thinking (bool, optional): Enable thinking mode for
            hybrid thinking models.
        thinking_budget (int, optional): Maximum token budget for thinking
            mode. Controls the maximum length of thinking process.
        n (int, optional): Number of responses to generate (1-4).
        logprobs (bool, optional): Whether to return log probabilities of
            the output tokens.
        top_logprobs (int, optional): Number of most likely tokens to
            return at each token position when logprobs is enabled.
        search_options (dict, optional): Configuration options for web
            search feature.
        parallel_tool_calls (bool, optional): Enable parallel tool calls
            for function calling.
        response_format (dict, optional): Format constraint for response,
            e.g., {"type": "json_object"} for JSON mode.
        output_format (str, optional): Output format for qwen-deep-research
            model. Options: "model_detailed_report" (default),
            "model_summary_report".
        **kwargs: Additional parameters passed to the API.

    Returns:
        Union[GenerationResponse,
              Generator[GenerationResponse, None, None]]: If
        stream is True, return Generator, otherwise GenerationResponse.
    """
    if (prompt is None or not prompt) and (
        messages is None or not messages
    ):
        raise InputRequired("prompt or messages is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    if stream is not None:
        kwargs["stream"] = stream
    if temperature is not None:
        kwargs["temperature"] = temperature
    if top_p is not None:
        kwargs["top_p"] = top_p
    if top_k is not None:
        kwargs["top_k"] = top_k
    if max_tokens is not None:
        kwargs["max_tokens"] = max_tokens
    if seed is not None:
        kwargs["seed"] = seed
    if stop is not None:
        kwargs["stop"] = stop
    if repetition_penalty is not None:
        kwargs["repetition_penalty"] = repetition_penalty
    if presence_penalty is not None:
        kwargs["presence_penalty"] = presence_penalty
    if result_format is not None:
        kwargs["result_format"] = result_format
    if incremental_output is not None:
        kwargs["incremental_output"] = incremental_output
    if enable_search is not None:
        kwargs["enable_search"] = enable_search
    if tools is not None:
        kwargs["tools"] = tools
    if tool_choice is not None:
        kwargs["tool_choice"] = tool_choice
    if enable_thinking is not None:
        kwargs["enable_thinking"] = enable_thinking
    if thinking_budget is not None:
        kwargs["thinking_budget"] = thinking_budget
    if n is not None:
        kwargs["n"] = n
    if logprobs is not None:
        kwargs["logprobs"] = logprobs
    if top_logprobs is not None:
        kwargs["top_logprobs"] = top_logprobs
    if search_options is not None:
        kwargs["search_options"] = search_options
    if parallel_tool_calls is not None:
        kwargs["parallel_tool_calls"] = parallel_tool_calls
    if response_format is not None:
        kwargs["response_format"] = response_format
    task_group, function = _get_task_group_and_task(__name__)
    if plugins is not None:
        headers = kwargs.pop("headers", {})
        if isinstance(plugins, str):
            headers["X-DashScope-Plugin"] = plugins
        else:
            headers["X-DashScope-Plugin"] = json.dumps(plugins)
        kwargs["headers"] = headers
    (
        input,  # pylint: disable=redefined-builtin
        parameters,
    ) = cls._build_input_parameters(
        model,
        prompt,
        history,
        messages,
        **kwargs,
    )

    is_stream = parameters.get("stream", False)
    # Check if we need to merge incremental output
    is_incremental_output = kwargs.get("incremental_output", None)
    to_merge_incremental_output = False
    if (
        ParamUtil.should_modify_incremental_output(model)
        and is_stream
        and is_incremental_output is False
    ):
        to_merge_incremental_output = True
        parameters["incremental_output"] = True

    # Pass incremental_to_full flag via user_agent parameter
    flag = "1" if to_merge_incremental_output else "0"
    existing_ua = parameters.get("user_agent", "")
    new_ua = f"incremental_to_full/{flag}"
    parameters["user_agent"] = (
        f"{existing_ua}; {new_ua}".strip() if existing_ua else new_ua
    )

    response = super().call(
        model=model,
        task_group=task_group,
        task=Generation.task,
        function=function,
        api_key=api_key,
        input=input,
        workspace=workspace,
        **parameters,
    )
    if is_stream:
        if to_merge_incremental_output:
            # Extract n parameter for merge logic
            n = parameters.get("n", 1)
            return cls._merge_generation_response(response, n)
        else:
            return (
                GenerationResponse.from_api_response(rsp)
                for rsp in response
            )
    else:
        return GenerationResponse.from_api_response(response)

AioGeneration

Bases: BaseAioApi

task class-attribute instance-attribute

task = 'text-generation'

API for AI-Generated Content(AIGC) models.

Models

@deprecated, use qwen_turbo instead

qwen_v1 class-attribute instance-attribute
qwen_v1 = 'qwen-v1'

@deprecated, use qwen_plus instead

qwen_plus_v1 class-attribute instance-attribute
qwen_plus_v1 = 'qwen-plus-v1'
bailian_v1 class-attribute instance-attribute
bailian_v1 = 'bailian-v1'
dolly_12b_v2 class-attribute instance-attribute
dolly_12b_v2 = 'dolly-12b-v2'
qwen_turbo class-attribute instance-attribute
qwen_turbo = 'qwen-turbo'
qwen_plus class-attribute instance-attribute
qwen_plus = 'qwen-plus'
qwen_max class-attribute instance-attribute
qwen_max = 'qwen-max'

call async classmethod

call(
    model: str,
    prompt: Any = None,
    history: list | None = None,
    api_key: str | None = None,
    messages: List[Message] | None = None,
    plugins: Union[str, Dict[str, Any]] = None,
    workspace: str = None,
    stream: bool = None,
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    max_tokens: int = None,
    seed: int = None,
    stop: Union[str, List] = None,
    repetition_penalty: float = None,
    presence_penalty: float = None,
    result_format: str = None,
    incremental_output: bool = None,
    enable_search: bool = None,
    tools: List[Dict[str, Any]] = None,
    tool_choice: Union[str, Dict[str, Any]] = None,
    enable_thinking: bool = None,
    thinking_budget: int = None,
    n: int = None,
    logprobs: bool = None,
    top_logprobs: int = None,
    search_options: Dict[str, Any] = None,
    parallel_tool_calls: bool = None,
    response_format: Dict[str, Any] = None,
    output_format: str = None,
    **kwargs: Any
) -> Union[
    GenerationResponse,
    Generator[GenerationResponse, None, None],
]

Call generation model service.

Parameters:

Name Type Description Default
model str

The requested model, such as qwen-turbo.

required
prompt Any

The input prompt.

None
history list

The user provided history, deprecated.

None
api_key str

The api api_key, can be None.

None
messages list

The generation messages.

None
plugins Any

The plugin config, str or dict.

None
workspace str

The dashscope workspace id.

None
stream bool

Enable streaming output.

None
temperature float

Controls randomness, range [0, 2).

None
top_p float

Nucleus sampling, range (0, 1.0].

None
top_k int

Size of candidate token set for sampling.

None
max_tokens int

Maximum output token count.

None
seed int

Random seed for reproducibility.

None
stop str or list

Stop sequences.

None
repetition_penalty float

Penalizes repeated sequences.

None
presence_penalty float

Controls content repetition.

None
result_format str

"message" or "text".

None
incremental_output bool

In streaming mode, output only new tokens (True) vs. cumulative output (False).

None
enable_search bool

Enable web search.

None
tools list

Tool definitions for function calling.

None
tool_choice str or dict

Tool selection strategy.

None
enable_thinking bool

Enable thinking mode.

None
thinking_budget int

Maximum token budget for thinking mode. Controls the maximum length of thinking process.

None
n int

Number of responses to generate (1-4).

None
logprobs bool

Whether to return log probabilities of the output tokens.

None
top_logprobs int

Number of most likely tokens to return at each token position when logprobs is enabled.

None
search_options dict

Configuration options for web search feature.

None
parallel_tool_calls bool

Enable parallel tool calls for function calling.

None
response_format dict

Format constraint for response, e.g., {"type": "json_object"} for JSON mode.

None
output_format str

Output format for qwen-deep-research model. Options: "model_detailed_report" (default), "model_summary_report".

None
**kwargs Any

Additional parameters passed to the API.

{}

Returns:

Type Description
Union[GenerationResponse, Generator[GenerationResponse, None, None]]

Union[GenerationResponse, AsyncGenerator[GenerationResponse, None]]: If

Union[GenerationResponse, Generator[GenerationResponse, None, None]]

stream is True, return AsyncGenerator, else GenerationResponse.

Source code in dashscope/legacy_1x/aigc/generation.py
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
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
410
411
412
413
414
415
416
417
418
419
420
421
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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
@classmethod
async def call(  # type: ignore[override] # pylint: disable=arguments-renamed,too-many-branches,too-many-statements # noqa: E501
    # type: ignore[override]
    cls,
    model: str,
    prompt: Any = None,
    history: list = None,
    api_key: str = None,
    messages: List[Message] = None,
    plugins: Union[str, Dict[str, Any]] = None,
    workspace: str = None,
    stream: bool = None,
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    max_tokens: int = None,
    seed: int = None,
    stop: Union[str, List] = None,
    repetition_penalty: float = None,
    presence_penalty: float = None,
    result_format: str = None,
    incremental_output: bool = None,
    enable_search: bool = None,
    tools: List[Dict[str, Any]] = None,
    tool_choice: Union[str, Dict[str, Any]] = None,
    enable_thinking: bool = None,
    thinking_budget: int = None,
    n: int = None,
    logprobs: bool = None,
    top_logprobs: int = None,
    search_options: Dict[str, Any] = None,
    parallel_tool_calls: bool = None,
    response_format: Dict[str, Any] = None,
    output_format: str = None,
    **kwargs,
) -> Union[GenerationResponse, AsyncGenerator[GenerationResponse, None]]:
    """Call generation model service.

    Args:
        model (str): The requested model, such as qwen-turbo.
        prompt (Any): The input prompt.
        history (list): The user provided history, deprecated.
        api_key (str, optional): The api api_key, can be None.
        messages (list): The generation messages.
        plugins (Any): The plugin config, str or dict.
        workspace (str): The dashscope workspace id.
        stream (bool, optional): Enable streaming output.
        temperature (float, optional): Controls randomness, range [0, 2).
        top_p (float, optional): Nucleus sampling, range (0, 1.0].
        top_k (int, optional): Size of candidate token set for sampling.
        max_tokens (int, optional): Maximum output token count.
        seed (int, optional): Random seed for reproducibility.
        stop (str or list, optional): Stop sequences.
        repetition_penalty (float, optional): Penalizes repeated sequences.
        presence_penalty (float, optional): Controls content repetition.
        result_format (str, optional): "message" or "text".
        incremental_output (bool, optional): In streaming mode, output only
            new tokens (True) vs. cumulative output (False).
        enable_search (bool, optional): Enable web search.
        tools (list, optional): Tool definitions for function calling.
        tool_choice (str or dict, optional): Tool selection strategy.
        enable_thinking (bool, optional): Enable thinking mode.
        thinking_budget (int, optional): Maximum token budget for thinking
            mode. Controls the maximum length of thinking process.
        n (int, optional): Number of responses to generate (1-4).
        logprobs (bool, optional): Whether to return log probabilities of
            the output tokens.
        top_logprobs (int, optional): Number of most likely tokens to
            return at each token position when logprobs is enabled.
        search_options (dict, optional): Configuration options for web
            search feature.
        parallel_tool_calls (bool, optional): Enable parallel tool calls
            for function calling.
        response_format (dict, optional): Format constraint for response,
            e.g., {"type": "json_object"} for JSON mode.
        output_format (str, optional): Output format for qwen-deep-research
            model. Options: "model_detailed_report" (default),
            "model_summary_report".
        **kwargs: Additional parameters passed to the API.

    Returns:
        Union[GenerationResponse,
              AsyncGenerator[GenerationResponse, None]]: If
        stream is True, return AsyncGenerator, else GenerationResponse.
    """
    if (prompt is None or not prompt) and (
        messages is None or not messages
    ):
        raise InputRequired("prompt or messages is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    if stream is not None:
        kwargs["stream"] = stream
    if temperature is not None:
        kwargs["temperature"] = temperature
    if top_p is not None:
        kwargs["top_p"] = top_p
    if top_k is not None:
        kwargs["top_k"] = top_k
    if max_tokens is not None:
        kwargs["max_tokens"] = max_tokens
    if seed is not None:
        kwargs["seed"] = seed
    if stop is not None:
        kwargs["stop"] = stop
    if repetition_penalty is not None:
        kwargs["repetition_penalty"] = repetition_penalty
    if presence_penalty is not None:
        kwargs["presence_penalty"] = presence_penalty
    if result_format is not None:
        kwargs["result_format"] = result_format
    if incremental_output is not None:
        kwargs["incremental_output"] = incremental_output
    if enable_search is not None:
        kwargs["enable_search"] = enable_search
    if tools is not None:
        kwargs["tools"] = tools
    if tool_choice is not None:
        kwargs["tool_choice"] = tool_choice
    if enable_thinking is not None:
        kwargs["enable_thinking"] = enable_thinking
    if thinking_budget is not None:
        kwargs["thinking_budget"] = thinking_budget
    if n is not None:
        kwargs["n"] = n
    if logprobs is not None:
        kwargs["logprobs"] = logprobs
    if top_logprobs is not None:
        kwargs["top_logprobs"] = top_logprobs
    if search_options is not None:
        kwargs["search_options"] = search_options
    if parallel_tool_calls is not None:
        kwargs["parallel_tool_calls"] = parallel_tool_calls
    if response_format is not None:
        kwargs["response_format"] = response_format
    if output_format is not None:
        kwargs["output_format"] = output_format
    task_group, function = _get_task_group_and_task(__name__)
    if plugins is not None:
        headers = kwargs.pop("headers", {})
        if isinstance(plugins, str):
            headers["X-DashScope-Plugin"] = plugins
        else:
            headers["X-DashScope-Plugin"] = json.dumps(plugins)
        kwargs["headers"] = headers
    # pylint: disable=protected-access
    (
        input,  # pylint: disable=redefined-builtin
        parameters,
    ) = Generation._build_input_parameters(
        model,
        prompt,
        history,
        messages,
        **kwargs,
    )

    is_stream = parameters.get("stream", False)
    # Check if we need to merge incremental output
    is_incremental_output = kwargs.get("incremental_output", None)
    to_merge_incremental_output = False
    if (
        ParamUtil.should_modify_incremental_output(model)
        and is_stream
        and is_incremental_output is False
    ):
        to_merge_incremental_output = True
        parameters["incremental_output"] = True

    # Pass incremental_to_full flag via user_agent parameter
    flag = "1" if to_merge_incremental_output else "0"
    existing_ua = parameters.get("user_agent", "")
    new_ua = f"incremental_to_full/{flag}"
    parameters["user_agent"] = (
        f"{existing_ua}; {new_ua}".strip() if existing_ua else new_ua
    )

    response = await super().call(
        model=model,
        task_group=task_group,
        task=Generation.task,
        function=function,
        api_key=api_key,
        input=input,
        workspace=workspace,
        **parameters,
    )
    if is_stream:
        if to_merge_incremental_output:
            # Extract n parameter for merge logic
            n = parameters.get("n", 1)
            return cls._merge_generation_response(response, n)
        else:
            return cls._stream_responses(response)
    else:
        return GenerationResponse.from_api_response(response)

CodeGeneration

Bases: BaseApi

function class-attribute instance-attribute

function = 'generation'

API for AI-Generated Content(AIGC) models.

Models

tongyi_lingma_v1 class-attribute instance-attribute
tongyi_lingma_v1 = 'tongyi-lingma-v1'

Scenes

custom class-attribute instance-attribute
custom = 'custom'
nl2code class-attribute instance-attribute
nl2code = 'nl2code'
code2comment class-attribute instance-attribute
code2comment = 'code2comment'
code2explain class-attribute instance-attribute
code2explain = 'code2explain'
commit2msg class-attribute instance-attribute
commit2msg = 'commit2msg'
unit_test class-attribute instance-attribute
unit_test = 'unittest'
code_qa class-attribute instance-attribute
code_qa = 'codeqa'
nl2sql class-attribute instance-attribute
nl2sql = 'nl2sql'

call classmethod

call(
    model: str,
    scene: str = None,
    api_key: str = None,
    message: List[MessageParam] = None,
    workspace: str = None,
    **kwargs: Any
) -> Any

Call generation model service.

    Args:
        model (str): The requested model, such as tongyi-lingma-v1
        scene (str): Scene type, single choice, such as custom
            examples:
                custom:User defined prompt
                nl2code:Natural language generated code
                code2comment:annotation
                code2explain:explain
                commit2msg:Automatically generate commit
                uinttest:Generating Unit Tests
                codeqa:Code Q&A
                nl2sql:Generate SQL code using natural language
        api_key (str, optional): The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).
        message (list): The generation messages.
            scene == custom, examples:
                [{"role": "user", "content": "根据下面的功能描述生成一个python函数。代码的功能是计算给定路径下所有文件的总大小。"}]  # noqa E501  # pylint: disable=line-too-long
            scene == nl2code, examples:
                [{"role": "user", "content": "计算给定路径下所有文件的总大小"}, {"role": "attachment", "meta": {"language": "java"}}]  # noqa E501  # pylint: disable=line-too-long
            scene == code2comment, examples:
                [{"role": "user", "content": "1. 生成中文注释
  1. 仅生成代码部分,不需要额外解释函数功能 "}, {"role": "attachment", "meta": {"code": " @Override public CancelExportTaskResponse cancelExportTask( CancelExportTask cancelExportTask) { AmazonEC2SkeletonInterface ec2Service = ServiceProvider.getInstance().getServiceImpl(AmazonEC2SkeletonInterface.class); return ec2Service.cancelExportTask(cancelExportTask); }", "language": "java"}}] # noqa E501 # pylint: disable=line-too-long scene == code2explain, examples: [{"role": "user", "content": "要求不低于200字"}, {"role": "attachment", "meta": {"code": "@Override public int getHeaderCacheSize() { return 0; }

", "language": "java"}}] # noqa E501 # pylint: disable=line-too-long scene == commit2msg, examples: [{"role": "attachment", "meta": {"diff_list": [{"diff": "--- src/com/siondream/core/PlatformResolver.java +++ src/com/siondream/core/PlatformResolver.java @@ -1,11 +1,8 @@ package com.siondream.core; - -import com.badlogic.gdx.files.FileHandle;

public interface PlatformResolver { public void openURL(String url); public void rateApp(); public void sendFeedback(); - public FileHandle[] listFolder(String path); } ", "old_file_path": "src/com/siondream/core/PlatformResolver.java", "new_file_path": "src/com/siondream/core/PlatformResolver.java"}]}}] # noqa E501 # pylint: disable=line-too-long scene == unittest, examples: [{"role": "attachment", "meta": {"code": "public static TimestampMap parseTimestampMap(Class typeClass, String input, DateTimeZone timeZone) throws IllegalArgumentException { if (typeClass == null) { throw new IllegalArgumentException("typeClass required"); }

    if (input == null) {
        return null;
    }

    TimestampMap result;

    typeClass = AttributeUtils.getStandardizedType(typeClass);
    if (typeClass.equals(String.class)) {
        result = new TimestampStringMap();
    } else if (typeClass.equals(Byte.class)) {
        result = new TimestampByteMap();
    } else if (typeClass.equals(Short.class)) {
        result = new TimestampShortMap();
    } else if (typeClass.equals(Integer.class)) {
        result = new TimestampIntegerMap();
    } else if (typeClass.equals(Long.class)) {
        result = new TimestampLongMap();
    } else if (typeClass.equals(Float.class)) {
        result = new TimestampFloatMap();
    } else if (typeClass.equals(Double.class)) {
        result = new TimestampDoubleMap();
    } else if (typeClass.equals(Boolean.class)) {
        result = new TimestampBooleanMap();
    } else if (typeClass.equals(Character.class)) {
        result = new TimestampCharMap();
    } else {
        throw new IllegalArgumentException("Unsupported type " + typeClass.getClass().getCanonicalName());
    }

    if (input.equalsIgnoreCase(EMPTY_VALUE)) {
        return result;
    }

    StringReader reader = new StringReader(input + ' ');// Add 1 space so
                                                        // reader.skip
                                                        // function always
                                                        // works when
                                                        // necessary (end of
                                                        // string not
                                                        // reached).

    try {
        int r;
        char c;
        while ((r = reader.read()) != -1) {
            c = (char) r;
            switch (c) {
                case LEFT_BOUND_SQUARE_BRACKET:
                case LEFT_BOUND_BRACKET:
                    parseTimestampAndValue(typeClass, reader, result, timeZone);
                    break;
                default:
                    // Ignore other chars outside of bounds
            }
        }
    } catch (IOException ex) {
        throw new RuntimeException("Unexpected expection while parsing timestamps", ex);
    }

    return result;
}", "language": "java"}}]  # noqa E501  # pylint: disable=line-too-long
            scene == codeqa, examples:
                [{"role": "user", "content": "I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?

What I'm doing now: class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...]

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass

server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler) server.serve_forever()"}] # noqa E501 # pylint: disable=line-too-long scene == nl2sql, examples: [{"role": "user", "content": "小明的总分数是多少"}, {"role": "attachment", "meta": {"synonym_infos": {"学生姓名": "姓名|名字|名称", "学生分数": "分数|得分"}, "recall_infos": [{"content": "student_score.id='小明'", "score": "0.83"}], "schema_infos": [{"table_id": "student_score", "table_desc": "学生分数表", "columns": [{"col_name": "id", "col_caption": "学生id", "col_desc": "例值为:1,2,3", "col_type": "string"}, {"col_name": "name", "col_caption": "学生姓名", "col_desc": "例值为:张三,李四,小明", "col_type": "string"}, {"col_name": "score", "col_caption": "学生分数", "col_desc": "例值为:98,100,66", "col_type": "string"}]}]}}] # noqa E501 # pylint: disable=line-too-long workspace (str): The dashscope workspace id. **kwargs: n( int, optional ): The number of output results, currently only supports 1, with a default value of 1 # noqa E501

    Returns:
        Union[DashScopeAPIResponse,
              Generator[DashScopeAPIResponse, None, None]]: If
        stream is True, return Generator, otherwise DashScopeAPIResponse.
Source code in dashscope/legacy_1x/aigc/code_generation.py
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    scene: str = None,
    api_key: str = None,
    message: List[MessageParam] = None,
    workspace: str = None,
    **kwargs,
) -> Union[
    DashScopeAPIResponse,
    Generator[
        DashScopeAPIResponse,
        None,
        None,
    ],
]:
    """Call generation model service.

    Args:
        model (str): The requested model, such as tongyi-lingma-v1
        scene (str): Scene type, single choice, such as custom
            examples:
                custom:User defined prompt
                nl2code:Natural language generated code
                code2comment:annotation
                code2explain:explain
                commit2msg:Automatically generate commit
                uinttest:Generating Unit Tests
                codeqa:Code Q&A
                nl2sql:Generate SQL code using natural language
        api_key (str, optional): The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).
        message (list): The generation messages.
            scene == custom, examples:
                [{"role": "user", "content": "根据下面的功能描述生成一个python函数。代码的功能是计算给定路径下所有文件的总大小。"}]  # noqa E501  # pylint: disable=line-too-long
            scene == nl2code, examples:
                [{"role": "user", "content": "计算给定路径下所有文件的总大小"}, {"role": "attachment", "meta": {"language": "java"}}]  # noqa E501  # pylint: disable=line-too-long
            scene == code2comment, examples:
                [{"role": "user", "content": "1. 生成中文注释\n2. 仅生成代码部分,不需要额外解释函数功能\n"}, {"role": "attachment", "meta": {"code": "\t\t@Override\n\t\tpublic  CancelExportTaskResponse  cancelExportTask(\n\t\t\t\tCancelExportTask  cancelExportTask)  {\n\t\t\tAmazonEC2SkeletonInterface  ec2Service  =  ServiceProvider.getInstance().getServiceImpl(AmazonEC2SkeletonInterface.class);\n\t\t\treturn  ec2Service.cancelExportTask(cancelExportTask);\n\t\t}", "language": "java"}}]  # noqa E501  # pylint: disable=line-too-long
            scene == code2explain, examples:
                [{"role": "user", "content": "要求不低于200字"}, {"role": "attachment", "meta": {"code": "@Override\n                                public  int  getHeaderCacheSize()\n                                {\n                                        return  0;\n                                }\n\n", "language": "java"}}]  # noqa E501  # pylint: disable=line-too-long
            scene == commit2msg, examples:
                [{"role": "attachment", "meta": {"diff_list": [{"diff": "--- src/com/siondream/core/PlatformResolver.java\n+++ src/com/siondream/core/PlatformResolver.java\n@@ -1,11 +1,8 @@\npackage com.siondream.core;\n-\n-import com.badlogic.gdx.files.FileHandle;\n\npublic interface PlatformResolver {\npublic void openURL(String url);\npublic void rateApp();\npublic void sendFeedback();\n-\tpublic FileHandle[] listFolder(String path);\n}\n", "old_file_path": "src/com/siondream/core/PlatformResolver.java", "new_file_path": "src/com/siondream/core/PlatformResolver.java"}]}}]  # noqa E501  # pylint: disable=line-too-long
            scene == unittest, examples:
                [{"role": "attachment", "meta": {"code": "public static <T> TimestampMap<T> parseTimestampMap(Class<T> typeClass, String input, DateTimeZone timeZone) throws IllegalArgumentException {\n        if (typeClass == null) {\n            throw new IllegalArgumentException(\"typeClass required\");\n        }\n\n        if (input == null) {\n            return null;\n        }\n\n        TimestampMap result;\n\n        typeClass = AttributeUtils.getStandardizedType(typeClass);\n        if (typeClass.equals(String.class)) {\n            result = new TimestampStringMap();\n        } else if (typeClass.equals(Byte.class)) {\n            result = new TimestampByteMap();\n        } else if (typeClass.equals(Short.class)) {\n            result = new TimestampShortMap();\n        } else if (typeClass.equals(Integer.class)) {\n            result = new TimestampIntegerMap();\n        } else if (typeClass.equals(Long.class)) {\n            result = new TimestampLongMap();\n        } else if (typeClass.equals(Float.class)) {\n            result = new TimestampFloatMap();\n        } else if (typeClass.equals(Double.class)) {\n            result = new TimestampDoubleMap();\n        } else if (typeClass.equals(Boolean.class)) {\n            result = new TimestampBooleanMap();\n        } else if (typeClass.equals(Character.class)) {\n            result = new TimestampCharMap();\n        } else {\n            throw new IllegalArgumentException(\"Unsupported type \" + typeClass.getClass().getCanonicalName());\n        }\n\n        if (input.equalsIgnoreCase(EMPTY_VALUE)) {\n            return result;\n        }\n\n        StringReader reader = new StringReader(input + ' ');// Add 1 space so\n                                                            // reader.skip\n                                                            // function always\n                                                            // works when\n                                                            // necessary (end of\n                                                            // string not\n                                                            // reached).\n\n        try {\n            int r;\n            char c;\n            while ((r = reader.read()) != -1) {\n                c = (char) r;\n                switch (c) {\n                    case LEFT_BOUND_SQUARE_BRACKET:\n                    case LEFT_BOUND_BRACKET:\n                        parseTimestampAndValue(typeClass, reader, result, timeZone);\n                        break;\n                    default:\n                        // Ignore other chars outside of bounds\n                }\n            }\n        } catch (IOException ex) {\n            throw new RuntimeException(\"Unexpected expection while parsing timestamps\", ex);\n        }\n\n        return result;\n    }", "language": "java"}}]  # noqa E501  # pylint: disable=line-too-long
            scene == codeqa, examples:
                [{"role": "user", "content": "I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?\nWhat I'm doing now:\nclass MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n  def doGET\n  [...]\n\nclass ThreadingHTTPServer(ThreadingMixIn, HTTPServer): \n    pass\n\nserver = ThreadingHTTPServer(('localhost', 80), MyRequestHandler)\nserver.serve_forever()"}]  # noqa E501  # pylint: disable=line-too-long
            scene == nl2sql, examples:
                [{"role": "user", "content": "小明的总分数是多少"}, {"role": "attachment", "meta": {"synonym_infos": {"学生姓名": "姓名|名字|名称", "学生分数": "分数|得分"}, "recall_infos": [{"content": "student_score.id='小明'", "score": "0.83"}], "schema_infos": [{"table_id": "student_score", "table_desc": "学生分数表", "columns": [{"col_name": "id", "col_caption": "学生id", "col_desc": "例值为:1,2,3", "col_type": "string"}, {"col_name": "name", "col_caption": "学生姓名", "col_desc": "例值为:张三,李四,小明", "col_type": "string"}, {"col_name": "score", "col_caption": "学生分数", "col_desc": "例值为:98,100,66", "col_type": "string"}]}]}}]  # noqa E501  # pylint: disable=line-too-long
        workspace (str): The dashscope workspace id.
        **kwargs:
            n(
                int,
                `optional`
            ): The number of output results, currently only supports 1, with a default value of 1  # noqa E501

    Returns:
        Union[DashScopeAPIResponse,
              Generator[DashScopeAPIResponse, None, None]]: If
        stream is True, return Generator, otherwise DashScopeAPIResponse.
    """
    if (scene is None or not scene) or (message is None or not message):
        raise InputRequired("scene and message is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    task_group, task = _get_task_group_and_task(__name__)
    (
        input,  # pylint: disable=redefined-builtin
        parameters,
    ) = cls._build_input_parameters(
        model,
        scene,
        message,
        **kwargs,
    )
    response = super().call(
        model=model,
        task_group=task_group,
        task=task,
        function=CodeGeneration.function,
        api_key=api_key,
        input=input,
        workspace=workspace,
        is_service=False,
        **parameters,
    )

    is_stream = kwargs.get("stream", False)
    if is_stream:
        return (rsp for rsp in response)
    else:
        return response

Conversation

Conversation(history: History | None = None)

Bases: BaseApi

Conversational robot interface.

Init a chat.

Parameters:

Name Type Description Default
history dict

The conversation initialization settings. will be recorded in the system history list. Defaults to None.

None
Source code in dashscope/legacy_1x/aigc/conversation.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def __init__(self, history: History = None) -> None:
    """Init a chat.

    Args:
        history (dict): The conversation initialization settings.
            will be recorded in the system history list.
            Defaults to None.
    """
    super().__init__()
    if history is None:
        self.history = History()
    else:
        logger.warning(DEPRECATED_MESSAGE)
        self.history = history  # type: ignore[has-type]

task class-attribute instance-attribute

task = 'generation'

history instance-attribute

history = History()

Models

@deprecated, use qwen_turbo instead

qwen_v1 class-attribute instance-attribute
qwen_v1 = 'qwen-v1'

@deprecated, use qwen_plus instead

qwen_plus_v1 class-attribute instance-attribute
qwen_plus_v1 = 'qwen-plus-v1'
qwen_turbo class-attribute instance-attribute
qwen_turbo = 'qwen-turbo'
qwen_plus class-attribute instance-attribute
qwen_plus = 'qwen-plus'
qwen_max class-attribute instance-attribute
qwen_max = 'qwen-max'

call

call(
    model: str,
    prompt: Any = None,
    history: History | None = None,
    auto_history: bool = False,
    n_history: int = -1,
    api_key: str = None,
    messages: List[Message] = None,
    plugins: Union[str, Dict[str, Any]] = None,
    workspace: str = None,
    **kwargs: Any
) -> Union[
    ConversationResponse,
    Generator[ConversationResponse, None, None],
]

Call conversational robot generator a response.

Note: This method overrides BaseApi.call() as an instance method instead of a classmethod because Conversation maintains instance state (self.history). Pylint's arguments-renamed warning is disabled because the first parameter changes from 'cls' (in the classmethod) to 'self' (in the instance method). The type checker is instructed to ignore the signature incompatibility via type: ignore[override].

Parameters:

Name Type Description Default
model str

The request model.

required
prompt Any

The input prompt.

None
history History

The user provided history. Only works for this call, will not be recorded in the system history list. The history and auto_history are mutually exclusive. Default to None.

None
auto_history bool

Call with the automatically maintenance conversation history list. The history and auto_history are mutually exclusive.

False
n_history int

Number of latest history in conversation, -1 all history. Default to -1

-1
api_key str

The api api_key, if not present, will get by default rule(TODO: api key doc). Defaults to None.

None
messages list

The generation messages. examples: [{'role': 'user', 'content': 'The weather is fine today.'}, {'role': 'assistant', 'content': 'Suitable for outings'}]

None
plugins Any

The plugin config, Can be plugins config str, or dict.

None
**kwargs (qwen - turbo, qwen - plus)

stream(bool, optional): Enable server-sent events (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) # noqa E501 # pylint: disable=line-too-long the result will back partially. temperature(float, optional): Used to control the degree of randomness and diversity. Specifically, the temperature value controls the degree to which the probability distribution of each candidate word is smoothed when generating text. A higher temperature value will reduce the peak value of the probability, allowing more low-probability words to be selected, and the generated results will be more diverse; while a lower temperature value will enhance the peak value of the probability, making it easier for high-probability words to be selected, the generated results are more deterministic,range(0, 2) .[qwen-turbo,qwen-plus]. top_p(float, optional): A sampling strategy, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. top_k(int, optional): The size of the sample candidate set when generated. # noqa E501 # pylint: disable=line-too-long For example, when the value is 50, only the 50 highest-scoring tokens # noqa E501 # pylint: disable=line-too-long in a single generation form a randomly sampled candidate set. # noqa E501 The larger the value, the higher the randomness generated; # noqa E501 the smaller the value, the higher the certainty generated. # noqa E501 The default value is 0, which means the top_k policy is # noqa E501 not enabled. At this time, only the top_p policy takes effect. # noqa E501 enable_search(bool, optional): Whether to enable web search(quark). # noqa E501 Currently works best only on the first round of conversation. Default to False, support model: [qwen-turbo]. customized_model_id(str, required) The enterprise-specific large model id, which needs to be generated from the operation background of the enterprise-specific large model product, support model: [bailian-v1]. result_format(str, optional): [message|text] Set result result format. # noqa E501 Default result is text incremental_output(bool, optional): Used to control the streaming output mode. # noqa E501 # pylint: disable=line-too-long If true, the subsequent output will include the previously input content. # noqa E501 # pylint: disable=line-too-long Otherwise, the subsequent output will not include the previously output # noqa E501 # pylint: disable=line-too-long content. Default false. stop(list[str] or list[list[int]], optional): Used to control the generation to stop # noqa E501 # pylint: disable=line-too-long when encountering setting str or token ids, the result will not include # noqa E501 # pylint: disable=line-too-long stop words or tokens. max_tokens(int, optional): The maximum token num expected to be output. It should be # noqa E501 # pylint: disable=line-too-long noted that the length generated by the model will only be less than max_tokens, # noqa E501 # pylint: disable=line-too-long not necessarily equal to it. If max_tokens is set too large, the service will # noqa E501 # pylint: disable=line-too-long directly prompt that the length exceeds the limit. It is generally # noqa E501 not recommended to set this value. repetition_penalty(float, optional): Used to control the repeatability when generating models. # noqa E501 # pylint: disable=line-too-long Increasing repetition_penalty can reduce the duplication of model generation. # noqa E501 # pylint: disable=line-too-long 1.0 means no punishment.

{}
workspace str

The dashscope workspace id.

None

Raises: InputRequired: The prompt cannot be empty. InvalidInput: The history and auto_history are mutually exclusive.

Returns:

Type Description
Union[ConversationResponse, Generator[ConversationResponse, None, None]]

Union[ConversationResponse, Generator[ConversationResponse, None, None]]: If

Union[ConversationResponse, Generator[ConversationResponse, None, None]]

stream is True, return Generator, otherwise ConversationResponse.

Source code in dashscope/legacy_1x/aigc/conversation.py
145
146
147
148
149
150
151
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
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
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
292
293
294
def call(  # type: ignore[override]
    self,
    model: str,
    prompt: Any = None,
    history: History = None,
    auto_history: bool = False,
    n_history: int = -1,
    api_key: str = None,
    messages: List[Message] = None,
    plugins: Union[str, Dict[str, Any]] = None,
    workspace: str = None,
    **kwargs,
) -> Union[
    ConversationResponse,
    Generator[
        ConversationResponse,
        None,
        None,
    ],
]:
    """Call conversational robot generator a response.

    Note: This method overrides BaseApi.call() as an instance method
    instead of a classmethod because Conversation maintains instance
    state (self.history). Pylint's arguments-renamed warning is
    disabled because the first parameter changes from 'cls' (in the
    classmethod) to 'self' (in the instance method). The type
    checker is instructed to ignore the signature incompatibility
    via type: ignore[override].

    Args:
        model (str): The request model.
        prompt (Any): The input prompt.
        history(History): The user provided history.
            Only works for this call, will not be recorded in the
            system history list. The ``history`` and ``auto_history``
            are mutually exclusive. Default to None.
        auto_history (bool): Call with the automatically maintenance
            conversation history list. The ``history`` and ``auto_history``
            are mutually exclusive.
        n_history (int): Number of latest history in conversation,
            -1 all history. Default to -1
        api_key (str, optional): The api api_key, if not present,
            will get by default rule(TODO: api key doc). Defaults to None.
        messages (list): The generation messages.
            examples:
                [{'role': 'user',
                  'content': 'The weather is fine today.'},
                  {'role': 'assistant', 'content': 'Suitable for outings'}]
        plugins (Any): The plugin config, Can be plugins config str, or dict.
        **kwargs(qwen-turbo, qwen-plus):
            stream(bool, `optional`): Enable server-sent events
                (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)  # noqa E501  # pylint: disable=line-too-long
                the result will back partially.
            temperature(float, `optional`): Used to control the degree
                of randomness and diversity. Specifically, the temperature
                value controls the degree to which the probability distribution
                of each candidate word is smoothed when generating text.
                A higher temperature value will reduce the peak value of
                the probability, allowing more low-probability words to be
                selected, and the generated results will be more diverse;
                while a lower temperature value will enhance the peak value
                of the probability, making it easier for high-probability
                words to be selected, the generated results are more
                deterministic,range(0, 2) .[qwen-turbo,qwen-plus].
            top_p(float, `optional`): A sampling strategy, called nucleus
                sampling, where the model considers the results of the
                tokens with top_p probability mass. So 0.1 means only
                the tokens comprising the top 10% probability mass are
                considered.
            top_k(int, `optional`): The size of the sample candidate set when generated.  # noqa E501  # pylint: disable=line-too-long
                For example, when the value is 50, only the 50 highest-scoring tokens  # noqa E501  # pylint: disable=line-too-long
                in a single generation form a randomly sampled candidate set. # noqa E501
                The larger the value, the higher the randomness generated;  # noqa E501
                the smaller the value, the higher the certainty generated. # noqa E501
                The default value is 0, which means the top_k policy is  # noqa E501
                not enabled. At this time, only the top_p policy takes effect. # noqa E501
            enable_search(bool, `optional`): Whether to enable web search(quark).  # noqa E501
                Currently works best only on the first round of conversation.
                Default to False, support model: [qwen-turbo].
            customized_model_id(str, required) The enterprise-specific
                large model id, which needs to be generated from the
                operation background of the enterprise-specific
                large model product, support model: [bailian-v1].
            result_format(str, `optional`): [message|text] Set result result format. # noqa E501
                Default result is text
            incremental_output(bool, `optional`): Used to control the streaming output mode. # noqa E501  # pylint: disable=line-too-long
                If true, the subsequent output will include the previously input content. # noqa E501  # pylint: disable=line-too-long
                Otherwise, the subsequent output will not include the previously output # noqa E501  # pylint: disable=line-too-long
                content. Default false.
            stop(list[str] or list[list[int]], `optional`): Used to control the generation to stop  # noqa E501  # pylint: disable=line-too-long
                when encountering setting str or token ids, the result will not include # noqa E501  # pylint: disable=line-too-long
                stop words or tokens.
            max_tokens(int, `optional`): The maximum token num expected to be output. It should be # noqa E501  # pylint: disable=line-too-long
                noted that the length generated by the model will only be less than max_tokens,  # noqa E501  # pylint: disable=line-too-long
                not necessarily equal to it. If max_tokens is set too large, the service will # noqa E501  # pylint: disable=line-too-long
                directly prompt that the length exceeds the limit. It is generally # noqa E501
                not recommended to set this value.
            repetition_penalty(float, `optional`): Used to control the repeatability when generating models.  # noqa E501  # pylint: disable=line-too-long
                Increasing repetition_penalty can reduce the duplication of model generation.  # noqa E501  # pylint: disable=line-too-long
                1.0 means no punishment.
        workspace (str): The dashscope workspace id.
    Raises:
        InputRequired: The prompt cannot be empty.
        InvalidInput: The history and auto_history are mutually exclusive.

    Returns:
        Union[ConversationResponse,
              Generator[ConversationResponse, None, None]]: If
        stream is True, return Generator, otherwise ConversationResponse.

    """
    if (prompt is None or not prompt) and (
        (messages is None or not messages)
    ):
        raise InputRequired("prompt or messages is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    task_group, _ = _get_task_group_and_task(__name__)
    if plugins is not None:
        headers = kwargs.pop("headers", {})
        if isinstance(plugins, str):
            headers["X-DashScope-Plugin"] = plugins
        else:
            headers["X-DashScope-Plugin"] = json.dumps(plugins)
        kwargs["headers"] = headers
    (
        input,  # pylint: disable=redefined-builtin
        parameters,
    ) = self._build_input_parameters(
        model,
        prompt,
        history,
        auto_history,
        n_history,
        messages,
        **kwargs,
    )
    response = super().call(
        model=model,
        task_group=task_group,
        task="text-generation",
        function="generation",
        api_key=api_key,
        input=input,
        workspace=workspace,
        **parameters,
    )
    is_stream = kwargs.get("stream", False)
    return self._handle_response(prompt, response, is_stream)

History

History(items: List[HistoryItem] = None)

Bases: list

Manage the conversation history.

Init a history with list of HistoryItems.

Parameters:

Name Type Description Default
items List[HistoryItem]

The history items. Defaults to None.

None
Source code in dashscope/legacy_1x/aigc/conversation.py
64
65
66
67
68
69
70
71
72
73
74
75
def __init__(self, items: List[HistoryItem] = None):
    """Init a history with list of HistoryItems.

    Args:
        items (List[HistoryItem], optional): The history items.
            Defaults to None.
    """
    if items is not None:
        logger.warning(DEPRECATED_MESSAGE)
        list.__init__(self, items)
    else:
        list.__init__(self, [])

HistoryItem

HistoryItem(role: str, text: str = None, **kwargs)

Bases: dict

A conversation history item.

Init a history item.

Parameters:

Name Type Description Default
role str

The role name.

required
text str

The text history. Default ot None.

None
**kwargs Any

The key/value pair of history content.

{}

Raises:

Type Description
InvalidInput

The key and value must pair.

Source code in dashscope/legacy_1x/aigc/conversation.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def __init__(self, role: str, text: str = None, **kwargs):
    """Init a history item.

    Args:
        role (str): The role name.
        text (str): The text history. Default ot None.
        **kwargs (Any): The key/value pair of history content.

    Raises:
        InvalidInput: The key and value must pair.
    """
    logger.warning(DEPRECATED_MESSAGE)
    self.role = role
    dict.__init__(self, {role: []})
    if text is not None:
        self[self.role].append({"text": text})
    for k, v in kwargs.items():
        self[self.role].append({k: v})

role instance-attribute

role = role

add

add(key: str, content: Any)

Add a key/value to history.

Parameters:

Name Type Description Default
key str

The key of the content.

required
content Any

The history content.

required
Source code in dashscope/legacy_1x/aigc/conversation.py
51
52
53
54
55
56
57
58
def add(self, key: str, content: Any):
    """Add a key/value to history.

    Args:
        key (str): The key of the content.
        content (Any): The history content.
    """
    self[self.role].append({key: content})

Multimodal conversation

MultiModalConversation

Bases: BaseApi

MultiModal conversational robot interface.

task class-attribute instance-attribute

task = 'multimodal-generation'

function class-attribute instance-attribute

function = 'generation'

Models

qwen_vl_chat_v1 class-attribute instance-attribute
qwen_vl_chat_v1 = 'qwen-vl-chat-v1'

call classmethod

call(
    model: str,
    messages: List[Any] | None = None,
    api_key: str | None = None,
    workspace: str | None = None,
    text: str | None = None,
    voice: str | None = None,
    language_type: str = None,
    stream: bool | None = None,
    temperature: float | None = None,
    top_p: float | None = None,
    top_k: int | None = None,
    max_tokens: int | None = None,
    seed: int | None = None,
    stop: Union[str, List[str], None] = None,
    repetition_penalty: float = None,
    presence_penalty: float = None,
    result_format: str | None = None,
    incremental_output: bool | None = None,
    enable_search: bool | None = None,
    tools: List[Dict[str, Any]] | None = None,
    tool_choice: Union[str, Dict[str, Any], None] = None,
    enable_thinking: bool | None = None,
    n: int | None = None,
    ocr_options: Dict[str, Any] | None = None,
    logprobs: bool | None = None,
    top_logprobs: int | None = None,
    **kwargs: Any
) -> Union[
    MultiModalConversationResponse,
    Generator[MultiModalConversationResponse, None, None],
]

Call the conversation model service.

Parameters:

Name Type Description Default
model str

The requested model, such as 'qwen-vl-max'.

required
messages list

The generation messages.

None
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
text str

The text to generate.

None
voice str

The voice name for qwen tts.

None
language_type str

The synthesized language type.

None
stream bool

Enable streaming output.

None
temperature float

Controls randomness, range [0, 2).

None
top_p float

Nucleus sampling, range (0, 1.0].

None
top_k int

Size of candidate token set for sampling.

None
max_tokens int

Maximum output token count.

None
seed int

Random seed for reproducibility.

None
stop str or list

Stop sequences.

None
repetition_penalty float

Penalizes repeated sequences.

None
presence_penalty float

Controls content repetition.

None
result_format str

"message" or "text".

None
incremental_output bool

In streaming mode, output only new tokens (True) vs. cumulative output (False).

None
enable_search bool

Enable web search.

None
tools list

Tool definitions for function calling.

None
tool_choice str or dict

Tool selection strategy.

None
enable_thinking bool

Enable thinking mode.

None
n int

Number of responses to generate (1-4).

None
ocr_options dict

OCR task options for qwen-ocr models.

None
logprobs bool

Whether to return log probabilities of the output tokens.

None
top_logprobs int

Number of most likely tokens to return at each token position.

None
**kwargs Any

Additional parameters passed to the API.

{}

Returns:

Type Description
Union[MultiModalConversationResponse, Generator[MultiModalConversationResponse, None, None]]

Union[MultiModalConversationResponse, Generator[MultiModalConversationResponse, None, None]]: If

Union[MultiModalConversationResponse, Generator[MultiModalConversationResponse, None, None]]

stream is True, return Generator, otherwise

Source code in dashscope/legacy_1x/aigc/multimodal_conversation.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
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
@classmethod
# type: ignore
def call(  # pylint: disable=arguments-renamed,too-many-branches,too-many-statements  # noqa: E501
    cls,
    model: str,
    messages: List = None,
    api_key: str = None,
    workspace: str = None,
    text: str = None,
    voice: str = None,
    language_type: str = None,
    stream: bool = None,
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    max_tokens: int = None,
    seed: int = None,
    stop: Union[str, List] = None,
    repetition_penalty: float = None,
    presence_penalty: float = None,
    result_format: str = None,
    incremental_output: bool = None,
    enable_search: bool = None,
    tools: List[Dict[str, Any]] = None,
    tool_choice: Union[str, Dict[str, Any]] = None,
    enable_thinking: bool = None,
    n: int = None,
    ocr_options: Dict[str, Any] = None,
    logprobs: bool = None,
    top_logprobs: int = None,
    **kwargs,
) -> Union[
    MultiModalConversationResponse,
    Generator[
        MultiModalConversationResponse,
        None,
        None,
    ],
]:
    """Call the conversation model service.

    Args:
        model (str): The requested model, such as 'qwen-vl-max'.
        messages (list): The generation messages.
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        text (str): The text to generate.
        voice (str): The voice name for qwen tts.
        language_type (str): The synthesized language type.
        stream (bool, optional): Enable streaming output.
        temperature (float, optional): Controls randomness, range [0, 2).
        top_p (float, optional): Nucleus sampling, range (0, 1.0].
        top_k (int, optional): Size of candidate token set for sampling.
        max_tokens (int, optional): Maximum output token count.
        seed (int, optional): Random seed for reproducibility.
        stop (str or list, optional): Stop sequences.
        repetition_penalty (float, optional): Penalizes repeated sequences.
        presence_penalty (float, optional): Controls content repetition.
        result_format (str, optional): "message" or "text".
        incremental_output (bool, optional): In streaming mode, output only
            new tokens (True) vs. cumulative output (False).
        enable_search (bool, optional): Enable web search.
        tools (list, optional): Tool definitions for function calling.
        tool_choice (str or dict, optional): Tool selection strategy.
        enable_thinking (bool, optional): Enable thinking mode.
        n (int, optional): Number of responses to generate (1-4).
        ocr_options (dict, optional): OCR task options for qwen-ocr models.
        logprobs (bool, optional): Whether to return log probabilities of
            the output tokens.
        top_logprobs (int, optional): Number of most likely tokens to
            return at each token position.
        **kwargs: Additional parameters passed to the API.

    Returns:
        Union[MultiModalConversationResponse,
              Generator[MultiModalConversationResponse, None, None]]: If
        stream is True, return Generator, otherwise
    """
    if stream is not None:
        kwargs["stream"] = stream
    if temperature is not None:
        kwargs["temperature"] = temperature
    if top_p is not None:
        kwargs["top_p"] = top_p
    if top_k is not None:
        kwargs["top_k"] = top_k
    if max_tokens is not None:
        kwargs["max_tokens"] = max_tokens
    if seed is not None:
        kwargs["seed"] = seed
    if stop is not None:
        kwargs["stop"] = stop
    if repetition_penalty is not None:
        kwargs["repetition_penalty"] = repetition_penalty
    if presence_penalty is not None:
        kwargs["presence_penalty"] = presence_penalty
    if result_format is not None:
        kwargs["result_format"] = result_format
    if incremental_output is not None:
        kwargs["incremental_output"] = incremental_output
    if enable_search is not None:
        kwargs["enable_search"] = enable_search
    if tools is not None:
        kwargs["tools"] = tools
    if tool_choice is not None:
        kwargs["tool_choice"] = tool_choice
    if enable_thinking is not None:
        kwargs["enable_thinking"] = enable_thinking
    if n is not None:
        kwargs["n"] = n
    if ocr_options is not None:
        kwargs["ocr_options"] = ocr_options
    if logprobs is not None:
        kwargs["logprobs"] = logprobs
    if top_logprobs is not None:
        kwargs["top_logprobs"] = top_logprobs
    if model is None or not model:
        raise ModelRequired("Model is required!")
    task_group, _ = _get_task_group_and_task(__name__)
    input = {}  # pylint: disable=redefined-builtin
    msg_copy = None

    if messages is not None and messages:
        msg_copy = copy.deepcopy(messages)
        has_upload = cls._preprocess_messages(model, msg_copy, api_key)
        if has_upload:
            headers = kwargs.pop("headers", {})
            headers["X-DashScope-OssResourceResolve"] = "enable"
            kwargs["headers"] = headers

    if text is not None and text:
        input.update({"text": text})
    if voice is not None and voice:
        input.update({"voice": voice})
    if language_type is not None and language_type:
        input.update({"language_type": language_type})
    if msg_copy is not None:
        input.update({"messages": msg_copy})  # type: ignore

    # Validate input is not empty before sending request
    if not input:
        raise ValueError(
            "Input data is required. Please provide at least one of: "
            "messages, text, voice, or language_type.",
        )

    # Check if we need to merge incremental output
    is_incremental_output = kwargs.get("incremental_output", None)
    to_merge_incremental_output = False
    is_stream = kwargs.get("stream", False)
    if (
        ParamUtil.should_modify_incremental_output(model)
        and is_stream
        and is_incremental_output is not None
        and is_incremental_output is False
    ):
        to_merge_incremental_output = True
        kwargs["incremental_output"] = True

    # Pass incremental_to_full flag via user_agent parameter
    flag = "1" if to_merge_incremental_output else "0"
    existing_ua = kwargs.get("user_agent", "")
    new_ua = f"incremental_to_full/{flag}"
    kwargs["user_agent"] = (
        f"{existing_ua}; {new_ua}".strip() if existing_ua else new_ua
    )

    response = super().call(
        model=model,
        task_group=task_group,
        task=MultiModalConversation.task,
        function=MultiModalConversation.function,
        api_key=api_key,
        input=input,
        workspace=workspace,
        **kwargs,
    )
    if is_stream:
        if to_merge_incremental_output:
            # Extract n parameter for merge logic
            n = kwargs.get("n", 1)
            return cls._merge_multimodal_response(response, n)
        else:
            return (
                MultiModalConversationResponse.from_api_response(rsp)
                for rsp in response
            )
    else:
        return MultiModalConversationResponse.from_api_response(response)

AioMultiModalConversation

Bases: BaseAioApi

Async MultiModal conversational robot interface.

task class-attribute instance-attribute

task = 'multimodal-generation'

function class-attribute instance-attribute

function = 'generation'

Models

qwen_vl_chat_v1 class-attribute instance-attribute
qwen_vl_chat_v1 = 'qwen-vl-chat-v1'

call async classmethod

call(
    model: str,
    messages: List[Any] | None = None,
    api_key: str | None = None,
    workspace: str | None = None,
    text: str = None,
    voice: str = None,
    language_type: str = None,
    stream: bool = None,
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    max_tokens: int = None,
    seed: int = None,
    stop: Union[str, List] = None,
    repetition_penalty: float = None,
    presence_penalty: float = None,
    result_format: str = None,
    incremental_output: bool = None,
    enable_search: bool = None,
    tools: List[Dict[str, Any]] = None,
    tool_choice: Union[str, Dict[str, Any]] = None,
    enable_thinking: bool = None,
    n: int = None,
    ocr_options: Dict[str, Any] = None,
    logprobs: bool = None,
    top_logprobs: int = None,
    **kwargs: Any
) -> Union[
    MultiModalConversationResponse,
    Generator[MultiModalConversationResponse, None, None],
]

Call the conversation model service asynchronously.

Parameters:

Name Type Description Default
model str

The requested model, such as 'qwen-vl-max'.

required
messages list

The generation messages.

None
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
text str

The text to generate.

None
voice str

The voice name for qwen tts.

None
language_type str

The synthesized language type.

None
stream bool

Enable streaming output.

None
temperature float

Controls randomness, range [0, 2).

None
top_p float

Nucleus sampling, range (0, 1.0].

None
top_k int

Size of candidate token set for sampling.

None
max_tokens int

Maximum output token count.

None
seed int

Random seed for reproducibility.

None
stop str or list

Stop sequences.

None
repetition_penalty float

Penalizes repeated sequences.

None
presence_penalty float

Controls content repetition.

None
result_format str

"message" or "text".

None
incremental_output bool

In streaming mode, output only new tokens (True) vs. cumulative output (False).

None
enable_search bool

Enable web search.

None
tools list

Tool definitions for function calling.

None
tool_choice str or dict

Tool selection strategy.

None
enable_thinking bool

Enable thinking mode.

None
n int

Number of responses to generate (1-4).

None
ocr_options dict

OCR task options for qwen-ocr models.

None
logprobs bool

Whether to return log probabilities of the output tokens.

None
top_logprobs int

Number of most likely tokens to return at each token position.

None
**kwargs Any

Additional parameters passed to the API.

{}

Returns:

Type Description
Union[MultiModalConversationResponse, Generator[MultiModalConversationResponse, None, None]]

Union[MultiModalConversationResponse, AsyncGenerator[MultiModalConversationResponse, None]]: If

Union[MultiModalConversationResponse, Generator[MultiModalConversationResponse, None, None]]

stream is True, return AsyncGenerator, otherwise

Source code in dashscope/legacy_1x/aigc/multimodal_conversation.py
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
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
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
410
411
412
413
414
415
416
417
418
419
420
421
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
@classmethod  # type: ignore
async def call(  # pylint: disable=arguments-renamed,too-many-branches,too-many-statements  # noqa: E501
    cls,
    model: str,
    messages: List = None,
    api_key: str = None,
    workspace: str = None,
    text: str = None,
    voice: str = None,
    language_type: str = None,
    stream: bool = None,
    temperature: float = None,
    top_p: float = None,
    top_k: int = None,
    max_tokens: int = None,
    seed: int = None,
    stop: Union[str, List] = None,
    repetition_penalty: float = None,
    presence_penalty: float = None,
    result_format: str = None,
    incremental_output: bool = None,
    enable_search: bool = None,
    tools: List[Dict[str, Any]] = None,
    tool_choice: Union[str, Dict[str, Any]] = None,
    enable_thinking: bool = None,
    n: int = None,
    ocr_options: Dict[str, Any] = None,
    logprobs: bool = None,
    top_logprobs: int = None,
    **kwargs,
) -> Union[
    MultiModalConversationResponse,
    AsyncGenerator[
        MultiModalConversationResponse,
        None,
    ],
]:
    """Call the conversation model service asynchronously.

    Args:
        model (str): The requested model, such as 'qwen-vl-max'.
        messages (list): The generation messages.
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        text (str): The text to generate.
        voice (str): The voice name for qwen tts.
        language_type (str): The synthesized language type.
        stream (bool, optional): Enable streaming output.
        temperature (float, optional): Controls randomness, range [0, 2).
        top_p (float, optional): Nucleus sampling, range (0, 1.0].
        top_k (int, optional): Size of candidate token set for sampling.
        max_tokens (int, optional): Maximum output token count.
        seed (int, optional): Random seed for reproducibility.
        stop (str or list, optional): Stop sequences.
        repetition_penalty (float, optional): Penalizes repeated sequences.
        presence_penalty (float, optional): Controls content repetition.
        result_format (str, optional): "message" or "text".
        incremental_output (bool, optional): In streaming mode, output only
            new tokens (True) vs. cumulative output (False).
        enable_search (bool, optional): Enable web search.
        tools (list, optional): Tool definitions for function calling.
        tool_choice (str or dict, optional): Tool selection strategy.
        enable_thinking (bool, optional): Enable thinking mode.
        n (int, optional): Number of responses to generate (1-4).
        ocr_options (dict, optional): OCR task options for qwen-ocr models.
        logprobs (bool, optional): Whether to return log probabilities of
            the output tokens.
        top_logprobs (int, optional): Number of most likely tokens to
            return at each token position.
        **kwargs: Additional parameters passed to the API.

    Returns:
        Union[MultiModalConversationResponse,
              AsyncGenerator[MultiModalConversationResponse, None]]: If
        stream is True, return AsyncGenerator, otherwise
    """
    if stream is not None:
        kwargs["stream"] = stream
    if temperature is not None:
        kwargs["temperature"] = temperature
    if top_p is not None:
        kwargs["top_p"] = top_p
    if top_k is not None:
        kwargs["top_k"] = top_k
    if max_tokens is not None:
        kwargs["max_tokens"] = max_tokens
    if seed is not None:
        kwargs["seed"] = seed
    if stop is not None:
        kwargs["stop"] = stop
    if repetition_penalty is not None:
        kwargs["repetition_penalty"] = repetition_penalty
    if presence_penalty is not None:
        kwargs["presence_penalty"] = presence_penalty
    if result_format is not None:
        kwargs["result_format"] = result_format
    if incremental_output is not None:
        kwargs["incremental_output"] = incremental_output
    if enable_search is not None:
        kwargs["enable_search"] = enable_search
    if tools is not None:
        kwargs["tools"] = tools
    if tool_choice is not None:
        kwargs["tool_choice"] = tool_choice
    if enable_thinking is not None:
        kwargs["enable_thinking"] = enable_thinking
    if n is not None:
        kwargs["n"] = n
    if ocr_options is not None:
        kwargs["ocr_options"] = ocr_options
    if logprobs is not None:
        kwargs["logprobs"] = logprobs
    if top_logprobs is not None:
        kwargs["top_logprobs"] = top_logprobs
    if model is None or not model:
        raise ModelRequired("Model is required!")
    task_group, _ = _get_task_group_and_task(__name__)
    input = {}  # pylint: disable=redefined-builtin
    msg_copy = None

    if messages is not None and messages:
        msg_copy = copy.deepcopy(messages)
        has_upload = cls._preprocess_messages(model, msg_copy, api_key)
        if has_upload:
            headers = kwargs.pop("headers", {})
            headers["X-DashScope-OssResourceResolve"] = "enable"
            kwargs["headers"] = headers

    if text is not None and text:
        input.update({"text": text})
    if voice is not None and voice:
        input.update({"voice": voice})
    if language_type is not None and language_type:
        input.update({"language_type": language_type})
    if msg_copy is not None:
        input.update({"messages": msg_copy})  # type: ignore

    # Validate input is not empty before sending request
    if not input:
        raise ValueError(
            "Input data is required. Please provide at least one of: "
            "messages, text, voice, or language_type.",
        )
    # Check if we need to merge incremental output
    is_incremental_output = kwargs.get("incremental_output", None)
    to_merge_incremental_output = False
    is_stream = kwargs.get("stream", False)
    if (
        ParamUtil.should_modify_incremental_output(model)
        and is_stream
        and is_incremental_output is not None
        and is_incremental_output is False
    ):
        to_merge_incremental_output = True
        kwargs["incremental_output"] = True

    # Pass incremental_to_full flag via headers user-agent
    if "headers" not in kwargs:
        kwargs["headers"] = {}
    flag = "1" if to_merge_incremental_output else "0"
    kwargs["headers"]["user-agent"] = (
        kwargs["headers"].get("user-agent", "")
        + f"; incremental_to_full/{flag}"
    )

    response = await super().call(
        model=model,
        task_group=task_group,
        task=AioMultiModalConversation.task,
        function=AioMultiModalConversation.function,
        api_key=api_key,
        input=input,
        workspace=workspace,
        **kwargs,
    )
    if is_stream:
        if to_merge_incremental_output:
            # Extract n parameter for merge logic
            n = kwargs.get("n", 1)
            return cls._merge_multimodal_response(response, n)
        else:
            return cls._stream_responses(response)
    else:
        return MultiModalConversationResponse.from_api_response(response)

Image & video synthesis

ImageSynthesis

Bases: BaseAsyncApi

task class-attribute instance-attribute

task = 'text2image'

API for image synthesis.

Models

wanx_v1 class-attribute instance-attribute
wanx_v1 = 'wanx-v1'
wanx_sketch_to_image_v1 class-attribute instance-attribute
wanx_sketch_to_image_v1 = 'wanx-sketch-to-image-v1'
wanx_2_1_imageedit class-attribute instance-attribute
wanx_2_1_imageedit = 'wanx2.1-imageedit'

call classmethod

call(
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] | None = None,
    api_key: str | None = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str | None = None,
    n: int | None = None,
    seed: int | None = None,
    style: str | None = None,
    ref_strength: float | None = None,
    ref_mode: str = None,
    prompt_extend: bool | None = None,
    watermark: bool | None = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs: Any
) -> ImageSynthesisResponse

Call image(s) synthesis service and get result.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
prompt Any

The prompt for image(s) synthesis.

required
negative_prompt Any

The negative_prompt. Defaults to None.

None
images List[str]

The input list of images url, currently not supported.

None
api_key str

The api api_key. Defaults to None.

None
sketch_image_url str

Only for wanx-sketch-to-image-v1, can be local file. Defaults to None.

None
workspace str

The dashscope workspace id.

None
extra_input Dict

The extra input parameters.

None
task str

The task of api, ref doc.

None
function str

The specific functions to be achieved. like: colorization,super_resolution,expand,remove_watermaker,doodle, description_edit_with_mask,description_edit,stylization_local,stylization_all

None
base_image_url str

Enter the URL address of the target edited image.

None
mask_image_url str

Provide the URL address of the image of the marked area by the user. It should be consistent with the image resolution of the base_image_url. # pylint: disable=line-too-long

None
size str

The output image(s) size(width*height).

None
n int

Number of images to synthesis.

None
seed int

Random seed for image generation.

None
style str

The output image style. Supported values: , , , <3d cartoon>, , , , , , . Default is .

None
ref_strength float

Control the similarity between output image and reference image. Range [0.0, 1.0]. Higher value means more similar to reference image.

None
ref_mode str

Mode for generating image based on reference image. Supported values: repaint (default, based on content), refonly (based on style).

None
prompt_extend bool

Whether to extend prompt automatically for better results.

None
watermark bool

Whether to add watermark.

None
bbox_list List

List of bounding boxes for region-specific editing.

None
enable_sequential bool

Enable sequential generation mode.

None
thinking_mode str

Thinking mode for generation. Supported values: fast, balanced, quality.

None
color_palette str

Color palette specification for consistent styling.

None
**kwargs Any

similarity(float, optional): The similarity between the output image and the input image sketch_weight(int, optional): How much the input sketch affects the output image[0-10], only for wanx-sketch-to-image-v1. # noqa E501 Default 10. realisticness(int, optional): The realisticness of the output image[0-10], only for wanx-sketch-to-image-v1. Default 5

{}

Raises:

Type Description
InputRequired

The prompt cannot be empty.

Returns:

Name Type Description
ImageSynthesisResponse ImageSynthesisResponse

The image(s) synthesis result.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs,
) -> ImageSynthesisResponse:
    """Call image(s) synthesis service and get result.

    Args:
        model (str): The model, reference ``Models``.
        prompt (Any): The prompt for image(s) synthesis.
        negative_prompt (Any): The negative_prompt. Defaults to None.
        images (List[str]): The input list of images url,
            currently not supported.
        api_key (str, optional): The api api_key. Defaults to None.
        sketch_image_url (str, optional): Only for wanx-sketch-to-image-v1,
            can be local file.
            Defaults to None.
        workspace (str): The dashscope workspace id.
        extra_input (Dict): The extra input parameters.
        task (str): The task of api, ref doc.
        function (str): The specific functions to be achieved. like:
            colorization,super_resolution,expand,remove_watermaker,doodle,
            description_edit_with_mask,description_edit,stylization_local,stylization_all
        base_image_url (str): Enter the URL address of the target edited image.
        mask_image_url (str): Provide the URL address of the image of the marked area by the user. It should be consistent with the image resolution of the base_image_url.  # pylint: disable=line-too-long
        size (str, optional): The output image(s) size(width*height).
        n (int, optional): Number of images to synthesis.
        seed (int, optional): Random seed for image generation.
        style (str, optional): The output image style. Supported values:
            <auto>, <photography>, <portrait>, <3d cartoon>, <anime>,
            <oil painting>, <watercolor>, <sketch>, <chinese painting>,
            <flat illustration>. Default is <auto>.
        ref_strength (float, optional): Control the similarity between
            output image and reference image. Range [0.0, 1.0].
            Higher value means more similar to reference image.
        ref_mode (str, optional): Mode for generating image based on
            reference image. Supported values: repaint (default, based on
            content), refonly (based on style).
        prompt_extend (bool, optional): Whether to extend prompt
            automatically for better results.
        watermark (bool, optional): Whether to add watermark.
        bbox_list (List, optional): List of bounding boxes for region-specific editing.
        enable_sequential (bool, optional): Enable sequential generation mode.
        thinking_mode (str, optional): Thinking mode for generation. Supported values: fast, balanced, quality.
        color_palette (str, optional): Color palette specification for consistent styling.
        **kwargs (Any):
            similarity(float, `optional`): The similarity between the
                output image and the input image
            sketch_weight(int, optional): How much the input sketch
                affects the output image[0-10], only for wanx-sketch-to-image-v1. # noqa E501
                Default 10.
            realisticness(int, optional): The realisticness of the output
                image[0-10], only for wanx-sketch-to-image-v1. Default 5

    Raises:
        InputRequired: The prompt cannot be empty.

    Returns:
        ImageSynthesisResponse: The image(s) synthesis result.
    """
    if size is not None:
        kwargs["size"] = size
    if n is not None:
        kwargs["n"] = n
    if seed is not None:
        kwargs["seed"] = seed
    if style is not None:
        kwargs["style"] = style
    if ref_strength is not None:
        kwargs["ref_strength"] = ref_strength
    if ref_mode is not None:
        kwargs["ref_mode"] = ref_mode
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if bbox_list is not None:
        kwargs["bbox_list"] = bbox_list
    if enable_sequential is not None:
        kwargs["enable_sequential"] = enable_sequential
    if thinking_mode is not None:
        kwargs["thinking_mode"] = thinking_mode
    if color_palette is not None:
        kwargs["color_palette"] = color_palette
    return super().call(  # type: ignore[return-value]
        model,
        prompt,
        negative_prompt,
        images,
        api_key=api_key,
        sketch_image_url=sketch_image_url,
        ref_img=ref_img,
        workspace=workspace,
        extra_input=extra_input,
        task=task,
        function=function,
        mask_image_url=mask_image_url,
        base_image_url=base_image_url,
        **kwargs,
    )

sync_call classmethod

sync_call(
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] | None = None,
    api_key: str | None = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs: Any
) -> ImageSynthesisResponse
This method currently now only supports wan2.2-t2i-flash and wan2.2-t2i-plus. # noqa: E501 # pylint: disable=line-too-long

Using other models will result in an error,More raw image models may be added for use later # pylint: disable=line-too-long

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
163
164
165
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
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
246
247
@classmethod
def sync_call(
    cls,
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs,
) -> ImageSynthesisResponse:
    """
    Note: This method currently now only supports wan2.2-t2i-flash and wan2.2-t2i-plus.  # noqa: E501  # pylint: disable=line-too-long
        Using other models will result in an error,More raw image models may be added for use later  # pylint: disable=line-too-long
    """
    if size is not None:
        kwargs["size"] = size
    if n is not None:
        kwargs["n"] = n
    if seed is not None:
        kwargs["seed"] = seed
    if style is not None:
        kwargs["style"] = style
    if ref_strength is not None:
        kwargs["ref_strength"] = ref_strength
    if ref_mode is not None:
        kwargs["ref_mode"] = ref_mode
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if bbox_list is not None:
        kwargs["bbox_list"] = bbox_list
    if enable_sequential is not None:
        kwargs["enable_sequential"] = enable_sequential
    if thinking_mode is not None:
        kwargs["thinking_mode"] = thinking_mode
    if color_palette is not None:
        kwargs["color_palette"] = color_palette
    task_group, f = _get_task_group_and_task(__name__)
    inputs, kwargs, task = cls._get_input(
        model,
        prompt,
        negative_prompt,
        images,
        api_key,
        sketch_image_url,
        ref_img,
        extra_input,
        task,
        function,
        mask_image_url,
        base_image_url,
        **kwargs,
    )
    response = BaseApi.call(
        model,
        inputs,
        task_group,
        task,
        f,
        api_key,
        workspace,
        **kwargs,
    )
    return ImageSynthesisResponse.from_api_response(response)

async_call classmethod

async_call(
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] | None = None,
    api_key: str | None = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs: Any
) -> ImageSynthesisResponse

Create a image(s) synthesis task, and return task information.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
prompt Any

The prompt for image(s) synthesis.

required
negative_prompt Any

The negative_prompt. Defaults to None.

None
images List[str]

The input list of images url.

None
api_key str

The api api_key. Defaults to None.

None
sketch_image_url str

Only for wanx-sketch-to-image-v1. Defaults to None.

None
workspace str

The dashscope workspace id.

None
extra_input Dict

The extra input parameters.

None
task str

The task of api, ref doc.

None
function str

The specific functions to be achieved.

None
mask_image_url str

Provide the URL address of the image of the marked area by the user.

None
base_image_url str

Enter the URL address of the target edited image.

None
size str

The output image(s) size(width*height).

None
seed int

Random seed for image generation.

None
style str

The output image style. Supported values: , , , <3d cartoon>, , , , , , . Default is .

None
ref_strength float

Control the similarity between output image and reference image. Range [0.0, 1.0].

None
ref_mode str

Mode for generating image based on reference image. Supported values: repaint (default, based on content), refonly (based on style).

None
prompt_extend bool

Whether to extend prompt automatically for better results.

None
watermark bool

Whether to add watermark.

None
bbox_list List

List of bounding boxes for region-specific editing.

None
enable_sequential bool

Enable sequential generation mode.

None
thinking_mode str

Thinking mode for generation. Supported values: fast, balanced, quality.

None
color_palette str

Color palette specification for consistent styling.

None
Source code in dashscope/legacy_1x/aigc/image_synthesis.py
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
410
411
412
413
414
415
416
417
418
419
420
421
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
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
@classmethod
# type: ignore[override]
def async_call(  # pylint: disable=arguments-renamed  # type: ignore[override] # noqa: E501
    cls,
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs,
) -> ImageSynthesisResponse:
    """Create a image(s) synthesis task, and return task information.

    Args:
        model (str): The model, reference ``Models``.
        prompt (Any): The prompt for image(s) synthesis.
        negative_prompt (Any): The negative_prompt. Defaults to None.
        images (List[str]): The input list of images url.
        api_key (str, optional): The api api_key. Defaults to None.
        sketch_image_url (str, optional): Only for wanx-sketch-to-image-v1.
            Defaults to None.
        workspace (str): The dashscope workspace id.
        extra_input (Dict): The extra input parameters.
        task (str): The task of api, ref doc.
        function (str): The specific functions to be achieved.
        mask_image_url (str): Provide the URL address of the image of
            the marked area by the user.
        base_image_url (str): Enter the URL address of the target edited
            image.
        size (str, optional): The output image(s) size(width*height).
        seed (int, optional): Random seed for image generation.
        style (str, optional): The output image style. Supported values:
            <auto>, <photography>, <portrait>, <3d cartoon>, <anime>,
            <oil painting>, <watercolor>, <sketch>, <chinese painting>,
            <flat illustration>. Default is <auto>.
        ref_strength (float, optional): Control the similarity between
            output image and reference image. Range [0.0, 1.0].
        ref_mode (str, optional): Mode for generating image based on
            reference image. Supported values: repaint (default, based on
            content), refonly (based on style).
        prompt_extend (bool, optional): Whether to extend prompt
            automatically for better results.
        watermark (bool, optional): Whether to add watermark.
        bbox_list (List, optional): List of bounding boxes for
            region-specific editing.
        enable_sequential (bool, optional): Enable sequential generation
            mode.
        thinking_mode (str, optional): Thinking mode for generation.
            Supported values: fast, balanced, quality.
        color_palette (str, optional): Color palette specification for
            consistent styling.
    """
    if size is not None:
        kwargs["size"] = size
    if n is not None:
        kwargs["n"] = n
    if seed is not None:
        kwargs["seed"] = seed
    if style is not None:
        kwargs["style"] = style
    if ref_strength is not None:
        kwargs["ref_strength"] = ref_strength
    if ref_mode is not None:
        kwargs["ref_mode"] = ref_mode
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if bbox_list is not None:
        kwargs["bbox_list"] = bbox_list
    if enable_sequential is not None:
        kwargs["enable_sequential"] = enable_sequential
    if thinking_mode is not None:
        kwargs["thinking_mode"] = thinking_mode
    if color_palette is not None:
        kwargs["color_palette"] = color_palette
    task_group, f = _get_task_group_and_task(__name__)
    # pylint: disable=protected-access
    inputs, kwargs, task = ImageSynthesis._get_input(
        model,
        prompt,
        negative_prompt,
        images,
        api_key,
        sketch_image_url,
        ref_img,
        extra_input,
        task,
        function,
        mask_image_url,
        base_image_url,
        **kwargs,
    )
    response = super().async_call(
        model=model,
        task_group=task_group,
        task=task,
        function=f,
        api_key=api_key,
        input=inputs,
        workspace=workspace,
        **kwargs,
    )
    return ImageSynthesisResponse.from_api_response(response)

fetch classmethod

fetch(
    task: Union[str, ImageSynthesisResponse],
    api_key: str | None = None,
    workspace: str | None = None,
) -> ImageSynthesisResponse

Fetch image(s) synthesis task status or result.

Parameters:

Name Type Description Default
task Union[str, ImageSynthesisResponse]

The task_id or ImageSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
ImageSynthesisResponse ImageSynthesisResponse

The task status or result.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
@classmethod
def fetch(  # type: ignore[override]
    cls,
    task: Union[str, ImageSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
) -> ImageSynthesisResponse:
    """Fetch image(s) synthesis task status or result.

    Args:
        task (Union[str, ImageSynthesisResponse]): The task_id or
            ImageSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        ImageSynthesisResponse: The task status or result.
    """
    response = super().fetch(task, api_key=api_key, workspace=workspace)
    return ImageSynthesisResponse.from_api_response(response)

wait classmethod

wait(
    task: Union[str, ImageSynthesisResponse],
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> ImageSynthesisResponse

Wait for image(s) synthesis task to complete, and return the result.

Parameters:

Name Type Description Default
task Union[str, ImageSynthesisResponse]

The task_id or ImageSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
ImageSynthesisResponse ImageSynthesisResponse

The task result.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
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
@classmethod
def wait(  # type: ignore[override]
    cls,
    task: Union[str, ImageSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> ImageSynthesisResponse:
    """Wait for image(s) synthesis task to complete, and return the result.

    Args:
        task (Union[str, ImageSynthesisResponse]): The task_id or
            ImageSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        ImageSynthesisResponse: The task result.
    """
    response = super().wait(
        task,
        api_key,
        workspace=workspace,
        **kwargs,
    )
    return ImageSynthesisResponse.from_api_response(response)

cancel classmethod

cancel(
    task: Union[str, ImageSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
) -> DashScopeAPIResponse

Cancel image synthesis task. Only tasks whose status is PENDING can be canceled.

Parameters:

Name Type Description Default
task Union[str, ImageSynthesisResponse]

The task_id or ImageSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
@classmethod
def cancel(  # type: ignore[override]
    cls,
    task: Union[str, ImageSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
) -> DashScopeAPIResponse:
    """Cancel image synthesis task.
    Only tasks whose status is PENDING can be canceled.

    Args:
        task (Union[str, ImageSynthesisResponse]): The task_id or
            ImageSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return super().cancel(task, api_key, workspace=workspace)

list classmethod

list(
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List async tasks.

Parameters:

Name Type Description Default
start_time str

The tasks start time, for example: 20230420000000. Defaults to None.

None
end_time str

The tasks end time, for example: 20230420000000. Defaults to None.

None
model_name str

The tasks model name. Defaults to None.

None
api_key_id str

The tasks api-key-id. Defaults to None.

None
region str

The service region, for example: cn-beijing. Defaults to None.

None
status str

The status of tasks[PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.

None
page_no int

The page number. Defaults to 1.

1
page_size int

The page size. Defaults to 10.

10
api_key str

The user api-key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/image_synthesis.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
@classmethod
def list(
    cls,
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List async tasks.

    Args:
        start_time (str, optional): The tasks start time,
            for example: 20230420000000. Defaults to None.
        end_time (str, optional): The tasks end time,
            for example: 20230420000000. Defaults to None.
        model_name (str, optional): The tasks model name. Defaults to None.
        api_key_id (str, optional): The tasks api-key-id. Defaults to None.
        region (str, optional): The service region,
            for example: cn-beijing. Defaults to None.
        status (str, optional): The status of tasks[PENDING,
            RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
        page_no (int, optional): The page number. Defaults to 1.
        page_size (int, optional): The page size. Defaults to 10.
        api_key (str, optional): The user api-key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return super().list(
        start_time=start_time,
        end_time=end_time,
        model_name=model_name,
        api_key_id=api_key_id,
        region=region,
        status=status,
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

AioImageSynthesis

Bases: BaseAsyncAioApi

call async classmethod

call(
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs
) -> ImageSynthesisResponse

Call image(s) synthesis service and get result.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
prompt Any

The prompt for image(s) synthesis.

required
negative_prompt Any

The negative_prompt. Defaults to None.

None
images List[str]

The input list of images url, currently not supported.

None
api_key str

The api api_key. Defaults to None.

None
sketch_image_url str

Only for wanx-sketch-to-image-v1, can be local file. Defaults to None.

None
workspace str

The dashscope workspace id.

None
extra_input Dict

The extra input parameters.

None
task str

The task of api, ref doc.

None
function str

The specific functions to be achieved. like: colorization,super_resolution,expand,remove_watermaker,doodle, description_edit_with_mask,description_edit,stylization_local,stylization_all

None
base_image_url str

Enter the URL address of the target edited image.

None
mask_image_url str

Provide the URL address of the image of the marked area by the user. It should be consistent with the image resolution of the base_image_url. # pylint: disable=line-too-long

None
size str

The output image(s) size(width*height).

None
n int

Number of images to synthesis.

None
seed int

Random seed for image generation.

None
style str

The output image style. Supported values: , , , <3d cartoon>, , , , , , . Default is .

None
ref_strength float

Control the similarity between output image and reference image. Range [0.0, 1.0].

None
ref_mode str

Mode for generating image based on reference image. Supported values: repaint (default, based on content), refonly (based on style).

None
prompt_extend bool

Whether to extend prompt automatically for better results.

None
watermark bool

Whether to add watermark.

None
bbox_list List

List of bounding boxes for region-specific editing.

None
enable_sequential bool

Enable sequential generation mode.

None
thinking_mode str

Thinking mode for generation. Supported values: fast, balanced, quality.

None
color_palette str

Color palette specification for consistent styling.

None
**kwargs Any

similarity(float, optional): The similarity between the output image and the input image sketch_weight(int, optional): How much the input sketch affects the output image[0-10], only for wanx-sketch-to-image-v1. # noqa E501 Default 10. realisticness(int, optional): The realisticness of the output image[0-10], only for wanx-sketch-to-image-v1. Default 5

{}

Raises:

Type Description
InputRequired

The prompt cannot be empty.

Returns:

Name Type Description
ImageSynthesisResponse ImageSynthesisResponse

The image(s) synthesis result.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
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
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
@classmethod
async def call(  # type: ignore[override] # pylint: disable=arguments-renamed # noqa: E501
    # type: ignore[override]
    cls,
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs,
) -> ImageSynthesisResponse:
    """Call image(s) synthesis service and get result.

    Args:
        model (str): The model, reference ``Models``.
        prompt (Any): The prompt for image(s) synthesis.
        negative_prompt (Any): The negative_prompt. Defaults to None.
        images (List[str]): The input list of images url,
            currently not supported.
        api_key (str, optional): The api api_key. Defaults to None.
        sketch_image_url (str, optional): Only for wanx-sketch-to-image-v1,
            can be local file.
            Defaults to None.
        workspace (str): The dashscope workspace id.
        extra_input (Dict): The extra input parameters.
        task (str): The task of api, ref doc.
        function (str): The specific functions to be achieved. like:
            colorization,super_resolution,expand,remove_watermaker,doodle,
            description_edit_with_mask,description_edit,stylization_local,stylization_all
        base_image_url (str): Enter the URL address of the target edited image.
        mask_image_url (str): Provide the URL address of the image of the marked area by the user. It should be consistent with the image resolution of the base_image_url.  # pylint: disable=line-too-long
        size (str, optional): The output image(s) size(width*height).
        n (int, optional): Number of images to synthesis.
        seed (int, optional): Random seed for image generation.
        style (str, optional): The output image style. Supported values:
            <auto>, <photography>, <portrait>, <3d cartoon>, <anime>,
            <oil painting>, <watercolor>, <sketch>, <chinese painting>,
            <flat illustration>. Default is <auto>.
        ref_strength (float, optional): Control the similarity between
            output image and reference image. Range [0.0, 1.0].
        ref_mode (str, optional): Mode for generating image based on
            reference image. Supported values: repaint (default, based on
            content), refonly (based on style).
        prompt_extend (bool, optional): Whether to extend prompt
            automatically for better results.
        watermark (bool, optional): Whether to add watermark.
        bbox_list (List, optional): List of bounding boxes for region-specific editing.
        enable_sequential (bool, optional): Enable sequential generation mode.
        thinking_mode (str, optional): Thinking mode for generation. Supported values: fast, balanced, quality.
        color_palette (str, optional): Color palette specification for consistent styling.
        **kwargs (Any):
            similarity(float, `optional`): The similarity between the
                output image and the input image
            sketch_weight(int, optional): How much the input sketch
                affects the output image[0-10], only for wanx-sketch-to-image-v1. # noqa E501
                Default 10.
            realisticness(int, optional): The realisticness of the output
                image[0-10], only for wanx-sketch-to-image-v1. Default 5

    Raises:
        InputRequired: The prompt cannot be empty.

    Returns:
        ImageSynthesisResponse: The image(s) synthesis result.
    """
    if size is not None:
        kwargs["size"] = size
    if n is not None:
        kwargs["n"] = n
    if seed is not None:
        kwargs["seed"] = seed
    if style is not None:
        kwargs["style"] = style
    if ref_strength is not None:
        kwargs["ref_strength"] = ref_strength
    if ref_mode is not None:
        kwargs["ref_mode"] = ref_mode
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if bbox_list is not None:
        kwargs["bbox_list"] = bbox_list
    if enable_sequential is not None:
        kwargs["enable_sequential"] = enable_sequential
    if thinking_mode is not None:
        kwargs["thinking_mode"] = thinking_mode
    if color_palette is not None:
        kwargs["color_palette"] = color_palette
    task_group, f = _get_task_group_and_task(__name__)
    # pylint: disable=protected-access
    inputs, kwargs, task = ImageSynthesis._get_input(
        model,
        prompt,
        negative_prompt,
        images,
        api_key,
        sketch_image_url,
        ref_img,
        extra_input,
        task,
        function,
        mask_image_url,
        base_image_url,
        **kwargs,
    )
    response = await super().call(
        model,
        inputs,
        task_group,
        task,
        f,
        api_key,
        workspace,
        **kwargs,
    )
    return ImageSynthesisResponse.from_api_response(response)

sync_call async classmethod

sync_call(
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs
) -> ImageSynthesisResponse
This method currently now only supports wan2.2-t2i-flash and wan2.2-t2i-plus. # noqa: E501 # pylint: disable=line-too-long

Using other models will result in an error,More raw image models may be added for use later # pylint: disable=line-too-long

Source code in dashscope/legacy_1x/aigc/image_synthesis.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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
@classmethod
async def sync_call(
    cls,
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,  # pylint: disable=unused-argument
    n: int = None,  # pylint: disable=unused-argument
    seed: int = None,  # pylint: disable=unused-argument
    style: str = None,  # pylint: disable=unused-argument
    ref_strength: float = None,  # pylint: disable=unused-argument
    ref_mode: str = None,  # pylint: disable=unused-argument
    prompt_extend: bool = None,  # pylint: disable=unused-argument
    watermark: bool = None,  # pylint: disable=unused-argument
    bbox_list: List = None,  # pylint: disable=unused-argument
    enable_sequential: bool = None,  # pylint: disable=unused-argument
    thinking_mode: str = None,  # pylint: disable=unused-argument
    color_palette: str = None,  # pylint: disable=unused-argument
    **kwargs,
) -> ImageSynthesisResponse:
    """
    Note: This method currently now only supports wan2.2-t2i-flash and wan2.2-t2i-plus.  # noqa: E501  # pylint: disable=line-too-long
        Using other models will result in an error,More raw image models may be added for use later  # pylint: disable=line-too-long
    """
    if size is not None:
        kwargs["size"] = size
    if n is not None:
        kwargs["n"] = n
    if seed is not None:
        kwargs["seed"] = seed
    if style is not None:
        kwargs["style"] = style
    if ref_strength is not None:
        kwargs["ref_strength"] = ref_strength
    if ref_mode is not None:
        kwargs["ref_mode"] = ref_mode
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if bbox_list is not None:
        kwargs["bbox_list"] = bbox_list
    if enable_sequential is not None:
        kwargs["enable_sequential"] = enable_sequential
    if thinking_mode is not None:
        kwargs["thinking_mode"] = thinking_mode
    if color_palette is not None:
        kwargs["color_palette"] = color_palette
    task_group, f = _get_task_group_and_task(__name__)
    # pylint: disable=protected-access
    inputs, kwargs, task = ImageSynthesis._get_input(
        model,
        prompt,
        negative_prompt,
        images,
        api_key,
        sketch_image_url,
        ref_img,
        extra_input,
        task,
        function,
        mask_image_url,
        base_image_url,
        **kwargs,
    )
    response = await BaseAioApi.call(
        model,
        inputs,
        task_group,
        task,
        f,
        api_key,
        workspace,
        **kwargs,
    )
    return ImageSynthesisResponse.from_api_response(response)

async_call async classmethod

async_call(
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,
    n: int = None,
    seed: int = None,
    style: str = None,
    ref_strength: float = None,
    ref_mode: str = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    bbox_list: List = None,
    enable_sequential: bool = None,
    thinking_mode: str = None,
    color_palette: str = None,
    **kwargs
) -> ImageSynthesisResponse

Create a image(s) synthesis task, and return task information.

Note: This method overrides BaseAsyncAioApi.async_call() with renamed parameters to provide a more user-friendly API. The generic parameters (input_data, task_group) are replaced with domain-specific ones (prompt, negative_prompt, images, etc.). Pylint's arguments-renamed warning is disabled for this reason.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
prompt Any

The prompt for image(s) synthesis.

required
negative_prompt Any

The negative_prompt. Defaults to None.

None
images List[str]

The input list of images url.

None
api_key str

The api api_key. Defaults to None.

None
sketch_image_url str

Only for wanx-sketch-to-image-v1. Defaults to None.

None
workspace str

The dashscope workspace id.

None
extra_input Dict

The extra input parameters.

None
task str

The task of api, ref doc.

None
function str

The specific functions to be achieved. like: colorization,super_resolution,expand,remove_watermaker,doodle, description_edit_with_mask,description_edit,stylization_local,stylization_all

None
base_image_url str

Enter the URL address of the target edited image.

None
mask_image_url str

Provide the URL address of the image of the marked area by the user. It should be consistent with the image resolution of the base_image_url. # pylint: disable=line-too-long

None
**kwargs wanx - v1

n(int, optional): Number of images to synthesis. size: The output image(s) size, Default 1024*1024 similarity(float, optional): The similarity between the output image and the input image. sketch_weight(int, optional): How much the input sketch affects the output image[0-10], only for wanx-sketch-to-image-v1. # noqa E501 Default 10. realisticness(int, optional): The realisticness of the output image[0-10], only for wanx-sketch-to-image-v1. Default 5

{}

Raises:

Type Description
InputRequired

The prompt cannot be empty.

Returns:

Name Type Description
DashScopeAPIResponse ImageSynthesisResponse

The image synthesis task id in the response.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
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
913
914
915
916
917
918
919
920
921
922
923
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
@classmethod
async def async_call(  # type: ignore[override]  # pylint: disable=arguments-renamed  # noqa: E501
    cls,
    model: str,
    prompt: Any,
    negative_prompt: Any = None,
    images: List[str] = None,
    api_key: str = None,
    sketch_image_url: str = None,
    ref_img: str = None,
    workspace: str = None,
    extra_input: Dict = None,
    task: str = None,
    function: str = None,
    mask_image_url: str = None,
    base_image_url: str = None,
    size: str = None,  # pylint: disable=unused-argument
    n: int = None,  # pylint: disable=unused-argument
    seed: int = None,  # pylint: disable=unused-argument
    style: str = None,  # pylint: disable=unused-argument
    ref_strength: float = None,  # pylint: disable=unused-argument
    ref_mode: str = None,  # pylint: disable=unused-argument
    prompt_extend: bool = None,  # pylint: disable=unused-argument
    watermark: bool = None,  # pylint: disable=unused-argument
    bbox_list: List = None,  # pylint: disable=unused-argument
    enable_sequential: bool = None,  # pylint: disable=unused-argument
    thinking_mode: str = None,  # pylint: disable=unused-argument
    color_palette: str = None,  # pylint: disable=unused-argument
    **kwargs,
) -> ImageSynthesisResponse:
    """Create a image(s) synthesis task, and return task information.

    Note: This method overrides BaseAsyncAioApi.async_call() with
    renamed parameters to provide a more user-friendly API. The
    generic parameters (input_data, task_group) are replaced with
    domain-specific ones (prompt, negative_prompt, images, etc.).
    Pylint's arguments-renamed warning is disabled for this reason.

    Args:
        model (str): The model, reference ``Models``.
        prompt (Any): The prompt for image(s) synthesis.
        negative_prompt (Any): The negative_prompt. Defaults to None.
        images (List[str]): The input list of images url.
        api_key (str, optional): The api api_key. Defaults to None.
        sketch_image_url (str, optional): Only for wanx-sketch-to-image-v1.
            Defaults to None.
        workspace (str): The dashscope workspace id.
        extra_input (Dict): The extra input parameters.
        task (str): The task of api, ref doc.
        function (str): The specific functions to be achieved. like:
            colorization,super_resolution,expand,remove_watermaker,doodle,
            description_edit_with_mask,description_edit,stylization_local,stylization_all
        base_image_url (str): Enter the URL address of the target edited image.
        mask_image_url (str): Provide the URL address of the image of the marked area by the user. It should be consistent with the image resolution of the base_image_url.  # pylint: disable=line-too-long
        **kwargs(wanx-v1):
            n(int, `optional`): Number of images to synthesis.
            size: The output image(s) size, Default 1024*1024
            similarity(float, `optional`): The similarity between the
                output image and the input image.
            sketch_weight(int, optional): How much the input sketch
                affects the output image[0-10], only for wanx-sketch-to-image-v1. # noqa E501
                Default 10.
            realisticness(int, optional): The realisticness of the output
                image[0-10], only for wanx-sketch-to-image-v1. Default 5

    Raises:
        InputRequired: The prompt cannot be empty.

    Returns:
        DashScopeAPIResponse: The image synthesis
            task id in the response.
    """
    if size is not None:
        kwargs["size"] = size
    if n is not None:
        kwargs["n"] = n
    if seed is not None:
        kwargs["seed"] = seed
    if style is not None:
        kwargs["style"] = style
    if ref_strength is not None:
        kwargs["ref_strength"] = ref_strength
    if ref_mode is not None:
        kwargs["ref_mode"] = ref_mode
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if bbox_list is not None:
        kwargs["bbox_list"] = bbox_list
    if enable_sequential is not None:
        kwargs["enable_sequential"] = enable_sequential
    if thinking_mode is not None:
        kwargs["thinking_mode"] = thinking_mode
    if color_palette is not None:
        kwargs["color_palette"] = color_palette
    task_group, f = _get_task_group_and_task(__name__)
    # pylint: disable=protected-access
    inputs, kwargs, task = ImageSynthesis._get_input(
        model,
        prompt,
        negative_prompt,
        images,
        api_key,
        sketch_image_url,
        ref_img,
        extra_input,
        task,
        function,
        mask_image_url,
        base_image_url,
        **kwargs,
    )
    response = await super().async_call(
        model,
        inputs,
        task_group,
        task,
        f,
        api_key,
        workspace,
        **kwargs,
    )
    return ImageSynthesisResponse.from_api_response(response)

fetch async classmethod

fetch(
    task: Union[str, ImageSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> ImageSynthesisResponse

Fetch image(s) synthesis task status or result.

Parameters:

Name Type Description Default
task Union[str, ImageSynthesisResponse]

The task_id or ImageSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
ImageSynthesisResponse ImageSynthesisResponse

The task status or result.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
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
@classmethod
async def fetch(
    cls,
    task: Union[str, ImageSynthesisResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> ImageSynthesisResponse:
    """Fetch image(s) synthesis task status or result.

    Args:
        task (Union[str, ImageSynthesisResponse]): The task_id or
            ImageSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        ImageSynthesisResponse: The task status or result.
    """
    response = await super().fetch(
        task,
        api_key=api_key,
        workspace=workspace,
    )
    return ImageSynthesisResponse.from_api_response(response)

wait async classmethod

wait(
    task: Union[str, ImageSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs
) -> ImageSynthesisResponse

Wait for image(s) synthesis task to complete, and return the result.

Parameters:

Name Type Description Default
task Union[str, ImageSynthesisResponse]

The task_id or ImageSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
wait_timeout int

The maximum seconds to wait. Default is -1 (no timeout).

-1

Returns:

Name Type Description
ImageSynthesisResponse ImageSynthesisResponse

The task result.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
@classmethod
async def wait(
    cls,
    task: Union[str, ImageSynthesisResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs,
) -> ImageSynthesisResponse:
    """Wait for image(s) synthesis task to complete, and return the result.

    Args:
        task (Union[str, ImageSynthesisResponse]): The task_id or
            ImageSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        wait_timeout (int, optional): The maximum seconds to wait.
            Default is -1 (no timeout).

    Returns:
        ImageSynthesisResponse: The task result.
    """
    response = await super().wait(
        task,
        api_key,
        workspace=workspace,
        wait_timeout=wait_timeout,
    )
    return ImageSynthesisResponse.from_api_response(response)

cancel async classmethod

cancel(
    task: Union[str, ImageSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Cancel image synthesis task. Only tasks whose status is PENDING can be canceled.

Parameters:

Name Type Description Default
task Union[str, ImageSynthesisResponse]

The task_id or ImageSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
@classmethod
async def cancel(
    cls,
    task: Union[str, ImageSynthesisResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Cancel image synthesis task.
    Only tasks whose status is PENDING can be canceled.

    Args:
        task (Union[str, ImageSynthesisResponse]): The task_id or
            ImageSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return await super().cancel(task, api_key, workspace=workspace)

list async classmethod

list(
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List async tasks.

Parameters:

Name Type Description Default
start_time str

The tasks start time, for example: 20230420000000. Defaults to None.

None
end_time str

The tasks end time, for example: 20230420000000. Defaults to None.

None
model_name str

The tasks model name. Defaults to None.

None
api_key_id str

The tasks api-key-id. Defaults to None.

None
region str

The service region, for example: cn-beijing. Defaults to None.

None
status str

The status of tasks[PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.

None
page_no int

The page number. Defaults to 1.

1
page_size int

The page size. Defaults to 10.

10
api_key str

The user api-key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/image_synthesis.py
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
1091
1092
1093
1094
1095
1096
1097
@classmethod
async def list(
    cls,
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List async tasks.

    Args:
        start_time (str, optional): The tasks start time,
            for example: 20230420000000. Defaults to None.
        end_time (str, optional): The tasks end time,
            for example: 20230420000000. Defaults to None.
        model_name (str, optional): The tasks model name. Defaults to None.
        api_key_id (str, optional): The tasks api-key-id. Defaults to None.
        region (str, optional): The service region,
            for example: cn-beijing. Defaults to None.
        status (str, optional): The status of tasks[PENDING,
            RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
        page_no (int, optional): The page number. Defaults to 1.
        page_size (int, optional): The page size. Defaults to 10.
        api_key (str, optional): The user api-key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return await super().list(
        start_time=start_time,
        end_time=end_time,
        model_name=model_name,
        api_key_id=api_key_id,
        region=region,
        status=status,
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

ImageGeneration

Bases: BaseApi, BaseAsyncApi

sync_task class-attribute instance-attribute

sync_task = 'multimodal-generation'

async_task class-attribute instance-attribute

async_task = 'image-generation'

function class-attribute instance-attribute

function = 'generation'

API for AI-Generated Content(AIGC) models.

Models

wan2_6_image class-attribute instance-attribute
wan2_6_image = 'wan2.6-image'
wan2_6_t2i class-attribute instance-attribute
wan2_6_t2i = 'wan2.6-t2i'

call classmethod

call(
    model: str,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs
) -> Union[
    ImageGenerationResponse,
    Generator[ImageGenerationResponse, None, None],
]

Call generation model service.

Parameters:

Name Type Description Default
model str

The requested model

required
api_key str

The api api_key, can be None, if None, will get by default rule(TODO: api key doc).

None
messages list

The generation messages. examples: [{'role': 'user', 'content': 'The weather is fine today.'}, {'role': 'assistant', 'content': 'Suitable for outings'}]

None
**kwargs Any

stream(bool, optional): Enable server-sent events (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) # noqa E501 # pylint: disable=line-too-long the result will back partially[qwen-turbo,bailian-v1].

{}
workspace str

The dashscope workspace id.

None

Raises: InvalidInput: The history and auto_history are mutually exclusive.

Returns:

Type Description
Union[ImageGenerationResponse, Generator[ImageGenerationResponse, None, None]]

Union[ImageGenerationResponse, Generator[ImageGenerationResponse, None, None]]: If

Union[ImageGenerationResponse, Generator[ImageGenerationResponse, None, None]]

stream is True, return Generator, otherwise ImageGenerationResponse.

Source code in dashscope/legacy_1x/aigc/image_generation.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs,
) -> Union[
    ImageGenerationResponse,
    Generator[ImageGenerationResponse, None, None],
]:
    """Call generation model service.

    Args:
        model (str): The requested model
        api_key (str, optional): The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).
        messages (list): The generation messages.
            examples:
                [{'role': 'user',
                  'content': 'The weather is fine today.'},
                  {'role': 'assistant', 'content': 'Suitable for outings'}]
        **kwargs (Any):
            stream(bool, `optional`): Enable server-sent events
                (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)  # noqa E501  # pylint: disable=line-too-long
                the result will back partially[qwen-turbo,bailian-v1].
        workspace (str): The dashscope workspace id.
    Raises:
        InvalidInput: The history and auto_history are mutually exclusive.

    Returns:
        Union[ImageGenerationResponse,
              Generator[ImageGenerationResponse, None, None]]: If
        stream is True, return Generator, otherwise ImageGenerationResponse.
    """
    if messages is None or not messages:
        raise InputRequired("messages is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")

    task_group, _ = _get_task_group_and_task(__name__)
    _input = {}

    if messages is not None and messages:
        has_upload = cls._preprocess_messages(model, messages, api_key)  # type: ignore[arg-type] # pylint: disable=line-too-long # noqa: E501
        if has_upload:
            headers = kwargs.pop("headers", {})
            headers["X-DashScope-OssResourceResolve"] = "enable"
            kwargs["headers"] = headers

    _input.update({"messages": messages})

    # Check if we need to merge incremental output
    is_incremental_output = kwargs.get("incremental_output", None)
    is_stream = kwargs.get("stream", False)
    to_merge_incremental_output = False
    if (
        ParamUtil.should_modify_incremental_output(model)
        and is_stream
        and is_incremental_output is not None
        and is_incremental_output is False
    ):
        to_merge_incremental_output = True
        kwargs["incremental_output"] = True

    # Pass incremental_to_full flag via user_agent parameter
    flag = "1" if to_merge_incremental_output else "0"
    existing_ua = kwargs.get("user_agent", "")
    new_ua = f"incremental_to_full/{flag}"
    kwargs["user_agent"] = (
        f"{existing_ua}; {new_ua}".strip() if existing_ua else new_ua
    )
    if kwargs.get("is_async", False):
        kwargs.setdefault("headers", {})["X-DashScope-Async"] = "enable"
        task = cls.async_task
    else:
        task = cls.sync_task

    response = super().call(
        model=model,
        task_group=task_group,
        task=task,
        function=ImageGeneration.function,
        api_key=api_key,
        input=_input,
        workspace=workspace,
        **kwargs,
    )
    if is_stream:
        if to_merge_incremental_output:
            # Extract n parameter for merge logic
            n = kwargs.get("n", 1)
            return cls._merge_generation_response(response, n)
        else:
            return (
                ImageGenerationResponse.from_api_response(rsp)
                for rsp in response
            )
    else:
        return ImageGenerationResponse.from_api_response(response)

async_call classmethod

async_call(
    model: str,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs
) -> Union[
    ImageGenerationResponse,
    Generator[ImageGenerationResponse, None, None],
]
Source code in dashscope/legacy_1x/aigc/image_generation.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
@classmethod
def async_call(  # type: ignore[override]
    cls,
    model: str,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs,
) -> Union[
    ImageGenerationResponse,
    Generator[ImageGenerationResponse, None, None],
]:
    kwargs["is_async"] = True
    return cls.call(model, api_key, messages, workspace, **kwargs)

fetch classmethod

fetch(
    task: Union[str, ImageGenerationResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Fetch image(s) synthesis task status or result.

Parameters:

Name Type Description Default
task Union[str, ImageGenerationResponse]

The task_id or ImageGenerationResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The task status or result.

Source code in dashscope/legacy_1x/aigc/image_generation.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
@classmethod
def fetch(
    cls,
    task: Union[str, ImageGenerationResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Fetch image(s) synthesis task status or result.

    Args:
        task (Union[str, ImageGenerationResponse]): The task_id or
            ImageGenerationResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The task status or result.
    """
    response = super().fetch(task, api_key=api_key, workspace=workspace)
    return ImageGenerationResponse.from_api_response(response)

wait classmethod

wait(
    task: Union[str, ImageGenerationResponse],
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs
) -> DashScopeAPIResponse

Wait for image(s) synthesis task to complete, and return the result.

Parameters:

Name Type Description Default
task Union[str, ImageGenerationResponse]

The task_id or ImageGenerationResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
wait_timeout int

The maximum seconds to wait. Default is -1 (no timeout).

-1

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The task result.

Source code in dashscope/legacy_1x/aigc/image_generation.py
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
@classmethod
def wait(
    cls,
    task: Union[str, ImageGenerationResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs,
) -> DashScopeAPIResponse:
    """Wait for image(s) synthesis task to complete, and return the result.

    Args:
        task (Union[str, ImageGenerationResponse]): The task_id or
            ImageGenerationResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        wait_timeout (int, optional): The maximum seconds to wait.
            Default is -1 (no timeout).

    Returns:
        DashScopeAPIResponse: The task result.
    """
    response = super().wait(
        task,
        api_key,
        workspace=workspace,
        wait_timeout=wait_timeout,
    )
    return ImageGenerationResponse.from_api_response(response)

cancel classmethod

cancel(
    task: Union[str, ImageGenerationResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Cancel image synthesis task. Only tasks whose status is PENDING can be canceled.

Parameters:

Name Type Description Default
task Union[str, ImageGenerationResponse]

The task_id or ImageGenerationResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/image_generation.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
@classmethod
def cancel(
    cls,
    task: Union[str, ImageGenerationResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Cancel image synthesis task.
    Only tasks whose status is PENDING can be canceled.

    Args:
        task (Union[str, ImageGenerationResponse]): The task_id or
            ImageGenerationResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return super().cancel(task, api_key, workspace=workspace)

list classmethod

list(
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List async tasks.

Parameters:

Name Type Description Default
start_time str

The tasks start time, for example: 20230420000000. Defaults to None.

None
end_time str

The tasks end time, for example: 20230420000000. Defaults to None.

None
model_name str

The tasks model name. Defaults to None.

None
api_key_id str

The tasks api-key-id. Defaults to None.

None
region str

The service region, for example: cn-beijing. Defaults to None.

None
status str

The status of tasks[PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.

None
page_no int

The page number. Defaults to 1.

1
page_size int

The page size. Defaults to 10.

10
api_key str

The user api-key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/image_generation.py
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
@classmethod
def list(
    cls,
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List async tasks.

    Args:
        start_time (str, optional): The tasks start time,
            for example: 20230420000000. Defaults to None.
        end_time (str, optional): The tasks end time,
            for example: 20230420000000. Defaults to None.
        model_name (str, optional): The tasks model name. Defaults to None.
        api_key_id (str, optional): The tasks api-key-id. Defaults to None.
        region (str, optional): The service region,
            for example: cn-beijing. Defaults to None.
        status (str, optional): The status of tasks[PENDING,
            RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
        page_no (int, optional): The page number. Defaults to 1.
        page_size (int, optional): The page size. Defaults to 10.
        api_key (str, optional): The user api-key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return super().list(
        start_time=start_time,
        end_time=end_time,
        model_name=model_name,
        api_key_id=api_key_id,
        region=region,
        status=status,
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

AioImageGeneration

Bases: BaseAioApi, BaseAsyncAioApi

sync_task class-attribute instance-attribute

sync_task = 'multimodal-generation'

async_task class-attribute instance-attribute

async_task = 'image-generation'

function class-attribute instance-attribute

function = 'generation'

API for AI-Generated Content(AIGC) models.

Models

wan2_6_image class-attribute instance-attribute
wan2_6_image = 'wan2.6-image'
wan2_6_t2i class-attribute instance-attribute
wan2_6_t2i = 'wan2.6-t2i'

call async classmethod

call(
    model: str,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs
) -> Union[
    ImageGenerationResponse,
    AsyncGenerator[ImageGenerationResponse, None],
]

Call generation model service.

Parameters:

Name Type Description Default
model str

The requested model

required
api_key str

The api api_key, can be None, if None, will get by default rule(TODO: api key doc).

None
messages list

The generation messages. examples: [{'role': 'user', 'content': 'The weather is fine today.'}, {'role': 'assistant', 'content': 'Suitable for outings'}]

None
**kwargs Any

stream(bool, optional): Enable server-sent events (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) # noqa E501 # pylint: disable=line-too-long the result will back partially[qwen-turbo,bailian-v1].

{}
workspace str

The dashscope workspace id.

None

Raises: InvalidInput: The history and auto_history are mutually exclusive.

Returns:

Type Description
Union[ImageGenerationResponse, AsyncGenerator[ImageGenerationResponse, None]]

Union[ImageGenerationResponse, AsyncGenerator[ImageGenerationResponse, None]]: If

Union[ImageGenerationResponse, AsyncGenerator[ImageGenerationResponse, None]]

stream is True, return AsyncGenerator, otherwise ImageGenerationResponse.

Source code in dashscope/legacy_1x/aigc/image_generation.py
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
386
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
@classmethod
async def call(  # type: ignore[override]
    cls,
    model: str,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs,
) -> Union[
    ImageGenerationResponse,
    AsyncGenerator[ImageGenerationResponse, None],
]:
    """Call generation model service.

    Args:
        model (str): The requested model
        api_key (str, optional): The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).
        messages (list): The generation messages.
            examples:
                [{'role': 'user',
                  'content': 'The weather is fine today.'},
                  {'role': 'assistant', 'content': 'Suitable for outings'}]
        **kwargs (Any):
            stream(bool, `optional`): Enable server-sent events
                (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)  # noqa E501  # pylint: disable=line-too-long
                the result will back partially[qwen-turbo,bailian-v1].
        workspace (str): The dashscope workspace id.
    Raises:
        InvalidInput: The history and auto_history are mutually exclusive.

    Returns:
        Union[ImageGenerationResponse,
              AsyncGenerator[ImageGenerationResponse, None]]: If
        stream is True, return AsyncGenerator, otherwise ImageGenerationResponse.
    """
    if messages is None or not messages:
        raise InputRequired("messages is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")

    task_group, _ = _get_task_group_and_task(__name__)
    _input = {}

    if messages is not None and messages:  # type: ignore
        has_upload = cls._preprocess_messages(model, messages, api_key)  # type: ignore[arg-type] # pylint: disable=line-too-long # noqa: E501
        if has_upload:
            headers = kwargs.pop("headers", {})
            headers["X-DashScope-OssResourceResolve"] = "enable"
            kwargs["headers"] = headers

    _input.update({"messages": messages})

    # Check if we need to merge incremental output
    is_incremental_output = kwargs.get("incremental_output", None)
    is_stream = kwargs.get("stream", False)
    to_merge_incremental_output = False
    if (
        ParamUtil.should_modify_incremental_output(model)
        and is_stream
        and is_incremental_output is not None
        and is_incremental_output is False
    ):
        to_merge_incremental_output = True
        kwargs["incremental_output"] = True

    # Pass incremental_to_full flag via user_agent parameter
    flag = "1" if to_merge_incremental_output else "0"
    existing_ua = kwargs.get("user_agent", "")
    new_ua = f"incremental_to_full/{flag}"
    kwargs["user_agent"] = (
        f"{existing_ua}; {new_ua}".strip() if existing_ua else new_ua
    )
    if kwargs.get("is_async", False):
        kwargs.setdefault("headers", {})["X-DashScope-Async"] = "enable"
        task = cls.async_task
    else:
        task = cls.sync_task

    response = await super().call(
        model=model,
        task_group=task_group,
        task=task,
        function=AioImageGeneration.function,
        api_key=api_key,
        input=_input,
        workspace=workspace,
        **kwargs,
    )
    if is_stream:
        if to_merge_incremental_output:
            # Extract n parameter for merge logic
            n = kwargs.get("n", 1)
            return cls._merge_generation_response(response, n)
        else:
            return cls._stream_responses(response)
    else:
        return ImageGenerationResponse.from_api_response(response)

async_call async classmethod

async_call(
    model: str,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs
) -> Union[
    ImageGenerationResponse,
    AsyncGenerator[ImageGenerationResponse, None],
]
Source code in dashscope/legacy_1x/aigc/image_generation.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
@classmethod
async def async_call(  # type: ignore[override]
    cls,
    model: str,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs,
) -> Union[
    ImageGenerationResponse,
    AsyncGenerator[ImageGenerationResponse, None],
]:
    kwargs["is_async"] = True
    return await cls.call(model, api_key, messages, workspace, **kwargs)

fetch async classmethod

fetch(
    task: Union[str, ImageGenerationResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Fetch image(s) synthesis task status or result.

Parameters:

Name Type Description Default
task Union[str, ImageGenerationResponse]

The task_id or ImageGenerationResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The task status or result.

Source code in dashscope/legacy_1x/aigc/image_generation.py
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
@classmethod
async def fetch(
    cls,
    task: Union[str, ImageGenerationResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Fetch image(s) synthesis task status or result.

    Args:
        task (Union[str, ImageGenerationResponse]): The task_id or
            ImageGenerationResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The task status or result.
    """
    response = await super().fetch(
        task,
        api_key=api_key,
        workspace=workspace,
    )
    return ImageGenerationResponse.from_api_response(response)

wait async classmethod

wait(
    task: Union[str, ImageGenerationResponse],
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs
) -> DashScopeAPIResponse

Wait for image(s) synthesis task to complete, and return the result.

Parameters:

Name Type Description Default
task Union[str, ImageGenerationResponse]

The task_id or ImageGenerationResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
wait_timeout int

The maximum seconds to wait. Default is -1 (no timeout).

-1

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The task result.

Source code in dashscope/legacy_1x/aigc/image_generation.py
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
@classmethod
async def wait(
    cls,
    task: Union[str, ImageGenerationResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs,
) -> DashScopeAPIResponse:
    """Wait for image(s) synthesis task to complete, and return the result.

    Args:
        task (Union[str, ImageGenerationResponse]): The task_id or
            ImageGenerationResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        wait_timeout (int, optional): The maximum seconds to wait.
            Default is -1 (no timeout).

    Returns:
        DashScopeAPIResponse: The task result.
    """
    response = await super().wait(
        task,
        api_key,
        workspace=workspace,
        wait_timeout=wait_timeout,
    )
    return ImageGenerationResponse.from_api_response(response)

cancel async classmethod

cancel(
    task: Union[str, ImageGenerationResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Cancel image synthesis task. Only tasks whose status is PENDING can be canceled.

Parameters:

Name Type Description Default
task Union[str, ImageGenerationResponse]

The task_id or ImageGenerationResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/image_generation.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
@classmethod
async def cancel(
    cls,
    task: Union[str, ImageGenerationResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Cancel image synthesis task.
    Only tasks whose status is PENDING can be canceled.

    Args:
        task (Union[str, ImageGenerationResponse]): The task_id or
            ImageGenerationResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return await super().cancel(task, api_key, workspace=workspace)

list async classmethod

list(
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List async tasks.

Parameters:

Name Type Description Default
start_time str

The tasks start time, for example: 20230420000000. Defaults to None.

None
end_time str

The tasks end time, for example: 20230420000000. Defaults to None.

None
model_name str

The tasks model name. Defaults to None.

None
api_key_id str

The tasks api-key-id. Defaults to None.

None
region str

The service region, for example: cn-beijing. Defaults to None.

None
status str

The status of tasks[PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.

None
page_no int

The page number. Defaults to 1.

1
page_size int

The page size. Defaults to 10.

10
api_key str

The user api-key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/image_generation.py
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
@classmethod
async def list(
    cls,
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List async tasks.

    Args:
        start_time (str, optional): The tasks start time,
            for example: 20230420000000. Defaults to None.
        end_time (str, optional): The tasks end time,
            for example: 20230420000000. Defaults to None.
        model_name (str, optional): The tasks model name. Defaults to None.
        api_key_id (str, optional): The tasks api-key-id. Defaults to None.
        region (str, optional): The service region,
            for example: cn-beijing. Defaults to None.
        status (str, optional): The status of tasks[PENDING,
            RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
        page_no (int, optional): The page number. Defaults to 1.
        page_size (int, optional): The page size. Defaults to 10.
        api_key (str, optional): The user api-key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return await super().list(
        start_time=start_time,
        end_time=end_time,
        model_name=model_name,
        api_key_id=api_key_id,
        region=region,
        status=status,
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

VideoSynthesis

Bases: BaseAsyncApi

task class-attribute instance-attribute

task = 'video-generation'

API for video synthesis.

Models

@deprecated, use wanx2.1-t2v-plus instead

wanx_txt2video_pro class-attribute instance-attribute
wanx_txt2video_pro = 'wanx-txt2video-pro'

@deprecated, use wanx2.1-i2v-plus instead

wanx_img2video_pro class-attribute instance-attribute
wanx_img2video_pro = 'wanx-img2video-pro'
wanx_2_1_t2v_turbo class-attribute instance-attribute
wanx_2_1_t2v_turbo = 'wanx2.1-t2v-turbo'
wanx_2_1_t2v_plus class-attribute instance-attribute
wanx_2_1_t2v_plus = 'wanx2.1-t2v-plus'
wanx_2_1_i2v_plus class-attribute instance-attribute
wanx_2_1_i2v_plus = 'wanx2.1-i2v-plus'
wanx_2_1_i2v_turbo class-attribute instance-attribute
wanx_2_1_i2v_turbo = 'wanx2.1-i2v-turbo'
wanx_2_1_kf2v_plus class-attribute instance-attribute
wanx_2_1_kf2v_plus = 'wanx2.1-kf2v-plus'
wanx_kf2v class-attribute instance-attribute
wanx_kf2v = 'wanx-kf2v'

MediaType

FIRST_FRAME class-attribute instance-attribute
FIRST_FRAME = 'first_frame'
LAST_FRAME class-attribute instance-attribute
LAST_FRAME = 'last_frame'
REFERENCE_IMAGE class-attribute instance-attribute
REFERENCE_IMAGE = 'reference_image'
REFERENCE_VIDEO class-attribute instance-attribute
REFERENCE_VIDEO = 'reference_video'
REFERENCE_VOICE class-attribute instance-attribute
REFERENCE_VOICE = 'reference_voice'
REFERENCE_AUDIO class-attribute instance-attribute
REFERENCE_AUDIO = 'reference_audio'
VIDEO class-attribute instance-attribute
VIDEO = 'video'
FIRST_CLIP class-attribute instance-attribute
FIRST_CLIP = 'first_clip'
DRIVING_AUDIO class-attribute instance-attribute
DRIVING_AUDIO = 'driving_audio'
FILE class-attribute instance-attribute
FILE = 'file'
LINK = 'link'

call classmethod

call(
    model: str,
    prompt: Any = None,
    extend_prompt: bool = True,
    negative_prompt: str | None = None,
    template: str = None,
    img_url: str | None = None,
    audio_url: str | None = None,
    reference_video_urls: List[str] | None = None,
    reference_urls: List[str] = None,
    reference_url: str = None,
    reference_video_description: List[str] = None,
    api_key: str | None = None,
    extra_input: Dict = None,
    workspace: str | None = None,
    task: str = None,
    head_frame: str = None,
    tail_frame: str = None,
    first_frame_url: str = None,
    last_frame_url: str = None,
    media: List[Dict] = None,
    size: str | None = None,
    duration: int | None = None,
    seed: int | None = None,
    prompt_extend: bool | None = None,
    watermark: bool | None = None,
    resolution: str | None = None,
    ratio: str | None = None,
    shot_type: Optional[str] = None,
    audio_setting: Optional[str] = None,
    enable_thinking: Optional[bool] = None,
    **kwargs: Any
) -> VideoSynthesisResponse

Call video synthesis service and get result.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
prompt Any

The prompt for video synthesis.

None
extend_prompt bool

@deprecated, use prompt_extend in parameters

True
negative_prompt str

The negative prompt is the opposite of the prompt meaning.

None
template str

LoRa input, such as gufeng, katong, etc.

None
img_url str

The input image url.

None
audio_url str

The input audio url.

None
reference_video_urls List[str]

Character reference video file urls.

None
reference_urls List[str]

Character reference file urls.

None
reference_url str

Reference file url.

None
reference_video_description List[str]

Description for reference video picture and sound.

None
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
extra_input Dict

The extra input parameters.

None
task str

The task of api, ref doc.

None
head_frame str

URL of the first frame image.

None
tail_frame str

URL of the last frame image.

None
first_frame_url str

URL of the first frame image.

None
last_frame_url str

URL of the last frame image.

None
media list

media file list.

None
size str

Output video size (widthheight), e.g. "1280720".

None
duration int

Duration of video in seconds. Default is 5.

None
seed int

Random seed for video generation.

None
prompt_extend bool

Whether to extend prompt automatically for better results.

None
watermark bool

Whether to add watermark.

None
resolution str

Output resolution, e.g. "720P", "1080P".

None
ratio str

Aspect ratio, e.g. "16:9", "9:16".

None
shot_type str

Shot type for video generation.

None
audio_setting str

Audio setting for video, "auto" or "origin".

None
enable_thinking bool

Whether to use Agentic PE.

None
**kwargs Any

Additional parameters passed to the API.

{}

Raises:

Type Description
InputRequired

The prompt cannot be empty.

Returns:

Name Type Description
VideoSynthesisResponse VideoSynthesisResponse

The video synthesis result.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
182
183
184
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    prompt: Any = None,
    # """@deprecated, use prompt_extend in parameters """
    extend_prompt: bool = True,
    negative_prompt: str = None,
    template: str = None,
    img_url: str = None,
    audio_url: str = None,
    reference_video_urls: List[str] = None,
    reference_urls: List[str] = None,
    reference_url: str = None,
    reference_video_description: List[str] = None,
    api_key: str = None,
    extra_input: Dict = None,
    workspace: str = None,
    task: str = None,
    head_frame: str = None,
    tail_frame: str = None,
    first_frame_url: str = None,
    last_frame_url: str = None,
    media: List[Dict] = None,
    size: Optional[str] = None,
    duration: Optional[int] = None,
    seed: Optional[int] = None,
    prompt_extend: Optional[bool] = None,
    watermark: Optional[bool] = None,
    resolution: Optional[str] = None,
    ratio: Optional[str] = None,
    shot_type: Optional[str] = None,
    audio_setting: Optional[str] = None,
    enable_thinking: Optional[bool] = None,
    **kwargs,
) -> VideoSynthesisResponse:
    """Call video synthesis service and get result.

    Args:
        model (str): The model, reference ``Models``.
        prompt (Any): The prompt for video synthesis.
        extend_prompt (bool): @deprecated, use prompt_extend in parameters
        negative_prompt (str): The negative prompt is the opposite
            of the prompt meaning.
        template (str): LoRa input, such as gufeng, katong, etc.
        img_url (str): The input image url.
        audio_url (str): The input audio url.
        reference_video_urls (List[str]): Character reference video
            file urls.
        reference_urls (List[str]): Character reference file urls.
        reference_url (str): Reference file url.
        reference_video_description (List[str]): Description for
            reference video picture and sound.
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        extra_input (Dict): The extra input parameters.
        task (str): The task of api, ref doc.
        head_frame (str): URL of the first frame image.
        tail_frame (str): URL of the last frame image.
        first_frame_url (str): URL of the first frame image.
        last_frame_url (str): URL of the last frame image.
        media (list): media file list.
        size (str, optional): Output video size (width*height),
            e.g. "1280*720".
        duration (int, optional): Duration of video in seconds.
            Default is 5.
        seed (int, optional): Random seed for video generation.
        prompt_extend (bool, optional): Whether to extend prompt
            automatically for better results.
        watermark (bool, optional): Whether to add watermark.
        resolution (str, optional): Output resolution, e.g.
            "720P", "1080P".
        ratio (str, optional): Aspect ratio, e.g. "16:9", "9:16".
        shot_type (str, optional): Shot type for video generation.
        audio_setting (str, optional): Audio setting for video,
            "auto" or "origin".
        enable_thinking (bool, optional): Whether to use Agentic PE.
        **kwargs (Any): Additional parameters passed to the API.

    Raises:
        InputRequired: The prompt cannot be empty.

    Returns:
        VideoSynthesisResponse: The video synthesis result.
    """
    if size is not None:
        kwargs["size"] = size
    if duration is not None:
        kwargs["duration"] = duration
    if seed is not None:
        kwargs["seed"] = seed
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if resolution is not None:
        kwargs["resolution"] = resolution
    if ratio is not None:
        kwargs["ratio"] = ratio
    if shot_type is not None:
        kwargs["shot_type"] = shot_type
    if audio_setting is not None:
        kwargs["audio_setting"] = audio_setting
    if enable_thinking is not None:
        kwargs["enable_thinking"] = enable_thinking
    return super().call(  # type: ignore[return-value]
        model,
        prompt,
        img_url=img_url,
        audio_url=audio_url,
        reference_video_urls=reference_video_urls,
        reference_urls=reference_urls,
        reference_url=reference_url,
        reference_video_description=reference_video_description,
        api_key=api_key,
        extend_prompt=extend_prompt,
        negative_prompt=negative_prompt,
        template=template,
        workspace=workspace,
        extra_input=extra_input,
        task=task,
        head_frame=head_frame,
        tail_frame=tail_frame,
        first_frame_url=first_frame_url,
        last_frame_url=last_frame_url,
        media=media,
        **kwargs,
    )

async_call classmethod

async_call(
    model: str,
    prompt: Any = None,
    img_url: str | None = None,
    audio_url: str | None = None,
    reference_video_urls: List[str] | None = None,
    reference_urls: List[str] = None,
    reference_url: str = None,
    reference_video_description: List[str] = None,
    extend_prompt: bool = True,
    negative_prompt: str | None = None,
    template: str = None,
    api_key: str | None = None,
    extra_input: Dict = None,
    workspace: str | None = None,
    task: str = None,
    head_frame: str = None,
    tail_frame: str = None,
    first_frame_url: str = None,
    last_frame_url: str = None,
    media: List[Dict] = None,
    size: str | None = None,
    duration: int | None = None,
    seed: int | None = None,
    prompt_extend: bool | None = None,
    watermark: bool | None = None,
    resolution: str | None = None,
    ratio: str | None = None,
    shot_type: Optional[str] = None,
    audio_setting: Optional[str] = None,
    enable_thinking: Optional[bool] = None,
    **kwargs: Any
) -> VideoSynthesisResponse

Create a video synthesis task, and return task information.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
prompt Any

The prompt for video synthesis.

None
extend_prompt bool

@deprecated, use prompt_extend in parameters

True
negative_prompt str

The negative prompt is the opposite of the prompt meaning.

None
template str

LoRa input, such as gufeng, katong, etc.

None
img_url str

The input image url.

None
audio_url str

The input audio url.

None
reference_video_urls List[str]

Character reference video file urls.

None
reference_urls List[str]

Character reference file urls.

None
reference_url str

Reference file url.

None
reference_video_description List[str]

Description for reference video picture and sound.

None
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
extra_input Dict

The extra input parameters.

None
task str

The task of api, ref doc.

None
head_frame str

URL of the first frame image.

None
tail_frame str

URL of the last frame image.

None
first_frame_url str

URL of the first frame image.

None
last_frame_url str

URL of the last frame image.

None
media list

media file list.

None
size str

Output video size (width*height).

None
duration int

Duration of video in seconds.

None
seed int

Random seed for video generation.

None
prompt_extend bool

Whether to extend prompt.

None
watermark bool

Whether to add watermark.

None
resolution str

Output resolution.

None
ratio str

Aspect ratio, e.g. "16:9".

None
shot_type str

Shot type for video generation.

None
audio_setting str

Audio setting for video, "auto" or "origin".

None
enable_thinking bool

Whether to use Agentic PE.

None
**kwargs Any

Additional parameters passed to the API.

{}

Raises:

Type Description
InputRequired

The prompt cannot be empty.

Returns:

Name Type Description
DashScopeAPIResponse VideoSynthesisResponse

The video synthesis task id in the response.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
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
410
411
412
413
414
415
416
417
418
419
420
421
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
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
@classmethod
# type: ignore[override]
def async_call(  # pylint: disable=arguments-renamed  # type: ignore[override] # noqa: E501
    cls,
    model: str,
    prompt: Any = None,
    img_url: str = None,
    audio_url: str = None,
    reference_video_urls: List[str] = None,
    reference_urls: List[str] = None,
    reference_url: str = None,
    reference_video_description: List[str] = None,
    # """@deprecated, use prompt_extend in parameters """
    extend_prompt: bool = True,
    negative_prompt: str = None,
    template: str = None,
    api_key: str = None,
    extra_input: Dict = None,
    workspace: str = None,
    task: str = None,
    head_frame: str = None,
    tail_frame: str = None,
    first_frame_url: str = None,
    last_frame_url: str = None,
    media: List[Dict] = None,
    size: Optional[str] = None,
    duration: Optional[int] = None,
    seed: Optional[int] = None,
    prompt_extend: Optional[bool] = None,
    watermark: Optional[bool] = None,
    resolution: Optional[str] = None,
    ratio: Optional[str] = None,
    shot_type: Optional[str] = None,
    audio_setting: Optional[str] = None,
    enable_thinking: Optional[bool] = None,
    **kwargs,
) -> VideoSynthesisResponse:
    """Create a video synthesis task, and return task information.

    Args:
        model (str): The model, reference ``Models``.
        prompt (Any): The prompt for video synthesis.
        extend_prompt (bool): @deprecated, use prompt_extend in parameters
        negative_prompt (str): The negative prompt is the opposite
            of the prompt meaning.
        template (str): LoRa input, such as gufeng, katong, etc.
        img_url (str): The input image url.
        audio_url (str): The input audio url.
        reference_video_urls (List[str]): Character reference video
            file urls.
        reference_urls (List[str]): Character reference file urls.
        reference_url (str): Reference file url.
        reference_video_description (List[str]): Description for
            reference video picture and sound.
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        extra_input (Dict): The extra input parameters.
        task (str): The task of api, ref doc.
        head_frame (str): URL of the first frame image.
        tail_frame (str): URL of the last frame image.
        first_frame_url (str): URL of the first frame image.
        last_frame_url (str): URL of the last frame image.
        media (list): media file list.
        size (str, optional): Output video size (width*height).
        duration (int, optional): Duration of video in seconds.
        seed (int, optional): Random seed for video generation.
        prompt_extend (bool, optional): Whether to extend prompt.
        watermark (bool, optional): Whether to add watermark.
        resolution (str, optional): Output resolution.
        ratio (str, optional): Aspect ratio, e.g. "16:9".
        shot_type (str, optional): Shot type for video generation.
        audio_setting (str, optional): Audio setting for video,
            "auto" or "origin".
        enable_thinking (bool, optional): Whether to use Agentic PE.
        **kwargs (Any): Additional parameters passed to the API.

    Raises:
        InputRequired: The prompt cannot be empty.

    Returns:
        DashScopeAPIResponse: The video synthesis
            task id in the response.
    """
    if size is not None:
        kwargs["size"] = size
    if duration is not None:
        kwargs["duration"] = duration
    if seed is not None:
        kwargs["seed"] = seed
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if resolution is not None:
        kwargs["resolution"] = resolution
    if ratio is not None:
        kwargs["ratio"] = ratio
    if shot_type is not None:
        kwargs["shot_type"] = shot_type
    if audio_setting is not None:
        kwargs["audio_setting"] = audio_setting
    if enable_thinking is not None:
        kwargs["enable_thinking"] = enable_thinking
    task_group, function = _get_task_group_and_task(__name__)

    inputs, kwargs, task = cls._get_input(
        model,
        prompt,
        img_url,
        audio_url,
        reference_video_urls,
        reference_urls,
        reference_url,
        reference_video_description,
        extend_prompt,
        negative_prompt,
        template,
        api_key,
        extra_input,
        task,
        function,
        head_frame,
        tail_frame,
        first_frame_url,
        last_frame_url,
        media,
        **kwargs,
    )

    response = super().async_call(
        model=model,
        task_group=task_group,
        task=VideoSynthesis.task if task is None else task,
        function=function,
        api_key=api_key,
        input=inputs,
        workspace=workspace,
        **kwargs,
    )
    return VideoSynthesisResponse.from_api_response(response)

fetch classmethod

fetch(
    task: Union[str, VideoSynthesisResponse],
    api_key: str | None = None,
    workspace: str | None = None,
) -> VideoSynthesisResponse

Fetch video synthesis task status or result.

Parameters:

Name Type Description Default
task Union[str, VideoSynthesisResponse]

The task_id or VideoSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
VideoSynthesisResponse VideoSynthesisResponse

The task status or result.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
@classmethod
def fetch(  # type: ignore[override]
    cls,
    task: Union[str, VideoSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
) -> VideoSynthesisResponse:
    """Fetch video synthesis task status or result.

    Args:
        task (Union[str, VideoSynthesisResponse]): The task_id or
            VideoSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        VideoSynthesisResponse: The task status or result.
    """
    response = super().fetch(task, api_key=api_key, workspace=workspace)
    return VideoSynthesisResponse.from_api_response(response)

wait classmethod

wait(
    task: Union[str, VideoSynthesisResponse],
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> VideoSynthesisResponse

Wait for video synthesis task to complete, and return the result.

Parameters:

Name Type Description Default
task Union[str, VideoSynthesisResponse]

The task_id or VideoSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
VideoSynthesisResponse VideoSynthesisResponse

The task result.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
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
@classmethod
def wait(  # type: ignore[override]
    cls,
    task: Union[str, VideoSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> VideoSynthesisResponse:
    """Wait for video synthesis task to complete, and return the result.

    Args:
        task (Union[str, VideoSynthesisResponse]): The task_id or
            VideoSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        VideoSynthesisResponse: The task result.
    """
    response = super().wait(
        task,
        api_key,
        workspace=workspace,
        **kwargs,
    )
    return VideoSynthesisResponse.from_api_response(response)

cancel classmethod

cancel(
    task: Union[str, VideoSynthesisResponse],
    api_key: str | None = None,
    workspace: str | None = None,
) -> DashScopeAPIResponse

Cancel video synthesis task. Only tasks whose status is PENDING can be canceled.

Parameters:

Name Type Description Default
task Union[str, VideoSynthesisResponse]

The task_id or VideoSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
@classmethod
def cancel(  # type: ignore[override]
    cls,
    task: Union[str, VideoSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
) -> DashScopeAPIResponse:
    """Cancel video synthesis task.
    Only tasks whose status is PENDING can be canceled.

    Args:
        task (Union[str, VideoSynthesisResponse]): The task_id or
            VideoSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return super().cancel(task, api_key, workspace=workspace)

list classmethod

list(
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List async tasks.

Parameters:

Name Type Description Default
start_time str

The tasks start time, for example: 20230420000000. Defaults to None.

None
end_time str

The tasks end time, for example: 20230420000000. Defaults to None.

None
model_name str

The tasks model name. Defaults to None.

None
api_key_id str

The tasks api-key-id. Defaults to None.

None
region str

The service region, for example: cn-beijing. Defaults to None.

None
status str

The status of tasks[PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.

None
page_no int

The page number. Defaults to 1.

1
page_size int

The page size. Defaults to 10.

10
api_key str

The user api-key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
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
@classmethod
def list(
    cls,
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List async tasks.

    Args:
        start_time (str, optional): The tasks start time,
            for example: 20230420000000. Defaults to None.
        end_time (str, optional): The tasks end time,
            for example: 20230420000000. Defaults to None.
        model_name (str, optional): The tasks model name. Defaults to None.
        api_key_id (str, optional): The tasks api-key-id. Defaults to None.
        region (str, optional): The service region,
            for example: cn-beijing. Defaults to None.
        status (str, optional): The status of tasks[PENDING,
            RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
        page_no (int, optional): The page number. Defaults to 1.
        page_size (int, optional): The page size. Defaults to 10.
        api_key (str, optional): The user api-key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return super().list(
        start_time=start_time,
        end_time=end_time,
        model_name=model_name,
        api_key_id=api_key_id,
        region=region,
        status=status,
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

AioVideoSynthesis

Bases: BaseAsyncAioApi

call async classmethod

call(
    model: str,
    prompt: Any = None,
    img_url: str = None,
    audio_url: str = None,
    reference_video_urls: List[str] = None,
    reference_urls: List[str] = None,
    reference_url: str = None,
    reference_video_description: List[str] = None,
    extend_prompt: bool = True,
    negative_prompt: str = None,
    template: str = None,
    api_key: str = None,
    extra_input: Dict = None,
    workspace: str = None,
    task: str = None,
    head_frame: str = None,
    tail_frame: str = None,
    first_frame_url: str = None,
    last_frame_url: str = None,
    media: List[Dict] = None,
    size: str = None,
    duration: int = None,
    seed: int = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    resolution: str = None,
    ratio: str = None,
    shot_type: str = None,
    audio_setting: str = None,
    enable_thinking: bool = None,
    **kwargs
) -> VideoSynthesisResponse

Call video synthesis service and get result.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
prompt Any

The prompt for video synthesis.

None
extend_prompt bool

@deprecated, use prompt_extend in parameters

True
negative_prompt str

The negative prompt is the opposite of the prompt meaning.

None
template str

LoRa input, such as gufeng, katong, etc.

None
img_url str

The input image url.

None
audio_url str

The input audio url.

None
reference_video_urls List[str]

Character reference video file urls.

None
reference_urls List[str]

Character reference file urls.

None
reference_url str

Reference file url.

None
reference_video_description List[str]

Description for reference video picture and sound.

None
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
extra_input Dict

The extra input parameters.

None
task str

The task of api, ref doc.

None
head_frame str

URL of the first frame image.

None
tail_frame str

URL of the last frame image.

None
first_frame_url str

URL of the first frame image.

None
last_frame_url str

URL of the last frame image.

None
media list

media file list.

None
size str

Output video size (width*height).

None
duration int

Duration of video in seconds.

None
seed int

Random seed for video generation.

None
prompt_extend bool

Whether to extend prompt.

None
watermark bool

Whether to add watermark.

None
resolution str

Output resolution.

None
ratio str

Aspect ratio, e.g. "16:9".

None
shot_type str

Shot type for video generation.

None
audio_setting str

Audio setting for video, "auto" or "origin".

None
enable_thinking bool

Whether to use Agentic PE.

None
**kwargs Any

Additional parameters passed to the API.

{}

Raises:

Type Description
InputRequired

The prompt cannot be empty.

Returns:

Name Type Description
VideoSynthesisResponse VideoSynthesisResponse

The video synthesis result.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
637
638
639
640
641
642
643
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
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
769
770
771
772
773
774
775
@classmethod
async def call(  # type: ignore[override] # pylint: disable=arguments-renamed  # noqa: E501
    # type: ignore[override]
    cls,
    model: str,
    prompt: Any = None,
    img_url: str = None,
    audio_url: str = None,
    reference_video_urls: List[str] = None,
    reference_urls: List[str] = None,
    reference_url: str = None,
    reference_video_description: List[str] = None,
    # """@deprecated, use prompt_extend in parameters """
    extend_prompt: bool = True,
    negative_prompt: str = None,
    template: str = None,
    api_key: str = None,
    extra_input: Dict = None,
    workspace: str = None,
    task: str = None,
    head_frame: str = None,
    tail_frame: str = None,
    first_frame_url: str = None,
    last_frame_url: str = None,
    media: List[Dict] = None,
    size: str = None,
    duration: int = None,
    seed: int = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    resolution: str = None,
    ratio: str = None,
    shot_type: str = None,
    audio_setting: str = None,
    enable_thinking: bool = None,
    **kwargs,
) -> VideoSynthesisResponse:
    """Call video synthesis service and get result.

    Args:
        model (str): The model, reference ``Models``.
        prompt (Any): The prompt for video synthesis.
        extend_prompt (bool): @deprecated, use prompt_extend in parameters
        negative_prompt (str): The negative prompt is the opposite
            of the prompt meaning.
        template (str): LoRa input, such as gufeng, katong, etc.
        img_url (str): The input image url.
        audio_url (str): The input audio url.
        reference_video_urls (List[str]): Character reference video
            file urls.
        reference_urls (List[str]): Character reference file urls.
        reference_url (str): Reference file url.
        reference_video_description (List[str]): Description for
            reference video picture and sound.
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        extra_input (Dict): The extra input parameters.
        task (str): The task of api, ref doc.
        head_frame (str): URL of the first frame image.
        tail_frame (str): URL of the last frame image.
        first_frame_url (str): URL of the first frame image.
        last_frame_url (str): URL of the last frame image.
        media (list): media file list.
        size (str, optional): Output video size (width*height).
        duration (int, optional): Duration of video in seconds.
        seed (int, optional): Random seed for video generation.
        prompt_extend (bool, optional): Whether to extend prompt.
        watermark (bool, optional): Whether to add watermark.
        resolution (str, optional): Output resolution.
        ratio (str, optional): Aspect ratio, e.g. "16:9".
        shot_type (str, optional): Shot type for video generation.
        audio_setting (str, optional): Audio setting for video,
            "auto" or "origin".
        enable_thinking (bool, optional): Whether to use Agentic PE.
        **kwargs (Any): Additional parameters passed to the API.

    Raises:
        InputRequired: The prompt cannot be empty.

    Returns:
        VideoSynthesisResponse: The video synthesis result.
    """
    if size is not None:
        kwargs["size"] = size
    if duration is not None:
        kwargs["duration"] = duration
    if seed is not None:
        kwargs["seed"] = seed
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if resolution is not None:
        kwargs["resolution"] = resolution
    if ratio is not None:
        kwargs["ratio"] = ratio
    if shot_type is not None:
        kwargs["shot_type"] = shot_type
    if audio_setting is not None:
        kwargs["audio_setting"] = audio_setting
    if enable_thinking is not None:
        kwargs["enable_thinking"] = enable_thinking
    task_group, f = _get_task_group_and_task(__name__)
    # pylint: disable=protected-access
    inputs, kwargs, task = VideoSynthesis._get_input(
        model,
        # pylint: disable=protected-access
        prompt,
        img_url,
        audio_url,
        reference_video_urls,
        reference_urls,
        reference_url,
        reference_video_description,
        extend_prompt,
        negative_prompt,
        template,
        api_key,
        extra_input,
        task,
        f,
        head_frame,
        tail_frame,
        first_frame_url,
        last_frame_url,
        media,
        **kwargs,
    )
    response = await super().call(
        model,
        inputs,
        task_group,
        task,
        f,
        api_key,
        workspace,
        **kwargs,
    )
    return VideoSynthesisResponse.from_api_response(response)

async_call async classmethod

async_call(
    model: str,
    prompt: Any = None,
    img_url: str = None,
    audio_url: str = None,
    reference_video_urls: List[str] = None,
    reference_urls: List[str] = None,
    reference_url: str = None,
    reference_video_description: List[str] = None,
    extend_prompt: bool = True,
    negative_prompt: str = None,
    template: str = None,
    api_key: str = None,
    extra_input: Dict = None,
    workspace: str = None,
    task: str = None,
    head_frame: str = None,
    tail_frame: str = None,
    first_frame_url: str = None,
    last_frame_url: str = None,
    media: List[Dict] = None,
    size: str = None,
    duration: int = None,
    seed: int = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    resolution: str = None,
    ratio: str = None,
    shot_type: str = None,
    audio_setting: str = None,
    enable_thinking: bool = None,
    **kwargs
) -> VideoSynthesisResponse

Create a video synthesis task, and return task information.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
prompt Any

The prompt for video synthesis.

None
extend_prompt bool

@deprecated, use prompt_extend in parameters

True
negative_prompt str

The negative prompt is the opposite of the prompt meaning.

None
template str

LoRa input, such as gufeng, katong, etc.

None
img_url str

The input image url.

None
audio_url str

The input audio url.

None
reference_video_urls List[str]

Character reference video file urls.

None
reference_urls List[str]

Character reference file urls.

None
reference_url str

Reference file url.

None
reference_video_description List[str]

Description for reference video picture and sound.

None
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
extra_input Dict

The extra input parameters.

None
task str

The task of api, ref doc.

None
head_frame str

URL of the first frame image.

None
tail_frame str

URL of the last frame image.

None
first_frame_url str

URL of the first frame image.

None
last_frame_url str

URL of the last frame image.

None
media list

media file list.

None
size str

Output video size (width*height).

None
duration int

Duration of video in seconds.

None
seed int

Random seed for video generation.

None
prompt_extend bool

Whether to extend prompt.

None
watermark bool

Whether to add watermark.

None
resolution str

Output resolution.

None
ratio str

Aspect ratio, e.g. "16:9".

None
shot_type str

Shot type for video generation.

None
enable_thinking bool

Whether to use Agentic PE.

None
audio_setting str

Audio setting for video,

None
**kwargs Any

Additional parameters passed to the API.

{}

Raises:

Type Description
InputRequired

The prompt cannot be empty.

Returns:

Name Type Description
DashScopeAPIResponse VideoSynthesisResponse

The video synthesis task id in the response.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
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
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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
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
913
914
915
916
917
918
@classmethod
async def async_call(  # type: ignore[override] # pylint: disable=arguments-renamed # noqa: E501
    cls,
    model: str,
    prompt: Any = None,
    img_url: str = None,
    audio_url: str = None,
    reference_video_urls: List[str] = None,
    reference_urls: List[str] = None,
    reference_url: str = None,
    reference_video_description: List[str] = None,
    # """@deprecated, use prompt_extend in parameters """
    extend_prompt: bool = True,
    negative_prompt: str = None,
    template: str = None,
    api_key: str = None,
    extra_input: Dict = None,
    workspace: str = None,
    task: str = None,
    head_frame: str = None,
    tail_frame: str = None,
    first_frame_url: str = None,
    last_frame_url: str = None,
    media: List[Dict] = None,
    size: str = None,
    duration: int = None,
    seed: int = None,
    prompt_extend: bool = None,
    watermark: bool = None,
    resolution: str = None,
    ratio: str = None,
    shot_type: str = None,
    audio_setting: str = None,
    enable_thinking: bool = None,
    **kwargs,
) -> VideoSynthesisResponse:
    """Create a video synthesis task, and return task information.

    Args:
        model (str): The model, reference ``Models``.
        prompt (Any): The prompt for video synthesis.
        extend_prompt (bool): @deprecated, use prompt_extend in parameters
        negative_prompt (str): The negative prompt is the opposite
            of the prompt meaning.
        template (str): LoRa input, such as gufeng, katong, etc.
        img_url (str): The input image url.
        audio_url (str): The input audio url.
        reference_video_urls (List[str]): Character reference video
            file urls.
        reference_urls (List[str]): Character reference file urls.
        reference_url (str): Reference file url.
        reference_video_description (List[str]): Description for
            reference video picture and sound.
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        extra_input (Dict): The extra input parameters.
        task (str): The task of api, ref doc.
        head_frame (str): URL of the first frame image.
        tail_frame (str): URL of the last frame image.
        first_frame_url (str): URL of the first frame image.
        last_frame_url (str): URL of the last frame image.
        media (list): media file list.
        size (str, optional): Output video size (width*height).
        duration (int, optional): Duration of video in seconds.
        seed (int, optional): Random seed for video generation.
        prompt_extend (bool, optional): Whether to extend prompt.
        watermark (bool, optional): Whether to add watermark.
        resolution (str, optional): Output resolution.
        ratio (str, optional): Aspect ratio, e.g. "16:9".
        shot_type (str, optional): Shot type for video generation.
        enable_thinking (bool, optional): Whether to use Agentic PE.
        audio_setting (str, optional): Audio setting for video,
        **kwargs (Any): Additional parameters passed to the API.

    Raises:
        InputRequired: The prompt cannot be empty.

    Returns:
        DashScopeAPIResponse: The video synthesis
            task id in the response.
    """
    if size is not None:
        kwargs["size"] = size
    if duration is not None:
        kwargs["duration"] = duration
    if seed is not None:
        kwargs["seed"] = seed
    if prompt_extend is not None:
        kwargs["prompt_extend"] = prompt_extend
    if watermark is not None:
        kwargs["watermark"] = watermark
    if resolution is not None:
        kwargs["resolution"] = resolution
    if ratio is not None:
        kwargs["ratio"] = ratio
    if shot_type is not None:
        kwargs["shot_type"] = shot_type
    if audio_setting is not None:
        kwargs["audio_setting"] = audio_setting
    if enable_thinking is not None:
        kwargs["enable_thinking"] = enable_thinking
    task_group, function = _get_task_group_and_task(__name__)

    # pylint: disable=protected-access
    inputs, kwargs, task = VideoSynthesis._get_input(
        model,
        # pylint: disable=protected-access
        prompt,
        img_url,
        audio_url,
        reference_video_urls,
        reference_urls,
        reference_url,
        reference_video_description,
        extend_prompt,
        negative_prompt,
        template,
        api_key,
        extra_input,
        task,
        function,
        head_frame,
        tail_frame,
        first_frame_url,
        last_frame_url,
        media,
        **kwargs,
    )

    response = await super().async_call(
        model=model,
        task_group=task_group,
        task=VideoSynthesis.task if task is None else task,
        function=function,
        api_key=api_key,
        input=inputs,
        workspace=workspace,
        **kwargs,
    )
    return VideoSynthesisResponse.from_api_response(response)

fetch async classmethod

fetch(
    task: Union[str, VideoSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> VideoSynthesisResponse

Fetch video synthesis task status or result.

Parameters:

Name Type Description Default
task Union[str, VideoSynthesisResponse]

The task_id or VideoSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
VideoSynthesisResponse VideoSynthesisResponse

The task status or result.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
@classmethod
async def fetch(
    cls,
    task: Union[str, VideoSynthesisResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> VideoSynthesisResponse:
    """Fetch video synthesis task status or result.

    Args:
        task (Union[str, VideoSynthesisResponse]): The task_id or
            VideoSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        VideoSynthesisResponse: The task status or result.
    """
    response = await super().fetch(
        task,
        api_key=api_key,
        workspace=workspace,
    )
    return VideoSynthesisResponse.from_api_response(response)

wait async classmethod

wait(
    task: Union[str, VideoSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs
) -> VideoSynthesisResponse

Wait for video synthesis task to complete, and return the result.

Parameters:

Name Type Description Default
task Union[str, VideoSynthesisResponse]

The task_id or VideoSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
wait_timeout int

The maximum seconds to wait. Default is -1 (no timeout).

-1

Returns:

Name Type Description
VideoSynthesisResponse VideoSynthesisResponse

The task result.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
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
972
973
974
@classmethod
async def wait(
    cls,
    task: Union[str, VideoSynthesisResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs,
) -> VideoSynthesisResponse:
    """Wait for video synthesis task to complete, and return the result.

    Args:
        task (Union[str, VideoSynthesisResponse]): The task_id or
            VideoSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        wait_timeout (int, optional): The maximum seconds to wait.
            Default is -1 (no timeout).

    Returns:
        VideoSynthesisResponse: The task result.
    """
    response = await super().wait(
        task,
        api_key,
        workspace=workspace,
        wait_timeout=wait_timeout,
    )
    return VideoSynthesisResponse.from_api_response(response)

cancel async classmethod

cancel(
    task: Union[str, VideoSynthesisResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Cancel video synthesis task. Only tasks whose status is PENDING can be canceled.

Parameters:

Name Type Description Default
task Union[str, VideoSynthesisResponse]

The task_id or VideoSynthesisResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
@classmethod
async def cancel(
    cls,
    task: Union[str, VideoSynthesisResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Cancel video synthesis task.
    Only tasks whose status is PENDING can be canceled.

    Args:
        task (Union[str, VideoSynthesisResponse]): The task_id or
            VideoSynthesisResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return await super().cancel(task, api_key, workspace=workspace)

list async classmethod

list(
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List async tasks.

Parameters:

Name Type Description Default
start_time str

The tasks start time, for example: 20230420000000. Defaults to None.

None
end_time str

The tasks end time, for example: 20230420000000. Defaults to None.

None
model_name str

The tasks model name. Defaults to None.

None
api_key_id str

The tasks api-key-id. Defaults to None.

None
region str

The service region, for example: cn-beijing. Defaults to None.

None
status str

The status of tasks[PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.

None
page_no int

The page number. Defaults to 1.

1
page_size int

The page size. Defaults to 10.

10
api_key str

The user api-key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/aigc/video_synthesis.py
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
@classmethod
async def list(
    cls,
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List async tasks.

    Args:
        start_time (str, optional): The tasks start time,
            for example: 20230420000000. Defaults to None.
        end_time (str, optional): The tasks end time,
            for example: 20230420000000. Defaults to None.
        model_name (str, optional): The tasks model name. Defaults to None.
        api_key_id (str, optional): The tasks api-key-id. Defaults to None.
        region (str, optional): The service region,
            for example: cn-beijing. Defaults to None.
        status (str, optional): The status of tasks[PENDING,
            RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
        page_no (int, optional): The page number. Defaults to 1.
        page_size (int, optional): The page size. Defaults to 10.
        api_key (str, optional): The user api-key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return await super().list(
        start_time=start_time,
        end_time=end_time,
        model_name=model_name,
        api_key_id=api_key_id,
        region=region,
        status=status,
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

Embeddings

TextEmbedding

Bases: BaseApi

task class-attribute instance-attribute

task = 'text-embedding'

Models

text_embedding_v1 class-attribute instance-attribute
text_embedding_v1 = 'text-embedding-v1'
text_embedding_v2 class-attribute instance-attribute
text_embedding_v2 = 'text-embedding-v2'
text_embedding_v3 class-attribute instance-attribute
text_embedding_v3 = 'text-embedding-v3'
text_embedding_v4 class-attribute instance-attribute
text_embedding_v4 = 'text-embedding-v4'
qwen3_7_text_embedding class-attribute instance-attribute
qwen3_7_text_embedding = 'qwen3.7-text-embedding'

call classmethod

call(
    model: str,
    input: Union[str, List[str]],
    workspace: str | None = None,
    api_key: str | None = None,
    text_type: str | None = None,
    dimension: int | None = None,
    output_type: str | None = None,
    instruct: str | None = None,
    **kwargs: Any
) -> DashScopeAPIResponse

Get embedding of text input.

Parameters:

Name Type Description Default
model str

The embedding model name.

required
input Union[str, List[str], IOBase]

The text input, can be a text or list of text or opened file object, if opened file object, will read all lines, one embedding per line.

required
workspace str

The dashscope workspace id.

None
text_type str

"query" for search queries, "document" (default) for corpus/symmetric tasks.

None
dimension int

Output vector dimension. Options: 2048 (v4 only), 1536 (v4 only), 1024 (default), 768, 512, 256, 128, 64. Only for v3/v4.

None
output_type str

Output format: "dense" (default), "sparse", or "dense&sparse". Only for v3/v4.

None
instruct str

Custom task instruction to guide model understanding of query intent.

None
**kwargs Any

Additional parameters passed to the API.

{}

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The embedding result.

Source code in dashscope/legacy_1x/embeddings/text_embedding.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
@classmethod
def call(  # type: ignore[override]  # pylint: disable=arguments-renamed
    cls,
    model: str,
    input: Union[str, List[str]],  # pylint: disable=redefined-builtin
    workspace: str = None,
    api_key: str = None,
    text_type: str = None,
    dimension: int = None,
    output_type: str = None,
    instruct: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Get embedding of text input.

    Args:
        model (str): The embedding model name.
        input (Union[str, List[str], io.IOBase]): The text input,
            can be a text or list of text or opened file object,
            if opened file object, will read all lines,
            one embedding per line.
        workspace (str): The dashscope workspace id.
        text_type (str, optional): "query" for search queries,
            "document" (default) for corpus/symmetric tasks.
        dimension (int, optional): Output vector dimension.
            Options: 2048 (v4 only), 1536 (v4 only), 1024 (default),
            768, 512, 256, 128, 64. Only for v3/v4.
        output_type (str, optional): Output format: "dense" (default),
            "sparse", or "dense&sparse". Only for v3/v4.
        instruct (str, optional): Custom task instruction to guide
            model understanding of query intent.
        **kwargs:
            Additional parameters passed to the API.

    Returns:
        DashScopeAPIResponse: The embedding result.
    """
    embedding_input = {}
    if isinstance(input, str):
        embedding_input[TEXT_EMBEDDING_INPUT_KEY] = [input]
    else:
        embedding_input[TEXT_EMBEDDING_INPUT_KEY] = input
    kwargs.pop("stream", False)  # not support streaming output.
    if text_type is not None:
        kwargs["text_type"] = text_type
    if dimension is not None:
        kwargs["dimension"] = dimension
    if output_type is not None:
        kwargs["output_type"] = output_type
    if instruct is not None:
        kwargs["instruct"] = instruct
    task_group, function = _get_task_group_and_task(__name__)
    return super().call(
        model=model,
        input=embedding_input,
        task_group=task_group,
        task=TextEmbedding.task,
        function=function,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

BatchTextEmbedding

Bases: BaseAsyncApi

task class-attribute instance-attribute

task = 'text-embedding'

function class-attribute instance-attribute

function = 'text-embedding'

API for async text embedding.

Models

text_embedding_async_v1 class-attribute instance-attribute
text_embedding_async_v1 = 'text-embedding-async-v1'
text_embedding_async_v2 class-attribute instance-attribute
text_embedding_async_v2 = 'text-embedding-async-v2'

call classmethod

call(
    model: str,
    url: str,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> BatchTextEmbeddingResponse

Call async text embedding service and get result.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
url Any

The async request file url, which contains text to embedding line by line.

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
**kwargs Any

text_type(str, optional): [query|document], After the text is converted into a vector, it can be applied to downstream tasks such as retrieval, clustering, and classification. For asymmetric tasks such as retrieval, in order to achieve better retrieval results, it is recommended to distinguish between query text (query) and bottom database text (document) types, clustering Symmetric tasks such as , classification, etc. do not need to be specially specified, and the system default value "document" can be used

{}

Raises: InputRequired: The url cannot be empty.

Returns:

Name Type Description
AsyncTextEmbeddingResponse BatchTextEmbeddingResponse

The async text embedding task result.

Source code in dashscope/legacy_1x/embeddings/batch_text_embedding.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    url: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> BatchTextEmbeddingResponse:
    """Call async text embedding service and get result.

    Args:
        model (str): The model, reference ``Models``.
        url (Any): The async request file url, which contains text
            to embedding line by line.
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        **kwargs:
            text_type(str, `optional`): [query|document], After the
            text is converted into a vector, it can be applied to
            downstream tasks such as retrieval, clustering, and
            classification. For asymmetric tasks such as retrieval,
            in order to achieve better retrieval results, it is
            recommended to distinguish between query text (query)
            and bottom database text (document) types, clustering
            Symmetric tasks such as , classification, etc. do not
            need to be specially specified, and the system
            default value "document" can be used
    Raises:
        InputRequired: The url cannot be empty.

    Returns:
        AsyncTextEmbeddingResponse: The async text embedding task result.
    """
    return super().call(  # type: ignore[return-value]
        model,
        url,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

async_call classmethod

async_call(
    model: str,
    url: str,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> BatchTextEmbeddingResponse

Create a async text embedding task, and return task information.

Parameters:

Name Type Description Default
model str

The model, reference Models.

required
url Any

The async request file url, which contains text to embedding line by line.

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
**kwargs Any

text_type(str, optional): [query|document], After the text is converted into a vector, it can be applied to downstream tasks such as retrieval, clustering, and classification. For asymmetric tasks such as retrieval, in order to achieve better retrieval results, it is recommended to distinguish between query text (query) and bottom database text (document) types, clustering Symmetric tasks such as , classification, etc. do not need to be specially specified, and the system default value "document" can be used

{}

Raises:

Type Description
InputRequired

The url cannot be empty.

Returns:

Name Type Description
DashScopeAPIResponse BatchTextEmbeddingResponse

The image synthesis task id in the response.

Source code in dashscope/legacy_1x/embeddings/batch_text_embedding.py
 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
@classmethod
def async_call(  # type: ignore[override]
    cls,
    model: str,
    url: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> BatchTextEmbeddingResponse:
    """Create a async text embedding task, and return task information.

    Args:
        model (str): The model, reference ``Models``.
        url (Any): The async request file url, which contains text
            to embedding line by line.
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        **kwargs:
            text_type(str, `optional`): [query|document], After the
            text is converted into a vector, it can be applied to
            downstream tasks such as retrieval, clustering, and
            classification. For asymmetric tasks such as retrieval,
            in order to achieve better retrieval results, it is
            recommended to distinguish between query text (query)
            and bottom database text (document) types, clustering
            Symmetric tasks such as , classification, etc. do not
            need to be specially specified, and the system
            default value "document" can be used

    Raises:
        InputRequired: The url cannot be empty.

    Returns:
        DashScopeAPIResponse: The image synthesis
            task id in the response.
    """
    if url is None or not url:
        raise InputRequired("url is required!")
    input = {"url": url}  # pylint: disable=redefined-builtin
    task_group, _ = _get_task_group_and_task(__name__)
    response = super().async_call(
        model=model,
        task_group=task_group,
        task=BatchTextEmbedding.task,
        function=BatchTextEmbedding.function,
        api_key=api_key,
        input=input,
        workspace=workspace,
        **kwargs,
    )
    return BatchTextEmbeddingResponse.from_api_response(response)

fetch classmethod

fetch(
    task: Any,
    api_key: str | None = None,
    workspace: str | None = None,
) -> BatchTextEmbeddingResponse

Fetch async text embedding task status or result.

Parameters:

Name Type Description Default
task Union[str, AsyncTextEmbeddingResponse]

The task_id or AsyncTextEmbeddingResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
AsyncTextEmbeddingResponse BatchTextEmbeddingResponse

The task status or result.

Source code in dashscope/legacy_1x/embeddings/batch_text_embedding.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@classmethod
def fetch(  # type: ignore[override]
    cls,
    task: Union[str, BatchTextEmbeddingResponse],
    api_key: str = None,
    workspace: str = None,
) -> BatchTextEmbeddingResponse:
    """Fetch async text embedding task status or result.

    Args:
        task (Union[str, AsyncTextEmbeddingResponse]): The task_id or
            AsyncTextEmbeddingResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        AsyncTextEmbeddingResponse: The task status or result.
    """
    response = super().fetch(task, api_key, workspace=workspace)
    return BatchTextEmbeddingResponse.from_api_response(response)

wait classmethod

wait(
    task: Any,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> BatchTextEmbeddingResponse

Wait for async text embedding task to complete, and return the result. # noqa: E501

Parameters:

Name Type Description Default
task Union[str, AsyncTextEmbeddingResponse]

The task_id or AsyncTextEmbeddingResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
AsyncTextEmbeddingResponse BatchTextEmbeddingResponse

The task result.

Source code in dashscope/legacy_1x/embeddings/batch_text_embedding.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
@classmethod
def wait(  # type: ignore[override]
    cls,
    task: Union[str, BatchTextEmbeddingResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> BatchTextEmbeddingResponse:
    """Wait for async text embedding task to complete, and return the result.  # noqa: E501

    Args:
        task (Union[str, AsyncTextEmbeddingResponse]): The task_id or
            AsyncTextEmbeddingResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        AsyncTextEmbeddingResponse: The task result.
    """
    response = super().wait(
        task,
        api_key,
        workspace=workspace,
        **kwargs,
    )
    return BatchTextEmbeddingResponse.from_api_response(response)

cancel classmethod

cancel(
    task: Any,
    api_key: str | None = None,
    workspace: str | None = None,
) -> DashScopeAPIResponse

Cancel async text embedding task. Only tasks whose status is PENDING can be canceled.

Parameters:

Name Type Description Default
task Union[str, AsyncTextEmbeddingResponse]

The task_id or AsyncTextEmbeddingResponse return by async_call().

required
api_key str

The api api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/embeddings/batch_text_embedding.py
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
@classmethod
def cancel(  # type: ignore[override]
    cls,
    task: Union[str, BatchTextEmbeddingResponse],
    api_key: str = None,
    workspace: str = None,
) -> DashScopeAPIResponse:
    """Cancel async text embedding task.
    Only tasks whose status is PENDING can be canceled.

    Args:
        task (Union[str, AsyncTextEmbeddingResponse]): The task_id or
            AsyncTextEmbeddingResponse return by async_call().
        api_key (str, optional): The api api_key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return super().cancel(task, api_key, workspace=workspace)

list classmethod

list(
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List async tasks.

Parameters:

Name Type Description Default
start_time str

The tasks start time, for example: 20230420000000. Defaults to None.

None
end_time str

The tasks end time, for example: 20230420000000. Defaults to None.

None
model_name str

The tasks model name. Defaults to None.

None
api_key_id str

The tasks api-key-id. Defaults to None.

None
region str

The service region, for example: cn-beijing. Defaults to None.

None
status str

The status of tasks[PENDING, RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.

None
page_no int

The page number. Defaults to 1.

1
page_size int

The page size. Defaults to 10.

10
api_key str

The user api-key. Defaults to None.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The response data.

Source code in dashscope/legacy_1x/embeddings/batch_text_embedding.py
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
226
227
228
229
230
231
232
233
234
235
236
237
@classmethod
def list(
    cls,
    start_time: str = None,
    end_time: str = None,
    model_name: str = None,
    api_key_id: str = None,
    region: str = None,
    status: str = None,
    page_no: int = 1,
    page_size: int = 10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List async tasks.

    Args:
        start_time (str, optional): The tasks start time,
            for example: 20230420000000. Defaults to None.
        end_time (str, optional): The tasks end time,
            for example: 20230420000000. Defaults to None.
        model_name (str, optional): The tasks model name. Defaults to None.
        api_key_id (str, optional): The tasks api-key-id. Defaults to None.
        region (str, optional): The service region,
            for example: cn-beijing. Defaults to None.
        status (str, optional): The status of tasks[PENDING,
            RUNNING, SUCCEEDED, FAILED, CANCELED]. Defaults to None.
        page_no (int, optional): The page number. Defaults to 1.
        page_size (int, optional): The page size. Defaults to 10.
        api_key (str, optional): The user api-key. Defaults to None.

    Returns:
        DashScopeAPIResponse: The response data.
    """
    return super().list(
        start_time=start_time,
        end_time=end_time,
        model_name=model_name,
        api_key_id=api_key_id,
        region=region,
        status=status,
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

BatchTextEmbeddingResponse dataclass

BatchTextEmbeddingResponse(
    status_code: int,
    request_id: str = "",
    code: str = "",
    message: str = "",
    output: Any = None,
    usage: Any = None,
    headers: Dict[Any, Any] = None,
    **kwargs
)

Bases: DashScopeAPIResponse

Source code in dashscope/legacy_1x/api_entities/dashscope_response.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def __init__(
    self,
    status_code: int,
    request_id: str = "",
    code: str = "",
    message: str = "",
    output: Any = None,
    usage: Any = None,
    headers: Dict[Any, Any] = None,
    **kwargs,
):
    super().__init__(
        status_code=status_code,
        request_id=request_id,
        code=code,
        message=message,
        output=output,
        usage=usage,
        headers=headers,
        **kwargs,
    )

output instance-attribute

output: BatchTextEmbeddingOutput

usage instance-attribute

usage: BatchTextEmbeddingUsage

from_api_response staticmethod

from_api_response(api_response: DashScopeAPIResponse)
Source code in dashscope/legacy_1x/embeddings/batch_text_embedding_response.py
49
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
@staticmethod
def from_api_response(api_response: DashScopeAPIResponse):
    if api_response.status_code == HTTPStatus.OK:
        output = None
        usage = None
        if api_response.output is not None:
            output = BatchTextEmbeddingOutput(**api_response.output)
        if api_response.usage is not None:
            usage = BatchTextEmbeddingUsage(**api_response.usage)

        return BatchTextEmbeddingResponse(
            status_code=api_response.status_code,
            request_id=api_response.request_id,
            code=api_response.code,
            message=api_response.message,
            output=output,
            usage=usage,
        )

    else:
        return BatchTextEmbeddingResponse(
            status_code=api_response.status_code,
            request_id=api_response.request_id,
            code=api_response.code,
            message=api_response.message,
        )

MultiModalEmbedding

Bases: BaseApi

task class-attribute instance-attribute

task = 'multimodal-embedding'

Models

multimodal_embedding_one_peace_v1 class-attribute instance-attribute
multimodal_embedding_one_peace_v1 = (
    "multimodal-embedding-one-peace-v1"
)
multimodal_embedding_v1 class-attribute instance-attribute
multimodal_embedding_v1 = 'multimodal-embedding-v1'
qwen3_vl_embedding class-attribute instance-attribute
qwen3_vl_embedding = 'qwen3-vl-embedding'
qwen2_5_vl_embedding class-attribute instance-attribute
qwen2_5_vl_embedding = 'qwen2.5-vl-embedding'
tongyi_embedding_vision_plus class-attribute instance-attribute
tongyi_embedding_vision_plus = (
    "tongyi-embedding-vision-plus"
)
tongyi_embedding_vision_flash class-attribute instance-attribute
tongyi_embedding_vision_flash = (
    "tongyi-embedding-vision-flash"
)

call classmethod

call(
    model: str,
    input: Any,
    api_key: str | None = None,
    workspace: str | None = None,
    dimension: int | None = None,
    output_type: str = None,
    fps: float = None,
    instruct: str = None,
    enable_fusion: bool = None,
    res_level: int = None,
    max_video_frames: int = None,
    **kwargs: Any
) -> DashScopeAPIResponse

Get embedding multimodal contents..

Parameters:

Name Type Description Default
model str

The embedding model name.

required
input List[MultiModalEmbeddingElement]

The embedding elements, every element include data, modal, factor field.

required
workspace str

The dashscope workspace id.

None
dimension int

Output vector dimensions. Model-specific supported values.

None
output_type str

Output vector format, currently only "dense" is supported.

None
fps float

Video frame extraction ratio in range [0,1]. Default: 1.0.

None
instruct str

Custom task instruction to guide model understanding of query intent.

None
enable_fusion bool

Only for qwen3-vl-embedding. When True, fuses all contents into 1 vector.

None
res_level int

Resolution tier: 0/1/2/3. Only for snapshot models.

None
max_video_frames int

Max video sampling frames, up to 64. Only for snapshot models.

None
**kwargs Any

auto_truncation(bool, optional): Automatically truncate audio longer than 15 seconds or text longer than 70 words. Default to false(Too long input will result in failure).

{}

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The embedding result.

Source code in dashscope/legacy_1x/embeddings/multimodal_embedding.py
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
@classmethod
def call(  # type: ignore[override]  # pylint: disable=arguments-renamed
    cls,
    model: str,
    # pylint: disable=redefined-builtin
    input: List[MultiModalEmbeddingItemBase],
    api_key: str = None,
    workspace: str = None,
    dimension: int = None,
    output_type: str = None,
    fps: float = None,
    instruct: str = None,
    enable_fusion: bool = None,
    res_level: int = None,
    max_video_frames: int = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Get embedding multimodal contents..

    Args:
        model (str): The embedding model name.
        input (List[MultiModalEmbeddingElement]): The embedding
            elements, every element include data, modal, factor field.
        workspace (str): The dashscope workspace id.
        dimension (int, optional): Output vector dimensions.
            Model-specific supported values.
        output_type (str, optional): Output vector format,
            currently only "dense" is supported.
        fps (float, optional): Video frame extraction ratio
            in range [0,1]. Default: 1.0.
        instruct (str, optional): Custom task instruction to guide
            model understanding of query intent.
        enable_fusion (bool, optional): Only for qwen3-vl-embedding.
            When True, fuses all contents into 1 vector.
        res_level (int, optional): Resolution tier: 0/1/2/3.
            Only for snapshot models.
        max_video_frames (int, optional): Max video sampling frames,
            up to 64. Only for snapshot models.
        **kwargs:
            auto_truncation(bool, `optional`): Automatically truncate
            audio longer than 15 seconds or text longer than 70 words.
            Default to false(Too long input will result in failure).

    Returns:
        DashScopeAPIResponse: The embedding result.
    """
    if input is None or not input:
        raise InputRequired("prompt is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    embedding_input = {}
    has_upload = cls._preprocess_message_inputs(
        model,
        input,  # type: ignore[arg-type]
        api_key,
    )  # noqa: E501
    if has_upload:
        headers = kwargs.pop("headers", {})
        headers["X-DashScope-OssResourceResolve"] = "enable"
        kwargs["headers"] = headers
    embedding_input["contents"] = input
    kwargs.pop("stream", False)  # not support streaming output.
    if dimension is not None:
        kwargs["dimension"] = dimension
    if output_type is not None:
        kwargs["output_type"] = output_type
    if fps is not None:
        kwargs["fps"] = fps
    if instruct is not None:
        kwargs["instruct"] = instruct
    if enable_fusion is not None:
        kwargs["enable_fusion"] = enable_fusion
    if res_level is not None:
        kwargs["res_level"] = res_level
    if max_video_frames is not None:
        kwargs["max_video_frames"] = max_video_frames
    task_group, function = _get_task_group_and_task(__name__)
    return super().call(
        model=model,
        input=embedding_input,
        task_group=task_group,
        task=MultiModalEmbedding.task,
        function=function,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )

AioMultiModalEmbedding

Bases: BaseAioApi

task class-attribute instance-attribute

task = 'multimodal-embedding'

Models

multimodal_embedding_one_peace_v1 class-attribute instance-attribute
multimodal_embedding_one_peace_v1 = (
    "multimodal-embedding-one-peace-v1"
)
multimodal_embedding_v1 class-attribute instance-attribute
multimodal_embedding_v1 = 'multimodal-embedding-v1'
qwen3_vl_embedding class-attribute instance-attribute
qwen3_vl_embedding = 'qwen3-vl-embedding'
qwen2_5_vl_embedding class-attribute instance-attribute
qwen2_5_vl_embedding = 'qwen2.5-vl-embedding'
tongyi_embedding_vision_plus class-attribute instance-attribute
tongyi_embedding_vision_plus = (
    "tongyi-embedding-vision-plus"
)
tongyi_embedding_vision_flash class-attribute instance-attribute
tongyi_embedding_vision_flash = (
    "tongyi-embedding-vision-flash"
)

call async classmethod

call(
    model: str,
    input: Any,
    api_key: str | None = None,
    workspace: str | None = None,
    dimension: int | None = None,
    output_type: str = None,
    fps: float = None,
    instruct: str = None,
    enable_fusion: bool = None,
    res_level: int = None,
    max_video_frames: int = None,
    **kwargs: Any
) -> DashScopeAPIResponse

Get embedding multimodal contents..

Parameters:

Name Type Description Default
model str

The embedding model name.

required
input List[MultiModalEmbeddingElement]

The embedding elements, every element include data, modal, factor field.

required
workspace str

The dashscope workspace id.

None
dimension int

Output vector dimensions. Model-specific supported values.

None
output_type str

Output vector format, currently only "dense" is supported.

None
fps float

Video frame extraction ratio in range [0,1]. Default: 1.0.

None
instruct str

Custom task instruction to guide model understanding of query intent.

None
enable_fusion bool

Only for qwen3-vl-embedding. When True, fuses all contents into 1 vector.

None
res_level int

Resolution tier: 0/1/2/3. Only for snapshot models.

None
max_video_frames int

Max video sampling frames, up to 64. Only for snapshot models.

None
**kwargs Any

auto_truncation(bool, optional): Automatically truncate audio longer than 15 seconds or text longer than 70 words. Default to false(Too long input will result in failure).

{}

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The embedding result.

Source code in dashscope/legacy_1x/embeddings/multimodal_embedding.py
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
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
@classmethod
async def call(  # type: ignore[override]  # pylint: disable=arguments-renamed  # noqa: E501
    cls,
    model: str,
    # pylint: disable=redefined-builtin
    input: List[MultiModalEmbeddingItemBase],
    api_key: str = None,
    workspace: str = None,
    dimension: int = None,
    output_type: str = None,
    fps: float = None,
    instruct: str = None,
    enable_fusion: bool = None,
    res_level: int = None,
    max_video_frames: int = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Get embedding multimodal contents..

    Args:
        model (str): The embedding model name.
        input (List[MultiModalEmbeddingElement]): The embedding
            elements, every element include data, modal, factor field.
        workspace (str): The dashscope workspace id.
        dimension (int, optional): Output vector dimensions.
            Model-specific supported values.
        output_type (str, optional): Output vector format,
            currently only "dense" is supported.
        fps (float, optional): Video frame extraction ratio
            in range [0,1]. Default: 1.0.
        instruct (str, optional): Custom task instruction to guide
            model understanding of query intent.
        enable_fusion (bool, optional): Only for qwen3-vl-embedding.
            When True, fuses all contents into 1 vector.
        res_level (int, optional): Resolution tier: 0/1/2/3.
            Only for snapshot models.
        max_video_frames (int, optional): Max video sampling frames,
            up to 64. Only for snapshot models.
        **kwargs:
            auto_truncation(bool, `optional`): Automatically truncate
            audio longer than 15 seconds or text longer than 70 words.
            Default to false(Too long input will result in failure).

    Returns:
        DashScopeAPIResponse: The embedding result.
    """
    if input is None or not input:
        raise InputRequired("prompt is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    embedding_input = {}
    has_upload = cls._preprocess_message_inputs(
        model,
        input,  # type: ignore[arg-type]
        api_key,
    )  # noqa: E501
    if has_upload:
        headers = kwargs.pop("headers", {})
        headers["X-DashScope-OssResourceResolve"] = "enable"
        kwargs["headers"] = headers
    embedding_input["contents"] = input
    kwargs.pop("stream", False)  # not support streaming output.
    if dimension is not None:
        kwargs["dimension"] = dimension
    if output_type is not None:
        kwargs["output_type"] = output_type
    if fps is not None:
        kwargs["fps"] = fps
    if instruct is not None:
        kwargs["instruct"] = instruct
    if enable_fusion is not None:
        kwargs["enable_fusion"] = enable_fusion
    if res_level is not None:
        kwargs["res_level"] = res_level
    if max_video_frames is not None:
        kwargs["max_video_frames"] = max_video_frames
    task_group, function = _get_task_group_and_task(__name__)
    response = await super().call(
        model=model,
        input=embedding_input,
        task_group=task_group,
        task=MultiModalEmbedding.task,
        function=function,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return response

MultiModalEmbeddingItemText dataclass

MultiModalEmbeddingItemText(
    text: str, factor: float, **kwargs
)

Bases: MultiModalEmbeddingItemBase

Source code in dashscope/legacy_1x/embeddings/multimodal_embedding.py
29
30
31
def __init__(self, text: str, factor: float, **kwargs):
    super().__init__(factor, **kwargs)
    self.text = text

text instance-attribute

text: str = text

MultiModalEmbeddingItemImage dataclass

MultiModalEmbeddingItemImage(
    image: str, factor: float, **kwargs
)

Bases: MultiModalEmbeddingItemBase

Source code in dashscope/legacy_1x/embeddings/multimodal_embedding.py
38
39
40
def __init__(self, image: str, factor: float, **kwargs):
    super().__init__(factor, **kwargs)
    self.image = image

image instance-attribute

image: str = image

MultiModalEmbeddingItemAudio dataclass

MultiModalEmbeddingItemAudio(
    audio: str, factor: float, **kwargs
)

Bases: MultiModalEmbeddingItemBase

Source code in dashscope/legacy_1x/embeddings/multimodal_embedding.py
47
48
49
def __init__(self, audio: str, factor: float, **kwargs):
    super().__init__(factor, **kwargs)
    self.audio = audio

audio instance-attribute

audio: str = audio

Rerank

TextReRank

Bases: BaseApi

task class-attribute instance-attribute

task = 'text-rerank'

API for rerank models.

Models

gte_rerank class-attribute instance-attribute
gte_rerank = 'gte-rerank'
gte_rerank_v2 class-attribute instance-attribute
gte_rerank_v2 = 'gte-rerank-v2'
qwen3_rerank class-attribute instance-attribute
qwen3_rerank = 'qwen3-rerank'
qwen3_vl_rerank class-attribute instance-attribute
qwen3_vl_rerank = 'qwen3-vl-rerank'
qwen3_7_text_rerank class-attribute instance-attribute
qwen3_7_text_rerank = 'qwen3.7-text-rerank'

call classmethod

call(
    model: str,
    query: str,
    documents: List[str],
    return_documents: bool | None = None,
    top_n: int | None = None,
    api_key: str | None = None,
    instruct: str | None = None,
    **kwargs: Any
) -> ReRankResponse

Calling rerank service.

Parameters:

Name Type Description Default
model str

The model to use.

required
query str

The query string.

required
documents List[str]

The documents to rank.

required
return_documents bool, `optional`

enable return origin documents, system default is false.

None
top_n int, `optional`

how many documents to return, default return all the documents.

None
api_key str

The DashScope api key. Defaults to None.

None
instruct str

Custom task instruction to guide ranking strategy. English recommended.

None

Raises:

Type Description
InputRequired

The query and documents are required.

ModelRequired

The model is required.

Returns:

Name Type Description
RerankResponse ReRankResponse

The rerank result.

Source code in dashscope/legacy_1x/rerank/text_rerank.py
 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
@classmethod
def call(  # type: ignore[override]  # pylint: disable=arguments-renamed
    cls,
    model: str,
    query: str,
    documents: List[str],
    return_documents: bool = None,
    top_n: int = None,
    api_key: str = None,
    instruct: str = None,
    **kwargs,
) -> ReRankResponse:
    """Calling rerank service.

    Args:
        model (str): The model to use.
        query (str): The query string.
        documents (List[str]): The documents to rank.
        return_documents(bool, `optional`): enable return origin documents,
            system default is false.
        top_n(int, `optional`): how many documents to return,
            default return all the documents.
        api_key (str, optional): The DashScope api key. Defaults to None.
        instruct (str, optional): Custom task instruction to guide
            ranking strategy. English recommended.

    Raises:
        InputRequired: The query and documents are required.
        ModelRequired: The model is required.

    Returns:
        RerankResponse: The rerank result.
    """

    task_group, function, rerank_input, parameters = _build_rerank_request(
        model=model,
        query=query,
        documents=documents,
        return_documents=return_documents,
        top_n=top_n,
        instruct=instruct,
        **kwargs,
    )

    response = super().call(
        model=model,
        task_group=task_group,
        task=TextReRank.task,
        function=function,
        api_key=api_key,
        input=rerank_input,
        **parameters,  # type: ignore[arg-type]
    )

    return ReRankResponse.from_api_response(response)

AioTextReRank

Bases: BaseAioApi

task class-attribute instance-attribute

task = 'text-rerank'

Async API for rerank models.

Models class-attribute instance-attribute

Models = TextReRank.Models

call async classmethod

call(
    model: str,
    query: str,
    documents: List[str],
    return_documents: bool | None = None,
    top_n: int | None = None,
    api_key: str | None = None,
    workspace: str = None,
    instruct: str | None = None,
    **kwargs: Any
) -> ReRankResponse

Calling rerank service asynchronously.

Parameters:

Name Type Description Default
model str

The model to use.

required
query str

The query string.

required
documents List[str]

The documents to rank.

required
return_documents bool, `optional`

enable return origin documents, system default is false.

None
top_n int, `optional`

how many documents to return, default return all the documents.

None
api_key str

The DashScope api key. Defaults to None.

None
workspace str

The DashScope workspace id.

None
instruct str

Custom task instruction to guide ranking strategy. English recommended.

None

Raises:

Type Description
InputRequired

The query and documents are required.

ModelRequired

The model is required.

Returns:

Name Type Description
RerankResponse ReRankResponse

The rerank result.

Source code in dashscope/legacy_1x/rerank/text_rerank.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
@classmethod
# pylint: disable=arguments-renamed
async def call(  # type: ignore[override]
    cls,
    model: str,
    query: str,
    documents: List[str],
    return_documents: bool = None,
    top_n: int = None,
    api_key: str = None,
    workspace: str = None,
    instruct: str = None,
    **kwargs,
) -> ReRankResponse:
    """Calling rerank service asynchronously.

    Args:
        model (str): The model to use.
        query (str): The query string.
        documents (List[str]): The documents to rank.
        return_documents(bool, `optional`): enable return origin documents,
            system default is false.
        top_n(int, `optional`): how many documents to return,
            default return all the documents.
        api_key (str, optional): The DashScope api key. Defaults to None.
        workspace (str, optional): The DashScope workspace id.
        instruct (str, optional): Custom task instruction to guide
            ranking strategy. English recommended.

    Raises:
        InputRequired: The query and documents are required.
        ModelRequired: The model is required.

    Returns:
        RerankResponse: The rerank result.
    """
    task_group, function, rerank_input, parameters = _build_rerank_request(
        model=model,
        query=query,
        documents=documents,
        return_documents=return_documents,
        top_n=top_n,
        instruct=instruct,
        **kwargs,
    )

    response = await super().call(
        model=model,
        task_group=task_group,
        task=AioTextReRank.task,
        function=function,
        api_key=api_key,
        workspace=workspace,
        input=rerank_input,
        **parameters,  # type: ignore[arg-type]
    )

    return ReRankResponse.from_api_response(response)

NLP understanding

Understanding

Bases: BaseApi

nlu_task class-attribute instance-attribute

nlu_task = 'nlu'

API for AI-Generated Content(AIGC) models.

Models

opennlu_v1 class-attribute instance-attribute
opennlu_v1 = 'opennlu-v1'

call classmethod

call(
    model: str,
    sentence: str = None,
    labels: str = None,
    task: str = None,
    api_key: str = None,
    **kwargs
) -> DashScopeAPIResponse

Call generation model service.

Parameters:

Name Type Description Default
model str

The requested model, such as opennlu-v1

required
sentence str

The text content entered by the user that needs to be processed supports both Chinese and English. (The maximum limit for input is 1024 tokens, which is the sum of all input fields). # noqa E501 # pylint: disable=line-too-long

None
labels list

For the extraction task, label is the name of the type that needs to be extracted. For classification tasks, label is the classification system. Separate different labels with Chinese commas.. # noqa E501 # pylint: disable=line-too-long

None
task str

Task type, optional as extraction or classification, default as extraction.

None
api_key str

The api api_key, can be None, if None, will get by default rule(TODO: api key doc).

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The understanding result.

Source code in dashscope/legacy_1x/nlp/understanding.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    sentence: str = None,
    labels: str = None,
    task: str = None,
    api_key: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Call generation model service.

    Args:
        model (str): The requested model, such as opennlu-v1
        sentence (str): The text content entered by the user that needs to be processed supports both Chinese and English. (The maximum limit for input is 1024 tokens, which is the sum of all input fields).  # noqa E501  # pylint: disable=line-too-long
        labels (list): For the extraction task, label is the name of the type that needs to be extracted. For classification tasks, label is the classification system. Separate different labels with Chinese commas..  # noqa E501  # pylint: disable=line-too-long
        task (str): Task type, optional as extraction or classification, default as extraction.
        api_key (str, optional): The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).

    Returns:
        DashScopeAPIResponse: The understanding result.
    """
    if (sentence is None or not sentence) or (
        labels is None or not labels
    ):
        raise InputRequired("sentence and labels is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    if kwargs.pop("stream", False):  # not support stream
        logger.warning("stream option not supported for Understanding.")
    task_group, function = _get_task_group_and_task(__name__)
    (
        input,  # pylint: disable=redefined-builtin
        parameters,
    ) = cls._build_input_parameters(
        model,
        sentence,
        labels,
        task,
        **kwargs,
    )
    return super().call(
        model=model,
        task_group=task_group,
        task=Understanding.nlu_task,
        function=function,
        api_key=api_key,
        input=input,
        is_service=False,
        **parameters,
    )

Application calls

Application

Bases: BaseApi

task_group class-attribute instance-attribute

task_group = 'apps'

function class-attribute instance-attribute

function = 'completion'

API for app completion calls.

DocReferenceType

doc reference type for rag completion

simple class-attribute instance-attribute
simple = 'simple'
indexed class-attribute instance-attribute
indexed = 'indexed'

call classmethod

call(
    app_id: str,
    prompt: str | None = None,
    history: list | None = None,
    workspace: str | None = None,
    api_key: str | None = None,
    messages: List[Message] | None = None,
    stream: Optional[bool] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    seed: Optional[int] = None,
    session_id: Optional[str] = None,
    biz_params: Optional[Dict[str, Any]] = None,
    has_thoughts: Optional[bool] = None,
    doc_tag_codes: Optional[List[str]] = None,
    doc_reference_type: Optional[str] = None,
    memory_id: Optional[str] = None,
    image_list: Optional[List[str]] = None,
    file_list: Optional[List[str]] = None,
    rag_options: Optional[Dict[str, Any]] = None,
    incremental_output: Optional[bool] = None,
    **kwargs: Any
) -> Union[
    ApplicationResponse,
    Generator[ApplicationResponse, None, None],
]

Call app completion service.

Parameters:

Name Type Description Default
app_id str

Id of bailian application

required
prompt str

The input prompt.

None
history list

The user provided history examples: [{'user':'The weather is fine today.', 'bot': 'Suitable for outings'}]. Defaults to None.

None
workspace str, `optional`

Workspace for app completion call

None
api_key str

The api api_key, can be None, if None, will get by default rule(TODO: api key doc).

None
messages list

The generation messages.

None
stream bool

Enable server-sent events (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) # noqa E501 # pylint: disable=line-too-long the result will back partially[qwen-turbo,bailian-v1].

None
temperature float

Used to control the degree of randomness and diversity. Specifically, the temperature value controls the degree to which the probability distribution of each candidate word is smoothed when generating text. A higher temperature value will reduce the peak value of the probability, allowing more low-probability words to be selected, and the generated results will be more diverse; while a lower temperature value will enhance the peak value of the probability, making it easier for high-probability words to be selected, the generated results are more deterministic, range(0, 2) .[qwen-turbo,qwen-plus].

None
top_p float

A sampling strategy, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered[qwen-turbo,bailian-v1].

None
top_k int

The size of the sample candidate set when generated. # noqa E501 # pylint: disable=line-too-long For example, when the value is 50, only the 50 highest-scoring tokens # noqa E501 # pylint: disable=line-too-long in a single generation form a randomly sampled candidate set. # noqa E501 The larger the value, the higher the randomness generated; # noqa E501 the smaller the value, the higher the certainty generated. # noqa E501 The default value is 0, which means the top_k policy is # noqa E501 not enabled. At this time, only the top_p policy takes effect. # noqa E501

None
seed int

When generating, the seed of the random number is used to control the # pylint: disable=line-too-long randomness of the model generation. If you use the same seed, each run will generate the same results; # pylint: disable=line-too-long you can use the same seed when you need to reproduce the model's generated results. # pylint: disable=line-too-long The seed parameter supports unsigned 64-bit integer types. Default value 1234

None
session_id str

Session if for multiple rounds call.

None
biz_params dict

The extra parameters for flow or plugin.

None
has_thoughts bool

Flag to return rag or plugin process details. Default value false. # pylint: disable=line-too-long

None
doc_tag_codes list[str]

Tag code list for doc retrival.

None
doc_reference_type str

The type of doc reference. simple: simple format of doc retrival which not include index in response text but in doc reference list. # pylint: disable=line-too-long indexed: include both index in response text and doc reference list

None
memory_id str

Used to store long term context summary between end users and assistant. # pylint: disable=line-too-long

None
image_list list

Used to pass image url list.

None
file_list list

Used to pass file url list.

None
rag_options dict

Rag options for retrieval augmented generation options. # pylint: disable=line-too-long

None
incremental_output bool

In streaming mode, output only new tokens (True) vs. cumulative output (False).

None
**kwargs Any

Additional parameters passed to the API.

{}

Raises:

Type Description
InvalidInput

The history and auto_history are mutually exclusive.

Returns:

Type Description
Union[ApplicationResponse, Generator[ApplicationResponse, None, None]]

Union[CompletionResponse, Generator[CompletionResponse, None, None]]: If

Union[ApplicationResponse, Generator[ApplicationResponse, None, None]]

stream is True, return Generator, otherwise GenerationResponse.

Source code in dashscope/legacy_1x/app/application.py
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
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
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
@classmethod
def call(  # type: ignore[override]
    # pylint: disable=too-many-locals,arguments-renamed
    # pylint: disable=too-many-branches,too-many-statements
    cls,
    app_id: str,
    prompt: str = None,
    history: list = None,
    workspace: str = None,
    api_key: str = None,
    messages: List[Message] = None,
    stream: Optional[bool] = None,
    temperature: Optional[float] = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    seed: Optional[int] = None,
    session_id: Optional[str] = None,
    biz_params: Optional[Dict[str, Any]] = None,
    has_thoughts: Optional[bool] = None,
    doc_tag_codes: Optional[List[str]] = None,
    doc_reference_type: Optional[str] = None,
    memory_id: Optional[str] = None,
    image_list: Optional[List[str]] = None,
    file_list: Optional[List[str]] = None,
    rag_options: Optional[Dict[str, Any]] = None,
    incremental_output: Optional[bool] = None,
    **kwargs,
) -> Union[
    ApplicationResponse,
    Generator[
        ApplicationResponse,
        None,
        None,
    ],
]:
    """Call app completion service.

    Args:
        app_id (str): Id of bailian application
        prompt (str): The input prompt.
        history (list):The user provided history
            examples:
                [{'user':'The weather is fine today.',
                'bot': 'Suitable for outings'}].
            Defaults to None.
        workspace(str, `optional`): Workspace for app completion call
        api_key (str, optional): The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).
        messages(list): The generation messages.
        stream (bool, optional): Enable server-sent events
            (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)  # noqa E501  # pylint: disable=line-too-long
            the result will back partially[qwen-turbo,bailian-v1].
        temperature (float, optional): Used to control the degree
            of randomness and diversity. Specifically, the temperature
            value controls the degree to which the probability distribution
            of each candidate word is smoothed when generating text.
            A higher temperature value will reduce the peak value of
            the probability, allowing more low-probability words to be
            selected, and the generated results will be more diverse;
            while a lower temperature value will enhance the peak value
            of the probability, making it easier for high-probability
            words to be selected, the generated results are more
            deterministic, range(0, 2) .[qwen-turbo,qwen-plus].
        top_p (float, optional): A sampling strategy, called nucleus
            sampling, where the model considers the results of the
            tokens with top_p probability mass. So 0.1 means only
            the tokens comprising the top 10% probability mass are
            considered[qwen-turbo,bailian-v1].
        top_k (int, optional): The size of the sample candidate set when generated.  # noqa E501  # pylint: disable=line-too-long
            For example, when the value is 50, only the 50 highest-scoring tokens  # noqa E501  # pylint: disable=line-too-long
            in a single generation form a randomly sampled candidate set. # noqa E501
            The larger the value, the higher the randomness generated;  # noqa E501
            the smaller the value, the higher the certainty generated. # noqa E501
            The default value is 0, which means the top_k policy is  # noqa E501
            not enabled. At this time, only the top_p policy takes effect. # noqa E501
        seed (int, optional): When generating, the seed of the random number is used to control the  # pylint: disable=line-too-long
            randomness of the model generation. If you use the same seed, each run will generate the same results;  # pylint: disable=line-too-long
            you can use the same seed when you need to reproduce the model's generated results.  # pylint: disable=line-too-long
            The seed parameter supports unsigned 64-bit integer types. Default value 1234
        session_id (str, optional): Session if for multiple rounds call.
        biz_params (dict, optional): The extra parameters for flow or plugin.
        has_thoughts (bool, optional): Flag to return rag or plugin process details. Default value false.  # pylint: disable=line-too-long
        doc_tag_codes (list[str], optional): Tag code list for doc retrival.
        doc_reference_type (str, optional): The type of doc reference.
            simple: simple format of doc retrival which not include index in response text but in doc reference list.  # pylint: disable=line-too-long
            indexed: include both index in response text and doc reference list
        memory_id (str, optional): Used to store long term context summary between end users and assistant.  # pylint: disable=line-too-long
        image_list (list, optional): Used to pass image url list.
        file_list (list, optional): Used to pass file url list.
        rag_options (dict, optional): Rag options for retrieval augmented generation options.  # pylint: disable=line-too-long
        incremental_output (bool, optional): In streaming mode, output only
            new tokens (True) vs. cumulative output (False).
        **kwargs: Additional parameters passed to the API.

    Raises:
        InvalidInput: The history and auto_history are mutually exclusive.

    Returns:
        Union[CompletionResponse,
              Generator[CompletionResponse, None, None]]: If
        stream is True, return Generator, otherwise GenerationResponse.
    """

    api_key, app_id = Application._validate_params(api_key, app_id)

    if (prompt is None or not prompt) and (
        messages is None or len(messages) == 0
    ):
        raise InputRequired("prompt or messages is required!")

    # Build kwargs from explicit parameters
    explicit_kwargs = {}
    if workspace is not None and workspace:
        headers = kwargs.pop("headers", {})
        headers["X-DashScope-WorkSpace"] = workspace
        explicit_kwargs["headers"] = headers

    if stream is not None:
        explicit_kwargs["stream"] = stream
    if temperature is not None:
        explicit_kwargs["temperature"] = temperature
    if top_p is not None:
        explicit_kwargs["top_p"] = top_p
    if top_k is not None:
        explicit_kwargs["top_k"] = top_k
    if seed is not None:
        explicit_kwargs["seed"] = seed
    if session_id is not None:
        explicit_kwargs["session_id"] = session_id
    if biz_params is not None:
        explicit_kwargs["biz_params"] = biz_params
    if has_thoughts is not None:
        explicit_kwargs["has_thoughts"] = has_thoughts
    if doc_tag_codes is not None:
        explicit_kwargs["doc_tag_codes"] = doc_tag_codes
    if doc_reference_type is not None:
        explicit_kwargs["doc_reference_type"] = doc_reference_type
    if memory_id is not None:
        explicit_kwargs["memory_id"] = memory_id
    if image_list is not None:
        explicit_kwargs["image_list"] = image_list
    if file_list is not None:
        explicit_kwargs["file_list"] = file_list
    if rag_options is not None:
        explicit_kwargs["rag_options"] = rag_options
    if incremental_output is not None:
        explicit_kwargs["incremental_output"] = incremental_output

    # Merge with remaining kwargs (user-provided extras)
    merged_kwargs = {**kwargs, **explicit_kwargs}

    # Check if we need to merge incremental output (compute once)
    is_stream = merged_kwargs.get("stream", False)
    is_incremental_output = merged_kwargs.get("incremental_output", None)
    to_merge_incremental_output = (
        is_stream and is_incremental_output is False
    )

    if to_merge_incremental_output:
        merged_kwargs["incremental_output"] = True

    # Pass incremental_to_full flag via user_agent parameter to avoid
    # overwriting the default SDK user-agent
    flag = "1" if to_merge_incremental_output else "0"
    existing_ua = merged_kwargs.get("user_agent", "")
    new_ua = f"incremental_to_full/{flag}"
    merged_kwargs["user_agent"] = (
        f"{existing_ua}; {new_ua}".strip() if existing_ua else new_ua
    )

    (
        input,  # pylint: disable=redefined-builtin
        parameters,
    ) = cls._build_input_parameters(
        prompt,
        history,
        messages,
        **merged_kwargs,
    )
    request = _build_api_request(
        model="",
        input=input,
        task_group=Application.task_group,
        task=app_id,
        function=Application.function,
        workspace=workspace,
        api_key=api_key,
        is_service=False,
        sdk_module="app",
        **parameters,
    )
    # call request service.
    response = request.call()

    if is_stream:
        if to_merge_incremental_output:
            return cls._merge_application_response(response)
        else:
            return (
                ApplicationResponse.from_api_response(rsp)
                for rsp in response
            )
    else:
        return ApplicationResponse.from_api_response(response)

ApplicationResponse dataclass

ApplicationResponse()

Bases: DashScopeAPIResponse

output instance-attribute

output: ApplicationOutput

usage instance-attribute

usage: ApplicationUsage

from_api_response staticmethod

from_api_response(api_response: DashScopeAPIResponse)
Source code in dashscope/legacy_1x/app/application_response.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
@staticmethod
def from_api_response(api_response: DashScopeAPIResponse):
    if api_response.status_code == HTTPStatus.OK:
        usage = {}
        if api_response.usage:
            usage = api_response.usage

        return ApplicationResponse(
            status_code=api_response.status_code,
            request_id=api_response.request_id,
            code=api_response.code,
            message=api_response.message,
            output=ApplicationOutput(**api_response.output),
            usage=ApplicationUsage(**usage),
        )
    else:
        return ApplicationResponse(
            status_code=api_response.status_code,
            request_id=api_response.request_id,
            code=api_response.code,
            message=api_response.message,
        )

Speech synthesis (1.x)

SpeechSynthesizer

Bases: BaseApi

Text-to-speech interface.

AudioFormat

format_wav class-attribute instance-attribute
format_wav = 'wav'
format_pcm class-attribute instance-attribute
format_pcm = 'pcm'
format_mp3 class-attribute instance-attribute
format_mp3 = 'mp3'

call classmethod

call(
    model: str,
    text: str,
    callback: ResultCallback | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> SpeechSynthesisResult

Convert text to speech synchronously.

Parameters:

Name Type Description Default
model str

The requested model_id.

required
text str

Text content used for speech synthesis.

required
callback ResultCallback

A callback that returns speech synthesis results.

None
workspace str

The dashscope workspace id.

None
**kwargs Any

format(str, optional): Audio encoding format, such as pcm wav mp3, default is wav. sample_rate(int, optional): Audio sample rate, default is the sample rate of model. volume(int, optional): The volume of synthesized speech ranges from 0~100, default is 50. rate(float, optional): The speech rate of synthesized speech, the value range is 0.5~2.0, default is 1.0. pitch(float, optional): The intonation of synthesized speech,the value range is 0.5~2.0, default is 1.0. word_timestamp_enabled(bool, optional): Turn on word-level timestamping, default is False. phoneme_timestamp_enabled(bool, optional): Turn on phoneme level timestamping, default is False.

{}

Returns:

Name Type Description
SpeechSynthesisResult SpeechSynthesisResult

The result of systhesis.

Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
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
144
145
146
147
148
149
150
151
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
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
@classmethod
# type: ignore[override]
def call(  # pylint: disable=R1702,too-many-branches  # type: ignore[override] # noqa: E501
    cls,
    model: str,
    text: str,
    callback: ResultCallback = None,
    workspace: str = None,
    **kwargs,
) -> SpeechSynthesisResult:
    """Convert text to speech synchronously.

    Args:
        model (str): The requested model_id.
        text (str): Text content used for speech synthesis.
        callback (ResultCallback): A callback that returns
            speech synthesis results.
        workspace (str): The dashscope workspace id.
        **kwargs:
            format(str, `optional`): Audio encoding format,
                such as pcm wav mp3, default is wav.
            sample_rate(int, `optional`): Audio sample rate,
                default is the sample rate of model.
            volume(int, `optional`): The volume of synthesized speech
                ranges from 0~100, default is 50.
            rate(float, `optional`): The speech rate of synthesized
                speech, the value range is 0.5~2.0, default is 1.0.
            pitch(float, `optional`): The intonation of synthesized
                speech,the value range is 0.5~2.0, default is 1.0.
            word_timestamp_enabled(bool, `optional`): Turn on word-level
                timestamping, default is False.
            phoneme_timestamp_enabled(bool, `optional`): Turn on phoneme
                level timestamping, default is False.

    Returns:
        SpeechSynthesisResult: The result of systhesis.
    """
    _callback = callback
    _audio_data: bytes = None
    _sentences: List[Dict[str, str]] = []
    _the_final_response = None
    _task_failed_flag: bool = False
    task_name, _ = _get_task_group_and_task(__name__)

    response = super().call(
        model=model,
        task_group="audio",
        task=task_name,
        function="SpeechSynthesizer",
        input={"text": text},
        stream=True,
        api_protocol=ApiProtocol.WEBSOCKET,
        workspace=workspace,
        **kwargs,
    )

    if _callback is not None:
        _callback.on_open()

    for part in response:
        if isinstance(part.output, bytes):
            if _callback is not None:
                audio_frame = SpeechSynthesisResult(
                    bytes(part.output),
                    None,  # type: ignore[arg-type]
                    None,  # type: ignore[arg-type]
                    None,  # type: ignore[arg-type]
                    None,  # type: ignore[arg-type]
                )
                _callback.on_event(audio_frame)

            if _audio_data is None:
                _audio_data = bytes(part.output)
            else:
                _audio_data = _audio_data + bytes(part.output)

        else:
            if part.status_code == HTTPStatus.OK:
                if part.output is None:
                    _the_final_response = SpeechSynthesisResponse.from_api_response(  # noqa E501  # pylint: disable=line-too-long
                        part,
                    )
                else:
                    if (
                        not isinstance(part.output, dict)
                        or "sentence" not in part.output
                    ):
                        # Non-timestamp message (e.g. extra messages returned
                        # in the SSML/bgm scenario). Skip it safely instead of
                        # raising KeyError on part.output["sentence"].
                        continue
                    if _callback is not None:
                        sentence = SpeechSynthesisResult(
                            None,  # type: ignore[arg-type]
                            None,  # type: ignore[arg-type]
                            part.output["sentence"],
                            None,  # type: ignore[arg-type]
                            None,  # type: ignore[arg-type]
                        )
                        _callback.on_event(sentence)
                    if len(_sentences) == 0:
                        _sentences.append(part.output["sentence"])
                    else:
                        if (
                            _sentences[-1]["begin_time"]
                            == part.output["sentence"]["begin_time"]
                        ):
                            if (
                                _sentences[-1]["end_time"]
                                != part.output["sentence"]["end_time"]
                            ):
                                _sentences.pop()
                                _sentences.append(part.output["sentence"])
                        else:
                            _sentences.append(part.output["sentence"])
            else:
                _task_failed_flag = True
                _the_final_response = (
                    SpeechSynthesisResponse.from_api_response(  # noqa E501
                        part,
                    )
                )
                if _callback is not None:
                    _callback.on_error(
                        SpeechSynthesisResponse.from_api_response(part),
                    )

    if _callback is not None:
        if _task_failed_flag is False:
            _callback.on_complete()
        _callback.on_close()

    result = SpeechSynthesisResult(
        None,  # type: ignore[arg-type]
        _audio_data,
        None,  # type: ignore[arg-type]
        _sentences,
        _the_final_response,  # type: ignore[arg-type]
    )
    return result

ResultCallback

An interface that defines callback methods for getting speech synthesis results. # noqa E501 Derive from this class and implement its function to provide your own data.

on_open

on_open() -> None
Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
76
77
def on_open(self) -> None:
    pass

on_complete

on_complete() -> None
Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
79
80
def on_complete(self) -> None:
    pass

on_error

on_error(response: SpeechSynthesisResponse) -> None
Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
82
83
def on_error(self, response: SpeechSynthesisResponse) -> None:
    pass

on_close

on_close() -> None
Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
85
86
def on_close(self) -> None:
    pass

on_event

on_event(result: SpeechSynthesisResult) -> None
Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
88
89
def on_event(self, result: SpeechSynthesisResult) -> None:
    pass

SpeechSynthesisResult

SpeechSynthesisResult(
    frame: bytes,
    data: bytes,
    sentence: Dict[str, str],
    sentences: List[Dict[str, str]],
    response: SpeechSynthesisResponse,
)

The result set of speech synthesis, including audio data, timestamp information, and final result information.

Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __init__(
    self,
    frame: bytes,
    data: bytes,
    sentence: Dict[str, str],
    sentences: List[Dict[str, str]],
    response: SpeechSynthesisResponse,
):
    if frame is not None:
        self._audio_frame = bytes(frame)
    if data is not None:
        self._audio_data = bytes(data)
    if sentence is not None:
        self._sentence = sentence
    if sentences is not None:
        self._sentences = sentences
    if response is not None:
        self._response = response

get_audio_frame

get_audio_frame() -> bytes

Obtain the audio frame data of speech synthesis through callbacks.

Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
45
46
47
def get_audio_frame(self) -> bytes:
    """Obtain the audio frame data of speech synthesis through callbacks."""  # noqa: E501
    return self._audio_frame

get_audio_data

get_audio_data() -> bytes

Get complete audio data for speech synthesis.

Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
49
50
51
def get_audio_data(self) -> bytes:
    """Get complete audio data for speech synthesis."""
    return self._audio_data

get_timestamp

get_timestamp() -> Dict[str, str]

Obtain the timestamp information of the current speech synthesis sentence through the callback.

Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
53
54
55
56
57
def get_timestamp(self) -> Dict[str, str]:
    """Obtain the timestamp information of the current speech synthesis
    sentence through the callback.
    """
    return self._sentence

get_timestamps

get_timestamps() -> List[Dict[str, str]]

Get complete timestamp information for all speech synthesis sentences.

Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
59
60
61
def get_timestamps(self) -> List[Dict[str, str]]:
    """Get complete timestamp information for all speech synthesis sentences."""  # noqa: E501
    return self._sentences

get_response

get_response() -> SpeechSynthesisResponse

Obtain the status information of the current speech synthesis task, including error information and billing information.

Source code in dashscope/legacy_1x/audio/tts/speech_synthesizer.py
63
64
65
66
67
def get_response(self) -> SpeechSynthesisResponse:
    """Obtain the status information of the current speech synthesis task,
    including error information and billing information.
    """
    return self._response

HttpSpeechSynthesizer

Bases: BaseApi

HTTP-based text-to-speech interface for CosyVoice.

AudioFormat

WAV class-attribute instance-attribute
WAV = 'wav'
PCM class-attribute instance-attribute
PCM = 'pcm'
MP3 class-attribute instance-attribute
MP3 = 'mp3'

call classmethod

call(
    model: str,
    text: str,
    voice: str,
    audio_format: str = "wav",
    sample_rate: int = 24000,
    stream: bool = False,
    workspace: Optional[str] = None,
    api_key: Optional[str] = None,
    url: Optional[str] = None,
    **kwargs
) -> Union[
    HttpSpeechSynthesisResult,
    Iterator[HttpSpeechSynthesisResult],
]

Convert text to speech via HTTP API.

Parameters:

Name Type Description Default
model str

The speech synthesis model, e.g., 'cosyvoice-v3-flash'.

required
text str

The text to synthesize.

required
voice str

The voice to use for synthesis.

required
audio_format str

Audio encoding format ('wav', 'pcm', 'mp3'). Defaults to 'wav'.

'wav'
sample_rate int

Audio sample rate in Hz. Defaults to 24000.

24000
stream bool

Whether to use streaming (SSE) mode. Defaults to False.

False
workspace str

The DashScope workspace ID.

None
api_key str

The DashScope API key.

None
url str

custom http url if needed.

None
**kwargs Any

Additional parameters like volume, rate, pitch, etc.

{}

Returns:

Name Type Description
HttpSpeechSynthesisResult Union[HttpSpeechSynthesisResult, Iterator[HttpSpeechSynthesisResult]]

For non-streaming mode.

Union[HttpSpeechSynthesisResult, Iterator[HttpSpeechSynthesisResult]]

Iterator[HttpSpeechSynthesisResult]: For streaming mode.

Source code in dashscope/legacy_1x/audio/http_tts/http_speech_synthesizer.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
182
183
184
185
186
187
188
@classmethod
def call(  # type: ignore # pylint: disable=arguments-renamed
    cls,
    model: str,
    text: str,
    voice: str,
    audio_format: str = "wav",
    sample_rate: int = 24000,
    stream: bool = False,
    workspace: Optional[str] = None,
    api_key: Optional[str] = None,
    url: Optional[str] = None,
    **kwargs,
) -> Union[HttpSpeechSynthesisResult, Iterator[HttpSpeechSynthesisResult]]:
    """Convert text to speech via HTTP API.

    Args:
        model (str): The speech synthesis model, e.g.,
            'cosyvoice-v3-flash'.
        text (str): The text to synthesize.
        voice (str): The voice to use for synthesis.
        audio_format (str): Audio encoding format ('wav', 'pcm', 'mp3').
            Defaults to 'wav'.
        sample_rate (int): Audio sample rate in Hz. Defaults to 24000.
        stream (bool): Whether to use streaming (SSE) mode.
            Defaults to False.
        workspace (str): The DashScope workspace ID.
        api_key (str): The DashScope API key.
        url (str): custom http url if needed.
        **kwargs (Any): Additional parameters like volume, rate, pitch, etc.

    Returns:
        HttpSpeechSynthesisResult: For non-streaming mode.
        Iterator[HttpSpeechSynthesisResult]: For streaming mode.
    """
    # Build request body
    body = {
        "model": model,
        "input": {
            "text": text,
            "voice": voice,
            "format": audio_format,
            "sample_rate": sample_rate,
            **{k: v for k, v in kwargs.items() if v is not None},
        },
    }

    # Prepare headers
    headers = {}
    if stream:
        headers["X-DashScope-SSE"] = "enable"

    # Make the HTTP request
    response = cls._http_call(
        method=HTTPMethod.POST,
        body=body,
        headers=headers if headers else None,
        stream=stream,
        workspace=workspace,
        api_key=api_key,
        url=url,
    )

    if stream:
        return cls._handle_streaming_response(response)
    else:
        return cls._handle_non_streaming_response(response)

SpeechSynthesizer

SpeechSynthesizer(
    model,
    voice,
    format: AudioFormat = AudioFormat.DEFAULT,
    volume=50,
    speech_rate=1.0,
    pitch_rate=1.0,
    seed=0,
    synthesis_type=0,
    instruction=None,
    language_hints: list = None,
    headers=None,
    callback: ResultCallback = None,
    workspace=None,
    url=None,
    hot_fix=None,
    additional_params=None,
)

CosyVoice Speech Synthesis SDK Parameters:


model: str Model name. voice: str Voice name. format: AudioFormat Synthesis audio format. volume: int The volume of the synthesized audio, with a range from 0 to 100. Default is 50. rate: float The speech rate of the synthesized audio, with a range from 0.5 to 2. Default is 1.0. # noqa: E501 # pylint: disable=line-too-long pitch: float The pitch of the synthesized audio, with a range from 0.5 to 2. Default is 1.0. # noqa: E501 # pylint: disable=line-too-long headers: Dict User-defined headers. callback: ResultCallback Callback to receive real-time synthesis results. workspace: str Dashscope workspace ID. url: str Dashscope WebSocket URL. seed: int The seed of the synthesizer, with a range from 0 to 65535. Default is 0. synthesis_type: int The type of the synthesizer, Default is 0. instruction: str The instruction of the synthesizer, max length is 128. language_hints: list The language hints of the synthesizer. supported language: zh, en. additional_params: Dict Additional parameters for the Dashscope API. hot_fix: Dict or HotFix Hot fix parameters for pronunciation and text replacement. Example: { "pronunciation": [{"草地": "cao3 di4"}], "replace": [{"草地": "草弟"}] } enable_markdown_filter: bool Whether to enable markdown filter. should be set into additional_params.

Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
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
327
328
329
330
331
332
333
334
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
385
386
387
388
389
390
391
def __init__(  # pylint: disable=redefined-builtin
    self,
    model,
    voice,
    format: AudioFormat = AudioFormat.DEFAULT,
    volume=50,
    speech_rate=1.0,
    pitch_rate=1.0,
    seed=0,
    synthesis_type=0,
    instruction=None,
    language_hints: list = None,
    headers=None,
    callback: ResultCallback = None,
    workspace=None,
    url=None,
    hot_fix=None,
    additional_params=None,
):
    """
    CosyVoice Speech Synthesis SDK
    Parameters:
    -----------
    model: str
        Model name.
    voice: str
        Voice name.
    format: AudioFormat
        Synthesis audio format.
    volume: int
        The volume of the synthesized audio, with a range from 0 to 100. Default is 50.
    rate: float
        The speech rate of the synthesized audio, with a range from 0.5 to 2. Default is 1.0.  # noqa: E501  # pylint: disable=line-too-long
    pitch: float
        The pitch of the synthesized audio, with a range from 0.5 to 2. Default is 1.0.  # noqa: E501  # pylint: disable=line-too-long
    headers: Dict
        User-defined headers.
    callback: ResultCallback
        Callback to receive real-time synthesis results.
    workspace: str
        Dashscope workspace ID.
    url: str
        Dashscope WebSocket URL.
    seed: int
        The seed of the synthesizer, with a range from 0 to 65535. Default is 0.
    synthesis_type: int
        The type of the synthesizer, Default is 0.
    instruction: str
        The instruction of the synthesizer, max length is 128.
    language_hints: list
        The language hints of the synthesizer. supported language: zh, en.
    additional_params: Dict
        Additional parameters for the Dashscope API.
    hot_fix: Dict or HotFix
        Hot fix parameters for pronunciation and text replacement.
        Example: {
            "pronunciation": [{"草地": "cao3 di4"}],
            "replace": [{"草地": "草弟"}]
        }
    enable_markdown_filter: bool
        Whether to enable markdown filter. should be set into additional_params.
    """
    self.ws = None
    self.start_event = threading.Event()
    self.complete_event = threading.Event()
    self._stopped = threading.Event()
    self._audio_data: bytes = None
    self._is_started = False
    self._cancel = False
    self._cancel_lock = threading.Lock()
    self.async_call = True
    self._is_first = True
    self.async_call = True
    # since dashscope sdk will send first text in run-task
    self._start_stream_timestamp = -1
    self._first_package_timestamp = -1
    self._recv_audio_length = 0
    self.last_response = None
    # Error reported by the websocket receiver thread, re-raised in the
    # caller thread. See __raise_if_task_failed.
    self._receiver_error: Optional[Exception] = None
    self._close_ws_after_use = True
    self.__update_params(
        model,
        voice,
        format,
        volume,
        speech_rate,
        pitch_rate,
        seed,
        synthesis_type,
        instruction,
        language_hints,
        headers,
        callback,
        workspace,
        url,
        additional_params,
        self._close_ws_after_use,
        hot_fix,
    )

ws instance-attribute

ws = None

start_event instance-attribute

start_event = threading.Event()

complete_event instance-attribute

complete_event = threading.Event()

async_call instance-attribute

async_call = True

last_response instance-attribute

last_response = None

streaming_call

streaming_call(text: str)

Streaming input mode: You can call the streaming_call function multiple times to send text. A session will be created on the first call. The session ends after calling streaming_complete. Parameters:


text: str utf-8 encoded text

Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
def streaming_call(self, text: str):
    """
    Streaming input mode:
    You can call the streaming_call function multiple times to send text.
    A session will be created on the first call.
    The session ends after calling streaming_complete.
    Parameters:
    -----------
    text: str
        utf-8 encoded text
    """
    if self._is_first:
        self._is_first = False
        self.__start_stream()
    self.__submit_text(text)
    return None

streaming_flush

streaming_flush()

send tts flush request.

Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
644
645
646
647
648
649
650
651
652
653
654
655
def streaming_flush(self):
    """
    send tts flush request.
    """
    if not self._is_started:
        raise InvalidTask("speech synthesizer has not been started.")

    if self._stopped.is_set():
        raise InvalidTask("speech synthesizer task has stopped.")
    request = self.request.get_flush_request()
    self.__send_str(request)
    return None

streaming_complete

streaming_complete(complete_timeout_millis=600000)

Synchronously stop the streaming input speech synthesis task. Wait for all remaining synthesized audio before returning

Parameters:

complete_timeout_millis: int Throws TimeoutError exception if it times out. If the timeout is not None # noqa: E501 and greater than zero, it will wait for the corresponding number of milliseconds; otherwise, it will wait indefinitely.

Raises:

If the server reported a task-failed event, its error is raised here, unless a callback is set, in which case the error has already been delivered through ResultCallback.on_error.

Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
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
def streaming_complete(self, complete_timeout_millis=600000):
    """
    Synchronously stop the streaming input speech synthesis task.
    Wait for all remaining synthesized audio before returning

    Parameters:
    -----------
    complete_timeout_millis: int
        Throws TimeoutError exception if it times out. If the timeout is not None  # noqa: E501
        and greater than zero, it will wait for the corresponding number of
        milliseconds; otherwise, it will wait indefinitely.

    Raises:
    -----------
    If the server reported a task-failed event, its error is raised here,
    unless a callback is set, in which case the error has already been
    delivered through ResultCallback.on_error.
    """
    if not self._is_started:
        raise InvalidTask("speech synthesizer has not been started.")
    if self._stopped.is_set():
        raise InvalidTask("speech synthesizer task has stopped.")
    request = self.request.get_finish_request()
    self.__send_str(request)
    try:
        if (
            complete_timeout_millis is not None
            and complete_timeout_millis > 0
        ):
            if not self.complete_event.wait(
                timeout=complete_timeout_millis / 1000,
            ):
                raise TimeoutError(
                    f"speech synthesizer wait for complete timeout "
                    f"{complete_timeout_millis}ms",
                )
        else:
            self.complete_event.wait()
    finally:
        # Release resources even if the task failed or timed out.
        self.__cleanup_task()
    self.__raise_if_task_failed()

async_streaming_complete

async_streaming_complete(complete_timeout_millis=600000)

Asynchronously stop the streaming input speech synthesis task, returns immediately. # noqa: E501 # pylint: disable=line-too-long You need to listen and handle the STREAM_INPUT_TTS_EVENT_SYNTHESIS_COMPLETE event in the on_event callback. # noqa: E501 # pylint: disable=line-too-long Do not destroy the object and callback before this event.

Parameters:

complete_timeout_millis: int Throws TimeoutError exception if it times out. If the timeout is not None # noqa: E501 and greater than zero, it will wait for the corresponding number of milliseconds; otherwise, it will wait indefinitely.

Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
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
def async_streaming_complete(self, complete_timeout_millis=600000):
    """
    Asynchronously stop the streaming input speech synthesis task, returns immediately.  # noqa: E501  # pylint: disable=line-too-long
    You need to listen and handle the STREAM_INPUT_TTS_EVENT_SYNTHESIS_COMPLETE event in the on_event callback.  # noqa: E501  # pylint: disable=line-too-long
    Do not destroy the object and callback before this event.

    Parameters:
    -----------
    complete_timeout_millis: int
        Throws TimeoutError exception if it times out. If the timeout is not None  # noqa: E501
        and greater than zero, it will wait for the corresponding number of
        milliseconds; otherwise, it will wait indefinitely.
    """

    if not self._is_started:
        raise InvalidTask("speech synthesizer has not been started.")
    if self._stopped.is_set():
        raise InvalidTask("speech synthesizer task has stopped.")
    request = self.request.get_finish_request()
    self.__send_str(request)
    thread = threading.Thread(
        target=self.__waiting_for_complete,
        args=(complete_timeout_millis,),
    )
    thread.start()

streaming_cancel

streaming_cancel(complete_timeout_millis=10000)

Immediately terminate the streaming input speech synthesis task and discard any remaining audio that is not yet delivered.

A finish-task message with payload.input.directive=cancel is sent to notify the server to stop synthesis in advance. The server will then respond with a task-finished message, after which the connection is closed.

Parameters:

complete_timeout_millis: int If it times out waiting for the server's task-finished message, the connection is force-closed and a warning is logged. If the timeout is not None and greater than zero, it will wait for the corresponding number of milliseconds; otherwise, it will wait indefinitely.

Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
def streaming_cancel(self, complete_timeout_millis=10000):
    """
    Immediately terminate the streaming input speech synthesis task
    and discard any remaining audio that is not yet delivered.

    A finish-task message with payload.input.directive=cancel is sent
    to notify the server to stop synthesis in advance. The server will
    then respond with a task-finished message, after which the
    connection is closed.

    Parameters:
    -----------
    complete_timeout_millis: int
        If it times out waiting for the server's task-finished message,
        the connection is force-closed and a warning is logged. If the
        timeout is not None and greater than zero, it will wait for the
        corresponding number of milliseconds; otherwise, it will wait
        indefinitely.
    """

    if not self._is_started:
        raise InvalidTask("speech synthesizer has not been started.")
    if self._stopped.is_set():
        return
    request = self.request.get_finish_request(directive="cancel")
    self.__send_str(request)
    if complete_timeout_millis is not None and complete_timeout_millis > 0:
        if not self.complete_event.wait(
            timeout=complete_timeout_millis / 1000,
        ):
            logger.warning(
                "speech synthesizer wait for task-finished "
                "after cancel timeout %sms, force closing.",
                complete_timeout_millis,
            )
            self.close()
        elif self._close_ws_after_use:
            self.close()
    else:
        self.complete_event.wait()
        if self._close_ws_after_use:
            self.close()
    self._stopped.set()
    self._is_started = False

on_message

on_message(ws, message)
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
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
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
848
849
850
851
852
853
854
855
856
857
858
859
def on_message(  # pylint: disable=unused-argument,too-many-branches
    self,
    ws,
    message,
):
    if isinstance(message, str):
        logger.debug("<<<recv %s", message)
        try:
            # Attempt to parse message as JSON
            json_data = json.loads(message)
            self.last_response = json_data
            event = json_data["header"][EVENT_KEY]
            # Invoke JSON callback
            if EventType.STARTED == event:
                self.start_event.set()
            elif EventType.FINISHED == event:
                self.complete_event.set()
                if self.callback:
                    self.callback.on_complete()
                    self.callback.on_close()
            elif EventType.FAILED == event:
                logger.error("TaskFailed: %s", message)
                # Save the error before releasing the waiters: raising it
                # here would only be logged by websocket-client and the
                # caller would silently get the partial audio.
                self._receiver_error = self.__build_task_failed_error(
                    json_data,
                    message,
                )
                self.start_event.set()
                self.complete_event.set()
                if self.async_call:
                    self.callback.on_error(message)
                    self.callback.on_close()
            elif EventType.GENERATED == event:
                if self.callback:
                    self.callback.on_event(message)
            else:
                pass
        except json.JSONDecodeError:
            logger.error("Failed to parse message as JSON.")
            # pylint: disable=broad-exception-raised,raise-missing-from
            raise Exception("Failed to parse message as JSON.")
    elif isinstance(message, (bytes, bytearray)):
        # If parsing fails, treat as binary message
        logger.debug("<<<recv binary %s", len(message))
        if self._recv_audio_length == 0:
            self._first_package_timestamp = time.time() * 1000
            logger.debug(
                "first package delay %s",
                self._first_package_timestamp
                - self._start_stream_timestamp,
            )
        self._recv_audio_length += len(message) / (
            2 * self.sample_rate / 1000
        )
        current = time.time() * 1000
        current_rtf = (
            current - self._start_stream_timestamp
        ) / self._recv_audio_length
        logger.debug(
            "total audio %s ms, current_rtf: %s",
            self._recv_audio_length,
            current_rtf,
        )
        # Only save audio in non-async calls
        if not self.async_call:
            if self._audio_data is None:
                self._audio_data = bytes(message)
            else:
                self._audio_data = self._audio_data + bytes(message)
        if self.callback:
            self.callback.on_data(message)

call

call(text: str, timeout_millis=None)

Speech synthesis. If callback is set, the audio will be returned in real-time through the on_event interface. # noqa: E501 # pylint: disable=line-too-long Otherwise, this function blocks until all audio is received and then returns the complete audio data. # noqa: E501 # pylint: disable=line-too-long

Parameters:

text: str utf-8 encoded text timeoutMillis: Integer or None return: bytes If a callback is not set during initialization, the complete audio is returned # noqa: E501 # pylint: disable=line-too-long as the function's return value. Otherwise, the return value is null. # noqa: E501 If the timeout is set to a value greater than zero and not None, it will wait for the corresponding number of milliseconds; otherwise, it will wait indefinitely. If the server reported a task-failed event, its error is raised instead of returning the partially synthesized audio.

Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
861
862
863
864
865
866
867
868
869
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
def call(self, text: str, timeout_millis=None):
    """
    Speech synthesis.
    If callback is set, the audio will be returned in real-time through the on_event interface.  # noqa: E501  # pylint: disable=line-too-long
    Otherwise, this function blocks until all audio is received and then returns the complete audio data.  # noqa: E501  # pylint: disable=line-too-long

    Parameters:
    -----------
    text: str
        utf-8 encoded text
    timeoutMillis:
        Integer or None
    return: bytes
        If a callback is not set during initialization, the complete audio is returned  # noqa: E501  # pylint: disable=line-too-long
        as the function's return value. Otherwise, the return value is null.  # noqa: E501
        If the timeout is set to a value greater than zero and not None,
        it will wait for the corresponding number of milliseconds;
        otherwise, it will wait indefinitely.
        If the server reported a task-failed event, its error is raised
        instead of returning the partially synthesized audio.
    """
    # print('non-streaming TTS not yet supported for LLM calls,'
    #       ' using streaming simulation')
    if self.additional_params is None:
        self.additional_params = {"enable_ssml": True}
    else:
        self.additional_params["enable_ssml"] = True
    if not self.callback:
        self.callback = ResultCallback()
    self.__start_stream()
    self.__submit_text(text)
    if self.async_call:
        self.async_streaming_complete(timeout_millis)
        return None
    else:
        self.streaming_complete(timeout_millis)
        return self._audio_data

on_close

on_close(ws, close_status_code, close_msg)
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
900
901
902
903
904
905
906
def on_close(  # pylint: disable=unused-argument
    self,
    ws,
    close_status_code,
    close_msg,
):
    pass

on_error

on_error(ws, error)
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
909
910
def on_error(self, ws, error):  # pylint: disable=unused-argument
    logger.error("websocket error: %s", error)

close

close()
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
915
916
917
def close(self):
    if self.ws is not None:
        self.ws.close()

get_last_request_id

get_last_request_id()
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
920
921
def get_last_request_id(self):
    return self.last_request_id

get_first_package_delay

get_first_package_delay()

First Package Delay is the time between start sending text and receive first audio package

Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
923
924
925
def get_first_package_delay(self):
    """First Package Delay is the time between start sending text and receive first audio package"""  # noqa: E501  # pylint: disable=line-too-long
    return self._first_package_timestamp - self._start_stream_timestamp

get_response

get_response()
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
927
928
def get_response(self):
    return self.last_response

ResultCallback

An interface that defines callback methods for getting speech synthesis results. # noqa E501 Derive from this class and implement its function to provide your own data.

on_open

on_open() -> None
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
75
76
def on_open(self) -> None:
    pass

on_complete

on_complete() -> None
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
78
79
def on_complete(self) -> None:
    pass

on_error

on_error(message) -> None
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
81
82
def on_error(self, message) -> None:
    pass

on_close

on_close() -> None
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
84
85
def on_close(self) -> None:
    pass

on_event

on_event(message: str) -> None
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
87
88
def on_event(self, message: str) -> None:
    pass

on_data

on_data(data: bytes) -> None
Source code in dashscope/legacy_1x/audio/tts_v2/speech_synthesizer.py
90
91
def on_data(self, data: bytes) -> None:
    pass

VoiceEnrollmentService

VoiceEnrollmentService(
    api_key=None, workspace=None, model=None, **kwargs
)

Bases: BaseApi

API for voice clone service

Source code in dashscope/legacy_1x/audio/tts_v2/enrollment.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def __init__(
    self,
    api_key=None,
    workspace=None,
    model=None,
    **kwargs,
) -> None:
    super().__init__()
    self._api_key = api_key
    self._workspace = workspace
    self._kwargs = kwargs
    self._last_request_id = None
    self.model = model
    if self.model is None:
        self.model = "voice-enrollment"

MAX_QUERY_TRY_COUNT class-attribute instance-attribute

MAX_QUERY_TRY_COUNT = 3

model instance-attribute

model = model

create_voice

create_voice(
    target_model: str,
    prefix: str,
    url: str,
    language_hints: List[str] = None,
    max_prompt_audio_length: float = None,
    **kwargs
) -> str

Create a new cloned voice. param: target_model TTS model version for the cloned voice param: prefix Custom voice prefix, only digits and lowercase letters allowed, less than 10 characters. param: url Audio file URL for voice cloning param: language_hints Target language for the cloned voice param: max_prompt_audio_length Max length of prompt audio output from audio preprocessing, in seconds. Default is 10s. param: kwargs Additional parameters return: voice_id

Source code in dashscope/legacy_1x/audio/tts_v2/enrollment.py
 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
121
122
123
124
125
126
127
128
def create_voice(
    self,
    target_model: str,
    prefix: str,
    url: str,
    language_hints: List[str] = None,
    max_prompt_audio_length: float = None,
    **kwargs,
) -> str:
    """
    Create a new cloned voice.
    param: target_model TTS model version for the cloned voice
    param: prefix Custom voice prefix, only digits and lowercase
        letters allowed, less than 10 characters.
    param: url Audio file URL for voice cloning
    param: language_hints Target language for the cloned voice
    param: max_prompt_audio_length Max length of prompt audio output
        from audio preprocessing, in seconds. Default is 10s.
    param: kwargs Additional parameters
    return: voice_id
    """

    input_params = {
        "action": "create_voice",
        "target_model": target_model,
        "prefix": prefix,
        "url": url,
    }
    if language_hints is not None:
        input_params["language_hints"] = language_hints
    if max_prompt_audio_length is not None:
        input_params["max_prompt_audio_length"] = max_prompt_audio_length
    if kwargs:
        input_params.update(kwargs)
    response = self.__call_with_input(input_params)
    self._last_request_id = response.request_id
    if response.status_code == 200:
        return response.output["voice_id"]
    else:
        raise VoiceEnrollmentException(
            response.request_id,
            response.status_code,
            response.code,
            response.message,
        )

list_voices

list_voices(
    prefix=None, page_index: int = 0, page_size: int = 10
) -> List[dict]

List all created voices. param: page_index Page index for query param: page_size Page size return: List[dict] Voice list, including id, creation time, modification time, and status for each voice.

Source code in dashscope/legacy_1x/audio/tts_v2/enrollment.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def list_voices(
    self,
    prefix=None,
    page_index: int = 0,
    page_size: int = 10,
) -> List[dict]:
    """
    List all created voices.
    param: page_index Page index for query
    param: page_size Page size
    return: List[dict] Voice list, including id, creation time,
        modification time, and status for each voice.
    """
    if prefix:
        # pylint: disable=no-value-for-parameter
        response = self.__call_with_input(
            input={
                "action": "list_voice",
                "prefix": prefix,
                "page_index": page_index,
                "page_size": page_size,
            },
        )
    else:
        # pylint: disable=no-value-for-parameter
        response = self.__call_with_input(
            input={
                "action": "list_voice",
                "page_index": page_index,
                "page_size": page_size,
            },
        )
    self._last_request_id = response.request_id
    if response.status_code == 200:
        return response.output["voice_list"]
    else:
        raise VoiceEnrollmentException(
            response.request_id,
            response.status_code,
            response.code,
            response.message,
        )

query_voice

query_voice(voice_id: str) -> List[str]

Query voice details. param: voice_id Voice ID to query return: bytes Audio used for voice registration

Source code in dashscope/legacy_1x/audio/tts_v2/enrollment.py
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def query_voice(self, voice_id: str) -> List[str]:
    """
    Query voice details.
    param: voice_id Voice ID to query
    return: bytes Audio used for voice registration
    """
    # pylint: disable=no-value-for-parameter
    response = self.__call_with_input(
        input={
            "action": "query_voice",
            "voice_id": voice_id,
        },
    )
    self._last_request_id = response.request_id
    if response.status_code == 200:
        return response.output
    else:
        raise VoiceEnrollmentException(
            response.request_id,
            response.status_code,
            response.code,
            response.message,
        )

update_voice

update_voice(voice_id: str, url: str) -> None

Update voice. param: voice_id Voice ID param: url Audio file URL for cloning

Source code in dashscope/legacy_1x/audio/tts_v2/enrollment.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def update_voice(self, voice_id: str, url: str) -> None:
    """
    Update voice.
    param: voice_id Voice ID
    param: url Audio file URL for cloning
    """
    # pylint: disable=no-value-for-parameter
    response = self.__call_with_input(
        input={
            "action": "update_voice",
            "voice_id": voice_id,
            "url": url,
        },
    )
    self._last_request_id = response.request_id
    if response.status_code == 200:
        return
    else:
        raise VoiceEnrollmentException(
            response.request_id,
            response.status_code,
            response.code,
            response.message,
        )

delete_voice

delete_voice(voice_id: str) -> None

Delete voice. param: voice_id Voice ID to delete

Source code in dashscope/legacy_1x/audio/tts_v2/enrollment.py
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def delete_voice(self, voice_id: str) -> None:
    """
    Delete voice.
    param: voice_id Voice ID to delete
    """
    # pylint: disable=no-value-for-parameter
    response = self.__call_with_input(
        input={
            "action": "delete_voice",
            "voice_id": voice_id,
        },
    )
    self._last_request_id = response.request_id
    if response.status_code == 200:
        return
    else:
        raise VoiceEnrollmentException(
            response.request_id,
            response.status_code,
            response.code,
            response.message,
        )

get_last_request_id

get_last_request_id()
Source code in dashscope/legacy_1x/audio/tts_v2/enrollment.py
245
246
def get_last_request_id(self):
    return self._last_request_id

SpeechSynthesizer

Bases: BaseApi

Text-to-speech interface.

task_group class-attribute instance-attribute

task_group = 'aigc'

task class-attribute instance-attribute

task = 'multimodal-generation'

function class-attribute instance-attribute

function = 'generation'

Models

qwen_tts class-attribute instance-attribute
qwen_tts = 'qwen-tts'

call classmethod

call(
    model: str,
    text: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> Union[
    TextToSpeechResponse,
    Generator[TextToSpeechResponse, None, None],
]

Call the conversation model service.

Parameters:

Name Type Description Default
model str

The requested model, such as 'qwen-tts'

required
text str

Text content used for speech synthesis.

required
api_key str

The api api_key, can be None, if None, will retrieve by rule [1]. [1]: https://help.aliyun.com/zh/dashscope/developer-reference/api-key-settings. # noqa E501 # pylint: disable=line-too-long

None
workspace str

The dashscope workspace id.

None
**kwargs Any

stream(bool, optional): Enable server-sent events (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) # noqa E501 # pylint: disable=line-too-long the result will back partially[qwen-turbo,bailian-v1]. voice: str Voice name.

{}

Raises:

Type Description
InputRequired

The input must include the text parameter.

ModelRequired

The input must include the model parameter.

Returns:

Type Description
Union[TextToSpeechResponse, Generator[TextToSpeechResponse, None, None]]

Union[TextToSpeechResponse, Generator[TextToSpeechResponse, None, None]]: If

Union[TextToSpeechResponse, Generator[TextToSpeechResponse, None, None]]

stream is True, return Generator, otherwise TextToSpeechResponse.

Source code in dashscope/legacy_1x/audio/qwen_tts/speech_synthesizer.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    text: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> Union[
    TextToSpeechResponse,
    Generator[
        TextToSpeechResponse,
        None,
        None,
    ],
]:
    """Call the conversation model service.

    Args:
        model (str): The requested model, such as 'qwen-tts'
        text (str): Text content used for speech synthesis.
        api_key (str, optional): The api api_key, can be None,
            if None, will retrieve by rule [1].
            [1]: https://help.aliyun.com/zh/dashscope/developer-reference/api-key-settings. # noqa E501  # pylint: disable=line-too-long
        workspace (str): The dashscope workspace id.
        **kwargs (Any):
            stream(bool, `optional`): Enable server-sent events
                (ref: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events)  # noqa E501  # pylint: disable=line-too-long
                the result will back partially[qwen-turbo,bailian-v1].
            voice: str
                Voice name.

    Raises:
        InputRequired: The input must include the text parameter.
        ModelRequired: The input must include the model parameter.

    Returns:
        Union[TextToSpeechResponse,
              Generator[TextToSpeechResponse, None, None]]: If
        stream is True, return Generator, otherwise TextToSpeechResponse.
    """
    if not text:
        raise InputRequired("text is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    input = {"text": text}  # pylint: disable=redefined-builtin
    if "voice" in kwargs:
        input["voice"] = kwargs.pop("voice")
    response = super().call(
        model=model,
        task_group=SpeechSynthesizer.task_group,
        task=SpeechSynthesizer.task,
        function=SpeechSynthesizer.function,
        api_key=api_key,
        input=input,
        workspace=workspace,
        **kwargs,
    )
    is_stream = kwargs.get("stream", False)
    if is_stream:
        return (
            TextToSpeechResponse.from_api_response(rsp) for rsp in response
        )
    else:
        return TextToSpeechResponse.from_api_response(response)

QwenTtsRealtime

QwenTtsRealtime(
    model,
    headers=None,
    callback: QwenTtsRealtimeCallback = None,
    workspace=None,
    url=None,
    additional_params=None,
)

Qwen Tts Realtime SDK Parameters:


model: str Model name. headers: Dict User-defined headers. callback: OmniRealtimeCallback Callback to receive real-time omni results. workspace: str Dashscope workspace ID. url: str Dashscope WebSocket URL. additional_params: Dict Additional parameters for the Dashscope API.

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
 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
def __init__(
    self,
    model,
    headers=None,
    callback: QwenTtsRealtimeCallback = None,
    workspace=None,
    url=None,
    additional_params=None,  # pylint: disable=unused-argument
):
    """
    Qwen Tts Realtime SDK
    Parameters:
    -----------
    model: str
        Model name.
    headers: Dict
        User-defined headers.
    callback: OmniRealtimeCallback
        Callback to receive real-time omni results.
    workspace: str
        Dashscope workspace ID.
    url: str
        Dashscope WebSocket URL.
    additional_params: Dict
        Additional parameters for the Dashscope API.
    """

    if model is None:
        raise ModelRequired("Model is required!")
    if url is None:
        url = f"wss://dashscope.aliyuncs.com/api-ws/v1/realtime?model={model}"  # noqa: E501
    else:
        url = f"{url}?model={model}"
    self.url = url
    self.apikey = dashscope.api_key
    self.user_headers = headers
    self.user_workspace = workspace
    self.model = model
    self.config = {}
    self.callback = callback
    self.ws = None
    self.session_id = None
    self.last_message = None
    self.last_response_id = None
    self.last_first_text_time = None
    self.last_first_audio_delay = None
    self.metrics = []

url instance-attribute

url = url

apikey instance-attribute

apikey = dashscope.api_key

user_headers instance-attribute

user_headers = headers

user_workspace instance-attribute

user_workspace = workspace

model instance-attribute

model = model

config instance-attribute

config = {}

callback instance-attribute

callback = callback

ws instance-attribute

ws = None

session_id instance-attribute

session_id = None

last_message instance-attribute

last_message = None

last_response_id instance-attribute

last_response_id = None

last_first_text_time instance-attribute

last_first_text_time = None

last_first_audio_delay instance-attribute

last_first_audio_delay = None

metrics instance-attribute

metrics = []

connect

connect() -> None

connect to server, create session and return default session configuration # noqa: E501

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def connect(self) -> None:
    """
    connect to server, create session and return default session configuration  # noqa: E501
    """
    self.ws = websocket.WebSocketApp(
        self.url,
        header=self._get_websocket_header(),
        on_message=self.on_message,
        on_error=self.on_error,
        on_close=self.on_close,
    )
    self.thread = threading.Thread(target=self.ws.run_forever)
    self.thread.daemon = True
    self.thread.start()
    timeout = 5  # max wait time in seconds
    start_time = time.time()
    while (
        not (self.ws.sock and self.ws.sock.connected)
        and (time.time() - start_time) < timeout
    ):
        time.sleep(0.1)  # Brief sleep to avoid busy polling
    if not (self.ws.sock and self.ws.sock.connected):
        raise TimeoutError(
            "websocket connection could not established within 5s. "
            "Please check your network connection, firewall settings, or server status.",  # noqa: E501  # pylint: disable=line-too-long
        )
    self.callback.on_open()

update_session

update_session(
    voice: str,
    response_format: AudioFormat = AudioFormat.PCM_24000HZ_MONO_16BIT,
    mode: str = "server_commit",
    sample_rate: int = None,
    volume: int = None,
    speech_rate: float = None,
    audio_format: str = None,
    pitch_rate: float = None,
    bit_rate: int = None,
    language_type: str = None,
    enable_tn: bool = None,
    instructions: str = None,
    optimize_instructions: bool = None,
    **kwargs
) -> None

update session configuration, should be used before create response

Parameters

voice: str voice to be used in session response_format: AudioFormat output audio format mode: str response mode, server_commit or commit language_type: str language type for synthesized audio, default is 'auto' sample_rate: int sampleRate for tts, range [8000,16000,22050,24000,44100,48000] default is 24000 # noqa: E501 # pylint: disable=line-too-long volume: int volume for tts, range [0,100] default is 50 speech_rate: float speech_rate for tts, range [0.5~2.0] default is 1.0 audio_format: str format for tts, support mp3,wav,pcm,opus, default is 'pcm' pitch_rate: float pitch_rate for tts, range [0.5~2.0] default is 1.0 bit_rate: int bit_rate for tts, support 6~510,default is 128kbps. only work on format: opus/mp3 # noqa: E501 # pylint: disable=line-too-long enable_tn: bool enable text normalization for tts, default is None instructions: str instructions for tts, default is None optimize_instructions: bool optimize_instructions for tts, default is None

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
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
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
def update_session(
    self,
    voice: str,
    response_format: AudioFormat = AudioFormat.PCM_24000HZ_MONO_16BIT,
    mode: str = "server_commit",
    sample_rate: int = None,
    volume: int = None,
    speech_rate: float = None,
    audio_format: str = None,
    pitch_rate: float = None,
    bit_rate: int = None,
    language_type: str = None,
    enable_tn: bool = None,
    instructions: str = None,
    optimize_instructions: bool = None,
    **kwargs,
) -> None:
    """
    update session configuration, should be used before create response

    Parameters
    ----------
    voice: str
        voice to be used in session
    response_format: AudioFormat
        output audio format
    mode: str
        response mode, server_commit or commit
    language_type: str
        language type for synthesized audio, default is 'auto'
    sample_rate: int
        sampleRate for tts, range [8000,16000,22050,24000,44100,48000] default is 24000  # noqa: E501  # pylint: disable=line-too-long
    volume: int
        volume for tts, range [0,100] default is 50
    speech_rate: float
        speech_rate for tts, range [0.5~2.0] default is 1.0
    audio_format: str
        format for tts, support mp3,wav,pcm,opus, default is 'pcm'
    pitch_rate: float
        pitch_rate for tts, range [0.5~2.0] default is 1.0
    bit_rate: int
        bit_rate for tts, support 6~510,default is 128kbps. only work on format: opus/mp3  # noqa: E501  # pylint: disable=line-too-long
    enable_tn: bool
        enable text normalization for tts, default is None
    instructions: str
        instructions for tts, default is None
    optimize_instructions: bool
        optimize_instructions for tts, default is None
    """
    self.config = {
        "voice": voice,
        "mode": mode,
        "response_format": response_format.format,
        "sample_rate": response_format.sample_rate,
    }
    if sample_rate is not None:  # update if configured
        self.config["sample_rate"] = sample_rate
    if volume is not None:
        self.config["volume"] = volume
    if speech_rate is not None:
        self.config["speech_rate"] = speech_rate
    if audio_format is not None:
        self.config[
            "response_format"
        ] = audio_format  # update if configured
    if pitch_rate is not None:
        self.config["pitch_rate"] = pitch_rate
    if bit_rate is not None:
        self.config["bit_rate"] = bit_rate
    if enable_tn is not None:
        self.config["enable_tn"] = enable_tn

    if language_type is not None:
        self.config["language_type"] = language_type
    if instructions is not None:
        self.config["instructions"] = instructions
    if optimize_instructions is not None:
        self.config["optimize_instructions"] = optimize_instructions
    self.config.update(kwargs)
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "session.update",
                "session": self.config,
            },
        ),
    )

append_text

append_text(text: str) -> None

send text

Parameters

text: str text to send

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def append_text(self, text: str) -> None:
    """
    send text

    Parameters
    ----------
    text: str
        text to send
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "input_text_buffer.append",
                "text": text,
            },
        ),
    )
    if self.last_first_text_time is None:
        self.last_first_text_time = time.time() * 1000

commit

commit() -> None

commit the text sent before, create response and start synthesis audio.

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
281
282
283
284
285
286
287
288
289
290
291
292
def commit(self) -> None:
    """
    commit the text sent before, create response and start synthesis audio.
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "input_text_buffer.commit",
            },
        ),
    )

clear_appended_text

clear_appended_text() -> None

clear the text sent to server before.

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
294
295
296
297
298
299
300
301
302
303
304
305
def clear_appended_text(self) -> None:
    """
    clear the text sent to server before.
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "input_text_buffer.clear",
            },
        ),
    )

cancel_response

cancel_response() -> None

cancel the current response

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
307
308
309
310
311
312
313
314
315
316
317
318
def cancel_response(self) -> None:
    """
    cancel the current response
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "response.cancel",
            },
        ),
    )

send_raw

send_raw(raw_data: str) -> None

send raw data to server

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
320
321
322
323
324
def send_raw(self, raw_data: str) -> None:
    """
    send raw data to server
    """
    self.__send_str(raw_data)

finish

finish() -> None

finish input text stream, server will synthesis all text in buffer and close the connection # noqa: E501 # pylint: disable=line-too-long

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
326
327
328
329
330
331
332
333
334
335
336
337
def finish(self) -> None:
    """
    finish input text stream, server will synthesis all text in buffer and close the connection  # noqa: E501  # pylint: disable=line-too-long
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "session.finish",
            },
        ),
    )

close

close() -> None

close the connection to server

Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
339
340
341
342
343
def close(self) -> None:
    """
    close the connection to server
    """
    self.ws.close()

on_message

on_message(ws, message)
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
def on_message(  # pylint: disable=unused-argument
    self,
    ws,
    message,
):
    if isinstance(message, str):
        logger.debug(
            "[omni realtime] receive string %s",
            message[:1024],
        )
        try:
            # Attempt to parse message as JSON
            json_data = json.loads(message)
            self.last_message = json_data
            self.callback.on_event(json_data)
            if "type" in message:
                if "session.created" == json_data["type"]:
                    self.session_id = json_data["session"]["id"]
                if "response.created" == json_data["type"]:
                    self.last_response_id = json_data["response"]["id"]
                elif "response.audio.delta" == json_data["type"]:
                    if (
                        self.last_first_text_time
                        and self.last_first_audio_delay is None
                    ):
                        self.last_first_audio_delay = (
                            time.time() * 1000 - self.last_first_text_time
                        )
                elif "response.done" == json_data["type"]:
                    logger.debug(
                        "[Metric] response: %s, first audio delay: %s",  # noqa: E501
                        self.last_response_id,
                        self.last_first_audio_delay,
                    )
        except json.JSONDecodeError:
            logger.error(
                "Failed to parse message as JSON: %s",
                message[:200],
            )
            # Do not raise exception here, let the connection stay alive.
            # Raising exception in callback can cause unexpected thread
            # termination.
        except Exception as e:
            logger.error("Error processing message: %s", str(e))
            # Do not raise exception here, let the connection stay alive.
            # Raising exception in callback can cause unexpected thread
            # termination.
    elif isinstance(message, (bytes, bytearray)):
        # If parsing fails, treat as binary message
        logger.error(
            "should not receive binary message in omni realtime api",
        )
        logger.debug(
            "[omni realtime] receive binary %s bytes",
            len(message),
        )

on_close

on_close(ws, close_status_code, close_msg)
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
403
404
405
406
407
408
409
410
411
412
413
414
def on_close(  # pylint: disable=unused-argument
    self,
    ws,
    close_status_code,
    close_msg,
):
    logger.debug(
        "[omni realtime] connection closed with code %s and message %s",  # noqa: E501
        close_status_code,
        close_msg,
    )
    self.callback.on_close(close_status_code, close_msg)

on_error

on_error(ws, error)
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
417
418
def on_error(self, ws, error):  # pylint: disable=unused-argument
    logger.error(f"websocket error: {error}")

get_session_id

get_session_id()
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
423
424
def get_session_id(self):
    return self.session_id

get_last_message

get_last_message()
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
426
427
def get_last_message(self):
    return self.last_message

get_last_response_id

get_last_response_id()
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
429
430
def get_last_response_id(self):
    return self.last_response_id

get_first_audio_delay

get_first_audio_delay()
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
432
433
def get_first_audio_delay(self):
    return self.last_first_audio_delay

QwenTtsRealtimeCallback

An interface that defines callback methods for getting omni-realtime results. # noqa E501 Derive from this class and implement its function to provide your own data.

on_open

on_open() -> None
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
24
25
def on_open(self) -> None:
    pass

on_close

on_close(close_status_code, close_msg) -> None
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
27
28
def on_close(self, close_status_code, close_msg) -> None:
    pass

on_event

on_event(message: str) -> None
Source code in dashscope/legacy_1x/audio/qwen_tts_realtime/qwen_tts_realtime.py
30
31
def on_event(self, message: str) -> None:
    pass

Speech recognition (1.x)

Recognition

Recognition(
    model: str,
    callback: RecognitionCallback,
    format: str,
    sample_rate: int,
    workspace: str = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs
)

Bases: BaseApi

Speech recognition interface.

Parameters:

Name Type Description Default
model str

The requested model_id.

required
callback RecognitionCallback

A callback that returns speech recognition results.

required
format str

The input audio format for speech recognition.

required
sample_rate int

The input audio sample rate for speech recognition.

required
workspace str

The dashscope workspace id.

None
**kwargs Any

phrase_id (list, optional): The ID of phrase. disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Raises:

Type Description
InputRequired

Input is required.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def __init__(
    self,
    model: str,
    callback: RecognitionCallback,
    format: str,  # pylint: disable=redefined-builtin
    sample_rate: int,
    workspace: str = None,
    # Recognition parameters
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs,
):
    if model is None:
        raise ModelRequired("Model is required!")
    if format is None:
        raise InputRequired("format is required!")
    if sample_rate is None:
        raise InputRequired("sample_rate is required!")

    self.model = model
    self.format = format
    self.sample_rate = sample_rate
    # continuous recognition with start() or once recognition with call()
    self._recognition_once = False
    self._callback = callback
    self._running = False
    self._stream_data = Queue()
    self._worker = None
    self._silence_timer = None
    self._kwargs = kwargs
    # Store recognition parameters
    _merge_recognition_params(
        self._kwargs,
        disfluency_removal_enabled,
        diarization_enabled,
        speaker_count,
        timestamp_alignment_enabled,
        special_word_filter,
        audio_event_detection_enabled,
    )
    self._workspace = workspace
    self._start_stream_timestamp = -1
    self._first_package_timestamp = -1
    self._stop_stream_timestamp = -1
    self._on_complete_timestamp = -1
    self.request_id_confirmed = False
    self.last_request_id = uuid.uuid4().hex

SILENCE_TIMEOUT_S class-attribute instance-attribute

SILENCE_TIMEOUT_S = 23

model instance-attribute

model = model

format instance-attribute

format = format

sample_rate instance-attribute

sample_rate = sample_rate

request_id_confirmed instance-attribute

request_id_confirmed = False

last_request_id instance-attribute

last_request_id = uuid.uuid4().hex

start

start(
    phrase_id: str = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs
)

Real-time speech recognition in asynchronous mode. Please call 'stop()' after you have completed recognition.

Parameters:

Name Type Description Default
phrase_id str, `optional`

The ID of phrase.

None
**kwargs Any

disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Raises:

Type Description
InvalidParameter

This interface cannot be called again if it has already been started.

InvalidTask

Task create failed.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def start(
    self,
    phrase_id: str = None,
    # Recognition parameters
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs,
):
    """Real-time speech recognition in asynchronous mode.
       Please call 'stop()' after you have completed recognition.

    Args:
        phrase_id (str, `optional`): The ID of phrase.

        **kwargs (Any):
            disfluency_removal_enabled(bool, `optional`):
                Filter mood words, turned off by default.
            diarization_enabled (bool, `optional`):
                Speech auto diarization, turned off by default.
            speaker_count (int, `optional`): The number of speakers.
            timestamp_alignment_enabled (bool, `optional`):
                Timestamp-alignment calibration, turned off by default.
            special_word_filter(str, `optional`): Sensitive word filter.
            audio_event_detection_enabled(bool, `optional`):
                Audio event detection, turned off by default.

    Raises:
        InvalidParameter: This interface cannot be called again
            if it has already been started.
        InvalidTask: Task create failed.
    """
    assert (
        self._callback is not None
    ), "Please set the callback to get the speech recognition result."  # noqa E501

    if self._running:
        raise InvalidParameter("Speech recognition has started.")

    self._start_stream_timestamp = -1
    self._first_package_timestamp = -1
    self._stop_stream_timestamp = -1
    self._on_complete_timestamp = -1
    self._phrase = phrase_id
    # Update recognition parameters
    _merge_recognition_params(
        self._kwargs,
        disfluency_removal_enabled,
        diarization_enabled,
        speaker_count,
        timestamp_alignment_enabled,
        special_word_filter,
        audio_event_detection_enabled,
    )
    self._kwargs.update(**kwargs)
    self._recognition_once = False
    self._worker = threading.Thread(target=self.__receive_worker)
    self._worker.start()
    if self._worker.is_alive():
        self._running = True
        self._callback.on_open()

        # If audio data is not received for 23 seconds, the timeout exits
        self._silence_timer = Timer(
            Recognition.SILENCE_TIMEOUT_S,
            self._silence_stop_timer,
        )
        self._silence_timer.start()
    else:
        self._running = False
        raise InvalidTask("Invalid task, task create failed.")

call

call(
    file: str,
    phrase_id: str = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs
) -> RecognitionResult

Real-time speech recognition in synchronous mode.

Parameters:

Name Type Description Default
file str

The path to the local audio file.

required
phrase_id str, `optional`

The ID of phrase.

None
**kwargs Any

disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Raises:

Type Description
InvalidParameter

This interface cannot be called again if it has already been started.

InputDataRequired

The supplied file was empty.

Returns:

Name Type Description
RecognitionResult RecognitionResult

The result of speech recognition.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
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
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
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
def call(  # type: ignore[override]  # noqa: E501
    self,
    file: str,
    phrase_id: str = None,
    # Recognition parameters
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs,
) -> RecognitionResult:
    """Real-time speech recognition in synchronous mode.

    Args:
        file (str): The path to the local audio file.
        phrase_id (str, `optional`): The ID of phrase.

        **kwargs (Any):
            disfluency_removal_enabled(bool, `optional`):
                Filter mood words, turned off by default.
            diarization_enabled (bool, `optional`):
                Speech auto diarization, turned off by default.
            speaker_count (int, `optional`): The number of speakers.
            timestamp_alignment_enabled (bool, `optional`):
                Timestamp-alignment calibration, turned off by default.
            special_word_filter(str, `optional`): Sensitive word filter.
            audio_event_detection_enabled(bool, `optional`):
                Audio event detection, turned off by default.

    Raises:
        InvalidParameter: This interface cannot be called again
            if it has already been started.
        InputDataRequired: The supplied file was empty.

    Returns:
        RecognitionResult: The result of speech recognition.
    """
    self._start_stream_timestamp = time.time() * 1000
    if self._running:
        raise InvalidParameter("Speech recognition has been called.")

    if os.path.exists(file):
        if os.path.isdir(file):
            raise IsADirectoryError("Is a directory: " + file)
    else:
        raise FileNotFoundError("No such file or directory: " + file)

    self._recognition_once = True
    self._stream_data = Queue()
    self._phrase = phrase_id
    # Update recognition parameters
    _merge_recognition_params(
        self._kwargs,
        disfluency_removal_enabled,
        diarization_enabled,
        speaker_count,
        timestamp_alignment_enabled,
        special_word_filter,
        audio_event_detection_enabled,
    )
    self._kwargs.update(**kwargs)
    error_flag: bool = False
    sentences: List[Any] = []
    usages: List[Any] = []
    response: RecognitionResponse = None
    result: RecognitionResult = None

    try:
        audio_data: bytes = None
        # pylint: disable=consider-using-with
        f = open(file, "rb")
        if os.path.getsize(file):
            while True:
                audio_data = f.read(12800)
                if not audio_data:
                    break
                self._stream_data.put(
                    audio_data,
                )  # pylint: disable=no-else-break
        else:
            raise InputDataRequired(
                "The supplied file was empty (zero bytes long)",
            )
        f.close()
        self._stop_stream_timestamp = time.time() * 1000
    except Exception as e:
        logger.debug(e)
        raise

    if not self._stream_data.empty():
        self._running = True
        responses = self.__launch_request()
        for part in responses:
            if part.status_code == HTTPStatus.OK:
                if "sentence" in part.output:
                    if (
                        "text" in part.output["sentence"]
                        and part.output["sentence"]["text"] != ""
                    ):
                        if self._first_package_timestamp < 0:
                            self._first_package_timestamp = (
                                time.time() * 1000
                            )
                            logger.debug(
                                "first package delay %s",
                                self._first_package_timestamp
                                - self._start_stream_timestamp,
                            )
                    sentence = part.output["sentence"]
                    logger.debug(
                        "Recv Result [rid:%s]:%s, isEnd: %s",
                        part.request_id,
                        sentence,
                        RecognitionResult.is_sentence_end(sentence),
                    )
                    if RecognitionResult.is_sentence_end(sentence):
                        sentences.append(sentence)

                        if part.usage is not None:
                            usage = {
                                "end_time": part.output["sentence"][
                                    "end_time"
                                ],
                                "usage": part.usage,
                            }
                            usages.append(usage)

                response = RecognitionResponse.from_api_response(part)
            else:
                response = RecognitionResponse.from_api_response(part)
                logger.error(response)
                error_flag = True
                break

    self._on_complete_timestamp = time.time() * 1000
    logger.debug(
        "last package delay %s",
        self.get_last_package_delay(),
    )

    if error_flag:
        result = RecognitionResult(response)
    else:
        result = RecognitionResult(response, sentences, usages)

    self._stream_data = Queue()
    self._recognition_once = False
    self._running = False

    return result

stop

stop()

End asynchronous speech recognition.

Raises:

Type Description
InvalidParameter

Cannot stop an uninitiated recognition.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
def stop(self):
    """End asynchronous speech recognition.

    Raises:
        InvalidParameter: Cannot stop an uninitiated recognition.
    """
    if self._running is False:
        raise InvalidParameter("Speech recognition has stopped.")

    self._stop_stream_timestamp = time.time() * 1000

    self._running = False
    if self._worker is not None and self._worker.is_alive():
        self._worker.join()
    self._stream_data = Queue()
    if self._silence_timer is not None and self._silence_timer.is_alive():
        self._silence_timer.cancel()
        self._silence_timer = None
    if self._callback:
        self._callback.on_close()

send_audio_frame

send_audio_frame(buffer: bytes)

Push speech recognition.

Raises:

Type Description
InvalidParameter

Cannot send data to an uninitiated recognition.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
620
621
622
623
624
625
626
627
628
629
630
631
632
def send_audio_frame(self, buffer: bytes):
    """Push speech recognition.

    Raises:
        InvalidParameter: Cannot send data to an uninitiated recognition.
    """
    if self._running is False:
        raise InvalidParameter("Speech recognition has stopped.")

    if self._start_stream_timestamp < 0:
        self._start_stream_timestamp = time.time() * 1000
    logger.debug("send_audio_frame: %s", len(buffer))
    self._stream_data.put(buffer)

update_context

update_context(payload_input: dict)

Update recognition context while the task is running.

The context is sent through a continue-task event and takes effect on subsequent audio frames.

Parameters:

Name Type Description Default
payload_input dict

Conversation context messages.

required

Raises:

Type Description
InvalidParameter

Cannot update an uninitiated recognition, or the context is None.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def update_context(self, payload_input: dict):
    """Update recognition context while the task is running.

    The context is sent through a ``continue-task`` event and takes effect
    on subsequent audio frames.

    Args:
        payload_input (dict): Conversation context messages.

    Raises:
        InvalidParameter: Cannot update an uninitiated recognition, or the
            context is None.
    """
    if self._running is False:
        raise InvalidParameter("Speech recognition has stopped.")
    if payload_input is None:
        raise InvalidParameter("Context is required.")

    logger.debug("update_context: %s", payload_input)
    self._stream_data.put({"input": payload_input})

get_first_package_delay

get_first_package_delay()

First Package Delay is the time between start sending audio and receive first words package

Source code in dashscope/legacy_1x/audio/asr/recognition.py
703
704
705
def get_first_package_delay(self):
    """First Package Delay is the time between start sending audio and receive first words package"""  # noqa: E501  # pylint: disable=line-too-long
    return self._first_package_timestamp - self._start_stream_timestamp

get_last_package_delay

get_last_package_delay()

Last Package Delay is the time between stop sending audio and receive last words package

Source code in dashscope/legacy_1x/audio/asr/recognition.py
707
708
709
def get_last_package_delay(self):
    """Last Package Delay is the time between stop sending audio and receive last words package"""  # noqa: E501  # pylint: disable=line-too-long
    return self._on_complete_timestamp - self._stop_stream_timestamp

get_last_request_id

get_last_request_id()
Source code in dashscope/legacy_1x/audio/asr/recognition.py
712
713
def get_last_request_id(self):
    return self.last_request_id

RecognitionCallback

An interface that defines callback methods for getting speech recognition results. # noqa E501 # pylint: disable=line-too-long Derive from this class and implement its function to provide your own data.

on_open

on_open() -> None
Source code in dashscope/legacy_1x/audio/asr/recognition.py
147
148
def on_open(self) -> None:
    pass

on_complete

on_complete() -> None
Source code in dashscope/legacy_1x/audio/asr/recognition.py
150
151
def on_complete(self) -> None:
    pass

on_error

on_error(result: RecognitionResult) -> None
Source code in dashscope/legacy_1x/audio/asr/recognition.py
153
154
def on_error(self, result: RecognitionResult) -> None:
    pass

on_close

on_close() -> None
Source code in dashscope/legacy_1x/audio/asr/recognition.py
156
157
def on_close(self) -> None:
    pass

on_event

on_event(result: RecognitionResult) -> None
Source code in dashscope/legacy_1x/audio/asr/recognition.py
159
160
def on_event(self, result: RecognitionResult) -> None:
    pass

RecognitionResult

RecognitionResult(
    response: RecognitionResponse,
    sentences: List[Any] = None,
    usages: List[Any] = None,
)

Bases: RecognitionResponse

The result set of speech recognition, including the single-sentence recognition result returned by the callback mode, and all recognition results in a synchronized manner.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
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
def __init__(
    self,
    response: RecognitionResponse,
    sentences: List[Any] = None,
    usages: List[Any] = None,
):
    self.status_code = response.status_code
    self.request_id = response.request_id
    self.code = response.code
    self.message = response.message
    self.usages = usages
    if sentences is not None and len(sentences) > 0:
        self.output = {"sentence": sentences}
    else:
        self.output = response.output
    if (
        self.usages is not None
        and len(
            self.usages,
        )
        > 0
        and "usage" in self.usages[-1]
    ):
        self.usage = self.usages[-1]["usage"]
    else:
        self.usage = None

status_code instance-attribute

status_code = response.status_code

request_id instance-attribute

request_id = response.request_id

code instance-attribute

code = response.code

message instance-attribute

message = response.message

usages instance-attribute

usages = usages

output instance-attribute

output = {'sentence': sentences}

usage instance-attribute

usage = self.usages[-1]['usage']

get_sentence

get_sentence() -> Union[Dict[str, Any], List[Any]]

The result of speech recognition.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
101
102
103
104
105
106
def get_sentence(self) -> Union[Dict[str, Any], List[Any]]:
    """The result of speech recognition."""
    if self.output and "sentence" in self.output:
        return self.output["sentence"]
    else:
        return None  # type: ignore[return-value]

get_request_id

get_request_id() -> str

The request_id of speech recognition.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
108
109
110
def get_request_id(self) -> str:
    """The request_id of speech recognition."""
    return self.request_id

get_usage

get_usage(sentence: Dict[str, Any]) -> Dict[str, Any]

Get billing for the input sentence.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
112
113
114
115
116
117
118
119
120
121
122
123
124
def get_usage(self, sentence: Dict[str, Any]) -> Dict[str, Any]:
    """Get billing for the input sentence."""
    if self.usages is not None:
        if (
            sentence is not None
            and "end_time" in sentence
            and sentence["end_time"] is not None
        ):
            for usage in self.usages:
                if usage["end_time"] == sentence["end_time"]:
                    return usage["usage"]

    return None  # type: ignore[return-value]

is_sentence_end staticmethod

is_sentence_end(sentence: Dict[str, Any]) -> bool

Determine whether the speech recognition result is the end of a sentence. # noqa: E501 This is a static method.

Source code in dashscope/legacy_1x/audio/asr/recognition.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
@staticmethod
def is_sentence_end(sentence: Dict[str, Any]) -> bool:
    """Determine whether the speech recognition result is the end of a sentence.  # noqa: E501
    This is a static method.
    """
    # pylint: disable=simplifiable-if-statement
    if (
        sentence is not None
        and "end_time" in sentence
        and sentence["end_time"] is not None
    ):
        return True
    else:
        return False

Transcription

Bases: BaseAsyncApi

API for File Transcription models.

MAX_QUERY_TRY_COUNT class-attribute instance-attribute

MAX_QUERY_TRY_COUNT = 3

Models

paraformer_v1 class-attribute instance-attribute
paraformer_v1 = 'paraformer-v1'
paraformer_8k_v1 class-attribute instance-attribute
paraformer_8k_v1 = 'paraformer-8k-v1'
paraformer_mtl_v1 class-attribute instance-attribute
paraformer_mtl_v1 = 'paraformer-mtl-v1'

call classmethod

call(
    model: str,
    file_urls: List[str],
    phrase_id: str | None = None,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> TranscriptionResponse

Transcribe the given files synchronously.

Parameters:

Name Type Description Default
model str

The requested model_id.

required
file_urls List[str]

List of stored URLs.

required
phrase_id str, `optional`

The ID of phrase.

None
workspace str

The dashscope workspace id.

None
**kwargs Any

channel_id (List[int], optional): The selected channel_id of audio file. disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Returns:

Name Type Description
TranscriptionResponse TranscriptionResponse

The result of batch transcription.

Source code in dashscope/legacy_1x/audio/asr/transcription.py
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    file_urls: List[str],
    phrase_id: str = None,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> TranscriptionResponse:
    """Transcribe the given files synchronously.

    Args:
        model (str): The requested model_id.
        file_urls (List[str]): List of stored URLs.
        phrase_id (str, `optional`): The ID of phrase.
        workspace (str): The dashscope workspace id.

        **kwargs:
            channel_id (List[int], optional):
                The selected channel_id of audio file.
            disfluency_removal_enabled(bool, `optional`):
                Filter mood words, turned off by default.
            diarization_enabled (bool, `optional`):
                Speech auto diarization, turned off by default.
            speaker_count (int, `optional`): The number of speakers.
            timestamp_alignment_enabled (bool, `optional`):
                Timestamp-alignment calibration, turned off by default.
            special_word_filter(str, `optional`): Sensitive word filter.
            audio_event_detection_enabled(bool, `optional`):
                Audio event detection, turned off by default.

    Returns:
        TranscriptionResponse: The result of batch transcription.
    """
    kwargs.update(cls._fill_resource_id(phrase_id, **kwargs))
    kwargs = cls._tidy_kwargs(**kwargs)
    response = super().call(
        model,
        file_urls,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return TranscriptionResponse.from_api_response(response)

async_call classmethod

async_call(
    model: str,
    file_urls: List[str],
    phrase_id: str | None = None,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> TranscriptionResponse

Transcribe the given files asynchronously, return the status of task submission for querying results subsequently.

Parameters:

Name Type Description Default
model str

The requested model, such as paraformer-16k-1

required
file_urls List[str]

List of stored URLs.

required
phrase_id str, `optional`

The ID of phrase.

None
workspace str

The dashscope workspace id.

None

**kwargs: channel_id (List[int], optional): The selected channel_id of audio file. disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

Returns:

Name Type Description
TranscriptionResponse TranscriptionResponse

The response including task_id.

Source code in dashscope/legacy_1x/audio/asr/transcription.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
110
111
112
113
114
115
116
117
118
119
120
@classmethod
def async_call(  # type: ignore[override]
    cls,
    model: str,
    file_urls: List[str],
    phrase_id: str = None,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> TranscriptionResponse:
    """Transcribe the given files asynchronously,
    return the status of task submission for querying results subsequently.

    Args:
        model (str): The requested model, such as paraformer-16k-1
        file_urls (List[str]): List of stored URLs.
        phrase_id (str, `optional`): The ID of phrase.
        workspace (str): The dashscope workspace id.

    **kwargs:
        channel_id (List[int], optional):
            The selected channel_id of audio file.
        disfluency_removal_enabled(bool, `optional`):
            Filter mood words, turned off by default.
        diarization_enabled (bool, `optional`):
            Speech auto diarization, turned off by default.
        speaker_count (int, `optional`): The number of speakers.
        timestamp_alignment_enabled (bool, `optional`):
            Timestamp-alignment calibration, turned off by default.
        special_word_filter(str, `optional`): Sensitive word filter.
        audio_event_detection_enabled(bool, `optional`):
            Audio event detection, turned off by default.

    Returns:
        TranscriptionResponse: The response including task_id.
    """
    kwargs.update(cls._fill_resource_id(phrase_id, **kwargs))
    kwargs = cls._tidy_kwargs(**kwargs)
    response = cls._launch_request(
        model,
        file_urls,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return TranscriptionResponse.from_api_response(response)

fetch classmethod

fetch(
    task: Any,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> TranscriptionResponse

Fetch the status of task, including results of batch transcription when task_status is SUCCEEDED. # noqa: E501 # pylint: disable=line-too-long

Parameters:

Name Type Description Default
task Union[str, TranscriptionResponse]

The task_id or response including task_id returned from async_call().

required
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
TranscriptionResponse TranscriptionResponse

The status of task_id,

including results of batch transcription when task_status is SUCCEEDED.

Source code in dashscope/legacy_1x/audio/asr/transcription.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
@classmethod
def fetch(
    cls,
    task: Union[str, TranscriptionResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> TranscriptionResponse:
    """Fetch the status of task, including results of batch transcription when task_status is SUCCEEDED.  # noqa: E501  # pylint: disable=line-too-long

    Args:
        task (Union[str, TranscriptionResponse]): The task_id or
            response including task_id returned from async_call().
        workspace (str): The dashscope workspace id.

    Returns:
        TranscriptionResponse: The status of task_id,
    including results of batch transcription when task_status is SUCCEEDED.
    """
    try_count: int = 0
    while True:
        try:
            response = super().fetch(
                task,
                api_key=api_key,
                workspace=workspace,
                **kwargs,
            )
        except (requests.Timeout, requests.ConnectionError) as e:
            logger.debug(e)
            try_count += 1
            if try_count <= Transcription.MAX_QUERY_TRY_COUNT:
                time.sleep(2)
                continue
            raise

        try_count = 0
        break

    return TranscriptionResponse.from_api_response(response)

wait classmethod

wait(
    task: Any,
    api_key: str | None = None,
    workspace: str | None = None,
    wait_timeout: int | None = -1,
    **kwargs: Any
) -> TranscriptionResponse

Poll task until the final results of transcription is obtained.

Parameters:

Name Type Description Default
task Union[str, TranscriptionResponse]

The task_id or response including task_id returned from async_call().

required
api_key str

The api_key. Defaults to None.

None
workspace str

The dashscope workspace id.

None
wait_timeout int

The timeout for waiting. Defaults to -1.That means no timeout. If set to a value > 0, the task does not complete within this time, a timeout error response will be returned.

-1

Returns:

Name Type Description
TranscriptionResponse TranscriptionResponse

The result of batch transcription.

Source code in dashscope/legacy_1x/audio/asr/transcription.py
163
164
165
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
@classmethod
def wait(
    cls,
    task: Union[str, TranscriptionResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs,
) -> TranscriptionResponse:
    """Poll task until the final results of transcription is obtained.

    Args:
        task (Union[str, TranscriptionResponse]): The task_id or
            response including task_id returned from async_call().
        api_key (str, optional): The api_key. Defaults to None.
        workspace (str): The dashscope workspace id.
        wait_timeout (int, optional): The timeout for waiting.
            Defaults to -1.That means no timeout.
            If set to a value > 0, the task does not complete
            within this time, a timeout error response will be returned.

    Returns:
        TranscriptionResponse: The result of batch transcription.
    """
    response = super().wait(
        task,
        api_key=api_key,
        workspace=workspace,
        wait_timeout=wait_timeout,
        **kwargs,
    )
    return TranscriptionResponse.from_api_response(response)

AsrPhraseManager

Bases: BaseAsyncApi

Hot word management for speech recognition.

create_phrases classmethod

create_phrases(
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Create hot words.

Parameters:

Name Type Description Default
model str

The requested model.

required
phrases Dict[str, Any]

A dictionary that contains phrases, such as {'下一首':90,'上一首':90}.

required
training_type str, `optional`

The training type, 'compile_asr_phrase' is default.

'compile_asr_phrase'
workspace str

The dashscope workspace id.

None

Raises:

Type Description
InvalidParameter

Parameter input is None or empty!

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The results of creating hot words.

Source code in dashscope/legacy_1x/audio/asr/asr_phrase_manager.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@classmethod
def create_phrases(
    cls,
    model: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Create hot words.

    Args:
        model (str): The requested model.
        phrases (Dict[str, Any]): A dictionary that contains phrases,
            such as {'下一首':90,'上一首':90}.
        training_type (str, `optional`): The training type,
            'compile_asr_phrase' is default.
        workspace (str): The dashscope workspace id.

    Raises:
        InvalidParameter: Parameter input is None or empty!

    Returns:
        DashScopeAPIResponse: The results of creating hot words.
    """
    if phrases is None or len(phrases) == 0:
        raise InvalidParameter("phrases is empty!")
    if training_type is None or len(training_type) == 0:
        raise InvalidParameter("training_type is empty!")

    original_ft_sub_path = FineTunes.SUB_PATH
    FineTunes.SUB_PATH = "fine-tunes"
    response = FineTunes.call(
        model=model,
        training_file_ids=[],
        validation_file_ids=[],
        mode=training_type,
        hyper_parameters={"phrase_list": phrases},
        workspace=workspace,
        **kwargs,
    )
    FineTunes.SUB_PATH = original_ft_sub_path

    if response.status_code != HTTPStatus.OK:
        logger.error("Create phrase failed, %s", response)

    return response  # type: ignore[return-value]

update_phrases classmethod

update_phrases(
    model: str,
    phrase_id: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Update the hot words marked phrase_id.

Parameters:

Name Type Description Default
model str

The requested model.

required
phrase_id str

The ID of phrases, which created by create_phrases().

required
phrases Dict[str, Any]

A dictionary that contains phrases, such as {'暂停':90}.

required
training_type str, `optional`

The training type, 'compile_asr_phrase' is default.

'compile_asr_phrase'
workspace str

The dashscope workspace id.

None

Raises:

Type Description
InvalidParameter

Parameter input is None or empty!

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The results of updating hot words.

Source code in dashscope/legacy_1x/audio/asr/asr_phrase_manager.py
 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
@classmethod
def update_phrases(
    cls,
    model: str,
    phrase_id: str,
    phrases: Dict[str, Any],
    training_type: str = "compile_asr_phrase",
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Update the hot words marked phrase_id.

    Args:
        model (str): The requested model.
        phrase_id (str): The ID of phrases,
            which created by create_phrases().
        phrases (Dict[str, Any]): A dictionary that contains phrases,
            such as {'暂停':90}.
        training_type (str, `optional`):
            The training type, 'compile_asr_phrase' is default.
        workspace (str): The dashscope workspace id.

    Raises:
        InvalidParameter: Parameter input is None or empty!

    Returns:
        DashScopeAPIResponse: The results of updating hot words.
    """
    if phrase_id is None or len(phrase_id) == 0:
        raise InvalidParameter("phrase_id is empty!")
    if phrases is None or len(phrases) == 0:
        raise InvalidParameter("phrases is empty!")
    if training_type is None or len(training_type) == 0:
        raise InvalidParameter("training_type is empty!")

    original_ft_sub_path = FineTunes.SUB_PATH
    FineTunes.SUB_PATH = "fine-tunes"
    response = FineTunes.call(
        model=model,
        training_file_ids=[],
        validation_file_ids=[],
        mode=training_type,
        hyper_parameters={"phrase_list": phrases},
        finetuned_output=phrase_id,
        workspace=workspace,
        **kwargs,
    )
    FineTunes.SUB_PATH = original_ft_sub_path

    if response.status_code != HTTPStatus.OK:
        logger.error("Update phrase failed, %s", response)

    return response  # type: ignore[return-value]

query_phrases classmethod

query_phrases(
    phrase_id: str, workspace: str = None, **kwargs
) -> DashScopeAPIResponse

Query the hot words by phrase_id.

Parameters:

Name Type Description Default
phrase_id str

The ID of phrases, which created by create_phrases().

required
workspace str

The dashscope workspace id.

None

Raises:

Type Description
InvalidParameter

phrase_id input is None or empty!

Returns:

Name Type Description
AsrPhraseManagerResult DashScopeAPIResponse

The results of querying hot words.

Source code in dashscope/legacy_1x/audio/asr/asr_phrase_manager.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
@classmethod
def query_phrases(
    cls,
    phrase_id: str,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Query the hot words by phrase_id.

    Args:
        phrase_id (str): The ID of phrases,
            which created by create_phrases().
        workspace (str): The dashscope workspace id.

    Raises:
        InvalidParameter: phrase_id input is None or empty!

    Returns:
        AsrPhraseManagerResult: The results of querying hot words.
    """
    if phrase_id is None or len(phrase_id) == 0:
        raise InvalidParameter("phrase_id is empty!")

    original_ft_sub_path = FineTunes.SUB_PATH
    FineTunes.SUB_PATH = "fine-tunes/outputs"
    response = FineTunes.get(
        job_id=phrase_id,
        workspace=workspace,
        **kwargs,
    )
    FineTunes.SUB_PATH = original_ft_sub_path

    if response.status_code != HTTPStatus.OK:
        logger.error("Query phrase failed, %s", response)

    return response  # type: ignore[return-value]

list_phrases classmethod

list_phrases(
    page: int = 1,
    page_size: int = 10,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List all information of phrases.

Parameters:

Name Type Description Default
page int

Page number, greater than 0, default value 1.

1
page_size int

The paging size, greater than 0 and less than or equal to 100, default value 10.

10
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The results of listing hot words.

Source code in dashscope/legacy_1x/audio/asr/asr_phrase_manager.py
158
159
160
161
162
163
164
165
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
@classmethod
def list_phrases(
    cls,
    page: int = 1,
    page_size: int = 10,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List all information of phrases.

    Args:
        page (int): Page number, greater than 0, default value 1.
        page_size (int): The paging size, greater than 0
            and less than or equal to 100, default value 10.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The results of listing hot words.
    """
    original_ft_sub_path = FineTunes.SUB_PATH
    FineTunes.SUB_PATH = "fine-tunes/outputs"
    response = FineTunes.list(
        page=page,
        page_size=page_size,
        workspace=workspace,
        **kwargs,
    )
    FineTunes.SUB_PATH = original_ft_sub_path

    if response.status_code != HTTPStatus.OK:
        logger.error("List phrase failed, %s", response)

    return response  # type: ignore[return-value]

delete_phrases classmethod

delete_phrases(
    phrase_id: str, workspace: str = None, **kwargs
) -> DashScopeAPIResponse

Delete the hot words by phrase_id.

Parameters:

Name Type Description Default
phrase_id str

The ID of phrases, which created by create_phrases().

required

Raises:

Type Description
InvalidParameter

phrase_id input is None or empty!

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The results of deleting hot words.

Source code in dashscope/legacy_1x/audio/asr/asr_phrase_manager.py
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
226
@classmethod
def delete_phrases(
    cls,
    phrase_id: str,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Delete the hot words by phrase_id.

    Args:
        phrase_id (str): The ID of phrases,
            which created by create_phrases().

    Raises:
        InvalidParameter: phrase_id input is None or empty!

    Returns:
        DashScopeAPIResponse: The results of deleting hot words.
    """
    if phrase_id is None or len(phrase_id) == 0:
        raise InvalidParameter("phrase_id is empty!")

    original_ft_sub_path = FineTunes.SUB_PATH
    FineTunes.SUB_PATH = "fine-tunes/outputs"
    response = FineTunes.delete(
        job_id=phrase_id,
        workspace=workspace,
        **kwargs,
    )
    FineTunes.SUB_PATH = original_ft_sub_path

    if response.status_code != HTTPStatus.OK:
        logger.error("Delete phrase failed, %s", response)

    return response  # type: ignore[return-value]

TranslationRecognizerRealtime

TranslationRecognizerRealtime(
    model: str,
    callback: TranslationRecognizerCallback,
    format: str,
    sample_rate: int,
    transcription_enabled: bool = True,
    source_language: str = None,
    translation_enabled: bool = False,
    workspace: str = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs
)

Bases: BaseApi

TranslationRecognizerRealtime interface.

Parameters:

Name Type Description Default
model str

The requested model_id.

required
callback TranslationRecognizerRealtime

A callback that returns TranslationRecognizerRealtime results.

required
format str

The input audio format.

required
sample_rate int

The input audio sample rate.

required
workspace str

The dashscope workspace id.

None
**kwargs Any

phrase_id (list, optional): The ID of phrase. disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Raises:

Type Description
InputRequired

Input is required.

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
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
def __init__(
    self,
    model: str,
    callback: TranslationRecognizerCallback,
    format: str,  # pylint: disable=redefined-builtin
    sample_rate: int,
    transcription_enabled: bool = True,
    source_language: str = None,
    translation_enabled: bool = False,
    workspace: str = None,
    # Recognition parameters
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs,
):
    if model is None:
        raise ModelRequired("Model is required!")
    if format is None:
        raise InputRequired("format is required!")
    if sample_rate is None:
        raise InputRequired("sample_rate is required!")

    self.model = model
    self.format = format
    self.sample_rate = sample_rate
    self.source_language = source_language
    self.transcription_enabled = transcription_enabled
    self.translation_enabled = translation_enabled
    # continuous recognition with start() or once recognition with call()
    self._recognition_once = False
    self._callback = callback
    self._running = False
    self._stream_data = Queue()
    self._worker = None
    self._silence_timer = None
    self._kwargs = kwargs
    # Store recognition parameters
    _merge_recognition_params(
        self._kwargs,
        disfluency_removal_enabled,
        diarization_enabled,
        speaker_count,
        timestamp_alignment_enabled,
        special_word_filter,
        audio_event_detection_enabled,
    )
    self._workspace = workspace
    self._start_stream_timestamp = -1
    self._first_package_timestamp = -1
    self._stop_stream_timestamp = -1
    self._on_complete_timestamp = -1
    self.request_id_confirmed = False
    self.last_request_id = uuid.uuid4().hex

SILENCE_TIMEOUT_S class-attribute instance-attribute

SILENCE_TIMEOUT_S = 23

model instance-attribute

model = model

format instance-attribute

format = format

sample_rate instance-attribute

sample_rate = sample_rate

source_language instance-attribute

source_language = source_language

transcription_enabled instance-attribute

transcription_enabled = transcription_enabled

translation_enabled instance-attribute

translation_enabled = translation_enabled

request_id_confirmed instance-attribute

request_id_confirmed = False

last_request_id instance-attribute

last_request_id = uuid.uuid4().hex

start

start(
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs
)

Real-time translation recognizer in asynchronous mode. Please call 'stop()' after you have completed translation & recognition. # noqa: E501

Parameters:

Name Type Description Default
**kwargs Any

phrase_id (str, optional): The ID of phrase. disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Raises:

Type Description
InvalidParameter

This interface cannot be called again if it has already been started.

InvalidTask

Task create failed.

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
def start(
    self,
    # Recognition parameters
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs,
):
    """Real-time translation recognizer in asynchronous mode.
       Please call 'stop()' after you have completed translation & recognition.  # noqa: E501

    Args:
        **kwargs (Any):
            phrase_id (str, `optional`): The ID of phrase.
            disfluency_removal_enabled(bool, `optional`):
                Filter mood words, turned off by default.
            diarization_enabled (bool, `optional`):
                Speech auto diarization, turned off by default.
            speaker_count (int, `optional`): The number of speakers.
            timestamp_alignment_enabled (bool, `optional`):
                Timestamp-alignment calibration, turned off by default.
            special_word_filter(str, `optional`): Sensitive word filter.
            audio_event_detection_enabled(bool, `optional`):
                Audio event detection, turned off by default.

    Raises:
        InvalidParameter: This interface cannot be called again
            if it has already been started.
        InvalidTask: Task create failed.
    """
    assert (
        self._callback is not None
    ), "Please set the callback to get the translation & recognition result."  # noqa E501

    if self._running:
        raise InvalidParameter(
            "TranslationRecognizerRealtime has started.",
        )

    self._start_stream_timestamp = -1
    self._first_package_timestamp = -1
    self._stop_stream_timestamp = -1
    self._on_complete_timestamp = -1
    # Update recognition parameters
    _merge_recognition_params(
        self._kwargs,
        disfluency_removal_enabled,
        diarization_enabled,
        speaker_count,
        timestamp_alignment_enabled,
        special_word_filter,
        audio_event_detection_enabled,
    )
    self._kwargs.update(**kwargs)
    self._recognition_once = False
    self._worker = threading.Thread(target=self.__receive_worker)
    self._worker.start()
    if self._worker.is_alive():
        self._running = True
        self._callback.on_open()

        # If audio data is not received for 23 seconds, the timeout exits
        self._silence_timer = Timer(
            TranslationRecognizerRealtime.SILENCE_TIMEOUT_S,
            self._silence_stop_timer,
        )
        self._silence_timer.start()
    else:
        self._running = False
        raise InvalidTask("Invalid task, task create failed.")

call

call(
    file: str,
    phrase_id: str = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs
) -> TranslationRecognizerResultPack

TranslationRecognizerRealtime in synchronous mode.

Parameters:

Name Type Description Default
file str

The path to the local audio file.

required
phrase_id str, `optional`

The ID of phrase.

None
**kwargs Any

disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Raises:

Type Description
InvalidParameter

This interface cannot be called again if it has already been started.

InputDataRequired

The supplied file was empty.

Returns:

Name Type Description
TranslationRecognizerResultPack TranslationRecognizerResultPack

The result of speech translation & recognition. # noqa: E501 # pylint: disable=line-too-long

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
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
637
638
639
640
641
642
643
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
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
def call(  # type: ignore[override]
    self,
    file: str,
    phrase_id: str = None,
    # Recognition parameters
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs,
) -> TranslationRecognizerResultPack:
    """TranslationRecognizerRealtime in synchronous mode.

    Args:
        file (str): The path to the local audio file.
        phrase_id (str, `optional`): The ID of phrase.

        **kwargs (Any):
            disfluency_removal_enabled(bool, `optional`):
                Filter mood words, turned off by default.
            diarization_enabled (bool, `optional`):
                Speech auto diarization, turned off by default.
            speaker_count (int, `optional`): The number of speakers.
            timestamp_alignment_enabled (bool, `optional`):
                Timestamp-alignment calibration, turned off by default.
            special_word_filter(str, `optional`): Sensitive word filter.
            audio_event_detection_enabled(bool, `optional`):
                Audio event detection, turned off by default.

    Raises:
        InvalidParameter: This interface cannot be called again
            if it has already been started.
        InputDataRequired: The supplied file was empty.

    Returns:
        TranslationRecognizerResultPack: The result of speech translation & recognition.  # noqa: E501  # pylint: disable=line-too-long
    """
    self._start_stream_timestamp = time.time() * 1000
    if self._running:
        raise InvalidParameter(
            "TranslationRecognizerRealtime has been called.",
        )

    if os.path.exists(file):
        if os.path.isdir(file):
            raise IsADirectoryError("Is a directory: " + file)
    else:
        raise FileNotFoundError("No such file or directory: " + file)

    self._recognition_once = True
    self._stream_data = Queue()
    self._phrase = phrase_id
    # Update recognition parameters
    _merge_recognition_params(
        self._kwargs,
        disfluency_removal_enabled,
        diarization_enabled,
        speaker_count,
        timestamp_alignment_enabled,
        special_word_filter,
        audio_event_detection_enabled,
    )
    self._kwargs.update(**kwargs)
    results = TranslationRecognizerResultPack()
    error_message = None

    try:
        audio_data: bytes = None
        # pylint: disable=consider-using-with
        f = open(file, "rb")
        if os.path.getsize(file):
            while True:
                audio_data = f.read(12800)
                if not audio_data:
                    break
                self._stream_data.put(
                    audio_data,
                )  # pylint: disable=no-else-break
        else:
            raise InputDataRequired(
                "The supplied file was empty (zero bytes long)",
            )
        f.close()
        self._stop_stream_timestamp = time.time() * 1000
    except Exception as e:
        logger.debug(e)
        raise

    if not self._stream_data.empty():
        self._running = True
        responses = self.__launch_request()
        for part in responses:
            if part.status_code == HTTPStatus.OK:
                logger.debug("received data: %s", part.output)
                # debug log cal fpd
                transcription = None
                translation = None
                usage = None
                if ("translation" in part.output) or (
                    "transcription" in part.output
                ):
                    if self._first_package_timestamp < 0:
                        self._first_package_timestamp = time.time() * 1000
                        logger.debug(
                            "first package delay %s",
                            self._first_package_timestamp
                            - self._start_stream_timestamp,
                        )
                    if part.usage is not None:
                        usage = part.usage

                if DASHSCOPE_TRANSCRIPTION_KEY in part.output:
                    transcription = TranscriptionResult.from_json(
                        part.output[DASHSCOPE_TRANSCRIPTION_KEY],
                    )

                if DASHSCOPE_TRANSLATION_KEY in part.output:
                    translation = TranslationResult.from_json(
                        part.output[DASHSCOPE_TRANSLATION_KEY],
                    )

                if (
                    transcription is not None
                    and transcription.is_sentence_end
                ) or (
                    translation is not None and translation.is_sentence_end
                ):
                    results.request_id = part.request_id
                    results.transcription_result_list.append(
                        transcription,  # type: ignore[arg-type]
                    )  # noqa: E501
                    results.translation_result_list.append(
                        translation,  # type: ignore[arg-type]
                    )  # noqa: E501
                    results.usage_list.append(usage)
            else:
                error_message = part
                logger.error(error_message)
                break

    self._on_complete_timestamp = time.time() * 1000
    logger.debug(
        "last package delay %s",
        self.get_last_package_delay(),
    )

    self._stream_data = Queue()
    self._recognition_once = False
    self._running = False
    results.error_message = error_message
    return results

stop

stop()

End asynchronous TranslationRecognizerRealtime.

Raises:

Type Description
InvalidParameter

Cannot stop an uninitiated TranslationRecognizerRealtime. # noqa: E501 # pylint: disable=line-too-long

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
def stop(self):
    """End asynchronous TranslationRecognizerRealtime.

    Raises:
        InvalidParameter: Cannot stop an uninitiated TranslationRecognizerRealtime.  # noqa: E501  # pylint: disable=line-too-long
    """
    if self._running is False:
        raise InvalidParameter(
            "TranslationRecognizerRealtime has stopped.",
        )

    self._stop_stream_timestamp = time.time() * 1000

    self._running = False
    if self._worker is not None and self._worker.is_alive():
        self._worker.join()
    self._stream_data = Queue()
    if self._silence_timer is not None and self._silence_timer.is_alive():
        self._silence_timer.cancel()
        self._silence_timer = None
    if self._callback:
        self._callback.on_close()

send_audio_frame

send_audio_frame(buffer: bytes)

Push audio to TranslationRecognizerRealtime.

Raises:

Type Description
InvalidParameter

Cannot send data to an uninitiated TranslationRecognizerRealtime. # noqa: E501 # pylint: disable=line-too-long

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
def send_audio_frame(self, buffer: bytes):
    """Push audio to TranslationRecognizerRealtime.

    Raises:
        InvalidParameter: Cannot send data to an uninitiated TranslationRecognizerRealtime.  # noqa: E501  # pylint: disable=line-too-long
    """
    if self._running is False:
        raise InvalidParameter(
            "TranslationRecognizerRealtime has stopped.",
        )

    if self._start_stream_timestamp < 0:
        self._start_stream_timestamp = time.time() * 1000
    logger.debug("send_audio_frame: %s", len(buffer))
    self._stream_data.put(buffer)

get_first_package_delay

get_first_package_delay()

First Package Delay is the time between start sending audio and receive first words package

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
793
794
795
def get_first_package_delay(self):
    """First Package Delay is the time between start sending audio and receive first words package"""  # noqa: E501  # pylint: disable=line-too-long
    return self._first_package_timestamp - self._start_stream_timestamp

get_last_package_delay

get_last_package_delay()

Last Package Delay is the time between stop sending audio and receive last words package

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
797
798
799
def get_last_package_delay(self):
    """Last Package Delay is the time between stop sending audio and receive last words package"""  # noqa: E501  # pylint: disable=line-too-long
    return self._on_complete_timestamp - self._stop_stream_timestamp

get_last_request_id

get_last_request_id()
Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
802
803
def get_last_request_id(self):
    return self.last_request_id

TranslationRecognizerChat

TranslationRecognizerChat(
    model: str,
    callback: TranslationRecognizerCallback,
    format: str,
    sample_rate: int,
    transcription_enabled: bool = True,
    source_language: str = None,
    translation_enabled: bool = False,
    workspace: str = None,
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs
)

Bases: BaseApi

TranslationRecognizerChat interface.

Parameters:

Name Type Description Default
model str

The requested model_id.

required
callback TranslationRecognizerChat

A callback that returns TranslationRecognizerChat results.

required
format str

The input audio format.

required
sample_rate int

The input audio sample rate.

required
workspace str

The dashscope workspace id.

None
**kwargs Any

phrase_id (list, optional): The ID of phrase. disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Raises:

Type Description
InputRequired

Input is required.

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
def __init__(
    self,
    model: str,
    callback: TranslationRecognizerCallback,
    format: str,  # pylint: disable=redefined-builtin
    sample_rate: int,
    transcription_enabled: bool = True,
    source_language: str = None,
    translation_enabled: bool = False,
    workspace: str = None,
    # Recognition parameters
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs,
):
    if model is None:
        raise ModelRequired("Model is required!")
    if format is None:
        raise InputRequired("format is required!")
    if sample_rate is None:
        raise InputRequired("sample_rate is required!")

    self.model = model
    self.format = format
    self.sample_rate = sample_rate
    self.source_language = source_language
    self.transcription_enabled = transcription_enabled
    self.translation_enabled = translation_enabled
    # continuous recognition with start() or once recognition with call()
    self._recognition_once = False
    self._callback = callback
    self._running = False
    self._stream_data = Queue()
    self._worker = None
    self._silence_timer = None
    self._kwargs = kwargs
    # Store recognition parameters
    _merge_recognition_params(
        self._kwargs,
        disfluency_removal_enabled,
        diarization_enabled,
        speaker_count,
        timestamp_alignment_enabled,
        special_word_filter,
        audio_event_detection_enabled,
    )
    self._workspace = workspace
    self._start_stream_timestamp = -1
    self._first_package_timestamp = -1
    self._stop_stream_timestamp = -1
    self._on_complete_timestamp = -1
    self.request_id_confirmed = False
    self.last_request_id = uuid.uuid4().hex
    self._is_sentence_end = ThreadSafeBool(False)

SILENCE_TIMEOUT_S class-attribute instance-attribute

SILENCE_TIMEOUT_S = 23

model instance-attribute

model = model

format instance-attribute

format = format

sample_rate instance-attribute

sample_rate = sample_rate

source_language instance-attribute

source_language = source_language

transcription_enabled instance-attribute

transcription_enabled = transcription_enabled

translation_enabled instance-attribute

translation_enabled = translation_enabled

request_id_confirmed instance-attribute

request_id_confirmed = False

last_request_id instance-attribute

last_request_id = uuid.uuid4().hex

start

start(
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs
)

Real-time translation recognizer in asynchronous mode. Please call 'stop()' after you have completed translation & recognition. # noqa: E501

Parameters:

Name Type Description Default
**kwargs Any

phrase_id (str, optional): The ID of phrase. disfluency_removal_enabled(bool, optional): Filter mood words, turned off by default. diarization_enabled (bool, optional): Speech auto diarization, turned off by default. speaker_count (int, optional): The number of speakers. timestamp_alignment_enabled (bool, optional): Timestamp-alignment calibration, turned off by default. special_word_filter(str, optional): Sensitive word filter. audio_event_detection_enabled(bool, optional): Audio event detection, turned off by default.

{}

Raises:

Type Description
InvalidParameter

This interface cannot be called again if it has already been started.

InvalidTask

Task create failed.

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
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
def start(
    self,
    # Recognition parameters
    disfluency_removal_enabled: Optional[bool] = None,
    diarization_enabled: Optional[bool] = None,
    speaker_count: Optional[int] = None,
    timestamp_alignment_enabled: Optional[bool] = None,
    special_word_filter: Optional[str] = None,
    audio_event_detection_enabled: Optional[bool] = None,
    **kwargs,
):
    """Real-time translation recognizer in asynchronous mode.
       Please call 'stop()' after you have completed translation & recognition.  # noqa: E501

    Args:
        **kwargs (Any):
            phrase_id (str, `optional`): The ID of phrase.
            disfluency_removal_enabled(bool, `optional`):
                Filter mood words, turned off by default.
            diarization_enabled (bool, `optional`):
                Speech auto diarization, turned off by default.
            speaker_count (int, `optional`): The number of speakers.
            timestamp_alignment_enabled (bool, `optional`):
                Timestamp-alignment calibration, turned off by default.
            special_word_filter(str, `optional`): Sensitive word filter.
            audio_event_detection_enabled(bool, `optional`):
                Audio event detection, turned off by default.

    Raises:
        InvalidParameter: This interface cannot be called again
            if it has already been started.
        InvalidTask: Task create failed.
    """
    assert (
        self._callback is not None
    ), "Please set the callback to get the translation & recognition result."  # noqa E501

    if self._running:
        raise InvalidParameter("TranslationRecognizerChat has started.")

    self._start_stream_timestamp = -1
    self._first_package_timestamp = -1
    self._stop_stream_timestamp = -1
    self._on_complete_timestamp = -1
    # Update recognition parameters
    _merge_recognition_params(
        self._kwargs,
        disfluency_removal_enabled,
        diarization_enabled,
        speaker_count,
        timestamp_alignment_enabled,
        special_word_filter,
        audio_event_detection_enabled,
    )
    self._kwargs.update(**kwargs)
    self._recognition_once = False
    self._worker = threading.Thread(target=self.__receive_worker)
    self._worker.start()
    if self._worker.is_alive():
        self._running = True
        self._callback.on_open()

        # If audio data is not received for 23 seconds, the timeout exits
        self._silence_timer = Timer(
            TranslationRecognizerChat.SILENCE_TIMEOUT_S,
            self._silence_stop_timer,
        )
        self._silence_timer.start()
    else:
        self._running = False
        raise InvalidTask("Invalid task, task create failed.")

stop

stop()

End asynchronous TranslationRecognizerChat.

Raises:

Type Description
InvalidParameter

Cannot stop an uninitiated TranslationRecognizerChat. # noqa: E501

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
def stop(self):
    """End asynchronous TranslationRecognizerChat.

    Raises:
        InvalidParameter: Cannot stop an uninitiated TranslationRecognizerChat.  # noqa: E501
    """
    if self._running is False:
        raise InvalidParameter("TranslationRecognizerChat has stopped.")

    self._stop_stream_timestamp = time.time() * 1000
    logger.debug("stop TranslationRecognizerChat")
    self._running = False
    if self._worker is not None and self._worker.is_alive():
        self._worker.join()
    self._stream_data = Queue()
    if self._silence_timer is not None and self._silence_timer.is_alive():
        self._silence_timer.cancel()
        self._silence_timer = None
    if self._callback:
        self._callback.on_close()

send_audio_frame

send_audio_frame(buffer: bytes) -> bool

Push audio to TranslationRecognizerChat.

Raises:

Type Description
InvalidParameter

Cannot send data to an uninitiated TranslationRecognizerChat. # noqa: E501 # pylint: disable=line-too-long

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
def send_audio_frame(self, buffer: bytes) -> bool:
    """Push audio to TranslationRecognizerChat.

    Raises:
        InvalidParameter: Cannot send data to an uninitiated TranslationRecognizerChat.  # noqa: E501  # pylint: disable=line-too-long
    """
    if self._is_sentence_end.get():
        logger.debug("skip audio due to has sentence end.")
        return False

    if self._running is False:
        raise InvalidParameter("TranslationRecognizerChat has stopped.")

    if self._start_stream_timestamp < 0:
        self._start_stream_timestamp = time.time() * 1000
    logger.debug("send_audio_frame: %s", len(buffer))
    self._stream_data.put(buffer)
    return True

get_first_package_delay

get_first_package_delay()

First Package Delay is the time between start sending audio and receive first words package

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
1172
1173
1174
def get_first_package_delay(self):
    """First Package Delay is the time between start sending audio and receive first words package"""  # noqa: E501  # pylint: disable=line-too-long
    return self._first_package_timestamp - self._start_stream_timestamp

get_last_package_delay

get_last_package_delay()

Last Package Delay is the time between stop sending audio and receive last words package

Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
1176
1177
1178
def get_last_package_delay(self):
    """Last Package Delay is the time between stop sending audio and receive last words package"""  # noqa: E501  # pylint: disable=line-too-long
    return self._on_complete_timestamp - self._stop_stream_timestamp

get_last_request_id

get_last_request_id()
Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
1181
1182
def get_last_request_id(self):
    return self.last_request_id

TranslationRecognizerCallback

An interface that defines callback methods for getting translation recognizer results. # noqa E501 # pylint: disable=line-too-long Derive from this class and implement its function to provide your own data.

on_open

on_open() -> None
Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
266
267
def on_open(self) -> None:
    pass

on_complete

on_complete() -> None
Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
269
270
def on_complete(self) -> None:
    pass

on_error

on_error(message) -> None
Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
272
273
def on_error(self, message) -> None:
    pass

on_close

on_close() -> None
Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
275
276
def on_close(self) -> None:
    pass

on_event

on_event(
    request_id,
    transcription_result: TranscriptionResult,
    translation_result: TranslationResult,
    usage,
) -> None
Source code in dashscope/legacy_1x/audio/asr/translation_recognizer.py
278
279
280
281
282
283
284
285
def on_event(
    self,
    request_id,
    transcription_result: TranscriptionResult,
    translation_result: TranslationResult,
    usage,
) -> None:
    pass

QwenTranscription

Bases: BaseAsyncApi

API for File Transcription models.

MAX_QUERY_TRY_COUNT class-attribute instance-attribute

MAX_QUERY_TRY_COUNT = 3

call classmethod

call(
    model: str,
    file_url: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> TranscriptionResponse

Transcribe the given files synchronously.

Parameters:

Name Type Description Default
model str

The requested model_id.

required
file_url str

stored URL.

required
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
TranscriptionResponse TranscriptionResponse

The result of batch transcription.

Source code in dashscope/legacy_1x/audio/qwen_asr/qwen_transcription.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@classmethod
def call(  # type: ignore[override]
    cls,
    model: str,
    file_url: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> TranscriptionResponse:
    """Transcribe the given files synchronously.

    Args:
        model (str): The requested model_id.
        file_url (str): stored URL.
        workspace (str): The dashscope workspace id.

    Returns:
        TranscriptionResponse: The result of batch transcription.
    """
    kwargs = cls._tidy_kwargs(**kwargs)
    response = super().call(
        model,
        file_url,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return TranscriptionResponse.from_api_response(response)

async_call classmethod

async_call(
    model: str,
    file_url: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> TranscriptionResponse

Transcribe the given files asynchronously, return the status of task submission for querying results subsequently.

Parameters:

Name Type Description Default
model str

The requested model, such as paraformer-16k-1

required
file_url str

stored URL.

required
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
TranscriptionResponse TranscriptionResponse

The response including task_id.

Source code in dashscope/legacy_1x/audio/qwen_asr/qwen_transcription.py
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
@classmethod
def async_call(  # type: ignore[override]
    cls,
    model: str,
    file_url: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> TranscriptionResponse:
    """Transcribe the given files asynchronously,
    return the status of task submission for querying results subsequently.

    Args:
        model (str): The requested model, such as paraformer-16k-1
        file_url (str): stored URL.
        workspace (str): The dashscope workspace id.

    Returns:
        TranscriptionResponse: The response including task_id.
    """
    kwargs = cls._tidy_kwargs(**kwargs)
    response = cls._launch_request(
        model,
        file_url,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return TranscriptionResponse.from_api_response(response)

fetch classmethod

fetch(
    task: Union[str, TranscriptionResponse],
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> TranscriptionResponse

Fetch the status of task, including results of batch transcription when task_status is SUCCEEDED. # noqa: E501 # pylint: disable=line-too-long

Parameters:

Name Type Description Default
task Union[str, TranscriptionResponse]

The task_id or response including task_id returned from async_call().

required
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
TranscriptionResponse TranscriptionResponse

The status of task_id,

including results of batch transcription when task_status is SUCCEEDED.

Source code in dashscope/legacy_1x/audio/qwen_asr/qwen_transcription.py
 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
121
@classmethod
def fetch(
    cls,
    task: Union[str, TranscriptionResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> TranscriptionResponse:
    """Fetch the status of task, including results of batch transcription when task_status is SUCCEEDED.  # noqa: E501  # pylint: disable=line-too-long

    Args:
        task (Union[str, TranscriptionResponse]): The task_id or
            response including task_id returned from async_call().
        workspace (str): The dashscope workspace id.

    Returns:
        TranscriptionResponse: The status of task_id,
    including results of batch transcription when task_status is SUCCEEDED.
    """
    try_count: int = 0
    while True:
        try:
            response = super().fetch(
                task,
                api_key=api_key,
                workspace=workspace,
                **kwargs,
            )
        except (requests.Timeout, requests.ConnectionError) as e:
            logger.debug(e)
            try_count += 1
            if try_count <= QwenTranscription.MAX_QUERY_TRY_COUNT:
                time.sleep(2)
                continue
            raise

        try_count = 0
        break

    return TranscriptionResponse.from_api_response(response)

wait classmethod

wait(
    task: Union[str, TranscriptionResponse],
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs
) -> TranscriptionResponse

Poll task until the final results of transcription is obtained.

Parameters:

Name Type Description Default
task Union[str, TranscriptionResponse]

The task_id or response including task_id returned from async_call().

required
workspace str

The dashscope workspace id.

None
wait_timeout int

The maximum seconds to wait. Default is -1 (no timeout).

-1

Returns:

Name Type Description
TranscriptionResponse TranscriptionResponse

The result of batch transcription.

Source code in dashscope/legacy_1x/audio/qwen_asr/qwen_transcription.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
@classmethod
def wait(
    cls,
    task: Union[str, TranscriptionResponse],  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    wait_timeout: int = -1,
    **kwargs,
) -> TranscriptionResponse:
    """Poll task until the final results of transcription is obtained.

    Args:
        task (Union[str, TranscriptionResponse]): The task_id or
            response including task_id returned from async_call().
        workspace (str): The dashscope workspace id.
        wait_timeout (int, optional): The maximum seconds to wait.
            Default is -1 (no timeout).

    Returns:
        TranscriptionResponse: The result of batch transcription.
    """
    response = super().wait(
        task,
        api_key=api_key,
        workspace=workspace,
        wait_timeout=wait_timeout,
        **kwargs,
    )
    return TranscriptionResponse.from_api_response(response)

Omni realtime (1.x)

OmniRealtimeConversation

OmniRealtimeConversation(
    model,
    callback: OmniRealtimeCallback,
    headers=None,
    workspace=None,
    url=None,
    api_key: str = None,
    additional_params=None,
)

Qwen Omni Realtime SDK Parameters:


model: str Model name. headers: Dict User-defined headers. callback: OmniRealtimeCallback Callback to receive real-time omni results. workspace: str Dashscope workspace ID. url: str Dashscope WebSocket URL. additional_params: Dict Additional parameters for the Dashscope API.

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def __init__(
    self,
    model,
    callback: OmniRealtimeCallback,
    headers=None,
    workspace=None,
    url=None,
    api_key: str = None,
    additional_params=None,  # pylint: disable=unused-argument
):
    """
    Qwen Omni Realtime SDK
    Parameters:
    -----------
    model: str
        Model name.
    headers: Dict
        User-defined headers.
    callback: OmniRealtimeCallback
        Callback to receive real-time omni results.
    workspace: str
        Dashscope workspace ID.
    url: str
        Dashscope WebSocket URL.
    additional_params: Dict
        Additional parameters for the Dashscope API.
    """

    if model is None:
        raise ModelRequired("Model is required!")
    if callback is None:
        raise ModelRequired("Callback is required!")
    if url is None:
        url = f"wss://dashscope.aliyuncs.com/api-ws/v1/realtime?model={model}"  # noqa: E501
    else:
        url = f"{url}?model={model}"
    self.url = url
    self.apikey = api_key or dashscope.api_key
    self.user_headers = headers
    self.user_workspace = workspace
    self.model = model
    self.config = {}
    self.callback = callback
    self.ws = None
    self.session_id = None
    self.last_message = None
    self.last_response_id = None
    self.last_response_create_time = None
    self.last_first_text_delay = None
    self.last_first_audio_delay = None
    self.metrics = []
    # Add event for synchronously waiting on connection close
    self.disconnect_event = None
    self._disconnect_error = None

url instance-attribute

url = url

apikey instance-attribute

apikey = api_key or dashscope.api_key

user_headers instance-attribute

user_headers = headers

user_workspace instance-attribute

user_workspace = workspace

model instance-attribute

model = model

config instance-attribute

config = {}

callback instance-attribute

callback = callback

ws instance-attribute

ws = None

session_id instance-attribute

session_id = None

last_message instance-attribute

last_message = None

last_response_id instance-attribute

last_response_id = None

last_response_create_time instance-attribute

last_response_create_time = None

last_first_text_delay instance-attribute

last_first_text_delay = None

last_first_audio_delay instance-attribute

last_first_audio_delay = None

metrics instance-attribute

metrics = []

disconnect_event instance-attribute

disconnect_event = None

connect

connect() -> None

connect to server, create session and return default session configuration # noqa: E501

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
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
def connect(self) -> None:
    """
    connect to server, create session and return default session configuration  # noqa: E501
    """
    self.ws = websocket.WebSocketApp(
        self.url,
        header=self._get_websocket_header(),
        on_message=self._on_message,
        on_error=self._on_error,
        on_close=self._on_close,
    )
    self.thread = threading.Thread(target=self.ws.run_forever)
    self.thread.daemon = True
    self.thread.start()
    timeout = 5  # max wait time in seconds
    start_time = time.time()
    while (
        not (self.ws.sock and self.ws.sock.connected)
        and (time.time() - start_time) < timeout
    ):
        time.sleep(0.1)  # Brief sleep to avoid busy polling
    if not (self.ws.sock and self.ws.sock.connected):
        raise TimeoutError(
            "websocket connection could not established within 5s. "
            "Please check your network connection, firewall settings, "
            "or server status.",
        )
    self.callback.on_open()

create_item

create_item(item: dict)

send item.create request

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
def create_item(self, item: dict):
    """
    send item.create request
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "conversation.item.create",
                "item": item,
            },
        ),
        enable_log=True,
    )

update_session

update_session(
    output_modalities: List[MultiModality],
    voice: str = None,
    input_audio_format: AudioFormat = AudioFormat.PCM_16000HZ_MONO_16BIT,
    output_audio_format: AudioFormat = AudioFormat.PCM_24000HZ_MONO_16BIT,
    enable_input_audio_transcription: bool = True,
    input_audio_transcription_model: str = None,
    enable_turn_detection: bool = True,
    turn_detection_type: str = "server_vad",
    prefix_padding_ms: int = 300,
    turn_detection_threshold: float = 0.2,
    turn_detection_silence_duration_ms: int = 800,
    turn_detection_param: dict = None,
    translation_params: TranslationParams = None,
    transcription_params: TranscriptionParams = None,
    input_audio_config: AudioFormatConfig = None,
    output_audio_config: AudioFormatConfig = None,
    input_video_representation_compact: str = None,
    **kwargs
) -> None

update session configuration, should be used before create response

Parameters

output_modalities: list[MultiModality] omni output modalities to be used in session voice: str voice to be used in session input_audio_format: AudioFormat input audio format. Legacy parameter, kept for backward compatibility and still the default path. Prefer input_audio_config which supports separate audio format type and sample rate. output_audio_format: AudioFormat output audio format. Legacy parameter, kept for backward compatibility and still the default path. Prefer output_audio_config which supports separate audio format type and sample rate. enable_turn_detection: bool enable turn detection turn_detection_threshold: float turn detection threshold, range [-1, 1] In a noisy environment, it may be necessary to increase the threshold to reduce false detections # noqa: E501 # pylint: disable=line-too-long In a quiet environment, it may be necessary to decrease the threshold to improve sensitivity # noqa: E501 # pylint: disable=line-too-long turn_detection_silence_duration_ms: int duration of silence in milliseconds to detect turn, range [200, 6000] # noqa: E501 translation_params: TranslationParams translation params, include language. Only effective with qwen3-livetranslate-flash-realtime model or # noqa: E501 # pylint: disable=line-too-long further models. Do not set this parameter for other models. transcription_params: TranscriptionParams transcription params, include language, sample_rate, input_audio_format, corpus. # noqa: E501 # pylint: disable=line-too-long Only effective with qwen3-asr-flash-realtime model or further models. Do not set this parameter for other models. input_audio_config: AudioFormatConfig input(uplink) audio format config. Supports separate format type (pcm/wav) and sample rate (8000/16000/24000/48000), as well as free extension parameters via extra_params. When provided, the request emits the session.audio.input.format structure. output_audio_config: AudioFormatConfig output(downlink) audio format config. Supports separate format type (pcm/wav) and sample rate (8000/16000/24000/48000), as well as free extension parameters via extra_params. When provided, the request emits the session.audio.output.format structure. input_video_representation_compact: str input video representation compact setting. When provided, the request emits session.video.input.representation_compact and passes the string value through without client-side validation.

Notes

Once either input_audio_config or output_audio_config is provided, the legacy top-level input_audio_format / output_audio_format fields are not sent; an unspecified side falls back to the server-side default. The top-level format fields from transcription_params are also skipped in this case.

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
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
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
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
def update_session(
    self,
    output_modalities: List[MultiModality],
    voice: str = None,
    input_audio_format: AudioFormat = AudioFormat.PCM_16000HZ_MONO_16BIT,
    output_audio_format: AudioFormat = AudioFormat.PCM_24000HZ_MONO_16BIT,
    enable_input_audio_transcription: bool = True,
    input_audio_transcription_model: str = None,
    enable_turn_detection: bool = True,
    turn_detection_type: str = "server_vad",
    prefix_padding_ms: int = 300,
    turn_detection_threshold: float = 0.2,
    turn_detection_silence_duration_ms: int = 800,
    turn_detection_param: dict = None,
    translation_params: TranslationParams = None,
    transcription_params: TranscriptionParams = None,
    input_audio_config: AudioFormatConfig = None,
    output_audio_config: AudioFormatConfig = None,
    input_video_representation_compact: str = None,
    **kwargs,
) -> None:
    """
    update session configuration, should be used before create response

    Parameters
    ----------
    output_modalities: list[MultiModality]
        omni output modalities to be used in session
    voice: str
        voice to be used in session
    input_audio_format: AudioFormat
        input audio format. Legacy parameter, kept for backward
        compatibility and still the default path. Prefer
        ``input_audio_config`` which supports separate audio format
        type and sample rate.
    output_audio_format: AudioFormat
        output audio format. Legacy parameter, kept for backward
        compatibility and still the default path. Prefer
        ``output_audio_config`` which supports separate audio format
        type and sample rate.
    enable_turn_detection: bool
        enable turn detection
    turn_detection_threshold: float
        turn detection threshold, range [-1, 1]
        In a noisy environment, it may be necessary to increase the threshold to reduce false detections  # noqa: E501  # pylint: disable=line-too-long
        In a quiet environment, it may be necessary to decrease the threshold to improve sensitivity  # noqa: E501  # pylint: disable=line-too-long
    turn_detection_silence_duration_ms: int
        duration of silence in milliseconds to detect turn, range [200, 6000]  # noqa: E501
    translation_params: TranslationParams
        translation params, include language. Only effective with qwen3-livetranslate-flash-realtime model or  # noqa: E501  # pylint: disable=line-too-long
         further models. Do not set this parameter for other models.
    transcription_params: TranscriptionParams
        transcription params, include language, sample_rate, input_audio_format, corpus.  # noqa: E501  # pylint: disable=line-too-long
        Only effective with qwen3-asr-flash-realtime model or
        further models. Do not set this parameter for other models.
    input_audio_config: AudioFormatConfig
        input(uplink) audio format config. Supports separate format type
        (pcm/wav) and sample rate (8000/16000/24000/48000), as well as
        free extension parameters via ``extra_params``. When provided,
        the request emits the ``session.audio.input.format`` structure.
    output_audio_config: AudioFormatConfig
        output(downlink) audio format config. Supports separate format
        type (pcm/wav) and sample rate (8000/16000/24000/48000), as well
        as free extension parameters via ``extra_params``. When provided,
        the request emits the ``session.audio.output.format`` structure.
    input_video_representation_compact: str
        input video representation compact setting. When provided, the
        request emits ``session.video.input.representation_compact`` and
        passes the string value through without client-side validation.

    Notes
    -----
    Once either ``input_audio_config`` or ``output_audio_config`` is
    provided, the legacy top-level ``input_audio_format`` /
    ``output_audio_format`` fields are not sent; an unspecified side
    falls back to the server-side default. The top-level format fields
    from ``transcription_params`` are also skipped in this case.
    """
    self.config = {
        "modalities": [m.value for m in output_modalities],
        "voice": voice,
    }
    self._apply_audio_format(
        input_audio_format,
        output_audio_format,
        input_audio_config,
        output_audio_config,
    )
    if enable_input_audio_transcription:
        self.config["input_audio_transcription"] = {
            "model": input_audio_transcription_model,
        }
    else:
        self.config["input_audio_transcription"] = None
    if enable_turn_detection:
        self.config["turn_detection"] = {
            "type": turn_detection_type,
            "threshold": turn_detection_threshold,
            "prefix_padding_ms": prefix_padding_ms,
            "silence_duration_ms": turn_detection_silence_duration_ms,
        }
        if turn_detection_param is not None:
            self.config["turn_detection"].update(turn_detection_param)
    else:
        self.config["turn_detection"] = None
    if translation_params is not None:
        self.config["translation"] = {
            "language": translation_params.language,
        }
        if translation_params.corpus is not None:
            if (
                translation_params.corpus
                and translation_params.corpus.phrases is not None
            ):
                self.config["translation"]["corpus"] = {
                    "phrases": translation_params.corpus.phrases,
                }
    if transcription_params is not None:
        self._apply_transcription_params(transcription_params)
    if input_video_representation_compact is not None:
        self.config["video"] = {
            "input": {
                "representation_compact": input_video_representation_compact,
            },
        }
    self.config.update(kwargs)
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "session.update",
                "session": self.config,
            },
        ),
    )

end_session

end_session(timeout: int = 20) -> None

end session

Parameters:

timeout: int Timeout in seconds to wait for the session to end. Default is 20 seconds. # noqa: E501

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
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
def end_session(self, timeout: int = 20) -> None:
    """
    end session

    Parameters:
    -----------
    timeout: int
        Timeout in seconds to wait for the session to end. Default is 20 seconds.  # noqa: E501
    """
    if self.disconnect_event is not None:
        # if the event is already set, do nothing
        return

    # create the event
    self.disconnect_event = threading.Event()
    self._disconnect_error = None

    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "session.finish",
            },
        ),
    )

    # wait for the event to be set
    finish_success = self.disconnect_event.wait(timeout)
    error = self._disconnect_error
    self.disconnect_event = None
    self._disconnect_error = None

    # if the server returned an error or timed out, close the connection
    if error is not None:
        self.close()
        raise RuntimeError(f"Session ended with error: {error}")
    if not finish_success:
        self.close()
        raise TimeoutError(
            f"Session end timeout after {timeout} seconds",
        )

end_session_async

end_session_async() -> None

end session asynchronously. you need close the connection manually

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
577
578
579
580
581
582
583
584
585
586
587
588
589
def end_session_async(self) -> None:
    """
    end session asynchronously. you need close the connection manually
    """
    # Send end session message
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "session.finish",
            },
        ),
    )

append_audio

append_audio(audio_b64: str) -> None

send audio in base64 format

Parameters

audio_b64: str base64 audio string

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
def append_audio(self, audio_b64: str) -> None:
    """
    send audio in base64 format

    Parameters
    ----------
    audio_b64: str
        base64 audio string
    """
    logger.debug("[omni realtime] append audio: %s", len(audio_b64))
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "input_audio_buffer.append",
                "audio": audio_b64,
            },
        ),
        False,
    )

append_video

append_video(video_b64: str) -> None

send one image frame in video in base64 format

Parameters

video_b64: str base64 image string

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
def append_video(self, video_b64: str) -> None:
    """
    send one image frame in video in base64 format

    Parameters
    ----------
    video_b64: str
        base64 image string
    """
    logger.debug("[omni realtime] append video: %s", len(video_b64))
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "input_image_buffer.append",
                "image": video_b64,
            },
        ),
        False,
    )

commit

commit() -> None

Commit the audio and video sent before. When in Server VAD mode, the client does not need to use this method, the server will commit the audio automatically after detecting vad end.

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def commit(self) -> None:
    """
    Commit the audio and video sent before.
    When in Server VAD mode, the client does not need to use this method,
    the server will commit the audio automatically after detecting vad end.
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "input_audio_buffer.commit",
            },
        ),
    )

clear_appended_audio

clear_appended_audio() -> None

clear the audio sent to server before.

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
648
649
650
651
652
653
654
655
656
657
658
659
def clear_appended_audio(self) -> None:
    """
    clear the audio sent to server before.
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "input_audio_buffer.clear",
            },
        ),
    )

create_response

create_response(
    instructions: str = None,
    output_modalities: List[MultiModality] = None,
) -> None

create response, use audio and video commited before to request llm. When in Server VAD mode, the client does not need to use this method, the server will create response automatically after detecting vad and sending commit.

Parameters

instructions: str instructions to llm output_modalities: list[MultiModality] omni output modalities to be used in session

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
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
def create_response(
    self,
    instructions: str = None,
    output_modalities: List[MultiModality] = None,
) -> None:
    """
    create response, use audio and video commited before to request llm.
    When in Server VAD mode, the client does not need to use this method,
    the server will create response automatically after detecting vad
    and sending commit.

    Parameters
    ----------
    instructions: str
        instructions to llm
    output_modalities: list[MultiModality]
        omni output modalities to be used in session
    """
    request = {
        "event_id": self._generate_event_id(),
        "type": "response.create",
        "response": {},
    }
    request["response"]["instructions"] = instructions
    if output_modalities:
        request["response"]["modalities"] = [
            m.value for m in output_modalities
        ]
    self.__send_str(json.dumps(request))

cancel_response

cancel_response() -> None

cancel the current response

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
691
692
693
694
695
696
697
698
699
700
701
702
def cancel_response(self) -> None:
    """
    cancel the current response
    """
    self.__send_str(
        json.dumps(
            {
                "event_id": self._generate_event_id(),
                "type": "response.cancel",
            },
        ),
    )

send_raw

send_raw(raw_data: str) -> None

send raw data to server

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
704
705
706
707
708
def send_raw(self, raw_data: str) -> None:
    """
    send raw data to server
    """
    self.__send_str(raw_data)

close

close() -> None

close the connection to server

Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
710
711
712
713
714
def close(self) -> None:
    """
    close the connection to server
    """
    self.ws.close()

get_session_id

get_session_id() -> str
Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
811
812
def get_session_id(self) -> str:
    return self.session_id  # type: ignore[return-value]

get_last_message

get_last_message() -> str
Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
814
815
def get_last_message(self) -> str:
    return self.last_message  # type: ignore[return-value]

get_last_response_id

get_last_response_id() -> str
Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
817
818
def get_last_response_id(self) -> str:
    return self.last_response_id  # type: ignore[return-value]

get_last_first_text_delay

get_last_first_text_delay()
Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
820
821
def get_last_first_text_delay(self):
    return self.last_first_text_delay

get_last_first_audio_delay

get_last_first_audio_delay()
Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
823
824
def get_last_first_audio_delay(self):
    return self.last_first_audio_delay

OmniRealtimeCallback

An interface that defines callback methods for getting omni-realtime results. # noqa E501 Derive from this class and implement its function to provide your own data.

on_open

on_open() -> None
Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
26
27
def on_open(self) -> None:
    pass

on_close

on_close(close_status_code, close_msg) -> None
Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
29
30
def on_close(self, close_status_code, close_msg) -> None:
    pass

on_event

on_event(message: str) -> None
Source code in dashscope/legacy_1x/audio/qwen_omni/omni_realtime.py
32
33
def on_event(self, message: str) -> None:
    pass

Files & models (1.x)

Files

Bases: FileUploadMixin, ListMixin, DeleteMixin, GetMixin

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'files'

upload classmethod

upload(
    file_path: str,
    purpose: str = FilePurpose.fine_tune,
    description: Optional[str] = None,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Upload file for model fine-tune or other tasks.

Parameters:

Name Type Description Default
file_path str

The local file name to upload.

required
purpose str

The purpose of the file[fine-tune|inference]

fine_tune
description str

The file description message.

None
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The upload information

Source code in dashscope/legacy_1x/files.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@classmethod
def upload(  # pylint: disable=arguments-renamed
    cls,
    file_path: str,  # type: ignore[override]
    purpose: str = FilePurpose.fine_tune,  # type: ignore[override]
    description: Optional[str] = None,  # type: ignore[override]
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Upload file for model fine-tune or other tasks.

    Args:
        file_path (str): The local file name to upload.
        purpose (str): The purpose of the file[fine-tune|inference]
        description (str, optional): The file description message.
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The upload information
    """
    if purpose == FilePurpose.fine_tune:
        if not is_validate_fine_tune_file(file_path):
            raise InvalidFileFormat(
                f"The file {file_path} is not in valid jsonl format",
            )
    with open(file_path, "rb") as f:
        return super().upload(  # type: ignore[return-value]
            files=[
                (
                    "files",
                    (
                        os.path.basename(f.name),
                        f,
                        None,
                    ),
                ),
            ],
            descriptions=[description] if description is not None else [],
            api_key=api_key,
            workspace=workspace,
            **kwargs,
        )

list classmethod

list(
    page=1,
    page_size=10,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

List uploaded files.

Parameters:

Name Type Description Default
api_key str

The api api_key, can be None, if None, will get by default rule(TODO: api key doc).

None
page int

Page number. Defaults to 1.

1
page_size int

Items per page. Defaults to 10.

10
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The fine-tune jobs in the result.

Source code in dashscope/legacy_1x/files.py
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
@classmethod
def list(  # type: ignore[override]
    cls,
    page=1,
    page_size=10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List uploaded files.

    Args:
        api_key (str, optional):
            The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).
        page (int, optional): Page number. Defaults to 1.
        page_size (int, optional): Items per page. Defaults to 10.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The fine-tune jobs in the result.
    """
    return super().list(  # type: ignore[return-value]
        page,
        page_size,
        api_key,
        workspace=workspace,
        **kwargs,
    )

get classmethod

get(
    file_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Get the file info.

Parameters:

Name Type Description Default
file_id str

The file id.

required
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The job info

Source code in dashscope/legacy_1x/files.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@classmethod
def get(  # type: ignore[override]
    cls,
    file_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Get the file info.

    Args:
        file_id (str): The file id.
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The job info
    """
    # type: ignore
    return super().get(file_id, api_key, workspace=workspace, **kwargs)  # type: ignore[return-value] # pylint: disable=line-too-long # noqa: E501

delete classmethod

delete(
    file_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> DashScopeAPIResponse

Delete uploaded file.

Parameters:

Name Type Description Default
file_id str

The file id want to delete.

required
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

Delete result.

Source code in dashscope/legacy_1x/files.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
@classmethod
def delete(  # type: ignore[override]
    cls,
    file_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Delete uploaded file.

    Args:
        file_id (str): The file id want to delete.
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: Delete result.
    """  # type: ignore
    return super().delete(file_id, api_key, workspace=workspace, **kwargs)  # type: ignore[return-value] # pylint: disable=line-too-long # noqa: E501

Models

Bases: ListMixin, GetMixin

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'models'

get classmethod

get(
    name: str, api_key: str = None, **kwargs
) -> DashScopeAPIResponse

Get the model information.

Parameters:

Name Type Description Default
name str

The model name.

required
api_key str

The api key. Defaults to None.

None
**kwargs Any

workspace (str): The dashscope workspace id.

{}

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The model information.

Source code in dashscope/legacy_1x/models.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
@classmethod
def get(  # type: ignore[override]
    cls,
    name: str,
    api_key: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Get the model information.

    Args:
        name (str): The model name.
        api_key (str, optional): The api key. Defaults to None.
        **kwargs (Any):
            workspace (str): The dashscope workspace id.

    Returns:
        DashScopeAPIResponse: The model information.
    """
    from http import HTTPStatus

    # Use query parameter to filter by model name on server side
    # API endpoint: /api/v1/models?model={name}&page_no=1&page_size=1
    url = join_url(dashscope.base_http_api_url, cls.SUB_PATH.lower())
    params = {"model": name, "page_no": 1, "page_size": 1}

    response = _get(
        url,
        params=params,
        api_key=api_key,
        module=get_api_module(cls.__module__),
        **kwargs,
    )

    if response.status_code != HTTPStatus.OK:
        return response  # type: ignore[return-value]

    output = response.output
    if not output or "models" not in output or not output["models"]:
        response.status_code = 404
        response.message = f"Model '{name}' not found"
        response.output = None
        return response  # type: ignore[return-value]

    # Return the first (and only) model from the filtered list
    response.output = output["models"][0]
    return response  # type: ignore[return-value]

list classmethod

list(
    page=1, page_size=10, api_key: str = None, **kwargs
) -> DashScopeAPIResponse

List models.

Parameters:

Name Type Description Default
api_key str

The api key

None
page int

Page number. Defaults to 1.

1
page_size int

Items per page. Defaults to 10.

10

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The models.

Source code in dashscope/legacy_1x/models.py
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@classmethod
def list(  # type: ignore[override]
    cls,
    page=1,
    page_size=10,
    api_key: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """List models.

    Args:
        api_key (str, optional): The api key
        page (int, optional): Page number. Defaults to 1.
        page_size (int, optional): Items per page. Defaults to 10.

    Returns:
        DashScopeAPIResponse: The models.
    """
    # type: ignore
    return super().list(page, page_size, api_key=api_key, **kwargs)  # type: ignore[return-value] # pylint: disable=line-too-long # noqa: E501

Fine-tuning & deployments (1.x)

FineTunes

Bases: CreateMixin, CancelMixin, DeleteMixin, ListMixin, GetStatusMixin, StreamEventMixin, LogMixin

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'fine-tunes'

call classmethod

call(
    model: str,
    training_file_ids: Union[list, str],
    validation_file_ids: Union[list, str] | None = None,
    mode: str | None = None,
    hyper_parameters: dict | None = {},
    api_key: str = None,
    workspace: str = None,
    **kwargs: Any
) -> Any

Create fine-tune job

Parameters:

Name Type Description Default
model str

The model to be fine-tuned

required
training_file_ids (list, str)

Ids of the fine-tune training data, which can be pre-uploaded using the File API.

required
validation_file_ids [list, str]

Ids of the fine-tune validating data, which can be pre-uploaded using the File API.

None
mode str

The fine-tune mode, sft or efficient_sft.

None
hyper_parameters dict

The fine-tune hyper parameters. Defaults to empty.

{}
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
FineTune Any

The request result.

Source code in dashscope/legacy_1x/finetune/finetunes.py
38
39
40
41
42
43
44
45
46
47
48
49
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
@classmethod
# type: ignore[override]
# pylint: disable=arguments-renamed,dangerous-default-value
def call(  # noqa: E501  # type: ignore[override]
    cls,
    model: str,
    training_file_ids: Union[list, str],
    validation_file_ids: Union[list, str] = None,
    mode: Optional[str] = None,
    hyper_parameters: Optional[dict] = {},
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> FineTune:
    """Create fine-tune job

    Args:
        model (str): The model to be fine-tuned
        training_file_ids (list, str): Ids of the fine-tune training data,
            which can be pre-uploaded using the File API.
        validation_file_ids ([list,str], optional): Ids of the fine-tune
            validating data, which can be pre-uploaded using the File API.
        mode (str): The fine-tune mode, sft or efficient_sft.
        hyper_parameters (dict, optional): The fine-tune hyper parameters.
            Defaults to empty.
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        FineTune: The request result.
    """
    if isinstance(training_file_ids, str):
        training_file_ids = [training_file_ids]
    if validation_file_ids and isinstance(validation_file_ids, str):
        validation_file_ids = [validation_file_ids]
    request = {
        "model": model,
        "training_file_ids": training_file_ids,
        "validation_file_ids": validation_file_ids,
        "hyper_parameters": hyper_parameters if hyper_parameters else {},
    }
    if mode is not None:
        request["training_type"] = mode
    if "finetuned_output" in kwargs:
        request["finetuned_output"] = kwargs["finetuned_output"]
    resp = super().call(
        request,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return FineTune(**resp)

cancel classmethod

cancel(
    job_id: str,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> Any

Cancel a running fine-tune job.

Parameters:

Name Type Description Default
job_id str

The fine-tune job id.

required
api_key str

The api api_key, can be None, if None, will get by default rule(TODO: api key doc).

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
FineTune Any

The request result.

Source code in dashscope/legacy_1x/finetune/finetunes.py
 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
@classmethod
def cancel(  # type: ignore[override]
    cls,
    job_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> FineTuneCancel:
    """Cancel a running fine-tune job.

    Args:
        job_id (str): The fine-tune job id.
        api_key (str, optional): The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).
        workspace (str): The dashscope workspace id.

    Returns:
        FineTune: The request result.
    """
    rsp = super().cancel(
        job_id,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return FineTuneCancel(**rsp)

list classmethod

list(
    page_no: int = 1,
    page_size: int = 10,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> Any

List fine-tune job.

Parameters:

Name Type Description Default
api_key str

The api key

None
page_no int

Page number. Defaults to 1.

1
page_size int

Items per page. Defaults to 10.

10
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
FineTune Any

The fine-tune jobs in the result.

Source code in dashscope/legacy_1x/finetune/finetunes.py
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
144
145
@classmethod
def list(  # type: ignore[override]
    cls,
    page_no=1,
    page_size=10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> FineTuneList:
    """List fine-tune job.

    Args:
        api_key (str, optional): The api key
        page_no (int, optional): Page number. Defaults to 1.
        page_size (int, optional): Items per page. Defaults to 10.
        workspace (str): The dashscope workspace id.

    Returns:
        FineTune: The fine-tune jobs in the result.
    """
    response = super().list(
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return FineTuneList(**response)

get classmethod

get(
    job_id: str,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> Any

Get fine-tune job information.

Parameters:

Name Type Description Default
job_id str

The fine-tune job id

required
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
FineTune Any

The job info

Source code in dashscope/legacy_1x/finetune/finetunes.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@classmethod
def get(  # type: ignore[override]
    cls,
    job_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> FineTune:
    """Get fine-tune job information.

    Args:
        job_id (str): The fine-tune job id
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        FineTune: The job info
    """
    response = super().get(
        job_id,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return FineTune(**response)

delete classmethod

delete(
    job_id: str,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> Any

Delete a fine-tune job.

Parameters:

Name Type Description Default
job_id str

The fine-tune job id.

required
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
FineTune Any

The delete result.

Source code in dashscope/legacy_1x/finetune/finetunes.py
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
@classmethod
def delete(  # type: ignore[override]
    cls,
    job_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> FineTuneDelete:
    """Delete a fine-tune job.

    Args:
        job_id (str): The fine-tune job id.
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        FineTune: The delete result.
    """
    rsp = super().delete(
        job_id,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return FineTuneDelete(**rsp)

stream_events classmethod

stream_events(
    job_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> Iterator[FineTuneEvent]

Get fine-tune job events.

Parameters:

Name Type Description Default
job_id str

The fine-tune job id

required
api_key str

the api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
FineTune Iterator[FineTuneEvent]

The job log events.

Source code in dashscope/legacy_1x/finetune/finetunes.py
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
@classmethod
def stream_events(  # type: ignore[override] # pylint: disable=arguments-renamed  # noqa: E501
    # type: ignore[override]
    cls,
    job_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> Iterator[FineTuneEvent]:
    """Get fine-tune job events.

    Args:
        job_id (str): The fine-tune job id
        api_key (str, optional): the api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        FineTune: The job log events.
    """
    responses = super().stream_events(
        job_id,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    for rsp in responses:
        yield FineTuneEvent(**rsp)

logs classmethod

logs(
    job_id: str,
    *,
    offset: int = 1,
    line: int = 1000,
    api_key: str = None,
    workspace: str = None,
    **kwargs
) -> FineTune

Get log of the job.

Parameters:

Name Type Description Default
job_id str

The job id(used for fine-tune)

required
offset int

start log line. Defaults to 1.

1
line int

total line return. Defaults to 1000.

1000
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
FineTune FineTune

The response

Source code in dashscope/legacy_1x/finetune/finetunes.py
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
@classmethod
def logs(  # type: ignore[override]
    cls,
    job_id: str,
    *,
    offset: int = 1,
    line: int = 1000,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> FineTune:
    """Get log of the job.

    Args:
        job_id (str): The job id(used for fine-tune)
        offset (int, optional): start log line. Defaults to 1.
        line (int, optional): total line return. Defaults to 1000.
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        FineTune: The response
    """
    return super().logs(  # type: ignore[return-value]
        job_id,
        offset=offset,
        line=line,
        workspace=workspace,
        api_key=api_key,
        **kwargs,
    )

wait classmethod

wait(
    job_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs
)
Source code in dashscope/legacy_1x/finetune/finetunes.py
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
@classmethod
def wait(
    cls,
    job_id: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
):
    try:
        while True:
            rsp = FineTunes.get(
                job_id,
                api_key=api_key,
                workspace=workspace,
                **kwargs,
            )
            if rsp.status_code == HTTPStatus.OK:
                if rsp.output["status"] in [
                    TaskStatus.FAILED,
                    TaskStatus.CANCELED,
                    TaskStatus.SUCCEEDED,
                ]:
                    return rsp
                else:
                    time.sleep(30)
            else:
                return rsp
    except Exception:
        # pylint: disable=broad-exception-raised,raise-missing-from
        raise Exception(
            f"You can stream output via: dashscope fine_tunes.stream -j "
            f"{job_id}",
        )

Deployments

Bases: CreateMixin, DeleteMixin, ListMixin, GetMixin, StreamEventMixin, PutMixin

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'deployments'

Deploy a model.

call classmethod

call(
    model: str,
    capacity: int,
    version: str = None,
    suffix: str | None = None,
    plan: Optional[str] = None,
    template_id: Optional[str] = None,
    api_key: str | None = None,
    workspace: str = None,
    **kwargs: Any
) -> Any

Call to deployment a model service.

Parameters:

Name Type Description Default
model str

The model name.

required
capacity int

The model service capacity.

required
version str

The model version, unnecessary for fine-tuned model. Defaults to None.

None
suffix str

The name suffix of the model deployment, If specified, the final model name will be model_suffix. Defaults to None.

None
plan str

The deployment plan required by the service: "ptu" (PTU reserved), "mu" (model unit) or "Lora" (LoRA deployment). Defaults to None.

None
template_id str

Template ID for deployment configuration. Defaults to None.

None
api_key str

The api-key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
Deployment Any

description

Source code in dashscope/legacy_1x/finetune/deployments.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
@classmethod
# type: ignore[override]
def call(  # pylint: disable=arguments-renamed  # type: ignore[override]
    cls,
    model: str,
    capacity: int,
    version: str = None,
    suffix: Optional[str] = None,
    plan: Optional[str] = None,
    template_id: Optional[str] = None,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> Deployment:
    """Call to deployment a model service.

    Args:
        model (str): The model name.
        capacity (int): The model service capacity.
        version (str, optional): The model version, unnecessary
            for fine-tuned model. Defaults to None.
        suffix (str, optional): The name suffix of the model deployment,
            If specified, the final model name will be model_suffix.
            Defaults to None.
        plan (str, optional): The deployment plan required by the
            service: "ptu" (PTU reserved), "mu" (model unit) or
            "Lora" (LoRA deployment). Defaults to None.
        template_id (str, optional): Template ID for deployment
            configuration. Defaults to None.
        api_key (str, optional): The api-key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        Deployment: _description_
    """
    req = {"model_name": model, "capacity": capacity}

    if version is not None:
        req["model_version"] = version
    if suffix is not None:
        req["suffix"] = suffix
    if plan is not None:
        req["plan"] = plan
    if template_id is not None:
        req["template_id"] = template_id
    response = super().call(
        req,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return Deployment(**response)

list classmethod

list(
    page_no: int = 1,
    page_size: int = 10,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> Any

List deployments.

Parameters:

Name Type Description Default
api_key str

The api api_key, if not present, will get by default rule(TODO: api key doc). Defaults to None.

None
page_no int

Page number. Defaults to 1.

1
page_size int

Items per page. Defaults to 10.

10
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
Deployment Any

The deployment list.

Source code in dashscope/legacy_1x/finetune/deployments.py
 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
@classmethod
def list(  # type: ignore[override]
    cls,
    page_no=1,
    page_size=10,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DeploymentList:
    """List deployments.

    Args:
        api_key (str, optional): The api api_key, if not present,
            will get by default rule(TODO: api key doc). Defaults to None.
        page_no (int, optional): Page number. Defaults to 1.
        page_size (int, optional): Items per page. Defaults to 10.
        workspace (str): The dashscope workspace id.

    Returns:
        Deployment: The deployment list.
    """
    response = super().list(
        page_no=page_no,
        page_size=page_size,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return DeploymentList(**response)

get classmethod

get(
    deployed_model: str,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> Any

Get model deployment information.

Parameters:

Name Type Description Default
deployed_model str

The deployment_id.

required
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
Deployment Any

The deployment information.

Source code in dashscope/legacy_1x/finetune/deployments.py
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
@classmethod
def get(  # type: ignore[override]
    cls,
    deployed_model: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> Deployment:
    """Get model deployment information.

    Args:
        deployed_model (str): The deployment_id.
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        Deployment: The deployment information.
    """
    response = super().get(
        deployed_model,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return Deployment(**response)

delete classmethod

delete(
    deployed_model: str,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> Any

Delete model deployment.

Parameters:

Name Type Description Default
deployed_model str

The deployment id.

required
api_key str

The api key. Defaults to None.

None
workspace str

The dashscope workspace id.

None

Returns:

Name Type Description
Deployment Any

The delete result.

Source code in dashscope/legacy_1x/finetune/deployments.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@classmethod
def delete(  # type: ignore[override]
    cls,
    deployed_model: str,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> DeploymentDelete:
    """Delete model deployment.

    Args:
        deployed_model (str): The deployment id.
        api_key (str, optional): The api key. Defaults to None.
        workspace (str): The dashscope workspace id.

    Returns:
        Deployment: The delete result.
    """
    response = super().delete(
        deployed_model,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return DeploymentDelete(**response)

scale classmethod

scale(
    deployed_model: str,
    capacity: int,
    api_key: str | None = None,
    workspace: str | None = None,
    **kwargs: Any
) -> Any

Scaling model deployment.

Parameters:

Name Type Description Default
deployed_model str

The deployed model id.

required
capacity int

The target service capacity.

required
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
Deployment Any

The delete result.

Source code in dashscope/legacy_1x/finetune/deployments.py
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
@classmethod
def scale(
    cls,
    deployed_model: str,
    capacity: int,
    api_key: str = None,
    workspace: str = None,
    **kwargs,
) -> Deployment:
    """Scaling model deployment.

    Args:
        deployed_model (str): The deployed model id.
        capacity (int): The target service capacity.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        Deployment: The delete result.
    """
    req = {"deployed_model": deployed_model, "capacity": capacity}
    path = f"{cls.SUB_PATH.lower()}/{deployed_model}/scale"
    response = super().put(
        deployed_model,
        req,
        path=path,
        api_key=api_key,
        workspace=workspace,
        **kwargs,
    )
    return Deployment(**response)

Tokenizers

Tokenization

Bases: BaseApi

FUNCTION class-attribute instance-attribute

FUNCTION = 'tokenizer'

API for get tokenizer result..

Models

List of models currently supported

qwen_turbo class-attribute instance-attribute
qwen_turbo = 'qwen-turbo'
qwen_plus class-attribute instance-attribute
qwen_plus = 'qwen-plus'
qwen_7b_chat class-attribute instance-attribute
qwen_7b_chat = 'qwen-7b-chat'
qwen_14b_chat class-attribute instance-attribute
qwen_14b_chat = 'qwen-14b-chat'
llama2_7b_chat_v2 class-attribute instance-attribute
llama2_7b_chat_v2 = 'llama2-7b-chat-v2'
llama2_13b_chat_v2 class-attribute instance-attribute
llama2_13b_chat_v2 = 'llama2-13b-chat-v2'
text_embedding_v2 class-attribute instance-attribute
text_embedding_v2 = 'text-embedding-v2'
qwen_72b_chat class-attribute instance-attribute
qwen_72b_chat = 'qwen-72b-chat'

call classmethod

call(
    model: str,
    input: Any = None,
    prompt: Any = None,
    history: list = None,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs: Any
) -> DashScopeAPIResponse

Call tokenization.

Parameters:

Name Type Description Default
model str

The requested model, such as qwen-v1

required
input Any

(Any): The model input body.

None
prompt Any

The input prompt, for qwen serial model.

None
history list

The user provided history, deprecated, use messages instead. examples: [{'user':'The weather is fine today.', 'bot': 'Suitable for outings'}]. Defaults to None.

None
api_key str

The api api_key, can be None, if None, will get by default rule(TODO: api key doc).

None
messages list

The generation messages. examples: [{'role': 'user', 'content': 'The weather is fine today.'}, {'role': 'assistant', 'content': 'Suitable for outings'}]

None
workspace str

The dashscope workspace id.

None
**kwargs Any

see model input.

{}

Raises:

Type Description
InputRequired

input is required.

ModelRequired

model is required.

Returns:

Name Type Description
DashScopeAPIResponse DashScopeAPIResponse

The tokenizer output.

Source code in dashscope/legacy_1x/tokenizers/tokenization.py
 42
 43
 44
 45
 46
 47
 48
 49
 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
121
122
@classmethod
# type: ignore[override]
def call(  # pylint: disable=arguments-renamed # noqa: E501
    cls,
    model: str,
    input: Any = None,  # pylint: disable=redefined-builtin
    prompt: Any = None,
    history: list = None,
    api_key: str = None,
    messages: List[Message] = None,
    workspace: str = None,
    **kwargs,
) -> DashScopeAPIResponse:
    """Call tokenization.

    Args:
        model (str): The requested model, such as qwen-v1
        input: (Any): The model input body.
        prompt (Any): The input prompt, for qwen serial model.
        history (list):The user provided history,
            deprecated, use messages instead.
            examples:
                [{'user':'The weather is fine today.',
                'bot': 'Suitable for outings'}].
            Defaults to None.
        api_key (str, optional): The api api_key, can be None,
            if None, will get by default rule(TODO: api key doc).
        messages (list): The generation messages.
            examples:
                [{'role': 'user',
                  'content': 'The weather is fine today.'},
                  {'role': 'assistant', 'content': 'Suitable for outings'}]
        workspace (str): The dashscope workspace id.
        **kwargs:
            see model input.

    Raises:
        InputRequired: input is required.
        ModelRequired: model is required.

    Returns:
        DashScopeAPIResponse: The tokenizer output.
    """
    if (  # pylint: disable=too-many-boolean-expressions
        (input is None or not input)
        and (prompt is None or not prompt)
        and (messages is None or not messages)
    ):
        raise InputRequired("prompt or messages is required!")
    if model is None or not model:
        raise ModelRequired("Model is required!")
    if input is None:
        # Extract model-specific parameters
        enable_search = kwargs.pop("enable_search", False)
        customized_model_id = kwargs.pop("customized_model_id", None)

        input, parameters = cls._build_llm_parameters(
            model,
            prompt,
            history,
            messages,
            enable_search=enable_search,
            customized_model_id=customized_model_id,
            **kwargs,
        )
    else:
        parameters = kwargs

    if kwargs.pop("stream", False):  # not support stream
        logger.warning("streaming option not supported for tokenization.")

    return super().call(
        model=model,
        task_group=None,  # type: ignore[arg-type]
        function=cls.FUNCTION,
        api_key=api_key,
        input=input,
        is_service=False,
        workspace=workspace,
        **parameters,
    )

Tokenizer

Tokenizer()

Base tokenizer interface for local tokenizers.

Source code in dashscope/legacy_1x/tokenizers/tokenizer_base.py
10
11
def __init__(self):
    pass

encode

encode(text: str, **kwargs: Any) -> List[int]

Encode input text string to token ids.

Parameters:

Name Type Description Default
text str

The string to be encoded.

required

Returns:

Type Description
List[int]

List[int]: The token ids.

Source code in dashscope/legacy_1x/tokenizers/tokenizer_base.py
13
14
15
16
17
18
19
20
21
def encode(self, text: str, **kwargs) -> List[int]:  # type: ignore[empty-body] # noqa: E501
    """Encode input text string to token ids.

    Args:
        text (str): The string to be encoded.

    Returns:
        List[int]: The token ids.
    """

decode

decode(token_ids: List[int], **kwargs: Any) -> str

Decode token ids to string.

Parameters:

Name Type Description Default
token_ids List[int]

The input token ids.

required

Returns:

Name Type Description
str str

The string of the token ids.

Source code in dashscope/legacy_1x/tokenizers/tokenizer_base.py
23
24
25
26
27
28
29
30
31
def decode(self, token_ids: List[int], **kwargs) -> str:  # type: ignore[empty-body] # pylint: disable=line-too-long # noqa: E501
    """Decode token ids to string.

    Args:
        token_ids (List[int]): The input token ids.

    Returns:
        str: The string of the token ids.
    """

get_tokenizer

get_tokenizer(model: str) -> Tokenizer

Get a tokenizer based on model name.

The vocab file is downloaded on first use from ModelScope into ~/.cache/dashscope/tokenizers. Set DASHSCOPE_QWEN_VOCAB to a local file path for offline use.

Parameters:

Name Type Description Default
model str

The model name.

required

Raises:

Type Description
UnsupportedModel

Not support model

Returns:

Name Type Description
Tokenizer Tokenizer

The Tokenizer of the model.

Source code in dashscope/legacy_1x/tokenizers/tokenizer.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def get_tokenizer(model: str) -> Tokenizer:
    """Get a tokenizer based on model name.

    The vocab file is downloaded on first use from ModelScope into
    ``~/.cache/dashscope/tokenizers``.
    Set ``DASHSCOPE_QWEN_VOCAB`` to a local file path for offline use.

    Args:
        model (str): The model name.

    Raises:
        UnsupportedModel: Not support model

    Returns:
        Tokenizer: The  `Tokenizer` of the model.
    """
    if model.startswith("qwen"):
        return QwenTokenizer(_resolve_vocab_path())
    raise UnsupportedModel(
        f"Not support model: {model}, currently only support qwen models.",
    )

list_tokenizers

list_tokenizers() -> List[str]

List support models

Returns:

Type Description
List[str]

List[str]: The model list.

Source code in dashscope/legacy_1x/tokenizers/tokenizer.py
109
110
111
112
113
114
115
def list_tokenizers() -> List[str]:
    """List support models

    Returns:
        List[str]: The model list.
    """
    return QWEN_SERIALS

Assistants & Threads (deprecated)

The Assistants API is deprecated; accessing these names emits a DeprecationWarning.

Assistants

Bases: CreateMixin, CancelMixin, DeleteMixin, ListObjectMixin, GetStatusMixin, UpdateMixin

.. deprecated:: The Assistants API is deprecated and will be removed in a future release. Please migrate to the Responses API. See https://help.aliyun.com/zh/model-studio/ synchronous-call-api-reference for migration details.

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'assistants'

call classmethod

call(
    *,
    model: str,
    name: str = None,
    description: str = None,
    instructions: str = None,
    tools: Optional[List[Dict]] = None,
    file_ids: Optional[List[str]] = [],
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Assistant

Create Assistant.

Parameters:

Name Type Description Default
model str

The model to use.

required
name str

The assistant name. Defaults to None.

None
description str

The assistant description. Defaults to None.

None
instructions str

The system instructions this assistant uses. Defaults to None.

None
tools Optional[List[Dict]]

List of tools to use. Defaults to [].

None
file_ids Optional[List[str]]

: The files to use. Defaults to [].

[]
metadata Dict

Custom key-value pairs associate with assistant. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

The DashScope api key. Defaults to None.

None

Raises:

Type Description
ModelRequired

The model is required.

Returns:

Name Type Description
Assistant Assistant

The Assistant object.

Source code in dashscope/legacy_1x/assistants/assistants.py
 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
144
145
146
147
148
149
150
@classmethod
# pylint: disable=dangerous-default-value
def call(  # type: ignore[override]
    cls,
    *,
    model: str,
    name: str = None,
    description: str = None,
    instructions: str = None,
    tools: Optional[List[Dict]] = None,
    file_ids: Optional[List[str]] = [],
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Assistant:
    """Create Assistant.

    Args:
        model (str): The model to use.
        name (str, optional): The assistant name. Defaults to None.
        description (str, optional):
            The assistant description. Defaults to None.
        instructions (str, optional):
            The system instructions this assistant uses. Defaults to None.
        tools (Optional[List[Dict]], optional):
            List of tools to use. Defaults to [].
        file_ids (Optional[List[str]], optional):
            : The files to use. Defaults to [].
        metadata (Dict, optional):
            Custom key-value pairs associate with assistant. Defaults to
            None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): The DashScope api key. Defaults to None.

    Raises:
        ModelRequired: The model is required.

    Returns:
        Assistant: The `Assistant` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    return cls.create(
        model=model,
        name=name,
        description=description,
        instructions=instructions,
        tools=tools,
        file_ids=file_ids,
        metadata=metadata,
        workspace=workspace,
        api_key=api_key,
        **kwargs,
    )

create classmethod

create(
    *,
    model: str,
    name: str = None,
    description: str = None,
    instructions: str = None,
    tools: Optional[List[Dict]] = None,
    file_ids: Optional[List[str]] = [],
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    temperature: Optional[float] = None,
    max_tokens: Optional[int] = None,
    **kwargs
) -> Assistant

Create Assistant.

Parameters:

Name Type Description Default
model str

The model to use.

required
name str

The assistant name. Defaults to None.

None
description str

The assistant description. Defaults to None.

None
instructions str

The system instructions this assistant uses. Defaults to None.

None
tools Optional[List[Dict]]

List of tools to use. Defaults to [].

None
file_ids Optional[List[str]]

: The files to use. Defaults to [].

[]
metadata Dict

Custom key-value pairs associate with assistant. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

The DashScope api key. Defaults to None.

None
top_p float

top_p parameter for model. Defaults to None.

None
top_k int

top_p parameter for model. Defaults to None.

None
temperature float

temperature parameter for model. Defaults to None.

None
max_tokens int

max_tokens parameter for model. Defaults to None.

None

Raises:

Type Description
ModelRequired

The model is required.

Returns:

Name Type Description
Assistant Assistant

The Assistant object.

Source code in dashscope/legacy_1x/assistants/assistants.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
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
226
227
228
229
230
231
232
@classmethod
# pylint: disable=dangerous-default-value
def create(
    cls,
    *,
    model: str,
    name: str = None,
    description: str = None,
    instructions: str = None,
    tools: Optional[List[Dict]] = None,
    file_ids: Optional[List[str]] = [],
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    temperature: Optional[float] = None,
    max_tokens: Optional[int] = None,
    **kwargs,
) -> Assistant:
    """Create Assistant.

    Args:
        model (str): The model to use.
        name (str, optional): The assistant name. Defaults to None.
        description (str, optional):
            The assistant description. Defaults to None.
        instructions (str, optional):
            The system instructions this assistant uses. Defaults to None.
        tools (Optional[List[Dict]], optional):
            List of tools to use. Defaults to [].
        file_ids (Optional[List[str]], optional):
            : The files to use. Defaults to [].
        metadata (Dict, optional):
            Custom key-value pairs associate with assistant. Defaults to
            None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): The DashScope api key. Defaults to None.
        top_p (float, optional):
            top_p parameter for model. Defaults to None.
        top_k (int, optional): top_p parameter for model. Defaults to None.
        temperature (float, optional):
            temperature parameter for model. Defaults to None.
        max_tokens (int, optional):
            max_tokens parameter for model. Defaults to None.

    Raises:
        ModelRequired: The model is required.

    Returns:
        Assistant: The `Assistant` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not model:
        raise ModelRequired("Model is required!")
    data = cls._create_assistant_object(
        model,
        name,
        description,
        instructions,
        tools,
        file_ids,
        metadata,
        top_p,
        top_k,
        temperature,
        max_tokens,
    )
    response = super().call(
        data=data,
        api_key=api_key,
        flattened_output=True,
        workspace=workspace,
        **kwargs,
    )
    return Assistant(**response)

retrieve classmethod

retrieve(
    assistant_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Assistant

Get the Assistant.

Parameters:

Name Type Description Default
assistant_id str

The assistant id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
Assistant Assistant

The Assistant object.

Source code in dashscope/legacy_1x/assistants/assistants.py
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
@classmethod
def retrieve(
    cls,
    assistant_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Assistant:
    """Get the `Assistant`.

    Args:
        assistant_id (str): The assistant id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        Assistant: The `Assistant` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    return cls.get(
        assistant_id,
        workspace=workspace,
        api_key=api_key,
        **kwargs,
    )

get classmethod

get(
    assistant_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Assistant

Get the Assistant.

Parameters:

Name Type Description Default
assistant_id str

The assistant id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
Assistant Assistant

The Assistant object.

Source code in dashscope/legacy_1x/assistants/assistants.py
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
294
295
296
297
298
@classmethod
def get(  # type: ignore[override]
    cls,
    assistant_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Assistant:
    """Get the `Assistant`.

    Args:
        assistant_id (str): The assistant id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        Assistant: The `Assistant` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not assistant_id:
        raise ModelRequired("assistant_id is required!")
    response = super().get(
        assistant_id,
        workspace=workspace,
        api_key=api_key,
        flattened_output=True,
        **kwargs,
    )
    return Assistant(**response)

list classmethod

list(
    *,
    limit: int = None,
    order: str = None,
    after: str = None,
    before: str = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> AssistantList

List assistants

Parameters:

Name Type Description Default
limit int

How many assistant to retrieve. Defaults to None.

None
order str

Sort order by created_at. Defaults to None.

None
after str

Assistant id after. Defaults to None.

None
before str

Assistant id before. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
AssistantList AssistantList

The list of assistants.

Source code in dashscope/legacy_1x/assistants/assistants.py
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
342
@classmethod
def list(  # type: ignore[override]
    cls,
    *,
    limit: int = None,
    order: str = None,
    after: str = None,
    before: str = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> AssistantList:
    """List assistants

    Args:
        limit (int, optional):
            How many assistant to retrieve. Defaults to None.
        order (str, optional): Sort order by created_at. Defaults to None.
        after (str, optional): Assistant id after. Defaults to None.
        before (str, optional): Assistant id before. Defaults to None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        AssistantList: The list of assistants.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    response = super().list(
        limit=limit,
        order=order,
        after=after,
        before=before,
        workspace=workspace,
        api_key=api_key,
        flattened_output=True,
        **kwargs,
    )
    return AssistantList(**response)

update classmethod

update(
    assistant_id: str,
    *,
    model: str = None,
    name: str = None,
    description: str = None,
    instructions: str = None,
    tools: Optional[List[Dict]] = None,
    file_ids: Optional[List[str]] = [],
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    temperature: Optional[float] = None,
    max_tokens: Optional[int] = None,
    **kwargs
) -> Assistant

Update an exist assistants

Parameters:

Name Type Description Default
assistant_id str

The target assistant id.

required
model str

The model to use.

None
name str

The assistant name. Defaults to None.

None
description str

The assistant description . Defaults to None.

None
instructions str

The system instructions this assistant uses.. Defaults to None. # noqa: E501 # pylint: disable=line-too-long

None
tools Optional[str]

List of tools to use.. Defaults to []. # noqa: E501

None
file_ids Optional[str]

The files to use in assistants.. Defaults to []. # noqa: E501 # pylint: disable=line-too-long

[]
metadata Dict

Custom key-value pairs associate with assistant. Defaults to None.

None
workspace str

The DashScope workspace id.

None
api_key str

The DashScope workspace id. Defaults to None.

None
top_p float

top_p parameter for model. Defaults to None.

None
top_k int

top_p parameter for model. Defaults to None.

None
temperature float

temperature parameter for model. Defaults to None.

None
max_tokens int

max_tokens parameter for model. Defaults to None.

None

Returns:

Name Type Description
Assistant Assistant

The updated assistant.

Source code in dashscope/legacy_1x/assistants/assistants.py
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
386
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
@classmethod
# pylint: disable=dangerous-default-value
def update(  # type: ignore[override]
    cls,
    assistant_id: str,
    *,
    model: str = None,
    name: str = None,
    description: str = None,
    instructions: str = None,
    tools: Optional[List[Dict]] = None,
    file_ids: Optional[List[str]] = [],
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    temperature: Optional[float] = None,
    max_tokens: Optional[int] = None,
    **kwargs,
) -> Assistant:
    """Update an exist assistants

    Args:
        assistant_id (str): The target assistant id.
        model (str): The model to use.
        name (str, optional): The assistant name. Defaults to None.
        description (str, optional):
            The assistant description . Defaults to None.
        instructions (str, optional): The system instructions this assistant uses.. Defaults to None.  # noqa: E501  # pylint: disable=line-too-long
        tools (Optional[str], optional): List of tools to use.. Defaults to [].  # noqa: E501
        file_ids (Optional[str], optional): The files to use in assistants.. Defaults to [].  # noqa: E501  # pylint: disable=line-too-long
        metadata (Dict, optional):
            Custom key-value pairs associate with assistant. Defaults to
            None.
        workspace (str): The DashScope workspace id.
        api_key (str, optional):
            The DashScope workspace id. Defaults to None.
        top_p (float, optional):
            top_p parameter for model. Defaults to None.
        top_k (int, optional): top_p parameter for model. Defaults to None.
        temperature (float, optional):
            temperature parameter for model. Defaults to None.
        max_tokens (int, optional):
            max_tokens parameter for model. Defaults to None.

    Returns:
        Assistant: The updated assistant.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not assistant_id:
        raise ModelRequired("assistant_id is required!")
    response = super().update(
        assistant_id,
        cls._create_assistant_object(
            model,
            name,
            description,
            instructions,
            tools,
            file_ids,
            metadata,
            top_p,
            top_k,
            temperature,
            max_tokens,
        ),
        api_key=api_key,
        workspace=workspace,
        flattened_output=True,
        method="post",
        **kwargs,
    )
    return Assistant(**response)

delete classmethod

delete(
    assistant_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> DeleteResponse

Delete uploaded file.

Parameters:

Name Type Description Default
assistant_id str

The assistant id want to delete.

required
workspace str

The DashScope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
AssistantsDeleteResponse DeleteResponse

Delete result.

Source code in dashscope/legacy_1x/assistants/assistants.py
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
@classmethod
def delete(  # type: ignore[override]
    cls,
    assistant_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> DeleteResponse:
    """Delete uploaded file.

    Args:
        assistant_id (str): The assistant id want to delete.
        workspace (str): The DashScope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        AssistantsDeleteResponse: Delete result.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not assistant_id:
        raise ModelRequired("assistant_id is required!")
    response = super().delete(
        assistant_id,
        api_key=api_key,
        workspace=workspace,
        flattened_output=True,
        **kwargs,
    )
    return DeleteResponse(**response)

Assistant dataclass

Assistant(**kwargs)

Bases: BaseObjectMixin

Source code in dashscope/legacy_1x/assistants/assistant_types.py
135
136
137
def __init__(self, **kwargs):
    self.tools = convert_tools_dict_to_objects(kwargs.pop("tools", []))
    super().__init__(**kwargs)

status_code instance-attribute

status_code: int

The call response status_code, 200 indicate create success.

code instance-attribute

code: str

The request failed, this is the error code.

message instance-attribute

message: str

The request failed, this is the error message.

id instance-attribute

id: str

ID of the assistant.

model instance-attribute

model: str

created_at instance-attribute

created_at: int

The Unix timestamp (in seconds) for when the assistant was created.

file_ids instance-attribute

file_ids: List[str]

name class-attribute instance-attribute

name: Optional[str] = None

description class-attribute instance-attribute

description: Optional[str] = None

instructions class-attribute instance-attribute

instructions: Optional[str] = None

metadata class-attribute instance-attribute

metadata: Optional[object] = None

object class-attribute instance-attribute

object: Optional[str] = None

top_p class-attribute instance-attribute

top_p: Optional[float] = None

top_k class-attribute instance-attribute

top_k: Optional[int] = None

temperature class-attribute instance-attribute

temperature: Optional[float] = None

max_tokens class-attribute instance-attribute

max_tokens: Optional[int] = None

request_id class-attribute instance-attribute

request_id: Optional[str] = None

tools instance-attribute

tools: List[Tool] = convert_tools_dict_to_objects(
    kwargs.pop("tools", [])
)

Threads

Bases: CreateMixin, DeleteMixin, GetStatusMixin, UpdateMixin

.. deprecated:: The Threads API is deprecated and will be removed in a future release. Please migrate to the Responses API. See https://help.aliyun.com/zh/model-studio/ synchronous-call-api-reference for migration details.

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'threads'

call classmethod

call(
    *,
    messages: List[Dict] = None,
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Thread

Create a thread.

Parameters:

Name Type Description Default
messages List[Dict]

List of messages to start thread. Defaults to None.

None
metadata Dict

The key-value information associate with thread. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
Thread Thread

The thread object.

Source code in dashscope/legacy_1x/threads/threads.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@classmethod
def call(  # type: ignore[override]
    cls,
    *,
    messages: List[Dict] = None,
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Thread:
    """Create a thread.

    Args:
        messages (List[Dict], optional):
            List of messages to start thread. Defaults to None.
        metadata (Dict, optional):
            The key-value information associate with thread. Defaults to
            None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        Thread: The thread object.
    """
    return cls.create(
        messages=messages,
        metadata=metadata,
        workspace=workspace,
        api_key=api_key,
        **kwargs,
    )

create classmethod

create(
    *,
    messages: List[Dict] = None,
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Thread

Create a thread.

Parameters:

Name Type Description Default
messages List[Dict]

List of messages to start thread. Defaults to None.

None
metadata Dict

The key-value information associate with thread. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
Thread Thread

The thread object.

Source code in dashscope/legacy_1x/threads/threads.py
 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
@classmethod
def create(
    cls,
    *,
    messages: List[Dict] = None,
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Thread:
    """Create a thread.

    Args:
        messages (List[Dict], optional):
            List of messages to start thread. Defaults to None.
        metadata (Dict, optional):
            The key-value information associate with thread. Defaults to
            None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        Thread: The thread object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    data = {}
    if messages:
        data["messages"] = messages
    if metadata:
        data["metadata"] = metadata
    response = super().call(
        data=data if data else "",
        api_key=api_key,
        flattened_output=True,
        workspace=workspace,
        **kwargs,
    )
    return Thread(**response)

get classmethod

get(
    thread_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Thread

Retrieve the thread.

Parameters:

Name Type Description Default
thread_id str

The target thread.

required
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
Thread Thread

The Thread information.

Source code in dashscope/legacy_1x/threads/threads.py
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
@classmethod
def get(  # type: ignore[override]
    cls,
    thread_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Thread:
    """Retrieve the thread.

    Args:
        thread_id (str): The target thread.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        Thread: The `Thread` information.
    """
    return cls.retrieve(
        thread_id,
        workspace=workspace,
        api_key=api_key,
        **kwargs,
    )

retrieve classmethod

retrieve(
    thread_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Thread

Retrieve the thread.

Parameters:

Name Type Description Default
thread_id str

The target thread.

required
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
Thread Thread

The Thread information.

Source code in dashscope/legacy_1x/threads/threads.py
142
143
144
145
146
147
148
149
150
151
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
@classmethod
def retrieve(
    cls,
    thread_id: str,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Thread:
    """Retrieve the thread.

    Args:
        thread_id (str): The target thread.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        Thread: The `Thread` information.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id:
        raise InputRequired("thread_id is required!")
    response = super().get(
        thread_id,
        api_key=api_key,
        flattened_output=True,
        workspace=workspace,
        **kwargs,
    )
    return Thread(**response)

update classmethod

update(
    thread_id: str,
    *,
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Thread

Update thread information.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
metadata Dict

The thread key-value information. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
Thread Thread

The Thread information.

Source code in dashscope/legacy_1x/threads/threads.py
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
@classmethod
def update(  # type: ignore[override]
    cls,
    thread_id: str,
    *,
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Thread:
    """Update thread information.

    Args:
        thread_id (str): The thread id.
        metadata (Dict, optional):
            The thread key-value information. Defaults to None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        Thread: The `Thread` information.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id:
        raise InputRequired("thread_id is required!")
    response = super().update(
        thread_id,
        json={"metadata": metadata},
        api_key=api_key,
        workspace=workspace,
        flattened_output=True,
        method="post",
        **kwargs,
    )
    return Thread(**response)

delete classmethod

delete(
    thread_id,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> DeleteResponse

Delete thread.

Parameters:

Name Type Description Default
thread_id str

The thread id to delete.

required
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
AssistantsDeleteResponse DeleteResponse

The deleted information.

Source code in dashscope/legacy_1x/threads/threads.py
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
@classmethod
def delete(  # type: ignore[override]
    cls,
    thread_id,
    *,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> DeleteResponse:
    """Delete thread.

    Args:
        thread_id (str): The thread id to delete.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        AssistantsDeleteResponse: The deleted information.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id:
        raise InputRequired("thread_id is required!")
    response = super().delete(
        thread_id,
        api_key=api_key,
        workspace=workspace,
        flattened_output=True,
        **kwargs,
    )
    return DeleteResponse(**response)

create_and_run classmethod

create_and_run(
    *,
    assistant_id: str,
    thread: Optional[Dict] = None,
    model: Optional[str] = None,
    instructions: Optional[str] = None,
    additional_instructions: Optional[str] = None,
    tools: Optional[List[Dict]] = None,
    metadata: Optional[Dict] = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Run
Source code in dashscope/legacy_1x/threads/threads.py
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
294
295
296
297
298
299
@classmethod
def create_and_run(
    cls,
    *,
    assistant_id: str,
    thread: Optional[Dict] = None,
    model: Optional[str] = None,
    instructions: Optional[str] = None,
    additional_instructions: Optional[str] = None,
    tools: Optional[List[Dict]] = None,
    metadata: Optional[Dict] = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Run:
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not assistant_id:
        raise InputRequired("assistant_id is required")
    data = {"assistant_id": assistant_id}
    if thread:
        data["thread"] = thread
    if model:
        data["model"] = model
    if instructions:
        data["instructions"] = instructions
    if additional_instructions:
        data["additional_instructions"] = additional_instructions
    if tools:
        data["tools"] = tools
    if metadata:
        data["metadata"] = metadata

    response = super().call(
        data=data,
        path="threads/runs",
        api_key=api_key,
        flattened_output=True,
        workspace=workspace,
        **kwargs,
    )
    return Run(**response)

Thread dataclass

Thread(**kwargs)

Bases: BaseObjectMixin

Source code in dashscope/legacy_1x/threads/thread_types.py
229
230
def __init__(self, **kwargs):
    super().__init__(**kwargs)

status_code instance-attribute

status_code: int

id instance-attribute

id: str

created_at instance-attribute

created_at: int

metadata class-attribute instance-attribute

metadata: Optional[object] = None

object class-attribute instance-attribute

object: str = 'thread'

ThreadMessage dataclass

ThreadMessage(**kwargs)

Bases: BaseObjectMixin

Source code in dashscope/legacy_1x/threads/thread_types.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def __init__(self, **kwargs):
    input_content = kwargs.pop('content', None)
    if input_content:
        content_list = []
        for content in input_content:
            if 'type' in content:
                content_type = MESSAGE_SUPPORT_CONTENT.get(
                    content['type'], None,
                )
                if content_type:
                    content_list.append(content_type(**content))
                else:
                    content_list.append(content)
            else:
                content_list.append(content)
        self.content = content_list
    else:
        self.content = input_content

    super().__init__(**kwargs)

status_code instance-attribute

status_code: int

id instance-attribute

id: str

created_at instance-attribute

created_at: int

thread_id instance-attribute

thread_id: str

role instance-attribute

role: str

content instance-attribute

content: List[Content]

metadata class-attribute instance-attribute

metadata: Optional[object] = None

object class-attribute instance-attribute

object: str = 'thread.message'

assistant_id class-attribute instance-attribute

assistant_id: Optional[str] = None

file_ids class-attribute instance-attribute

file_ids: List[str] = None

run_id class-attribute instance-attribute

run_id: Optional[str] = None

Messages

Bases: CreateMixin, ListObjectMixin, GetStatusMixin, UpdateMixin

.. deprecated:: The Messages API (Assistants API) is deprecated and will be removed in a future release. Please migrate to the Responses API. See https://help.aliyun.com/zh/model-studio/ synchronous-call-api-reference for migration details.

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'messages'

call classmethod

call(
    thread_id: str,
    *,
    content: str,
    role: str = "user",
    file_ids: List[str] = [],
    metadata: Optional[object] = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> ThreadMessage

Create message of thread.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
content str

The message content.

required
role str

The message role. Defaults to 'user'.

'user'
file_ids List[str]

The file_ids include in message. Defaults to [].

[]
metadata Optional[object]

The custom key/value pairs. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

The DashScope api key. Defaults to None.

None

Returns:

Name Type Description
ThreadMessage ThreadMessage

The ThreadMessage object.

Source code in dashscope/legacy_1x/threads/messages/messages.py
41
42
43
44
45
46
47
48
49
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
@classmethod
# pylint: disable=dangerous-default-value
def call(  # type: ignore[override]
    cls,
    thread_id: str,
    *,
    content: str,
    role: str = "user",
    file_ids: List[str] = [],
    metadata: Optional[object] = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> ThreadMessage:
    """Create message of thread.

    Args:
        thread_id (str): The thread id.
        content (str): The message content.
        role (str, optional): The message role. Defaults to 'user'.
        file_ids (List[str], optional):
            The file_ids include in message. Defaults to [].
        metadata (Optional[object], optional):
            The custom key/value pairs. Defaults to None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): The DashScope api key. Defaults to None.

    Returns:
        ThreadMessage: The `ThreadMessage` object.
    """
    return cls.create(
        thread_id,
        content=content,
        role=role,
        file_ids=file_ids,
        metadata=metadata,
        workspace=workspace,
        **kwargs,
    )

create classmethod

create(
    thread_id: str,
    *,
    content: str,
    role: str = "user",
    file_ids: List[str] = [],
    metadata: Optional[object] = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> ThreadMessage

Create message of thread.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
content str

The message content.

required
role str

The message role. Defaults to 'user'.

'user'
file_ids List[str]

The file_ids include in message. Defaults to [].

[]
metadata Optional[object]

The custom key/value pairs. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

The DashScope api key. Defaults to None.

None

Returns:

Name Type Description
ThreadMessage ThreadMessage

The ThreadMessage object.

Source code in dashscope/legacy_1x/threads/messages/messages.py
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@classmethod
# pylint: disable=dangerous-default-value
def create(
    cls,
    thread_id: str,
    *,
    content: str,
    role: str = "user",
    file_ids: List[str] = [],
    metadata: Optional[object] = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> ThreadMessage:
    """Create message of thread.

    Args:
        thread_id (str): The thread id.
        content (str): The message content.
        role (str, optional): The message role. Defaults to 'user'.
        file_ids (List[str], optional):
            The file_ids include in message. Defaults to [].
        metadata (Optional[object], optional):
            The custom key/value pairs. Defaults to None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): The DashScope api key. Defaults to None.

    Returns:
        ThreadMessage: The `ThreadMessage` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    cls.SUB_PATH = f"{thread_id}/messages"
    data = {}
    if not thread_id or not content:
        raise InputRequired("thread_id and content are required!")
    data["content"] = content
    data["role"] = role
    if metadata:
        data["metadata"] = metadata
    if file_ids:
        data["file_ids"] = file_ids
    response = super().call(
        data=data,
        path=f"threads/{thread_id}/messages",
        api_key=api_key,
        flattened_output=True,
        workspace=workspace,
        **kwargs,
    )
    return ThreadMessage(**response)

retrieve classmethod

retrieve(
    message_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> ThreadMessage

Get the ThreadMessage.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
message_id str

The message id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
ThreadMessage ThreadMessage

The ThreadMessage object.

Source code in dashscope/legacy_1x/threads/messages/messages.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@classmethod
def retrieve(
    cls,
    message_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> ThreadMessage:
    """Get the `ThreadMessage`.

    Args:
        thread_id (str): The thread id.
        message_id (str): The message id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        ThreadMessage: The `ThreadMessage` object.
    """
    return cls.get(
        message_id,
        thread_id=thread_id,
        workspace=workspace,
        api_key=api_key,
        **kwargs,
    )

get classmethod

get(
    message_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> ThreadMessage

Get the ThreadMessage.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
message_id str

The message id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
ThreadMessage ThreadMessage

The ThreadMessage object.

Source code in dashscope/legacy_1x/threads/messages/messages.py
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
@classmethod
def get(  # type: ignore[override]
    cls,
    message_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> ThreadMessage:
    """Get the `ThreadMessage`.

    Args:
        thread_id (str): The thread id.
        message_id (str): The message id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        ThreadMessage: The `ThreadMessage` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not message_id or not thread_id:
        raise InputRequired("thread id, message id are required!")
    response = super().get(
        message_id,
        path=f"threads/{thread_id}/messages/{message_id}",
        workspace=workspace,
        api_key=api_key,
        flattened_output=True,
        **kwargs,
    )
    return ThreadMessage(**response)

list classmethod

list(
    thread_id: str,
    *,
    limit: int = None,
    order: str = None,
    after: str = None,
    before: str = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> ThreadMessageList

List message of the thread.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
limit int

How many assistant to retrieve. Defaults to None.

None
order str

Sort order by created_at. Defaults to None.

None
after str

Assistant id after. Defaults to None.

None
before str

Assistant id before. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
ThreadMessageList ThreadMessageList

The ThreadMessageList object.

Source code in dashscope/legacy_1x/threads/messages/messages.py
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
246
247
248
249
250
251
252
@classmethod
def list(  # type: ignore[override]
    cls,
    thread_id: str,
    *,
    limit: int = None,
    order: str = None,
    after: str = None,
    before: str = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> ThreadMessageList:
    """List message of the thread.

    Args:
        thread_id (str): The thread id.
        limit (int, optional):
            How many assistant to retrieve. Defaults to None.
        order (str, optional): Sort order by created_at. Defaults to None.
        after (str, optional): Assistant id after. Defaults to None.
        before (str, optional): Assistant id before. Defaults to None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        ThreadMessageList: The `ThreadMessageList` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id:
        raise InputRequired("thread id is required!")
    response = super().list(
        limit=limit,
        order=order,
        after=after,
        before=before,
        path=f"threads/{thread_id}/messages",
        workspace=workspace,
        api_key=api_key,
        flattened_output=True,
        **kwargs,
    )
    return ThreadMessageList(**response)

update classmethod

update(
    message_id: str,
    *,
    thread_id: str,
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> ThreadMessage

Update an message of the thread.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
message_id str

The message id.

required
metadata Optional[object]

The custom key/value pairs. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

The DashScope api key. Defaults to None.

None
**kwargs Any

content (str): The message content. role (str, optional): The message role. Defaults to 'user'. file_ids (List[str], optional): The file_ids include in message. Defaults to [].

{}

Returns:

Name Type Description
ThreadMessage ThreadMessage

The ThreadMessage object.

Source code in dashscope/legacy_1x/threads/messages/messages.py
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
294
295
296
@classmethod
def update(  # type: ignore[override]
    cls,
    message_id: str,
    *,
    thread_id: str,
    metadata: Dict = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> ThreadMessage:
    """Update an message of the thread.

    Args:
        thread_id (str): The thread id.
        message_id (str): The message id.
        metadata (Optional[object], optional):
            The custom key/value pairs. Defaults to None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): The DashScope api key. Defaults to None.
        **kwargs (Any):
            content (str): The message content.
            role (str, optional): The message role. Defaults to 'user'.
            file_ids (List[str], optional):
                The file_ids include in message. Defaults to [].

    Returns:
        ThreadMessage: The `ThreadMessage` object.
    """
    if not thread_id or not message_id:
        raise InputRequired("thread id and message id are required!")
    response = super().update(
        target=message_id,
        json={"metadata": metadata},
        path=f"threads/{thread_id}/messages/{message_id}",
        api_key=api_key,
        workspace=workspace,
        flattened_output=True,
        method="post",
        **kwargs,
    )
    return ThreadMessage(**response)

Runs

Bases: CreateMixin, CancelMixin, ListObjectMixin, GetStatusMixin, UpdateMixin

.. deprecated:: The Runs API (Assistants API) is deprecated and will be removed in a future release. Please migrate to the Responses API. See https://help.aliyun.com/zh/model-studio/ synchronous-call-api-reference for migration details.

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'RUNS'

create_thread_and_run classmethod

create_thread_and_run(
    *,
    assistant_id: str,
    thread: Optional[Dict] = None,
    model: Optional[str] = None,
    instructions: Optional[str] = None,
    additional_instructions: Optional[str] = None,
    tools: Optional[List[Dict]] = None,
    stream: Optional[bool] = False,
    metadata: Optional[Dict] = None,
    workspace: str = None,
    extra_body: Optional[Dict] = None,
    api_key: str = None,
    **kwargs
) -> Run

Create a thread and run it with an assistant.

Parameters:

Name Type Description Default
assistant_id str

The assistant id to run.

required
thread Optional[Dict]

The thread to create.

None
model Optional[str]

The model to use.

None
instructions Optional[str]

The instructions.

None
additional_instructions Optional[str]

Additional instructions.

None
tools Optional[List[Dict]]

The tools to use.

None
stream Optional[bool]

Whether to stream. Defaults to False.

False
metadata Optional[Dict]

The metadata.

None
workspace str

The workspace id.

None
extra_body Optional[Dict]

Extra body parameters.

None
api_key str

The api key.

None

Returns:

Name Type Description
Run Run

The run object.

Source code in dashscope/legacy_1x/threads/runs/runs.py
 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@classmethod
def create_thread_and_run(
    cls,
    *,
    assistant_id: str,
    thread: Optional[Dict] = None,
    model: Optional[str] = None,
    instructions: Optional[str] = None,
    additional_instructions: Optional[str] = None,
    tools: Optional[List[Dict]] = None,
    stream: Optional[bool] = False,
    metadata: Optional[Dict] = None,
    workspace: str = None,
    extra_body: Optional[Dict] = None,
    api_key: str = None,
    **kwargs,
) -> Run:
    """Create a thread and run it with an assistant.

    Args:
        assistant_id (str): The assistant id to run.
        thread (Optional[Dict], optional): The thread to create.
        model (Optional[str], optional): The model to use.
        instructions (Optional[str], optional): The instructions.
        additional_instructions (Optional[str], optional):
            Additional instructions.
        tools (Optional[List[Dict]], optional): The tools to use.
        stream (Optional[bool], optional):
            Whether to stream. Defaults to False.
        metadata (Optional[Dict], optional): The metadata.
        workspace (str, optional): The workspace id.
        extra_body (Optional[Dict], optional): Extra body parameters.
        api_key (str, optional): The api key.

    Returns:
        Run: The run object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not assistant_id:
        raise InputRequired("assistant_id is required")
    data = {"assistant_id": assistant_id}
    if thread:
        data["thread"] = thread
    if model:
        data["model"] = model
    if instructions:
        data["instructions"] = instructions
    if additional_instructions:
        data["additional_instructions"] = additional_instructions
    if tools:
        data["tools"] = tools
    if metadata:
        data["metadata"] = metadata
    data["stream"] = stream
    if extra_body is not None and extra_body:
        data = {**data, **extra_body}

    response = super().call(
        data=data,
        path="threads/runs",
        api_key=api_key,
        flattened_output=True,
        stream=stream,  # type: ignore[arg-type]
        workspace=workspace,
        **kwargs,
    )
    if stream:
        return (  # type: ignore[return-value]
            (event_type, cls.convert_stream_object(event_type, item))
            for event_type, item in response
        )
    else:
        return Run(**response)

create classmethod

create(
    thread_id: str,
    *,
    assistant_id: str,
    model: Optional[str] = None,
    instructions: Optional[str] = None,
    additional_instructions: Optional[str] = None,
    tools: Optional[List[Dict]] = None,
    metadata: Optional[Dict] = None,
    stream: Optional[bool] = False,
    workspace: str = None,
    extra_body: Optional[Dict] = None,
    api_key: str = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    temperature: Optional[float] = None,
    max_tokens: Optional[int] = None,
    **kwargs
) -> Run

Create a run.

Parameters:

Name Type Description Default
thread_id str

The thread to run.

required
assistant_id str

The assistant id to run.

required
model str

The model to use.

None
instructions str

The system instructions this assistant uses. Defaults to None.

None
additional_instructions Optional[str]

Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.. Defaults to None.

None
tools Optional[str]

List of tools to use.. Defaults to []. # noqa: E501

None
metadata Dict

Custom key-value pairs associate with run. Defaults to None.

None
workspace str

The DashScope workspace id.

None
api_key str

The DashScope workspace id. Defaults to None.

None

Raises:

Type Description
InputRequired

thread and assistant is required.

Returns:

Name Type Description
Run Run

The Run object.

Source code in dashscope/legacy_1x/threads/runs/runs.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
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
226
227
228
229
230
231
@classmethod
def create(  # pylint: disable=too-many-branches
    cls,
    thread_id: str,
    *,
    assistant_id: str,
    model: Optional[str] = None,
    instructions: Optional[str] = None,
    additional_instructions: Optional[str] = None,
    tools: Optional[List[Dict]] = None,
    metadata: Optional[Dict] = None,
    stream: Optional[bool] = False,
    workspace: str = None,
    extra_body: Optional[Dict] = None,
    api_key: str = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    temperature: Optional[float] = None,
    max_tokens: Optional[int] = None,
    **kwargs,
) -> Run:
    """Create a run.

    Args:
        thread_id (str): The thread to run.
        assistant_id (str): The assistant id to run.
        model (str): The model to use.
        instructions (str, optional):
            The system instructions this assistant uses. Defaults to None.
        additional_instructions (Optional[str], optional):
            Appends additional
            instructions at the end of the instructions for the run. This is
            useful for modifying the behavior on a per-run basis without
            overriding other instructions.. Defaults to None.
        tools (Optional[str], optional): List of tools to use.. Defaults to [].  # noqa: E501
        metadata (Dict, optional):
            Custom key-value pairs associate with run. Defaults to None.
        workspace (str): The DashScope workspace id.
        api_key (str, optional):
            The DashScope workspace id. Defaults to None.

    Raises:
        InputRequired: thread and assistant is required.

    Returns:
        Run: The `Run` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id or not assistant_id:
        raise InputRequired("thread_id and assistant_id is required")
    data = {"assistant_id": assistant_id}
    if model:
        data["model"] = model
    if instructions:
        data["instructions"] = instructions
    if additional_instructions:
        data["additional_instructions"] = additional_instructions
    if tools:
        data["tools"] = tools
    if metadata:
        data["metadata"] = metadata
    data["stream"] = stream
    if extra_body is not None and extra_body:
        data = {**data, **extra_body}

    if top_p is not None:
        data["top_p"] = top_p
    if top_k is not None:
        data["top_k"] = top_k
    if temperature is not None:
        data["temperature"] = temperature
    if max_tokens is not None:
        data["max_tokens"] = max_tokens

    response = super().call(
        data=data,
        path=f"threads/{thread_id}/runs",
        api_key=api_key,
        flattened_output=True,
        stream=stream,  # type: ignore[arg-type]
        workspace=workspace,
        **kwargs,
    )
    if stream:
        return (  # type: ignore[return-value]
            (event_type, cls.convert_stream_object(event_type, item))
            for event_type, item in response
        )
    else:
        return Run(**response)

convert_stream_object classmethod

convert_stream_object(event, item)
Source code in dashscope/legacy_1x/threads/runs/runs.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
@classmethod
def convert_stream_object(cls, event, item):
    event_object_map = {
        "thread.created": Thread,
        "thread.run.created": Run,
        "thread.run.queued": Run,
        "thread.run.in_progress": Run,
        "thread.run.requires_action": Run,
        "thread.run.completed": Run,
        "thread.run.failed": Run,
        "thread.run.cancelled": Run,
        "thread.run.expired": Run,
        "thread.run.step.created": RunStep,
        "thread.run.step.in_progress": RunStep,
        "thread.run.step.delta": RunStepDelta,
        "thread.run.step.completed": RunStep,
        "thread.run.step.failed": RunStep,
        "thread.run.step.cancelled": RunStep,
        "thread.run.step.expired": RunStep,
        "thread.message.created": ThreadMessage,
        "thread.message.in_progress": ThreadMessage,
        "thread.message.delta": ThreadMessageDelta,
        "thread.message.completed": ThreadMessage,
        "thread.message.incomplete": ThreadMessage,
        "error": AssistantError,
    }
    if event in event_object_map:
        return event_object_map[event](**item)
    else:
        return item

call classmethod

call(
    thread_id: str,
    *,
    assistant_id: str,
    model: Optional[str] = None,
    instructions: Optional[str] = None,
    additional_instructions: Optional[str] = None,
    tools: Optional[List[Dict]] = None,
    stream: Optional[bool] = False,
    metadata: Optional[Dict] = None,
    workspace: str = None,
    extra_body: Optional[Dict] = None,
    api_key: str = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    temperature: Optional[float] = None,
    max_tokens: Optional[int] = None,
    **kwargs
) -> Run

Create a run.

Parameters:

Name Type Description Default
thread_id str

The thread to run.

required
assistant_id str

The assistant id to run.

required
model str

The model to use.

None
instructions str

The system instructions this assistant uses. Defaults to None.

None
additional_instructions Optional[str]

Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.. Defaults to None.

None
tools Optional[str]

List of tools to use.. Defaults to []. # noqa: E501

None
metadata Dict

Custom key-value pairs associate with run. Defaults to None.

None
workspace str

The DashScope workspace id.

None
api_key str

The DashScope workspace id. Defaults to None.

None

Raises:

Type Description
InputRequired

thread and assistant is required.

Returns:

Name Type Description
Run Run

The Run object.

Source code in dashscope/legacy_1x/threads/runs/runs.py
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
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
327
328
@classmethod
def call(  # type: ignore[override]
    cls,
    thread_id: str,
    *,
    assistant_id: str,
    model: Optional[str] = None,
    instructions: Optional[str] = None,
    additional_instructions: Optional[str] = None,
    tools: Optional[List[Dict]] = None,
    stream: Optional[bool] = False,
    metadata: Optional[Dict] = None,
    workspace: str = None,
    extra_body: Optional[Dict] = None,
    api_key: str = None,
    top_p: Optional[float] = None,
    top_k: Optional[int] = None,
    temperature: Optional[float] = None,
    max_tokens: Optional[int] = None,
    **kwargs,
) -> Run:
    """Create a run.

    Args:
        thread_id (str): The thread to run.
        assistant_id (str): The assistant id to run.
        model (str): The model to use.
        instructions (str, optional):
            The system instructions this assistant uses. Defaults to None.
        additional_instructions (Optional[str], optional):
            Appends additional
            instructions at the end of the instructions for the run. This is
            useful for modifying the behavior on a per-run basis without
            overriding other instructions.. Defaults to None.
        tools (Optional[str], optional): List of tools to use.. Defaults to [].  # noqa: E501
        metadata (Dict, optional):
            Custom key-value pairs associate with run. Defaults to None.
        workspace (str): The DashScope workspace id.
        api_key (str, optional):
            The DashScope workspace id. Defaults to None.

    Raises:
        InputRequired: thread and assistant is required.

    Returns:
        Run: The `Run` object.
    """
    return cls.create(
        thread_id,
        assistant_id=assistant_id,
        model=model,
        instructions=instructions,
        additional_instructions=additional_instructions,
        tools=tools,
        stream=stream,
        metadata=metadata,
        workspace=workspace,
        extra_body=extra_body,
        api_key=api_key,
        top_p=top_p,
        top_k=top_k,
        temperature=temperature,
        max_tokens=max_tokens,
        **kwargs,
    )

list classmethod

list(
    thread_id: str,
    *,
    limit: int = None,
    order: str = None,
    after: str = None,
    before: str = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> RunList

List Run.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
limit int

How many assistant to retrieve. Defaults to None.

None
order str

Sort order by created_at. Defaults to None.

None
after str

Assistant id after. Defaults to None.

None
before str

Assistant id before. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
RunList RunList

The list of runs.

Source code in dashscope/legacy_1x/threads/runs/runs.py
330
331
332
333
334
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
@classmethod
def list(  # type: ignore[override]
    cls,
    thread_id: str,
    *,
    limit: int = None,
    order: str = None,
    after: str = None,
    before: str = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> RunList:
    """List `Run`.

    Args:
        thread_id (str): The thread id.
        limit (int, optional):
            How many assistant to retrieve. Defaults to None.
        order (str, optional): Sort order by created_at. Defaults to None.
        after (str, optional): Assistant id after. Defaults to None.
        before (str, optional): Assistant id before. Defaults to None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        RunList: The list of runs.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id:
        raise InputRequired("thread_id is required!")
    response = super().list(
        limit=limit,
        order=order,
        after=after,
        before=before,
        path=f"threads/{thread_id}/runs",
        workspace=workspace,
        api_key=api_key,
        flattened_output=True,
        **kwargs,
    )
    return RunList(**response)

retrieve classmethod

retrieve(
    run_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Run

Retrieve the Run.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
run_id str

The run id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
Run Run

The Run object.

Source code in dashscope/legacy_1x/threads/runs/runs.py
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
410
411
412
413
414
415
@classmethod
def retrieve(
    cls,
    run_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Run:
    """Retrieve the `Run`.

    Args:
        thread_id (str): The thread id.
        run_id (str): The run id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        Run: The `Run` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id or not run_id:
        raise InputRequired("thread_id and run_id are required!")
    response = super().get(
        run_id,
        path=f"threads/{thread_id}/runs/{run_id}",
        workspace=workspace,
        api_key=api_key,
        flattened_output=True,
        **kwargs,
    )
    return Run(**response)

get classmethod

get(
    run_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Run

Retrieve the Run.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
run_id str

The run id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
Run Run

The Run object.

Source code in dashscope/legacy_1x/threads/runs/runs.py
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
@classmethod
def get(  # type: ignore[override]
    cls,
    run_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Run:
    """Retrieve the `Run`.

    Args:
        thread_id (str): The thread id.
        run_id (str): The run id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        Run: The `Run` object.
    """
    return cls.retrieve(
        run_id,
        thread_id=thread_id,
        workspace=workspace,
        api_key=api_key,
        **kwargs,
    )

submit_tool_outputs classmethod

submit_tool_outputs(
    run_id: str,
    *,
    thread_id: str,
    tool_outputs: List[Dict],
    stream: Optional[bool] = False,
    workspace: str = None,
    extra_body: Optional[Dict] = None,
    api_key: str = None,
    **kwargs
) -> Run

Submit tool outputs.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
run_id str

The run id.

required
tool_outputs List[Dict]

The tool outputs.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Raises:

Type Description
InputRequired

The tool output thread id run id are required.

Returns:

Name Type Description
Run Run

The 'Run`.

Source code in dashscope/legacy_1x/threads/runs/runs.py
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
@classmethod
def submit_tool_outputs(
    cls,
    run_id: str,
    *,
    thread_id: str,
    tool_outputs: List[Dict],
    stream: Optional[bool] = False,
    workspace: str = None,
    extra_body: Optional[Dict] = None,
    api_key: str = None,
    **kwargs,
) -> Run:
    """Submit tool outputs.

    Args:
        thread_id (str): The thread id.
        run_id (str): The run id.
        tool_outputs (List[Dict]): The tool outputs.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Raises:
        InputRequired: The tool output thread id run id
            are required.

    Returns:
        Run: The 'Run`.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not tool_outputs:
        raise InputRequired("tool_outputs is required!")
    if not thread_id or not run_id:
        raise InputRequired("thread_id and run_id are required!")

    data = {"tool_outputs": tool_outputs}
    data["stream"] = stream
    if extra_body is not None and extra_body:
        data = {**data, **extra_body}

    response = super().call(
        data,
        path=f"threads/{thread_id}/runs/{run_id}/submit_tool_outputs",
        workspace=workspace,
        api_key=api_key,
        stream=stream,  # type: ignore[arg-type]
        flattened_output=True,
        **kwargs,
    )
    if stream:
        return (  # type: ignore[return-value]
            (event_type, cls.convert_stream_object(event_type, item))
            for event_type, item in response
        )
    else:
        return Run(**response)

wait classmethod

wait(
    run_id: str,
    *,
    thread_id: str,
    timeout_seconds: float = float("inf"),
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Run

Wait for run to complete.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
run_id str

The run id.

required
timeout_seconds int

The timeout seconds. Defaults inf.

float('inf')
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
Run Run

The run final status.

Source code in dashscope/legacy_1x/threads/runs/runs.py
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
@classmethod
def wait(  # pylint: disable=unused-argument
    cls,
    run_id: str,
    *,
    thread_id: str,
    timeout_seconds: float = float("inf"),
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Run:
    """Wait for run to complete.

    Args:
        thread_id (str): The thread id.
        run_id (str): The run id.
        timeout_seconds (int): The timeout seconds. Defaults inf.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        Run: The run final status.
    """
    if not run_id or not thread_id:
        raise InputRequired("run_id and thread_id are required!")
    start_time = time.perf_counter()
    while True:
        run = cls.get(
            run_id,
            thread_id=thread_id,
            workspace=workspace,
            api_key=api_key,
        )
        if run.status_code == HTTPStatus.OK:
            if hasattr(run, "status"):
                if run.status in [
                    "cancelled",
                    "failed",
                    "completed",
                    "expired",
                    "requires_action",
                ]:
                    break
                time_eclipsed = (
                    time.perf_counter() - start_time
                )  # pylint: disable=no-else-break
                if time_eclipsed > timeout_seconds:
                    raise TimeoutException("Wait run complete timeout")
                time.sleep(1)
            else:
                logger.error("run has no status")
                break
        else:
            logger.error(
                "Get run thread_id: %s, run_id: %s failed, message: %s",
                thread_id,
                run_id,
                run.message,
            )
            break
    return run

update classmethod

update(
    run_id: str,
    *,
    thread_id: str,
    metadata: Optional[Dict] = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Run

Create a run.

Parameters:

Name Type Description Default
thread_id str

The thread of the run id to be updated.

required
run_id str

The run id to update.

required
metadata Dict

Custom key-value pairs associate with run. Defaults to None.

None
workspace str

The DashScope workspace id.

None
api_key str

The DashScope workspace id. Defaults to None.

None
**kwargs Any

model (str): The model to use.

{}

Raises:

Type Description
InputRequired

thread id and run is required.

Returns:

Name Type Description
Run Run

The Run object.

Source code in dashscope/legacy_1x/threads/runs/runs.py
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
@classmethod
def update(  # type: ignore[override]
    cls,
    run_id: str,
    *,
    thread_id: str,
    metadata: Optional[Dict] = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Run:
    """Create a run.

    Args:
        thread_id (str): The thread of the run id to be updated.
        run_id (str): The run id to update.
        metadata (Dict, optional):
            Custom key-value pairs associate with run. Defaults to None.
        workspace (str): The DashScope workspace id.
        api_key (str, optional):
            The DashScope workspace id. Defaults to None.
        **kwargs (Any):
            model (str): The model to use.

    Raises:
        InputRequired: thread id and run is required.

    Returns:
        Run: The `Run` object.
    """
    if not thread_id or not run_id:
        raise InputRequired("thread id and run id are required!")
    response = super().update(
        run_id,
        json={"metadata": metadata},
        path=f"threads/{thread_id}/runs/{run_id}",
        api_key=api_key,
        workspace=workspace,
        flattened_output=True,
        method="post",
        **kwargs,
    )
    return Run(**response)

cancel classmethod

cancel(
    run_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> Run

Cancel the Run.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
run_id str

The run id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
Run Run

The Run object.

Source code in dashscope/legacy_1x/threads/runs/runs.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
@classmethod
def cancel(  # type: ignore[override]
    cls,
    run_id: str,
    *,
    thread_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> Run:
    """Cancel the `Run`.

    Args:
        thread_id (str): The thread id.
        run_id (str): The run id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        Run: The `Run` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id or not run_id:
        raise InputRequired("thread id and run id are required!")
    response = super().cancel(
        run_id,
        path=f"threads/{thread_id}/runs/{run_id}/cancel",
        api_key=api_key,
        workspace=workspace,
        flattened_output=True,
        **kwargs,
    )

    return Run(**response)

Run dataclass

Run(**kwargs)

Bases: BaseObjectMixin

Source code in dashscope/legacy_1x/threads/thread_types.py
335
336
337
338
339
340
341
342
343
def __init__(self, **kwargs):
    self.tools = convert_tools_dict_to_objects(kwargs.pop('tools', []))
    actions = kwargs.pop('required_action', None)
    if actions:
        self.required_action = RequiredAction(**actions)
    else:
        self.required_action = actions

    super().__init__(**kwargs)

status_code instance-attribute

status_code: int

id instance-attribute

id: str

assistant_id instance-attribute

assistant_id: str

cancelled_at class-attribute instance-attribute

cancelled_at: Optional[int] = None

completed_at class-attribute instance-attribute

completed_at: Optional[int] = None

created_at class-attribute instance-attribute

created_at: int = None

expires_at class-attribute instance-attribute

expires_at: int = None

failed_at class-attribute instance-attribute

failed_at: Optional[int] = None

file_ids class-attribute instance-attribute

file_ids: List[str] = None

instructions class-attribute instance-attribute

instructions: str = None

metadata class-attribute instance-attribute

metadata: Optional[object] = None

last_error class-attribute instance-attribute

last_error: Optional[LastError] = None

model class-attribute instance-attribute

model: str = None

object class-attribute instance-attribute

object: str = 'thread.run'

required_action class-attribute instance-attribute

required_action: Optional[RequiredAction] = None

started_at class-attribute instance-attribute

started_at: Optional[int] = None

status instance-attribute

status: Literal[
    "queued",
    "in_progress",
    "requires_action",
    "cancelling",
    "cancelled",
    "failed",
    "completed",
    "expired",
]

thread_id instance-attribute

thread_id: str

top_p class-attribute instance-attribute

top_p: Optional[float] = None

top_k class-attribute instance-attribute

top_k: Optional[int] = None

temperature class-attribute instance-attribute

temperature: Optional[float] = None

max_tokens class-attribute instance-attribute

max_tokens: Optional[int] = None

usage class-attribute instance-attribute

usage: Optional[Usage] = None

tools instance-attribute

tools: List[Tool] = convert_tools_dict_to_objects(
    kwargs.pop("tools", [])
)

Steps

Bases: ListObjectMixin, GetStatusMixin

.. deprecated:: The Steps API (Assistants API) is deprecated and will be removed in a future release. Please migrate to the Responses API. See https://help.aliyun.com/zh/model-studio/ synchronous-call-api-reference for migration details.

SUB_PATH class-attribute instance-attribute

SUB_PATH = 'RUNS'

list classmethod

list(
    run_id: str,
    *,
    thread_id: str,
    limit: int = None,
    order: str = None,
    after: str = None,
    before: str = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> RunStepList

List RunStep of Run.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
run_id str

The run id.

required
limit int

How many assistant to retrieve. Defaults to None.

None
order str

Sort order by created_at. Defaults to None.

None
after str

Assistant id after. Defaults to None.

None
before str

Assistant id before. Defaults to None.

None
workspace str

The DashScope workspace id. Defaults to None.

None
api_key str

Your DashScope api key. Defaults to None.

None

Returns:

Name Type Description
RunList RunStepList

The list of runs.

Source code in dashscope/legacy_1x/threads/runs/steps.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
@classmethod
def list(  # type: ignore[override]
    cls,
    run_id: str,
    *,
    thread_id: str,
    limit: int = None,
    order: str = None,
    after: str = None,
    before: str = None,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> RunStepList:
    """List  `RunStep` of `Run`.

    Args:
        thread_id (str): The thread id.
        run_id (str): The run id.
        limit (int, optional):
            How many assistant to retrieve. Defaults to None.
        order (str, optional): Sort order by created_at. Defaults to None.
        after (str, optional): Assistant id after. Defaults to None.
        before (str, optional): Assistant id before. Defaults to None.
        workspace (str, optional):
            The DashScope workspace id. Defaults to None.
        api_key (str, optional): Your DashScope api key. Defaults to None.

    Returns:
        RunList: The list of runs.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not run_id:
        raise InputRequired("run_id is required!")
    response = super().list(
        limit=limit,
        order=order,
        after=after,
        before=before,
        path=f"threads/{thread_id}/runs/{run_id}/steps",
        workspace=workspace,
        api_key=api_key,
        flattened_output=True,
        **kwargs,
    )
    return RunStepList(**response)

retrieve classmethod

retrieve(
    step_id: str,
    *,
    thread_id: str,
    run_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> RunStep

Retrieve the RunStep.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
run_id str

The run id.

required
step_id str

The step id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
RunStep RunStep

The RunStep object.

Source code in dashscope/legacy_1x/threads/runs/steps.py
 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
121
@classmethod
def retrieve(
    cls,
    step_id: str,
    *,
    thread_id: str,
    run_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> RunStep:
    """Retrieve the `RunStep`.

    Args:
        thread_id (str): The thread id.
        run_id (str): The run id.
        step_id (str): The step id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        RunStep: The `RunStep` object.
    """
    warnings.warn(
        _DEPRECATION_MSG,
        category=DeprecationWarning,
        stacklevel=2,
    )
    if not thread_id or not run_id or not step_id:
        raise InputRequired("thread_id, run_id and step_id are required!")
    response = super().get(
        run_id,
        path=f"threads/{thread_id}/runs/{run_id}/steps/{step_id}",
        workspace=workspace,
        api_key=api_key,
        flattened_output=True,
        **kwargs,
    )
    return RunStep(**response)

get classmethod

get(
    step_id: str,
    *,
    thread_id: str,
    run_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs
) -> RunStep

Retrieve the RunStep.

Parameters:

Name Type Description Default
thread_id str

The thread id.

required
run_id str

The run id.

required
step_id str

The step id.

required
workspace str

The dashscope workspace id.

None
api_key str

The api key. Defaults to None.

None

Returns:

Name Type Description
RunStep RunStep

The RunStep object.

Source code in dashscope/legacy_1x/threads/runs/steps.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
@classmethod
def get(  # type: ignore[override]
    cls,
    step_id: str,
    *,
    thread_id: str,
    run_id: str,
    workspace: str = None,
    api_key: str = None,
    **kwargs,
) -> RunStep:
    """Retrieve the `RunStep`.

    Args:
        thread_id (str): The thread id.
        run_id (str): The run id.
        step_id (str): The step id.
        workspace (str): The dashscope workspace id.
        api_key (str, optional): The api key. Defaults to None.

    Returns:
        RunStep: The `RunStep` object.
    """
    # pylint: disable=too-many-function-args
    return cls.retrieve(  # type: ignore[misc]
        step_id,
        thread_id=thread_id,
        run_id=run_id,
        workspace=workspace,
        api_key=api_key,
        **kwargs,
    )

RunStep dataclass

RunStep(**kwargs)

Bases: BaseObjectMixin

Source code in dashscope/legacy_1x/threads/thread_types.py
668
669
670
671
672
673
674
675
676
677
678
679
680
def __init__(self, **kwargs):
    self.step_details = convert_step_details_dict_to_objects(
        kwargs.pop('step_details', {}),
    )
    if 'usage' in kwargs and kwargs['usage'] is not None and kwargs['usage']:  # noqa: E501
        self.usage = Usage(**kwargs.pop('usage', {}))
    else:
        self.usage = None
    last_error = kwargs.pop('last_error', None)
    if last_error:
        self.last_error = LastError(**last_error)

    super().__init__(**kwargs)

status_code class-attribute instance-attribute

status_code: int = None

id instance-attribute

id: str

The identifier of the run step, which can be referenced in API endpoints.

assistant_id instance-attribute

assistant_id: str

The ID of the assistant associated with the run step.

cancelled_at class-attribute instance-attribute

cancelled_at: Optional[int] = None

The Unix timestamp (in seconds) for when the run step was cancelled.

completed_at class-attribute instance-attribute

completed_at: Optional[int] = None

The Unix timestamp (in seconds) for when the run step completed.

created_at instance-attribute

created_at: int

The Unix timestamp (in seconds) for when the run step was created.

expired_at class-attribute instance-attribute

expired_at: Optional[int] = None

The Unix timestamp (in seconds) for when the run step expired.

A step is considered expired if the parent run is expired.

failed_at class-attribute instance-attribute

failed_at: Optional[int] = None

The Unix timestamp (in seconds) for when the run step failed.

last_error class-attribute instance-attribute

last_error: Optional[LastError] = None

The last error associated with this run step.

Will be null if there are no errors.

metadata class-attribute instance-attribute

metadata: Optional[object] = None

Set of 16 key-value pairs that can be attached to an object.

This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be # noqa: E501 a maxium of 512 characters long.

object instance-attribute

object: Literal['thread.run.step']

The object type, which is always thread.run.step.

run_id instance-attribute

run_id: str

The ID of the run that # noqa: E501 this run step is a part of.

status instance-attribute

status: Literal[
    "in_progress",
    "cancelled",
    "failed",
    "completed",
    "expired",
]

The status of the run step, which can be either in_progress, cancelled, failed, completed, or expired.

thread_id instance-attribute

thread_id: str

The ID of the thread # noqa: E501 that was run.

type instance-attribute

type: Literal['message_creation', 'tool_calls']

The type of run step, which can be either message_creation or tool_calls.

usage class-attribute instance-attribute

usage: Optional[Usage] = None

step_details instance-attribute

step_details: StepDetails = (
    convert_step_details_dict_to_objects(
        kwargs.pop("step_details", {})
    )
)

The details of the run step.

Shared session helpers

close_shared_sync_session

close_shared_sync_session() -> None

Close the shared synchronous session and its pooled connections.

Long-running applications may call this to bound the lifetime of the SDK-managed connection pool (e.g. periodically, or after a transport failure). A fresh session is created lazily on the next request.

Source code in dashscope/legacy_1x/api_entities/http_request.py
130
131
132
133
134
135
136
137
138
139
140
141
142
def close_shared_sync_session() -> None:
    """Close the shared synchronous session and its pooled connections.

    Long-running applications may call this to bound the lifetime of the
    SDK-managed connection pool (e.g. periodically, or after a transport
    failure). A fresh session is created lazily on the next request.
    """
    global _shared_sync_session
    with _shared_sync_session_lock:
        session = _shared_sync_session
        _shared_sync_session = None
    if session is not None:
        session.close()

close_shared_aio_session async

close_shared_aio_session() -> None

Close the shared session for the current event loop.

Source code in dashscope/legacy_1x/api_entities/aio_session.py
102
103
104
105
106
107
108
async def close_shared_aio_session() -> None:
    """Close the shared session for the current event loop."""
    loop = asyncio.get_running_loop()
    with _lock:
        session = _aio_sessions.pop(loop, None)
    if session is not None and not session.closed:
        await session.close()