# PDFs in

Send a PDF with your question; get an answer about it.

1. [Pick a model that reads PDFs](#1-pick-a-model-that-reads-pdfs).
2. [Add the PDF as a part of your message](#2-add-the-pdf-as-a-part-of-your-message).
3. [Choose how the PDF is read](#3-choose-how-the-pdf-is-read).
4. [Read the answer](#4-read-the-answer).

## 1. Pick a model that reads PDFs

[Models that take files in](/models?modality=text&input_modality=file) lists the ones that read a PDF themselves; the sample below uses `anthropic/claude-sonnet-4.5`. A model that cannot is still served: the PDF is read first, by a parser, and the model gets its text (step 3).

## 2. Add the PDF as a part of your message

A message's `content` is a text, or a list of parts. To send a PDF, make it a list: one `text` part for your question, one `file` part for the PDF.

| Part | Holds |
|---|---|
| `{"type": "text", "text": "..."}` | your question |
| `{"type": "file", "file": {"filename": "...", "file_data": "..."}}` | the PDF: a public link, or the PDF itself as a `data:application/pdf;base64,...` URL |
| `{"type": "file", "file": {"file_id": "..."}}` | a PDF you kept in Files: see [Files and storage](/docs/files-and-storage) |

```python
import json
import os
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/chat/completions"
MODEL = "anthropic/claude-sonnet-4.5"
PROMPT = "Summarise this document in two sentences."
FILENAME = "dummy.pdf"
PDF = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"

body = {
    "model": MODEL,
    "messages": [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": PROMPT},
                {
                    "type": "file",
                    "file": {"filename": FILENAME, "file_data": PDF},
                },
            ],
        }
    ],
}

request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(body).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    reply = json.load(response)

print(reply["choices"][0]["message"]["content"])
print(reply["usage"]["cost"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/chat/completions";
const MODEL = "anthropic/claude-sonnet-4.5";
const PROMPT = "Summarise this document in two sentences.";
const FILENAME = "dummy.pdf";
const PDF =
  "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf";

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: PROMPT },
          { type: "file", file: { filename: FILENAME, file_data: PDF } },
        ],
      },
    ],
  }),
});
const reply = await response.json();

console.log(reply.choices[0].message.content);
console.log(reply.usage.cost);
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const (
	address  = "https://opendunes.com/v1/chat/completions"
	model    = "anthropic/claude-sonnet-4.5"
	prompt   = "Summarise this document in two sentences."
	filename = "dummy.pdf"
	pdf      = "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/" +
		"resources/pdf/dummy.pdf"
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	body, err := json.Marshal(map[string]any{
		"model": model,
		"messages": []any{
			map[string]any{
				"role": "user",
				"content": []any{
					map[string]any{"type": "text", "text": prompt},
					map[string]any{
						"type": "file",
						"file": map[string]any{
							"filename":  filename,
							"file_data": pdf,
						},
					},
				},
			},
		},
	})
	if err != nil {
		panic(err)
	}

	request, err := http.NewRequest("POST", address, bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	request.Header.Set("Authorization", "Bearer "+apiKey)
	request.Header.Set("Content-Type", "application/json")

	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	var reply struct {
		Choices []struct {
			Message struct {
				Content string `json:"content"`
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			Cost float64 `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(response.Body).Decode(&reply); err != nil {
		panic(err)
	}
	fmt.Println(reply.Choices[0].Message.Content)
	fmt.Println(reply.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
PROMPT="Summarise this document in two sentences."
FILENAME="dummy.pdf"
PDF="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "type": "text",
            "text": "'"$PROMPT"'"
          },
          {
            "type": "file",
            "file": {
              "filename": "'"$FILENAME"'",
              "file_data": "'"$PDF"'"
            }
          }
        ]
      }
    ]
  }'
```

<div class="do">
<p>Send a link when the PDF is online, a <code>file_id</code> when you keep it in Files and use it often, and a <code>data:</code> URL when it is a file on your side. The whole request stays under 32 MB.</p>
</div>

<div class="dont">
<p>Don't send a <code>file_id</code> that is not yours, or whose file has expired. The request is refused with a 422.</p>
</div>

## 3. Choose how the PDF is read

A PDF can be read by the model itself, or by a parser that turns it into text first. Name the parser in `plugins` when the default is not the one you want.

| You send | The PDF is read by | Charged as |
|---|---|---|
| nothing | the model, if it reads PDFs; otherwise the page-billed parser | the model's input tokens, or the pages |
| `"plugins": [{"id": "file-parser", "pdf": {"engine": "native"}}]` | the model itself | input tokens, beside your words |
| `"plugins": [{"id": "file-parser", "pdf": {"engine": "cloudflare-ai"}}]` | a text parser | no charge for the parsing; the text it finds is input tokens |
| `"plugins": [{"id": "file-parser", "pdf": {"engine": "mistral-ocr"}}]` | an OCR parser, for scans | the pages it reads |

<div class="good-to-know">
<p>A scanned PDF holds pictures of text, not text. Name <code>mistral-ocr</code> for it.</p>
</div>

## 4. Read the answer

The answer is the text in `choices[0].message.content`, as on any text request. `usage.cost` is the whole charge, the parsing included.

To send the answer back as a stream, see [Streaming](/docs/streaming). To hold the answer to a shape, see [Structured outputs](/docs/structured-outputs). Every field of the request: [Chat](/docs/reference/chat-completions).

## Errors

The body says why. What to do on every status: [Errors and retries](/docs/errors-and-retries).

| Status | Means |
|---|---|
| 400 | the model takes no PDFs, and no parser was named for it |
| 402 | the balance cannot cover the request |
| 404 | no such model |
| 413 | the request is larger than the door takes |
| 422 | the `file_id` is not yours, or its file has expired |
