# `TokenUsage`

The tokens one call to a model used: what it read, what it wrote and what its cache served.

Use it to track what model calls cost. For one number alone, use [`TokenCount`](/docs/types/type-token-count.md).

## Shape

| Field | Type | Required? |
|---|---|---|
| `input` | [`TokenCount`](/docs/types/type-token-count.md) | Yes |
| `output` | [`TokenCount`](/docs/types/type-token-count.md) | Yes |
| `cached` | [`TokenCount`](/docs/types/type-token-count.md) | No |

Write every field when you build one, and give a field that isn't required as `none`.

Its parts keep these rules, and a value that breaks one fails with the rule's name:

- `cached_within_input`: cached <= input, where it is given

## Example

```jadpo
TokenUsage { input: 1200 output: 350 cached: none }
```

## Good to know

- `cached` is `none` where a provider doesn't say. It can't be above `input`.
- `==` tells you whether two are the same. `<` and `list.sort_by` don't take it, so sort by one of its parts instead.

## In JSON

An object of its parts, in a request, a response or `json.write`:

```json
{"input":1200,"output":350,"cached":null}
{"input":1200,"output":350,"cached":800}
{"input":0,"output":0,"cached":0}
```

When you read one, a field that isn't required may be left out, or sent as `null`.

## Details

<details>
<summary>Text form, storage, how it is shown, and operations</summary>

`TokenUsage` is in the group AI, and has been in Jadpo since 0.1.0.

### Text form

It has no single text form, so `text.from` and `text.parse` don't take it.

### How it is stored

It is stored in 3 columns, each named for the field, `_` and its suffix. This is `{"input":1200,"output":350,"cached":800}`:

| Column | Type | Holds |
|---|---|---|
| `<field>_input` | `bigint` | `1200` |
| `<field>_output` | `bigint` | `350` |
| `<field>_cached` | `bigint` | `800` |

### How it is shown to people

`text.format(value, locale:)` shows it to people in their locale.

With `locale: Locale.en_gb`:

| Value | Shown |
|---|---|
| `{"input":1200,"output":350,"cached":null}` | `input 1,200, output 350` |
| `{"input":1200,"output":350,"cached":800}` | `input 1,200, output 350, cached 800` |
| `{"input":0,"output":0,"cached":0}` | `input 0, output 0, cached 0` |

### Operations

It also takes `text.format`, `json.read`, `json.write` and `==`. [How every standard type behaves](/docs/every-standard-type-meets-one-contract.md) says how they work.

</details>
