# Activity export

Write your usage history to a CSV file you keep: one row per day, model and provider, with its spend in DA.

1. [Set your management key](#1-set-your-management-key).
2. [Export the last 30 days](#2-export-the-last-30-days).
3. [Keep a record past 30 days](#3-keep-a-record-past-30-days).

## Before you start

| You need | Where |
|---|---|
| a management key | *Settings*, under *Management keys* |
| Python 3.9+, Node 18+ or Go 1.22+ | your machine |
| `jq`, for the cURL tab | your machine |

## 1. Set your management key

[`GET /v1/activity`](/docs/reference/activity) takes a management key. An API key gets a 401. [API keys](/docs/api-keys) says what each kind of key does.

<div class="buttons">
<a href="/dashboard/settings/management-keys" class="button primary">Management keys</a>
</div>

```bash
export OPENDUNES_MANAGEMENT_KEY="…"
```

## 2. Export the last 30 days

Yacine keeps a file of what his account spends, for his accountant. Each sample appends the rows to `activity.csv` and writes the header on the first run.

| Input | Set to |
|---|---|
| `DAY` | empty: the last 30 days · a day, `YYYY-MM-DD`, in UTC: that day only |
| `FILE` | the file the rows are added to |

```python
import csv
import json
import os
import urllib.request
from datetime import datetime, timezone

MANAGEMENT_KEY = os.environ["OPENDUNES_MANAGEMENT_KEY"]
ADDRESS = "https://opendunes.com/v1/activity"
DAY = os.environ.get("DAY", "")
FILE = "activity.csv"
COLUMNS = [
    "date",
    "model",
    "provider_name",
    "endpoint_id",
    "requests",
    "prompt_tokens",
    "completion_tokens",
    "usage",
]

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

today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
rows = [row for row in rows if row["date"] < today]

new_file = not os.path.exists(FILE)
with open(FILE, "a", newline="") as out:
    writer = csv.DictWriter(out, fieldnames=COLUMNS, extrasaction="ignore")
    if new_file:
        writer.writeheader()
    writer.writerows(rows)

print(len(rows), "rows written to", FILE)
```

```javascript
import { appendFileSync, existsSync } from "node:fs";

const MANAGEMENT_KEY = process.env.OPENDUNES_MANAGEMENT_KEY;
const ADDRESS = "https://opendunes.com/v1/activity";
const DAY = process.env.DAY ?? "";
const FILE = "activity.csv";
const COLUMNS = [
  "date",
  "model",
  "provider_name",
  "endpoint_id",
  "requests",
  "prompt_tokens",
  "completion_tokens",
  "usage",
];

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

const today = new Date().toISOString().slice(0, 10);
const cell = (value) => `"${String(value).replaceAll('"', '""')}"`;
const lines = data
  .filter((row) => row.date < today)
  .map((row) => COLUMNS.map((column) => cell(row[column])).join(","));

if (!existsSync(FILE)) appendFileSync(FILE, COLUMNS.join(",") + "\n");
for (const line of lines) appendFileSync(FILE, line + "\n");

console.log(lines.length, "rows written to", FILE);
```

```go
package main

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"strconv"
	"time"
)

const (
	address = "https://opendunes.com/v1/activity"
	file    = "activity.csv"
)

type row struct {
	Date             string  `json:"date"`
	Model            string  `json:"model"`
	ProviderName     string  `json:"provider_name"`
	EndpointID       string  `json:"endpoint_id"`
	Requests         int     `json:"requests"`
	PromptTokens     int     `json:"prompt_tokens"`
	CompletionTokens int     `json:"completion_tokens"`
	Usage            float64 `json:"usage"`
}

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

	url := address
	if day != "" {
		url += "?date=" + day
	}
	req, err := http.NewRequest("GET", url, 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 []row `json:"data"`
	}
	if err := json.NewDecoder(res.Body).Decode(&body); err != nil {
		panic(err)
	}

	_, missing := os.Stat(file)
	flags := os.O_APPEND | os.O_CREATE | os.O_WRONLY
	out, err := os.OpenFile(file, flags, 0o644)
	if err != nil {
		panic(err)
	}
	defer out.Close()

	w := csv.NewWriter(out)
	if os.IsNotExist(missing) {
		w.Write([]string{"date", "model",
			"provider_name", "endpoint_id", "requests",
			"prompt_tokens", "completion_tokens", "usage"})
	}
	today := time.Now().UTC().Format("2006-01-02")
	written := 0
	for _, r := range body.Data {
		if r.Date >= today {
			continue
		}
		w.Write([]string{
			r.Date, r.Model, r.ProviderName, r.EndpointID,
			strconv.Itoa(r.Requests),
			strconv.Itoa(r.PromptTokens),
			strconv.Itoa(r.CompletionTokens),
			strconv.FormatFloat(r.Usage, 'f', -1, 64),
		})
		written++
	}
	w.Flush()
	if err := w.Error(); err != nil {
		panic(err)
	}
	fmt.Println(written, "rows written to", file)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/activity"
DAY="${DAY:-}"
FILE="activity.csv"
TODAY="$(date -u +%F)"

URL="$ADDRESS"
if [ -n "$DAY" ]; then URL="$ADDRESS?date=$DAY"; fi

if [ ! -f "$FILE" ]; then
  printf '%s,%s\n' "date,model,provider_name,endpoint_id" \
    "requests,prompt_tokens,completion_tokens,usage" > "$FILE"
fi

curl -s "$URL" \
  -H "Authorization: Bearer $OPENDUNES_MANAGEMENT_KEY" |
  jq -r --arg today "$TODAY" '.data[] | select(.date < $today) |
    [.date, .model, .provider_name, .endpoint_id, .requests,
     .prompt_tokens, .completion_tokens, .usage] | @csv' >> "$FILE"
```

Each column is a field of the route, under its own name, and `usage` is the spend in DA. [Usage history](/docs/reference/activity) says what every field holds.

<div class="good-to-know">
<p>The samples leave out today's rows. A day's totals grow until it ends in UTC, so the file keeps finished days only.</p>
</div>

## 3. Keep a record past 30 days

The usage history reaches 30 days back. To keep more, run the export once a day, after midnight UTC, with `DAY` set to yesterday: the file grows by one day each run.

On a Linux server whose clock is set to UTC, one crontab line runs the Python sample, saved as `export.py`, at 00:05:

```text
5 0 * * * cd ~/export && DAY=$(date -u -d yesterday +\%F) python3 export.py
```

<div class="watch-out">
<p>A day exported twice is written twice. Run the first export with <code>DAY</code> empty, then only the daily run.</p>
</div>

Reading your usage history is free: the daily run costs nothing. What each row's requests cost, and how to read one request's charge, is in [Usage accounting](/docs/cookbook/usage-accounting).
