Skip to main content
Visual understanding

Image and video understanding

Visual understanding models can answer questions based on the images or videos that you provide. They support single or multiple image inputs and are suitable for various tasks, such as image captioning, visual question answering, and object localization.

Try it online: Go to the Alibaba Cloud Model Studio console. In the upper-right corner of the page, select the destination region. Then, go to the Vision Models page to try out the models.

Getting started

Prerequisites
  • Obtain an API key and configure it as an environment variable.
  • To make calls using an SDK, install the SDK. The DashScope Python SDK must be version 1.24.6 or later, and the DashScope Java SDK must be version 2.21.10 or later.
The following examples show how to call a model to describe image content. For more information about local files and image limits, see Pass local files and Image limits.
  • OpenAI compatible
  • DashScope
  • Python
  • Node.js
  • Java
  • curl
from openai import OpenAI
import os

client = OpenAI(
    # API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. When you make a call, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

completion = client.chat.completions.create(
    model="qwen3.8-max",  # This example uses qwen3.7-plus. You can replace it with another model as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
                    },
                },
                {"type": "text", "text": "What scene is depicted in the image?"},
            ],
        },
    ],
)
print(completion.choices[0].message.content)

Response

This is a photo taken on a beach. In the photo, a person and a dog are sitting on the sand with the sea and sky in the background. The person and the dog seem to be interacting, with the dog's front paw on the person's hand. Sunlight shines from the right side of the frame, adding a warm atmosphere to the scene.

Model performance

Image Q&A

Describe the content of an image or classify and label it, such as identifying people, places, animals, and plants.

p1021359

What item in this image should I use if the sun is too bright?

If the sun is too bright, you should use the pink sunglasses in the image. Sunglasses can effectively block strong light, reduce UV damage to your eyes, and help protect your vision and improve visual comfort in bright sunlight.

Creative writing

Generate vivid text descriptions based on image or video content, suitable for creative scenarios such as story writing, copywriting, and short video scripts.

vl-Q&A

Please write an interesting social media post based on the content of the image.

Sure. This image is filled with a rich Mid-Autumn Festival atmosphere, cleverly combining classical and modern elements. Based on the main elements in the image, I have prepared several social media posts in different styles for you to choose from.

Poetic and beautiful style

Tonight, the moon is bright for all to see, but who knows where the autumn thoughts will fall? Chang'e flies to the moon, and the Jade Rabbit pounds medicine. The romance of the ancients is lit up tonight. May this bright moon light your way home and carry my deepest thoughts. Happy Mid-Autumn Festival!

Warm Wishes Style

The moon is full, and people are reunited. The Mid-Autumn night is the gentlest. Watch the fireworks bloom, admire the full moon in the sky, take a bite of a mooncake, and want for good health. May all that you and I want for come true. Happy Mid-Autumn Festival to everyone, and may your families be happy!

Text recognition and information extraction

Recognize text and formulas in images, or extract information from receipts, certificates, and forms. Supports formatted text output.

-q2cdz6jy89b6m3kp

Extract the following from the image: ['Invoice Code', 'Invoice Number', 'Destination', 'Fuel Surcharge', 'Fare', 'Date', 'Departure Time', 'Train Number', 'Seat Number']. Please output in JSON format.

{

"Invoice Code": "221021325353",

"Invoice Number": "10283819",

"Destination": "Development Zone",

"Fuel Surcharge": "2.0",

"Fare": "8.00<Full>",

"Date": "2013-06-29",

"Departure Time": "Rolling",

"Train Number": "040",

"Seat Number": "371"

}

Multi-disciplinary problem solving

Solve math, physics, chemistry, and other problems in images. Suitable for K-12, university, and adult education.

-5jwcstcvmdpqghaj

Solve the math problem in the graph step by step.

-answer

Visual programming

Generate code from images or videos. You can use this feature to generate HTML, CSS, and JS code from design drafts, website screenshots, and more.

code

Create a webpage using HTML and CSS based on my sketch. The main color should be black.

code-preview

Webpage preview

Object localization

Supports 2D and 3D localization. You can use this feature to determine object orientation, perspective changes, and occlusion relationships. 3D localization is a new capability added to the Qwen3-VL model.
The object localization performance of the Qwen2.5-VL model is robust within the resolution range of 480 × 480 to 2560 × 2560. Outside this range, the detection accuracy may decrease, with occasional detection frame drift.
For information about how to draw the localization results on the original image, see FAQ.
2D localization
-530xdcos1lqkcfuy
  • Return Box (bounding box) coordinates: Detect all food items in the image and output their bbox coordinates in JSON format.
  • Return Point (centroid) coordinates: Locate all food items in the image as points and output their point coordinates in XML format.
Visualization of 2D localization results
-mu9podu1eyvph1zd
3d
Detect the car in the image and predict its 3D position. Output JSON: [{"bbox_3d": [x_center, y_center, z_center, x_size, y_size, z_size, roll, pitch, yaw], "label": "category"}].
3d-result

Document parsing

Parse image-based documents (such as scanned copies or image PDFs) into QwenVL HTML or QwenVL Markdown format. This format not only accurately recognizes text but also obtains the position information of elements such as images and tables. The Qwen3-VL model adds the ability to parse into Markdown format.
The recommended prompts are as follows: qwenvl html (to parse into HTML format) or qwenvl markdown (to parse into Markdown format).

image

qwenvl markdown.

-result

Visualization of results

Video understanding

Analyze video content, such as locating specific events and obtaining timestamps, or generating summaries of key time periods.
Please describe the series of actions of the person in the video. Output the start time (start_time), end time (end_time), and event (event) in JSON format. Use HH:mm:ss for the timestamp.{"events": [{"start_time": "00:00:00","end_time": "00:00:05","event": "The person walks towards the table holding a cardboard box and places it on the table."},{"start_time": "00:00:05","end_time": "00:00:15","event": "The person picks up a scanner and scans the label on the cardboard box."},{"start_time": "00:00:15","end_time": "00:00:21","event": "The person puts the scanner back in its place and then picks up a pen to record information in a notebook."}]}

Core features

Enable or disable thinking mode

  • The qwen3.8, qwen3.7, qwen3.6, qwen3.5, qwen3-vl-plus, and qwen3-vl-flash series models are hybrid thinking models. They can either think before responding or respond directly. Use the enable_thinking parameter to control whether to enable thinking mode:
    • true: Enables thinking mode. The default value for the qwen3.8, qwen3.7, qwen3.6, and qwen3.5 series models is true.
    • false: Disables thinking mode. The default value for the qwen3-vl-plus and qwen3-vl-flash series models is false.
  • Models with the thinking suffix, such as qwen3-vl-235b-a22b-thinking, are thinking-only models. They always think before responding, and this feature cannot be disabled.
  • Model configuration: In general conversation scenarios that do not involve Agent tool calls, do not set a System Message to maintain optimal performance. You can pass instructions such as model role settings and output format requirements through the User Message.
  • Prioritize streaming output: When thinking mode is enabled, both streaming and non-streaming output are supported. To avoid timeouts caused by excessively long responses, prioritize using streaming output.
  • Limit thinking length: Deep thinking models sometimes output lengthy reasoning processes. You can use the thinking_budget parameter to limit the length of the thinking process. If the number of tokens generated during the model's thinking process exceeds the thinking_budget, the inference content is truncated, and the model immediately starts generating the final response. The default value of thinking_budget is the model's maximum chain-of-thought length. For more information, see the model list.
  • OpenAI compatible
  • DashScope
The enable_thinking parameter is not a standard OpenAI parameter. If you use the OpenAI Python SDK, pass it through extra_body.
import os
from openai import OpenAI

client = OpenAI(
    # API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. When you make a call, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
)

reasoning_content = ""  # Define the complete thinking process
answer_content = ""     # Define the complete response
is_answering = False   # Determine whether to end the thinking process and start responding
enable_thinking = True
# Create a chat completion request
completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://img.alicdn.com/imgextra/i1/O1CN01gDEY8M1W114Hi3XcN_!!6000000002727-0-tps-1024-406.jpg"
                    },
                },
                {"type": "text", "text": "How do I solve this problem?"},
            ],
        },
    ],
    stream=True,
    # The enable_thinking parameter enables the thinking process, and the thinking_budget parameter sets the maximum number of tokens for the inference process.
    # Use the enable_thinking parameter to switch the thinking mode.
    extra_body={
        'enable_thinking': enable_thinking,
        "thinking_budget": 81920},

    # Uncomment the following lines to return token usage in the last chunk.
    # stream_options={
    #     "include_usage": True
    # }
)

if enable_thinking:
    print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")

for chunk in completion:
    # If chunk.choices is empty, print the usage.
    if not chunk.choices:
        print("\nUsage:")
        print(chunk.usage)
    else:
        delta = chunk.choices[0].delta
        # Print the thinking process.
        if hasattr(delta, 'reasoning_content') and delta.reasoning_content is not None:
            print(delta.reasoning_content, end='', flush=True)
            reasoning_content += delta.reasoning_content
        else:
            # Start responding.
            if delta.content != "" and is_answering is False:
                print("\n" + "=" * 20 + "Complete response" + "=" * 20 + "\n")
                is_answering = True
            # Print the response process.
            print(delta.content, end='', flush=True)
            answer_content += delta.content

# print("=" * 20 + "Complete thinking process" + "=" * 20 + "\n")
# print(reasoning_content)
# print("=" * 20 + "Complete response" + "=" * 20 + "\n")
# print(answer_content)

Multiple image inputs

Visual understanding models support passing multiple images in a single request, which can be used for tasks such as product comparison and multi-page document processing. To do this, simply include multiple image objects in the content array of the user message.
The number of images is limited by the model's total token limit for images and text. The total token count for all images and text must not exceed the model's maximum input.
  • OpenAI compatible
  • DashScope
  • Python
  • Node.js
  • curl
import os
from openai import OpenAI

client = OpenAI(
    # API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. When you make a call, replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3.8-max",  #  This example uses qwen3.7-plus. You can replace it with another model as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    messages=[
        {"role": "user","content": [
            {"type": "image_url","image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},},
            {"type": "image_url","image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},},
            {"type": "text", "text": "What content do these images depict?"},
            ],
        }
    ],
)

print(completion.choices[0].message.content)

Response

Image 1 shows a scene of a woman and a Labrador retriever interacting on a beach. The woman is wearing a plaid shirt and sitting on the sand, shaking hands with the dog. The background is the ocean waves and the sky, and the whole picture is full of warmth and joy.

Image 2 shows a scene of a tiger walking in a forest. The tiger's coat is orange with black stripes. It is stepping forward, surrounded by dense trees and vegetation, and the ground is covered with fallen leaves. The whole picture gives a feeling of wild nature.

Video understanding

Visual understanding models can understand video content provided as an image list (video frames) or a video file. The following examples show how to understand online videos or image lists specified by a URL. For more information about video limits or the number of images that can be passed in an image list, see Video limits.
For better performance when understanding video files, use the latest or recent snapshot versions of the models.
  • Video files
  • Image list
Visual understanding models analyze video content by extracting a sequence of frames from the video. You can control the frame extraction strategy with the following two parameters:
  • fps: Controls the frame extraction frequency. One frame is extracted every f p s 1 ​ seconds. The value range is [0.1, 10], and the default value is 2.0.
    • For scenes with fast motion, set a higher fps value to capture more detail.
    • For static scenes or long videos, set a lower fps value to improve performance.
  • max_frames: The maximum number of frames to extract from a video. The system calculates the total frames based on the video's fps. If the total number of frames exceeds this limit, the system automatically samples frames evenly to meet the limit. This parameter is available only when using the DashScope SDK.
  • OpenAI compatible
  • DashScope
When you send a video file directly to the visual understanding model using the OpenAI SDK or HTTP, set the "type" parameter in the user message to "video_url".
Python
import os
from openai import OpenAI

client = OpenAI(
    # API keys vary by region. To get an API key, see https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    # If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. When you make a call, replace {WorkspaceId} with your workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[
        {
            "role": "user",
            "content": [
                # When you pass a video file directly, set the value of type to video_url.
                {
                    "type": "video_url",
                    "video_url": {
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"
                    },
                    "fps": 2
                },
                {
                    "type": "text",
                    "text": "What is the content of this video?"
                }
            ]
        }
    ]
)

print(completion.choices[0].message.content)

Pass a local file (Base64 encoding or file path)

Visual understanding models support two methods for uploading local files: Base64 encoding and direct file path upload. You can choose an upload method based on the file size and SDK type. For recommendations, see How to choose a file upload method. Both methods must meet the file requirements described in Image limitations.
  • Upload using Base64 encoding
  • Upload using a file path
Convert the file to a Base64-encoded string and then pass it to the model. This method is applicable to OpenAI and DashScope SDKs, and HTTP requests.
  1. Encode the file: Convert the local image to a Base64 encoding.
    # Encoding function: Converts a local file to a Base64-encoded string
    import base64
    def encode_image(image_path):
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode("utf-8")
    
    # Replace xxx/eagle.png with the absolute path of your local image
    base64_image = encode_image("xxx/eagle.png")
    
  2. Build a Data URL in the following format: data:[MIME_type];base64,{base64_image}.
    1. Replace MIME_type with the actual media type. Ensure that it matches the MIME Type value in the Supported image formats table, such as image/jpeg or image/png.
    2. base64_image is the Base64 string generated in the previous step.
  3. Call the model: Pass the Data URL using the image or image_url parameter.
  • Image
  • Video file
  • Image list
  • Pass using a file path
  • Base64-encoded input
Python
import os
import dashscope

# The following URL is for the Singapore region. When you call the API, 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'

# Replace xxx/eagle.png with the absolute path of your local image
local_path = "xxx/eagle.png"
image_path = f"file://{local_path}"
messages = [
                {'role':'user',
                'content': [{'image': image_path},
                            {'text': 'What scene is depicted in the image?'}]}]
response = dashscope.MultiModalConversation.call(
    # API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    # If you have not configured the 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.7-plus',  # This example uses qwen3.7-plus. You can change the model name as needed. For a list of models, see https://www.alibabacloud.com/help/model-studio/getting-started/models
    messages=messages)
print(response.output.choices[0].message.content[0]["text"])

Process high-resolution images

The visual understanding model API has a limit on the number of visual tokens for a single encoded image. With default configurations, high-resolution images are compressed, which may cause loss of detail and affect understanding accuracy. Enable vl_high_resolution_images or adjust max_pixels to increase the number of visual tokens. This retains more image details and improves understanding.
If the pixel count of the input image exceeds the model's pixel limit, the image is downscaled to fit within the limit.

Model

Pixels per token

vl_high_resolution_images

max_pixels

Token limit

Pixel limit

Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5 and Qwen3-VL series models

32×32

true

max_pixels is invalid

16,384 tokens

16,777,216 (that is, 16,384 × 32 × 32)

false (default)

Customizable. The default value is 2,621,440 and the maximum value is 16,777,216.

Determined by max_pixels, which is max_pixels / 32 / 32

max_pixels

qwen-vl-max, qwen-vl-plus

32 x 32

true

max_pixels is invalid

16,384 tokens

16,777,216 (that is, 16,384 × 32 × 32)

false (default)

Customizable. The default value is 1,310,720 and the maximum value is 16,777,216.

Determined by max_pixels, which is max_pixels / 32 / 32

max_pixels

Other qwen-vl-max, other qwen-vl-plus, open source Qwen2.5-VL series, and QVQ series models

28 × 28

true

max_pixels is invalid

16,384 tokens

12,845,056 (that is, 16,384 × 28 × 28)

false (default)

Customizable. The default value is 1,003,520 and the maximum value is 12,845,056.

Determined by max_pixels, which is max_pixels / 28 / 28

max_pixels

  • When vl_high_resolution_images=true, the API uses a fixed resolution policy and ignores the max_pixels setting. This is suitable for recognizing fine text, small objects, or rich details in images.
  • When vl_high_resolution_images=false, the final pixel limit depends on the value of the max_pixels parameter.
    • For cost-sensitive scenarios where you want to reduce visual token consumption: Use the default value of max_pixels or set it to a smaller value. max_pixels mainly affects the number of visual tokens and the call cost. In our tests, lowering it has no significant effect on the end-to-end response time. To reduce latency, see Response speed and model selection.
    • If you want to focus on certain details and can accept a lower processing speed, increase the value of max_pixels as needed.

Response speed and model selection

In latency-sensitive scenarios, the response time is mainly determined by the model that you select, not by max_pixels. The following table compares the response times of qwen-vl-max and qwen-vl-plus under the same input conditions:

Model

Average response time

Characteristics

qwen-vl-max

About 12s

High-accuracy recognition. Suitable for images with rich details and low error tolerance.

qwen-vl-plus

About 8s

Balanced speed and accuracy. About 39% faster than qwen-vl-max.

The response times above are measured reference values for a single 2480x3508 pixel image (qwen-vl-max: 12.75s and 11.84s, 12.29s on average; qwen-vl-plus: 8.29s and 6.75s, 7.52s on average). Actual latency varies with image size, output length, and network conditions. These values are for reference only and are not a performance commitment.
  • Enabling streaming output (stream=True) significantly reduces the time to first token: for the same request, the first token returns in about 0.95 seconds, while the total time of the complete response remains unchanged. This suits interactive scenarios that need to show feedback as early as possible.
  • For latency-sensitive image recognition scenarios such as workflows: Use qwen-vl-plus with stream=True to get the first token in about 1 second. Switch to qwen-vl-max only when the recognition accuracy of qwen-vl-plus does not meet your requirements. Adjusting max_pixels is not a way to improve speed.
  • OpenAI compatible
  • DashScope
vl_high_resolution_images is not a standard OpenAI parameter. The method for passing it varies across different language SDKs:
  • Python SDK: Must be passed through the extra_body dictionary.
  • Node.js SDK: Can be passed directly as a top-level parameter.
Python
import os
import time
from openai import OpenAI

client = OpenAI(
    # API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. When you call the API, replace {WorkspaceId} with your actual workspace ID. The URL varies by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[
        {"role": "user","content": [
            {"type": "image_url","image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250212/earbrt/vcg_VCG211286867973_RF.jpg"},
            # max_pixels represents the maximum pixel threshold for the input image. It is invalid when vl_high_resolution_images=True. When vl_high_resolution_images=False, it is customizable, and the maximum value varies by model.
            # "max_pixels": 16384 * 32 * 32
            },
           {"type": "text", "text": "What festival atmosphere does this image convey"},
            ],
        }
    ],
    extra_body={"vl_high_resolution_images":True}

)
print(f"Model output: {completion.choices[0].message.content}")
print(f"Total input tokens: {completion.usage.prompt_tokens}")

More usages

Limits

Input file limits

  • Image limits
  • Video limits
  • Image resolution:
    • Minimum size: The width and height of the image must both be greater than 10 pixels.
    • Aspect ratio: The ratio of the long side to the short side for both original and scaled images must not exceed 200:1.
      For information about the image scaling logic, see the smart_resize function in Calculate image tokens
    • Maximum pixels:
      • Keep the image resolution within 8K (7680x4320). Images with a higher resolution may cause API call timeouts because of large file sizes and long network transmission times.
      • Automatic scaling: The model can adjust the image size using max_pixels and min_pixels. Providing high-resolution images does not improve detection accuracy. Instead, it increases the risk of failed calls. Scale images to a reasonable size on the client before uploading.
  • Supported image formats
    • For resolutions below 4K (3840x2160), the following image formats are supported:

      Image format

      Common extensions

      MIME type

      BMP

      .bmp

      image/bmp

      JPEG

      .jpe, .jpeg, .jpg

      image/jpeg

      PNG

      .png

      image/png

      TIFF

      .tif, .tiff

      image/tiff

      WEBP

      .webp

      image/webp

      HEIC

      .heic

      image/heic

    • For resolutions between 4K (3840x2160) and 8K (7680x4320), only the JPEG, JPG, and PNG formats are supported.
  • Image size: The following limits apply to each individual image. For multi-image input, each image is evaluated independently and the sizes are not aggregated.
    • When passed as a public URL: A single image cannot exceed 20 MB for Qwen3.8, Qwen3.7, Qwen3.6, and Qwen3.5 and Qwen3-VL series models. For other models, a single image cannot exceed 10 MB.
    • When passed as a local path: A single image cannot exceed 10 MB.
    • When passed as Base64 encoding (OpenAI-compatible API): For Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5 and Qwen3-VL series models, the original image file before encoding cannot exceed 20 MB. For other models, it cannot exceed 10 MB. In both cases, the resulting Data URI string cannot exceed 20 MB.
    • When passed as Base64 encoding (Anthropic-compatible API): The total request body cannot exceed6 MB. When passing multiple images, they share this quota.
    These limits depend on the model you use. They cannot be raised by purchasing a higher-tier plan or upgrading the model version.
    To compress a file, see How to compress an image or video to the required size.
  • Image quantity limit: The maximum number of images supported for multi-image input varies by the input method:
    • When passed as public URLs or local paths:
      • Qwen3.8-Max, Qwen3.8-Flash, Qwen3.7-Plus series: Up to 2,048 images
      • Qwen3.7-Flash, Qwen3.6-Plus, Qwen3.6-Flash, Qwen3.5-Plus, Qwen3.5-Flash, Qwen3-VL, Qwen-VL, QVQ series: Up to 256 images
      • For Qwen-Omni series, see Omni-modal.
    • When passed as Base64-encoded strings: Up to 250 images
The total number of tokens for all images is also limited by the model's maximum input token limit. The total token count for all images and text must not exceed the model's maximum input.

File input methods

  • Public URL: Provide a publicly accessible file address that supports the HTTP or HTTPS protocol. For optimal stability and performance, upload the file to OSS to obtain a public URL. Model Studio cannot access OSS internal endpoints, whose addresses contain -internal, such as https://<bucket>.oss-cn-hangzhou-internal.aliyuncs.com/image.jpg. If you pass an internal address, the file download fails and InvalidParameter is returned with the message Failed to download multimodal content. Use an OSS public endpoint instead, such as https://<bucket>.oss-cn-hangzhou.aliyuncs.com/image.jpg, or a presigned OSS URL.
    To ensure the model can successfully download the file, the response header of the public URL must include Content-Length (file size) and Content-Type (media type, such as image/jpeg). If either field is missing or incorrect, the file download will fail.
  • Base64 encoding: Convert the file to a Base64-encoded string and then pass it.
  • Local file path (DashScope SDK only): Pass the path of a local file.
For recommendations on how to choose a file input method, see How do I choose a file upload method?

Using in a production environment

  • Image and video pre-processing: Visual understanding models have size limits for input files. To compress files, see Image or video compression methods.
  • Processing text files: Visual understanding models only support image and video files. They do not support processing TXT, Word (.doc/.docx), PDF, or other text-based files. Use one of the following workarounds:
    • Convert the text file to an image format. Use an image processing library, such as pdf2image for Python, to convert the file page by page into multiple high-quality images. Then, pass the images to the model using the multi-image input method.
    • Use Qwen-Long, which supports uploading documents and conducting conversations by passing information through file-id.
  • Fault tolerance and stability
    • Timeout handling: In non-streaming calls, a timeout error occurs if the model does not finish generating output within 300 seconds. When a timeout occurs, the generated content is returned in the response body. A response header that contains x-dashscope-partialresponse: true indicates that the response timed out. Use the partial mode feature, which is supported by some models. Add the generated content to the messages array and send the request again. This allows the Large Language Model (LLM) to continue generating content. For more information, see Continue generation from incomplete output.
    • Client-side timeout configuration: The preceding timeout is a server-side timeout that occurs when the model does not finish generating output within 300 seconds. It is different from the default client-side timeout of the SDK. When you process large images, such as a 4000 x 4000 pixel image, a request may take longer than the default client-side timeout of the SDK and be interrupted with an APITimeoutError, even though the server-side 300-second limit is not reached. To avoid this, use with_options in the OpenAI Python SDK to extend the client-side timeout:
client = client.with_options(timeout=1800.0)
response = client.chat.completions.create(
    model="qwen-vl-plus",
    messages=[...]
)
  • Streaming output: Set stream=True so that the model returns content incrementally instead of waiting for a single complete response. This prevents client-side timeouts caused by long-running non-streaming calls when you process large images:
stream = client.chat.completions.create(
    model="qwen-vl-plus",
    messages=[...],
    stream=True
)
for chunk in stream:
    print(chunk.choices[0].delta.content)
  • Retry mechanism: Design a reasonable API call retry logic, such as exponential backoff, to handle network fluctuations or temporary service unavailability.

Billing and rate limiting

  • Billing:Total cost is calculated based on the total number of input and output tokens. Input and output prices are available in the Model Studio console.
    • Token composition:Input tokens consist of text tokens and tokens converted from images or videos. Output tokens are the text generated by the model. In thinking mode, the model's thought process is also counted as output tokens. If the thought process is not output in thinking mode, billing follows the pricing for non-thinking mode.
    • Calculate tokens for images and videos:Use the following code to calculate the token consumption for images or videos. The estimated result is for reference only. Actual usage is based on the API response.
      • Images
      • Videos
      Formula: Image Tokens = h_bar * w_bar / token_pixels + 2
      • h_bar, w_bar: The height and width of the scaled image. Before processing an image, the model performs pre-processing to scale it down to a specific pixel limit. This limit depends on the values of the max_pixels and vl_high_resolution_images parameters. For more information, see Process high-resolution images.
      • token_pixels: The pixel value corresponding to each visual token. This varies by model:
        • qwen3.8-series,qwen3.7-series, qwen3.6-series, qwen3.5-series, Qwen3-VL, qwen-vl-max, and qwen-vl-plus:Each token corresponds to 32x32 pixels.
        • QVQ and other Qwen2.5-VL models:Each token corresponds to 28x28 pixels.
      The following code demonstrates the approximate image scaling logic used by the model. Use it to estimate the tokens for an image. For actual billing, refer to the API response.
      import math
      from PIL import Image  # pip install Pillow
      
      def smart_resize(image_path, max_pixels, vl_high_resolution_images):
          """Calculates the scaled dimensions of an image based on model parameters to estimate image tokens."""
          image = Image.open(image_path)
          height, width = image.height, image.width
      
          # The scaling factor is 32 for models such as Qwen3.6, Qwen3.5, and Qwen3-VL. For other models, it is 28.
          factor = 32
          h_bar = round(height / factor) * factor
          w_bar = round(width / factor) * factor
      
          # Token lower limit: 4 tokens
          min_pixels = 4 * factor * factor
      
          # If vl_high_resolution_images=True, the token upper limit is fixed at 16384, and max_pixels is ignored.
          if vl_high_resolution_images:
              max_pixels = 16384 * factor * factor
      
          # Constrains the total number of pixels to the range [min_pixels, max_pixels].
          if h_bar * w_bar > max_pixels:
              beta = math.sqrt((height * width) / max_pixels)
              h_bar = math.floor(height / beta / factor) * factor
              w_bar = math.floor(width / beta / factor) * factor
          elif h_bar * w_bar < min_pixels:
              beta = math.sqrt(min_pixels / (height * width))
              h_bar = math.ceil(height * beta / factor) * factor
              w_bar = math.ceil(width * beta / factor) * factor
      
          return h_bar, w_bar
      
      if __name__ == "__main__":
          # Note: The values of max_pixels and vl_high_resolution_images must match the parameters passed when calling the model.
          h_bar, w_bar = smart_resize("xxx/test.jpg", max_pixels=2560 * 32 * 32, vl_high_resolution_images=False)
          print(f"Scaled image dimensions: Height {h_bar}, Width {w_bar}")
      
          # Each image includes one <vision_bos> and one <vision_eos> token.
          token = int(h_bar * w_bar / (32 * 32)) + 2
          print(f"Number of image tokens: {token}")
      
  • View bills:View bills or top up your account on the Expenses and Costs page in the Alibaba Cloud Management Console.
  • Rate limiting:For more information about the rate limiting conditions for visual understanding models, see Rate limiting.
  • Free quota(Singapore region only): A free quota of 1 million tokens is provided for visual understanding models. The 90-day validity period starts from the date you enable Model Studio or your model request is approved.

API reference

For more information about the input and output parameters of the visual understanding model, see text generation.

FAQ

Choose the most suitable upload method based on the SDK type, file size, and network stability.

File type

File specifications

DashScope SDK (Python, Java)

OpenAI compatible / DashScope HTTP

Image

Greater than 7 MB and less than 10 MB

Pass the local path

Only public network URLs are supported. Use Alibaba Cloud Object Storage Service

Less than 7 MB

Pass the local path

Base64 encoding

Video

Greater than 100 MB

Only public network URLs are supported. Use Alibaba Cloud Object Storage Service

Only public network URLs are supported. Use Alibaba Cloud Object Storage Service

Greater than 7 MB and less than 100 MB

Pass the local path

Only public network URLs are supported. Use Alibaba Cloud Object Storage Service

Less than 7 MB

Pass the local path

Base64 encoding

Base64 encoding increases data size. The original file size must be less than 7 MB.
Use Base64 or a local path to avoid server-side download timeouts and improve stability.
Visual understanding models have size limits for input files. Use the following methods to compress your files.
  • Online tools: Use online tools such as CompressJPEG to compress images.
  • Local software: Use software such as Photoshop to adjust the quality when exporting.
  • Code implementation:
# pip install pillow

from PIL import Image
def compress_image(input_path, output_path, quality=85):
    with Image.open(input_path) as img:
        img.save(output_path, "JPEG", optimize=True, quality=quality)

# Pass the local image
compress_image("/xxx/before-large.jpeg","/xxx/after-min.jpeg")

# Batch compress the images in a directory
import glob
import os

def batch_compress(input_dir, output_dir, quality=85):
    files = (
        glob.glob(os.path.join(input_dir, "*.jpg"))
        + glob.glob(os.path.join(input_dir, "*.jpeg"))
        + glob.glob(os.path.join(input_dir, "*.png"))
    )
    for i, f in enumerate(files, 1):
        try:
            compress_image(f, os.path.join(output_dir, os.path.basename(f)), quality)
            print(f"[{i}/{len(files)}] {os.path.basename(f)} done")
        except Exception as e:
            print(f"[{i}/{len(files)}] {os.path.basename(f)} error: {e}")

batch_compress("/xxx/input_dir", "/xxx/output_dir")
  • Online tools: Use online tools such as FreeConvert to compress videos.
  • Local software: Use software such as HandBrake.
  • Code implementation: Use the FFmpeg tool. For more information, see the official FFmpeg website.
# Basic transform command
# -i, function: input file path, example: input.mp4
# -vcodec, function: video encoder, common values include libx264 (generally recommended) and libx265 (higher compression ratio)
# -crf, function: controls video quality, value range: [18-28]. The smaller the value, the higher the quality and the larger the file size.
# --preset, function: controls the balance between encoding speed and compression efficiency. Common values include slow, fast, and faster.
# -y, function: overwrite an existing file (no value needed)
# output.mp4, function: output file path

ffmpeg -i input.mp4 -vcodec libx264 -crf 28 -preset slow output.mp4
After the visual understanding model returns the object location results, you can use the following code to draw the detection frames and their label information on the original image.
  • Qwen2.5-VL: The returned coordinates are absolute values in pixels, relative to the top-left corner of the scaled image. To draw detection frames, see the code in qwen2_5_vl_2d.py.
  • Qwen3-VL, Qwen3.5, Qwen3.6, and Qwen3.7 series (such as qwen3.5-plus, qwen3.6-plus, and qwen3.7-plus): The returned coordinates are relative and normalized to the range [0, 999]. To draw detection frames, see the code in qwen3_vl_2d.py (2D positioning) or qwen3_vl_3d.zip (3D positioning).

Error codes

If a model call fails, an error message is returned. For information about how to resolve the error, see Error codes.
Token Plan
Model Playground
Statistics and Monitoring
Support