# Files and storage

What is kept of a model's output, and for how long: every file, until you delete it.

1. [Upload a file](#1-upload-a-file).
2. [Use it in a request](#2-use-it-in-a-request).
3. [Find what a model made](#3-find-what-a-model-made).
4. [Delete a file](#4-delete-a-file).

<table class="summary">
<tr><th>What is kept</th><td>every file a key sends or gets back: pictures, clips, songs, speech, uploads</td></tr>
<tr><th>How long</th><td>until you delete it: a kept file never expires</td></tr>
<tr><th>As what</th><td>byte for byte, as it arrived: never resized or re-encoded</td></tr>
<tr><th>What it costs</th><td>nothing, to keep or to fetch</td></tr>
</table>

Text, vectors, transcripts, rerank and classification make no file: their answer is the whole of it.

## 1. Upload a file

[`POST /v1/files`](/docs/reference/files) takes one file, sent as a form, in the field `file`, with your API key. It answers once the file is kept, with its `id`. The sample uploads a small catalogue for Souk Bot, then reads the file's details back.

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

key = os.environ["OPENDUNES_API_KEY"]
base_url = "https://opendunes.com/v1"
file_name = "catalogue.csv"
boundary = "opendunes-upload"

catalogue = (
    "sku,name\n"
    "burnous-01,Burnous en laine\n"
    "tapis-07,Tapis berbère 200 × 300\n"
).encode()
head = (
    f"--{boundary}\r\n"
    'Content-Disposition: form-data; name="file"; '
    f'filename="{file_name}"\r\n'
    "Content-Type: text/csv\r\n\r\n"
).encode()
body = head + catalogue + f"\r\n--{boundary}--\r\n".encode()

upload = urllib.request.Request(
    base_url + "/files",
    data=body,
    headers={
        "Authorization": "Bearer " + key,
        "Content-Type": "multipart/form-data; boundary=" + boundary,
    },
)
with urllib.request.urlopen(upload) as response:
    uploaded = json.load(response)

read = urllib.request.Request(
    base_url + "/files/" + uploaded["id"],
    headers={"Authorization": "Bearer " + key},
)
with urllib.request.urlopen(read) as response:
    details = json.load(response)

print(details["id"], details["filename"], details["downloadable"])
```

```javascript
const key = process.env.OPENDUNES_API_KEY;
const baseURL = "https://opendunes.com/v1";
const fileName = "catalogue.csv";

const catalogue = [
  "sku,name",
  "burnous-01,Burnous en laine",
  "tapis-07,Tapis berbère 200 × 300",
  "",
].join("\n");

const form = new FormData();
form.append("file", new Blob([catalogue], { type: "text/csv" }), fileName);

const upload = await fetch(`${baseURL}/files`, {
  method: "POST",
  headers: { Authorization: `Bearer ${key}` },
  body: form,
});
const uploaded = await upload.json();

const response = await fetch(`${baseURL}/files/${uploaded.id}`, {
  headers: { Authorization: `Bearer ${key}` },
});
const details = await response.json();

console.log(details.id, details.filename, details.downloadable);
```

```go
package main

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

var key = os.Getenv("OPENDUNES_API_KEY")

const baseURL = "https://opendunes.com/v1"
const fileName = "catalogue.csv"

const catalogue = "sku,name\n" +
	"burnous-01,Burnous en laine\n" +
	"tapis-07,Tapis berbère 200 × 300\n"

type File struct {
	ID           string `json:"id"`
	Filename     string `json:"filename"`
	Downloadable bool   `json:"downloadable"`
}

func send(req *http.Request) (File, error) {
	var file File
	req.Header.Set("Authorization", "Bearer "+key)
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		return file, err
	}
	defer res.Body.Close()
	err = json.NewDecoder(res.Body).Decode(&file)
	return file, err
}

func main() {
	var body bytes.Buffer
	form := multipart.NewWriter(&body)
	part, err := form.CreateFormFile("file", fileName)
	if err != nil {
		panic(err)
	}
	part.Write([]byte(catalogue))
	form.Close()

	req, err := http.NewRequest("POST", baseURL+"/files", &body)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", form.FormDataContentType())
	uploaded, err := send(req)
	if err != nil {
		panic(err)
	}

	req, err = http.NewRequest("GET", baseURL+"/files/"+uploaded.ID, nil)
	if err != nil {
		panic(err)
	}
	details, err := send(req)
	if err != nil {
		panic(err)
	}

	fmt.Println(details.ID, details.Filename, details.Downloadable)
}
```

```bash cURL
BASE_URL="https://opendunes.com/v1"
FILE_NAME="catalogue.csv"

printf 'sku,name\nburnous-01,Burnous en laine\n' > "$FILE_NAME"
printf 'tapis-07,Tapis berbère 200 × 300\n' >> "$FILE_NAME"

uploaded=$(curl -s "$BASE_URL/files" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -F "file=@$FILE_NAME")
file=$(echo "$uploaded" | grep -o '"id": *"[^"]*"' | head -1 |
  cut -d '"' -f 4)

curl -s "$BASE_URL/files/$file" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY"
```

| Field | Holds |
|---|---|
| `id` | the file's ID, such as `3f6c2a9e-8b1d-4e7a-9c5f-2d4b6a8e1c07` |
| `filename` | the name it was sent with |
| `mime_type` | what the file is, read from its bytes |
| `size_bytes` | its size |
| `created_at` | when it was kept |
| `downloadable` | `true` once its copy is kept; `false` until then |

An upload is kept whatever the key's storage setting.

## 2. Use it in a request

A kept file goes into a request by its ID, in place of its bytes. In a conversation, it is a content part:

```json
{
  "type": "file",
  "file": {
    "file_id": "3f6c2a9e-8b1d-4e7a-9c5f-2d4b6a8e1c07"
  }
}
```

Each route that reads files says where the ID goes: [Chat](/docs/reference/chat-completions), [Picture generation](/docs/reference/images), [Clips](/docs/reference/videos).

## 3. Find what a model made

Every file a model makes for your key lands in Files, under its own ID, and the answer names it.

| The answer | Carries the ID |
|---|---|
| a picture, a song or a spoken reply inside the answer | `file_id`, beside each file, one per file, in order |
| the file itself as raw bytes, such as speech | the header `X-File-Id` |

A picture, as it comes back, illustrative:

```json
{
  "created": 1758635520,
  "data": [
    {
      "b64_json": "iVBORw0KGgo…",
      "media_type": "image/png",
      "file_id": "3f6c2a9e-8b1d-4e7a-9c5f-2d4b6a8e1c07"
    }
  ]
}
```

A file is listed the moment the answer is delivered. Until its copy is kept, it reads `downloadable: false`; you already hold the bytes the answer carried.

<div class="good-to-know">
<p>Some answers carry an <code>expires_at</code>. It is the provider's clock, for the provider's copy. The copy in Files never expires.</p>
</div>

## 4. Delete a file

`DELETE /v1/files/{id}` deletes the file.

<div class="watch-out">
<p>A delete cannot be undone: no route brings the file back. If you may need it, download it first with <code>GET /v1/files/{id}/content</code>.</p>
</div>

Its charge stays in your history: deleting a file never touches what the request that made it cost.

| You delete | Goes |
|---|---|
| a file, from Files or the *Storage* page | that file |
| a conversation in the chat | every file in it |
| your account | every file, at once |

## Keep nothing on a key

Every key keeps by default. Storage is a setting on the key, like its name and its cap: switch it off, and that key's requests leave nothing behind.

Send `storage` as `false` to `PATCH /v1/keys/{hash}`; the key's hash is in the list of your keys, `GET /v1/keys`.

<div class="watch-out">
<p>The key routes take a management key, never an API key. An API key gets a 401. See <a href="/docs/api-keys">API keys</a>.</p>
</div>

| The key's storage | Sent with a request | Got back | Uploaded to Files |
|---|---|---|---|
| on | kept | kept | kept |
| off | not kept | not kept | kept |

A key with storage off gets no `file_id` in its answers.

<div class="do">
<p>Do switch storage off on a key whose files you keep on your own side. Nothing else about the key changes.</p>
</div>

## The Storage page

*Storage*, in your Home, lists every file your account holds, from the API and from the chat, with the total size. *From* says where each came from: *Chat*, or *API* and the key's name. Download or delete any file there. Nothing on the page is charged.

<div class="watch-out">
<p>A file from the chat never appears in the API's Files. It is listed on the <em>Storage</em> page and in its conversation.</p>
</div>

## Every route

All free, with your API key.

| Route | Does |
|---|---|
| `POST /v1/files` | uploads a file |
| `GET /v1/files` | lists your files |
| `GET /v1/files/{id}` | one file's details |
| `GET /v1/files/{id}/content` | the file's bytes |
| `DELETE /v1/files/{id}` | deletes the file |

## Errors

The body says why.

| Status | When |
|---|---|
| 400 | the request is malformed |
| 401 | the key is missing, wrong, disabled or expired |
| 404 | the file does not exist |
| 413 | the file is too large |

What to do on each: [Errors and retries](/docs/errors-and-retries).
