Todos os produtos
Search
Central de documentação

Alibaba Cloud Model Studio:PDF understanding

Última atualização: Oct 23, 2026

A compreensão de PDF permite ao modelo analisar e interpretar documentos PDF, extraindo texto e imagens para análise. Envie arquivos PDF por URL ou codificação Base64.

A compreensão de PDF está disponível atualmente apenas em China (Beijing). Chamadas pela Responses API não têm suporte no momento. Se você enviar um PDF usando a Responses API, a chamada retornará HTTP 200, mas o arquivo não será entregue ao modelo.

Modelos compatíveis

qwen3.8-max, qwen3.8-flash, qwen3.8-27b

Início rápido

Os exemplos a seguir demonstram como enviar um arquivo PDF para o modelo.

É necessário ter Obtenha uma chave de API e ter concluído Configure a chave de API como uma variável de ambiente .

OpenAI Compatible

Python

Código de exemplo

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 Singapore region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "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}
)

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

Código de exemplo

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 Singapore region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

async function main() {
    const stream = await openai.chat.completions.create({
        model: 'qwen3.8-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 }
    });

    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

Código de exemplo

# The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3.8-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
    }
}'

DashScope

Python

Código de exemplo

import os
from dashscope import MultiModalConversation
import dashscope

# The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.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="qwen3.8-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

Código de exemplo

# The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen3.8-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"
    }
}'

Uso de entrada Base64

Se não for possível fornecer uma URL, envie o arquivo PDF como uma string codificada em Base64. O campo filename é obrigatório ao usar file_data.

ObservaçãoA codificação Base64 aumenta o tamanho dos dados em aproximadamente um terço. Por exemplo, um arquivo de 150 MB passa para cerca de 200 MB após a codificação, o que excede o limite de tamanho do corpo da requisição. Para arquivos grandes, use o método de URL.

import base64
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the URL for the Singapore region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.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="qwen3.8-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 Singapore region. Replace {WorkspaceId} with your actual workspace ID when calling the API. URLs differ by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.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="qwen3.8-max",
    messages=messages
)

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

Parâmetros da requisição

Especifique a entrada de arquivo como um item de conteúdo com type: "file" (compatível com OpenAI) ou como um item de conteúdo contendo file_url/file_data (DashScope).

ObservaçãoO campo URL aceita apenas uma string. Não há suporte para lista (array) de URLs.

Formato compatível com OpenAI:

Parâmetro

Tipo

Obrigatório

Descrição

file_url

string

Condicional

URL do arquivo PDF para download. Mutuamente exclusivo com file_data.

file_data

string

Condicional

Dados do PDF codificados em Base64 no formato data:application/pdf;base64,.... Mutuamente exclusivo com file_url.

filename

string

Condicional

Nome do arquivo. Obrigatório ao usar file_data.

file_format

string

Não

Formato do arquivo. Atualmente, há suporte apenas para pdf. O padrão é pdf.

Limites

Item

Limite

Tamanho máximo do arquivo

150 MB

Contagem máxima de páginas

256 páginas

ObservaçãoA análise de PDF pode levar mais tempo do que requisições de texto comuns. O tempo limite para o primeiro token é de até 300 segundos. Recomendamos usar saída em streaming para evitar longas esperas.

Faturamento

O faturamento inclui os seguintes itens:

  • Tokens de entrada do modelo: O texto extraído do PDF e as imagens analisadas das páginas são contabilizados como tokens de entrada e cobrados à taxa padrão de tokens de entrada do modelo.
  • Taxa de análise de documento: Cobrada por página do documento PDF analisado, correspondente ao item de medição document_parsing (pdf). Os preços unitários variam por região: China (Beijing): $0,003 por página, Singapura: $0,0033 por página.