# Usage accounting

Account for what your requests cost, in DA: request by request, then model by model.

1. [Log the charge of each request](#1-log-the-charge-of-each-request).
2. [Read a receipt again](#2-read-a-receipt-again).
3. [Total a period by model](#3-total-a-period-by-model).
4. [Check against your balance](#4-check-against-your-balance).

## Where each figure is read

| Figure | Read from | Key |
|---|---|---|
| one request's charge, in DA | `usage.cost`, in the answer | API key |
| one request's receipt | [`GET /v1/generation`](/docs/reference/generation), with the answer's `X-Generation-Id` | API key |
| a day's spend, per model and provider, in DA | [`GET /v1/activity`](/docs/reference/activity) | management key |
| your balance, as what came in and what requests spent | [`GET /v1/credits`](/docs/reference/credits) | management key |

The docs name no rate: every figure here is a charge already made. How a request is charged is in [Balance and charges](/docs/balance-and-charges).

## 1. Log the charge of each request

Every answer carries its charge in `usage.cost`, in DA, and its receipt handle in the `X-Generation-Id` header. Yacine logs both for every Souk Bot request, one JSON line each, in `usage.jsonl`.

```python
import json
import os
from datetime import datetime, timezone
from openai import OpenAI

API_KEY = os.environ["OPENDUNES_API_KEY"]
BASE_URL = "https://opendunes.com/v1"
MODEL = "anthropic/claude-sonnet-4.5"
LOG = "usage.jsonl"

client = OpenAI(base_url=BASE_URL, api_key=API_KEY)

raw = client.chat.completions.with_raw_response.create(
    model=MODEL,
    messages=[
        {"role": "user", "content": "Two lines to welcome a shop in Oran."},
    ],
)
reply = raw.parse()

line = {
    "at": datetime.now(timezone.utc).isoformat(),
    "generation_id": raw.headers["X-Generation-Id"],
    "model": reply.model,
    "prompt_tokens": reply.usage.prompt_tokens,
    "completion_tokens": reply.usage.completion_tokens,
    "cost": reply.usage.cost,
}
with open(LOG, "a") as log:
    log.write(json.dumps(line) + "\n")

print(line)
```

```javascript
import { appendFileSync } from "node:fs";
import OpenAI from "openai";

const API_KEY = process.env.OPENDUNES_API_KEY;
const BASE_URL = "https://opendunes.com/v1";
const MODEL = "anthropic/claude-sonnet-4.5";
const LOG = "usage.jsonl";

const client = new OpenAI({ baseURL: BASE_URL, apiKey: API_KEY });

const { data: reply, response } = await client.chat.completions
  .create({
    model: MODEL,
    messages: [
      { role: "user", content: "Two lines to welcome a shop in Oran." },
    ],
  })
  .withResponse();

const line = {
  at: new Date().toISOString(),
  generation_id: response.headers.get("X-Generation-Id"),
  model: reply.model,
  prompt_tokens: reply.usage.prompt_tokens,
  completion_tokens: reply.usage.completion_tokens,
  cost: reply.usage.cost,
};
appendFileSync(LOG, JSON.stringify(line) + "\n");

console.log(line);
```

```go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
)

const (
	baseURL = "https://opendunes.com/v1"
	model   = "anthropic/claude-sonnet-4.5"
	logFile = "usage.jsonl"
)

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

	client := openai.NewClient(
		option.WithBaseURL(baseURL),
		option.WithAPIKey(apiKey),
	)

	params := openai.ChatCompletionNewParams{
		Model: model,
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.UserMessage("Two lines to welcome a shop in Oran."),
		},
	}
	var res *http.Response
	reply, err := client.Chat.Completions.New(
		context.TODO(), params, option.WithResponseInto(&res),
	)
	if err != nil {
		panic(err)
	}

	cost := reply.Usage.JSON.ExtraFields["cost"].Raw()
	line, err := json.Marshal(map[string]any{
		"at":                time.Now().UTC().Format(time.RFC3339),
		"generation_id":     res.Header.Get("X-Generation-Id"),
		"model":             reply.Model,
		"prompt_tokens":     reply.Usage.PromptTokens,
		"completion_tokens": reply.Usage.CompletionTokens,
		"cost":              json.RawMessage(cost),
	})
	if err != nil {
		panic(err)
	}

	flags := os.O_APPEND | os.O_CREATE | os.O_WRONLY
	log, err := os.OpenFile(logFile, flags, 0o644)
	if err != nil {
		panic(err)
	}
	defer log.Close()
	if _, err := log.Write(append(line, '\n')); err != nil {
		panic(err)
	}

	fmt.Println(string(line))
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="anthropic/claude-sonnet-4.5"
LOG="usage.jsonl"

curl -s -D headers.txt -o reply.json "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "Two lines to welcome a shop in Oran."
      }
    ]
  }'

ID="$(grep -i '^x-generation-id:' headers.txt | awk '{print $2}' | tr -d '\r')"
AT="$(date -u +%FT%TZ)"

jq -c --arg id "$ID" --arg at "$AT" '{
    at: $at,
    generation_id: $id,
    model: .model,
    prompt_tokens: .usage.prompt_tokens,
    completion_tokens: .usage.completion_tokens,
    cost: .usage.cost
  }' reply.json | tee -a "$LOG"
```

One line of the log, illustrative:

```json
{
  "at": "2026-09-28T09:14:02+00:00",
  "generation_id": "gen-3bhGkxlo4XFrqiabUM7NDtwDzWwG",
  "model": "anthropic/claude-sonnet-4.5",
  "prompt_tokens": 14,
  "completion_tokens": 38,
  "cost": 0.198288
}
```

`cost` is the charge taken from your balance, in DA, to six decimals: the smallest request never reads as free. Add the lines' `cost` and you have what those requests spent.

<div class="good-to-know">
<p>A streamed answer carries its <code>usage.cost</code> in the closing event: <a href="/docs/streaming">Streaming</a> shows where to read it.</p>
</div>

## 2. Read a receipt again

The `generation_id` in your log opens the request's receipt with `GET /v1/generation`. Its `total_cost` is the charge, in DA, with the model that served the request, its tokens and how long it took. Read it when a line of your log is questioned.

You read only your own account's receipts, with any of its API keys. Reading a receipt is free.

## 3. Total a period by model

For a day or a month, you need no log: `GET /v1/activity` answers what your account spent per day, model and provider, over the last 30 days. It takes a management key: set `OPENDUNES_MANAGEMENT_KEY` to it for this call. An API key gets a 401.

Each sample adds the rows up per model and prints each model's requests and spend, in DA.

```python
import json
import os
import urllib.request
from collections import defaultdict

MANAGEMENT_KEY = os.environ["OPENDUNES_MANAGEMENT_KEY"]
ADDRESS = "https://opendunes.com/v1/activity"

request = urllib.request.Request(
    ADDRESS,
    headers={"Authorization": "Bearer " + MANAGEMENT_KEY},
)
with urllib.request.urlopen(request) as response:
    rows = json.load(response)["data"]

requests = defaultdict(int)
spent = defaultdict(float)
for row in rows:
    requests[row["model"]] += row["requests"]
    spent[row["model"]] += row["usage"]

for model in sorted(spent, key=spent.get, reverse=True):
    print(model, requests[model], "requests", round(spent[model], 6), "DA")
```

```javascript
const MANAGEMENT_KEY = process.env.OPENDUNES_MANAGEMENT_KEY;
const ADDRESS = "https://opendunes.com/v1/activity";

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

const totals = new Map();
for (const row of data) {
  const total = totals.get(row.model) ?? { requests: 0, spent: 0 };
  total.requests += row.requests;
  total.spent += row.usage;
  totals.set(row.model, total);
}

const bySpend = [...totals].sort((a, b) => b[1].spent - a[1].spent);
for (const [model, total] of bySpend) {
  const spent = total.spent.toFixed(6);
  console.log(model, total.requests, "requests", spent, "DA");
}
```

```go
package main

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

const address = "https://opendunes.com/v1/activity"

func main() {
	managementKey := os.Getenv("OPENDUNES_MANAGEMENT_KEY")

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

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

	var body struct {
		Data []struct {
			Model    string  `json:"model"`
			Requests int     `json:"requests"`
			Usage    float64 `json:"usage"`
		} `json:"data"`
	}
	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
		panic(err)
	}

	requests := map[string]int{}
	spent := map[string]float64{}
	for _, row := range body.Data {
		requests[row.Model] += row.Requests
		spent[row.Model] += row.Usage
	}

	models := make([]string, 0, len(spent))
	for m := range spent {
		models = append(models, m)
	}
	sort.Slice(models, func(i, j int) bool {
		return spent[models[i]] > spent[models[j]]
	})
	for _, m := range models {
		fmt.Printf("%s %d requests %.6f DA\n", m, requests[m], spent[m])
	}
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/activity"

curl -s "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_MANAGEMENT_KEY" |
  jq -r '.data | group_by(.model)
    | map({
        model: .[0].model,
        requests: (map(.requests) | add),
        spent: (map(.usage) | add)
      })
    | sort_by(-.spent)[]
    | "\(.model) \(.requests) requests \(.spent) DA"'
```

For one day only, add `?date=` and the day, `YYYY-MM-DD`, in UTC, to the address. To keep the history past 30 days, export it every day: [Activity export](/docs/cookbook/activity-export).

## 4. Check against your balance

`GET /v1/credits` answers two totals, in DA: `total_credits`, every deposit, refund and adjustment, and `total_usage`, everything requests spent. Your balance is the first minus the second.

| Total | Runs from |
|---|---|
| your log's `cost` lines | the first request you logged |
| `GET /v1/activity` | 30 days back, per day |
| `total_usage` | your account's first request |

<div class="watch-out">
<p>Compare two totals over the same span only. <code>total_usage</code> counts every request since the account opened; the usage history counts 30 days.</p>
</div>

In the app, *Activity* lists every charge, one line each, to check a single line by eye.
