# Tags and usage breakdown

> Tag requests with your end user and your own key-value metadata, then break spending down per customer, feature or preset in the dashboard and through the API.

When several products, features or customers share one Lykia company, you want to know who spends what. Projects already split usage per product. Tags go further: you label each request with your end user (or tenant) and with your own key-value pairs, and Lykia adds them up for you.

## Tag a request

Send `user` and `metadata` in the request body:

**cURL**

```bash
curl https://api.getlykia.com/v1/chat/completions \
  -H "Authorization: Bearer $LYKIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "@text",
    "messages": [
      { "role": "user", "content": "Summarize this support ticket in one sentence: the invoice PDF is missing." }
    ],
    "user": "tenant-42",
    "metadata": { "feature": "ticket-summary", "plan": "pro" }
  }'
```

**Python**

```python
import os

from openai import OpenAI

client = OpenAI(base_url="https://api.getlykia.com/v1", api_key=os.environ["LYKIA_API_KEY"])

# user and metadata are stored with the request record and never sent to the provider.
completion = client.chat.completions.create(
    model="@text",
    messages=[{"role": "user", "content": "Summarize this support ticket in one sentence: the invoice PDF is missing."}],
    user="tenant-42",
    metadata={"feature": "ticket-summary", "plan": "pro"},
)
print(completion.id, completion.choices[0].message.content)
```

**TypeScript**

```typescript
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.getlykia.com/v1", apiKey: process.env.LYKIA_API_KEY });

// user and metadata are stored with the request record and never sent to the provider.
const completion = await client.chat.completions.create({
  model: "@text",
  messages: [{ role: "user", content: "Summarize this support ticket in one sentence: the invoice PDF is missing." }],
  user: "tenant-42",
  metadata: { feature: "ticket-summary", plan: "pro" },
});
console.log(completion.id, completion.choices[0].message.content);
```

- `user` (string) — Your end user or tenant id, at most 128 characters. Send a pseudonymous id rather than an email address or a name.
- `metadata` (object) — Up to 16 key-value pairs. Keys are 1 to 64 characters, must not contain `.` and must not start with `$`; values are strings of at most 512 characters. Good keys name a dimension you want to compare: `feature`, `plan`, `region`, `customer`.

Tags are stored with the request record and are **never sent to the provider**, whichever route the request takes. They are stored even when prompt logging is off for the project, since they are measurements, not content. A request whose tags are over the limits gets `400` with the code `invalid_tags`; nothing is trimmed silently. The [JavaScript SDK](https://www.getlykia.com/en/docs/guides/javascript-sdk#request-tags)'s `sanitizeTags()` fits any input to the limits before you send it.

Tags work the same way in [`POST /embeddings`](https://www.getlykia.com/en/docs/api-reference/embeddings). When you call a [preset](https://www.getlykia.com/en/docs/guides/model-presets), the preset name is recorded too, so you can compare `@text` with `@fast` without tagging anything.

## Break usage down in the dashboard

On the **Activity** page, choose what to break the period down by: model, API key, user, preset, or a metadata key you type in (for example `feature`). Each value gets its requests, tokens, spend and share, and the **untagged** row shows the share of requests that carried no value for that dimension, so you can see how much of your traffic is covered.

You can also filter the whole page, and the request log, by one tag at a time: a user, a preset, or one `metadata.key=value` pair. The filters stay in the page address, so you can bookmark or share a filtered view. The breakdown is kept separately from the request records, so it covers periods longer than their retention.

## Read records through the API

[`GET /generations`](https://www.getlykia.com/en/docs/api-reference/generations) lists the project's request records, newest first, filtered by `user`, `preset`, `model`, `metadata.<key>` and time range. Each record has the request's `cost` and `cost_details`, so you can total spending per customer in your own billing:

**cURL**

```bash
curl "https://api.getlykia.com/v1/generations?limit=20&user=tenant-42&metadata.feature=ticket-summary" \
  -H "Authorization: Bearer $LYKIA_API_KEY"
```

**Python**

```python
import os

import requests

params = {"limit": 50, "user": "tenant-42", "metadata.feature": "ticket-summary"}
total = 0.0
while True:
    response = requests.get(
        "https://api.getlykia.com/v1/generations",
        headers={"Authorization": f"Bearer {os.environ['LYKIA_API_KEY']}"},
        params=params,
        timeout=30,
    )
    response.raise_for_status()
    page = response.json()
    total += sum(record["cost"] for record in page["data"])
    if not page["next_cursor"]:
        break
    params["after"] = page["next_cursor"]

print(f"tenant-42 ticket summaries cost {total:.6f} USD")
```

**TypeScript**

```typescript
type Generation = { id: string; cost: number; preset: string | null; user: string | null };
type Page = { data: Generation[]; next_cursor: string | null };

const params = new URLSearchParams({ limit: "50", user: "tenant-42", "metadata.feature": "ticket-summary" });
let total = 0;
for (;;) {
  const response = await fetch(`https://api.getlykia.com/v1/generations?${params}`, {
    headers: { Authorization: `Bearer ${process.env.LYKIA_API_KEY}` },
  });
  if (!response.ok) throw new Error(`Lykia returned ${response.status}: ${await response.text()}`);
  const page = (await response.json()) as Page;
  total += page.data.reduce((sum, record) => sum + record.cost, 0);
  if (!page.next_cursor) break;
  params.set("after", page.next_cursor);
}
console.log(`tenant-42 ticket summaries cost ${total.toFixed(6)} USD`);
```

**Go**

```go
package main

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

type page struct {
	Data []struct {
		ID   string  `json:"id"`
		Cost float64 `json:"cost"`
	} `json:"data"`
	NextCursor *string `json:"next_cursor"`
}

func main() {
	params := url.Values{"limit": {"50"}, "user": {"tenant-42"}, "metadata.feature": {"ticket-summary"}}
	total := 0.0
	for {
		req, err := http.NewRequest(http.MethodGet, "https://api.getlykia.com/v1/generations?"+params.Encode(), nil)
		if err != nil {
			panic(err)
		}
		req.Header.Set("Authorization", "Bearer "+os.Getenv("LYKIA_API_KEY"))

		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			panic(err)
		}
		body, _ := io.ReadAll(resp.Body)
		resp.Body.Close()
		if resp.StatusCode != http.StatusOK {
			panic(fmt.Sprintf("Lykia returned %d: %s", resp.StatusCode, body))
		}

		var p page
		if err := json.Unmarshal(body, &p); err != nil {
			panic(err)
		}
		for _, record := range p.Data {
			total += record.Cost
		}
		if p.NextCursor == nil {
			break
		}
		params.Set("after", *p.NextCursor)
	}
	fmt.Printf("tenant-42 ticket summaries cost %.6f USD\n", total)
}
```

A single record, with the same fields, comes from [`GET /generation`](https://www.getlykia.com/en/docs/api-reference/generation).

## Next steps

- [Projects](https://www.getlykia.com/en/docs/guides/projects): split usage per product with separate keys and budgets.
- [Model presets](https://www.getlykia.com/en/docs/guides/model-presets): name your model choices and compare their cost.
- [Privacy and logging](https://www.getlykia.com/en/docs/guides/privacy-and-logging): what is stored with each request.
