# User tracking

Know what each of your apps, customer groups and end users spends, in DA.

1. [Give each group its own key](#1-give-each-group-its-own-key).
2. [Log each end user's charge](#2-log-each-end-users-charge).
3. [Read each key's spend](#3-read-each-keys-spend).

## Two levels

| Level | Told apart by | Spend read from |
|---|---|---|
| an app or a customer group | its own API key | the key: `GET /v1/key`, *Activity* in the app |
| one end user | your own id for them, in your log | your log of `usage.cost` |

## 1. Give each group its own key

Yacine runs Souk Bot for shops on the web and in a phone app. He gives each its own key, named for it: *Souk Bot web*, *Souk Bot mobile*. In the app, *Activity* then shows which key spent what.

<div class="buttons">
<a href="/dashboard/keys" class="button primary">API Keys</a>
</div>

Set a cap on each key, in DA, reset daily, weekly or monthly. A spent cap stops that key with a 402; the other keys run. [API keys](/docs/api-keys) sets out each setting.

<div class="watch-out">
<p>An account holds at most 5 keys, paused keys counted, unless raised. A key tells apart an app or a group, never each of your end users: step 2 does that.</p>
</div>

### From a script

With a management key, `POST /v1/keys` creates a key with its name and cap in one call, and answers its secret once. The body for Souk Bot mobile, capped at 2 000 DA a month, illustrative:

```json
{
  "name": "Souk Bot mobile",
  "limit": 2000,
  "limit_reset": "monthly"
}
```

[Keys](/docs/reference/keys) has the call in four languages.

## 2. Log each end user's charge

Your code knows which of your users sent a request; OpenDunes knows its charge. After each answer, log your user's id beside `usage.cost`, the charge in DA.

The sample sends one question for `CUSTOMER_ID` and adds a line to `spend.jsonl`. Run it with `OPENDUNES_API_KEY` set to the key of that customer's group.

```python
import json
import os
from openai import OpenAI

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

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

reply = client.chat.completions.create(
    model=MODEL,
    messages=[
        {"role": "user", "content": "Is the red jacket still in size M?"},
    ],
)

line = {"customer": CUSTOMER_ID, "cost": reply.usage.cost}
with open(LOG, "a") as log:
    log.write(json.dumps(line) + "\n")

print(reply.choices[0].message.content)
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 CUSTOMER_ID = "customer-4521";
const LOG = "spend.jsonl";

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

const reply = await client.chat.completions.create({
  model: MODEL,
  messages: [
    { role: "user", content: "Is the red jacket still in size M?" },
  ],
});

const line = { customer: CUSTOMER_ID, cost: reply.usage.cost };
appendFileSync(LOG, JSON.stringify(line) + "\n");

console.log(reply.choices[0].message.content);
console.log(line);
```

```go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"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"
	customerID = "customer-4521"
	logFile    = "spend.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("Is the red jacket still in size M?"),
		},
	}
	reply, err := client.Chat.Completions.New(context.TODO(), params)
	if err != nil {
		panic(err)
	}

	cost := reply.Usage.JSON.ExtraFields["cost"].Raw()
	line, err := json.Marshal(map[string]any{
		"customer": customerID,
		"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(reply.Choices[0].Message.Content)
	fmt.Println(string(line))
}
```

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

curl -s "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "Is the red jacket still in size M?"
      }
    ]
  }' |
  jq -c --arg customer "$CUSTOMER_ID" \
    '{customer: $customer, cost: .usage.cost}' | tee -a "$LOG"
```

Each customer's spend, in DA, from the log:

```bash
jq -s 'group_by(.customer)
  | map({customer: .[0].customer, spent: (map(.cost) | add)})' spend.jsonl
```

<div class="dont">
<p>Log a name, an email address or a phone number as the id. The log then holds personal data it has no need of.</p>
</div>

<div class="do">
<p>Log an id of your own that means nothing outside your app. The table from that id to a person stays in your user records.</p>
</div>

To keep the receipt handle, the model and the tokens on each line too, [Usage accounting](/docs/cookbook/usage-accounting) logs them all.

## 3. Read each key's spend

[`GET /v1/key`](/docs/reference/key) answers the key that sends it: what it has spent this UTC day, week and month, and what is left of its cap. Run the sample once per key, with `OPENDUNES_API_KEY` set to it.

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

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/key"

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

print("today:", key["usage_daily"], "this month:", key["usage_monthly"])
print("left of the cap:", key["limit_remaining"])
```

```javascript
const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/key";

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

console.log("today:", data.usage_daily, "this month:", data.usage_monthly);
console.log("left of the cap:", data.limit_remaining);
```

```go
package main

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

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

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 body struct {
		Data struct {
			LimitRemaining *float64 `json:"limit_remaining"`
			UsageDaily     float64  `json:"usage_daily"`
			UsageMonthly   float64  `json:"usage_monthly"`
		} `json:"data"`
	}
	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
		panic(err)
	}
	d := body.Data
	fmt.Println("today:", d.UsageDaily, "this month:", d.UsageMonthly)
	if d.LimitRemaining != nil {
		fmt.Println("left of the cap:", *d.LimitRemaining)
	} else {
		fmt.Println("no cap")
	}
}
```

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

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

`limit_remaining` is `null` on a key with no cap. Reading a key is free.

<div class="good-to-know">
<p>The usage history, <code>GET /v1/activity</code>, counts per day, model and provider, not per key. Per key, read the key itself, or <em>Activity</em> in the app.</p>
</div>

With a management key, [`GET /v1/keys`](/docs/reference/keys) lists every key of your account in one call, each with its `name`, `usage_daily`, `usage_weekly`, `usage_monthly` and `limit_remaining`, in DA.
