# Batch status

`GET /v1/batches/{id}` answers where a batch stands and, once it is done, every request's answer
under its `custom_id`.

## Request

Send it with an API key. The one field goes in the address. The [Batches](/docs/batches) guide
runs a batch from start to end.

| Field | Needed | You send |
|---|---|---|
| `id` | yes | the batch's id, as `POST /v1/batches` answered it |

Ask again every few minutes until `status` is `completed`, `failed`, `expired` or `cancelled`.
You read only your own account's batches: any other `id` is a 404. The id in each sample is an
example of the shape; put the one your batch was given in its place.

`GET /v1/batches` lists your batches, newest first, each without its `results`: after `?`, it
takes `limit`, 1 to 100, absent 20; `after`, a batch's `id`, to start after it; and `status`, to
list only batches in that status. `DELETE /v1/batches/{id}`
deletes a batch that has ended; its charge and its receipt stay.

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
BATCH_ID = "0d3f5a8e-6b1c-4e2a-9f7d-2c4b8e1a5f90"
ADDRESS = "https://opendunes.com/v1/batches/" + BATCH_ID

request = urllib.request.Request(
    ADDRESS,
    headers={"Authorization": "Bearer " + API_KEY},
)
with urllib.request.urlopen(request) as response:
    batch = json.load(response)

print(batch["status"], batch["request_counts"])
for result in batch["results"] or []:
    answer = result["response"]["body"]["choices"][0]["message"]["content"]
    print(result["custom_id"], answer)
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const BATCH_ID = "0d3f5a8e-6b1c-4e2a-9f7d-2c4b8e1a5f90";
const ADDRESS = `https://opendunes.com/v1/batches/${BATCH_ID}`;

const response = await fetch(ADDRESS, {
  headers: { Authorization: `Bearer ${API_KEY}` },
});
const batch = await response.json();

console.log(batch.status, batch.request_counts);
for (const result of batch.results ?? []) {
  const answer = result.response.body.choices[0].message.content;
  console.log(result.custom_id, answer);
}
```

```go
package main

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

const (
	batchID = "0d3f5a8e-6b1c-4e2a-9f7d-2c4b8e1a5f90"
	address = "https://opendunes.com/v1/batches/" + batchID
)

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

	req, err := http.NewRequest("GET", address, nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)

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

	var batch struct {
		Status        string         `json:"status"`
		RequestCounts map[string]int `json:"request_counts"`
		Results       []struct {
			CustomID string `json:"custom_id"`
			Response struct {
				Body struct {
					Choices []struct {
						Message struct {
							Content string `json:"content"`
						} `json:"message"`
					} `json:"choices"`
				} `json:"body"`
			} `json:"response"`
		} `json:"results"`
	}
	if err := json.NewDecoder(res.Body).Decode(&batch); err != nil {
		panic(err)
	}

	fmt.Println(batch.Status, batch.RequestCounts)
	for _, result := range batch.Results {
		if choices := result.Response.Body.Choices; len(choices) > 0 {
			fmt.Println(result.CustomID, choices[0].Message.Content)
		}
	}
}
```

```bash cURL
BATCH_ID="0d3f5a8e-6b1c-4e2a-9f7d-2c4b8e1a5f90"
ADDRESS="https://opendunes.com/v1/batches/$BATCH_ID"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY"
```

## Response

`200 OK`.

| Field | Holds |
|---|---|
| `id` | the batch's id |
| `object` | `batch` |
| `endpoint` | the route its requests go to |
| `model` | the model, `lab/model` |
| `completion_window` | `24h` |
| `status` | `validating`, `in_progress` and `finalizing` while it runs, `cancelling` while it stops, then `completed`, `failed`, `expired` or `cancelled` once it has ended |
| `created_at` | when it was taken, in Unix seconds |
| `finalized_at` | when it ended, in Unix seconds; `null` until then |
| `request_counts` | `total`, `completed` and `failed`: how many requests, and how many are done |
| `usage` | once it ends: the tokens counted across every request, and `cost`, the charge in DA |
| `results` | once it has ended: one entry per request; `null` until then |
| `custom_id` | in each entry: the name you gave the request |
| `response` | in each entry: its answer, `status_code` and `body`, the body in the shape of the batch's `endpoint` |
| `error` | in an entry: why that request failed, else `null`. On the batch: why the whole batch failed, with its `code` and `message` |

## What it cost

Free. Asking for a batch is never charged. The batch itself is charged once, when it ends: the
tokens of every request at the rates of the model's batch entry. `usage.cost` shows that charge,
and a failed batch charges nothing.

## Errors

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

| Status | When |
|---|---|
| 401 | the key is missing, wrong, disabled or expired |
| 403 | the key is kept to other addresses |
| 404 | no batch of yours has that `id` |
| 409 | `DELETE` on a batch that has not ended |
| 502 | `DELETE`: the batch service failed; ask again |
| 504 | `DELETE`: the batch service did not answer in time; ask again |
