# Batch jobs

`POST /v1/batches` sends many requests to one model at once; the answers come later, at the
model's batch rate, and `GET /v1/batches/{id}` fetches them.

## Request

Send it with an API key, as JSON. The [Batches](/docs/batches) guide runs one from start to
end. Every request in a batch goes to the same route and the same
model, and runs on that model's batch entry, picked for you. A batch never streams. The answer
is `202 Accepted` with the batch's `id`: ask for it with
[Batch status](/docs/reference/batches-id) until it is done.

| Field | Needed | You send |
|---|---|---|
| `endpoint` | yes | the route every request goes to: `/v1/chat/completions`, `/v1/responses`, `/v1/messages` or `/v1/embeddings` |
| `model` | yes | the model, `lab/model`, without `:batch`. A model with no batch entry is refused |
| `requests` | yes | the requests, one or more: each `{"custom_id": ..., "body": {...}}` |
| `custom_id` | yes | in each request: a name of your own, different for every request; its answer comes back under it |
| `body` | yes | in each request: the request, in the shape of `endpoint`. `model` may be left out; if sent, it is the batch's model. No `stream`, no audio or video, and a picture or a file only as a public link, `http` or `https` |
| `completion_window` | no | `24h`, the only window: a batch not done within it ends `expired` |
| `provider` | no | `{"only": [...]}`: the providers that may serve it, and no other setting |

A shop writes the product copy for its catalogue overnight: three products, three requests, one
batch.

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/batches"
MODEL = "anthropic/claude-sonnet-4.5"
ASK = "Write two lines of shop copy for: "

products = {
    "burnous-01": "Burnous en laine, blanc cassé, taille unique",
    "tapis-07": "Tapis berbère 200 × 300, motifs Ouarsenis",
    "theiere-03": "Théière en cuivre martelé, 1 litre",
}

request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(
        {
            "endpoint": "/v1/chat/completions",
            "model": MODEL,
            "requests": [
                {
                    "custom_id": sku,
                    "body": {
                        "messages": [
                            {"role": "user", "content": ASK + name},
                        ]
                    },
                }
                for sku, name in products.items()
            ],
        }
    ).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    batch = json.load(response)

print(batch["id"], batch["status"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/batches";
const MODEL = "anthropic/claude-sonnet-4.5";
const ASK = "Write two lines of shop copy for: ";

const products = {
  "burnous-01": "Burnous en laine, blanc cassé, taille unique",
  "tapis-07": "Tapis berbère 200 × 300, motifs Ouarsenis",
  "theiere-03": "Théière en cuivre martelé, 1 litre",
};

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    endpoint: "/v1/chat/completions",
    model: MODEL,
    requests: Object.entries(products).map(([sku, name]) => ({
      custom_id: sku,
      body: { messages: [{ role: "user", content: ASK + name }] },
    })),
  }),
});
const batch = await response.json();

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

```go
package main

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

const (
	address = "https://opendunes.com/v1/batches"
	model   = "anthropic/claude-sonnet-4.5"
	ask     = "Write two lines of shop copy for: "
)

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

	products := [][2]string{
		{"burnous-01", "Burnous en laine, blanc cassé, taille unique"},
		{"tapis-07", "Tapis berbère 200 × 300, motifs Ouarsenis"},
		{"theiere-03", "Théière en cuivre martelé, 1 litre"},
	}
	requests := []map[string]any{}
	for _, p := range products {
		requests = append(requests, map[string]any{
			"custom_id": p[0],
			"body": map[string]any{
				"messages": []map[string]string{
					{"role": "user", "content": ask + p[1]},
				},
			},
		})
	}
	body, err := json.Marshal(map[string]any{
		"endpoint": "/v1/chat/completions",
		"model":    model,
		"requests": requests,
	})
	if err != nil {
		panic(err)
	}

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

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

	var batch struct {
		ID     string `json:"id"`
		Status string `json:"status"`
	}
	if err := json.NewDecoder(res.Body).Decode(&batch); err != nil {
		panic(err)
	}
	fmt.Println(batch.ID, batch.Status)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/batches"
MODEL="anthropic/claude-sonnet-4.5"
ASK="Write two lines of shop copy for:"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d @- <<JSON
{
  "endpoint": "/v1/chat/completions",
  "model": "$MODEL",
  "requests": [
    {
      "custom_id": "burnous-01",
      "body": {
        "messages": [
          {
            "role": "user",
            "content": "$ASK Burnous en laine, blanc cassé, taille unique"
          }
        ]
      }
    },
    {
      "custom_id": "tapis-07",
      "body": {
        "messages": [
          {
            "role": "user",
            "content": "$ASK Tapis berbère 200 × 300, motifs Ouarsenis"
          }
        ]
      }
    },
    {
      "custom_id": "theiere-03",
      "body": {
        "messages": [
          {
            "role": "user",
            "content": "$ASK Théière en cuivre martelé, 1 litre"
          }
        ]
      }
    }
  ]
}
JSON
```

## Response

`202 Accepted`, once the batch is taken. Nothing has run yet.

| Field | Holds |
|---|---|
| `id` | the batch's id: ask for it with `GET /v1/batches/{id}` |
| `object` | `batch` |
| `endpoint` | the route its requests go to |
| `model` | the model, `lab/model` |
| `completion_window` | `24h` |
| `status` | `validating`: taken, not yet started |
| `created_at` | when it was taken, in Unix seconds |
| `finalized_at` | `null` until it ends |
| `request_counts` | `total`, `completed` and `failed`: how many requests, and how many are done |
| `usage` | `null` until it ends |
| `results` | `null` until it ends |
| `error` | `null`, or why the batch failed |

## What it cost

Nothing when you send it. The batch is charged once, in DA from your balance, when it ends:
the tokens every request used, at the rates of the model's batch entry, which its model page
shows. `usage.cost` on [Batch status](/docs/reference/batches-id) carries the charge.

- **Picks the price**: `model`, always on its batch entry.
- **Moves the count**: every `body`, each counted as the same request sent on its own would be.
- **Changes the answer, never the bill**: `custom_id` and `completion_window`.

Your balance must be above zero to send a batch. A batch that ends with nothing counted charges
nothing, and a failed batch charges nothing. Asking for a batch, listing and deleting are free.

## Errors

`error.code` carries the status, and `error.message` says why.

| Status | When |
|---|---|
| 400 | a needed field is missing, `endpoint` is not one of the four, two requests share a `custom_id`, `provider` holds more than `only`, the model has no batch entry, or a request streams, sends audio or video, names another model, or sends a picture or a file that is not a public link; the message names the request by its `custom_id` |
| 401 | the key is missing, wrong, disabled or expired |
| 402 | your balance is at zero or below, cannot pay the request's hold, or the key's cap is spent; `error.metadata.limit_source` names which, and `deposit_url` or `key_url` says where to lift it. After up to 60 seconds of waiting for money your running requests hold, the 402 carries `Retry-After: 60` |
| 403 | the key is kept to other models or other addresses, a guardrail's budget is spent, or a guardrail blocked the batch |
| 413 | the batch is too large to take in one request |
| 422 | the batch is well formed, but its model or its `custom_id`s break a batch rule; the message says which |
| 429 | the provider is limiting its rate; `Retry-After` says how many seconds to wait |
| 500 | an unexpected error |
| 502 | the batch service is down, or a provider failed |
| 503 | the batch cannot be taken right now; ask again shortly |
| 504 | the provider did not answer in time |
