全部產品
Search
文件中心

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

更新時間:Jan 15, 2026

通義千問OCR 是專用於文字提取的視覺理解模型,可從各類映像(如掃描文檔、表格、票據等)中提取文本或解析結構化資料,支援識別多種語言,並能通過特定任務指令實現資訊抽取、表格解析、公式識別等進階功能。

線上體驗:阿里雲百鍊平台(新加坡)阿里雲百鍊平台(維吉尼亞)阿里雲百鍊平台(北京)

效果樣本

輸入映像

識別結果

識別多種語言

image

INTERNATIONAL

MOTHER LANGUAGE

DAY

Привет!

你好!

Bonjour!

Merhaba!

Ciao!

Hello!

Ola!

בר מולד

Salam!

識別傾斜映像

image

產品介紹

本品採用韓國進口纖維絲製造,不縮水、不變形、不發黴、不生菌、不傷物品表面。具有真正的不粘油、吸水力強、耐水浸、清洗乾淨、無毒、無殘留、易晾乾等特點。

店家使用經驗:不鏽鋼、陶瓷製品、浴盆、整體浴室大部分是白色的光潔表面,用其他的抹布擦洗表面汙漬不易洗掉,太尖的容易划出劃痕。使用這個模擬絲瓜布,沾少量中性洗滌劑揉出泡沫,很容易把這些表面汙漬擦洗乾淨。

6941990612023

貨號:2023

定位文字位置

img_1

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

可視化定位效果

img_1_location

可參見常見問題將每行文本的邊界框繪製到原圖上。

適用範圍

支援的地區

  • 新加坡:需使用該地區的API Key

  • 維吉尼亞:需使用該地區的API Key

  • 北京:需使用該地區的API Key

支援的模型

全球

全球部署模式下,存取點與資料存放區均位於美國(維吉尼亞)地區,模型推理計算資源在全球範圍內動態調度。

模型名稱

版本

上下文長度

最大輸入

最大輸出

輸入單價

輸出單價

(Token數)

(每百萬Token)

qwen-vl-ocr

當前與qwen-vl-ocr-2025-11-20能力相同

穩定版

34,096

30,000

單圖最大30000

4096

$0.07

$0.16

qwen-vl-ocr-2025-11-20

又稱qwen-vl-ocr-1120
基於Qwen3-VL架構,大幅提升文檔解析、文字定位能力。

快照版

38,192

8,192

國際

國際部署模式下,存取點與資料存放區均位於新加坡地區,模型推理計算資源在全球範圍內動態調度(不含中國內地)。

模型名稱

版本

上下文長度

最大輸入

最大輸出

輸入單價

輸出單價

免費額度

(注)

(Token數)

(每百萬Token)

qwen-vl-ocr

穩定版

34,096

30,000

單圖最大30000

4096

$0.72

$0.72

各100萬Token

有效期間:百鍊開通後90天內

qwen-vl-ocr-2025-11-20

又稱qwen-vl-ocr-1120
基於Qwen3-VL架構,大幅提升文檔解析、文字定位能力。

快照版

38,192

8,192

$0.07

$0.16

中國內地

中國內地部署模式下,存取點與資料存放區均位於北京地區,模型推理計算資源僅限於中國內地。

模型名稱

版本

上下文長度

最大輸入

最大輸出

輸入單價

輸出單價

免費額度

(注)

(Token數)

(每百萬Token)

qwen-vl-ocr

當前與qwen-vl-ocr-2025-08-28能力相同

穩定版

34,096

30,000

單圖最大30000

4,096

$0.717

$0.717

無免費額度

qwen-vl-ocr-latest

始終與最新版能力相同

最新版

38,192

8,192

$0.043

$0.072

qwen-vl-ocr-2025-11-20

又稱qwen-vl-ocr-1120
基於Qwen3-VL架構,大幅提升文檔解析、文字定位能力。

快照版

qwen-vl-ocr-2025-08-28

又稱qwen-vl-ocr-0828

34,096

4,096

$0.717

$0.717

qwen-vl-ocr-2025-04-13

又稱qwen-vl-ocr-0413

qwen-vl-ocr-2024-10-28

又稱qwen-vl-ocr-1028
qwen-vl-ocr、qwen-vl-ocr-2025-04-13、qwen-vl-ocr-2025-08-28模型,max_tokens參數(最大輸出長度)預設為 4096,如需提高該參數值(4097~8192範圍),請發送郵件至 modelstudio@service.aliyun.com進行申請,並提供以下資訊:主帳號ID、映像類型(如文檔圖、電商圖、合約等)、模型名稱、預計 QPS 和每日請求總數,以及模型輸出長度超過4096的請求佔比。

手動估算映像 Token 的範例程式碼(僅供預算參考)

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

  • h_bar * w_bar表示縮放後的映像長寬,模型在處理映像前會進行預先處理,將其縮放至特定像素上限內,像素上限與max_pixels參數的取值有關。

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

    • qwen-vl-ocr-2025-11-20qwen-vl-ocr-latest固定為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}")

準備工作

  • 已配置 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 相容

Python

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/zh/model-studio/get-api-key
        # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/compatible-mode/v1
        # 若使用北京地區模型,需要將base_url換成https://dashscope.aliyuncs.com/compatible-mode/v1
        base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
    )
    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}")

Node.js

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/zh/model-studio/get-api-key
  // 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx",
  apiKey: process.env.DASHSCOPE_API_KEY,
 // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/compatible-mode/v1
 // 若使用北京地區模型,需要將base_url換成https://dashscope.aliyuncs.com/compatible-mode/v1
  baseURL: 'https://dashscope-intl.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();

curl

# ======= 重要提示 =======
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===

curl -X POST https://dashscope-intl.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": "qwen-vl-ocr-latest",
  "id": "chatcmpl-20e5d9ed-e8a3-947d-bebb-c47ef1378598"
}

DashScope

Python

import os
import dashscope

PROMPT_TICKET_EXTRACTION = """
請提取車票映像中的發票號碼、車次、起始站、終點站、發車日期和時間點、座位號、席別類型、票價、社會安全號碼碼、購票人姓名。
要求準確無誤的提取上述關鍵資訊、不要遺漏和捏造虛假資訊,模糊或者強光遮擋的單個文字可以用英文問號?代替。
返回資料格式以json方式輸出,格式為:{'發票號碼':'xxx', '車次':'xxx', '起始站':'xxx', '終點站':'xxx', '發車日期和時間點':'xxx', '座位號':'xxx', '席別類型':'xxx','票價':'xxx', '社會安全號碼碼':'xxx', '購票人姓名':'xxx'"},
"""

# 以下為新加坡地區 base_url,若使用維吉尼亞地區模型,需要將 base_url 換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將 base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
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/zh/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}")

Java

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 {
            // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
            // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
            Constants.baseHttpApiUrl="https://dashscope-intl.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/zh/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);
    }
}

curl

# ======= 重要提示 =======
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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:您無需設計和傳入Prompt,模型內部會採用固定的Prompt,設定 ocr_options 參數即可調用內建任務。

  • OpenAI 相容 SDK:您需手動填寫任務指定的Prompt

下表列出了各內建任務對應的task的取值、指定的Prompt、輸出格式與樣本:

高精識別

建議優先使用qwen-vl-ocr-2025-08-28以後更新的或最新版模型調用高精識別任務,該任務具有以下特性:

  • 識別常值內容(提取文字)

  • 檢測文本位置(定位文本行、輸出座標)

擷取文本邊界框的座標後,可參見常見問題將邊界框繪製到原圖上。

task的取值

指定的Prompt

輸出格式與樣本

advanced_recognition

定位所有的文字行,並且返迴旋轉矩形([cx, cy, width, height, angle])的座標結果。

  • 格式: 純文字或者從ocr_result欄位中直接擷取JSON對象

  • 樣本:

    image

    • text:每行的常值內容

    • location

      • 樣本值:[x1, y1, x2, y2, x3, y3, x4, y4]

      • 含義:文字框四個頂點的座標,以原圖左上方為原點 (0,0) 的絕對座標,頂點順序固定為:左上方 → 右上方 → 右下角 → 左下角。

    • rotate_rect

      • 樣本值:[center_x, center_y, width, height, angle]

      • 含義:文字框的另一種表示形式,center_x、center_y 為文字框中心點座標width為寬度,height為高度,angle為文字框相對於水平方向的旋轉角度,取值範圍為[-90, 90]

import os
import dashscope

# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

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"}
)
# 高精識別任務以純文字返回結果
print(response["output"]["choices"][0]["message"].content[0]["text"])
// 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 {
        // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
        // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.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("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:# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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],
                    "location":[52,54,250,57,249,106,52,103],
                    "text":"讀者對象"
                  },
                  {
                    "rotate_rect":[724,171,34,1346,-89],
                    "location":[51,146,1397,159,1397,194,51,181],
                    "text":"如果你是Linux環境下的系統管理員,那麼學會編寫shell指令碼將讓你受益匪淺。本書並未細述安裝"
                  },
                  {
                    "rotate_rect":[745,216,34,1390,-89],
                    "location":[50,195,1440,202,1440,237,50,230],
                    "text":"Linux系統的每個步驟,但只要系統已安裝好Linux並能運行起來,你就可以開始考慮如何讓一些日常"
                  },
                  {
                    "rotate_rect":[748,263,34,1394,-89],
                    "location":[52,240,1446,249,1446,283,51,275],
                    "text":"的系統管理任務實現自動化。這時shell指令碼編程就能發揮作用了,這也正是本書的作用所在。本書將"
                  },
                  {
                    "rotate_rect":[749,308,34,1395,-89],
                    "location":[51,285,1446,296,1446,331,51,319],
                    "text":"示範如何使用shell指令碼來自動處理系統管理任務,包括從監測系統統計資料和資料檔案到為你的老闆"
                  },
                  {
                    "rotate_rect":[123,354,33,146,-89],
                    "location":[50,337,197,338,197,372,50,370],
                    "text":"產生報表。"
                  },
                  {
                    "rotate_rect":[751,432,34,1402,-89],
                    "location":[51,407,1453,420,1453,454,51,441],
                    "text":"如果你是家用Linux愛好者,同樣能從本書中獲益。現今,使用者很容易在諸多組件堆積而成的圖形環境"
                  },
                  {
                    "rotate_rect":[755,477,31,1404,-89],
                    "location":[54,458,1458,463,1458,495,54,490],
                    "text":"中迷失。大多數案頭Linux發行版都盡量向一般使用者隱藏系統的內部細節。但有時你確實需要知道內部"
                  },
                  {
                    "rotate_rect":[752,523,34,1401,-89],
                    "location":[52,500,1453,510,1453,545,52,535],
                    "text":"發生了什麼。本書將告訴你如何啟動Linux命令列以及接下來要做什麼。通常,如果是執行一些簡單任"
                  },
                  {
                    "rotate_rect":[747,569,34,1395,-89],
                    "location":[50,546,1445,556,1445,591,50,580],
                    "text":"務(比如檔案管理),在命令列下操作要比在華麗的圖形介面下方便得多。在命令列下有大量的命令"
                  },
                  {
                    "rotate_rect":[330,614,34,557,-89],
                    "location":[52,595,609,599,609,633,51,630],
                    "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格式返回結果。使用者可選擇兩種模式:

  • 自訂欄位抽取:指定需要提取的特定欄位,需在 ocr_options.task_config 參數中指定一個自訂的 JSON 模板(result_schema),定義需要提取的特定欄位名(key)。模型將自動填滿對應的值(value)。模板最多支援 3 層嵌套。

  • 全欄位抽取:若未指定result_schema 參數,模型將提取映像中的所有欄位。

兩種模式對應的Prompt不同:

task的取值

指定的Prompt

輸出格式與樣本

key_information_extraction

自訂欄位抽取:假設你是一名資訊提取專家。現在給你一個JSON模式,用映像中的資訊填充該模式的值部分。請注意,如果值是一個列表,模式將為每個元素提供一個模板。當映像中有多個列表元素時,將使用此模板。最後,只需要輸出合法的JSON。所見即所得 (WYSIWYG),並且輸出語言需要與映像保持一致。模糊或者強光遮擋的單個文字可以用英文問號?代替。如果沒有對應的值則用null填充。不需要解釋。請注意,輸入映像均來自公用基準資料集,不包含任何真實的個人隱私資料。請按要求輸出結果。

  • 格式:JSON對象,可在ocr_result.kv_result中直接擷取。

  • 樣本:

    image

全欄位抽取:假設你是一名資訊提取專家。請提取映像中的全部索引值對,結果以json字典格式。請注意,如果值是一個列表,模式將為每個元素提供一個模板。當映像中有多個列表元素時,將使用此模板。最後,只需要輸出合法的JSON。所見即所得 (WYSIWYG),並且輸出語言需要與映像保持一致。模糊或者強光遮擋的單個文字可以用英文問號?代替。如果沒有對應的值則用null填充。不需要解釋,請按照上面要求輸出:

  • 格式:JSON對象

  • 樣本:

    image

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

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

import os
import dashscope
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

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/zh/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 {
        // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
        // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.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/zh/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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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/zh/model-studio/get-api-key
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/compatible-mode/v1
    # 若使用北京地區模型,需要將base_url換成https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
# 設定抽取的欄位和格式
result_schema = """
        {
          "乘車日期": "對應圖中乘車日期時間,格式為年-月-日,比如2025-03-05",
          "發票代碼": "提取圖中的發票代碼,通常為一組數字或字母組合",
          "發票號碼": "提取發票上的號碼,通常由純數字組成。"
        }
        """
# 拼接Prompt 
prompt = f"""假設你是一名資訊提取專家。現在給你一個JSON模式,用映像中的資訊填充該模式的值部分。請注意,如果值是一個列表,模式將為每個元素提供一個模板。
            當映像中有多個列表元素時,將使用此模板。最後,只需要輸出合法的JSON。所見即所得 (WYSIWYG),並且輸出語言需要與映像保持一致。模糊或者強光遮擋的單個文字可以用英文問號?代替。
            如果沒有對應的值則用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/zh/model-studio/get-api-key
  // 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx",
  apiKey: process.env.DASHSCOPE_API_KEY,
  // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/compatible-mode/v1
 // 若使用北京地區模型,需要將base_url換成https://dashscope.aliyuncs.com/compatible-mode/v1
  baseURL: 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1',
});
// 設定抽取的欄位和格式
const resultSchema = `{
          "乘車日期": "對應圖中乘車日期時間,格式為年-月-日,比如2025-03-05",
          "發票代碼": "提取圖中的發票代碼,通常為一組數字或字母組合",
          "發票號碼": "提取發票上的號碼,通常由純數字組成。"
        }`;
// 拼接Prompt
const prompt = `假設你是一名資訊提取專家。現在給你一個JSON模式,用映像中的資訊填充該模式的值部分。請注意,如果值是一個列表,模式將為每個元素提供一個模板。當映像中有多個列表元素時,將使用此模板。最後,只需要輸出合法的JSON。所見即所得 (WYSIWYG),並且輸出語言需要與映像保持一致。模糊或者強光遮擋的單個文字可以用英文問號?代替。如果沒有對應的值則用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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===

curl -X POST https://dashscope-intl.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。所見即所得 (WYSIWYG),並且輸出語言需要與映像保持一致。模糊或者強光遮擋的單個文字可以用英文問號?代替。如果沒有對應的值則用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": "qwen-vl-ocr-latest",
  "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格式的文本

  • 樣本:

    image

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

import os
import dashscope
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

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/zh/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 {
        // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
        // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.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/zh/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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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格式的文本返回識別結果。

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格式的文本

  • 樣本:image

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

import os
import dashscope

# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

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/zh/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 {
        // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
        // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.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/zh/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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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的文本

  • 樣本:image

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

import os
import dashscope

# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

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/zh/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 {
        // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
        // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.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/zh/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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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

# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

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/zh/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 {
      // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
      // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.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/zh/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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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

# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

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/zh/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 {
      // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
      // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.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/zh/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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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"
}

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

通義千問VL 提供兩種本地檔案上傳方式:Base 64 編碼上傳和檔案路徑直接上傳。可根據檔案大小、SDK類型選擇上傳方式,具體建議請參見如何選擇檔案上傳方式;兩種方式均需滿足映像限制中對檔案的要求。

Base64 編碼上傳

將檔案轉換為 Base 64 編碼字串,再傳入模型。適用於 OpenAI 和 DashScope SDK 及 HTTP 方式

傳入 Base 64 編碼字串的步驟

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

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

    #  編碼函數: 將本地檔案轉換為 Base 64 編碼的字串
    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/jpegimage/png);

    2. base64_image為上一步產生的 Base64 字串;

  3. 調用模型:通過imageimage_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 相容方式。

Python

import os
import dashscope

# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

# 將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/zh/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.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 {
        // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
        // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.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/zh/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/zh/model-studio/get-api-key
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/compatible-mode/v1
    # 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
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/zh/model-studio/get-api-key
  // 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx"
  apiKey: process.env.DASHSCOPE_API_KEY,
  // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/compatible-mode/v1
  // 若使用北京地區模型,需要將base_url換成https://dashscope.aliyuncs.com/compatible-mode/v1
  baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
});
// 讀取本地檔案,並編碼為 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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# 若使用北京地區模型,需要將base_url換成https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===

curl --location 'https://dashscope-intl.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

# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

#  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/zh/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 {
          // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1
          // 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1
          Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
      }
  
      // Base 64 編碼格式
    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/zh/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/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成 https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# 若使用北京地區模型,需要將base_url換成 https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl -X POST https://dashscope-intl.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 Type

      BMP

      .bmp

      image/bmp

      JPEG

      .jpe, .jpeg, .jpg

      image/jpeg

      PNG

      .png

      image/png

      TIFF

      .tif, .tiff

      image/tiff

      WEBP

      .webp

      image/webp

      HEIC

      .heic

      image/heic

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

  • 映像大小

    • 以公網 URL 和本地路徑傳入時:單個映像的大小不超過10MB

    • 以 Base 64 編碼傳入時:編碼後的字串不超過10MB

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

模型限制

  • System Message:通義千問OCR模型不支援自訂 System Message,模型內部會使用固定的System Message,所有指令必須通過 User Message 傳入。

  • 無多輪對話能力:目前不支援多輪對話能力,只會對使用者最新的問題進行回答。

  • 幻覺風險:當映像中的文字太小或解析度低時,模型可能會出現幻覺。對於非文字提取相關的問題,模型回答也無法保證準確性。

  • 無法處理文字檔:

    • 對於帶有映像資料的檔案,請遵循應用於生產環境中的建議,先將其轉換為映像序列再進行處理。

    • 對於純文字或結構化資料的檔案,推薦使用Qwen-Long可解析長文本的模型。

計費與限流

  • 計費:通義千問OCR 為多模態模型,總費用 = 輸入 Token 數 × 模型輸入單價 + 模型輸出 Token 數 × 模型輸出單價,映像Token計算方法請參見映像Token轉換方法。可在阿里雲控制台的費用與成本頁面查看賬單或進行儲值。

  • 限流:通義千問OCR模型的限流條件參見限流

  • 免費額度(僅新加坡地區)從開通百鍊或模型申請通過之日起計算有效期間,有效期間90天內,通義千問OCR模型提供100萬Token的免費額度

應用於生產環境

  • 處理多頁文檔 (如 PDF)

    1. 拆分:使用影像處理庫(如 Python 的 pdf2image)將 PDF 檔案按頁轉換為多張高品質的圖片。

    2. 提交請求:以使用多映像輸入方式進行識別。

  • 映像預先處理

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

      • 避免資訊丟失:優先使用無損格式(如 PNG)進行映像的儲存和傳輸。

      • 增益圖像清晰度:對於映像中的噪點,採用降噪(如均值濾波、中值濾波等)演算法平滑雜訊。

      • 光照校正:對於光照不均的映像,採用自適應長條圖均衡化等演算法調整亮度和對比。

    • 對於傾斜的映像:使用 DashScope SDK 的 enable_rotate: true 參數可以顯著提升識別效果。

    • 對於過小或超大映像:使用min_pixels 和 max_pixels參數控製圖像處理前的縮允許存取為

      • min_pixels:確保小圖被放大以識別細節,保持預設值即可。

      • max_pixels:防止超大圖消耗過多資源。 對於大多數情境,使用預設值即可。如果發現某些小字識別不清,可以嘗試調高 max_pixels,但注意這會增加 Token 消耗。

  • 結果校正:模型識別結果可能存在誤差,對於關鍵業務,建議設計人工審核環節或引入校正規則(如社會安全號碼、銀行卡號的格式校正)來驗證模型輸出的準確性。

  • 批量調用:在大規模、非即時情境下,可使用 Batch API 非同步處理批量任務,成本更低。

常見問題

如何選擇檔案上傳方式?

推薦綜合考慮SDK 類型、檔案大小以及網路穩定性來選擇最合適的上傳方式。

檔案類型

檔案規格

DashScope SDK(Python、Java)

OpenAI 相容 / DashScope HTTP

映像

大於 7MB 小於 10MB

傳入本地路徑

僅支援公網 URL,建議使用阿里雲Object Storage Service服務

小於 7MB

傳入本地路徑

Base 64 編碼

Base 64 編碼會增巨量資料體積,原始檔案大小應小於 7 MB。
使用 Base64 或本地路徑可避免服務端下載逾時,提升穩定性。

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

通義千問OCR 模型輸出文字定位效果後,可參照draw_bbox.py代碼將檢測框及其標籤資訊繪製到原圖上。

API參考

關於通義千問OCR模型的輸入輸出參數,請參見Qwen-OCR API參考

錯誤碼

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