Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Comprensión de PDF

Última actualización: Oct 23, 2026

La Comprensión de PDF permite al modelo analizar y comprender documentos PDF, extrayendo texto e imágenes para su análisis. Puede pasar archivos PDF mediante URL o codificación Base64.

La comprensión de PDF está disponible actualmente en China (Beijing) y Singapur (qwen3.8-27b admite la comprensión de PDF solo en China (Beijing); no está disponible en Singapur). Las llamadas a través de la Responses API no son compatibles en este momento; si pasa un PDF mediante la Responses API, la llamada aún devuelve HTTP 200, pero el archivo no se entrega al modelo.

Modelos compatibles

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

Inicio rápido

Los siguientes ejemplos demuestran cómo enviar un archivo PDF al modelo.

Debe haber Obtenido una clave API y completado Configurar la clave API como variable de entorno.

Compatible con OpenAI

Python

Código de ejemplo

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="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},
    # 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

Código de ejemplo

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: '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 },
        // 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

Código de ejemplo

# 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": "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
    },
    "include_tool_usage": true
}'

DashScope

Python

Código de ejemplo

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="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 ejemplo

# 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": "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

Si no puede proporcionar una URL, puede pasar el archivo PDF como una cadena codificada en Base64. El campo filename es obligatorio cuando se utiliza file_data.

NotaLa codificación Base64 aumenta el tamaño de los datos en aproximadamente un tercio. Por ejemplo, un archivo de 150 MB se convierte en unos 200 MB después de la codificación, lo que excede el límite de tamaño del cuerpo de la solicitud. Para archivos grandes, utilice el método de URL en su lugar.

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="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 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="qwen3.8-max",
    messages=messages
)

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

Parámetros de solicitud

La entrada de archivo se especifica como un elemento de contenido con type: "file" (compatible con OpenAI) o como un elemento de contenido que contiene file_url/file_data (DashScope).

NotaEl campo URL solo acepta una cadena. No se admite una lista (arreglo) de URLs.

Formato compatible con OpenAI:

Parámetro

Tipo

Obligatorio

Descripción

file_url

string

Condicional

URL del archivo PDF a descargar. Mutuamente excluyente con file_data.

file_data

string

Condicional

Datos PDF codificados en Base64 con el formato data:application/pdf;base64,.... Mutuamente excluyente con file_url.

filename

string

Condicional

El nombre del archivo. Obligatorio cuando se utiliza file_data.

file_format

string

No

El formato de archivo. Actualmente solo se admite pdf. El valor predeterminado es pdf.

Límites

Elemento

Límite

Tamaño máximo de archivo

150 MB

Número máximo de páginas

256 páginas

NotaEl análisis de PDF puede tardar más que las solicitudes de texto regulares. El tiempo de espera del primer token es de hasta 300 segundos. Se recomienda utilizar la salida por streaming para evitar largas esperas.

Facturación

La facturación incluye lo siguiente:

  • Tokens de entrada del modelo: El texto extraído del PDF y las imágenes analizadas de las páginas se cuentan como tokens de entrada, facturados a la tarifa estándar de tokens de entrada del modelo.
  • Tarifa de análisis de documentos: Se cobra por página del documento PDF analizado, correspondiente al elemento de medición document_parsing (pdf). Los precios unitarios varían según la región: China (Beijing) $0.003 por página, Singapur $0.0033 por página.

Para conocer los precios de tokens de entrada y salida por modelo, consulte Precios de inferencia de modelos.

Ver recuento de páginas PDF analizadas

Puede leer el recuento de páginas del PDF analizado desde el campo pdf_page_parser.count bajo usage en la respuesta. El comportamiento difiere ligeramente entre los dos protocolos:

// 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"
            }
        }
    }
}