All Products
Search
Document Center

Alibaba Cloud Model Studio:DashScope API Reference

Last Updated:Sep 17, 2026

You can call Qwen models using the DashScope API. This topic describes the input and output parameters and provides call examples.

Singapore

HTTP request address:

  • Plain text 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

The base_url for the SDK call configuration is as follows:

Python code

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(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";

US (Virginia)

HTTP request address:

  • Plain text models: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
  • Qwen-VL models: POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

The base_url for the SDK call configuration is as follows:

Python code

dashscope.base_http_api_url = 'https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1'

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(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 address:

  • Plain text 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

The base_url for the SDK call configuration is as follows:

Python code

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(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 address:

  • Plain text 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

The base_url for the SDK call configuration is as follows:

Python code

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com/api/v1'

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(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 address:

  • For plain text models, such as qwen-plus: POST https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
  • For 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

The base_url for the SDK call configuration is as follows:

Python code

dashscope.base_http_api_url = 'https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1'

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(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 address:

  • Plain text models, such as qwen-plus: POST https://{WorkspaceId}.ap-northeast-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-northeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

The base_url for the SDK call configuration is as follows:

Python code

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-northeast-1.maas.aliyuncs.com/api/v1'

Java code

  • Method 1:
import com.alibaba.dashscope.protocol.Protocol;
Generation gen = new Generation(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";

Replace {WorkspaceId} with your actual workspace ID.

You must obtain an API key and configure it as an environment variable. If you use the DashScope SDK to make calls, you must also install the DashScope SDK.

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

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

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

Request body

modelstring(Required)

The name of the model to use.

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

For specific model names and billing details, seeSelect a model.

messagesarray(Required)

The context to pass to the large language model (LLM), arranged in conversational order.

When you call over HTTP, place messages in the input object.

Message types

System Messageobject (Optional)

A system message that is used to set the role, tone, task objectives, or constraints for the LLM. It is usually placed first in the messages array.

We do not recommend that you set a system message for QwQ models. A system message does not take effect for QVQ models.

Properties

contentstring(Required)

The content of the message.

rolestring(Required)

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

User Messageobject(Required)

A user message that is used to pass questions, instructions, or context to the model.

Properties

contentstring or array(Required)

The content of the message. If the input is only text, this parameter is a string. If the input includes multimodal data, such as images, or if explicit caching is enabled, this parameter is an array.

Properties

textstring(Required)

The input text.

imagestring (Optional)

The image file for image understanding. You can pass an image in one of 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: {"image":"https://xxxx.jpeg"}

videoarray or string (Optional)

The video to pass when you use a Qwen-VL model or a QVQ model.

  • If you pass an image list, the type is array.
  • If you pass a video file, the type is string.

To pass a local file, see Local file (Qwen-VL) or Local file (QVQ).

Examples:

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

fpsfloat(Optional)

The number of frames to extract per second. The value must be in the range of [0.1, 10]. The default value is 2.0.

Description

The fps parameter has two functions:

  • When a video file is the input, this parameter controls the frame extraction frequency. One frame is extracted every f p s 1 ​ seconds.

    This applies to Qwen-VL models and QVQ models.

  • It informs the model of the time interval between adjacent frames, which helps the model better understand the video's temporal dynamics. This applies to both video file and image list inputs. This feature is suitable for scenarios such as event time localization or summarizing content by segment.

    This is supported by Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen2.5-VL, and QVQ models.

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

Examples

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

max_framesinteger(Optional)

The maximum number of frames that can be extracted from a video. If the number of frames calculated based on fps exceeds max_frames, the system automatically adjusts to extract frames uniformly within the max_frames limit. This ensures that the total number of frames does not exceed the limit.

Value range

  • qwen3.7 series, qwen3.6 series, qwen3.5 series: The maximum and default value is 8000.
  • qwen3-vl-plus series, qwen3-vl-flash series, qwen3-vl-235b-a22b-thinking, qwen3-vl-235b-a22b-instruct: The maximum and default value is 2000.
  • qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: The maximum and default value is 512.

Sample value

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

When you call with an OpenAI-compatible API, you cannot customize the max_frames parameter. The API automatically uses the default value for each model.

min_pixelsinteger(Optional)

Sets the minimum pixel threshold for the input image or video frames. If the total pixels of an input image or video frame are less than min_pixels, the image or frame is enlarged until its total pixels are higher than min_pixels.

Value range

  • Image input:
    • Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL: The default and minimum value is 65536.
    • qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: The default and minimum value is 4096.
    • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: The default and minimum value is 3136.
  • Video file or image list input:
    • Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL (commercial and open source editions), qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: The default value is 65536, and the minimum value is 4096.
    • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: The default value is 50176, and the minimum value is 3136.

Examples

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

max_pixelsinteger(Optional)

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

Value range

  • Image input:

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

    • If 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.
      • qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: The default value is 1310720, and the maximum value is 16777216.
      • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: The default value is 1003520, and the maximum value is 12845056.
    • If vl_high_resolution_images is True:

      • Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: max_pixels is invalid. The maximum pixels for the input image is fixed at 16777216.
      • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: max_pixels is invalid. The maximum pixels for the input image is fixed at 12845056.
  • Video file or image list input:
    • qwen3.7 series, qwen3.6 series, qwen3.5 series, qwen3-vl-plus series, qwen3-vl-flash series, qwen3-vl-235b-a22b-thinking, qwen3-vl-235b-a22b-instruct: The default value is 655360, and the maximum value is 2048000.
    • Other Qwen3-VL open source models, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: The default value is 655360, and the maximum value is 786432.
    • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: The default value is 501760, and the maximum value is 602112.

Examples

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

total_pixelsinteger(Optional)

Limits the total pixels of all frames that are extracted from a video (pixels of a single frame × total number of frames). If the total pixels of the video exceed this limit, the system scales down the video frames but still ensures that the pixel value of a single frame is within the [min_pixels, max_pixels] range. This applies to Qwen-VL and QVQ models.

For long videos with many extracted frames, you can appropriately lower this value to reduce token consumption and processing time, but this may result in the loss of image details.

Value range

  • qwen3.7 series, qwen3.6 series, qwen3.5 series: The default and maximum value is 819200000. This value corresponds to 800000 image tokens (1 image token per 32×32 pixels).
  • qwen3-vl-plus series, qwen3-vl-flash series, qwen3-vl-235b-a22b-thinking, qwen3-vl-235b-a22b-instruct: The default and maximum value is 134217728. This value corresponds to 131072 image tokens (1 image token per 32×32 pixels).
  • Other Qwen3-VL open source models, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815: The default and minimum value is 67108864. This value corresponds to 65536 image tokens (1 image token per 32×32 pixels).
  • Other qwen-vl-plus models, other qwen-vl-max models, Qwen2.5-VL open source series, and QVQ series models: The default and minimum value is 51380224. This value corresponds to 65536 image tokens (1 image token per 28×28 pixels).

Examples

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

cache_controlobject(Optional)

This is supported only by models that support explicit caching. It is used to enable explicit caching.

Properties

type string(Required)

The value must be ephemeral.

rolestring(Required)

The role for a user message. The value must be user.

Assistant Message object(Optional)

The model's reply to the user message.

Properties

contentstring(Optional)

The content of the message. This is optional only if the tool_calls parameter is specified in the assistant message.

rolestring(Required)

The value must be assistant.

partialboolean(Optional)

Specifies whether to enable partial mode. For more information and a list of supported models, see Partial mode.

tool_calls array(Optional)

The tool and input parameter information that is returned after you initiate a function call. It contains one or more objects. This is obtained from the tool_calls field of the previous model response.

Properties

id string

The ID of the tool response.

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 string format.

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. It must be in string format.

rolestring(Required)

The value must be tool.

tool_call_idstring(Optional)

The ID that is returned after you initiate a function call. You can retrieve it using response.output.choices[0].message.tool_calls[$index]["id"]. It is used to mark the tool that corresponds to the tool message.

temperaturefloat(Optional)

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

A higher temperature results in more diverse text, and a lower temperature results in more deterministic text.

Value range: [0, 2)

When you call over HTTP, place temperature in the parameters object.

We do not recommend that you modify the default temperature value for QVQ models.

top_pfloat(Optional)

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

A higher top_p value results in more diverse text, and a lower top_p value results in more deterministic text.

Value range: (0, 1.0].

In the Java SDK, this parameter is topP. When you call over HTTP, place top_p in the parameters object.

We do not recommend that you modify the default top_p value for QVQ models.

top_kinteger(Optional)

The size of the candidate set for sampling during generation. For example, if you set this parameter to 50, only the 50 tokens with the highest scores in a single generation are used to form the candidate set for random sampling. A larger value increases randomness, and a smaller value increases determinism. A value of None or a value greater than 100 indicates that the top_k strategy is not enabled and only the top_p strategy takes effect.

The value must be greater than or equal to 0.

Default top_k values

QVQ series: 10

QwQ series: 40

models before the rest of the qwen-vl-plus series, : 1

All other models: 20

GLM series (provided by Alibaba Cloud): 20

DeepSeek, Kimi, and MiniMax series do not support the top_k parameter.

In the Java SDK, this parameter is topK. When you call over HTTP, place top_k in the parameters object.

We do not recommend that you modify the default top_k value for QVQ models.

enable_thinking boolean (Optional)

Specifies whether to enable thinking mode for a hybrid thinking model. This applies to Qwen3.7, Qwen3.6, Qwen3.5, Qwen3, and Qwen3-VL models, along with the DeepSeek-V4-Pro/V4-Flash series, DeepSeek-V3.2/V3.2-exp/V3.1 series, Kimi-K2.6/K2.5 series, and GLM series. The DeepSeek-V4 series has thinking mode enabled by default. You can adjust the inference effort with the reasoning_effort parameter.

Valid values:

  • true: The feature is enabled.

    If enabled, the thinking content is returned in the reasoning_content field.

  • false: Disabled

For the default values for different models, see Supported models.

In the Java SDK, this parameter is enableThinking. When you call over HTTP, place enable_thinking in the parameters object.

preserve_thinking boolean (Optional) The default value is false. (Default value for qwen3.8-max/qwen3.8-flash:true)

Specifies whether to append the reasoning_content from assistant messages in the conversation history to the model input. This is suitable for scenarios where the model needs to refer to the historical thinking process.

Currently supported by qwen3.7-max, qwen3.7-max-2026-05-20 and subsequent snapshots, qwen3.6-max-preview, 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, qwen3.8-max (enabled by default), qwen3.8-max-0902 (enabled by default), qwen3.8-flash (enabled by default), kimi-k2.6 (deployed on Alibaba Cloud Model Studio), kimi-k2.7-code (deployed on Alibaba Cloud Model Studio, enabled by default), kimi/kimi-k2.7-code-highspeed (supplied by Moonshot AI, enabled by default), and kimi/kimi-k2.7-code (supplied by Moonshot AI, enabled by default).

Important (qwen3.8-max/qwen3.8-flash): When using qwen3.8-max/qwen3.8-flash, preserve_thinking defaults to true. You must send back all historical reasoning_content in the reasoning_content field. Do NOT concatenate reasoning_content into the content field. Doing so may degrade model performance.

  • If the historical messages do not contain reasoning_content, enabling this parameter does not cause an error.
  • When enabled, the reasoning_content from the historical conversation is included in the input token count and is billed.

When you call over HTTP, place preserve_thinking in the parameters object. The Java SDK is not supported.

thinking_budget integer (Optional)

The maximum length of the thinking process. This applies to Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen3, GLM and Kimi models, except kimi-k3, which does not support this parameter. For more information, see Limit thinking length.

The default value is the maximum chain-of-thought length for the model. For more information, see Select a model.

In the Java SDK, this parameter is thinkingBudget. When you call over HTTP, place thinking_budget in the parameters object.

The default value is the maximum chain-of-thought length for the model.

reasoning_effort string (Optional)

Controls the inference intensity of models. The valid values and default values vary by model.

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

Valid values: high (high-intensity inference) and max (maximum-intensity inference). low and medium are mapped to high, and xhigh is mapped to max.

This applies to glm-5.2, glm-5.1, glm-5, deepseek-v4.1-flash, deepseek-v4-pro, and deepseek-v4-flash.

glm-5.3: Default value:max

Valid values: max (deep inference), high (enhanced inference), and low (light inference). Passing any other value returns an error.

This model always thinks. enable_thinking only accepts true; passing false causes the API request to fail.

Qwen3.8 series models: Default value:xhigh

Valid values:

  • xhigh (default): Maximum-intensity inference
  • medium: Standard inference
  • low: Low-intensity inference

OpenAI standard value mapping: max is mapped to xhigh, high is mapped to xhigh, minimal is mapped to low, and none is mapped to enable_thinking=False.

Setting values other than the above valid values and mapped values will cause an error.

For the qwen3.8 series, reasoning_effort and thinking_budget cannot be set at the same time. Setting both will cause an error. However, they support mutual conversion:

  • When thinking_budget is not set, the reasoning_effort levels are 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 default reasoning_effort (xhigh) are used.

When you call over HTTP, place reasoning_effort in the parameters object.

tool_stream boolean (Optional) The default value is false.

This parameter only affects the streaming output behavior of complex tool parameters and is effective only in streaming calls. Simple tool parameters, where all parameter types are strings, can be streamed as long as streaming calls are enabled. tool_stream has no effect on them. Complex tools are tools where some parameter types in the tool definition are arrays or objects. Currently, only the Qwen and GLM series support this.

Qwen series support list:
  • qwen-max series: Text modality of the qwen3.8-max and qwen3.7-max series
  • qwen-plus series: Text modality of the qwen3.7-plus and qwen3.6-plus series, and all modalities of the qwen3.5-plus series
  • qwen-flash series: All modalities of the qwen3.8-flash, qwen3.7-flash, qwen3.6-flash and qwen3.5-flash series
Qwen series usage reference:
  • tool_stream=false: Complex tool parameters are output all at once. This is the default behavior, and the complex format is more accurate.
  • tool_stream=true: Complex tool parameters are streamed. This avoids the risk of timeout for complex formats.

Complex tools are tools where some parameter types in the tool definition are arrays or objects.

GLM series support list: glm-4.6, glm-4.7, glm-5, and glm-5.1.

GLM series usage reference:
  • tool_stream=false: Tool parameters are output all at once. This is the default behavior, and the complex format is more accurate.
  • tool_stream=true: Tool parameters are streamed. This avoids the risk of timeout for complex formats.

When you call over HTTP, place tool_stream in the parameters object.

enable_code_interpreter boolean (Optional) The default value is false.

Specifies whether to enable the code interpreter feature. For more information, see Code interpreter.

Valid values:

  • true: Enables the feature.
  • false: Disables the feature.

The Java SDK is not supported. When you call over HTTP, place enable_code_interpreter in the parameters object.

clear_thinkingboolean(Optional) The default value is false.

Controls whether to use the reasoning_content (thinking process) from previous turns as context input for the model in a multi-turn conversation. This is supported only by the GLM series models glm-5.3, glm-5.2, glm-5.1, glm-5, and glm-4.7. The default value is true for glm-5.3 and false for the other models.

  • true: Enables the feature. This ignores the reasoning_content from previous turns and uses only visible text, tool calls, and results as context input. This can reduce context length and cost.
  • false (default): Disables the feature. This retains the reasoning_content from previous turns and provides it to the model along with the context. If you want to enable preserved thinking, you must pass the historical reasoning_content completely, unmodified, and in its original order in the messages. Missing, trimming, rewriting, or reordering degrades performance or prevents the feature from taking effect.

repetition_penaltyfloat(Optional)

The penalty for repeating consecutive sequences during model generation. A higher repetition_penalty value can reduce repetition in the model's output. A value of 1.0 indicates no penalty. The value must be greater than 0.

In the Java SDK, this parameter is repetitionPenalty. When you call over HTTP, place repetition_penalty in the parameters object.

When you use the qwen-vl-plus_2025-01-25 model for text extraction, we recommend that you set repetition_penalty to 1.0.

We do not recommend that you modify the default repetition_penalty value for QVQ models.

presence_penaltyfloat(Optional)

Controls the content repetition when the model generates text.

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

In scenarios that require diversity, fun, or creativity, such as creative writing or brainstorming, you can increase this value. In scenarios that emphasize consistency and term accuracy, such as technical documents or formal texts, you can decrease this value.

Default presence_penalty values

Qwen3.8 (non-thinking mode), Qwen3.7 (non-thinking mode), Qwen3.6 (non-thinking mode), Qwen3.5-Omni, Qwen3.5 (non-thinking mode), qwen3-max-preview (thinking mode), Qwen3 (non-thinking mode), Qwen3-Instruct series/1.7b/4b (thinking mode), QVQ series, qwen-max, qwen2.5-vl series, qwen-vl-max series, qwen-vl-plus, Qwen3-VL (non-thinking): 1.5;

qwen3-8b/14b/32b/30b-a3b/235b-a22b (thinking mode), qwen-plus/qwen-plus-latest/2025-04-28 (thinking mode), qwen-turbo/qwen-turbo/2025-04-28 (thinking mode): 0.5;

All others are 0.0.

DeepSeek series (supplied by Alibaba Cloud): deepseek-r1, deepseek-r1-0528, deepseek-r1-distill-qwen distilled version: 1;

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

Kimi series (supplied by Moonshot AI): 0.0;

MiniMax series (supplied by Alibaba Cloud): MiniMax-M2.5, MiniMax-M2.1: 0.0;

Other DeepSeek, Kimi, GLM, and 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 text. The penalty is not related to the number of times the token appears. This reduces the likelihood of these tokens reappearing, thus reducing content repetition and increasing word diversity.

Example

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 2.0: This movie is great. The plot is fantastic, the acting is superb, and the music is also very beautiful. Overall, the entire film is just incredible. It is actually truly outstanding. The storyline is very exciting, the performances are excellent, and the soundtrack is so moving.

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

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

When you use the qwen-vl-plus model for text extraction, set presence_penalty to 1.5.

Do not modify the default presence_penalty value for QVQ models.

The Java SDK does not support setting this parameter*.* When you call over HTTP, place presence_penalty in the parameters object.

vl_high_resolution_imagesboolean(Optional) Default value: false

Specifies whether to increase the pixel limit for input images to the pixel count that corresponds to 16384 tokens. For more information, see Processing high-resolution images.

  • vl_high_resolution_images: true uses a fixed resolution strategy and ignores the max_pixels setting. If the resolution is exceeded, the total pixel count of the image is scaled down to stay within this limit.

    Click to view the pixel limits for each model

    When vl_high_resolution_images is True, the pixel limits vary by model:

    • For the Qwen3.8 series, Qwen3.7 series, Qwen3.6 series, Qwen3.5 series, Qwen3-VL series, qwen-vl-max, qwen-vl-max-0813, qwen-vl-plus, qwen-vl-plus-0815, and models, the value is 16777216. (Each Token corresponds to 32*32 pixels. The total value is calculated as 16384*32*32.)
    • QVQ series, other Qwen2.5-VL series models: 12845056 (1 token corresponds to 28*28 pixels, which is 16384*28*28)
  • vl_high_resolution_images is false, the pixel limit is determined by max_pixels. If the input image's pixel count exceeds max_pixels, the image is scaled down to within the max_pixels limit. The default pixel limit for each model is the default value of max_pixels.

In the Java SDK, this parameter is vlHighResolutionImages (requires V2.20.8 or later). When you call over HTTP, place vl_high_resolution_images in the parameters object.

vl_enable_image_hw_outputboolean(Optional) The default value is false.

Specifies whether to return the dimensions of the scaled image. The model scales the input image. If you set this parameter to True, it returns the height and width of the scaled image. If streaming output is enabled, this information is returned in the last chunk. This is supported by Qwen-VL models.

In the Java SDK, this parameter is vlEnableImageHwOutput. The minimum required Java SDK version is 2.20.8*.* When you call over HTTP, place vl_enable_image_hw_output in the parameters object.

max_tokensinteger(Optional, to be deprecated)

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

The meaning of this parameter varies by model:

  • deepseek-v4.1-flash, deepseek-v4-pro, deepseek-v4-pro-0813, deepseek-v4-flash, deepseek-v4-flash-0731: The maximum number of tokens for the sum of the model's answer and chain-of-thought content. If the model's output exceeds this value, generation stops early, and the returned 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. If the model's 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, and if the model's output exceeds this value, generation stops early with the returned finish_reason being length. When the thinking_budget parameter is passed, max_tokens is the maximum number of tokens for the model's answer only, and the number of tokens for the chain-of-thought part is controlled separately by thinking_budget.
  • Other models: The maximum number of tokens for the model's answer (excluding 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 are both the model's maximum output length.

In the Java SDK, this parameter is maxTokens. For Qwen-VL models, it is maxLength in the Java SDK, but versions later than 2.18.4 also support setting it as maxTokens. When you call over HTTP, place max_tokens in 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. If the model's output exceeds this value, generation stops early, and the returned finish_reason is length.

The default and maximum values are both the model's maximum output length.

Difference from max_tokens: max_completion_tokens limits the complete model output (chain-of-thought + answer), while max_tokens only limits the answer part. For thinking models, we recommend that you use max_completion_tokens.

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 models
  • GLM: glm-5 and later models
  • MiniMax: MiniMax-M2.5 and later models
  • DeepSeek: deepseek-v3, deepseek-r1, deepseek-r1-0528, deepseek-v3.1, deepseek-v3.2, deepseek-v3.2-exp, deepseek-v4-pro, deepseek-v4-flash, and later models

The models listed above do not include models supplied directly by third parties.

There may be a difference of up to 10 tokens between the actual output token count and the specified max_completion_tokens value.

The Java SDK does not currently support this parameter. When you call over HTTP, place max_completion_tokens in the parameters object.

seedinteger(Optional)

A random number seed. This parameter is used to ensure reproducible results with the same input and parameters. If you pass the same seed value in a call and other parameters remain unchanged, the model returns the same result as much as possible.

Value range: [0,2<sup>31</sup>−1].

When you call over HTTP, place seed in the parameters object.

streamboolean(Optional)The default value is false.

Specifies whether to stream the reply. The valid values are:

  • false: The model generates all content and then returns the result at once.
  • true: The model generates and outputs content on the fly. This means that the model immediately outputs a chunk of content as soon as it is generated.

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

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

incremental_outputboolean(Optional) The default is false. For Qwen3-Max, Qwen3-VL, Qwen3 open source edition, QwQ, and QVQ models, the default is true.

Specifies whether to enable incremental output in streaming output mode. We recommend that you set this parameter to true.

Value:

  • false: Each output contains the entire sequence that is generated so far. The last output is the complete generated result.
I
I like
I like apple
I like apple.
  • true (recommended): The output is incremental. Subsequent output does not include previously output content. You must read these chunks one by one in real time to obtain the complete result.
I
like
apple
.

In the Java SDK, this parameter is incrementalOutput. When you call over HTTP, place incremental_output in the parameters object.

QwQ models and Qwen3 models in thinking mode support only setting this parameter to true. Because the default value for Qwen3 commercial edition models is false, you must manually set it to true in thinking mode.

Qwen3 open source edition models do not support setting this parameter to false.

response_formatobject (Optional) The default value is {"type": "text"}.

The format of the returned content. The valid values are:

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

For more information, see Structured output. The json_object and json_schema modes support different models. For more information, see Supported models.

If you specify {"type": "json_object"}, you must explicitly instruct the model to output JSON in the prompt, such as "Please output in JSON format". Otherwise, an error occurs. If you specify {"type": "json_schema", ...}, the prompt does not need to contain the JSON keyword.

In the Java SDK, this parameter is responseFormat. When you call over HTTP, place response_format in the parameters object.

Properties

typestring(Required)

The format of the returned content. The valid values are:

  • text: Outputs a text reply.
  • json_object: Outputs a JSON string in a 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. Defines the JSON structure that the model output must follow. For more information, see Getting structured output.

When you call the model through DashScope, you must construct the JSON Schema manually. For the format and examples, see Getting structured output. The 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 list the required fields, and additionalProperties to control whether fields that are not defined in the schema can be returned. We recommend that you set additionalProperties to false so that only defined fields are returned. Supported data types: string, number, integer, boolean, object, array, and enum. For more information, see Configuration guide.

strictboolean(Optional)

Specifies whether to strictly follow the structure defined by schema. We recommend that you set this parameter to true.

result_formatstring(Optional)The default is text. For Qwen3-Max, Qwen3-VL, QwQ models, Qwen3 open source models (except qwen3-next-80b-a3b-instruct), the default is message.

The format of the returned data. We recommend that you set this parameter to message to facilitate multi-turn conversations.

The platform will later unify the default value to message.

In the Java SDK, this parameter is resultFormat. When you call over HTTP, place result_format in the parameters object.

If the model is Qwen-VL, QVQ, setting the value to text has no effect.

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

If you use the Java SDK to call a Qwen3 open source model and pass text, the response is still returned in message format.

logprobs boolean (Optional) The default value is false.

Specifies whether to return the log probabilities of the output tokens. The valid values are:

  • true

    Back

  • false

    You cannot return.

The following models are supported:

  • Snapshot models of the qwen-plus series (excluding stable edition models)
  • Snapshot models of the qwen-turbo series (excluding stable edition models)
  • qwen3-vl-plus series (including stable edition models)
  • qwen3-vl-flash series (including stable edition models)
  • Qwen3 open source models

When you call over HTTP, place logprobs in the parameters object.

top_logprobs integer (Optional) The default value is 0.

Specifies the number of most likely candidate tokens to return at each generation step.

Value range: [0, 5]

This parameter takes effect only if logprobs is true.

In the Java SDK, this parameter is topLogprobs. When you call over HTTP, place top_logprobs in the parameters object.

ninteger(Optional) The default value is 1.

The number of responses to generate. The value range is 1-4. For scenarios that require multiple responses to be generated, such as creative writing or ad copy, you can set a larger n value.

Currently, only Qwen3 (non-thinking mode) models are supported. The value is fixed at 1 if the tools parameter is passed.

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

When you call over HTTP, place n in the parameters object.

stopstring or array(Optional)

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

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

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

When you call over HTTP, place stop in the parameters object.

toolsarray(Optional)

An array that contains one or more tool objects for the model to call during function calling. For more information, see Function calling.

When you use tools, you must set result_format to message.

When you initiate function calling or submit tool execution results, you must set the tools parameter.

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 numbers, and can contain underscores and hyphens. The maximum length is 64 characters.

descriptionstring(Required)

A description of the tool function, which helps the model to choose when and how to call the tool function.

parametersobject(Optional) The default value is {}.

A description of the tool's parameters, which needs to be a valid JSON Schema. For a description of JSON Schema, see this link. If the parameters parameter is empty, it means the tool has no input parameters, such as a time query tool.

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

When you call over HTTP, place tools in the parameters object. This is temporarily not supported for qwen-vl series models.

tool_choicestring or object(Optional) The default value is auto.

The tool selection strategy. You can set this parameter to force a tool call method for a specific type of problem, such as always using a certain tool or disabling all tools.

  • auto

    The LLM chooses the tool strategy autonomously.

  • none

    If you want to temporarily disable tool calls in a specific request, you can set the tool_choice parameter to none.

  • required

    To force at least one tool to be called, set the tool_choice parameter to required, and the model will always return tool call information.

    The Qwen series models do not support required: in non-thinking mode it cannot guarantee that a tool is always called, and in thinking mode required is not supported.

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

    If you want to force a call to a specific tool, you can 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, this parameter is toolChoice. When you call over HTTP, place tool_choice in the parameters object.

parallel_tool_calls boolean (Optional) The default value is false.

Specifies whether to enable parallel tool calls.

Valid values:

  • true: Enabled
  • false: Disabled.

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

In the Java SDK, this parameter is parallelToolCalls. When you call over HTTP, place parallel_tool_calls in the parameters object.

Text input

Python

import os
from dashscope import MultiModalConversation
import dashscope

# The following is the base_url for the Singapore region. When making a call, replace {WorkspaceId} with your actual workspace ID. The URLs for different regions vary.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
    {'role': 'system', 'content': [{'text': 'You are a helpful assistant.'}]},
    {'role': 'user', 'content': [{'text': 'Who are you?'}]}
]
response = MultiModalConversation.call(
    # If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="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
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen3.8-max", # This example uses qwen3.8-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
    messages=messages,
    )
print(response)

Java

// We recommend that you use DashScope SDK V2.12.0 or later.
import java.util.Arrays;
import java.util.Collections;
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 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.protocol.Protocol;

public class Main {
    public static MultiModalConversationResult callWithMessage() throws ApiException, NoApiKeyException, UploadFileException {
        // The following is the base_url for the Singapore region. When making a call, replace {WorkspaceId} with your actual workspace ID. The URLs for different regions vary.
        MultiModalConversation conv = new MultiModalConversation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
        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 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 qwen3.8-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("qwen3.8-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 | UploadFileException 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 China (Beijing) 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 qwen3.8-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" => "qwen3.8-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 make calls using the OpenAI Node.js SDK, see the OpenAI section in this topic.

import fetch from 'node-fetch';
// 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
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    model: "qwen3.8-max", // This example uses qwen3.8-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
    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 China (Beijing) 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 qwen3.8-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"": ""qwen3.8-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 make calls using the OpenAI Go SDK, see the OpenAI-Go section in this topic.

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 qwen3.8-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: "qwen3.8-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 China (Beijing) 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

Replace {WorkspaceId} with your actual workspace ID.

The API keys for the Singapore, US (Virginia), and China (Beijing) regions are different. For more information, see Obtain an 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.8-max",
    "input":{
        "messages":[
            {
                "role": "system",
                "content": [{"text": "You are a helpful assistant."}]
            },
            {
                "role": "user",
                "content": [{"text": "Who are you?"}]
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

dashscope CLI

Call via the dashscope command line.

export DASHSCOPE_API_KEY="your-api-key"
# Replace {WorkspaceId} with your workspace ID, ap-southeast-1 with your region (e.g., us-east-1, 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 via natural language, see

DashScope SDK Expert.

For the complete region table, see Base URL overview.

Streaming output

For more information, see Streaming output.

Text generation models

import os
import dashscope

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
    {'role':'system','content':'you are a helpful assistant'},
    {'role': 'user','content': 'Who are you?'}
]
responses = dashscope.Generation.call(
    # If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="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
    api_key=os.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=messages,
    result_format='message',
    stream=True,
    incremental_output=True
    )
for response in responses:
    print(response)
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.protocol.Protocol;

public class Main {
    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(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
            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 --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 models

import os
from dashscope import MultiModalConversation
import dashscope

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

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 = MultiModalConversation.call(
    # 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: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model='qwen3-vl-plus',  #  You can replace this with another multimodal model and modify the messages accordingly.
    messages=messages,
    stream=True,
    incremental_output=True)

full_content = ""
print("Streaming output content:")
for response in responses:
    if response["output"]["choices"][0]["message"].content:
        print(response.output.choices[0].message.content[0]['text'])
        full_content += response.output.choices[0].message.content[0]['text']
print(f"Full content: {full_content}")
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")  //  You can replace this with another multimodal model and modify the messages accordingly.
                .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 -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 information about how to use large language models (LLMs) to analyze images, see Image and video understanding.

Python

import os
import dashscope

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
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 = dashscope.MultiModalConversation.call(
    # The API keys for the Singapore, Virginia, and Beijing regions are different. To get an API key, visit https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # This example uses qwen-vl-max. 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='qwen-vl-max',
    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 the environment variable, replace the next line with .apiKey("sk-xxx") and use your Model Studio API key.
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // This example uses qwen-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("qwen-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

Replace {WorkspaceId} with your actual workspace ID.

The API keys for the Singapore, US (Virginia), and China (Beijing) regions are different. To obtain an API key, see Get an 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": "qwen-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 examples show how to input video frames. For more information about other methods, such as inputting a video file, see Visual understanding.

Python

import os
# The DashScope SDK version must be 1.20.10 or later.
import dashscope

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [{"role": "user",
             "content": [
                  # 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.
                 {"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"}]}]
response = dashscope.MultiModalConversation.call(
    # If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # API keys are different for the Singapore/Virginia and Beijing regions. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model='qwen-vl-max',  # This example uses qwen-vl-max. Replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/models
    messages=messages
)
print(response["output"]["choices"][0]["message"].content[0]["text"])

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 = "qwen-vl-max"; // This example uses qwen-vl-max. Replace it with another model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/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 the environment variable, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                // API keys are different for the Singapore/Virginia and Beijing regions. 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

Replace {WorkspaceId} with your actual workspace ID.

The API keys are different for the Singapore, US (Virginia), and China (Beijing) regions. For more information, see Get an 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": "qwen-vl-max",
  "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 code of the function calling flow, see Overview.

Python

import os
import dashscope

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
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 Beijing, Hangzhou, or Yuhang District."
                    }
                }
            },
            "required": [
                "location"
            ]
        }
    }
]
messages = [{"role": "user", "content": [{"text": "What is the weather like in Hangzhou?"}]}]
response = dashscope.MultiModalConversation.call(
    # If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
    # The API keys for the Singapore, Virginia, and Beijing regions are different. To get an API key, visit: https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # This example uses qwen3.8-max. You can replace it with another model as needed. For a list of models, visit: https://www.alibabacloud.com/help/model-studio/getting-started/models
    model='qwen3.8-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 + " 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, Virginia, and Beijing regions are different. To get an API key, visit: https://www.alibabacloud.com/help/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // This example uses qwen3.8-max. You can replace it with another model as needed. For a list of models, visit: https://www.alibabacloud.com/help/model-studio/getting-started/models
                .model("qwen3.8-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

Replace {WorkspaceId} with your actual workspace ID.

The API keys for the Singapore, US (Virginia), and China (Beijing) regions are different. For more information, see Get an API key

The following URL is 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": "qwen3.8-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 Beijing, Hangzhou, or Yuhang District."
                        }
                    }
                },
                "required": ["location"]
            }
        }]
    }
}'

Asynchronous invocation

# Your Dashscope Python SDK must be version 1.19.0 or later.
import asyncio
import platform
import os
import dashscope
from dashscope.aigc.multimodal_conversation import AioMultiModalConversation

# The following base_url is for the Singapore region. Replace {WorkspaceId} with your actual workspace ID. The URL varies by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
async def main():
    response = await AioMultiModalConversation.call(
        # If you do not configure an environment variable, replace the next line with api_key="sk-xxx", where sk-xxx is your Model Studio API key.
        # The API keys for the Singapore, Virginia, and Beijing regions are different. To get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
        api_key=os.getenv('DASHSCOPE_API_KEY'),
        # This example uses the qwen3.8-max model. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
        model="qwen3.8-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

# Currently, the qwen-long-latest 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 assistant'},
        # 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-latest",
    messages=messages,
    result_format='message'
)
print(response)

Java

import os
import dashscope

# Currently, the qwen-long-latest 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 assistant'},
        # 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-latest",
    messages=messages,
    result_format='message'
)
print(response)

curl

Currently, only the China (Beijing) region supports calling the document understanding model.

Replace {FILE_ID} with the file ID that is used in your actual conversation scenario.

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" \
--data '{
    "model": "qwen-long-latest",
    "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 consistent)

status_codestring

The status code of the request. A value of 200 indicates that the request was successful. Otherwise, the request failed.

The Java SDK does not return this parameter. If the call fails, an exception is thrown. The exception message contains the content of status_code and message.

request_idstring

The unique ID for this call.

The Java SDK returns the parameter as requestId.

codestring

The error code. This field is empty if the call is successful.

Only the Python SDK returns this parameter.

outputobject

The information about the call result.

Properties

textstring

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

finish_reasonstring

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

This can occur in the following four situations:

  • null while generating
  • stop if the model output ends naturally or triggers a stop condition in the input parameters
  • The process was terminated because the generated output was too long.
  • When a tool call occurs, the value is tool_calls.

choicesarray

The model's output information. The choices parameter is returned if result_format is message.

Properties

finish_reasonstring

The value can be one of the following:

  • null while generating
  • stop if the model output ends naturally or triggers a stop condition in the input parameters
  • The generation terminates for the reason length, which means the output is too long.
  • The tool_calls reason indicates that a tool call occurred.

messageobject

The message object that is output by the model.

Properties

rolestring

The role of the output message, which must be assistant.

contentstring or array

The content of the output message. This is an array if you use qwen-vl or qwen-audio series models, and a string in other cases.

If function calling is initiated, this value is empty.

Properties

textstring

The content of the output message if you use qwen-vl or qwen-audio series models.

image_hwarray

If the vl_enable_image_hw_output parameter is enabled for a Qwen-VL series model, there are two cases:

  • Image input: Returns the height and width of the image in pixels.
  • Video input: Returns an empty array.

reasoning_content string

The model's deep thinking content.

tool_callsarray

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

Properties

functionobject

The name of the tool that is being called and its input parameters.

Properties

namestring

The name of the tool that is being called.

argumentsstring

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

Due to the randomness of the LLM's response, the output JSON string may not always satisfy your function. We recommend that you validate the parameters before you input them into 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, which must be function.

logprobsobject

The probability information for the current choices object.

Properties

content array

An array of tokens with log probability information.

Properties

token string

The current token.

bytes array

A list of the raw UTF-8 bytes of the current token. This is useful for accurately reconstructing the output content, especially when you handle emojis and Chinese characters.

logprob float

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

top_logprobs array

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

Properties

token string

The current token.

bytes array

A list of the raw UTF-8 bytes of the current token. This is useful for accurately reconstructing the output content, especially when you handle emojis and Chinese characters.

logprob float

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

usagemap

The token information for this chat request.

Properties

input_tokens integer

The length of the user input content after it is converted to tokens. For more information, see Additional information.

output_tokens integer

The length of the model output content after it is converted to tokens.

input_tokens_details object (Optional)

Details of the length of the input content after it is converted to tokens.

Properties

text_tokens integer (Optional)

The length of the input text after it is converted to tokens.

image_tokens integer (Optional)

The length of the input image after it is converted to tokens.

video_tokens integer (Optional)

The length of the input video file or image list after it is converted to tokens.

total_tokens integer

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

image_tokens integer

This field is returned if the input content includes an image. It is the length of the user's input image content after it is converted to tokens.

video_tokens integer

This field is returned if the input content includes a video. It is the length of the user's input video content after it is converted to tokens.

audio_tokens integer

This field is returned if the input content includes an audio. It is the length of the user's input audio content after it is converted to tokens.

output_tokens_details object (Optional)

Details of the length of the output content after it is converted to tokens. This field is returned only by some models.

Properties

text_tokens integer (Optional)

The length of the output text after it is converted to tokens.

reasoning_tokens integer (Optional)

The length of the thinking process after it is converted to tokens. This field is returned only for reasoning models.

audio_tokens integer (Optional)

The length of the output audio after it is converted to tokens. This field is returned only for audio output models.

prompt_tokens_details object

A 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 length of the tokens that are used to create an explicit cache with a 5-minute validity period.

cache_creation_input_tokens integer

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

cache_type string

If you use explicit caching, the parameter value is ephemeral. Otherwise, this parameter does not exist.

{
  "status_code": 200,
  "request_id": "902fee3b-f7f0-9a8c-96a1-6b4ea25af114",
  "code": "",
  "message": "",
  "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 the model call fails and an error message is returned, see Error codes to resolve the issue.