OpenAI compatible - Chat

Updated at:

You can call models using the OpenAI compatible Chat API. This document describes the input and output parameters and provides call examples.

China (Beijing)

SDK call configuration for base_url: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Singapore

SDK call configuration for base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

US (Virginia)

SDK call configuration for base_url: https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Germany (Frankfurt)

SDK call configuration for base_url: https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Japan (Tokyo)

SDK call configuration for base_url: https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Hong Kong (China)

SDK call configuration for base_url: https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1

HTTP request: POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/compatible-mode/v1/chat/completions

Replace {WorkspaceId} with your actual workspace ID.

Obtain an API key and set it as an environment variable. If you use an OpenAI SDK, you must also install the SDK.

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

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

{WorkspaceId} is your workspace ID, which can be found on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain remains fully functional.

Request body

modelstring(Required)

The model name.

Supported models: Qwen Large Language Model (commercial and open source versions), Qwen-VL, Qwen-Coder, Qwen-Omni, Qwen-Math, DeepSeek(supplied by Alibaba Cloud, SiliconFlow, and Vanchin), Kimi(supplied by Alibaba Cloud and Moonshot AI), GLM(supplied by Alibaba Cloud), and MiniMax(supplied by Alibaba Cloud and MiniMax).

Third-party direct-supply models are available only in the North China 2 (Beijing) region on the China site. Before calling them, you must activate the corresponding service in the Bailian console (taking SiliconFlow DeepSeek as an example: search for deepseek → find the SiliconFlow DeepSeek model card → click Activate Now → Confirm Authorization).

Qwen-Audio does not support the OpenAI compatible protocol. It only supports the DashScope protocol.

For specific model names and billing, seeBailian console.

messagesarray(Required)

The context passed to the large language model, arranged in conversational order.

Message type

System Messageobject(Optional)

A system message that defines the role, tone, task, or constraints for the large language model. It is usually the first element in the messages array.

Do not set a system message for QwQ models. System messages have no effect on QVQ models.

Properties

contentstring(Required)

The system instruction. It specifies the model's role, behavior, response style, and task constraints.

rolestring(Required)

The role for the system message. The value is fixed to system.

User Messageobject(Required)

The user message. It passes questions, instructions, or context to the model.

Properties

contentstring or array(Required)

The message content. The type is string if the input is text only. The type is array if the input contains multimodal data such as images, or if explicit caching is enabled.

Properties for multimodal models or when explicit caching is enabled

typestring(Required)

Valid values:

  • text

    Set to text for text input.

  • image_url

    Set to image_url for image input.

  • input_audio

    Set to input_audio for audio input.

  • video

    Set to video for video input as a list of images.

  • video_url

    Set to video_url for video file input.

    Only some Qwen-VL models support video file input. For more information, see Video understanding (Qwen-VL). QVQ and Qwen-Omni models support direct video file input.

textstring

The input text. This parameter is required when type is text.

image_urlobject

The input image information. This parameter is required when type is image_url.

Properties

url string(Required)

The URL or Base64-encoded Data URL of the image. To pass a local file, see Image and video understanding.

detail string (Optional)

Image processing detail. Max, Plus, and Flash models support this parameter starting with Qwen4. The default is high.

When max_pixels is omitted:

  • high: Process at the original resolution, up to 16777216 pixels.
  • low: Limit the image to 2621440 pixels.
  • auto: Same as low.

An explicit max_pixels value overrides the pixel limit selected by detail. The maximum is 16777216. In Chat Completions, place max_pixels alongside image_url; in DashScope, place it alongside image.

For high-resolution images, high typically uses more input tokens than low.

Chat Completions can pass in detail inside image_url or at the same level as image_url; DashScope passes it in at the same level as image.

{"type":"image_url","image_url":{"url":"https://example.com/image.jpg","detail":"high"}}

input_audioobject

The input audio information. This parameter is required when type is input_audio.

Properties

data string(Required)

The URL or Base64-encoded Data URL of the audio. To pass a local file, see Input a Base64-encoded local file.

formatstring(Required)

The format of the input audio, such as mp3 or wav.

videoarray

For Qwen4-Max, Qwen3.8, Qwen3.7, Qwen3.6, and Qwen3.5 series models, video input as a public URL image list supports 4–8000 images; Base64 image lists support up to 250 images.

The video information in image list form of the input. This parameter is required when type is video. For usage instructions, seeVideo Understanding (Qwen-VL, QVQ)orVideo Understanding (Qwen-Omni).

Example value:

[
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
]

video_urlobject

The input video file information. This parameter is required when type is video_url.

Qwen-VL can only understand the visual information of video files, while Qwen-Omni can understand both visual and audio information.

Properties

url string(Required)

The public URL or Base64-encoded Data URL of the video file. To input a local video file, see Input a Base64-encoded local file.

fpsfloat(Optional)

The number of frames to extract per second. Valid values: [0.1, 10]. Default value: 2.0.

For MiniMax/MiniMax-M3.1-Flash and MiniMax/MiniMax-M3, the valid range is [0.2, 5], and the default value is 1.

Feature description

The fps parameter has two functions:

  • When you input a video file, it controls the frame extraction frequency. One frame is extracted every 1/fps seconds.

    This applies to Qwen-VL and QVQ and MiniMax/MiniMax-M3.1-Flash and MiniMax/MiniMax-M3.

  • It informs the model of the time interval between adjacent frames to help it better understand the video's progression over time. This applies to both video file and image list inputs. This feature is suitable for scenarios such as event time localization or segmented content summarization.

    Supported by Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen2.5-VL, Qwen3.8-Omni-Flash, Qwen3.5-Omni, and QVQ models.

A larger fps value is suitable for high-speed motion scenarios, such as sports events or action movies. A smaller fps value is suitable for long videos or scenes with static content.

Example values

  • Pass in a image list: {"video":["https://xx1.jpg",...,"https://xxn.jpg"],"fps":2}
  • Pass in a video file: {"video": "https://xx1.mp4","fps":2}

min_pixelsinteger(Optional)

Sets the minimum pixel threshold for input images or video frames. If an input's pixel count is less than min_pixels, it is enlarged until its total pixel count is greater than min_pixels. See the supported models and values below.

Value range

  • Image input:
    • qwen4-max, qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL: Default and minimum value: 65536
    • qwen3.8-omni-flash, Qwen3.5-Omni: Default and minimum value: 24576
    • Qwen2.5-VL open source series, and QVQ series models: Default and minimum value: 3136
  • Video file or image list input:
    • qwen4-max, qwen3-omni-flash, qwen3-vl-plus, qwen3.5-122b-a10b, qwen3.5-27b, qwen3.5-35b-a3b, qwen3.5-397b-a17b, qwen3.5-flash, qwen3.5-flash-2026-02-23, qwen3.5-omni-flash, qwen3.5-omni-flash-2026-03-15, qwen3.5-omni-plus, qwen3.5-omni-plus-2026-03-15, qwen3.5-plus, qwen3.5-plus-2026-02-15, qwen3.5-plus-2026-04-20, qwen3.6-27b, qwen3.6-35b-a3b, qwen3.6-flash, qwen3.6-flash-2026-04-16, qwen3.6-plus, qwen3.6-plus-2026-04-02, qwen3.7-flash, qwen3.7-flash-2026-07-15, qwen3.7-max-2026-06-08, qwen3.7-plus, qwen3.7-plus-2026-05-26, qwen3.8-27b, qwen3.8-flash, qwen3.8-max, qwen3.8-max-0902, qwen3.8-omni-flash: Default value: 65536. Minimum value: 4096.
    • kimi-k2.5, kimi-k2.6, kimi-k2.7-code: Minimum value: 3136.
    • Qwen2.5-VL open source series, and QVQ series models: Default value: 50176. Minimum value: 3136

Example values

  • Image input: {"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"min_pixels": 65536}
  • Video file input: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"min_pixels": 65536}
  • Image list input: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"min_pixels": 65536}

max_pixelsinteger(Optional)

Specifies the maximum pixel threshold for input images or video frames. If the pixel count of an input image or video is within the [min_pixels, max_pixels] range, the model processes the original image. If the pixel count is greater than max_pixels, the image is scaled down until its pixel count is less than or equal to max_pixels. See the supported models and values below.

Value range

  • Image input:
    • qwen4-max: Maximum value: 16777216. When omitted, images are processed according to detail. An explicit max_pixels value applies regardless of vl_high_resolution_images.

    Other models: The value of max_pixels depends on whether the vl_high_resolution_images parameter is enabled.

    • When vl_high_resolution_images is False:

      • qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL: the default value is 2621440, and the maximum value is 16777216
      • qwen3.8-omni-flash, Qwen3.5-Omni: the default value is 1310720, and the maximum value is 16777216
      • Qwen2.5-VL open-source series and QVQ series models: the default value is 1003520, and the maximum value is 12845056
    • When vl_high_resolution_images is True:

      • qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, qwen3.8-omni-flash, Qwen3.7, Qwen3.6, Qwen3.5-Omni, Qwen3.5, Qwen3-VL: max_pixels is invalid. The maximum pixel count for input images is fixed at 16777216.
      • Qwen2.5-VL open source series, and QVQ series models: max_pixels is invalid. The maximum pixel count for input images is fixed at 12845056.
  • Video file or image list input:

    When both min_pixels and max_pixels are set, max_pixels must be greater than or equal to min_pixels.

    • qwen4-max, qwen3-vl-plus, qwen3.5-122b-a10b, qwen3.5-27b, qwen3.5-35b-a3b, qwen3.5-397b-a17b, qwen3.5-flash, qwen3.5-flash-2026-02-23, qwen3.5-omni-flash, qwen3.5-omni-flash-2026-03-15, qwen3.5-omni-plus, qwen3.5-omni-plus-2026-03-15, qwen3.5-plus, qwen3.5-plus-2026-02-15, qwen3.5-plus-2026-04-20, qwen3.6-27b, qwen3.6-35b-a3b, qwen3.6-flash, qwen3.6-flash-2026-04-16, qwen3.6-plus, qwen3.6-plus-2026-04-02, qwen3.7-flash, qwen3.7-flash-2026-07-15, qwen3.7-max-2026-06-08, qwen3.7-plus, qwen3.7-plus-2026-05-26, qwen3.8-27b, qwen3.8-flash, qwen3.8-max, qwen3.8-max-0902, qwen3.8-omni-flash: Default value: 655360. Maximum value: 2048000.
    • Other Qwen3-VL open source models: Default value: 655360. Maximum value: 786432
    • qwen3-omni-flash: Default value: 655360. Maximum value: 786432.
    • kimi-k2.7-code, kimi-k2.6, kimi-k2.5: Maximum 1568000.
    • Qwen2.5-VL open source series, and QVQ series models: Default value: 501760. Maximum value: 602112

Example values

  • Image input: {"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"max_pixels": 8388608}
  • Video file input: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"max_pixels": 655360}
  • Image list input: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"max_pixels": 655360}

total_pixelsinteger(Optional)

The total pixel budget for frames sampled from a video.

Maximum value

  • 268435456: qwen4-max, qwen3.8-max、qwen3.8-max-0902。
  • 234881024:qwen3.7-plus、qwen3.7-plus-2026-05-26、qwen3.7-max-2026-06-08。
  • 819200000:qwen3.8-flash、qwen3.8-27b、qwen3.7-flash、qwen3.7-flash-2026-07-15、qwen3.6-flash。
  • 184549376:qwen3.8-omni-flash。
  • 102760448:kimi-k2.5、kimi-k2.6。

Example values

  • Video file input: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"total_pixels": 134217728}
  • Image list input: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"total_pixels": 134217728}

prompt_cache_breakpoint object (Optional)

Specifies the end of the cached prefix. Supported only by qwen4-max. See Explicit cache.

Properties

mode string (Required)

Only explicit is supported. Pass it explicitly when setting a breakpoint.

cache_controlobject(Optional)

Enables explicit caching. For more information, see Explicit caching.

Properties

type string(Required)

Only ephemeral is supported.

Properties (Qwen4)

Supported only by qwen4-max. Qwen4 content block cache markers also support ttl: 5m or 1h, default 5m. See Explicit cache.

type string (Required)

ephemeral

ttl string (Optional)

Cache TTL. Supports 5m and 1h; defaults to 5m.

rolestring(Required)

The role for the user message. The value is fixed to user.

Assistant Message object(Optional)

The model's reply. It is typically passed back to the model as context in a multi-turn conversation.

Properties

contentstring(Optional)

The text content of the model's reply. When tool_calls is included, content can be empty. Otherwise, content is required.

rolestring(Required)

The role for the assistant message. The value is fixed to assistant.

encrypted_content string

The full encrypted chain of thought, used to restore reasoning in multi-turn conversations.

Applies to summary and encryption mode for qwen4-max. Enable summaries in every request and return previous encrypted content unchanged; summaries cannot replace it. Do not read, truncate, re-encode, modify, or concatenate encrypted content across turns. Thinking summary and encryption

partialboolean(Optional) Default value: false

Specifies whether to enable partial mode.

Valid values:

  • true: Enable.
  • false: Disable.

For a list of supported models, see partial mode.

tool_calls array(Optional)

The information about the tool and its input parameters that the model decides to call. It contains one or more objects and is obtained from the tool_calls field of the previous model response.

Properties

id string(Required)

The ID of the tool call.

type string(Required)

The tool type. Currently, only function is supported.

function object(Required)

Tools and input parameters

Properties

name string(Required)

The tool name.

arguments string(Required)

The input parameter information, as a JSON formatted string.

index integer(Required)

The index of the current tool information in the tool_calls array.

Tool Message object (Optional)

The output information of the tool.

Properties

contentstring(Required)

The output of the tool function, which must be a string. If the tool returns structured data (such as JSON), you must serialize it into a string.

rolestring(Required)

Fixed to tool.

tool_call_idstring(Required)

The id returned after initiating Function Calling, obtained via completion.choices[0].message.tool_calls[$index].id, used to identify the tool corresponding to the Tool Message.

prompt_cache_options object (Optional)

The cache configuration at the top level of the request. Only qwen4-max is supported. The Python SDK passes in top-level non-standard parameters via extra_body; the Node.js SDK and curl pass them in directly. For more information, seeExplicit Cache.

Properties

mode string (Optional)

implicit: Automatically sets cache breakpoints without manual configuration.

explicit: Does not automatically set breakpoints; creating an explicit cache requires manual breakpoints.

ttl string (Optional)

Cache TTL. Supports 5m and 1h; defaults to 5m.

Applies to all cache breakpoints in this request. If the top-level ttl is not set, the ttl in the last cache_control marker is used; if that marker does not set ttl or there are no markers, 5m is used.

streamboolean(Optional) Default value is false

Whether to respond in streaming output mode. Related documentation:Streaming output

Valid values:

  • false: The model generates all content and then returns it at once;
  • true: The model outputs while generating, returning a data chunk (chunk) each time part of the content is generated. You must read these chunks one by one in real time to assemble the complete response.

We recommend setting it to true, which improves the reading experience and reduces the risk of timeouts.

NoteThe maximum timeout for non-streaming calls is no less than 300 seconds; the actual duration varies depending on the deployment region and the model used. If generation is not completed before the timeout, the service will interrupt the request and return the content already generated (instead of returning an error). For scenarios with long outputs, be sure to use streaming calls. For more information, see the timeout description inText Generation Model Overview.

stream_optionsobject(Optional)

The configuration options for streaming output, which take effect only when stream is true.

Properties

include_usageboolean(Optional) Default value is false

Whether to include Token usage information in thelast data chunkof the response.

Valid values:

  • true: Include;
  • false: Exclude.

In streaming output mode, token usage information can only appear in the last chunk of the response.

modalitiesarray (Optional) Default value: ["text"]

The modalities of the output data. This parameter applies only to Qwen-Omni models. Related documentation: Non-realtime (Qwen-Omni)

Valid values:

  • ["text","audio"]: Outputs text and audio, applicable to models that support audio output;
  • ["text"]: Outputs text only.

qwen3.8-omni-flash outputs text only. For examples, see Qwen3.8-Omni-Flash.

audioobject (Optional)

The voice and format of the output audio. This parameter applies to Qwen-Omni models that support audio output, and requires the modalities parameter to be set to ["text","audio"]. Related documentation: Non-realtime (Qwen-Omni)

Properties

voicestring (Required)

The voice of the output audio. For more information, see Non-realtime (Qwen-Omni).

formatstring (Required)

The format of the output audio. Only wav is supported.

temperaturefloat (Optional)

The sampling temperature, which controls the diversity of text generated by the model.

A higher temperature value produces more diverse text, while a lower value produces more deterministic text.

Value range: [0, 2)

MiniMax/MiniMax-M3.1-Flash and MiniMax/MiniMax-M3 use a fixed value of 1.0, and customization is not supported. Other values passed in will not take effect.

Both temperature and top_p can control the diversity of generated text. We recommend setting only one of them. For more information, see Overview.

Default value of temperature

  • qwen4-max: 1.0 in thinking mode, 0.7 in non-thinking mode.

  • qwen3.8-max/qwen3.8-flash (thinking mode): 0.6 for visual understanding, 1.0 for text input. temperature values below 0.6 will be changed to 0.6 by default

  • Qwen3.8-Omni-Flash: 0.6 in thinking mode, 0.7 in non-thinking mode;

  • Qwen3.8 (non-thinking mode), Qwen3.7 (non-thinking mode), Qwen3.6 (non-thinking mode), Qwen3.5-Omni, Qwen3.5 (non-thinking mode), Qwen3 (non-thinking mode), Qwen3-Instruct series, Qwen3-Coder series, qwen-max series, qwen-plus series (non-thinking mode), qwen-flash series (non-thinking mode), qwen open-source series, qwen-coder series, qwen-doc-turbo, Qwen3-VL (non-thinking): 0.7;

  • QVQ series: 0.5;

  • qwen-audio-turbo series: 0.00001;

  • qwen-vl series: 0.01;

  • qwen-math series: 0;

  • Qwen3.7 (thinking mode), Qwen3.6 (thinking mode), Qwen3.5 (thinking mode), Qwen3 (thinking mode), Qwen3-Thinking, Qwen3-Omni-Captioner, QwQ series: 0.6;

  • qwen-long series: 1.0;

  • qwen-plus-character: 0.92

  • qwen3-omni-flash series: 0.9

  • Qwen3-VL (thinking mode): 0.8

  • DeepSeek series (Alibaba Cloud direct): deepseek-v4.1-flash, deepseek-v4-pro: 1.0; deepseek-r1-distill-qwen distilled version: 0.6;

  • DeepSeek series (SiliconFlow direct): siliconflow/deepseek-v3.2, siliconflow/deepseek-v3.1-terminus, siliconflow/deepseek-r1-0528, siliconflow/deepseek-v3-0324: 1.0;

  • DeepSeek series (Kuaishou Wanqing direct): vanchin/deepseek-v3.2-think (thinking mode): 0.6; vanchin/deepseek-v3.1-terminus: 0.7; vanchin/deepseek-v3.2-speciale, vanchin/deepseek-r1, vanchin/deepseek-v3, vanchin/deepseek-ocr: 1.0;

  • Kimi series (Alibaba Cloud direct): kimi-k2.7-code, kimi-k2.6 (thinking mode), kimi-k2.5 (thinking mode): 1.0; kimi-k2.6 (non-thinking mode), kimi-k2.5 (non-thinking mode): 0.6;

  • Kimi series (Moonshot direct): kimi/kimi-k3, kimi/kimi-k3.1-pro, kimi/kimi-k3.1-pro-highspeed, kimi/kimi-k2.7-code-highspeed, kimi/kimi-k2.7-code, kimi/kimi-k2.6 (thinking mode), kimi/kimi-k2.5 (thinking mode): 1.0; kimi/kimi-k2.6 (non-thinking mode), kimi/kimi-k2.5 (non-thinking mode): 0.6;

  • GLM series (Alibaba Cloud direct): glm-5.1, glm-5: 1.0;

  • GLM series (Zhipu direct): ZHIPU/GLM-5.1, ZHIPU/GLM-5: 0.6;

  • MiniMax series (Alibaba Cloud direct): MiniMax-M2.5: 1.0;

  • MiniMax series (Xiyu Technology direct): MiniMax/MiniMax-M3.1-Flash, MiniMax/MiniMax-M3, MiniMax/MiniMax-M2.7, MiniMax/MiniMax-M2.5, MiniMax/MiniMax-M2.1: 1.0.

  • MiMo series (Xiaomi direct): mimo-v2.5-pro: 1.0, range [0, 1.5]; xiaomi/mimo-v2.6-pro-ultraspeed: 1.0, customization not supported, other values passed in will still take effect as 1.0.

It is not recommended to change the default temperature value of QVQ models.

top_pfloat (Optional)

The probability threshold for nucleus sampling, which controls the diversity of text generated by the model.

A higher top_p value produces more diverse text, while a lower value produces more deterministic text.

Value range: (0,1.0]

MiniMax/MiniMax-M3.1-Flash and MiniMax/MiniMax-M3 use a fixed value of 0.95, and customization is not supported. Other values passed in will not take effect.

Both temperature and top_p can control the diversity of generated text. We recommend setting only one of them. For more information, see Overview.

Default value of top_p

  • qwen4-max: 0.95 in thinking mode, 0.8 in non-thinking mode.

The following models in non-thinking mode (qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b), Qwen3.7 (non-thinking mode), Qwen3.6 (non-thinking mode), Qwen3.5-Omni, Qwen3.5 (non-thinking mode), Qwen3 (non-thinking mode), Qwen3-Instruct series, Qwen3-Coder series, qwen-max series, qwen-plus series (non-thinking mode), qwen-flash series (non-thinking mode), Qwen 2.5 open-source series, qwen-coder series, qwen-long, qwen-doc-turbo, Qwen3-VL (non-thinking): 0.8;

Qwen3.8-Omni-Flash: 0.95 in thinking mode, 0.8 in non-thinking mode;

QVQ series: 0.5;

qwen-math series and Qwen3-Omni-Flash series: 1.0;

The following models in thinking mode (qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b), Qwen3.7 (thinking mode), Qwen3.6 (thinking mode), Qwen3.5 (thinking mode), Qwen3 (thinking mode), Qwen3-VL (thinking mode), Qwen3-Thinking, QwQ series, Qwen3-Omni-Captioner, qwen-plus-character: 0.95

DeepSeek series (directly provided by Alibaba Cloud): deepseek-v4-pro and deepseek-r1-distill-qwen distillation models: 0.95;

DeepSeek series (directly provided by SiliconFlow): siliconflow/deepseek-v3.2, siliconflow/deepseek-v3.1-terminus, siliconflow/deepseek-r1-0528, siliconflow/deepseek-v3-0324: 1.0;

DeepSeek series (directly provided by Kuaishou Wanqing): vanchin/deepseek-v3.2-think, vanchin/deepseek-v3.1-terminus: 0.95; vanchin/deepseek-v3.2-speciale: 0.9; vanchin/deepseek-r1: 0.8; vanchin/deepseek-v3, vanchin/deepseek-ocr: 1.0;

Kimi series (directly provided by Alibaba Cloud): kimi-k2.7-code, kimi-k2.6, kimi-k2.5: 0.95;

Kimi series (directly provided by Moonshot AI): kimi/kimi-k3, kimi/kimi-k3.1-pro, kimi/kimi-k3.1-pro-highspeed, kimi/kimi-k2.7-code-highspeed, kimi/kimi-k2.7-code, kimi/kimi-k2.6, kimi/kimi-k2.5: 0.95;

GLM series (directly provided by Alibaba Cloud): 0.95;

GLM series (directly provided by Zhipu AI): ZHIPU/GLM-5.1, ZHIPU/GLM-5: 0.95;

MiniMax series (directly provided by Alibaba Cloud): MiniMax-M2.5: 0.95;

MiniMax series (directly provided by Xiyu Technology): MiniMax/MiniMax-M3.1-Flash, MiniMax/MiniMax-M3: 0.95; MiniMax/MiniMax-M2.7, MiniMax/MiniMax-M2.5, MiniMax/MiniMax-M2.1: 0.9.

MiMo series (directly provided by Xiaomi): xiaomi/mimo-v2.5-pro: 0.95, range [0.01, 1.0]; xiaomi/mimo-v2.6-pro-ultraspeed: 0.95, custom values are not supported, and any other value passed in still takes effect as 0.95.

We do not recommend changing the default top_p value of QVQ models.

top_kinteger (optional)

The number of candidate tokens used for sampling during generation. The larger the value, the more random the output; the smaller the value, the more deterministic the output. If set to null or greater than 100, the top_k strategy is disabled and only the top_p strategy takes effect. The value must be an integer greater than or equal to 0.

top_k default value

QVQ series: 10;

QwQ series: 40;

qwen-math series and qwen-audio-turbo series: 1;

Qwen3-Omni-Flash series: 50;

All other models: 20.

GLM series (directly provided by Alibaba Cloud): 20;

The DeepSeek/Kimi/MiniMax series do not support the top_k parameter.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. The configuration method is: extra_body={"top_k":xxx}.

We do not recommend changing the default top_k value of QVQ models.

repetition_penaltyfloat (optional)

The degree of repetition in consecutive sequences during model generation. Increasing repetition_penalty can reduce the repetitiveness of model-generated content, and 1.0 means no penalty. There is no strict value range; it just needs to be greater than 0.

repetition_penalty default value

  • qwen4-max, qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, qwen-max, qwen-math series, qwen-audio-turbo series, QVQ series, QwQ series, Qwen3-VL: 1.0;
  • qwen-coder series, qwen2-1.5b-instruct, qwen2-0.5b-instruct: 1.1;
  • For other models: 1.05.
  • GLM series (directly provided by Alibaba Cloud): 1.0;
  • Kimi series (directly provided by Moonshot AI): 0.0.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. Configuration: extra_body={"repetition_penalty":xxx}.

We do not recommend changing the default repetition_penalty value of QVQ models.

frequency_penalty float (Optional)

Applies a penalty based on the number of times a Token has already appeared, to adjust the generation of repeated content. Supported on qwen4-max.

presence_penalty float (Optional)

Controls the content repetition of text generated by the model.

Value range: [-2.0, 2.0]. A positive value reduces repetition, while a negative value increases it.

For scenarios that require diversity, fun, or creativity, such as creative writing or brainstorming, we recommend increasing this value; for scenarios that emphasize consistency and terminology accuracy, such as technical documentation or formal text, we recommend decreasing this value.

presence_penalty default value

The following models in non-thinking mode (qwen4-max, qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b), Qwen3.7 (non-thinking mode), Qwen3.6 (non-thinking mode), Qwen3.5-Omni, Qwen3.5 (non-thinking mode), Qwen3 (non-thinking mode), Qwen3-Instruct series/1.7b/4b (thinking mode), QVQ series, qwen-max, qwen2.5-vl series, Qwen3-VL (non-thinking): 1.5;

Qwen3.8-Omni-Flash: 0.0 in thinking mode, and 1.5 in non-thinking mode;

qwen-plus/qwen-plus-latest/2025-04-28 (thinking mode), qwen-turbo-2025-04-28 (thinking mode): 0.5;

All others: 0.0.

DeepSeek series (directly provided by Alibaba Cloud): deepseek-r1-distill-qwen distilled version: 1;

Kimi series (directly provided by Alibaba Cloud): kimi-k2.7-code, kimi-k2.6, kimi-k2.5: 0.0;

Kimi series (directly provided by Moonshot AI): 0.0;

MiniMax series (directly provided by Alibaba Cloud): MiniMax-M2.5: 0.0;

Other DeepSeek/Kimi/GLM/MiniMax models have no default value.

How it works

If the parameter value is positive, the model applies a penalty to Tokens that already exist in the current text (the penalty is independent of the number of times the text appears), reducing the probability of these Tokens appearing repeatedly, thereby reducing content repetition and increasing word diversity.

Examples

Prompt: Translate this sentence into Chinese "This movie is good. The plot is good, the acting is good, the music is good, and overall, the whole movie is just good. It is really good, in fact. The plot is so good, and the acting is so good, and the music is so good."

Parameter value is 2.0: This movie is great. The plot is excellent, the acting is superb, and the music is delightful. Overall, the whole movie is absolutely fantastic. In fact, it's truly remarkable. The plot is marvelous, the acting is outstanding, and the music is equally enchanting.

Parameter value is 0.0: This movie is good. The plot is good, the acting is good, and the music is also good. Overall, the whole movie is good. In fact, it's really great. The plot is very good, the acting is very impressive, and the music is equally excellent.

Parameter value is -2.0: This movie is good. The plot is good, the acting is good, and the music is also good. Overall, the whole movie is good. In fact, it's really great. The plot is very good, the acting is also very good, and the music is also very good.

We do not recommend changing the default presence_penalty value of QVQ models.

response_formatobject (Optional) Default value: {"type": "text"}

The format of returned content. Valid values:

  • {"type": "text"}: Outputs a text response;
  • {"type": "json_object"}: Outputs a JSON string in standard format.
  • {"type": "json_schema", "json_schema": {...}}: Outputs a JSON string that strictly conforms to the specified JSON Schema, allowing precise control over the output structure and field types.

Related documentation: Structured output. json_object and json_schema support different models. For more information, see Supported models.

If {"type": "json_object"} is specified, you must explicitly instruct the model to output JSON in the prompt, for example, "Please output in JSON format"; otherwise an error will occur. If {"type": "json_schema", ...} is specified, the prompt does not need to include the JSON keyword.

Properties

typestring(Required)

The format of returned content. Valid values:

  • text: outputs a text reply;
  • json_object: outputs a JSON string in standard format;
  • json_schema: outputs a JSON string that strictly conforms to the structure defined by the json_schema field.

json_schemaobject (Optional)

Required when type is json_schema. It defines the JSON structure that the model output must follow. Related documentation: Obtain output in a specified format.

When calling through the parse method of the OpenAI SDK, you can directly pass in a Python Pydantic class or a Node.js Zod object, and the SDK will automatically convert it to a JSON Schema without manual construction.

Properties

namestring(Required)

The name of the schema.

schemaobject(Required)

The JSON Schema object that describes the output structure. Use properties to define the field structure, required to declare the list of required fields, and additionalProperties to control whether fields not defined in the schema are allowed in the output (setting it to false is recommended, that is, only output defined fields). Supported data types: string, number, integer, boolean, object, array, and enum. Related documentation: Configuration guide.

strictboolean (Optional)

Whether to strictly follow the structure defined by schema. Setting it to true is recommended.

max_tokensinteger (Optional, to be deprecated soon )

This parameter will be deprecated soon. For new integrations, use max_completion_tokens.

The meaning of this parameter varies by model, as follows:

  • qwen4-max, deepseek-v4.1-flash, deepseek-v4-pro, deepseek-v4-pro-0813, deepseek-v4-flash-0731: the maximum number of tokens for the sum of the model answer and the chain-of-thought content. max_tokens is equivalent to max_completion_tokens. When the model output exceeds this value, generation will stop early, and the returned finish_reason is length. Among these models, deepseek-v4.1-flash ignores the thinking_budget parameter.
  • glm-5.3: max_tokens is the maximum number of tokens for the sum of the model answer and the chain-of-thought content. When the model output exceeds this value, generation will stop early, and the returned finish_reason is length. glm-5.3 ignores the thinking_budget parameter.
  • glm-5.2: when the thinking_budget parameter is not passed in, max_tokens is the maximum number of tokens for the sum of the model answer and the chain-of-thought content. When the model output exceeds this value, generation will stop early, and the returned finish_reason is length; when the thinking_budget parameter is passed in, max_tokens is only the maximum number of tokens for the model answer, and the number of tokens for the chain-of-thought part is controlled separately by thinking_budget.
  • Other models: the maximum number of tokens for the model answer (excluding the chain-of-thought). If the generated content exceeds this value, generation will stop early, and the returned finish_reason is length.

The default and maximum values of GLM models are shown in the following table. For other models, both the default and maximum values are the maximum output length of the model.

Supply methodModelDefault valueMaximum value
Alibaba Cloud direct supplyglm-5.3, glm-5.2, glm-5.2-fast-preview, glm-5.1, glm-565536131072
Zhipu direct supplyZHIPU/GLM-5.3, ZHIPU/GLM-5.3-Flash, ZHIPU/GLM-5.3-FlashX, ZHIPU/GLM-5.2, ZHIPU/GLM-5.1, ZHIPU/GLM-565536131072

max_completion_tokensinteger (Optional)

The maximum length of the model output, including the chain-of-thought and the model answer. When the model output exceeds this value, generation will stop early, and the returned finish_reason is length.

When thinking mode is enabled, if the chain-of-thought consumes the entire budget, the answer content (content) may be empty and finish_reason is length. Reserve enough output space for the answer.

For the default and maximum values of GLM models, see the table in the max_tokens parameter. For other models, both the default and maximum values are the maximum output length of the model.

Difference from max_tokens: max_completion_tokens always limits the complete model output (chain-of-thought + answer); the specific limit scope of max_tokens varies by model and thinking_budget settings, as described above. For thinking models, using max_completion_tokens is recommended.

The following models are supported:

  • Qwen Max: Qwen3.7-Max and later models
  • Qwen Plus: Qwen3.5-Plus and later models
  • Qwen Flash: Qwen3.5-Flash and later models
  • Kimi: Kimi models released from kimi-k2.5 onwards
  • GLM: the Alibaba Cloud direct supply and Zhipu direct supply models listed in the table above
  • MiniMax: MiniMax models released from MiniMax-M2.5 onwards
  • DeepSeek: DeepSeek models released from deepseek-v4-pro onwards

Apart from the Zhipu direct supply GLM models listed in the table above, the models above do not include other third-party direct supply models.

There can be a discrepancy of up to 10 tokens between the actual number of output tokens and the configured max_completion_tokens value.

vl_high_resolution_imagesboolean (Optional) The default value is false

Whether to raise the pixel limit of input images to the pixel value corresponding to 16384 tokens. Related documentation: Process high-resolution images.

For qwen4-max, even if vl_high_resolution_images=true, the explicitly passed-in max_pixels still takes effect.

  • For models other than qwen4-max, vl_high_resolution_images:true uses the fixed resolution strategy, ignores the max_pixels setting, and when the resolution exceeds this limit, the total number of image pixels is scaled down to within this limit.

    Click to view the pixel limits of each model

    When vl_high_resolution_images is True, pixel limits vary by model:

    • qwen3.8-flash, qwen3.8-omni-flash, Qwen3.7 series, Qwen3.6 series, Qwen3.5 series, and Qwen3-VL series models: 16777216 (each Token corresponds to 32*32 pixels, that is, 16384*32*32)
    • QVQ series and other Qwen2.5-VL series models: 12845056 (each Token corresponds to 28*28 pixels, that is, 16384*28*28)
  • When vl_high_resolution_images is false, the pixel limit is determined by max_pixels; if the pixels of an input image exceed max_pixels, the image will be scaled down to within max_pixels. The default pixel limit of each model is the default value of max_pixels.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. Configuration: extra_body={"vl_high_resolution_images":xxx}.

ninteger (Optional) Default value: 1

The number of responses to generate, with a value range of 1-4. Suitable for scenarios that require multiple candidate responses, such as creative writing or advertising copy.

n=0 is equivalent to n=1.

Qwen3-series models and the Plus, Max, and Flash series in non-thinking mode, as well as qwen-plus-character, support n greater than 1. MiniMax/MiniMax-M3.1-Flash and MiniMax/MiniMax-M3 only support n=1. kimi/kimi-k3.1-pro and kimi/kimi-k3.1-pro-highspeed do not support this parameter.

If the tools parameter is passed, set n to 1.

Increasing n increases output Token consumption, but not input Token consumption.

enable_thinking boolean (Optional)

The default value of kimi-k3.1-pro (deployed on Alibaba Cloud Model Studio) is true; it can be set to false to disable thinking, but it is strongly recommended to keep it enabled, as disabling it significantly affects the output quality.

Whether to enable thinking mode when using hybrid thinking models (which may or may not think before responding). Applicable to Qwen4, Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5, Qwen3, Qwen3.8-Omni-Flash, Qwen3-Omni-Flash, and Qwen3-VL models, as well as DeepSeek-V4.1-Flash, the DeepSeek-V4-Pro/V4-Flash series (directly provided by Alibaba Cloud), the DeepSeek-V3.2/V3.2-exp/V3.1 series (directly provided by Alibaba Cloud, SiliconFlow, or Kuaishou Wanqing), Kimi-K2.7-code (thinking-only model), the Kimi-K2.6/K2.5 series (directly provided by Alibaba Cloud or Moonshot AI), and the GLM series. The DeepSeek-V4 series enables thinking by default, and the reasoning effort can be adjusted with the reasoning_effort parameter.

Valid values:

  • true: Enable

    When enabled, the thinking content is returned through the reasoning_content field.

  • false: Disable

Default values for different models: Supported models

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. Configuration: extra_body={"enable_thinking": xxx}.

If you do not use the OpenAI SDK and instead call directly via HTTP (for example, curl), extra_body is not needed; simply place enable_thinking at the top level of the request body (body), just like parameters such as model and messages, for example "enable_thinking": true.

MiniMax/MiniMax-M3.1-Flash and MiniMax/MiniMax-M3, directly provided by Xiyu Technology, do not use this parameter; use the thinking parameter instead.

thinking object (Optional) Default value: {"type":"adaptive"}

Controls the thinking mode of MiniMax models directly provided by Xiyu Technology.

Optional values of thinking.type:

  • adaptive: Enable thinking. MiniMax/MiniMax-M3.1-Flash always uses this mode; MiniMax/MiniMax-M3 uses this mode by default.
  • disabled: Disable thinking, supported only by MiniMax/MiniMax-M3. MiniMax/MiniMax-M3.1-Flash returns a 400 error when this value is set.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. Configuration: extra_body={"thinking": {"type": "adaptive"}}.

reasoning_split boolean (Optional)

Controls where the thinking content of MiniMax is returned:

  • true: Returned separately through the reasoning_content field. MiniMax/MiniMax-M3.1-Flash only supports this value.
  • false: Returned in the content field with the <think> tag. Only MiniMax/MiniMax-M3 supports this value.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object, for example extra_body={"reasoning_split": True}.

thinking_display string (Optional)

The format of returned reasoning. Full plaintext is returned by default; enabling summaries returns a display summary and the full encrypted content for restoring previous reasoning.

For qwen4-max, set "summarized" to enable summaries. Chain-of-thought summary and encryption

preserve_thinking boolean (optional)

Controls whether reasoning_content from earlier assistant messages is included in the current request. Retained reasoning is billed as input tokens. On models that support switching, true includes this reasoning and false excludes it.

  • To preserve reasoning, send each earlier assistant message in full in messages. Keep its reasoning in reasoning_content. Appending it to content is unsupported. Pass reasoning between turns
  • The Max, Plus, Flash (excluding Omni), and Kimi models listed below accept earlier messages without reasoning_content even when this parameter is enabled.
  • With the OpenAI Python SDK, pass this extension using extra_body={"preserve_thinking": True}.

Supported models

Family or providerModel IDsDefault
Qwen4 / Qwen3.8qwen4-max, qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-omni-flashtrue
Qwen3.7 / Qwen3.6qwen3.7-max, qwen3.7-max-2026-05-20 and later snapshots, qwen3.7-plus, qwen3.7-plus-2026-05-26, qwen3.7-flash, qwen3.7-flash-2026-07-15
qwen3.6-plus, qwen3.6-plus-2026-04-02, qwen3.6-flash, qwen3.6-flash-2026-04-16
false
Kimi (Alibaba Cloud Model Studio)kimi-k2.7-code, kimi-k3.1-pro, kimi-k3true¹
Kimi (Alibaba Cloud Model Studio)kimi-k2.6false
Kimi (direct from Moonshot AI)kimi/kimi-k2.7-code, kimi/kimi-k2.7-code-highspeedtrue
Kimi (direct from Moonshot AI)kimi/kimi-k3.1-pro, kimi/kimi-k3.1-pro-highspeedfalse

¹ These models retain reasoning even with false. To exclude it, omit reasoning_content when sending earlier assistant messages.

thinking_budget integer (Optional)

The maximum number of tokens for the thinking process. Applicable to qwen4-max, qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, as well as the Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen3, GLM (directly provided by Alibaba Cloud), and Kimi (directly provided by Alibaba Cloud) series models. kimi-k3.1-pro and kimi-k3 do not support this parameter. Related documentation: Limiting thinking length. Default value: 131072 (qwen4-max). deepseek-v4.1-flash ignores this parameter; setting it has no effect.

Other models: The default value for the models above is the maximum chain-of-thought length of the model. For more information, see Models.

This parameter is not a standard OpenAI parameter. When calling via the Python SDK, put it in the extra_body object. Configuration: extra_body={"thinking_budget": xxx}.

Important: qwen4-max, qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, qwen3.6-flash, and qwen3.8-omni-flash do not support setting thinking_budget and reasoning_effort at the same time. You can use only one of them in a request; setting both causes an error. For the valid values and mappings, see the reasoning_effort parameter in this topic.

use_multichannel boolean (Optional)

Controls whether to parse spatial information in multichannel audio. Applicable to audio input of qwen3.8-omni-flash. The default value is false, and all audio is parsed as single-channel. When set to true and the input is two-channel (left and right) or four-channel (FOA, WYZX order) audio, the spatial audio information is parsed. In HTTP requests, put it at the top level of the request body; when using the OpenAI Python SDK, pass it in via extra_body={"use_multichannel": True}.

reasoning_effort string (Optional)

Controls the model's reasoning effort. Different models support different optional values and default values.

qwen4-max

Default value: reasoning_effort=high.

reasoning_effortActual level
minimal, lowlow
medium, highhigh
xhigh, maxxhigh
noneDisable thinking

qwen4-max does not support setting reasoning_effort and thinking_budget at the same time. thinking_budget must be a positive integer and cannot be set to 0.

When only thinking_budget is set, the thinking level is determined according to the table below, and the passed-in budget value is retained.

thinking_budgetActual level
1–4096low
4097–131072high
131073–262144xhigh

When neither is set, high and 131072 are used.

kimi-k3.1-pro (Alibaba Cloud Model Studio deployment) (default value: max)

  • max (default): Deep reasoning
  • high: Enhanced reasoning
  • medium: Moderate reasoning
  • low: Light reasoning

MiniMax/MiniMax-M3.1-Flash (default value: max)

Optional values, ordered from low to high reasoning effort, are low, medium, high, xhigh, and max. The model always has thinking enabled; setting none returns a 400 error.

DeepSeek-V4 and GLM series (default value: high)

Valid values:

  • high: high-effort reasoning
  • max: maximum-effort reasoning

low and medium are mapped to high, and xhigh is mapped to max.

Applies to glm-5.2, glm-5.1, glm-5, and deepseek-v4-pro (provided directly by Alibaba Cloud)

kimi/kimi-k3, kimi/kimi-k3.1-pro, kimi/kimi-k3.1-pro-highspeed (provided directly by Moonshot) (default value: max, only max is supported)

Valid values:

  • max: maximum-effort reasoning

glm-5.3, ZHIPU/GLM-5.4, ZHIPU/GLM-5.3, ZHIPU/GLM-5.3-Flash, ZHIPU/GLM-5.3-FlashX, and kimi-k3 (provided directly by Alibaba Cloud) models: default value ismax

Valid values:

  • max (default): deep reasoning
  • high: enhanced reasoning
  • low: light reasoning

The glm-5.3 series models always have thinking enabled: enable_thinking only supports true, and passing false will cause the API request to fail; kimi-k3 supports passing false to disable thinking.

deepseek-v4-flash-0731 and deepseek-v4-pro-0813 models: default value ishigh

Valid values:

  • max: maximum-effort reasoning
  • high (default): high-effort reasoning
  • low: low-effort reasoning

For compatibility, medium is mapped to high, and xhigh is mapped to high.

deepseek-v4.1-flash model: default value ishigh

Valid values:

  • max: maximum-effort reasoning
  • high (default): high-effort reasoning
  • low: low-effort reasoning

minimal is mapped to low, medium and xhigh are mapped to high, and ultra is mapped to max.

qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, qwen3.6-flash: default value isxhigh

reasoning_effortActual level
minimal, lowlow
mediummedium
high, xhigh, maxxhigh
noneDisable thinking

Setting a value other than the above valid values will cause an error.

Important:qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-2.4t-a95b, qwen3.8-27b, and qwen3.6-flash do not support setting reasoning_effort and thinking_budget at the same time; setting both will cause an error. However, the two parameters support conversion between each other:

  • When thinking_budget is not set, the reasoning_effort level is automatically mapped to thinking_budget: low corresponds to 4096, medium corresponds to 16384, and xhigh corresponds to 262144.
  • When reasoning_effort is not set, thinking_budget is automatically mapped back to reasoning_effort: 0~4096 corresponds to low, 4097~16384 corresponds to medium, and 16385~262144 corresponds to xhigh.
  • When neither is set, the default thinking_budget (131072) and the default reasoning_effort (xhigh) are used.
Qwen3.8-Omni-Flash

qwen3.8-omni-flash has thinking enabled by default, and reasoning_effort defaults to xhigh. The reasoning_effort of Chat Completions accepts none, minimal, low, medium, high, xhigh, and max, and cannot be set together with thinking_budget. For the parameter location and examples, see Qwen3.8 Omni.

You can directly select one of the three thinking effort levels: low, medium, and xhigh. Among compatible values, minimal is mapped to low, high and max are mapped to xhigh, and none means disabling thinking.

tool_stream boolean (optional) default value is false

Only takes effect when stream=true is set. Currently, only the Qwen and GLM series are supported.

Qwen series support list:
  • qwen-max series: qwen4-max, the qwen3.8-max series, and the text modality of the qwen3.7-max series
  • qwen-plus series: the text modality of the qwen3.7-plus and qwen3.6-plus series, as well as the omni modality of the qwen3.5-plus series
  • qwen-flash series: the omni modality of the qwen3.8-flash, qwen3.7-flash, qwen3.6-flash, and qwen3.5-flash series
Qwen series usage reference:

tool_stream only affects cases with complex tool parameters. Ordinary tool parameters are streamed as long as stream=true is set. A complex tool refers to a tool whose definition contains parameters of the array or object type.

  • tool_stream=false: Complex tool parameters are output all at once, which is the default behavior, and complex formats are more accurate.
  • tool_stream=true: Complex tool parameters are streamed, and complex formats have no timeout risk.

GLM series supported list: glm-5, glm-5.1 (directly provided by Alibaba Cloud).

GLM series usage reference:
  • tool_stream=false: Tool parameters are output all at once, which is the default behavior, and complex formats are more accurate.
  • tool_stream=true: Tool parameters are streamed, and complex formats have no timeout risk.

This parameter is not a standard OpenAI parameter. When calling via the Python SDK, put it in the extra_body object. The configuration method is: extra_body={"tool_stream": true}.

enable_code_interpreter boolean (Optional) The default value is false

Whether to enable the code interpreter feature. Related documentation: Code interpreter

Valid values:

  • true: Enable
  • false: Do not enable

This parameter is not a standard OpenAI parameter. When calling via the Python SDK, put it in the extra_body object. The configuration method is: extra_body={"enable_code_interpreter": xxx}.

seedinteger(Optional)

Random number seed. Used to ensure that the generated results are reproducible with the same input and parameters. If the same seed is passed with other parameters unchanged, the model will return the same result as much as possible.

Value range: [0,2 31 −1].

Default value of seed

For all other models, it is 1234.

logprobs boolean (Optional) The default value is false

Whether to return the log probabilities of output tokens. Valid values:

  • true

    Return

  • false

    Do not return

Content generated during the thinking phase (reasoning_content) does not return log probabilities.

Supported models

  • Snapshot models of the qwen-plus series (excluding stable models)

  • qwen3-vl-plus series models (including stable models)

  • Qwen3 open-source models

  • qwen4-max

top_logprobs integer (Optional) The default value is 0

Specifies the number of candidate tokens with the highest probabilities returned by the model at each generation step.

Value range: [0,5]

Only takes effect when logprobs is true.

stopstring or array(Optional)

Used to specify stop words. When the string or token_id specified by stop appears in the text generated by the model, generation stops immediately.

MiniMax/MiniMax-M3.1-Flash does not support this parameter. If passed, the output will not be truncated at the specified stop word; the request may still succeed and return finish_reason: "stop", but this does not indicate that the specified stop word has taken effect.

You can pass sensitive words to control the model's output.

When stop is an array, you cannot pass both token_id and strings as elements. For example, you cannot specify ["hello",104307].

toolsarray(Optional)

An array containing one or more tool objects for the model to call during Function Calling. For more information, see Function Calling.

When tools is set and the model determines that a tool call is required, the response returns the tool information via tool_calls.

Properties

typestring(Required)

The tool type. Currently, only function is supported.

functionobject(Required)

Properties

namestring(Required)

The tool name. Only letters, digits, underscores (_), and hyphens (-) are allowed, with a maximum length of 64 tokens.

descriptionstring(Required)

The description of the tool, which helps the model determine when and how to call the tool.

parametersobject(Optional)The default value is {}

The parameter description of the tool, which must be a valid JSON Schema. For more information about JSON Schema, see link. If the parameters parameter is empty, it indicates that the tool has no input parameters (such as a time query tool).

To improve the accuracy of tool calling, we recommend that you pass in parameters.

tool_choice string or object(Optional)The default value is auto

The tool selection policy. If you need to force a specific tool calling behavior for certain types of questions (for example, always using a specific tool or disabling all tools), you can set this parameter.

MiniMax/MiniMax-M3.1-Flash only supports auto. Other values such as none, required, or a specified function name may cause errors or not take effect; specifying a function name does not guarantee that the model will call that function.

deepseek-v4.1-flash-1017 supports setting tool_choice to auto, none, required, or a specified function name.

Valid values:

  • auto

    The model selects the tool strategy autonomously.

  • none

    If you do not want to perform tool calling, set the tool_choice parameter to none;

  • required

    If you want to force at least one tool to be called, set the tool_choice parameter to required, and the model will always return tool calling information.

    Qwen series models do not currently support required: in non-thinking mode, tool calling cannot be guaranteed; in thinking mode, required is not currently supported.

  • {"type": "function", "function": {"name": "the_function_to_call"}}

    If you want to force a specific tool to be called, set the tool_choice parameter to {"type": "function", "function": {"name": "the_function_to_call"}}, where the_function_to_call is the specified tool function name.

    Models in thinking mode do not support forcing a specific tool to be called.

parallel_tool_calls boolean (Optional)The default value is true

Whether to enable parallel tool calls. For more information, see Parallel tool calling.

MiniMax/MiniMax-M3.1-Flash and kimi-k3 do not support controlling the parallelism of tool calls via this parameter. Setting it to false does not guarantee serial calls, and the model may still return multiple tool_calls in a single round. Handle the actual returned results accordingly.

kimi/kimi-k3.1-pro and kimi/kimi-k3.1-pro-highspeed do not support this parameter.

Valid values:

  • true: Enable
  • false: Do not enable

enable_search boolean(Optional)The default value is false

Whether to enable web search. kimi-k3.1-pro (deployed on Alibaba Cloud Model Studio) supports this parameter, which is applicable to Beijing, Singapore, United States (Virginia), Germany (Frankfurt), Japan (Tokyo), and Hong Kong (China). For more information, see Web search.

Valid values:

  • true: enabled;

    If web search is not performed after being enabled, you can optimize the prompt, or set the forced_search parameter in search_options to enable forced search.

  • false: disabled.

Enabling web search may increase token consumption.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. Configuration: extra_body={"enable_search": True}.

search_optionsobject (optional)

The strategy for web search. Related documentation: Web search

Properties

forced_search boolean (optional) Default value: false

Whether to force web search. Only takes effect when enable_search is true.

Valid values:

  • true: Force enable;
  • false: Not forced; the model decides whether to use web search.

search_strategy string (optional) Default value: turbo

Search volume strategy. Only takes effect when enable_search is true.

When qwen3.8-omni-flash enables web search, set this parameter to agent.

Valid values:

  • turbo (default): Balances response speed and search quality, suitable for most scenarios.

  • max: Adopts a more comprehensive search strategy and can call multiple search engines to obtain more detailed search results, but the response time may be longer.

  • agent: Can call web search tools and large models multiple times to achieve multi-round information retrieval and content integration.

    This strategy only applies to qwen3.5-plus, qwen3.5-plus-2026-02-15, qwen3.5-flash, qwen3.5-flash-2026-02-23, qwen3.8-omni-flash, qwen3.5-omni-plus, qwen3.5-omni-plus-2026-03-15, qwen3.5-omni-flash, and qwen3.5-omni-flash-2026-03-15.

enable_search_extension boolean (optional) Default value: false

Whether to enable vertical-domain search. Only takes effect when enable_search is true.

Valid values:

  • true: Enable.
  • false: Do not enable.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. Configuration: extra_body={"search_options": xxx}.

include_tool_usage boolean (optional) Default value: false

Whether to return web search invocation statistics in the usage of the response.

Valid values:

  • true: Return the x_tools field in usage.
  • false: Not returned.

x_tools is returned only when this request actually triggers web search. If enable_search is not enabled, or the model determines that web search is unnecessary, this field is not returned even if this parameter is set to true.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. Configuration: extra_body={"include_tool_usage": True}.

X-DashScope-DataInspectionstring (optional)

Based on the content security capabilities of the Qwen API, whether to further identify non-compliant information in input and output content. Values:

  • '{"input":"cip","output":"cip"}': Further identify;
  • Not setting this parameter: No further identification.

When calling via HTTP, put it in the request header: -H "X-DashScope-DataInspection: {\"input\": \"cip\", \"output\": \"cip\"}";

When calling through the Python SDK, configure it via extra_headers: extra_headers={'X-DashScope-DataInspection': '{"input":"cip","output":"cip"}'}.

For detailed usage, see Input and output AI safety guardrails; if you do not want to modify the calling code, you can enable the guardrail through the workspace-level switch.

Not supported via the Node.js SDK.

skillarray (optional)

Skill parameter, used to enable specific generation skills (such as PPT generation). Only supported by the qwen-doc-turbo model. For detailed usage, see Generate PPT.

This parameter is not an OpenAI standard parameter. When calling through the Python SDK, put it in the extra_body object. Configuration: extra_body={"skill": [...]}.

When using skill, stream must be set to true.

Properties

typestring(Required)

Skill type. Currently supported:

  • ppt: PPT generation.

modestring (Optional)

PPT generation mode. Valid values:

  • general (default): Template mode, which must be used with template_id to generate PPTs in HTML format.
  • creative: Creative mode, which does not require a template and generates slide-image PPTs (each page is an image).

template_idstring(Optional)

PPT template ID. Used together when mode is general or mode is not set. Valid values:

  • news_01: News template
  • summary_01: Summary template
  • internet_01: Internet template
  • thesis_01: Thesis template

clear_thinkingboolean(Optional) Default value: false

Controls whether reasoning_content (thinking process) from historical turns is included as context input to the model in multi-turn conversations. Only supported by GLM series models glm-5.3, glm-5.2, glm-5.1, and glm-5. The default value is true for glm-5.3 and false for the other models.

This parameter is not an OpenAI standard parameter. When called via the Python SDK, put it in the extra_body object. Configuration method: extra_body={"enable_thinking": True,"clear_thinking": True}.

  • true: Ignores reasoning_content from historical turns and uses only non-reasoning content such as visible text, tool calls, and results as context input, reducing context length and cost.
  • false (default): Retains reasoning_content from historical turns and provides it to the model along with the context. To enable Preserved Thinking, you must pass the historical reasoning_content in messages completely, unmodified, and in the original order. Missing, truncated, rewritten, or reordered content will degrade the effect or prevent it from working.

Text input

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    # 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    model="qwen4-max",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "你是谁?"},
    ]
)
print(completion.model_dump_json())
// 该代码 OpenAI SDK 版本为 2.6.0
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public class Main {
    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
                .build();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                .addUserMessage("你是谁")
                .model("qwen4-max")
                .build();

        try {
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            System.out.println(chatCompletion);
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen4-max",  //此处以qwen4-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "你是谁?" }
        ],
    });
    console.log(JSON.stringify(completion))
}

main();
package main

import (
	"context"
	"os"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
)

func main() {
	client := openai.NewClient(
		option.WithAPIKey(os.Getenv("DASHSCOPE_API_KEY")),
		option.WithBaseURL("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"),
	)
	chatCompletion, err := client.Chat.Completions.New(
		context.TODO(), openai.ChatCompletionNewParams{
			Messages: []openai.ChatCompletionMessageParamUnion{
				openai.UserMessage("你是谁"),
			},
			Model: "qwen4-max",
		},
	)

	if err != nil {
		panic(err.Error())
	}

	println(chatCompletion.Choices[0].Message.Content)
}
using System.Net.Http.Headers;
using System.Text;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        // 若没有配置环境变量,请用百炼API Key将下行替换为:string? apiKey = "sk-xxx";
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key 未设置。请确保环境变量 'DASHSCOPE_API_KEY' 已设置。");
            return;
        }

        // 设置请求 URL 和内容
        string url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
        // 此处以qwen4-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen4-max"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"",
                    ""content"": ""你是谁?""
                }
            ]
        }";

        // 发送请求并获取响应
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // 输出结果
        Console.WriteLine(result);
    }

    private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
    {
        using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
        {
            // 设置请求头
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // 发送请求并获取响应
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            // 处理响应
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"请求失败: {response.StatusCode}";
            }
        }
    }
}
<?php
// 设置请求的URL
$url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions';
// 若没有配置环境变量,请用百炼API Key将下行替换为:$apiKey = "sk-xxx";
$apiKey = getenv('DASHSCOPE_API_KEY');
// 设置请求头
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// 设置请求体
$data = [
    // 此处以qwen4-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    "model" => "qwen4-max",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "你是谁?"
        ]
    ]
];
// 初始化cURL会话
$ch = curl_init();
// 设置cURL选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 执行cURL会话
$response = curl_exec($ch);
// 检查是否有错误发生
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// 关闭cURL资源
curl_close($ch);
// 输出响应结果
echo $response;
?>
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen4-max",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "你是谁?"
        }
    ]
}'

Streaming output

Related documentation: Streaming output.

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen4-max",  # 此处以qwen4-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '你是谁?'}],
    stream=True,
    stream_options={"include_usage": True}
    )
for chunk in completion:
    print(chunk.model_dump_json())
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen4-max", // 此处以qwen4-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
        messages: [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "你是谁?"}
        ],
        stream: true,
        stream_options: {include_usage: true}
    });
    for await (const chunk of completion) {
        console.log(JSON.stringify(chunk));
    }
}

main();
curl --location "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen4-max",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "你是谁?"
        }
    ],
    "stream":true,
    "stream_options": {
        "include_usage": true
    }
}'

Image input

Related documentation: Image and video understanding.

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen3-vl-plus",  # 此处以qwen3-vl-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    messages=[{"role": "user","content": [
            {"type": "image_url",
             "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
            {"type": "text", "text": "这是什么"},
            ]}]
    )
print(completion.model_dump_json())
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const response = await openai.chat.completions.create({
        model: "qwen3-vl-plus", // 此处以qwen3-vl-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
        messages: [{role: "user",content: [
            { type: "image_url",image_url: {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
            { type: "text", text: "这是什么?" },
        ]}]
    });
    console.log(JSON.stringify(response));
}

main();
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen3-vl-plus",
  "messages": [{
      "role": "user",
      "content": [
       {"type": "image_url","image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
       {"type": "text","text": "这是什么"}
       ]}]
}'

Video input

The following example shows how to pass an image list as video input. To use other methods such as video files, see "Visual understanding.

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    # 此处以qwen3-vl-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    model="qwen3-vl-plus",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "video",
                "video": [
                    "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"]
            },
            {
                "type": "text",
                "text": "描述这个视频的具体过程"
            }]}]
)
print(completion.model_dump_json())
// 确保之前在 package.json 中指定了 "type": "module"
import OpenAI from "openai";

const openai = new OpenAI({
    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
    apiKey: process.env.DASHSCOPE_API_KEY,
    baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
});

async function main() {
    const response = await openai.chat.completions.create({
        // 此处以qwen3-vl-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
        model: "qwen3-vl-plus",
        messages: [{
            role: "user",
            content: [
                {
                    type: "video",
                    video: [
                        "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"
                    ]
                },
                {
                    type: "text",
                    text: "描述这个视频的具体过程"
                }
        ]}]
    });
    console.log(JSON.stringify(response));
}

main();
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "qwen3-vl-plus",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "video",
                    "video": [
                        "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"
                    ]
                },
                {
                    "type": "text",
                    "text": "描述这个视频的具体过程"
                }
            ]
        }
    ]
}'

Tool calling

Related documentation: Function Calling

NoteModel knowledge cutoff: Large models generate responses based on training data, and their knowledge has a cutoff date and cannot automatically perceive the current real date. When asked about the current date, the model returns an old date before the training data cutoff. This is not a parameter configuration error.

Ways to obtain the current accurate time:

  1. Function Calling: Define a get_current_time tool and let the model obtain the real-time time through function calls. See the tool calling example below.
  2. System prompt injection: Inject the current date into the system message (system role), dynamically passing it in with each call.
  3. Web search: enable_search can obtain real-time information, but cannot directly obtain the current time.
import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",  # 填写DashScope SDK的base_url
)

tools = [
    # 工具1 获取当前时刻的时间
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}  # 因为获取当前时间无需输入参数,因此parameters为空字典
        }
    },
    # 工具2 获取指定城市的天气
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    # 查询天气时需要提供位置,因此参数设置为location
                    "location": {
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                    }
                },
                "required": ["location"]
            }
        }
    }
]
messages = [{"role": "user", "content": "杭州天气怎么样"}]
completion = client.chat.completions.create(
    model="qwen4-max",  # 此处以qwen4-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    messages=messages,
    tools=tools
)

print(completion.model_dump_json())
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

const messages = [{"role": "user", "content": "杭州天气怎么样"}];
const tools = [
// 工具1 获取当前时刻的时间
{
    "type": "function",
    "function": {
        "name": "get_current_time",
        "description": "当你想知道现在的时间时非常有用。",
        // 因为获取当前时间无需输入参数,因此parameters为空
        "parameters": {}
    }
},
// 工具2 获取指定城市的天气
{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "当你想查询指定城市的天气时非常有用。",
        "parameters": {
            "type": "object",
            "properties": {
                // 查询天气时需要提供位置,因此参数设置为location
                "location": {
                    "type": "string",
                    "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                }
            },
            "required": ["location"]
        }
    }
}
];

async function main() {
    const response = await openai.chat.completions.create({
        model: "qwen4-max", // 此处以qwen4-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
        messages: messages,
        tools: tools,
    });
    console.log(JSON.stringify(response));
}

main();
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen4-max",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "杭州天气怎么样"
        }
    ],
    "tools": [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "当你想知道现在的时间时非常有用。",
            "parameters": {}
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "当你想查询指定城市的天气时非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location":{
                        "type": "string",
                        "description": "城市或县区,比如北京市、杭州市、余杭区等。"
                    }
                },
                "required": ["location"]
            }
        }
    }
  ]
}'

Asynchronous invocation

import os
import asyncio
from openai import AsyncOpenAI
import platform

client = AsyncOpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

async def main():
    response = await client.chat.completions.create(
        messages=[{"role": "user", "content": "你是谁"}],
        model="qwen4-max",  # 此处以qwen4-max为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    )
    print(response.model_dump_json())

if platform.system() == "Windows":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

Document understanding

Currently, only the qwen-long model supports document analysis. For detailed usage, see Long context (Qwen-Long).

import os
from pathlib import Path
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)
file_object = client.files.create(file=Path("百炼系列手机产品介绍.docx"), purpose="file-extract")
completion = client.chat.completions.create(
    model="qwen-long",  # 模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
    messages=[
        {'role': 'system', 'content': f'fileid://{file_object.id}'},
        {'role': 'user', 'content': '这篇文章讲了什么?'}
    ]
)
print(completion.model_dump_json())
// 建议OpenAI SDK的版本 >= 0.32.0
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import com.openai.models.files.FileCreateParams;
import com.openai.models.files.FileObject;
import com.openai.models.files.FilePurpose;

import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
    public static void main(String[] args) {
        // 创建客户端,使用环境变量中的API密钥
        OpenAIClient client = OpenAIOkHttpClient.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
                .build();

        // 设置文件路径
        Path filePath = Paths.get("百炼系列手机产品介绍.docx");
        // 创建文件上传参数
        FileCreateParams fileParams = FileCreateParams.builder()
                .file(filePath)
                .purpose(FilePurpose.of("file-extract"))
                .build();

        // 上传文件
        FileObject fileObject = client.files().create(fileParams);
        String fileId = fileObject.id();

        // 创建聊天请求
        ChatCompletionCreateParams chatParams = ChatCompletionCreateParams.builder()
                .addSystemMessage("fileid://" + fileId)
                .addUserMessage("这篇文章讲了什么?")
                .model("qwen-long")
                .build();

        // 发送请求并获取响应
        ChatCompletion chatCompletion = client.chat().completions().create(chatParams);

        // 打印响应结果
        System.out.println(chatCompletion);
    }
}
import fs from "fs";
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function getFileID() {
    const fileObject = await openai.files.create({
        file: fs.createReadStream("百炼系列手机产品介绍.docx"),
        purpose: "file-extract"
    });
    return fileObject.id;
}

async function main() {
    const fileID = await getFileID();
    const completion = await openai.chat.completions.create({
        model: "qwen-long",  //模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
        messages: [
            { role: "system", content: `fileid://${fileID}`},
            { role: "user", content: "这篇文章讲了什么?" }
        ],
    });
    console.log(JSON.stringify(completion))
}

main();
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long",
    "messages": [
        {"role": "system","content": "You are a helpful assistant."},
        {"role": "system","content": "fileid://file-fe-xxx"},
        {"role": "user","content": "这篇文章讲了什么?"}
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    }
}'

PPT generation

Currently, only the qwen-doc-turbo model supports PPT generation. For detailed usage, see Generate PPT.

When the skill parameter is used to generate a PPT, only streaming output is supported, and you must set stream: true.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen-doc-turbo",
    messages=[
        {"role": "system", "content": "you are a helpful assistant."},
        {"role": "system", "content": "您的文档内容"},
        {"role": "user", "content": "生成一个10到20页的ppt"}
    ],
    extra_body={"skill": [{"type": "ppt", "mode": "general", "template_id": "news_01"}]},
    stream=True,
    stream_options={"include_usage": True}
)

for chunk in completion:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end='', flush=True)
import OpenAI from "openai";

const openai = new OpenAI(
    {
        apiKey: process.env.DASHSCOPE_API_KEY,
        baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen-doc-turbo",
        messages: [
            {"role": "system", "content": "you are a helpful assistant."},
            {"role": "system", "content": "您的文档内容"},
            {"role": "user", "content": "生成一个10到20页的ppt"}
        ],
        skill: [{"type": "ppt", "mode": "general", "template_id": "news_01"}],
        stream: true,
        stream_options: {"include_usage": true}
    });
    for await (const chunk of completion) {
        if (chunk.choices?.length > 0 && chunk.choices[0].delta.content) {
            process.stdout.write(chunk.choices[0].delta.content);
        }
    }
}

main();
curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-doc-turbo",
    "messages": [
        {
            "role": "system",
            "content": "you are a helpful assistant."
        },
        {
            "role": "system",
            "content": "您的文档内容"
        },
        {
            "role": "user",
            "content": "生成一个10到20页的ppt"
        }
    ],
    "skill": [
        {
            "type": "ppt",
            "mode": "general",
            "template_id": "news_01"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    }
}'

chat response object (non-streaming output)

idstring

The unique identifier of this call.

choicesarray

An array of content generated by the model.

Properties

finish_reasonstring

The reason the model stopped generating.

There are three cases:

  • stop: The stop parameter in the input parameters is triggered, or the output stops naturally.
  • length: Generation ends because the length is too long.
  • tool_calls: Generation ends because a tool needs to be called.

indexinteger

The index of the current object in the choices array.

logprobsobject

Token probability information output by the model.

Properties

content array

An array containing each token and its log probability.

Properties

token string

The text of the current token.

bytes array

The list of raw UTF-8 bytes of the current token, used to precisely reconstruct the output content (for example, emojis or Chinese characters).

logprob float

The log probability of the current token. A return value of null indicates an extremely low probability.

top_logprobs array

The most likely candidate tokens at the current token position, with the count consistent with the request parameter top_logprobs. Each element contains:

Properties

token string

The candidate token text.

bytes array

The list of raw UTF-8 bytes of the current token, used to precisely reconstruct the output content (for example, emojis or Chinese characters).

logprob float

The log probability of the candidate token. A return value of null indicates an extremely low probability.

messageobject

The message output by the model.

Properties

content string

The reply content of the model.

encrypted_content string

The full encrypted chain of thought, used to restore reasoning in multi-turn conversations.

Returned by qwen4-max when thinking_display="summarized". Chain-of-thought summary and encryption

reasoning_content string

The chain-of-thought content of the model.

refusal string

This parameter is currently fixed to null.

role string

The role of the message, fixed as assistant.

audio object

This parameter is currently fixed to null.

function_call (to be deprecated soon) object

This value is fixed as null. Refer to the tool_calls parameter.

tool_calls array

The information about the tool and its input parameters that the model decides to call.

Properties

id string

The unique identifier for this tool call.

type string

The tool type. Currently, only function is supported.

function object

Tool details

Properties

name string

The tool name.

arguments string

The input parameter information, as a JSON formatted string.

Because the large language model's response is random, the output parameter information may not conform to the function signature. You must validate the parameters before you call the function.

index integer

The index of this tool call in the tool_calls array.

createdinteger

The Unix timestamp, in seconds, when the request was created.

modelstring

The model that is used for this request.

object string

The value is always chat.completion.

service_tier string

It is null for pay-as-you-go calls; when calling with a throughput-reserved exclusive model code, the performance tier is returned (ptu_default / ptu_fast). For more information, see Throughput reservation overview.

system_fingerprintstring

This parameter is currently fixed to null.

usage object

The token consumption information for this request.

Properties

completion_tokens integer

The number of tokens in the model's output.

prompt_tokens integer

The number of input tokens. For more information, see Additional notes.

total_tokens integer

The total number of tokens consumed. This is the sum of prompt_tokens and completion_tokens.

completion_tokens_details object (Optional)

A fine-grained classification of output tokens. This field is returned only by some models. Note that text_tokens includes reasoning_tokens — reasoning_tokens is the subset of text_tokens corresponding to the thinking process, so text_tokens minus reasoning_tokens is the number of tokens in the final visible reply. This field is typically returned only when the model outputs a thinking process; it may be null or absent when thinking is not enabled.

Properties

audio_tokens integer (Optional)

The number of output audio tokens. This field is returned only for audio output models.

reasoning_tokens integer (Optional)

The number of tokens in the thinking process. This field is returned only for reasoning models. This value is a subset of text_tokens.

text_tokens integer (Optional)

The number of tokens in the output text. This value already includes reasoning_tokens.

prompt_tokens_details object

A fine-grained classification of input tokens.

Properties

audio_tokens integer

This parameter is currently fixed to null.

cached_tokens integer

The number of tokens that hit the cache. For more information about Context Cache, see Context cache.

text_tokens integer

The number of input text tokens.

image_tokens integer

The number of input image tokens.

video_tokens integer

The number of tokens for the input video file or image list.

cache_creation object

The explicit cache creation information.

Properties

ephemeral_5m_input_tokens integer

The number of tokens that are used to create the explicit cache.

cache_creation_input_tokens integer

The number of tokens that are used to create the explicit cache.

cache_type string

When you use explicit cache, the parameter value is ephemeral. Otherwise, this parameter does not exist.

Properties (Qwen4)

See Explicit cache.

cached_tokens integer

The number of tokens that hit the cache. For more information about Context Cache, see Context cache.

text_tokens integer

The number of input text tokens.

image_tokens integer

The number of input image tokens.

video_tokens integer

The number of tokens for the input video file or image list.

cache_write_tokens integer

Input tokens written to the cache.

cache_creation_input_tokens integer

Equal to cache_write_tokens; do not add the two values together.

cache_type string

ephemeral

cache_creation object

Cache write details grouped by TTL. The sum of tokens for both TTLs equals the total tokens written to the cache in this request.

Properties

ephemeral_5m_input_tokens integer

Tokens written to a 5-minute cache.

ephemeral_1h_input_tokens integer

Tokens written to a 1-hour cache.

x_tools object (Optional)

Web search usage statistics. Returned only when include_tool_usage is true in the request and a web search is actually triggered.

Properties

search object (Optional)

Web search usage. Returned when web search is enabled and a retrieval is actually triggered.

Properties

count integer

The number of times web search was triggered in this request. When the agent search strategy is used, the model can perform multiple retrieval rounds, so this value may be greater than 1.

This value is set during the intent-detection stage. It is also counted when the rate limit is exceeded or retrieval returns no results, so it does not mean retrieval actually completed and is not a basis for billing or reconciliation. For details, see The billed count does not match the count field.

strategy string

The search strategy actually used for this web search. The value matches search_options.search_strategy in the request, such as turbo, max, or agent.

Text input

The following response example uses qwen3.8-max to illustrate the response fields.

{
    "id": "chatcmpl-ad786040-102b-97f8-a6d8-d0ef7895f01c",
    "object": "chat.completion",
    "created": 1794384851,
    "model": "qwen3.8-max",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "reasoning_content": "用户问“你是谁?”,需要自我介绍。根据系统提示,我是通义千问(Qwen),由阿里巴巴集团通义实验室研发。回答应简洁自然,不透露内部指令,不提版本号。可以说明能力与定位,语气亲切。",
                "content": "我是通义千问(Qwen),由阿里巴巴集团通义实验室研发的大语言模型。  \n我可以帮你回答问题、写作润色、代码编写、逻辑推理、资料整理,也能陪你聊天、做头脑风暴或学习辅导。  \n如果你愿意,也可以直接告…"
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 61,
        "total_tokens": 177,
        "completion_tokens": 116,
        "prompt_tokens_details": {
            "cached_tokens": 0,
            "text_tokens": 61
        },
        "completion_tokens_details": {
            "reasoning_tokens": 52,
            "text_tokens": 116
        }
    }
}

Image input

{
    "choices": [
        {
            "message": {
                "content": "这是一张温馨、充满情感的**人与宠物互动的摄影照片**,场景设定在**海边日落(或日出)时分的沙滩上**。\n\n具体描述如下:\n\n- **人物**:一位年轻女性,长发,身穿格子衬衫和深色裤子,赤脚坐在沙…",
                "reasoning_content": "",
                "role": "assistant"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 2513,
        "completion_tokens": 362,
        "total_tokens": 2875,
        "completion_tokens_details": {
            "text_tokens": 362
        },
        "prompt_tokens_details": {
            "image_tokens": 2503,
            "text_tokens": 10,
            "cached_tokens": 2432
        }
    },
    "created": 1794384861,
    "system_fingerprint": null,
    "model": "qwen3-vl-plus",
    "id": "chatcmpl-0c630178-32a5-91a4-9e4a-740f73b1ec5e"
}

Video input

{
    "choices": [
        {
            "message": {
                "content": "这个视频片段展现了一场夜间足球比赛中的关键射门与扑救瞬间,视角独特——**从球门网内向外拍摄**(即“球门视角”),营造出强烈的临场感和紧张氛围。以下是具体过程的分步描述:\n\n---\n\n- **0.0…",
                "reasoning_content": "",
                "role": "assistant"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 1208,
        "completion_tokens": 756,
        "total_tokens": 1964,
        "completion_tokens_details": {
            "text_tokens": 756
        },
        "prompt_tokens_details": {
            "text_tokens": 18,
            "video_tokens": 1190,
            "cached_tokens": 0
        }
    },
    "created": 1794384874,
    "system_fingerprint": null,
    "model": "qwen3-vl-plus",
    "id": "chatcmpl-4aaa644b-b37d-90df-984c-c138b47bf972"
}

Tool calling

The following response example uses qwen3.8-max to illustrate the response fields.

{
    "id": "chatcmpl-5cc0b5ec-42bf-99e8-ae83-1fd676eec9bf",
    "object": "chat.completion",
    "created": 1794384861,
    "model": "qwen3.8-max",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "reasoning_content": "The user asks about Hangzhou weather. I should call the weather tool.",
                "content": "",
                "tool_calls": [
                    {
                        "id": "call_7355c2deaffc4131ba015924",
                        "type": "function",
                        "function": {
                            "name": "get_current_weather",
                            "arguments": "{\"location\": \"杭州市\"}"
                        },
                        "index": 0
                    }
                ]
            },
            "finish_reason": "tool_calls",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 375,
        "total_tokens": 419,
        "completion_tokens": 44,
        "prompt_tokens_details": {
            "cached_tokens": 0,
            "text_tokens": 375
        },
        "completion_tokens_details": {
            "reasoning_tokens": 15,
            "text_tokens": 44
        }
    }
}

Web search

The following response example uses qwen3.8-max to illustrate the response fields.

{
    "id": "chatcmpl-0df41ee2-49c9-9ee8-a614-fdec17347b6a",
    "object": "chat.completion",
    "created": 1794384861,
    "model": "qwen3.8-max",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "reasoning_content": "用户问:“中国队在巴黎奥运会获得了多少枚金牌”。需要直接回答。知识库多处明确:2024巴黎奥运会中国体育代表团获得40金27银24铜,金牌数境外最佳。需要简洁中文回答。",
                "content": "中国队在2024年巴黎奥运会上共获得了 **40枚金牌**。"
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 2883,
        "total_tokens": 2954,
        "completion_tokens": 71,
        "prompt_tokens_details": {
            "cached_tokens": 0,
            "text_tokens": 2883
        },
        "completion_tokens_details": {
            "reasoning_tokens": 50,
            "text_tokens": 71
        }
    }
}

When include_tool_usage is set to true and a web search is actually triggered, the x_tools field is added to usage:

The following response example uses qwen3.8-max to illustrate the response fields.

{
    "id": "chatcmpl-4233d020-62cd-949f-94e2-444b97503856",
    "object": "chat.completion",
    "created": 1792037298,
    "model": "qwen3.8-max",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "杭州亚运会(第19届亚洲运动会)是在2023年举办的,具体举办时间为2023年9月23日至10月8日。"
            },
            "finish_reason": "stop",
            "logprobs": null
        }
    ],
    "usage": {
        "prompt_tokens": 1905,
        "total_tokens": 1987,
        "completion_tokens": 82,
        "prompt_tokens_details": {
            "cached_tokens": 0,
            "text_tokens": 1905
        },
        "x_tools": {
            "search": {
                "count": 1,
                "strategy": "turbo"
            }
        }
    }
}

Asynchronous invocation

Asynchronous invocation uses the OpenAI SDK and returns the same response object as text input. There is no separate curl asynchronous endpoint in this example.

Chat response chunk object (streaming output)

idstring

The unique identifier for this call. Each chunk object has the same ID.

choicesarray

An array of content generated by the model, which can contain one or more objects. If the include_usage parameter is set to true, choices is an empty array in the last chunk.

Properties

delta object

The incremental object of the request.

Properties

content string

The incremental message content.

encrypted_content string

The full encrypted chain of thought, used to restore reasoning in multi-turn conversations.

Returned by qwen4-max when thinking_display="summarized". Encrypted content is returned in a separate frame. Do not concatenate it with other frames or across turns. Thinking summary and encryption

reasoning_content string

The incremental chain-of-thought content.

function_call object

This value defaults to null. For more information, see the tool_calls parameter.

audioobject

The reply that is generated when you use the Qwen-Omni model.

Properties

data string

The incremental Base64-encoded audio data.

expires_at integer

The timestamp when the request was created.

refusal object

This parameter is currently fixed to null.

role string

The role of the incremental message object. It has a value only in the first chunk.

tool_calls array

The information about the tool and its input parameters that the model decides to call.

Properties

index integer

The index of this tool call in the tool_calls array.

id string

The unique identifier for this tool call.

function object

The information about the called tool.

Properties

arguments string

The incremental input parameters. The arguments from all chunks are concatenated to form the complete set of input parameters.

Because the large language model's response is random, the output parameter information may not conform to the function signature. You must validate the parameters before you call the function.

name string

The tool name. It has a value only in the first chunk.

type string

The tool type. Currently, only function is supported.

finish_reason string

The reason why the model stopped generating. The value can be one of the following:

  • stop: The model stopped generating because it triggered the stop parameter in the input or stopped naturally.
  • The value is null until the generation is complete.
  • length: The model stopped generating because the generation length is too long.
  • tool_calls: The model stopped generating because a tool needs to be called.

index integer

The index of the current response in the choices array. When the input parameter n is greater than 1, you can use this parameter to concatenate the complete content that corresponds to different responses.

logprobsobject

The probability information of the current object.

Properties

content array

An array of tokens with log probability information.

Properties

token string

The current token.

bytes array

A list of the raw UTF-8 bytes of the current token. This is helpful when you process emojis and Chinese characters.

logprob float

The log probability of the current token. A null value indicates an extremely low probability.

top_logprobs array

The most likely tokens at the current token position and their log probabilities. The number of elements is consistent with the top_logprobs input parameter.

Properties

token string

The current token.

bytes array

A list of the raw UTF-8 bytes of the current token. This is helpful when you process emojis and Chinese characters.

logprob float

The log probability of the current token. A null value indicates an extremely low probability.

createdinteger

The timestamp when this request was created. Each chunk has the same timestamp.

modelstring

The model that is used for this request.

object string

The value is always chat.completion.chunk.

service_tier string

This parameter is currently fixed to null.

system_fingerprintstring

This parameter is currently fixed to null.

usage object

The tokens consumed by this request. It is displayed only in the last chunk when include_usage is set to true.

Properties

completion_tokens integer

The number of tokens in the model's output.

prompt_tokens integer

The number of input tokens.

total_tokens integer

The total number of tokens, which is the sum of prompt_tokens and completion_tokens.

completion_tokens_details object (Optional)

Detailed information about the output tokens. This field is returned only by some models. Note that text_tokens includes reasoning_tokens — reasoning_tokens is the subset of text_tokens corresponding to the thinking process, so text_tokens minus reasoning_tokens is the number of tokens in the final visible reply. This field is typically returned only when the model outputs a thinking process; it may be null or absent when thinking is not enabled.

Properties

audio_tokensinteger (Optional)

The number of output audio tokens. This field is returned only for audio output models.

reasoning_tokens integer (Optional)

The number of tokens in the thinking process. This field is returned only for reasoning models. This value is a subset of text_tokens.

text_tokensinteger (Optional)

The number of output text tokens. This value already includes reasoning_tokens.

prompt_tokens_details object

A fine-grained classification of input tokens.

Properties

audio_tokens integer

The number of input audio tokens.

The number of audio tokens in a video file is returned in this parameter.

text_tokens integer

The number of input text tokens.

video_tokens integer

The number of tokens for the input video, which can be an image list or a video file.

image_tokens integer

The number of input image tokens.

cached_tokens integer

The number of tokens that hit the cache. For more information about Context Cache, see Context cache.

cache_creation object

The explicit cache creation information.

Properties

ephemeral_5m_input_tokens integer

The number of tokens that are used to create the explicit cache.

cache_creation_input_tokens integer

The number of tokens that are used to create the explicit cache.

cache_type string

The cache type. The value is fixed to ephemeral.

Properties (Qwen4)

See Explicit cache.

text_tokens integer

The number of input text tokens.

video_tokens integer

The number of tokens for the input video, which can be an image list or a video file.

image_tokens integer

The number of input image tokens.

cached_tokens integer

The number of tokens that hit the cache. For more information about Context Cache, see Context cache.

cache_write_tokens integer

Input tokens written to the cache.

cache_creation_input_tokens integer

Equal to cache_write_tokens; do not add the two values together.

cache_type string

ephemeral

cache_creation object

Cache write details grouped by TTL. The sum of tokens for both TTLs equals the total tokens written to the cache in this request.

Properties

ephemeral_5m_input_tokens integer

Tokens written to a 5-minute cache.

ephemeral_1h_input_tokens integer

Tokens written to a 1-hour cache.

x_tools object (Optional)

Web search usage statistics. Returned only when include_tool_usage is true in the request and a web search is actually triggered. It appears with usage in the last chunk.

Properties

search object (Optional)

Web search usage. Returned when web search is enabled and a retrieval is actually triggered.

Properties

count integer

The number of times web search was triggered in this request. When the agent search strategy is used, the model can perform multiple retrieval rounds, so this value may be greater than 1.

This value is set during the intent-detection stage. It is also counted when the rate limit is exceeded or retrieval returns no results, so it does not mean retrieval actually completed and is not a basis for billing or reconciliation. For details, see The billed count does not match the count field.

strategy string

The search strategy actually used for this web search. The value matches search_options.search_strategy in the request, such as turbo, max, or agent.

Streaming output

curl streaming responses use SSE: each event starts with data:, events are separated by blank lines, and the stream ends with data: [DONE]. Repeated intermediate chunks are omitted below; role, reasoning, content, finish, and usage events are retained. SDKs parse SSE and do not print data: or [DONE].

data: {"model":"qwen3.8-max","id":"chatcmpl-730609ad-25b4-9809-8bd2-29b3fb280cb9","created":1794384852,"object":"chat.completion.chunk","usage":null,"choices":[{"logprobs":null,"index":0,"delta":{"reasoning_content":"","content":"","role":"assistant"},"finish_reason":null}]}

data: {"id":"chatcmpl-730609ad-25b4-9809-8bd2-29b3fb280cb9","object":"chat.completion.chunk","created":1794384852,"model":"qwen3.8-max","choices":[{"index":0,"delta":{"content":"","reasoning_content":"用户"},"logprobs":null,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-730609ad-25b4-9809-8bd2-29b3fb280cb9","object":"chat.completion.chunk","created":1794384858,"model":"qwen3.8-max","choices":[{"index":0,"delta":{"content":"我是通义","reasoning_content":""},"logprobs":null,"finish_reason":null}],"usage":null}

data: {"id":"chatcmpl-730609ad-25b4-9809-8bd2-29b3fb280cb9","object":"chat.completion.chunk","created":1794384861,"model":"qwen3.8-max","choices":[{"index":0,"delta":{"content":"","reasoning_content":""},"finish_reason":"stop","logprobs":null}],"usage":null}

data: {"id":"chatcmpl-730609ad-25b4-9809-8bd2-29b3fb280cb9","object":"chat.completion.chunk","created":1794384861,"model":"qwen3.8-max","choices":[],"usage":{"prompt_tokens":61,"total_tokens":346,"completion_tokens":285,"prompt_tokens_details":{"cached_tokens":0,"text_tokens":61},"completion_tokens_details":{"reasoning_tokens":195,"text_tokens":285}}}

data: [DONE]
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":"assistant","tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen3.8-max","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"我是","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen3.8-max","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1735113344,"model":"qwen3.8-max","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[],"created":1735113344,"model":"qwen3.8-max","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":{"completion_tokens":17,"prompt_tokens":22,"total_tokens":39,"completion_tokens_details":null,"prompt_tokens_details":{"audio_tokens":null,"cached_tokens":0}}}

Document understanding

Replace the file ID in the request with the ID returned after uploading your document.

data: {"choices":[{"delta":{"content":"","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"usage":null,"created":1794384917,"system_fingerprint":null,"object":"chat.completion.chunk","model":"qwen-long","id":"chatcmpl-dd003860-d3ed-9996-8a46-0c50d416bb63"}

data: {"choices":[{"delta":{"content":"这篇文章","role":"assistant"},"finish_reason":null,"index":0,"logprobs":null}],"usage":null,"created":1794384917,"system_fingerprint":null,"object":"chat.completion.chunk","model":"qwen-long","id":"chatcmpl-dd003860-d3ed-9996-8a46-0c50d416bb63"}

data: {"choices":[{"delta":{"content":""},"finish_reason":"stop","index":0,"logprobs":null}],"usage":null,"created":1794384919,"system_fingerprint":null,"object":"chat.completion.chunk","model":"qwen-long","id":"chatcmpl-dd003860-d3ed-9996-8a46-0c50d416bb63"}

data: {"choices":[],"usage":{"prompt_tokens":59,"completion_tokens":107,"total_tokens":166},"created":1794384919,"system_fingerprint":null,"object":"chat.completion.chunk","model":"qwen-long","id":"chatcmpl-dd003860-d3ed-9996-8a46-0c50d416bb63"}

data: [DONE]

PPT generation

data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1794385034,"system_fingerprint":null,"model":"qwen-doc-turbo","id":"chatcmpl-fea338d0-e90f-93d3-9106-78b8132278e3"}

data: {"choices":[{"finish_reason":null,"logprobs":null,"delta":{"content":null,"reasoning_content":"大纲生成成功:ppt_overview = # 【PPT内容大纲与详细设计】\n\n## 第1页:封面\n**大纲要点:**\n- 主标题:AI智能体系统架构\n- 副标题:基于大模型驱动的自动化解决方案\n- …"},"index":0}],"object":"chat.completion.chunk","usage":null,"created":1794385034,"system_fingerprint":null,"model":"qwen-doc-turbo","id":"chatcmpl-fea338d0-e90f-93d3-9106-78b8132278e3"}

Web search

When include_tool_usage is true and a web search is triggered, the last chunk includes x_tools in usage:

The following response example uses qwen3.8-max to illustrate the response fields.

data: {"id":"chatcmpl-3d720785-fa18-9207-ac31-666fd4fb1ba3","object":"chat.completion.chunk","created":1794396212,"model":"qwen3.8-max","choices":[],"usage":{"prompt_tokens":2883,"total_tokens":2962,"completion_tokens":79,"prompt_tokens_details":{"cached_tokens":0,"text_tokens":2883},"completion_tokens_details":{"reasoning_tokens":58,"text_tokens":79},"x_tools":{"search":{"count":1,"strategy":"turbo"}}}}

data: [DONE]

Error codes

If the model call fails and an error message is returned, see Error codes to resolve the issue.