All Products
Search
Document Center

Alibaba Cloud Model Studio:DashScope API Reference

Last Updated:Dec 01, 2026

Call Qwen models through the DashScope API, and view input and output parameter descriptions and calling examples.

Singapore

HTTP request URL:

  • Text-only models (such as qwen-plus): POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
  • Multimodal models (such as qwen3.7-plus or qwen3-vl-plus): POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Region configuration for SDK calls:

Python code

import os
import dashscope

# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
MultiModalConversation conv = new MultiModalConversation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
  • Method 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";

dashscope CLI

Call through the dashscope command line.

export DASHSCOPE_API_KEY="your-api-key"
# Replace {WorkspaceId} with your workspace ID and ap-southeast-1 with your region (US Virginia: us-east-1; Germany: eu-central-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
dashscope generation create -m qwen-plus -p "Hello"

ImportantThe SDK Expert interactive assistant can accomplish the same development and troubleshooting tasks using natural language. See

DashScope SDK Expert.

For the complete region list, see Base URL Overview.

United States (Virginia)

HTTP request URL:

  • Text-only models (such as qwen-plus): POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
  • Multimodal models (such as qwen3.7-plus or qwen3-vl-plus): POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Region configuration for SDK calls:

Python code

import os
import dashscope

# The following is the configuration for the US (Virginia) region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="us-east-1",
)

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
MultiModalConversation conv = new MultiModalConversation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1");
  • Method 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1";

China (Beijing)

HTTP request URL:

  • Text-only models (such as qwen-plus): POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
  • Multimodal models (such as qwen3.7-plus or qwen3-vl-plus) POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Region configuration for SDK calls:

Python code

import os
import dashscope

# The following is the configuration for the China (Beijing) region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
MultiModalConversation conv = new MultiModalConversation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1");
  • Method 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";

Hong Kong (China)

HTTP request URL:

  • Text-only models (such as qwen-plus): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
  • Multimodal models (such as qwen3.7-plus or qwen3-vl-plus): POST https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Region configuration for SDK calls:

Python code

import os
import dashscope

# The following is the configuration for the China (Hong Kong) region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-hongkong",
)

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
MultiModalConversation conv = new MultiModalConversation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1");
  • Method 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1";

Germany (Frankfurt)

HTTP request URL:

  • Text-only models (such as qwen-plus): POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
  • Multimodal models (such as qwen3.7-plus or qwen3-vl-plus): POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Region configuration for SDK calls:

Python code

import os
import dashscope

# The following is the configuration for the Germany (Frankfurt) region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="eu-central-1",
)

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
MultiModalConversation conv = new MultiModalConversation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1");
  • Method 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1";

Japan (Tokyo)

HTTP request URL:

  • Text-only models (e.g., qwen-plus): POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
  • Multimodal models (e.g., qwen3.7-plus or qwen3-vl-plus): POST https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Region configuration for SDK calls:

Python code

import os
import dashscope

# The following is the configuration for the Japan (Tokyo) region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-northeast-1",
)

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
MultiModalConversation conv = new MultiModalConversation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1");
  • Method 2:
import com.alibaba.dashscope.utils.Constants;
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1";

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

You must have already obtained and configured an API Key and set the API Key as an environment variable. If you call through the DashScope SDK, you need to install the DashScope SDK.

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

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

{WorkspaceId} is your Workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domains remain fully functional.

Request body

modelstring (Required)

The model name.

Supported models: Qwen large language models (commercial and open-source versions), Qwen-VL, Qwen-Coder, math models, DeepSeek, Kimi, GLM, and MiniMax.

For specific model names and billing, see Select Model.

messagesarray (Required)

The context passed to the model, arranged in conversation order.

When calling via HTTP, place messages inside the input object.

Message Type

System Messageobject (Optional)

The system message, used to define the model's role, tone, task objectives, or constraints. It is generally placed first in the messages array.

Setting a System Message is not recommended for QwQ models, and it does not take effect for QVQ models.

Properties

contentstring (Required)

The message content.

rolestring (Required)

The role of the system message, fixed as system.

User Messageobject (Required)

The user message, used to pass questions, instructions, or context to the model.

Properties

contentstring or array (Required)

The message content. If the input contains only text, it is of the string type; if the input contains multimodal data such as images, or explicit cache is enabled, it is of the array type.

Properties

textstring (Required)

The input text.

imagestring (optional)

The image file used for image understanding. Images can be passed in the following three ways:

  • Public URL: a publicly accessible image link
  • Base64 encoding of the image, in the format data:image/<format>;base64,<data>
  • Local file: the absolute path of a local file

Applicable models: Qwen-VL, QVQ

Example value: {"image":"https://xxxx.jpeg"}

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 not specified:

  • high: processes at the original image resolution, with an upper limit of 16777216 pixels.
  • low: pixel upper limit of 2621440.
  • auto: same as low.

When max_pixels is explicitly specified, that value is used as the pixel upper limit, taking precedence over detail. The maximum value is 16777216. In Chat Completions, max_pixels is at the same level as image_url; in DashScope, it is at the same level as image.

For high-resolution images, using high typically results in higher input token usage than low.

In Chat Completions, detail can be passed inside image_url or at the same level as image_url; in DashScope, it is passed at the same level as image.

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

videoarray or string (optional)

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 passed in when using Qwen-VL models or QVQ models.

  • If an image list is passed in, the type is array;
  • If a video file is passed in, the type is string.

For passing in local files, see Local file.

Example value:

  • Image list: {"video":["https://xx1.jpg",...,"https://xxn.jpg"]}
  • Video file: {"video":"https://xxx.mp4"}

fpsfloat (optional)

Number of frames extracted per second. The value range is [0.1, 10], and the default value is 2.0.

Functionality

fps has two functions:

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

    Applicable to Qwen-VL models and QVQ models.

  • Informs the model of the time interval between adjacent frames, helping it better understand the temporal dynamics of the video. It also applies when a video file or an image list is input. This feature supports both video file and image list input, and 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, and QVQ models.

A larger fps is suitable for high-speed motion scenarios (such as sports events and action movies), while a smaller fps is suitable for long videos or relatively static content.

Example value

  • Image list input: {"video":["https://xx1.jpg",...,"https://xxn.jpg"],"fps":2}
  • Video file input: {"video": "https://xx1.mp4","fps":2}

max_framesinteger (optional)

The upper limit on the number of frames extracted from a video. When the number of frames calculated by fps exceeds max_frames, the system will automatically adjust to: uniformly sample frames within max_frames, ensuring the total number of frames does not exceed the limit.

Value range

  • qwen3.7 series, qwen3.6 series, and qwen3.5 series: both the maximum and default values are 8000.
  • qwen3-vl-plus series: both the maximum and default values are 2000.

Example value

{"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"max_frame": 2000}

When calling with the OpenAI-compatible API, the custom max_frames parameter is not supported, and the API automatically uses the default value of each model.

min_pixelsinteger (Optional)

Sets the minimum pixel threshold for input images or video frames. When the pixels of an input image or video frame are smaller than min_pixels, it will be scaled up until the total pixels exceed min_pixels.

Value range

  • Input images:
    • qwen4-max, Qwen3.7、Qwen3.6、Qwen3.5, Qwen3-VL: the default value and minimum value are both: 65536
    • Qwen2.5-VL open-source series and QVQ series models: the default value and minimum value are both 3136
  • Input video file or image list:
    • 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: the default value is 65536, and the minimum value is 4096.
    • kimi-k2.5, kimi-k2.6, kimi-k2.7-code: the minimum value is 3136.
    • Qwen2.5-VL open-source series and QVQ series models: the default value is 50176, and the minimum value is 3136

Example value

  • Input image: {"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"min_pixels": 65536}
  • When inputting a video file: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"min_pixels": 65536}
  • When inputting an image list: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"min_pixels": 65536}

max_pixelsinteger (Optional)

Sets the maximum pixel threshold for input images or video frames. When the pixels of an input image or video are within the [min_pixels, max_pixels] range, the model recognizes the original image. When the input image pixels exceed max_pixels, the image is scaled down until the total pixels are below max_pixels.

Value range

  • Input images:
    • qwen4-max: the maximum value is 16777216. If not specified, images are processed based on detail; an explicitly specified max_pixels is not affected by 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.7、Qwen3.6、Qwen3.5, Qwen3-VL: the default value is 2621440, 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.7、Qwen3.6、Qwen3.5, Qwen3-VL: max_pixels is invalid, and the maximum pixels of input images is fixed at 16777216
      • Qwen2.5-VL open-source series and QVQ series models: max_pixels is invalid, and the maximum pixels of input images is fixed at 12845056
  • Input video file or image list:

    When min_pixels and max_pixels are specified at the same time, max_pixels must not be smaller than 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: the default value is 655360, and the maximum value is 2048000.
    • qwen3-omni-flash: the default value is 655360, and the maximum value is 786432.
    • kimi-k2.5, kimi-k2.6, kimi-k2.7-code: the maximum value is 1568000.
    • Other Qwen3-VL open-source models: the default value is 655360, and the maximum value is 786432.
    • Qwen2.5-VL open-source series and QVQ series models: the default value is 501760, and the maximum value is 602112

Example value

  • Input image: {"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"max_pixels": 8388608}
  • When inputting a video file: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"max_pixels": 655360}
  • When inputting an image list: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"max_pixels": 655360}

total_pixelsinteger (Optional)

The total pixel budget after video frame extraction.

Maximum value

  • 268435456: qwen4-max, qwen3.8-max、qwen3.8-max-0902。
  • 234881024:qwen3.5-plus、qwen3.5-plus-2026-02-15、qwen3.5-plus-2026-04-20、qwen3.6-plus、qwen3.6-plus-2026-04-02、qwen3.7-max-2026-06-08、qwen3.7-plus、qwen3.7-plus-2026-05-26。
  • 819200000: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.6-27b、qwen3.6-35b-a3b、qwen3.6-flash、qwen3.6-flash-2026-04-16、qwen3.7-flash、qwen3.7-flash-2026-07-15、qwen3.8-27b、qwen3.8-flash。
  • 184549376:qwen3.5-omni-flash、qwen3.5-omni-flash-2026-03-15、qwen3.5-omni-plus、qwen3.5-omni-plus-2026-03-15、qwen3.8-omni-flash。
  • 16777216:qwen3-omni-flash。
  • 102760448:kimi-k2.5、kimi-k2.6、kimi-k2.7-code。
  • 134217728:qwen3-vl-plus。

Example value

  • When inputting a video file: {"type": "video_url","video_url": {"url":"https://xxxx.mp4"},"total_pixels": 134217728}
  • When inputting an image list: {"type": "video","video": ["https://xx1.jpg",...,"https://xxn.jpg"],"total_pixels": 134217728}

cache_controlobject (Optional)

Only supported by models that support explicit cache, used to enable explicit cache.

Properties

type string (Required)

Fixed to ephemeral.

rolestring (Required)

The role of the user message, fixed to user.

Assistant Message object (Optional)

The model's reply to the user message.

Properties

contentstring(Optional)

The message content. Required unless the assistant message includes the tool_calls parameter.

rolestring (Required)

Fixed to assistant.

partialboolean(Optional)

Whether to enable partial mode. Related documentation and supported models: Partial mode.

tool_calls array(Optional)

The tool and input parameter information returned after Function Calling is initiated, containing one or more objects. Obtained from the tool_calls field of the previous model response.

Properties

id string

The ID of the tool call.

type string

The tool type. Currently, only function is supported.

function object

The tool and input parameter information.

Properties

name string

The tool name.

arguments string

The input parameter information, in JSON format string.

index integer

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

Tool Messageobject(Optional)

The output information of the tool.

Properties

contentstring (Required)

The output content of the tool function, which must be in string format.

rolestring (Required)

Fixed to tool.

tool_call_idstring(Optional)

The ID returned after Function Calling is initiated. You can obtain it via response.output.choices[0].message.tool_calls[$index]["id"]. It is used to identify the tool corresponding to the Tool Message.

temperaturefloat(Optional)

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

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

Value range: [0, 2)

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

When calling via HTTP, place temperature in the parameters object.

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 the text generated by the model.

A higher top_p value makes the generated text more diverse. Conversely, a lower value makes the generated text more deterministic.

Value range: (0,1.0].

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

In the Java SDK, it is topP. When calling via HTTP, put top_p in the parameters object.

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

top_kinteger (optional)

The size of the candidate set sampled during generation. For example, when the value is 50, only the 50 highest-scoring tokens in a single generation form the candidate set for random sampling. A larger value leads to higher randomness in generation; a smaller value leads to higher determinism. A value of None or a top_k greater than 100 indicates that the top_k strategy is disabled, and only the top_p strategy takes effect.

The value must be greater than or equal to 0.

top_k default value

QVQ series: 10;

QwQ series: 40;

All other models: 20;

GLM series (Alibaba Cloud direct): 20;

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

In the Java SDK, it is topK. When calling via HTTP, put top_k in the parameters object.

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

enable_thinking boolean (optional)

Whether to enable thinking mode when using hybrid thinking models. This applies to Qwen4, Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5, Qwen3, and Qwen3-VL models, as well as the DeepSeek-V4 series, Kimi-K2.6/K2.5 series, and GLM series. The DeepSeek-V4 series enables thinking by default, and you can adjust the reasoning effort via the reasoning_effort parameter.

Optional values:

  • true: enable

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

  • false: disable

Default values for different models: Supported models

In the Java SDK, it is enableThinking; when calling via HTTP, put enable_thinking in the parameters object.

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

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.

preserve_thinking boolean (optional) The default value is false (for qwen4-max and qwen3.8-max, the default value istrue)

Whether to append the reasoning_content of assistant messages in the conversation history to the model input. This applies to scenarios where the model needs to reference the historical thinking process.

Currently supported: qwen4-max, qwen3.8-max (enabled by default), qwen3.8-max-0902 (enabled by default), qwen3.8-flash, qwen3.7-max, qwen3.7-max-2026-05-20 and subsequent snapshots, qwen3.7-plus, qwen3.7-plus-2026-05-26, qwen3.6-plus, qwen3.6-plus-2026-04-02, qwen3.7-flash, qwen3.7-flash-2026-07-15, qwen3.6-flash, qwen3.6-flash-2026-04-16, kimi-k2.6 (Alibaba Cloud Model Studio deployment), kimi-k2.7-code (Alibaba Cloud Model Studio deployment, enabled by default), kimi/kimi-k2.7-code-highspeed (Moonshot direct, enabled by default), kimi/kimi-k2.7-code (Moonshot direct, enabled by default).

Important: When using qwen4-max or qwen3.8-max, preserve_thinking is true by default, and you must pass back all reasoning_content from the conversation history in full. Appending reasoning_content to the content field for passback is not supported.

  • If the historical messages do not contain reasoning_content, enabling this parameter will not cause an error and is fully compatible.
  • After it is enabled, reasoning_content in the historical conversation will be counted toward the input tokens and billed.

When calling via HTTP, put preserve_thinking into the parameters object. Not supported by the Java SDK yet.

thinking_budget integer (optional)

The maximum length of the thinking process. Applicable to Qwen4, Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen3, GLM, and Kimi series models, among which kimi-k3 and kimi-k3.1-pro do not support this parameter. Related document: Limit thinking length. Default value: 131072 (qwen4-max). deepseek-v4.1-flash ignores this parameter; setting it has no effect.

Other models: the default value is the maximum chain-of-thought length of the model. See: Select Model

In the Java SDK, this parameter is thinkingBudget. When calling via HTTP, put thinking_budget into the parameters object.

Other models: the default value is the maximum chain-of-thought length of the model.

reasoning_effort string (optional)

Controls the reasoning effort of the model. Different models support different available 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 both 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 based on the following table, 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 (deployed on Alibaba Cloud Model Studio): the default value is max.

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

enable_thinking defaults to true. It can be set to false to disable thinking, but we recommend keeping it enabled, as disabling it significantly affects model output quality.

DeepSeek-V4, GLM series, and kimi/kimi-k3 (default value is high)

Optional values:

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

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

Applicable to glm-5.2, glm-5.1, glm-5, deepseek-v4.1-flash, deepseek-v4-pro (except deepseek-v4-flash-0731), and kimi/kimi-k3

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

Optional values:

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

These models always have thinking enabled. enable_thinking only supports true, and passing false will cause the API request to fail.

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

Optional 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.

qwen3.8 series models: the default value isxhigh

Optional values:

  • xhigh (default): high-effort reasoning
  • medium: medium-effort reasoning
  • low: low-effort reasoning

max is mapped to xhigh, high is mapped to xhigh, minimal is mapped to low, and none is mapped to enable_thinking=False.

Setting a value other than the above optional values and mapped values will cause an error.

Important: The qwen3.8 series does not support setting reasoning_effort and thinking_budget at the same time; setting both simultaneously will cause an error. However, the two support mutual conversion:

  • 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.

When calling via HTTP, put reasoning_effort into the parameters object.

tool_stream boolean (optional) The default value is false

Only affects the streaming output behavior of complex tool parameters, and takes effect only in streaming calls. Regular tool parameters (all parameters are of type string) can be streamed as long as streaming is enabled; tool_stream has no effect on them. Complex tools refer to tools whose definitions contain parameters of type array or object. Currently, only the Qwen and GLM series support this.

Qwen series support list:
  • qwen-max series: text modality of qwen4-max, the qwen3.8-max series, and the qwen3.7-max series
  • qwen-plus series: text modality of the qwen3.7-plus series and the qwen3.6-plus series, as well as the full modality of the qwen3.5-plus series
  • qwen-flash series: the qwen3.8-flash series, qwen3.7-flash series, and qwen3.6-flash series, as well as the full modality of qwen3.5-flash
Qwen series usage reference:
  • tool_stream=false: complex tool parameters are output all at once, which is the default behavior and is more accurate for complex formats.
  • tool_stream=true: complex tool parameters are streamed, and complex formats have no timeout risk.

Complex tools refer to tools whose definitions contain parameters of type array or object.

GLM series support list: glm-5, glm-5.1.

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

When calling via HTTP, put tool_stream into the parameters object.

enable_code_interpreter boolean (optional) The default value is false

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

Optional values:

  • true: Enable
  • false: Disable

The Java SDK is not supported. When calling via HTTP, put enable_code_interpreter into the parameters object.

clear_thinkingboolean (optional) The default value is false

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

  • true: Enable. The reasoning_content of previous turns is ignored, and only non-reasoning content such as visible text, tool calls, and results is input as context, which reduces context length and cost.
  • false (default): Disable. The reasoning_content of previous turns is retained and provided to the model together with the context. To enable Preserved Thinking, you must pass the historical reasoning_content through in messages completely, unmodified, and in the original order; missing, trimmed, rewritten, or reordered content will degrade the effect or prevent it from working.

repetition_penaltyfloat (optional)

The degree of repetition in consecutive sequences during model generation. Increasing repetition_penalty reduces the repetition in model generation; 1.0 means no penalty. There is no strict value range—it only needs to be greater than 0.

In the Java SDK, it is repetitionPenalty. When calling via HTTP, put repetition_penalty into the parameters object.

It is not recommended to change 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. Supports qwen4-max.

presence_penaltyfloat (Optional)

Controls the content repetition in the text generated by the model.

Value range: [-2.0, 2.0]. Positive values reduce repetition, and negative values increase repetition.

In scenarios that require diversity, fun, or creativity, such as creative writing or brainstorming, it is recommended to increase this value; in scenarios that emphasize consistency and terminology accuracy, such as technical documentation or formal texts, it is recommended to decrease this value.

presence_penalty default value

qwen4-max (non-thinking mode), Qwen3.8 (non-thinking mode), Qwen3.7 (non-thinking mode), Qwen3.6 (non-thinking mode), 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;

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

All others are 0.0.

DeepSeek series (Alibaba Cloud direct supply): deepseek-r1-distill-qwen distilled version: 1;

Kimi series (Alibaba Cloud direct supply): kimi-k2.7-code, kimi-k2.6, kimi-k2.5: 0.0;

Kimi series (Moonshot AI direct supply): 0.0;

MiniMax series (Alibaba Cloud direct supply): 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 excellent. The plot is wonderful, the acting is superb, and the music is delightful to listen to. Overall, the entire film is simply marvelous. In fact, it is truly outstanding. The storyline is captivating, the performances are exceptional, and the soundtrack is equally enchanting.

Parameter value is 0.0: This movie is good. The plot is good, the acting is good, the music is good, and overall, the whole movie is good. In fact, it is 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, the music is good, and overall, the whole movie is good. In fact, it is really good. The plot is really good, the acting is really good, and the music is really good.

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

The Java SDK does not support setting this parameter*.* When calling through HTTP, put presence_penalty into the parameters object.

vl_high_resolution_imagesboolean (Optional) The default value is false

Whether to raise the pixel limit of the input image 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, which uses a fixed resolution strategy and ignores the max_pixels setting; when the resolution is exceeded, the total pixels of the image are scaled down to within this limit.

    Click to view the pixel limits of each model

    When vl_high_resolution_images is True, different models have different pixel limits:

    • Qwen3.7 series, Qwen3.6 series, Qwen3.5 series, Qwen3-VL series models: 16777216 (each Token corresponds to 32*32 pixels, i.e., 16384*32*32)
    • QVQ series and other Qwen2.5-VL series models: 12845056 (each Token corresponds to 28*28 pixels, i.e., 16384*28*28)
  • vl_high_resolution_images is false: the pixel limit is determined by max_pixels. If the pixels of the input image exceed max_pixels, the image is scaled down to within max_pixels. The default pixel limit of each model is the default value of max_pixels.

In the Java SDK, this parameter is vlHighResolutionImages (the minimum required version is 2.20.8). When calling through HTTP, put vl_high_resolution_images into the parameters object.

vl_enable_image_hw_outputboolean (Optional) The default value is false

Whether to return the dimensions of the image after scaling. The model scales the input images; when this is set to True, the height and width of the scaled image are returned. When streaming output is enabled, this information is returned in the last chunk. Supported by Qwen-VL models.

In the Java SDK, this parameter is vlEnableImageHwOutput, and the minimum Java SDK version is 2.20.8*.* When calling through HTTP, put vl_enable_image_hw_output into the parameters object.

max_tokensinteger (Optional, will 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:

  • 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's answer and chain-of-thought content. When the model output exceeds this value, generation stops early and the returned finish_reason is length. Among these models, deepseek-v4.1-flash ignores the thinking_budget parameter.
  • qwen4-max: the maximum number of tokens (thinking plus final answer). max_tokens is equivalent to max_completion_tokens; when this limit is exceeded, generation stops early and finish_reason is length.
  • glm-5.3: max_tokens is the maximum number of tokens for the sum of the model's answer and chain-of-thought content. When the model output exceeds this value, generation stops 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, max_tokens is the maximum number of tokens for the sum of the model's answer and chain-of-thought content. When the model output exceeds this value, generation stops early and the returned finish_reason is length; when thinking_budget is passed, max_tokens only limits the maximum number of tokens of the model's answer, and the token count of the chain-of-thought part is controlled separately by thinking_budget.
  • Other models: the maximum number of tokens of the model's answer (excluding the chain of thought). If the generated content exceeds this value, generation stops 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 model's maximum output length.

Supply methodModelDefault valueMaximum value
Alibaba Cloud directglm-5.3, glm-5.2, glm-5.2-fast-preview, glm-5.1, glm-565536131072
ZHIPU directZHIPU/GLM-5.3, ZHIPU/GLM-5.265536131072

In the Java SDK, this parameter is maxTokens (for Qwen VL models, it is maxLength, in the Java SDK; from version 2.18.4 onwards, it can also be set to maxTokens). When calling through HTTP, put max_tokens into the parameters object.

max_completion_tokensinteger (Optional)

The maximum length of the model's output, including the chain of thought and the model's answer. When the model output exceeds this value, generation stops early and the returned finish_reason is length.

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

Differences from max_tokens: max_completion_tokens always limits the model's complete output (chain of thought + answer); the specific scope limited by max_tokens varies depending on the model and the thinking_budget setting, as described above. For thinking models, 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-k2.5 and later Kimi models
  • GLM: the Alibaba Cloud direct and ZHIPU direct models listed in the table above
  • MiniMax: MiniMax-M2.5 and later MiniMax models
  • DeepSeek: deepseek-v4-pro and later DeepSeek models

Apart from the ZHIPU direct GLM models listed in the table above, the above models do not include other third-party direct 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.

The Java SDK does not support this parameter yet. When calling through HTTP, put max_completion_tokens into the parameters object.

seedinteger (Optional)

The random number seed. Used to ensure that results are reproducible under 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].

When calling through HTTP, put seed into the parameters object.

streamboolean (Optional) The default value is false

Whether to stream the response. Parameter values:

  • false: the model returns the result all at once after generating all the content.
  • true: outputs while generating, i.e., each time part of the content is generated, a chunk is output immediately.

This parameter is only supported by the Python SDK. To implement streaming output with the Java SDK, call through the streamCall interface; to implement streaming output over HTTP, specify X-DashScope-SSE as enable in the Header.

Qwen3 commercial versions (thinking mode), Qwen3 open-source versions, QwQ, and QVQ only support streaming output.

incremental_outputboolean (Optional) The default is false (for Qwen3-Max, Qwen3-VL, Qwen3 open-source versions, QwQ, and QVQ models, the default value is true)

Whether to enable incremental output in streaming output mode. We recommend that you set it to true first.

Parameter value:

  • false: Each output is the entire sequence generated so far, and the last output is the complete generated result.
I
I like
I like apple
I like apple.
  • true (recommended): Incremental output, that is, subsequent output content does not include the content already output. You need to read these fragments one by one in real time to obtain the complete result.
I
like
apple
.

In the Java SDK, it is incrementalOutput. When calling via HTTP, put incremental_output into the parameters object.

QwQ models and Qwen3 models in thinking mode only support setting it to true. Since the default value of Qwen3 commercial models is false, you need to manually set it to true in thinking mode.

Qwen3 open-source models do not support setting it to false.

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

The format of the returned content. Valid values:

  • {"type": "text"}: Outputs a text reply;
  • {"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. The models supported by json_object and json_schema differ. 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 contain the JSON keyword.

In the Java SDK, it is responseFormat*.* When calling via HTTP, put response_format into the parameters object.

Properties

typestring(Required)

The format of the 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.

For the DashScope method, you need to manually construct the JSON Schema. For the format and examples, see Obtain output in a specified format. Java SDK is not supported yet.

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 (we recommend setting it to false, that is, outputting only defined fields). Supported data types: string, number, integer, boolean, object, array, enum. Related documentation: Configuration guide.

strictboolean(Optional)

Whether to strictly follow the structure defined by schema. We recommend setting it to true.

result_formatstring(Optional) Default value: text (the default value is message for Qwen3-Max, Qwen3-VL, QwQ models, and Qwen3 open-source models)

The format of the returned data. We recommend that you set it to message first, which makes it easier to have multi-turn conversations.

The platform will unify the default value to message in the future.

In the Java SDK, it is resultFormat. When calling via HTTP, put result_format into the parameters object.

When the model is Qwen-VL/QVQ, setting text does not take effect.

Qwen3-Max, Qwen3-VL, and Qwen3 models in thinking mode can only be set to message. Since the default value of Qwen3 commercial models is text, you need to set it to message.

If you use the Java SDK to call Qwen3 open-source models and pass in text, the response will still be returned in the message format.

logprobs boolean (Optional) The default value is false

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

  • true

    Return

  • false

    Do not return

The following models are supported:

  • qwen4-max
  • Snapshot models in the qwen-plus series (excluding stable models)
  • qwen3-vl-plus series (including stable models)
  • Qwen3 open-source models

When calling via HTTP, put logprobs into the parameters object.

top_logprobs integer (Optional) The default value is 0

Specifies the number of candidate tokens with the highest probability to return at each generation step.

Value range: [0,5]

Takes effect only when logprobs is true.

In the Java SDK, it is topLogprobs. When calling via HTTP, put top_logprobs into the parameters object.

ninteger(Optional) The default value is 1

The number of responses to generate. Value range: 1-4. For scenarios that require multiple responses (such as creative writing and advertising copy), you can set a larger n value.

Currently, only qwen4-max and Qwen3 (non-thinking mode) models are supported, and the value is fixed to 1 when the tools parameter is passed in.

Setting a larger n value does not increase input token consumption, but increases output token consumption.

When calling via HTTP, put n into the parameters object.

stopstring or array(Optional)

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

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

When stop is an array, you cannot pass token_id and strings as elements at the same time. For example, you cannot specify ["Hello",104307].

When calling via HTTP, put stop into the parameters object.

toolsarray(Optional)

An array containing one or more tool objects for the model to call in Function Calling. Related documentation: Function Calling

When using tools, you must set result_format to message.

You must set the tools parameter both when initiating a Function Calling and when submitting tool execution results.

Properties

typestring(Required)

The tool type. Currently, only function is supported.

functionobject(Required)

Properties

namestring(Required)

The name of the tool function. It must consist of letters and digits, and can contain underscores and hyphens, with a maximum length of 64.

descriptionstring(Required)

A description of the tool function, for the model to determine when and how to call the tool function.

parametersobject (Optional) Default value is {}

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

To improve the accuracy of tool calling, we recommend passing in parameters.

When calling via HTTP, put tools into the parameters object. The qwen-vl series models are not supported yet.

tool_choicestring or object (Optional) Default value is auto

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

  • auto

    The model selects the tool policy on its own;

  • none

    If you want to temporarily disable tool calling in a specific request, set the tool_choice parameter to none;

  • required

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

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

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

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

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

In the Java SDK, it is toolChoice. When calling via HTTP, put tool_choice into the parameters object.

parallel_tool_calls boolean (Optional) Default value is false

Whether to enable parallel tool calls.

Optional values:

  • true: enabled
  • false: disabled.

For more information about parallel tool calls, see Parallel tool calling.

In the Java SDK, it is parallelToolCalls. When calling via HTTP, put parallel_tool_calls into the parameters object.

Text input

Python

import os
import dashscope

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

messages = [
    {'role': 'system', 'content': [{'text': 'You are a helpful assistant.'}]},
    {'role': 'user', 'content': [{'text': 'Who are you?'}]}
]
response = client.multimodal.chat.create(
    # This example uses qwen4-max. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    model="qwen4-max",
    messages=messages,
    )
print(response)

Java

// We recommend that you use DashScope SDK V2.12.0 or later.
import java.util.Arrays;
import java.lang.System;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import java.util.Collections;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    // The following is the base URL for the Singapore region. When making a call, replace {WorkspaceId} with your actual workspace ID. The URL varies by region.
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";}
    public static MultiModalConversationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMsg = MultiModalMessage.builder()
                .role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
                .build();
        MultiModalMessage userMsg = MultiModalMessage.builder()
                .role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "Who are you?")))
                .build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // If you have not configured an environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                // The API keys for the Singapore/US (Virginia) and Singapore regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // This example uses qwen4-max. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
                .model("qwen4-max")
                .messages(Arrays.asList(systemMsg, userMsg))
                .build();
        return conv.call(param);
    }
    public static void main(String[] args) {
        try {
            MultiModalConversationResult result = callWithMessage();
            System.out.println(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // Use a logging framework to record the exception information.
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}

PHP(HTTP)

<?php
$url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation";
// The API keys for the Singapore/US (Virginia) and Singapore regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');

$data = [
    // This example uses qwen4-max. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    "model" => "qwen4-max",
    "input" => [
        "messages" => [
            [
                "role" => "system",
                "content" => [["text" => "You are a helpful assistant."]]
            ],
            [
                "role" => "user",
                "content" => [["text" => "Who are you?"]]
            ]
        ]
    ],
    "parameters" => [
        "result_format" => "message"
    ]
];

$jsonData = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $apiKey",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 200) {
    echo "Response: " . $response;
} else {
    echo "Error: " . $httpCode . " - " . $response;
}

curl_close($ch);
?>

Node.js(HTTP)

DashScope does not provide an SDK for the Node.js environment. To call via the OpenAI Node.js SDK, see the OpenAI section of this document.

import fetch from 'node-fetch';
// The API keys for the Singapore/US (Virginia) and Singapore regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    model: "qwen4-max", // This example uses qwen4-max. Replace the model as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    input: {
        messages: [
            {
                role: "system",
                content: [{ text: "You are a helpful assistant." }]
            },
            {
                role: "user",
                content: [{ text: "Who are you?" }]
            }
        ]
    },
    parameters: {
        result_format: "message"
    }
};

fetch('https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation', {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
    console.log(JSON.stringify(data));
})
.catch(error => {
    console.error('Error:', error);
});

C#(HTTP)

using System.Net.Http.Headers;
using System.Text;

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

    static async Task Main(string[] args)
    {
        // If you have not configured an environment variable, replace the following line with your Model Studio API key: string? apiKey = "sk-xxx";
        // The API keys for the Singapore/US (Virginia) and Singapore regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("The API key is not set. Make sure that the 'DASHSCOPE_API_KEY' environment variable is set.");
            return;
        }

        // Set the request URL and content.
        string url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation";
        // This example uses qwen4-max. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen4-max"",
            ""input"": {
                ""messages"": [
                    {
                        ""role"": ""system"",
                        ""content"": [{""text"": ""You are a helpful assistant.""}]
                    },
                    {
                        ""role"": ""user"",
                        ""content"": [{""text"": ""Who are you?""}]
                    }
                ]
            },
            ""parameters"": {
                ""result_format"": ""message""
            }
        }";

        // Send the request and get the response.
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // Print the result.
        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"))
        {
            // Set the request headers.
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // Send the request and get the response.
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            // Process the response.
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"Request failed: {response.StatusCode}";
            }
        }
    }
}

Go(HTTP)

DashScope does not provide an SDK for Go. To call via the OpenAI Go SDK, see the OpenAI-Go section of this document.

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

type ContentItem struct {
	Text string `json:"text"`
}

type Message struct {
	Role    string        `json:"role"`
	Content []ContentItem `json:"content"`
}

type Input struct {
	Messages []Message `json:"messages"`
}

type Parameters struct {
	ResultFormat string `json:"result_format"`
}

type RequestBody struct {
	Model      string     `json:"model"`
	Input      Input      `json:"input"`
	Parameters Parameters `json:"parameters"`
}

func main() {
	// Create an HTTP client.
	client := &http.Client{}

	// Build the request body.
	requestBody := RequestBody{
		// This example uses qwen4-max. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
		Model: "qwen4-max",
		Input: Input{
			Messages: []Message{
				{
					Role:    "system",
					Content: []ContentItem{{Text: "You are a helpful assistant."}},
				},
				{
					Role:    "user",
					Content: []ContentItem{{Text: "Who are you?"}},
				},
			},
		},
		Parameters: Parameters{
			ResultFormat: "message",
		},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatal(err)
	}

	// Create a POST request.
	req, err := http.NewRequest("POST", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}

	// Set the request headers.
	// If you have not configured an environment variable, replace the following line with your Model Studio API key: apiKey := "sk-xxx"
	// The API keys for the Singapore/US (Virginia) and Singapore regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// Send the request.
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// Read the response body.
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// Print the response content.
	fmt.Printf("%s\n", bodyText)
}

curl

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

The API Keys for the Singapore (China)/Virginia and Beijing regions are different. For more information, see Obtain and configure API Key

curl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen4-max",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": [{"text": "You are a helpful assistant."}]
            },
            {
                "role": "user",
                "content": [{"text": "Who are you?"}]
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

Streaming output

Related documentation: Streaming output.

Text generation model

Python

import os
import dashscope

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

messages = [
    {'role':'system','content':'you are a helpful assistant'},
    {'role': 'user','content': 'Who are you?'}
]
responses = client.chat.completions.create(
    # This example uses qwen-plus; replace with any other text-generation model as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    model="qwen-plus",
    messages=messages,
    stream=True,
    # Streaming output is incremental by default: each chunk contains only the newly generated content.
    )
for response in responses:
    print(response.choices[0].delta.content, end="")

Java

import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
import java.lang.System;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";}
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    private static void handleGenerationResult(GenerationResult message) {
        System.out.println(JsonUtils.toJson(message));
    }
    public static void streamCallWithMessage(Generation gen, Message userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException {
        GenerationParam param = buildGenerationParam(userMsg);
        Flowable<GenerationResult> result = gen.streamCall(param);
        result.blockingForEach(message -> handleGenerationResult(message));
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                // If you have not configured an environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                // The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // This example uses qwen-plus; replace with any other text-generation model as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }
    public static void main(String[] args) {
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("Who are you?").build();
            streamCallWithMessage(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException  e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

curl

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

curl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--header "X-DashScope-SSE: enable" \
--data '{
    "model": "qwen-plus",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters": {
        "result_format": "message",
        "incremental_output":true
    }
}'

Multimodal model

Python

import os
import dashscope

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
            {"text": "What is depicted in the image?"}
        ]
    }
]

responses = client.multimodal.chat.create(
    # You can replace this with another multimodal model and modify the messages accordingly.
    model='qwen3-vl-plus',
    messages=messages,
    stream=True,
    # Streaming output is incremental by default: each chunk contains only the newly generated content.
    )

full_content = ""
print("Streaming output content:")
for response in responses:
    if response.choices[0].delta.content:
        print(response.choices[0].delta.content)
        full_content += response.choices[0].delta.content
print(f"Full content: {full_content}")

Java

import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    public static void streamCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        // must create mutable map.
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
                        Collections.singletonMap("text", "What is depicted in the image?"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
                // If you have not configured an environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen3-vl-plus")  //  Replace with another multimodal model and update messages as needed
                .messages(Arrays.asList(userMessage))
                .incrementalOutput(true)
                .build();
        Flowable<MultiModalConversationResult> result = conv.streamCall(param);
        result.blockingForEach(item -> {
            try {
                var content = item.getOutput().getChoices().get(0).getMessage().getContent();
                    // Check if content exists and is not empty.
                if (content != null &&  !content.isEmpty()) {
                    System.out.println(content.get(0).get("text"));
                    }
            } catch (Exception e){
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

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

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-H 'X-DashScope-SSE: enable' \
-d '{
    "model": "qwen3-vl-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
                    {"text": "What is depicted in the image?"}
                ]
            }
        ]
    },
    "parameters": {
        "incremental_output": true
    }
}'

Image input

For more usage of models analyzing images, see Image and video understanding.

Python

import os
import dashscope

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
            {"text": "What are these?"}
        ]
    }
]
response = client.multimodal.chat.create(
    # This example uses qwen3-vl-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    model='qwen3-vl-plus',
    messages=messages
    )
print(response)

Java

// Copyright (c) Alibaba, Inc. and its affiliates.

import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Main {
    static {
     Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"),
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"),
                        Collections.singletonMap("text", "What are these?"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // If you have not configured an environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // This example uses qwen3-vl-plus. You can replace it with another model name as needed. For a list of models, visit https://www.alibabacloud.com/help/model-studio/getting-started/models
                .model("qwen3-vl-plus")
                .message(userMessage)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

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

The API Keys for the Singapore (China)/Virginia and Beijing regions are different. For more information, see Obtain and configure API Key

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen3-vl-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
                    {"text": "What are these?"}
                ]
            }
        ]
    }
}'

Video input

The following is sample code for passing in video frames. For more usage (such as passing in video files), see Visual understanding.

Python

import os
# DashScope 2.0.1 or later is required.
import dashscope
from dashscope import DashScopeError

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

messages = [{"role": "user",
             "content": [
                 # For Qwen2.5-VL series models, when a list of images is passed, you can set the fps parameter to indicate that the image list is sampled from the original video every 1/fps seconds.
                 {"video":["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"],
                   "fps":2},
                 {"text": "Describe the events in this video"}]}]
try:
    response = client.multimodal.chat.create(
        # This example uses qwen3-vl-plus. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/models
        model='qwen3-vl-plus',
        messages=messages
    )
    print(response)
except DashScopeError as e:
    print(f"HTTP status code: {e.status_code}")
    print(f"Error code: {e.code}")
    print(f"Error message: {e.message}")
    print("See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")

Java

// The DashScope SDK version must be 2.18.3 or later.
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    private static final String MODEL_NAME = "qwen3-vl-plus"; // This example uses qwen3-vl-plus. Replace the model as needed. Model list: https://www.alibabacloud.com/help/en/model-studio/getting-started/models
    public static void videoImageListSample() throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMessage = MultiModalMessage.builder()
                .role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
                .build();
        //  If you use a model from the Qwen2.5-VL series and input a list of images, you can set the fps parameter. This parameter specifies that the images are extracted from the original video every 1/fps seconds.
        Map<String, Object> params = Map.of(
                "video", Arrays.asList("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"),
                "fps",2);
        MultiModalMessage userMessage = MultiModalMessage.builder()
                .role(Role.USER.getValue())
                .content(Arrays.asList(
                        params,
                        Collections.singletonMap("text", "Describe the events in this video")))
                .build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // If you have not configured an environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                // The API keys for the Singapore/US (Virginia) and China (Beijing) regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model(MODEL_NAME)
                .messages(Arrays.asList(systemMessage, userMessage)).build();
        MultiModalConversationResult result = conv.call(param);
        System.out.print(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }
    public static void main(String[] args) {
        try {
            videoImageListSample();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

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

The API Keys for the Singapore (China)/Virginia and Beijing regions are different. For more information, see Obtain and configure API Key

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen3-vl-plus",
  "input": {
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "video": [
              "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"
            ],
            "fps":2

          },
          {
            "text": "Describe the events in this video"
          }
        ]
      }
    ]
  }
}'

Tool calling

For the complete Function Calling workflow code, see Overview.

Python

import os
import dashscope

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "Useful for getting the current time.",
            "parameters": {}
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Useful for getting the weather in a specific city.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city or district, such as Singapore, Hangzhou, or Yuhang District."
                    }
                }
            },
            "required": [
                "location"
            ]
        }
    }
]
messages = [{"role": "user", "content": [{"text": "What is the weather like in Hangzhou?"}]}]
response = client.multimodal.chat.create(
    # This example uses qwen4-max. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    model='qwen4-max',
    messages=messages,
    tools=tools,
)
print(response)

Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.aigc.conversation.ConversationParam.ResultFormat;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import java.util.Collections;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    // The following is the base URL for the Singapore region. When making a call, replace {WorkspaceId} with your actual workspace ID. The URL varies by region.
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";}
    public class GetWeatherTool {
        private String location;
        public GetWeatherTool(String location) {
            this.location = location;
        }
        public String call() {
            return location+"The weather is sunny today";
        }
    }
    public class GetTimeTool {
        public GetTimeTool() {
        }
        public String call() {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String currentTime = "Current time: " + now.format(formatter) + ".";
            return currentTime;
        }
    }
    public static void SelectTool()
            throws NoApiKeyException, ApiException, InputRequiredException {
        SchemaGeneratorConfigBuilder configBuilder =
                new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
        SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
                .without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
        SchemaGenerator generator = new SchemaGenerator(config);
        ObjectNode jsonSchema_weather = generator.generateSchema(GetWeatherTool.class);
        ObjectNode jsonSchema_time = generator.generateSchema(GetTimeTool.class);
        FunctionDefinition fdWeather = FunctionDefinition.builder().name("get_current_weather").description("Gets the weather for a specified area")
                .parameters(JsonUtils.parseString(jsonSchema_weather.toString()).getAsJsonObject()).build();
        FunctionDefinition fdTime = FunctionDefinition.builder().name("get_current_time").description("Gets the current time")
                .parameters(JsonUtils.parseString(jsonSchema_time.toString()).getAsJsonObject()).build();
        MultiModalMessage systemMsg = MultiModalMessage.builder().role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant. When asked a question, use tools wherever possible.")))
                .build();
        MultiModalMessage userMsg = MultiModalMessage.builder().role(Role.USER.getValue()).content(Arrays.asList(Collections.singletonMap("text", "Weather in Hangzhou"))).build();
        List<MultiModalMessage> messages = new ArrayList<>();
        messages.addAll(Arrays.asList(systemMsg, userMsg));
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // The API keys for the Singapore/US (Virginia) and Singapore regions are different. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // This example uses qwen4-max. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
                .model("qwen4-max")
                .messages(messages)
                .tools(Arrays.asList(
                        ToolFunction.builder().function(fdWeather).build(),
                        ToolFunction.builder().function(fdTime).build()))
                .build();
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(JsonUtils.toJson(result));
    }
    public static void main(String[] args) {
        try {
            SelectTool();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(String.format("Exception %s", e.getMessage()));
        }
        System.exit(0);
    }
}

curl

The API Keys for the Singapore (China)/Virginia and Beijing regions are different. For more information, see Obtain and configure API Key

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

The following is the URL for the Singapore region.

curl --location "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen4-max",
    "input": {
        "messages": [{
            "role": "user",
            "content": [{"text": "What is the weather like in Hangzhou?"}]
        }]
    },
    "parameters": {
        "result_format": "message",
        "tools": [{
            "type": "function",
            "function": {
                "name": "get_current_time",
                "description": "Useful for getting the current time.",
                "parameters": {}
            }
        },{
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Useful for getting the weather in a specific city.",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city or district, such as Singapore, Hangzhou, or Yuhang District."
                        }
                    }
                },
                "required": ["location"]
            }
        }]
    }
}'

Asynchronous Call

# Your DashScope Python SDK version must be 2.0.1 or later.
import asyncio
import platform
import os
import dashscope

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
aclient = dashscope.AsyncClient(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

async def main():
    response = await aclient.multimodal.chat.create(
        # This example uses qwen4-max. You can replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
        model="qwen4-max",
        messages=[{"role": "user", "content": [{"text": "Who are you?"}]}],
    )
    print(response)

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

Document understanding

Python

import os
import dashscope

# The following is the configuration for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when making a call. The region value varies by region.
# Currently, the qwen-long model is only available in the China (Beijing) region.
client = dashscope.Client(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    # The API keys are different for different regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

messages = [
        {'role': 'system', 'content': 'you are a helpful assisstant'},
        # Replace {FILE_ID} with the file ID used in your actual conversation scenario.
        {'role':'system','content':'fileid://{FILE_ID}'},
        {'role': 'user', 'content': 'What is this article about?'}]
response = client.chat.completions.create(
    model="qwen-long",
    messages=messages,
)
print(response)

Java

import os
import dashscope

# Currently, the qwen-long model can be called only in the China (Beijing) region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
        {'role': 'system', 'content': 'you are a helpful assisstant'},
        # Replace '{FILE_ID}' with the file-id used in your actual conversation scenario.
        {'role':'system','content':f'fileid://{FILE_ID}'},
        {'role': 'user', 'content': 'What is this article about?'}]
response = dashscope.Generation.call(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-long",
    messages=messages,
    result_format="message",
)
print(response)

curl

Currently, only the Beijing region supports calling document understanding models

Replace {FILE_ID} with the file-id actually used in your conversation scenario

curl --location "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "system",
                "content": "fileid://{FILE_ID}"
            },
            {
                "role": "user",
                "content": "What is this article about?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

chat response object (streaming and non-streaming output formats are the same)

request_idstring

The unique identifier of this call.

The Java SDK return parameter is requestId.

codestring

Error code, returned when the call fails.

Python SDK 2.0 does not return the envelope fields when a call fails; instead, it throws a DashScopeError (e.code/e.status_code/e.message/e.request_id).

outputobject

The call result information.

Properties

textstring

The reply generated by the model. When the input parameter result_format is set to text, the reply content is returned to this field.

finish_reasonstring

This parameter is not empty when the input parameter result_format is set to text.

There are four cases:

  • null while generation is in progress;
  • stop when generation ends due to natural completion of the model output, or when a stop condition in the input parameters is triggered;
  • length when generation ends due to excessive generation length;
  • tool_calls when a tool call occurs.

choicesarray

The model output information. The choices parameter is returned when result_format is message.

Properties

finish_reasonstring

There are four cases:

  • null while generation is in progress;
  • stop when generation ends due to natural completion of the model output, or when a stop condition in the input parameters is triggered;
  • length when generation ends due to excessive generation length;
  • tool_calls when a tool call occurs.

messageobject

The message object output by the model.

Properties

rolestring

The role of the output message, fixed to assistant.

contentstring or array

The content of the output message. It is an array when using qwen-vl or qwen-audio series models, and a string in all other cases.

If Function Calling is initiated, this value is empty.

Properties

textstring

The content of the output message when using qwen-vl or qwen-audio series models.

image_hwarray

When the vl_enable_image_hw_output parameter is enabled for Qwen-VL series models, there are two cases:

  • Image input: returns the height and width of the image (numeric unit: pixels)
  • Video input: returns an empty array

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 model's deep thinking content.

tool_callsarray

If the model needs to call tools, the tool_calls parameter is generated.

Properties

functionobject

The name of the tool to call, and the input parameters.

Properties

namestring

The name of the tool to call

argumentsstring

The parameters to be input into the tool, as a JSON string.

Due to the inherent randomness of large model responses, the output JSON string may not always satisfy your function. It is recommended that you validate the parameters before passing them to the function.

index integer

The index of the current tool_calls object in the tool_calls array.

id string

The ID of this tool response.

type string

The tool type, fixed as function.

logprobsobject

The probability information of the current choices object.

Properties

content array

An array of tokens with log probability information.

Properties

token string

The current Token.

bytes array

The list of raw UTF‑8 bytes of the current Token, used to accurately reconstruct the output content, which is helpful when processing emojis and Chinese characters.

logprob float

The log probability of the current Token. A returned value of null 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

The list of raw UTF‑8 bytes of the current Token, used to accurately reconstruct the output content, which is helpful when processing emojis and Chinese characters.

logprob float

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

usagemap

The token information used in this chat request.

Properties

input_tokens integer

The length of the user input content after being converted into tokens. Additional notes

output_tokens integer

The length of the model output content after being converted into tokens.

input_tokens_details object (optional)

Details of the length of the input content after being converted into tokens.

Properties

text_tokens integer (optional)

The length of the input text after being converted into tokens.

image_tokens integer (optional)

The length of the input images after being converted into tokens.

video_tokens integer (optional)

The length of the input video files or image list after being converted into tokens.

total_tokens integer

This field is returned when the input is plain text. It is the sum of input_tokens and output_tokens.

image_tokens integer

This field is returned when the input content contains image. It is the length of the image content input by the user after being converted into tokens.

video_tokens integer

This field is returned when the input content contains video. It is the length of the video content input by the user after being converted into tokens.

audio_tokens integer

This field is returned when the input content contains audio. It is the length of the audio content input by the user after being converted into tokens.

output_tokens_details object (optional)

Details of the length of the output content after being converted into tokens. Some models return this field.

Properties

text_tokens integer (optional)

The length of the output text after conversion to tokens.

reasoning_tokens integer (optional)

The length of the thinking process after conversion to tokens. Only reasoning models return this field.

audio_tokens integer (optional)

The length of the output audio after conversion to tokens. Only models with audio output return this field.

prompt_tokens_details object

The fine-grained classification of input tokens.

Properties

cached_tokens integer

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

cache_creation object

Information about explicit cache creation.

Properties

ephemeral_5m_input_tokens integer

The token length used to create an explicit cache with a 5-minute validity period.

cache_creation_input_tokens integer

The token length used to create an explicit cache.

cache_type string

When explicit cache is used, the parameter value is ephemeral; otherwise, this parameter does not exist.

{
  "request_id": "902fee3b-f7f0-9a8c-96a1-6b4ea25af114",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "I am a large-scale language model developed by Alibaba Cloud, and my name is Qwen."
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 22,
    "output_tokens": 17,
    "total_tokens": 39
  }
}

Error codes

If a model call fails and returns an error message, see Error codes for troubleshooting.