QwenCloudBRASIL
Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗

Compreensão em PDF

O entendimento de PDF permite que o modelo analise e compreenda documentos PDF, extraindo texto e imagens para análise. Você pode passar arquivos PDF por URL ou codificação Base64.

Você pode passar arquivos PDF via URL ou dados codificados pela API de Completação de Chat compatível com OpenAI ou pela API DashScope.

O entendimento de PDF não é suportado pela API de respostas neste momento. Se você passar um PDF usando a API Responses, o pedido ainda retorna HTTP 200, mas o arquivo não é entregue ao modelo.

Modelos apoiados.

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

-Começo rápido.

Execute o seguinte código para enviar um arquivo PDF para o modelo.

-Pegue um...QwenCloud Chave API] (/api-reference/preparation/api-key(configurando-o como uma variável de ambiente) (/api-reference/preparation/export-api-key-env).

OpenAI compatible

  ```python Python
  from openai import OpenAI
  import os

  client = OpenAI(
      # If the environment variable is not configured, replace it with your QwenCloud API key: api_key="sk-xxx"
      api_key=os.getenv("DASHSCOPE_API_KEY"),
      base_url="https://maas.qwencloudapi.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},
      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)
  ```

  ```javascript Node.js
  import OpenAI from "openai";
  import process from 'process';

  const openai = new OpenAI({
      // If the environment variable is not configured, replace it with your QwenCloud API key: apiKey: "sk-xxx",
      apiKey: process.env.DASHSCOPE_API_KEY,
      baseURL: 'https://maas.qwencloudapi.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 },
          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();
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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 Python
  import os
  from dashscope import MultiModalConversation
  import dashscope

  dashscope.base_http_api_url = "https://maas.qwencloudapi.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 QwenCloud 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)
  ```

  ```bash curl
  curl -X POST "https://maas.qwencloudapi.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"
      }
  }'
  ```

Base64 entrada

Se não puder fornecer um URL de arquivo, pode passar o arquivo PDF como uma string codificada pela Base64. Quando se usa file_data, o filename O campo é obrigatório.

A codificação Base64 aumenta o tamanho dos dados em cerca de 1/3. Por exemplo, um arquivo de 150 MB torna-se cerca de 200 MB após a codificação, que excede o limite de tamanho do corpo pedido. Para arquivos grandes, passe o arquivo por URL.

OpenAI compatible

```python Python
import base64
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://maas.qwencloudapi.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)
```

DashScope

```python Python
import base64
import os
from dashscope import MultiModalConversation
import dashscope

dashscope.base_http_api_url = "https://maas.qwencloudapi.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"])
```

Requisito parâmetros.

A entrada do arquivo é especificada como um elemento no content Array. O protocolo compatível com o OpenAI usa o type: "file" O protocolo DashScope usa um elemento contendo file_url/file_data.

O campo URL no protocolo só aceita uma string. Uma lista (array) de URLs não é suportada.

** Formato compatível com o OpenAI:**

Limites

Ver a tabela estruturada nos quadros de referência desta página ↓

A análise de PDF pode demorar mais do que um pedido de texto normal. O intervalo de espera de primeira hora é de 300 segundos. Recomendamos usar a saída de streaming para obter resultados em tempo real e evitar longas esperas.

Contagem

A cobrança envolve o seguinte:

Veja a contagem de páginas em PDF.

Para ver a página PDF analisada contar na resposta, obter a partir de pdf_page_parser.count na usage Campo. Os dois protocolos se comportam de forma um pouco diferente:

// Returned only when "include_tool_usage": true is passed at the top level of the request body.
// For the OpenAI Python SDK, pass it via extra_body={"include_tool_usage": True}.
// When using HTTP/curl directly, place 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 required.
{
    "usage": {
        "plugins": {
            "pdf_page_parser": {
                "count": 10,
                "strategy": "normal"
            }
        }
    }
}

Códigos de erro.

Se uma ligação falhar, veja [Mensagens de erro] (/api-reference/preparation/error-messages).

Quadros de referência

Tabelas restauradas a partir da referência original; a ordem das colunas e os valores técnicos foram preservados.

Quadro 1

Parâmetro Tipo Obrigatório Descrição
file_url string Um dos dois requeridos. A URL de download do arquivo PDF. -Mutualmente exclusivo comfile_data.
file_data string Um dos dois requeridos. Base64-codificado entrada PDF no formatodata:application/pdf;base64,xxx. -Mutualmente exclusivo comfile_url.
filename string Condicionalmente necessário. O nome do arquivo. - É necessário quando se usafile_data.
file_format string Não O formato do arquivo. Atualmente sópdfé apoiado. Predefinição parapdf.

Quadro 2

Item Limite
Tamanho máximo do arquivo 150 MB
Número máximo de páginas 256 páginas

* Valores em reais sujeitos a ajustes e a flutuações cambiais. Conversões estimadas, sem impostos, spread ou tarifas; confirme o valor final na plataforma oficial.