PDF understanding

Updated at:

Parse text and images in PDF documents with Chat Completions, the Responses API, DashScope, or the Anthropic-compatible API.

Supported Models

qwen4-max , qwen3.8-max, qwen3.8-max-0902, qwen3.8-flash, qwen3.8-27b, kimi-k3.1-pro

qwen3.8-27b supports PDF understanding only through Chat Completions or DashScope in Beijing.

Quick Start

The following examples demonstrate how to send a PDF file to the model.

You must have Obtain an API key and completed Configure API key as an environment variable.

OpenAI Compatible

Python

Sample Code

from openai import OpenAI
import os

client = OpenAI(
    # If the environment variable is not configured, replace it with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the Beijing (China) region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen4-max",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "file",
                    "file": {
                        "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
                    }
                },
                {
                    "type": "text",
                    "text": "Summarize this PDF document"
                }
            ]
        }
    ],
    stream=True,
    stream_options={"include_usage": True},
    # Required to return usage.x_tools.pdf_page_parser.count (PDF parsed page count)
    extra_body={"include_tool_usage": True}
)

for chunk in completion:
    if not chunk.choices:
        print(f"\nUsage: {chunk.usage}")
        continue
    delta = chunk.choices[0].delta
    if hasattr(delta, "content") and delta.content:
        print(delta.content, end="", flush=True)

Node.js

Sample Code

import OpenAI from "openai";
import process from 'process';

const openai = new OpenAI({
    // If the environment variable is not configured, replace it with your Model Studio API key: apiKey: "sk-xxx"
    apiKey: process.env.DASHSCOPE_API_KEY,
    // The following is the URL for the Beijing (China) region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
    baseURL: 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1'
});

async function main() {
    const stream = await openai.chat.completions.create({
        model: 'qwen4-max',
        messages: [
            {
                role: 'user',
                content: [
                    {
                        type: 'file',
                        file: {
                            file_url: 'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf'
                        }
                    },
                    {
                        type: 'text',
                        text: 'Summarize this PDF document'
                    }
                ]
            }
        ],
        stream: true,
        stream_options: { include_usage: true },
        // Required to return usage.x_tools.pdf_page_parser.count (PDF parsed page count)
        include_tool_usage: true
    });

    for await (const chunk of stream) {
        if (!chunk.choices?.length) {
            console.log('\nUsage:', chunk.usage);
            continue;
        }
        const delta = chunk.choices[0].delta;
        if (delta.content) {
            process.stdout.write(delta.content);
        }
    }
}

main();

HTTP

Sample Code

# The following is the URL for the Beijing (China) region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen4-max",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "file",
                    "file": {
                        "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
                    }
                },
                {
                    "type": "text",
                    "text": "Summarize this PDF document"
                }
            ]
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "include_tool_usage": true
}'

DashScope

Python

Sample Code

import os
from dashscope import MultiModalConversation
import dashscope

# The following is the URL for the Beijing (China) region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

messages = [
    {
        "role": "user",
        "content": [
            {
                "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
            },
            {
                "text": "Summarize this PDF document"
            }
        ]
    }
]

completion = MultiModalConversation.call(
    # If the environment variable is not configured, replace it with your Alibaba Cloud Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen4-max",
    messages=messages,
    stream=True,
    incremental_output=True
)

for chunk in completion:
    message = chunk.output.choices[0].message
    if message.content:
        print(message.content[0]["text"], end="", flush=True)

HTTP

Sample Code

# The following is the URL for the Beijing (China) region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
curl -X POST "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen4-max",
    "input": {
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
                    },
                    {
                        "text": "Summarize this PDF document"
                    }
                ]
            }
        ]
    },
    "parameters": {
        "incremental_output": true,
        "result_format": "message"
    }
}'

Responses API

The Responses API accepts PDF input through input_file.file_url. qwen3.8-27b does not support this input format.

These examples use a dedicated workspace endpoint in Beijing. Replace {WorkspaceId} and configure the API key and endpoint for your region and deployment scope. See Access information.

import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DASHSCOPE_API_KEY"],
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
    timeout=300.0,
)

response = client.responses.create(
    model="qwen3.8-flash",
    input=[{
        "role": "user",
        "content": [
            {"type": "input_file", "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"},
            {"type": "input_text", "text": "Summarize this PDF document."},
        ],
    }],
    extra_body={"include_tool_usage": True},
)

print(response.output_text)
curl 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/responses' \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "input": [{
      "role": "user",
      "content": [
        {"type": "input_file", "file_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"},
        {"type": "input_text", "text": "Summarize this PDF document."}
      ]
    }],
    "include_tool_usage": true
  }'

Anthropic

qwen3.8-max, qwen3.8-flash, and qwen4 series models support PDF file URLs through the Anthropic-compatible Messages API. In messages[].content, use a type: "document" content block, set source.type to url, and specify the PDF file URL in source.url.

curl --location 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic/v1/messages' \
  --header 'Content-Type: application/json' \
  --header "x-api-key: $DASHSCOPE_API_KEY" \
  --data '{
    "model": "qwen3.8-max",
    "max_tokens": 1024,
    "messages": [{
      "role": "user",
      "content": [
        {
          "type": "document",
          "source": {
            "type": "url",
            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260616/qmycjl/1506.02640v5.pdf"
          }
        },
        {"type": "text", "text": "总结一下这个PDF文档的内容"}
      ]
    }]
  }'

For the full parameter reference, see Anthropic-compatible Messages.

Using Base64 Input

If you cannot provide a URL, you can pass the PDF file as a Base64-encoded string. The filename field is required when using file_data.

NoteBase64 encoding increases the data size by about one third. For example, a 150 MB file becomes about 200 MB after encoding, which exceeds the request body size limit. For large files, use the URL method instead.

Chat Completions / DashScope

import base64
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the Beijing (China) region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

# Read and encode the PDF file
with open("report.pdf", "rb") as f:
    pdf_base64 = base64.b64encode(f.read()).decode("utf-8")

completion = client.chat.completions.create(
    model="qwen4-max",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "file",
                    "file": {
                        "file_data": f"data:application/pdf;base64,{pdf_base64}",
                        "filename": "report.pdf"
                    }
                },
                {
                    "type": "text",
                    "text": "What are the key findings in this report?"
                }
            ]
        }
    ]
)

print(completion.choices[0].message.content)
import base64
import os
from dashscope import MultiModalConversation
import dashscope

# The following is the URL for the Beijing (China) region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"

# Read and encode the PDF file
with open("report.pdf", "rb") as f:
    pdf_base64 = base64.b64encode(f.read()).decode("utf-8")

messages = [
    {
        "role": "user",
        "content": [
            {
                "file_data": f"data:application/pdf;base64,{pdf_base64}",
                "filename": "report.pdf"
            },
            {
                "text": "What are the key findings in this report?"
            }
        ]
    }
]

response = MultiModalConversation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen4-max",
    messages=messages
)

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

Anthropic

The Anthropic-compatible API supports Base64 PDF input. qwen3.8-max, qwen3.8-flash, and qwen4 series models also support PDF file URLs through document.source.type="url".

The Anthropic-compatible API accepts Base64 PDF input through document.source. Download the sample PDF as report.pdf, or use your own PDF file. Install the anthropic SDK to run the Python example.

These examples use a dedicated workspace endpoint in Beijing. Replace {WorkspaceId} and configure the API key and endpoint for your region and deployment scope. See Access information.

import os
import base64
from anthropic import Anthropic

client = Anthropic(
    api_key=os.environ["DASHSCOPE_API_KEY"],
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic",
    timeout=300.0,
)

with open("report.pdf", "rb") as file:
    pdf_base64 = base64.b64encode(file.read()).decode("utf-8")

response = client.messages.create(
    model="qwen3.8-flash",
    max_tokens=1024,
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "document",
                "source": {
                    "type": "base64",
                    "media_type": "application/pdf",
                    "data": pdf_base64,
                },
            },
            {"type": "text", "text": "Summarize this PDF document."},
        ],
    }],
    extra_body={"include_tool_usage": True},
)

for block in response.content:
    if block.type == "text":
        print(block.text)
PDF_BASE64=$(base64 < report.pdf | tr -d '\n')
curl 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/apps/anthropic/v1/messages' \
  -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @- <<EOF
{
  "model": "qwen3.8-flash",
  "max_tokens": 1024,
  "messages": [{
    "role": "user",
    "content": [
      {
        "type": "document",
        "source": {
          "type": "base64",
          "media_type": "application/pdf",
          "data": "$PDF_BASE64"
        }
      },
      {"type": "text", "text": "Summarize this PDF document."}
    ]
  }],
  "include_tool_usage": true
}
EOF

Request Parameters

The following parameter table applies to Chat Completions. The Responses API uses type: "input_file" and file_url. The Anthropic-compatible API uses type: "document". For URL input, set source.type: "url" and source.url; for Base64 input, set source.type: "base64", source.media_type: "application/pdf", and source.data (a Base64 string without a Data URI prefix). URL input is supported by qwen3.8-max, qwen3.8-flash, and qwen4 series models. DashScope accepts files as items in the content array containing file_url or file_data.

NoteThe URL field only accepts a string. A list (array) of URLs is not supported.

OpenAI-compatible format:

Parameter

Type

Required

Description

file_url

string

Required (choose one of the two)

The download URL of the PDF file. Choose either this or file_data.

file_data

string

Base64-encoded PDF input in the format data:application/pdf;base64,xxx. Choose either this or file_url.

filename

string

Conditionally required

The file name. Required when using file_data.

file_format

string

No

The file format. Currently only pdf is supported. Defaults to pdf.

Limits

Item

Limit

Maximum file size

150 MB

Maximum page count

256 pages

NotePDF parsing may take longer than regular text requests. The first token timeout is up to 300 seconds. We recommend using streaming output to avoid long waits.

Billing

Billing involves the following:

  • Model call fee: Text and images extracted from the PDF are counted as the model's input tokens and billed at the model's standard input token rate.
  • Document parsing fee: Charged per page of the PDF document parsed. Unit prices vary by region: China (Beijing) ¥0.02 per page, Singapore ¥0.024 per page. Global deployment mode: CNY 0.02 per page.

For per-model input and output token prices, see Model inference pricing.

View parsed PDF page count

For qwen4-max Responses, read the top-level tool_usage. Each tool’s num_requests is the billed request count; pdf_page_parser.num_requests is the parsed page count. Qwen3.8 Responses examples use usage.x_tools.

For Chat Completions and the Responses API (Qwen3.8), pass include_tool_usage: true at the top level of the request body and read usage.x_tools.pdf_page_parser.count. For DashScope, read usage.plugins.pdf_page_parser.count. The Anthropic-compatible API returns the count in the top-level response field x_tools.pdf_page_parser.count. An omitted count does not mean that no parsing fee was incurred.

// You must pass "include_tool_usage": true at the top level of the request body.
// With the OpenAI Python SDK, pass it via extra_body={"include_tool_usage": True}.
// With raw HTTP/curl, put it at the top level; do NOT nest it inside extra_body or stream_options.
{
    "usage": {
        "x_tools": {
            "pdf_page_parser": {
                "count": 10,
                "strategy": "normal"
            }
        }
    }
}
// Returned by default; no extra parameter is required.
{
    "usage": {
        "plugins": {
            "pdf_page_parser": {
                "count": 10,
                "strategy": "normal"
            }
        }
    }
}
{
    "x_tools": {
        "pdf_page_parser": {
            "count": 10,
            "strategy": "normal"
        }
    }
}