> ## Documentation Index
> Fetch the complete documentation index at: https://docs.perplexity.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Working with Files

> Send documents to the Agent API, continue a conversation about them, and download files produced by the agent.

## Overview

Agent runs can produce files such as CSV, JSON, JSONL, and reports in the sandbox. When code the model runs in the `sandbox` tool writes a file and delivers it with the `share_file` tool, the response `output` array includes a `share_file` item. The file content is not returned inline — retrieve it separately with the response files endpoints, using the response `id`.

## Send a document

Add an `input_file` part to a **user** message on `POST /v1/agent` or its `/v1/responses` alias. Set exactly one of `file_data` and `file_url`. Document inputs go to the model directly; you do not need the `sandbox` or `file_search` tool.

For a local file, set `file_data` to standard base64 or a base64 data URI, such as `data:application/pdf;base64,...`. PDF, DOC, DOCX, UTF-8 TXT, and RTF are recognized, but supported formats and sources depend on the selected model and provider. Known unsupported combinations return HTTP 400 before the response starts, including when `stream=true`.

`filename` is optional. For inline `file_data`, omitting it uses `document` and the recognized extension; a filename without an extension gets that extension automatically. The resulting basename, including any added extension, must be at most 255 UTF-8 bytes. For `file_url`, omit `filename` to use the PDF default, or supply a basename with a supported extension matching the remote document. Conflicting filename extensions or data-URI media types return HTTP 400.

The following HTTP examples read a local `document.pdf`. Set `PERPLEXITY_API_KEY` first. Keep the first response's `id` to ask a follow-up without resending the file. For a fixed JSON response shape, add a [JSON schema output format](https://docs.perplexity.ai/docs/agent-api/output-control.md).

```python Python theme={null}
import base64
import json
import os
from pathlib import Path
from urllib.request import Request, urlopen


def create_response(payload):
    request = Request(
        "https://api.perplexity.ai/v1/agent",
        data=json.dumps(payload).encode(),
        headers={
            "Authorization": f"Bearer {os.environ['PERPLEXITY_API_KEY']}",
            "Content-Type": "application/json",
        },
    )
    with urlopen(request) as response:
        return json.load(response)


first = create_response({
    "model": "openai/gpt-5.4",
    "input": [{"role": "user", "content": [
        {"type": "input_text", "text": "Summarize this document."},
        {"type": "input_file", "filename": "document.pdf",
         "file_data": base64.b64encode(Path("document.pdf").read_bytes()).decode()},
    ]}],
})
follow_up = create_response({
    "model": "openai/gpt-5.4",
    "previous_response_id": first["id"],
    "input": "What are the three most important details?",
})
print(follow_up["output"])
```

```typescript Typescript theme={null}
import { readFile } from 'node:fs/promises';

async function createResponse(payload: Record<string, unknown>) {
  const response = await fetch('https://api.perplexity.ai/v1/agent', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.PERPLEXITY_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  });
  if (!response.ok) throw new Error(await response.text());
  return response.json();
}

const first = await createResponse({
  model: 'openai/gpt-5.4',
  input: [{ role: 'user', content: [
    { type: 'input_text', text: 'Summarize this document.' },
    { type: 'input_file', filename: 'document.pdf',
      file_data: (await readFile('document.pdf')).toString('base64') },
  ] }],
});
const followUp = await createResponse({
  model: 'openai/gpt-5.4',
  previous_response_id: first.id,
  input: 'What are the three most important details?',
});
console.log(followUp.output);
```

```bash cURL theme={null}
base64 < document.pdf | tr -d '\r\n' > document.base64
jq -n --rawfile data document.base64 '{
  model: "openai/gpt-5.4",
  input: [{role: "user", content: [
    {type: "input_text", text: "Summarize this document."},
    {type: "input_file", filename: "document.pdf", file_data: $data}
  ]}]
}' > request.json

curl https://api.perplexity.ai/v1/agent \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @request.json | tee first-response.json | jq

jq -n --arg previous "$(jq -r .id first-response.json)" '{
  model: "openai/gpt-5.4", previous_response_id: $previous,
  input: "What are the three most important details?"
}' > follow-up.json
curl https://api.perplexity.ai/v1/agent \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @follow-up.json | jq
```

### Use a URL

Replace the file part with a public HTTPS URL. URLs cannot contain credentials or fragments and must use port 443. The provider retrieves the document; the API does not download or verify its contents in advance. Without `filename`, URL input is described as PDF. For another supported format, provide a filename with the correct extension. Ensure that this matches the remote document's actual type.

```json theme={null}
{"type": "input_file", "file_url": "https://example.com/document.pdf", "filename": "document.pdf"}
```

The URL must remain accessible for follow-up requests. Provider restrictions on URLs, redirects, formats, size, and page count still apply; an accepted request can fail if the provider cannot retrieve or parse the file.

### Limits and continuation

| Limit | Native Agent API |
| - | - |
| Document parts | 30, including documents inherited by a continuation |
| Inline document bytes | 50 MiB combined after base64 decoding; a single file can use the full budget |
| Complete JSON request body | 72 MiB, including base64, prompts, and other fields |
| Provider limits | Additional size, page, and context limits may be lower |
| Zero data retention | Document inputs are unavailable |
| Browser tools | Unavailable with document inputs or document continuations |
| Reusable upload identifiers | `file_id` is not supported for document input |

These limits differ from Sonar's attachment allowance of 50 MiB **per file**. Video input is not supported by this document contract. Requests that combine documents with browser tools return HTTP 400 before the response starts, including when an effort level enables the browser tool or `previous_response_id` inherits document context.

For inline files, use `previous_response_id` under the same API project to continue without sending the file again. Keep the total active document count and byte size within the limits, and choose a model that supports all inherited documents. Inline documents remain available for the original response's retention period, up to 30 days. A follow-up does not extend that period. If the original response is deleted or expires, resend the document in a new conversation. Input documents are separate from the output-file listing described below.

## Produce a file

Give the agent the `sandbox` tool and ask it to write a file. Here it generates a CSV of the latest AI news. Keep the resulting `response.id` — you use it to list and download the file.

```python Python theme={null}
from perplexity import Perplexity

client = Perplexity()

response = client.responses.create(
    effort="xhigh",
    tools=[{"type": "sandbox"}],
    input=(
        "Find the 10 latest AI news stories and write them to ai_news.csv "
        "with columns: title, source, url, published_date. Deliver the file."
    ),
)

print(response.id, response.status)
```

```typescript Typescript theme={null}
import Perplexity from '@perplexity-ai/perplexity_ai';

const client = new Perplexity();

const response = await client.responses.create({
  effort: 'xhigh',
  tools: [{ type: 'sandbox' }],
  input:
    'Find the 10 latest AI news stories and write them to ai_news.csv ' +
    'with columns: title, source, url, published_date. Deliver the file.',
});

console.log(response.id, response.status);
```

```bash cURL theme={null}
curl https://api.perplexity.ai/v1/agent \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "effort": "xhigh",
    "tools": [{ "type": "sandbox" }],
    "input": "Find the 10 latest AI news stories and write them to ai_news.csv with columns: title, source, url, published_date. Deliver the file."
  }'
```

> [!NOTE]
>
> For runs that take a while, submit with `background=true` and poll before listing files. See [Background mode](https://docs.perplexity.ai/docs/agent-api/background-mode.md).

## List a response's files

`GET /v1/agent/{id}/files`

Use the response `id` from the run above to list the files it produced.

```python Python theme={null}
files = client.responses.files.list(response.id)

for file in files.data:
    print(file.id, file.filename, file.bytes)
```

```typescript Typescript theme={null}
const files = await client.responses.files.list(response.id);

for (const file of files.data) {
  console.log(file.id, file.filename, file.bytes);
}
```

```bash cURL theme={null}
curl https://api.perplexity.ai/v1/agent/$RESPONSE_ID/files \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY"
```

```json theme={null}
{
  "data": [
    {
      "bytes": 8002,
      "created_at": 1780923289,
      "filename": "ai_news.csv",
      "id": "9198548a-490b-4119-858f-fd3676b60319",
      "object": "file"
    }
  ],
  "object": "list"
}
```

| Field | Type | Description |
| - | - | - |
| `id` | `string` | File identifier, used to download; distinct from response id. |
| `filename` | `string` | Name the sandbox gave the file. |
| `bytes` | `integer` | File size in bytes. |
| `created_at` | `integer` | Unix timestamp when created. |
| `object` | `string` | Always `file`. |

## Download a file

`GET /v1/agent/{id}/files/{file_id}/content`

Use the file `id` to download its content. The file `id` is distinct from the response `id`.

> [!NOTE]
>
> This endpoint returns raw file bytes, not JSON. The response includes a `Content-Type` matching the file and a `Content-Disposition: attachment` header carrying the original filename.

```python Python theme={null}
file = files.data[0]

content = client.responses.files.content(
    file_id=file.id,
    response_id=response.id,
)
content.write_to_file(file.filename)
```

```typescript Typescript theme={null}
import { writeFile } from 'node:fs/promises';

const file = files.data[0];

const content = await client.responses.files.content(file.id, {
  response_id: response.id,
});
await writeFile(file.filename, Buffer.from(await content.arrayBuffer()));
```

```bash cURL theme={null}
curl https://api.perplexity.ai/v1/agent/$RESPONSE_ID/files/$FILE_ID/content \
  -H "Authorization: Bearer $PERPLEXITY_API_KEY" \
  -o ai_news.csv
```

## Full example

Create a run that writes a file, then list and download everything it produced.

```python Python theme={null}
from perplexity import Perplexity

client = Perplexity()

response = client.responses.create(
    effort="xhigh",
    tools=[{"type": "sandbox"}],
    input=(
        "Find the 10 latest AI news stories and write them to ai_news.csv "
        "with columns: title, source, url, published_date. Deliver the file."
    ),
)

for file in client.responses.files.list(response.id).data:
    content = client.responses.files.content(
        file_id=file.id,
        response_id=response.id,
    )
    content.write_to_file(file.filename)
    print(f"Downloaded {file.filename} ({file.bytes} bytes)")
```

```typescript Typescript theme={null}
import { writeFile } from 'node:fs/promises';
import Perplexity from '@perplexity-ai/perplexity_ai';

const client = new Perplexity();

const response = await client.responses.create({
  effort: 'xhigh',
  tools: [{ type: 'sandbox' }],
  input:
    'Find the 10 latest AI news stories and write them to ai_news.csv ' +
    'with columns: title, source, url, published_date. Deliver the file.',
});

const files = await client.responses.files.list(response.id);

for (const file of files.data) {
  const content = await client.responses.files.content(file.id, {
    response_id: response.id,
  });
  await writeFile(file.filename, Buffer.from(await content.arrayBuffer()));
  console.log(`Downloaded ${file.filename} (${file.bytes} bytes)`);
}
```

## Next Steps

> [card] [Sandbox](https://docs.perplexity.ai/docs/agent-api/tools/sandbox.md)

> [card] [Background mode](https://docs.perplexity.ai/docs/agent-api/background-mode.md)
