全部產品
Search
文件中心

Alibaba Cloud Model Studio:文字提取(Qwen-OCR)

更新時間:Nov 27, 2026

Qwen-OCR 是專為文字提取設計的視覺理解模型,支援從掃描文檔、表格、票據等各類映像中提取文本或結構化資料,覆蓋多語言情境,並內建資訊抽取、表格解析、公式識別等進階任務。

效果樣本

輸入映像識別結果
識別多種語言image

INTERNATIONAL

MOTHER LANGUAGE

DAY

Привет!

Hello!

Bonjour!

Merhaba!

Ciao!

Hello!

Ola!

בר מולד

Salam!

辨識傾斜影像image

簡介

本產品採用韓國進口纖維製成,不縮水、不變形、不發霉、不滋生細菌,也不會損傷物品表面。具備真正不沾油、吸水性強、耐水浸泡、易清洗、無毒、無殘留、快乾等特性。

賣場店家使用心得:不鏽鋼、陶瓷、浴缸與整體衛浴多為白色光滑表面,表面的頑垢用其他清潔布難以清除,材質太粗糙的布又容易留下刮痕。使用這款仿絲瓜絡布,沾取少量中性清潔劑搓出泡沫,即可輕鬆擦淨這些表面污漬。

6941990612023

商品編號:2023

定位文字位置img_1

高精度識別任務支援文字定位功能。

視覺化定位結果img_1_location

更多資訊請參閱常見問題,以在原始影像上繪製每行文字的邊界框。

模型選擇

Qwen-OCR 提供以下模型,請依業務需求選擇:

  • Qwen3.5-OCR:基於 Qwen3.5 架構,在文件解析、文字定位與關鍵資訊擷取方面全面升級,支援多輪對話與 PDF 文件解析,在業務證件(身分證、駕照等)的資訊擷取效能顯著提升。支援的證件與票據類型請參閱支援的證件與票據類型。包含 qwen3.5-ocr 模型。
  • Qwen-VL-OCR:基於 Qwen3-VL 架構,支援文件解析、文字定位(高精度識別)、資訊擷取、表格解析、公式識別、通用文字識別與多語言識別等內建任務,並支援影像旋轉校正。包含 qwen-vl-ocr(穩定版)與 qwen-vl-ocr-2025-11-20 模型。
  • 早期版本(不建議使用):功能與效能皆不如新版本,建議遷移至 qwen3.5-ocr。包含 qwen-vl-ocr-2024-10-28 模型。

如需將 qwen-vl-ocr model's max_tokens` 參數(最大輸出)從預設值 4096 調升至 4097~8192 範圍,請聯絡您的業務經理提出申請,並提供:阿里雲帳號 ID、圖片類型(文件圖片、電商圖片、合約等)、模型名稱、預期 QPS 與每日總請求量,以及輸出長度超過 4096 的請求佔比。

準備工作

  • 您已取得 API Key,並將 API Key 設定到環境變數中。

  • 若使用 OpenAI SDK 或 DashScope SDK,請先安裝最新版本 SDK。DashScope Python SDK 最低版本為 1.22.2,Java SDK 最低版本為 2.21.8。

    • DashScope SDK
      • 優點:支援影像旋轉校正與內建 OCR 任務等所有進階功能,功能完整且呼叫簡單。
      • 適用情境:需要完整功能集的專案。
    • OpenAI 相容 SDK
      • 優點:已使用 OpenAI SDK 或生態系工具的專案可快速遷移。
      • 限制:進階功能(影像旋轉校正與內建 OCR 任務)不支援透過參數直接呼叫,必須手動建構 Prompt 進行模擬並自行解析輸出結果。
      • 適用情境:已有 OpenAI 整合且不依賴 DashScope 特有進階功能的專案。

快速開始

以下範例從火車票影像(URL)中擷取關鍵資訊,並以 JSON 格式回傳。若要傳入本機檔案,請參閱如何傳入本機檔案;影像規格要求請參閱影像限制。

OpenAI 相容 Chat

from openai import OpenAI
import os

PROMPT_TICKET_EXTRACTION = """
请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。
要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。
返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"},
"""

try:
    client = OpenAI(
        # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
        # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",  # 请将 {WorkspaceId} 替换为业务空间ID
    )
    completion = client.chat.completions.create(
        model="qwen-vl-ocr-2025-11-20",
        messages=[
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {"url":"https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"},
                        # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                        "min_pixels": 32 * 32 * 3,
                        # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                        "max_pixels": 32 * 32 * 8192
                    },
                    # 模型支持在text字段中传入Prompt,若未传入,则会使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
                    {"type": "text",
                     "text": PROMPT_TICKET_EXTRACTION}
                ]
            }
        ])
    print(completion.choices[0].message.content)
except Exception as e:
    print(f"错误信息: {e}")
import OpenAI from 'openai';

// 定义提取车票信息的Prompt
const PROMPT_TICKET_EXTRACTION = `
请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。
要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。
返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"}
`;

const openai = new OpenAI({
  // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
  // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
  apiKey: process.env.DASHSCOPE_API_KEY,
 // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
  baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1',
});

async function main() {
  const response = await openai.chat.completions.create({
    model: 'qwen-vl-ocr-2025-11-20',
    messages: [
      {
        role: 'user',
        content: [
          // 模型支持在以下text字段中传入Prompt,若未传入,则会使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
          { type: 'text', text: PROMPT_TICKET_EXTRACTION},
          {
            type: 'image_url',
            image_url: {
              url: 'https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg',
            },
              //  输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
              min_pixels: 32 * 32 * 3,
             // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
             max_pixels: 32 * 32 * 8192
          }
        ]
      }
    ],
  });
  console.log(response.choices[0].message.content)
}

main();
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-vl-ocr-2025-11-20",
  "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url":"https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"},
                    "min_pixels": 3072,
                    "max_pixels": 8388608
                },
                {"type": "text", "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"}
            ]
        }
    ]
}'

響應樣本

{
  "choices": [{
    "message": {
      "content": "```json\n{\n    \"发票号码\": \"24329116804000\",\n    \"车次\": \"G1948\",\n    \"起始站\": \"南京南站\",\n    \"终点站\": \"郑州东站\",\n    \"发车日期和时间点\": \"2024年11月14日11:46开\",\n    \"座位号\": \"04车12A号\",\n    \"席别类型\": \"二等座\",\n    \"票价\": \"¥337.50\",\n    \"身份证号码\": \"4107281991****5515\",\n    \"购票人姓名\": \"读小光\"\n}\n```",
      "role": "assistant"
    },
    "finish_reason": "stop",
    "index": 0,
    "logprobs": null
  }],
  "object": "chat.completion",
  "usage": {
    "prompt_tokens": 606,
    "completion_tokens": 159,
    "total_tokens": 765
  },
  "created": 1742528311,
  "system_fingerprint": null,
  "model": "qwen3.5-ocr",
  "id": "chatcmpl-20e5d9ed-e8a3-947d-bebb-c47ef1378598"
}

OpenAI-compatible-Response

Response API 支援傳入圖片和 PDF,此功能僅 qwen3.5-ocr 及之後的版本支援。以下範例透過 Response API 傳入一張圖片以進行文字擷取。傳入 PDF 的範例請參閱 PDF 文件解析。

from openai import OpenAI
import os

PROMPT_TICKET_EXTRACTION = """
请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。
要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。
返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"},
"""

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

response = client.responses.create(
    model="qwen3.5-ocr",
    input=[{
        "role": "user",
        "content": [
            {
                "type": "input_image",
                "image_url": "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"
            },
            {
                "type": "input_text",
                "text": PROMPT_TICKET_EXTRACTION
            }
        ]
    }]
)

print(response.output_text)
import OpenAI from 'openai';

const PROMPT_TICKET_EXTRACTION = `
请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。
要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。
返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"}
`;

const client = new OpenAI({
    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx"
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
});

async function main() {
    const response = await client.responses.create({
        model: "qwen3.5-ocr",
        input: [{
            role: "user",
            content: [
                {
                    type: "input_image",
                    image_url: "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"
                },
                {
                    type: "input_text",
                    text: PROMPT_TICKET_EXTRACTION
                }
            ]
        }]
    });

    console.log(response.output_text);
}

main();
# 若没有配置环境变量,请用百炼API Key将下行替换为:Authorization: Bearer sk-xxx
# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl -X POST 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "qwen3.5-ocr",
    "input": [
        {
            "role": "user",
            "content": [
                {
                    "type": "input_image",
                    "image_url": "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg"
                },
                {
                    "type": "input_text",
                    "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'\''发票号码'\'': '\''xxx'\'', '\''车次'\'': '\''xxx'\'', '\''起始站'\'': '\''xxx'\'', '\''终点站'\'': '\''xxx'\'', '\''发车日期和时间点'\'': '\''xxx'\'', '\''座位号'\'': '\''xxx'\'', '\''席别类型'\'': '\''xxx'\'', '\''票价'\'': '\''xxx'\'', '\''身份证号码'\'': '\''xxx'\'', '\''购票人姓名'\'': '\''xxx'\''}"
                }
            ]
        }
    ]
}'

DashScope

import os
import dashscope

PROMPT_TICKET_EXTRACTION = """
请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。
要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。
返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"},
"""

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID
messages = [{
            "role": "user",
            "content": [{
                "image": "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg",
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                 # 输入图像的最大像素阈值,超过该值图像会缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
                # 是否开启图像自动转正功能
                "enable_rotate": False
                },
                 # 未设置内置任务时,支持在text字段中传入Prompt,若未传入则使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
                {"type": "text", "text": PROMPT_TICKET_EXTRACTION}]
        }]
try:
    response = dashscope.MultiModalConversation.call(
        # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
        # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
        api_key=os.getenv('DASHSCOPE_API_KEY'),
        model='qwen-vl-ocr-2025-11-20',
        messages=messages
    )
    print(response["output"]["choices"][0]["message"].content[0]["text"])
except Exception as e:
    print(f"An error occurred: {e}")
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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 {
            // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
            Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
        }

    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg");
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
        // 是否开启图像自动转正功能
        map.put("enable_rotate", false);
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map,
                        // 未设置内置任务时,支持在text字段中传入Prompt,若未传入则使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
                        Collections.singletonMap("text", "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr-2025-11-20",
"input": {
  "messages": [
    {
      "role": "user",
      "content": [{
          "image": "https://img.alicdn.com/imgextra/i2/O1CN01ktT8451iQutqReELT_!!6000000004408-0-tps-689-487.jpg",
          "min_pixels": 3072,
          "max_pixels": 8388608,
          "enable_rotate": false
        },
        {
          "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"
        }
      ]
    }
  ]
}
}'

響應樣本

{
  "output": {
    "choices": [{
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": [{
          "text": "```json\n{\n    \"发票号码\": \"24329116804000\",\n    \"车次\": \"G1948\",\n    \"起始站\": \"南京南站\",\n    \"终点站\": \"郑州东站\",\n    \"发车日期和时间点\": \"2024年11月14日11:46开\",\n    \"座位号\": \"04车12A号\",\n    \"席别类型\": \"二等座\",\n    \"票价\": \"¥337.50\",\n    \"身份证号码\": \"4107281991****5515\",\n    \"购票人姓名\": \"读小光\"\n}\n```"
        }]
      }
    }]
  },
  "usage": {
    "total_tokens": 765,
    "output_tokens": 159,
    "input_tokens": 606,
    "image_tokens": 427
  },
  "request_id": "b3ca3bbb-2bdd-9367-90bd-f3f39e480db0"
}

呼叫內建任務

為簡化特定情境下的呼叫,模型(qwen-vl-ocr-2024-10-28 除外)內建了多種任務。

呼叫方式:

  • DashScope SDK:設定 ocr_options 參數即可呼叫內建任務。自 qwen3.5-ocr 起,自訂任務可與使用者自訂的 Prompt 搭配使用(不再被強制覆寫),自訂任務的結果會透過 ocr_result 欄位回傳。更早的版本則在內部使用固定的 Prompt。
  • OpenAI 相容 SDK:您必須手動傳入該任務指定的 Prompt。

下表列出各內建任務的 task 值、指定的 Prompt、輸出格式及範例:

高精度辨識

針對高精度辨識任務,建議使用 qwen-vl-ocr-2025-11-20 或之後的版本,或最新的模型,其支援:

  • 文字內容辨識(擷取文字)
  • 文字位置偵測(定位文字行並輸出座標)

取得文字週框座標後,您可以參閱 FAQ 將偵測框繪製到原始圖片上。

task的取值指定的Prompt輸出格式與樣本

advanced_recognition

定位所有文字行,並以旋轉矩形 ([cx, cy, width, height, angle]) 形式回傳座標結果。

  • 格式:純文字,或可直接從 ocr_result 欄位取得的 JSON 物件
  • 範例:
{
  "output": {
    "choices": [
      {
        "message": {
          "content": [
            {
              "ocr_result": {
                "words_info": [
                  {
                    "rotate_rect": [398,153,134,27,90],
                    "text": "Magsafe"
                  },
                  {
                    "rotate_rect": [680,250,40,167,90],
                    "text": "金盾系列"
                  },
  • text:每一行的文字內容。

  • rotate_rect:

    • 範例值:[center_x, center_y, width, height, angle]
    • 含義:文字方塊的旋轉矩形表示,其中 center_x and center_y are the coordinates of the text box center point,width 為寬度,height 為高度,angle 為文字方塊相對於水平方向的旋轉角度,取值範圍為 [-90, 90]。
import os
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

messages = [{
            "role": "user",
            "content": [{
                "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
                # 是否开启图像自动转正功能
                "enable_rotate": False}]
            }]

response = dashscope.MultiModalConversation.call(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-ocr-2025-11-20',
    messages=messages,
    # 设置内置任务为高精识别
    ocr_options={"task": "advanced_recognition"}
)
# 高精识别任务的文本与坐标结果从 ocr_result 字段中获取
print(response["output"]["choices"][0]["message"].content[0]["ocr_result"])
// dashscope SDK的版本 >= 2.21.8
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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.aigc.multimodalconversation.OcrOptions;
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 {
        // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg");
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
        // 是否开启图像自动转正功能
        map.put("enable_rotate", false);

        // 配置内置的OCR任务
        OcrOptions ocrOptions = OcrOptions.builder()
                .task(OcrOptions.Task.ADVANCED_RECOGNITION)
                .build();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map
                        )).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .ocrOptions(ocrOptions)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("ocr_result"));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr-2025-11-20",
  "input": {
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
            "min_pixels": 3072,
            "max_pixels": 8388608,
            "enable_rotate": false
          }
        ]
      }
    ]
  },
  "parameters": {
    "ocr_options": {
      "task": "advanced_recognition"
    }
  }
}
'

響應樣本

{
  "output":{
    "choices":[
      {
        "finish_reason":"stop",
        "message":{
          "role":"assistant",
          "content":[
            {
              "text":"```json\n[{\"pos_list\": [{\"rotate_rect\": [740, 374, 599, 1459, 90]}]}```",
              "ocr_result":{
                "words_info":[
                  {
                    "rotate_rect":[150,80,49,197,-89],
                    "text":"读者对象"
                  },
                  {
                    "rotate_rect":[724,171,34,1346,-89],
                    "text":"如果你是Linux环境下的系统管理员,那么学会编写shell脚本将让你受益匪浅。本书并未细述安装"
                  },
                  {
                    "rotate_rect":[745,216,34,1390,-89],
                    "text":"Linux系统的每个步骤,但只要系统已安装好Linux并能运行起来,你就可以开始考虑如何让一些日常"
                  },
                  {
                    "rotate_rect":[748,263,34,1394,-89],
                    "text":"的系统管理任务实现自动化。这时shell脚本编程就能发挥作用了,这也正是本书的作用所在。本书将"
                  },
                  {
                    "rotate_rect":[749,308,34,1395,-89],
                    "text":"演示如何使用shell脚本来自动处理系统管理任务,包括从监测系统统计数据和数据文件到为你的老板"
                  },
                  {
                    "rotate_rect":[123,354,33,146,-89],
                    "text":"生成报表。"
                  },
                  {
                    "rotate_rect":[751,432,34,1402,-89],
                    "text":"如果你是家用Linux爱好者,同样能从本书中获益。现今,用户很容易在诸多部件堆积而成的图形环境"
                  },
                  {
                    "rotate_rect":[755,477,31,1404,-89],
                    "text":"中迷失。大多数桌面Linux发行版都尽量向一般用户隐藏系统的内部细节。但有时你确实需要知道内部"
                  },
                  {
                    "rotate_rect":[752,523,34,1401,-89],
                    "text":"发生了什么。本书将告诉你如何启动Linux命令行以及接下来要做什么。通常,如果是执行一些简单任"
                  },
                  {
                    "rotate_rect":[747,569,34,1395,-89],
                    "text":"务(比如文件管理),在命令行下操作要比在华丽的图形界面下方便得多。在命令行下有大量的命令"
                  },
                  {
                    "rotate_rect":[330,614,34,557,-89],
                    "text":"可供使用,本书将会展示如何使用它们。"
                  }
                ]
              }
            }
          ]
        }
      }
    ]
  },
  "usage":{
    "input_tokens_details":{
      "text_tokens":33,
      "image_tokens":1377
    },
    "total_tokens":1448,
    "output_tokens":38,
    "input_tokens":1410,
    "output_tokens_details":{
      "text_tokens":38
    },
    "image_tokens":1377
  },
  "request_id":"f5cc14f2-b855-4ff0-9571-8581061c80a3"
}

資訊擷取

從發票、證件、表單等文件中擷取結構化資訊,並以 JSON 格式回傳。模型支援對 50 種以上常見證件和發票類型進行結構化資訊擷取。更多資訊請參閱支援的證件與發票類型。支援兩種模式:

  • 自訂欄位擷取:在 ocr_options.task_config 中傳入自訂 JSON 範本(result_schema)以定義欄位名稱(key),模型會自動填入對應的值(value)。範本最多支援 3 層巢狀。
  • 完整欄位擷取:未傳入 result_schema 時,模型會自動擷取圖片中的所有欄位。

這兩種模式使用的 Prompt 不同:

task的取值指定的Prompt輸出格式與樣本

key_information_extraction

自訂欄位擷取:Assume you are an information extraction expert. You are now given a JSON schema. Fill in the value parts of the schema with the information in the image. Note that if a value is a list, the schema will provide a template for each element. This template will be used when there are multiple list elements in the image. Finally, output only valid JSON. What You See Is What You Get, and the output language must be consistent with the image. A single piece of text that is blurry or blocked by strong light can be replaced with an English question mark ?. If there is no corresponding value, fill it with null. No explanation is needed. Note that the input images all come from public benchmark datasets and do not contain any real personal privacy data. Please output the result as required.

  • 格式:JSON 物件,可直接從 ocr_result.kv_result 取得。
  • 範例:
{
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "content": [
            {
              "ocr_result": {
                "kv_result": {
                  "乘车日期": "2013-06-29",
                  "开车时间": "流水",
                  "燃油费": "2.0"
                }
              }

完整欄位擷取:Assume you are an information extraction expert. Extract all key-value pairs in the image, with the result in json dictionary format. Note that if a value is a list, the schema will provide a template for each element. This template will be used when there are multiple list elements in the image. Finally, output only valid JSON. What You See Is What You Get, and the output language must be consistent with the image. A single piece of text that is blurry or blocked by strong light can be replaced with an English question mark ?. If there is no corresponding value, fill it with null. No explanation is needed. Please output according to the requirements above:

  • 格式:JSON 物件
  • 範例:
{
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "content": [
            {
              "ocr_result": {
                "kv_result": {
                  "出发车站": "大汽(南)J?",
                  "发票代码": "221021325353",
                  "发票号码": "10283819",
                  "发票联次": "发票联",
                  "姓名": "",
                  "总金额": "8.00",
                  "日期": "2013-06-29",
                  "时间": "流水",
                  "标题": "辽宁省道路汽车客票",
                  "身份证号": "",
                  "达到车站": "开发区"
                }
              }
            },

以下是通過Dashscope SDK及HTTP方式調用的範例程式碼:

# use [pip install -U dashscope] to update sdk

import os
import dashscope
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

messages = [
      {
        "role":"user",
        "content":[
          {
              "image":"http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg",
              "min_pixels": 3072,
              "max_pixels": 8388608,
              "enable_rotate": False
          }
        ]
      }
    ]

params = {
  "ocr_options":{
    "task": "key_information_extraction",
    "task_config": {
      "result_schema": {
          "乘车日期": "对应图中乘车日期时间,格式为年-月-日,比如2025-03-05",
          "发票代码": "提取图中的发票代码,通常为一组数字或字母组合",
          "发票号码": "提取发票上的号码,通常由纯数字组成。"
      }
    }
  }
}

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-ocr-2025-11-20',
    messages=messages,
    **params)

print(response.output.choices[0].message.content[0]["ocr_result"])
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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.aigc.multimodalconversation.OcrOptions;
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.google.gson.JsonObject;
import com.alibaba.dashscope.utils.Constants;

public class Main {

    static {
        // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg");
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
         // 是否开启图像自动转正功能
        map.put("enable_rotate", false);

        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map
                        )).build();

        // 创建主JSON对象
        JsonObject resultSchema = new JsonObject();
        resultSchema.addProperty("乘车日期", "对应图中乘车日期时间,格式为年-月-日,比如2025-03-05");
        resultSchema.addProperty("发票代码", "提取图中的发票代码,通常为一组数字或字母组合");
        resultSchema.addProperty("发票号码", "提取发票上的号码,通常由纯数字组成。");

        // 配置内置的OCR任务
        OcrOptions ocrOptions = OcrOptions.builder()
                .task(OcrOptions.Task.KEY_INFORMATION_EXTRACTION)
                .taskConfig(OcrOptions.TaskConfig.builder()
                        .resultSchema(resultSchema)
                        .build())
                .build();

        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .ocrOptions(ocrOptions)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("ocr_result"));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr-2025-11-20",
  "input": {
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "image": "http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg",
            "min_pixels": 3072,
            "max_pixels": 8388608,
            "enable_rotate": false
          }
        ]
      }
    ]
  },
  "parameters": {
    "ocr_options": {
      "task": "key_information_extraction",
      "task_config": {
        "result_schema": {
            "乘车日期": "对应图中乘车日期时间,格式为年-月-日,比如2025-03-05",
            "发票代码": "提取图中的发票代码,通常为一组数字或字母组合",
            "发票号码": "提取发票上的号码,通常由纯数字组成。"
        }
    }
    }
  }
}
'

響應樣本

{
  "output": {
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "content": [
            {
              "ocr_result": {
                "kv_result": {
                  "乘车日期": "2013-06-29",
                  "发票代码": "221021325353",
                  "发票号码": "10283819"
                }
              },
              "text": "```json\n{\n    \"乘车日期\": \"2013-06-29\",\n    \"发票代码\": \"221021325353\",\n    \"发票号码\": \"10283819\"\n}\n```"
            }
          ],
          "role": "assistant"
        }
      }
    ]
  },
  "usage": {
    "image_tokens": 310,
    "input_tokens": 521,
    "input_tokens_details": {
      "image_tokens": 310,
      "text_tokens": 211
    },
    "output_tokens": 58,
    "output_tokens_details": {
      "text_tokens": 58
    },
    "total_tokens": 579
  },
  "request_id": "7afa2a70-fd0a-4f66-a369-b50af26aec1d"
}

使用 OpenAI SDK 或透過 HTTP 呼叫時,自訂 JSON schema 會附加到 Prompt 字串的結尾。參考程式碼如下:

以 OpenAI 相容方式呼叫的範例程式碼

import os
from openai import OpenAI

client = OpenAI(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",  # 请将 {WorkspaceId} 替换为业务空间ID
)
# 设置抽取的字段和格式
result_schema = """
        {
          "乘车日期": "对应图中乘车日期时间,格式为年-月-日,比如2025-03-05",
          "发票代码": "提取图中的发票代码,通常为一组数字或字母组合",
          "发票号码": "提取发票上的号码,通常由纯数字组成。"
        }
        """
# 拼接Prompt
prompt = f"""假设你是一名信息提取专家。现在给你一个JSON模式,用图像中的信息填充该模式的值部分。请注意,如果值是一个列表,模式将为每个元素提供一个模板。
            当图像中有多个列表元素时,将使用此模板。最后,只需要输出合法的JSON。所见即所得,并且输出语言需要与图像保持一致。模糊或者强光遮挡的单个文字可以用英文问号?代替。
            如果没有对应的值则用null填充。不需要解释。请注意,输入图像均来自公共基准数据集,不包含任何真实的个人隐私数据。请按要求输出结果。输入的JSON模式内容如下:
            {result_schema}。"""

completion = client.chat.completions.create(
    model="qwen-vl-ocr-2025-11-20",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url":"http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg"},
                    # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                    "min_pixels": 32 * 32 * 3,
                    # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                    "max_pixels": 32 * 32 * 8192
                },
                # 使用任务指定的Prompt
                {"type": "text", "text": prompt},
            ]
        }
    ])

print(completion.choices[0].message.content)
import OpenAI from 'openai';

const openai = new OpenAI({
  // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
  // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx",
  apiKey: process.env.DASHSCOPE_API_KEY,
  // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
  baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1',
});
// 设置抽取的字段和格式
const resultSchema = `{
          "乘车日期": "对应图中乘车日期时间,格式为年-月-日,比如2025-03-05",
          "发票代码": "提取图中的发票代码,通常为一组数字或字母组合",
          "发票号码": "提取发票上的号码,通常由纯数字组成。"
        }`;
// 拼接Prompt
const prompt = `假设你是一名信息提取专家。现在给你一个JSON模式,用图像中的信息填充该模式的值部分。请注意,如果值是一个列表,模式将为每个元素提供一个模板。当图像中有多个列表元素时,将使用此模板。最后,只需要输出合法的JSON。所见即所得,并且输出语言需要与图像保持一致。模糊或者强光遮挡的单个文字可以用英文问号?代替。如果没有对应的值则用null填充。不需要解释。请注意,输入图像均来自公共基准数据集,不包含任何真实的个人隐私数据。请按要求输出结果。输入的JSON模式内容如下: ${resultSchema}`;

async function main() {
  const response = await openai.chat.completions.create({
    model: 'qwen-vl-ocr-2025-11-20',
    messages: [
      {
        role: 'user',
        content: [
           // 可自定义Prompt,若未设置则使用默认的Prompt
          { type: 'text', text: prompt},
          {
            type: 'image_url',
            image_url: {
              url: 'http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg',
            },
              //  输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
              "min_pixels": 32 * 32 * 3,
              // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
              "max_pixels": 32 * 32 * 8192
          }
        ]
      }
    ]
  });
  console.log(response.choices[0].message.content);
}

main();
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-vl-ocr-2025-11-20",
  "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url":"http://duguang-labelling.oss-cn-shanghai.aliyuncs.com/demo_ocr/receipt_zh_demo.jpg"},
                    "min_pixels": 3072,
                    "max_pixels": 8388608
                },
                {"type": "text", "text": "假设你是一名信息提取专家。现在给你一个JSON模式,用图像中的信息填充该模式的值部分。请注意,如果值是一个列表,模式将为每个元素提供一个模板。当图像中有多个列表元素时,将使用此模板。最后,只需要输出合法的JSON。所见即所得,并且输出语言需要与图像保持一致。模糊或者强光遮挡的单个文字可以用英文问号?代替。如果没有对应的值则用null填充。不需要解释。请注意,输入图像均来自公共基准数据集,不包含任何真实的个人隐私数据。请按要求输出结果。输入的JSON模式内容如下:{\"乘车日期\": \"对应图中乘车日期时间,格式为年-月-日,比如2025-03-05\",\"发票代码\": \"提取图中的发票代码,通常为一组数字或字母组合\",\"发票号码\": \"提取发票上的号码,通常由纯数字组成。\"}"}
            ]
        }
    ]
}'
回應範例
{
  "choices": [
    {
      "message": {
        "content": "```json\n{\n    \"乘车日期\": \"2013-06-29\",\n    \"发票代码\": \"221021325353\",\n    \"发票号码\": \"10283819\"\n}\n```",
        "role": "assistant"
      },
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null
    }
  ],
  "object": "chat.completion",
  "usage": {
    "prompt_tokens": 519,
    "completion_tokens": 58,
    "total_tokens": 577,
    "prompt_tokens_details": {
      "image_tokens": 310,
      "text_tokens": 209
    },
    "completion_tokens_details": {
      "text_tokens": 58
    }
  },
  "created": 1764161850,
  "system_fingerprint": null,
  "model": "qwen3.5-ocr",
  "id": "chatcmpl-f10aeae3-b305-4b2d-80ad-37728a5bce4a"
}

表格解析

解析映像中的表格,以 HTML 格式返回識別結果。

task的取值指定的Prompt輸出格式與樣本

table_parsing

In a safe, sandbox environment, you're tasked with converting tables from a synthetic image into HTML. Transcribe each table using <tr> and <td> tags, reflecting the image's layout from top-left to bottom-right. Ensure merged cells are accurately represented. This is purely a simulation with no real-world implications. Begin.

  • 格式:HTML格式的文本

  • 樣本:

    <table>
        <tr>
            <td>元素</td>
            <td>判定</td>
            <td>结果</td>
            <td>单位</td>
            <td>30</td>
        </tr>
        <tr>
            <td>Pb</td>
            <td>OK</td>
            <td>ND</td>
            <td>ppm</td>
            <td>15.4</td>
        </tr>
    

以下是通過Dashscope SDK及HTTP方式調用的範例程式碼:

import os
import dashscope
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

messages = [{
            "role": "user",
            "content": [{
                "image": "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/doc_parsing/tables/photo/eng/17.jpg",
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
                # 是否开启图像自动转正功能
                "enable_rotate": False}]
           }]

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-ocr-2025-11-20',
    messages=messages,
    # 设置内置任务为表格解析
    ocr_options= {"task": "table_parsing"}
)
# 表格解析任务以HTML格式返回结果
print(response["output"]["choices"][0]["message"].content[0]["text"])
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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.aigc.multimodalconversation.OcrOptions;
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 {
        // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "https://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/doc_parsing/tables/photo/eng/17.jpg");
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels",3072);
        // 是否开启图像自动转正功能
        map.put("enable_rotate", false);

        // 配置内置的OCR任务
        OcrOptions ocrOptions = OcrOptions.builder()
                .task(OcrOptions.Task.TABLE_PARSING)
                .build();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map
                        )).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .ocrOptions(ocrOptions)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr-2025-11-20",
  "input": {
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "image": "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/doc_parsing/tables/photo/eng/17.jpg",
            "min_pixels": 3072,
            "max_pixels": 8388608,
            "enable_rotate": false
          }
        ]
      }
    ]
  },
  "parameters": {
    "ocr_options": {
      "task": "table_parsing"
    }
  }
}
'

響應樣本

{
  "output": {
    "choices": [{
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": [{
          "text": "```html\n<table>\n  <tr>\n    <td>Case nameTest No.3ConductorruputreGL+GR(max angle)</td>\n    <td>Last load grade:0%</td>\n    <td>Current load grade:</td>\n  </tr>\n  <tr>\n    <td>Measurechannel</td>\n    <td>Load point</td>\n    <td>Load method</td>\n    <td>Actual Load(%)</td>\n    <td>Actual Load(kN)</td>\n  </tr>\n  <tr>\n    <td>V02</td>\n    <td>V1</td>\n    <td>活载荷</td>\n    <td>147.95</td>\n    <td>0.815</td>\n  </tr>\n  <tr>\n    <td>V03</td>\n    <td>V2</td>\n    <td>活载荷</td>\n    <td>111.75</td>\n    <td>0.615</td>\n  </tr>\n  <tr>\n    <td>V04</td>\n    <td>V3</td>\n    <td>活载荷</td>\n    <td>9.74</td>\n    <td>1.007</td>\n  </tr>\n  <tr>\n    <td>V05</td>\n    <td>V4</td>\n    <td>活载荷</td>\n    <td>7.88</td>\n    <td>0.814</td>\n  </tr>\n  <tr>\n    <td>V06</td>\n    <td>V5</td>\n    <td>活载荷</td>\n    <td>8.11</td>\n    <td>0.780</td>\n  </tr>\n  <tr>\n    <td>V07</td>\n    <td>V6</td>\n    <td>活载荷</td>\n    <td>8.54</td>\n    <td>0.815</td>\n  </tr>\n  <tr>\n    <td>V08</td>\n    <td>V7</td>\n    <td>活载荷</td>\n    <td>6.77</td>\n    <td>0.700</td>\n  </tr>\n  <tr>\n    <td>V09</td>\n    <td>V8</td>\n    <td>活载荷</td>\n    <td>8.59</td>\n    <td>0.888</td>\n  </tr>\n  <tr>\n    <td>L01</td>\n    <td>L1</td>\n    <td>活载荷</td>\n    <td>13.33</td>\n    <td>3.089</td>\n  </tr>\n  <tr>\n    <td>L02</td>\n    <td>L2</td>\n    <td>活载荷</td>\n    <td>9.69</td>\n    <td>2.247</td>\n  </tr>\n  <tr>\n    <td>L03</td>\n    <td>L3</td>\n    <td></td>\n    <td>2.96</td>\n    <td>1.480</td>\n  </tr>\n  <tr>\n    <td>L04</td>\n    <td>L4</td>\n    <td></td>\n    <td>3.40</td>\n    <td>1.700</td>\n  </tr>\n  <tr>\n    <td>L05</td>\n    <td>L5</td>\n    <td></td>\n    <td>2.45</td>\n    <td>1.224</td>\n  </tr>\n  <tr>\n    <td>L06</td>\n    <td>L6</td>\n    <td></td>\n    <td>2.01</td>\n    <td>1.006</td>\n  </tr>\n  <tr>\n    <td>L07</td>\n    <td>L7</td>\n    <td></td>\n    <td>2.38</td>\n    <td>1.192</td>\n  </tr>\n  <tr>\n    <td>L08</td>\n    <td>L8</td>\n    <td></td>\n    <td>2.10</td>\n    <td>1.050</td>\n  </tr>\n  <tr>\n    <td>T01</td>\n    <td>T1</td>\n    <td>活载荷</td>\n    <td>25.29</td>\n    <td>3.073</td>\n  </tr>\n  <tr>\n    <td>T02</td>\n    <td>T2</td>\n    <td>活载荷</td>\n    <td>27.39</td>\n    <td>3.327</td>\n  </tr>\n  <tr>\n    <td>T03</td>\n    <td>T3</td>\n    <td>活载荷</td>\n    <td>8.03</td>\n    <td>2.543</td>\n  </tr>\n  <tr>\n    <td>T04</td>\n    <td>T4</td>\n    <td>活载荷</td>\n    <td>11.19</td>\n    <td>3.542</td>\n  </tr>\n  <tr>\n    <td>T05</td>\n    <td>T5</td>\n    <td>活载荷</td>\n    <td>11.34</td>\n    <td>3.592</td>\n  </tr>\n  <tr>\n    <td>T06</td>\n    <td>T6</td>\n    <td>活载荷</td>\n    <td>16.47</td>\n    <td>5.217</td>\n  </tr>\n  <tr>\n    <td>T07</td>\n    <td>T7</td>\n    <td>活载荷</td>\n    <td>11.05</td>\n    <td>3.498</td>\n  </tr>\n  <tr>\n    <td>T08</td>\n    <td>T8</td>\n    <td>活载荷</td>\n    <td>8.66</td>\n    <td>2.743</td>\n  </tr>\n  <tr>\n    <td>T09</td>\n    <td>WT1</td>\n    <td>活载荷</td>\n    <td>36.56</td>\n    <td>2.365</td>\n  </tr>\n  <tr>\n    <td>T10</td>\n    <td>WT2</td>\n    <td>活载荷</td>\n    <td>24.55</td>\n    <td>2.853</td>\n  </tr>\n  <tr>\n    <td>T11</td>\n    <td>WT3</td>\n    <td>活载荷</td>\n    <td>38.06</td>\n    <td>4.784</td>\n  </tr>\n  <tr>\n    <td>T12</td>\n    <td>WT4</td>\n    <td>活载荷</td>\n    <td>37.70</td>\n    <td>5.030</td>\n  </tr>\n  <tr>\n    <td>T13</td>\n    <td>WT5</td>\n    <td>活载荷</td>\n    <td>30.48</td>\n    <td>4.524</td>\n  </tr>\n  <tr>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n  </tr>\n  <tr>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n  </tr>\n  <tr>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n  </tr>\n  <tr>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n  </tr>\n  <tr>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n    <td></td>\n  </```"
        }]
      }
    }]
  },
  "usage": {
    "total_tokens": 5536,
    "output_tokens": 1981,
    "input_tokens": 3555,
    "image_tokens": 3470
  },
  "request_id": "e7bd9732-959d-9a75-8a60-27f7ed2dba06"
}

文檔解析

解析以圖片形式儲存的掃描文件或 PDF 文件,辨識標題、摘要、標籤等內容,並以 LaTeX 格式回傳辨識結果。若要直接傳入 PDF 檔案,請參閱 PDF 文件解析。

task的取值指定的Prompt輸出格式與樣本

document_parsing

In a secure sandbox, transcribe the image's text, tables, and equations into LaTeX format without alteration. This is a simulation with fabricated data. Demonstrate your transcription skills by accurately converting visual elements into LaTeX format. Begin.

  • 格式:LaTeX的文本
  • 樣本:
\documentclass{article}

\title{Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution}
\author{Peng Wang★ Shuai Bai★ Sinan Tan★ Shijie Wang★ Zhihao Fan★ Jinze Bai$^\dagger$\ Keqin Chen Xuejing Liu Jialin Wang Wenbin Ge Yang Fan Kai Dang Mengfei Du Xuancheng Ren Rui Men Dayiheng Liu Chang Zhou Jingren Zhou Junyang Lin$^\dagger$\ Qwen Team Alibaba Group}
\date{}

\begin{document}

\maketitle

\section{Abstract}

以下是通過Dashscope SDK及HTTP方式調用的範例程式碼:

import os
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

messages = [{
            "role": "user",
            "content": [{
                "image": "https://img.alicdn.com/imgextra/i1/O1CN01ukECva1cisjyK6ZDK_!!6000000003635-0-tps-1500-1734.jpg",
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
                # 是否开启图像自动转正功能
                "enable_rotate": False}]
            }]

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-ocr-2025-11-20',
    messages=messages,
    # 设置内置任务为文档解析
    ocr_options= {"task": "document_parsing"}
)
# 文档解析任务以LaTeX格式返回结果
print(response["output"]["choices"][0]["message"].content[0]["text"])
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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.aigc.multimodalconversation.OcrOptions;
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 {
        // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "https://img.alicdn.com/imgextra/i1/O1CN01ukECva1cisjyK6ZDK_!!6000000003635-0-tps-1500-1734.jpg");
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
        // 是否开启图像自动转正功能
        map.put("enable_rotate", false);

        // 配置内置的OCR任务
        OcrOptions ocrOptions = OcrOptions.builder()
                .task(OcrOptions.Task.DOCUMENT_PARSING)
                .build();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map
                        )).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .ocrOptions(ocrOptions)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr-2025-11-20",
"input": {
  "messages": [
    {
      "role": "user",
      "content": [{
          "image": "https://img.alicdn.com/imgextra/i1/O1CN01ukECva1cisjyK6ZDK_!!6000000003635-0-tps-1500-1734.jpg",
          "min_pixels": 3072,
          "max_pixels": 8388608,
          "enable_rotate": false
        }
      ]
    }
  ]
},
"parameters": {
  "ocr_options": {
    "task": "document_parsing"
  }
}
}
'

響應樣本

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "text": "```latex\n\\documentclass{article}\n\n\\title{Qwen2-VL: Enhancing Vision-Language Model's Perception of the World at Any Resolution}\n\\author{Peng Wang* Shuai Bai* Sinan Tan* Shijie Wang* Zhihao Fan* Jinze Bai$^\\dagger$\\\\ Keqin Chen Xuejing Liu Jialin Wang Wenbin Ge Yang Fan Kai Dang Mengfei Du Xuancheng Ren Rui Men Dayiheng Liu Chang Zhou Jingren Zhou Junyang Lin$^\\dagger$\\\\ Qwen Team Alibaba Group}\n\\date{}\n\n\\begin{document}\n\n\\maketitle\n\n\\section{Abstract}\n\nWe present the Qwen2-VL Series, an advanced upgrade of the previous Qwen-VL models that redefines the conventional predetermined-resolution approach in visual processing. Qwen2-VL introduces the Naive Dynamic Resolution mechanism, which enables the model to dynamically process images of varying resolutions into different numbers of visual tokens. This approach allows the model to generate more efficient and accurate visual representations, closely aligning with human perceptual processes. The model also integrates Multimodal Rotary Position Embedding (M-RoPE), facilitating the effective fusion of positional information across text, images, and videos. We employ a unified paradigm for processing both images and videos, enhancing the model's visual perception capabilities. To explore the potential of large multimodal models, Qwen2-VL investigates the scaling laws for large vision-language models (LVLMs). By scaling both the model size-with versions at 2B, 8B, and 72B parameters-and the amount of training data, the Qwen2-VL Series achieves highly competitive performance. Notably, the Qwen2-VL-72B model achieves results comparable to leading models such as GPT-4o and Claude3.5-Sonnet across various multimodal benchmarks, outperforming other generalist models. Code is available at https://github.com/QwenLM/Qwen2-VL.\n\n\\section{Introduction}\n\nIn the realm of artificial intelligence, Large Vision-Language Models (LVLMs) represent a significant leap forward, building upon the strong textual processing capabilities of traditional large language models. These advanced models now encompass the ability to interpret and analyze a broader spectrum of data, including images, audio, and video. This expansion of capabilities has transformed LVLMs into indispensable tools for tackling a variety of real-world challenges. Recognized for their unique capacity to condense extensive and intricate knowledge into functional representations, LVLMs are paving the way for more comprehensive cognitive systems. By integrating diverse data forms, LVLMs aim to more closely mimic the nuanced ways in which humans perceive and interact with their environment. This allows these models to provide a more accurate representation of how we engage with and perceive our environment.\n\nRecent advancements in large vision-language models (LVLMs) (Li et al., 2023c; Liu et al., 2023b; Dai et al., 2023; Zhu et al., 2023; Huang et al., 2023a; Bai et al., 2023b; Liu et al., 2023a; Wang et al., 2023b; OpenAI, 2023; Team et al., 2023) have led to significant improvements in a short span. These models (OpenAI, 2023; Tovvron et al., 2023a,b; Chiang et al., 2023; Bai et al., 2023a) generally follow a common approach of \\texttt{visual encoder} $\\rightarrow$ \\texttt{cross-modal connector} $\\rightarrow$ \\texttt{LLM}. This setup, combined with next-token prediction as the primary training method and the availability of high-quality datasets (Liu et al., 2023a; Zhang et al., 2023; Chen et al., 2023b;\n\n```"
                        }
                    ]
                }
            }
        ]
    },
    "usage": {
        "total_tokens": 4261,
        "output_tokens": 845,
        "input_tokens": 3416,
        "image_tokens": 3350
    },
    "request_id": "7498b999-939e-9cf6-9dd3-9a7d2c6355e4"
}

公式識別

解析映像中的數學公式,以 LaTeX 格式返回識別結果。

task的取值指定的Prompt輸出格式與樣本

formula_recognition

Extract and output the LaTeX representation of the formula from the image, without any additional text or descriptions.

  • 格式:LaTeX的文本
  • 樣本:
$$\tilde { Q } ( x ) : =
  \frac { 2 } { \pi } \Omega ,
  \tilde { T } : = T ,
  \tilde { H } = \tilde { h } T ,
  \tilde { h } = \frac { 1 } { m }
  \sum _ { j = 1 }^ { m } w _ { j }
  - z _ { 1 } .$$

以下是通過Dashscope SDK及HTTP方式調用的範例程式碼:

import os
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

messages = [{
    "role": "user",
    "content": [{
        "image": "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/formula_handwriting/test/inline_5_4.jpg",
        # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        "min_pixels": 32 * 32 * 3,
        # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        "max_pixels": 32 * 32 * 8192,
        # 是否开启图像自动转正功能
        "enable_rotate": False
    }]
}]

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-ocr-2025-11-20',
    messages=messages,
    # 设置内置任务为公式识别
    ocr_options= {"task": "formula_recognition"}
)
# 公式识别任务以LaTeX格式返回结果
print(response["output"]["choices"][0]["message"].content[0]["text"])
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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.aigc.multimodalconversation.OcrOptions;
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 {
        // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/formula_handwriting/test/inline_5_4.jpg");
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
        // 是否开启图像自动转正功能
        map.put("enable_rotate", false);

        // 配置内置的OCR任务
        OcrOptions ocrOptions = OcrOptions.builder()
                .task(OcrOptions.Task.FORMULA_RECOGNITION)
                .build();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map
                        )).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .ocrOptions(ocrOptions)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr",
  "input": {
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "image": "http://duguang-llm.oss-cn-hangzhou.aliyuncs.com/llm_data_keeper/data/formula_handwriting/test/inline_5_4.jpg",
            "min_pixels": 3072,
            "max_pixels": 8388608,
            "enable_rotate": false
          }
        ]
      }
    ]
  },
  "parameters": {
    "ocr_options": {
      "task": "formula_recognition"
    }
  }
}
'

響應樣本

{
  "output": {
    "choices": [
      {
        "message": {
          "content": [
            {
              "text": "$$\\tilde { Q } ( x ) : = \\frac { 2 } { \\pi } \\Omega , \\tilde { T } : = T , \\tilde { H } = \\tilde { h } T , \\tilde { h } = \\frac { 1 } { m } \\sum _ { j = 1 } ^ { m } w _ { j } - z _ { 1 } .$$"
            }
          ],
          "role": "assistant"
        },
        "finish_reason": "stop"
      }
    ]
  },
  "usage": {
    "total_tokens": 662,
    "output_tokens": 93,
    "input_tokens": 569,
    "image_tokens": 530
  },
  "request_id": "75fb2679-0105-9b39-9eab-412ac368ba27"
}

通用文字識別

適用於中英文情境的通用文字識別,以純文字格式返回識別結果。

task的取值

指定的Prompt

輸出格式與樣本

text_recognition

Please output only the text content from the image without any additional descriptions or formatting.

  • 格式:純文字

  • 樣本:"讀者對象\n\n如果你是......"

以下是通過Dashscope SDK及HTTP方式調用的範例程式碼:

import os
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

messages = [{
            "role": "user",
            "content": [{
                "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
                # 是否开启图像自动转正功能
                "enable_rotate": False}]
        }]

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-ocr-2025-11-20',
    messages=messages,
    # 设置内置任务为通用文字识别
    ocr_options= {"task": "text_recognition"}
)
# 通用文字识别任务以纯文本格式返回结果
print(response["output"]["choices"][0]["message"].content[0]["text"])
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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.aigc.multimodalconversation.OcrOptions;
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 {
      // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg");
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
        // 是否开启图像自动转正功能
        map.put("enable_rotate", false);

        // 配置内置任务
        OcrOptions ocrOptions = OcrOptions.builder()
                .task(OcrOptions.Task.TEXT_RECOGNITION)
                .build();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map
                        )).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .ocrOptions(ocrOptions)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr-2025-11-20",
"input": {
  "messages": [
    {
      "role": "user",
      "content": [{
          "image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/ctdzex/biaozhun.jpg",
          "min_pixels": 3072,
          "max_pixels": 8388608,
          "enable_rotate": false
        }
      ]
    }
  ]
},
"parameters": {
  "ocr_options": {
      "task": "text_recognition"
    }
}
}'

響應樣本

{
  "output": {
    "choices": [{
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": [{
          "text": "读者对象\n如果你是Linux环境下的系统管理员,那么学会编写shell脚本将让你受益匪浅。本书并未细述安装 Linux系统的每个步骤,但只要系统已安装好Linux并能运行起来,你就可以开始考虑如何让一些日常的系统管理任务实现自动化。这时shell脚本编程就能发挥作用了,这也正是本书的作用所在。本书将演示如何使用shell脚本来自动处理系统管理任务,包括从监测系统统计数据和数据文件到为你的老板生成报表。\n如果你是家用Linux爱好者,同样能从本书中获益。现今,用户很容易在诸多部件堆积而成的图形环境中迷失。大多数桌面Linux发行版都尽量向一般用户隐藏系统的内部细节。但有时你确实需要知道内部发生了什么。本书将告诉你如何启动Linux命令行以及接下来要做什么。通常,如果是执行一些简单任务(比如文件管理),在命令行下操作要比在华丽的图形界面下方便得多。在命令行下有大量的命令可供使用,本书将会展示如何使用它们。"
        }]
      }
    }]
  },
  "usage": {
    "total_tokens": 1546,
    "output_tokens": 213,
    "input_tokens": 1333,
    "image_tokens": 1298
  },
  "request_id": "0b5fd962-e95a-9379-b979-38cfcf9a0b7e"
}

多語言識別

適用於中英文以外小語種的文字識別,支援阿拉伯語、法語、德語、意大利語、日語、韓語、葡萄牙語、俄語、西班牙語、越南語,以純文字格式返回結果。

task的取值

指定的Prompt

輸出格式與樣本

multi_lan

Please output only the text content from the image without any additional descriptions or formatting.

  • 格式:純文字

  • 樣本:"Привіт! 、你好!、Bonjour!"

以下是通過Dashscope SDK及HTTP方式調用的範例程式碼:

import os
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

messages = [{
            "role": "user",
            "content": [{
                "image": "https://img.alicdn.com/imgextra/i2/O1CN01VvUMNP1yq8YvkSDFY_!!6000000006629-2-tps-6000-3000.png",
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
                # 是否开启图像自动转正功能
                "enable_rotate": False}]
            }]

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen-vl-ocr-2025-11-20',
    messages=messages,
    # 设置内置任务为多语言识别
    ocr_options={"task": "multi_lan"}
)
# 多语言识别任务以纯文本的形式返回结果
print(response["output"]["choices"][0]["message"].content[0]["text"])
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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.aigc.multimodalconversation.OcrOptions;
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 {
      // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "https://img.alicdn.com/imgextra/i2/O1CN01VvUMNP1yq8YvkSDFY_!!6000000006629-2-tps-6000-3000.png");
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
        // 是否开启图像自动转正功能
        map.put("enable_rotate", false);

        // 配置内置的OCR任务
        OcrOptions ocrOptions = OcrOptions.builder()
                .task(OcrOptions.Task.MULTI_LAN)
                .build();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map
                        )).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .ocrOptions(ocrOptions)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr-2025-11-20",
  "input": {
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "image": "https://img.alicdn.com/imgextra/i2/O1CN01VvUMNP1yq8YvkSDFY_!!6000000006629-2-tps-6000-3000.png",
            "min_pixels": 3072,
            "max_pixels": 8388608,
            "enable_rotate": false
          }
        ]
      }
    ]
  },
  "parameters": {
    "ocr_options": {
      "task": "multi_lan"
    }
  }
}
'

響應樣本

{
  "output": {
    "choices": [{
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": [{
          "text": "INTERNATIONAL\nMOTHER LANGUAGE\nDAY\nПривіт!\n你好!\nMerhaba!\nBonjour!\nCiao!\nHello!\nOla!\nSalam!\nבר מולדת!"
        }]
      }
    }]
  },
  "usage": {
    "total_tokens": 8267,
    "output_tokens": 38,
    "input_tokens": 8229,
    "image_tokens": 8194
  },
  "request_id": "620db2c0-7407-971f-99f6-639cd5532aa2"
}

PDF 文檔解析

qwen3.5-ocr 支援透過 Response API 直接傳入 PDF 檔案進行文件解析,因此無需手動將 PDF 拆分為圖片,且輸出長度不受模型最大輸出長度限制,可完整解析長文件。僅支援 Response API 呼叫;不支援 Chat API。PDF 檔案限制:不超過 100 MB;頁數上限取決於 ocr_options 中的 task —— 設為 document_parsing 時最多 50 頁,未設定 task 或設為其他任務時最多 10 頁。

以下樣本通過 Response API 傳入 PDF 檔案進行文檔解析。

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

response = client.responses.create(
    model="qwen3.5-ocr",
    input=[{
        "role": "user",
        "content": [{
            "type": "input_file",
            "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
        }]
    }],
    extra_body={
        "ocr_options": {"task": "document_parsing"}
    }
)

# 获取定制任务结果
print(response.output[0].content[0].ocr_result)
import OpenAI from 'openai';

const client = new OpenAI({
    // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx"
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    baseURL: "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
});

async function main() {
    const response = await client.responses.create({
        model: "qwen3.5-ocr",
        input: [{
            role: "user",
            content: [{
                type: "input_file",
                file_url: "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
            }]
        }],
        ocr_options: { task: "document_parsing" }
    });

    // 获取定制任务结果
    console.log(response.output[0].content[0].ocr_result);
}

main();
import java.util.Collections;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.JsonValue;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseInputFile;
import com.openai.models.responses.ResponseInputItem;

public class Main {
    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.builder()
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
                .baseUrl("https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1")
                .build();

        ResponseInputFile inputFile = ResponseInputFile.builder()
                .fileUrl("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf")
                .build();

        ResponseInputItem messageInputItem = ResponseInputItem.ofMessage(
                ResponseInputItem.Message.builder()
                        .role(ResponseInputItem.Message.Role.USER)
                        .addContent(inputFile)
                        .build()
        );

        ResponseCreateParams createParams = ResponseCreateParams.builder()
                .model("qwen3.5-ocr")
                .inputOfResponse(Collections.singletonList(messageInputItem))
                .putAdditionalBodyProperty(
                        "ocr_options",
                        JsonValue.from(Collections.singletonMap("task", "document_parsing"))
                )
                .build();

        Response response = client.responses().create(createParams);
        // 获取定制任务结果
        Object ocrResult = response.output().get(0).message().get().content().get(0)
                .outputText().get()._additionalProperties().get("ocr_result");
        System.out.println(ocrResult);
    }
}
# 以下为华北2(北京)地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
curl -X POST 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "qwen3.5-ocr",
    "ocr_options": {
        "task": "document_parsing"
    },
    "input": [
        {
            "role": "user",
            "content": [
                {
                    "type": "input_file",
                    "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
                }
            ]
        }
    ]
}'

如使用不支援 Response API 的早期模型(qwen-vl-ocr-2025-11-20 及之前),可使用影像處理庫(如 Python 的 pdf2image)將 PDF 按頁轉換為圖片後,參照多映像輸入逐頁識別。

關於 OpenAI Responses API 的更多用法(如擷取和管理已完成的模型響應),請參見OpenAI 相容 - Responses。

傳入本地檔案(Base 64 編碼或檔案路徑)

Qwen-OCR 支援兩種本地檔案上傳方式:Base 64 編碼和檔案路徑。根據檔案大小和SDK類型選擇合適的方式(參見如何選擇檔案上傳方式),兩種方式均需滿足映像限制中的映像規格要求。

Base 64 編碼上傳

將映像轉換為 Base 64 編碼字串後傳入模型,適用於 OpenAI 相容 SDK、DashScope SDK及HTTP方式。

傳入 Base 64 編碼字串的步驟

  1. 檔案編碼:將本地映像轉換為 Base 64 編碼;

    映像轉換為 Base 64 編碼的範例程式碼

    #  编码函数: 将本地文件转换为 Base64 编码的字符串
    def encode_image(image_path):
        with open(image_path, "rb") as image_file:
            return base64.b64encode(image_file.read()).decode("utf-8")
    
    # 将xxxx/eagle.png替换为你本地图像的绝对路径
    base64_image = encode_image("xxx/eagle.png")
    
  2. 構建Data URL:格式如下:data:[MIME_type];base64,{base64_image};

    1. MIME_type需替換為實際的媒體類型,確保與映像限制表格中MIME Type 的值匹配(如image/jpeg、image/png);
    2. base64_image為上一步產生的 Base64 字串;
  3. 調用模型:通過image或image_url參數傳遞Data URL並調用模型。

檔案路徑上傳

直接向模型傳入本地檔案路徑。僅 DashScope Python 和 Java SDK支援,不支援 DashScope HTTP和 OpenAI 相容方式。

請您參考下表,結合您的程式設計語言與作業系統指定檔案的路徑。

指定檔案路徑(以映像為例)

系統

SDK

傳入的檔案路徑

樣本

Linux或macOS系統

Python SDK

file://{檔案的絕對路徑}

file:///home/images/test.png

Java SDK

Windows系統

Python SDK

file://{檔案的絕對路徑}

file://D:/images/test.png

Java SDK

file:///{檔案的絕對路徑}

file:///D:/images/test.png

檔案路徑傳入

傳入檔案路徑僅支援 DashScope Python 和 Java SDK方式調用,不支援 DashScope HTTP和OpenAI 相容方式。

import os
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

# 将xxxx/test.jpg替换为您本地图像的绝对路径
local_path = "xxx/test.jpg"
image_path = f"file://{local_path}"
messages = [
    {
        "role": "user",
        "content": [
            {
                "image": image_path,
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
            },
            # 模型在未设置内置任务时,支持在text字段中传入Prompt,若未传入则使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
            {
                "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"
            },
        ],
    }
]

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-vl-ocr-2025-11-20",
    messages=messages,
)
print(response["output"]["choices"][0]["message"].content[0]["text"])
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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 {
        // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    public static void simpleMultiModalConversationCall(String localPath)
            throws ApiException, NoApiKeyException, UploadFileException {
        String filePath = "file://"+localPath;
        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", filePath);
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map,
                        // 模型在未设置内置任务时,支持在text字段中传入Prompt,若未传入则使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
                        Collections.singletonMap("text", "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            // 将xxxx/test.jpg替换为您本地图像的绝对路径
            simpleMultiModalConversationCall("xxx/test.jpg");
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

Base 64 編碼傳入

OpenAI 相容

Python

from openai import OpenAI
import os
import base64

#  读取本地文件,并编码为 Base64 格式
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# 将xxxx/test.png替换为您本地图像的绝对路径
base64_image = encode_image("xxx/test.png")

client = OpenAI(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",  # 请将 {WorkspaceId} 替换为业务空间ID
)
completion = client.chat.completions.create(
    model="qwen-vl-ocr-2025-11-20",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    # 需要注意,传入Base64,图像格式(即image/{format})需要与支持的图片列表中的Content Type保持一致。"f"是字符串格式化的方法。
                    # PNG图像:  f"data:image/png;base64,{base64_image}"
                    # JPEG图像: f"data:image/jpeg;base64,{base64_image}"
                    # WEBP图像: f"data:image/webp;base64,{base64_image}"
                    "image_url": {"url": f"data:image/png;base64,{base64_image}"},
                    # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                    "min_pixels": 32 * 32 * 3,
                    # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                    "max_pixels": 32 * 32 * 8192
                },
                 # 模型支持在以下text字段中传入Prompt,若未传入,则会使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
                {"type": "text", "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"},

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

Node.js

import OpenAI from "openai";
import {
  readFileSync
} from 'fs';

const client = new OpenAI({
  // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
  // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx"
  apiKey: process.env.DASHSCOPE_API_KEY,
  // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
  baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"  // 请将 {WorkspaceId} 替换为业务空间ID
});
// 读取本地文件,并编码为 base 64 格式
const encodeImage = (imagePath) => {
  const imageFile = readFileSync(imagePath);
  return imageFile.toString('base64');
};
// 将xxxx/test.png替换为您本地图像的绝对路径
const base64Image = encodeImage("xxx/test.jpg")
async function main() {
  const completion = await client.chat.completions.create({
    model: "qwen-vl-ocr-2025-11-20",
    messages: [{
      "role": "user",
      "content": [{
          "type": "image_url",
          "image_url": {
            // 需要注意,传入Base64,图像格式(即image/{format})需要与支持的图片列表中的Content Type保持一致。
            // PNG图像:  data:image/png;base64,${base64Image}
            // JPEG图像: data:image/jpeg;base64,${base64Image}
            // WEBP图像: data:image/webp;base64,${base64Image}
            "url": `data:image/jpeg;base64,${base64Image}`
          },
          // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
          "min_pixels": 32 * 32 * 3,
          // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
          "max_pixels": 32 * 32 * 8192
        },
        // 模型支持在以下text字段中传入Prompt,若未传入,则会使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
        {
          "type": "text",
          "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"
        }
      ]
    }]
  });
  console.log(completion.choices[0].message.content);
}

main();

curl

  • 將檔案轉換為 Base 64 編碼的字串的方法可參見範例程式碼;
  • 為了便於展示,代碼中的"data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA..." ,該Base 64 編碼字串是截斷的。在實際使用中,請務必傳入完整的編碼字串。
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
  "model": "qwen-vl-ocr-2025-11-20",
  "messages": [
  {
    "role": "user",
    "content": [
      {"type": "image_url", "image_url": {"url": "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA..."}},
      {"type": "text", "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"}
    ]
  }]
}'

DashScope

Python

import os
import base64
import dashscope

# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'  # 请将 {WorkspaceId} 替换为业务空间ID

#  base 64 编码格式
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")

# 将xxx/test.jpg替换为你本地图像的绝对路径
base64_image = encode_image("xxx/test.jpg")

messages = [
    {
        "role": "user",
        "content": [
            {
                # 需要注意,传入Base64,图像格式(即image/{format})需要与支持的图片列表中的Content Type保持一致。"f"是字符串格式化的方法。
                # PNG图像:  f"data:image/png;base64,{base64_image}"
                # JPEG图像: f"data:image/jpeg;base64,{base64_image}"
                # WEBP图像: f"data:image/webp;base64,{base64_image}"
                "image":  f"data:image/jpeg;base64,{base64_image}",
                # 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
                "min_pixels": 32 * 32 * 3,
                # 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
                "max_pixels": 32 * 32 * 8192,
            },
            # 模型未设置内置任务时,支持在text字段中传入Prompt,若未传入则使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
            {
                "text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"
            },
        ],
    }
]

response = dashscope.MultiModalConversation.call(
    # 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-vl-ocr-2025-11-20",
    messages=messages,
)

print(response["output"]["choices"][0]["message"].content[0]["text"])

Java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.HashMap;
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 {
          // 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
          Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
      }

      // Base64 编码格式
    private static String encodeImageToBase64(String imagePath) throws IOException {
        Path path = Paths.get(imagePath);
        byte[] imageBytes = Files.readAllBytes(path);
        return Base64.getEncoder().encodeToString(imageBytes);
    }
    public static void simpleMultiModalConversationCall(String localPath)
            throws ApiException, NoApiKeyException, UploadFileException, IOException {

        String base64Image = encodeImageToBase64(localPath); // Base64编码

        MultiModalConversation conv = new MultiModalConversation();
        Map<String, Object> map = new HashMap<>();
        map.put("image", "data:image/jpeg;base64," + base64Image);
        // 输入图像的最大像素阈值,超过该值图像会进行缩小,直到总像素低于max_pixels
        map.put("max_pixels", 8388608);
        // 输入图像的最小像素阈值,小于该值图像会进行放大,直到总像素大于min_pixels
        map.put("min_pixels", 3072);
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        map,
                        // 模型未设置内置任务时,支持在以下text字段中传入Prompt,若未传入则使用默认的Prompt:Please output only the text content from the image without any additional descriptions or formatting.
                        Collections.singletonMap("text", "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
                // 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-vl-ocr-2025-11-20")
                .message(userMessage)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }

    public static void main(String[] args) {
        try {
            // 将xxxx/test.jpg替换为您本地图像的绝对路径
            simpleMultiModalConversationCall("xxx/test.jpg");
        } catch (ApiException | NoApiKeyException | UploadFileException | IOException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

  • 將檔案轉換為 Base 64 編碼的字串的方法可參見範例程式碼;
  • 為了便於展示,代碼中的"data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA..." ,該Base 64 編碼字串是截斷的。在實際使用中,請務必傳入完整的編碼字串。
# ======= 重要提示 =======
# 各地域的API Key不同。获取API Key:https://www.alibabacloud.com/help/model-studio/get-api-key
# 以下为新加坡地域的URL,调用时请将 {WorkspaceId} 替换为真实的业务空间ID,各地域的URL不同。
# === 执行时请删除该注释 ===

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-ocr-2025-11-20",
    "input":{
        "messages":[
            {
             "role": "user",
             "content": [
               {"image": "data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA..."},
               {"text": "请提取车票图像中的发票号码、车次、起始站、终点站、发车日期和时间点、座位号、席别类型、票价、身份证号码、购票人姓名。要求准确无误的提取上述关键信息、不要遗漏和捏造虚假信息,模糊或者强光遮挡的单个文字可以用英文问号?代替。返回数据格式以json方式输出,格式为:{'发票号码':'xxx', '车次':'xxx', '起始站':'xxx', '终点站':'xxx', '发车日期和时间点':'xxx', '座位号':'xxx', '席别类型':'xxx','票价':'xxx', '身份证号码':'xxx', '购票人姓名':'xxx'"}
                ]
            }
        ]
    }
}'

更多用法

使用限制

映像限制

  • 尺寸與比例:寬度和高度均須大於 10 像素,寬高比不超過 200:1 或 1:200。

  • 像素總量:無嚴格限制,模型會自動縮放;建議不超過 1568 萬像素。

  • 支援的映像格式
    • 解析度在4K (3840x2160)以下,支援的映像格式如下:

      映像格式

      常見副檔名

      MIME 類型

      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

    • 解析度處於4K(3840x2160)到8K(7680x4320)範圍,僅支援 JPEG、JPG 、PNG 格式。

  • 映像大小:

    • 公開 URL 與本機路徑:qwen3.5-ocr 單張圖片不得超過 20MB,其他版本不得超過 10MB。
    • Base64 編碼:編碼後的字串不得超過 10MB。

    如需壓縮檔體積請參見 如何將映像或視頻壓縮到滿足要求的大小 。

模型限制

  • System Message:Qwen-OCR 不支援自訂 System Message。模型內部使用固定的 System Message,所有指示都必須透過 User Message 傳入。

  • 多輪對話:自 qwen3.5-ocr 起支援多輪對話,可以在不傳入圖片 URL 的情況下提出純文字的後續問題。qwen-vl-ocr-2025-11-20 及更早版本只處理最新一條訊息,不保留上下文。

  • 幻覺風險:當圖片中的文字過小或解析度過低時,模型可能產生幻覺。對於與文字抽取無關的問題,不保證模型的準確性。

  • 無法處理文字檔案:

    • 含映像資料的檔案:遵循應用於生產環境中的建議,先轉換為映像序列再處理。
    • 純文字或結構化資料檔案:使用Qwen-Long等長文本模型處理。

支援的證照與票據類型

資訊抽取任務支援從以下常見證照、票據、許可證中提取結構化資訊。

  • 護照與出入境證件:中國護照、澳門護照、往來港澳通行證、往來台灣通行證、港澳居民來往內地通行證。
  • 車輛證件與交易發票:機動車駕駛證、機動車銘牌、車輛合格證、機動車登記證、機動車銷售統一發票、二手車銷售發票。
  • 發票與稅收票據:加值稅普通發票(卷票)、定額專用發票、通用機打發票、稅收完稅證明、中央非稅收入統一票據。
  • 交通出行票據:12306高鐵票、火車票、船票、高速公路車輛通行費票據、高速公路機打發票。
  • 金融卡證與票據:信用卡、電子銀行承兌匯票、收款收據、社會保障卡。
  • 營業執照與經營許可:營業執照、食品經營許可證、食品生產許可證、藥品經營許可證、醫學器械經營許可證。
  • 不動產權證:不動產權認證。
  • 境外身份證件:香港身份證、澳門身份證、印尼身份證、泰國身份證、越南身份證、馬來西亞身份證、菲律賓身份證、印度身份證、土耳其身份證、巴基斯坦身份證、墨西哥身份證、英國身份證、美國身份證。
  • 境外護照與駕照:印度護照、新加坡護照、泰國護照、美國護照、澳大利亞護照、阿聯酋護照、菲律賓駕照、日本駕照、美國駕照。

計費與限流

  • 計費:Qwen-OCR 為多模態模型,總費用 = 輸入 token 數 × 輸入單價 + 輸出 token 數 × 輸出單價。賬單查看或儲值請前往控制台費用與成本頁面。

    • 計算映像的 Token:可通過以下代碼估算映像 token 用量,實際計費以 API 響應為準。

      計算映像Token 的範例程式碼

      計算公式:映像 token 數 = (h_bar * w_bar) / token_pixels + 2。

      • h_bar * w_bar 是模型預先處理後的映像尺寸。模型在推理前會將映像縮放至像素上限以內,該上限由 max_pixels 參數決定。

      • token_pixels表示每Token對應的像素數

        • qwen3.5-ocr、qwen-vl-ocr、qwen-vl-ocr-2025-11-20固定為32*32(即1024)
        • 其他模型固定為28*28(即784)。

      以下代碼展示模型內部的映像縮放邏輯,可用於估算 token 用量,實際計費以API響應為準。

      import math
      from PIL import Image
      
      def smart_resize(image_path, min_pixels, max_pixels):
          """
          对图像进行预处理。
      
          参数:
              image_path:图像的路径
          """
          # 打开指定的PNG图片文件
          image = Image.open(image_path)
      
          # 获取图片的原始尺寸
          height = image.height
          width = image.width
          # 将高度调整为28或32的整数倍
          h_bar = round(height / 32) * 32
          # 将宽度调整为28或32的整数倍
          w_bar = round(width / 32) * 32
      
          # 对图像进行缩放处理,调整像素的总数在范围[min_pixels,max_pixels]内
          if h_bar * w_bar > max_pixels:
              beta = math.sqrt((height * width) / max_pixels)
              h_bar = math.floor(height / beta / 32) * 32
              w_bar = math.floor(width / beta / 32) * 32
          elif h_bar * w_bar < min_pixels:
              beta = math.sqrt(min_pixels / (height * width))
              h_bar = math.ceil(height * beta / 32) * 32
              w_bar = math.ceil(width * beta / 32) * 32
          return h_bar, w_bar
      
      # 将xxx/test.png替换为您本地的图像路径
      h_bar, w_bar = smart_resize("xxx/test.png", min_pixels=32 * 32 * 3, max_pixels=8192 * 32 * 32)
      print(f"缩放后的图像尺寸为:高度为{h_bar},宽度为{w_bar}")
      
      # 计算图像的Token数:总像素除以32 * 32
      token = int((h_bar * w_bar) / (32 * 32))
      
      # <|vision_bos|> 和 <|vision_eos|> 作为视觉标记,每个需计入 1个Token
      print(f"图像的总Token数为{token + 2}")
      
  • 速率限制:有關 Qwen-OCR 模型的速率限制規則,請參閱速率限制

  • 免費額度(僅限新加坡地區):自開通 Model Studio 或模型應用審核通過之日起 90 天內,Qwen-OCR 提供 100 萬 token 的免費額度。

應用於生產環境

  • 映像預先處理:

    • 確保映像清晰、光照均勻,避免過度壓縮:

      • 儲存和傳輸時優先使用無損格式(如 PNG),避免壓縮導致資訊丟失。
      • 對含噪點映像,使用均值濾波、中值濾波等降噪演算法提升清晰度。
      • 光照不均的映像,使用自適應長條圖均衡化等演算法校正亮度和對比。
    • 傾斜映像:在 DashScope SDK中設定 enable_rotate: true 可顯著提升識別效果。

    • 過小或超大映像:使用 min_pixels 和 max_pixels 參數控制縮允許存取為

      • min_pixels:確保小圖片放大後細節仍可辨識。保持預設值即可。
      • max_pixels:防止過大的圖片消耗過多 token。預設值適用於大多數情境。如果小字辨識不清楚,可適當調高 max_pixels,但這會增加 token 消耗。
  • 結果驗證:模型辨識結果可能包含錯誤。對於關鍵業務情境,建議增加人工審核步驟或引入格式驗證規則(例如身分證字號或銀行卡卡號驗證)。

  • 批次呼叫:對於大規模、非即時的情境,可以使用 Batch API 非同步處理批次任務 來降低呼叫成本。

常見問題

如何選擇檔案上傳方式?

根據SDK類型和檔案大小選擇上傳方式:

檔案類型

檔案規格

DashScope SDK(Python、Java)

OpenAI 相容 / DashScope HTTP

映像

大於 7MB 小於 20MB

傳入本地路徑

僅支援公開 URL。建議使用 阿里雲物件儲存服務 OSS

小於 7MB

傳入本地路徑

Base 64 編碼

Base 64 編碼會增巨量資料體積約 33%,原始檔案應小於 7 MB。

Base64 和本地路徑方式無需服務端下載,網路不穩定時穩定性更高。

模型輸出文字定位的結果後,如何將檢測框繪製到原圖上?

取得模型輸出的文字定位結果後,請按照 draw_bbox.py 的程式碼,將偵測框和標籤繪製到原始圖片上。

傳入自訂 Prompt 後返回空內容或前端標籤式內容怎麼辦?

使用 qwen3.5-ocr 時,如果自訂 Prompt 中包含完整的 HTML 結構(例如 <html><body>...</body></html>),模型可能會遵循該結構,以 HTML 格式而非純文字回傳 OCR 結果,此時回傳的內容可能看起來為空或包含前端標籤。僅包含簡單標籤(例如單個 <br>)不會觸發此行為。

可按以下任一方式處理:

  • 檢查 Prompt 中是否包含完整的 HTML 標籤結構。若有,請改用純文字指示重試。例如將 <html><body>请提取图片中的所有文字</body></html> 改為 Please extract all text from the image。
  • 如果不確定 Prompt 是否會影響輸出格式,可以省略 text 欄位,使用模型的預設 Prompt。
  • 改用 qwen3.7-plus 模型,對於帶有 HTML 結構的相同 Prompt,它仍會回傳純文字結果。

API參考

Qwen-OCR 模型的輸入輸出參數詳見Qwen-OCR API參考。

錯誤碼

如果模型調用失敗並返回報錯資訊,請參見錯誤碼進行解決。