# User Usage Query API Documentation

This document describes the usage query interfaces available to regular users.

> Quota unit note: The system stores quota internally in the smallest unit; the actual amount = quota / quota_per_unit (default 500000, i.e. $1 = 500000 quota).

---

## Table of Contents

- [Authentication Methods](#authentication-methods)
- [Interface List](#interface-list)
  1. [Usage Trend Data (Aggregated by Hour)](#1-usage-trend-data-aggregated-by-hour)
  2. [Consumption Log Details (Paginated)](#2-consumption-log-details-paginated)
  3. [Consumption Statistics Summary](#3-consumption-statistics-summary)
  4. [Token Usage Query (API Key Authentication)](#4-token-usage-query-api-key-authentication)
  5. [Token Log Query (API Key Authentication)](#5-token-log-query-api-key-authentication)
- [Error Response Format](#error-response-format)

---

## Authentication Methods

The user interfaces of this project have two types of authentication: **Access Token** and **API Key**.

### Method 1: Access Token

Applicable interfaces: `/api/data/self`, `/api/log/self`, `/api/log/self/stat`

Users can generate a system access token (Access Token) on the personal settings page. Pass it via the `Authorization` request header:

```
Authorization: your_access_token
```

> Note: The Access Token does **not** carry the `Bearer ` prefix; pass the token value directly.

#### Required Request Headers

**All Access Token interfaces must also carry the `New-Api-User` request header**, whose value is the current user's numeric ID:

```
New-Api-User: 1
```

The user ID can be viewed on the personal settings page, or obtained from the `data.id` field in the login interface response.

#### Complete Request Example

```bash
curl -s 'https://beeroute.ai/api/data/self?start_timestamp=1746460800&end_timestamp=1747065600' \
  -H 'Authorization: your_access_token' \
  -H 'New-Api-User: 1'
```

### Method 2: API Key

Applicable interfaces: `/api/usage/token/`, `/api/log/token`

Use the API Key (`sk-xxx`), passed in the standard Bearer Token format. The `New-Api-User` header is **not required**:

```
Authorization: Bearer sk-xxxxxxxxxxxxxxxx
```

### Authentication Methods Comparison Table

| Authentication Method | Applicable Interfaces | Credential Source | Requires `New-Api-User` Header |
|---------|---------|---------|----------------------|
| Access Token | `/api/data/self`, `/api/log/self`, `/api/log/self/stat` | Generated on the user's personal settings page | Yes |
| API Key (Bearer) | `/api/usage/token/`, `/api/log/token` | The `sk-xxx` created on the token management page | No |

---

## Interface List

## 1. Usage Trend Data (Aggregated by Hour)

Suitable for trend charts and bar charts. Data is grouped and aggregated by **model + hour**.

### Request

```
GET /api/data/self?start_timestamp={start}&end_timestamp={end}
```

### Authentication

[Access Token](#method-1-access-token) + `New-Api-User` header

### Parameters

| Parameter | Type | Required | Description |
|------|------|------|------|
| `start_timestamp` | int64 | No | Start time, Unix seconds |
| `end_timestamp` | int64 | No | End time, Unix seconds |

**Restriction: The time span cannot exceed 1 month (2592000 seconds).**

### Response

```json
{
  "success": true,
  "message": "",
  "data": [
    {
      "id": 0,
      "user_id": 1,
      "username": "user1",
      "model_name": "gpt-4o",
      "created_at": 1715558400,
      "token_used": 23456,
      "count": 42,
      "quota": 180000
    },
    {
      "id": 0,
      "user_id": 1,
      "username": "user1",
      "model_name": "claude-sonnet-4-20250514",
      "created_at": 1715558400,
      "token_used": 10200,
      "count": 15,
      "quota": 95000
    }
  ]
}
```

### Response Fields

| Field | Type | Description |
|------|------|------|
| `model_name` | string | Model name |
| `created_at` | int64 | Timestamp (Unix seconds, accurate to the top of the hour) |
| `count` | int | Number of requests within that hour |
| `quota` | int | Quota consumed within that hour |
| `token_used` | int | Total tokens consumed within that hour (prompt + completion) |

### Request Example

Query the usage trend for the last 7 days (2025-05-06 ~ 2025-05-13):

```bash
curl -s 'https://beeroute.ai/api/data/self?start_timestamp=1746460800&end_timestamp=1747065600' \
  -H 'Authorization: your_access_token' \
  -H 'New-Api-User: 1'
```

### Data Processing Suggestions

- **Aggregate by day**: Sum the `count`/`quota`/`token_used` of each hour within the same day
- **Group by model**: The returned data is naturally distinguished by `model_name`, and can be used directly for multi-series charts
- **Time axis**: `created_at` is an on-the-hour timestamp that can be directly converted to a date-time format

---

## 2. Consumption Log Details (Paginated)

Get the per-request logs of the current user, supporting multi-dimensional filtering and pagination.

### Request

```
GET /api/log/self
```

### Authentication

[Access Token](#method-1-access-token) + `New-Api-User` header

### Parameters

| Parameter | Type | Required | Description |
|------|------|------|------|
| `p` | int | No | Page number, starting from 1, default 1 |
| `page_size` | int | No | Items per page, default 10, max 100 |
| `type` | int | No | Log type: 1=top-up 2=consumption 3=management 4=system 5=error 6=refund, 0=all |
| `start_timestamp` | int64 | No | Start time, Unix seconds |
| `end_timestamp` | int64 | No | End time, Unix seconds |
| `model_name` | string | No | Model name, supports LIKE fuzzy matching (e.g. `gpt-4%`) |
| `token_name` | string | No | Token name, exact match |
| `group` | string | No | Group name, exact match |
| `request_id` | string | No | Request ID, exact match |

### Response

```json
{
  "success": true,
  "data": {
    "page": 1,
    "page_size": 10,
    "total": 256,
    "items": [
      {
        "id": 1,
        "user_id": 1,
        "created_at": 1715590123,
        "type": 2,
        "content": "模型倍率 1.25，分组倍率 1.00",
        "username": "user1",
        "token_name": "my-token",
        "model_name": "gpt-4o",
        "quota": 5000,
        "prompt_tokens": 1200,
        "completion_tokens": 800,
        "use_time": 3,
        "is_stream": true,
        "channel": 0,
        "token_id": 10,
        "group": "default",
        "request_id": "chatcmpl-abc123",
        "other": "{}"
      }
    ]
  }
}
```

### Response Fields (elements of the items array)

| Field | Type | Description |
|------|------|------|
| `id` | int | Log sequence number (within-page index, not the database ID) |
| `user_id` | int | User ID |
| `created_at` | int64 | Request time, Unix seconds |
| `type` | int | Log type |
| `content` | string | Log description (billing notes, etc.) |
| `token_name` | string | The token name used |
| `model_name` | string | The requested model name |
| `quota` | int | Quota consumed |
| `prompt_tokens` | int | Number of prompt tokens |
| `completion_tokens` | int | Number of completion tokens |
| `use_time` | int | Request duration (seconds) |
| `is_stream` | bool | Whether it is a streaming request |
| `group` | string | User group |
| `request_id` | string | Request ID |
| `other` | string | Additional information (JSON string) |

> Note: The user interface does not return `channel_name` (channel name); this field is visible only to administrators.

### Request Example

Query the gpt-4o consumption logs for the last 24 hours, page 1 with 20 items per page:

```bash
START=$(date -d '24 hours ago' +%s)  # Linux
# START=$(date -v-24H +%s)           # macOS

curl -s "https://beeroute.ai/api/log/self?type=2&model_name=gpt-4o&start_timestamp=${START}&p=1&page_size=20" \
  -H 'Authorization: your_access_token' \
  -H 'New-Api-User: 1'
```

---

## 3. Consumption Statistics Summary

Get the total quota consumption and real-time rates (RPM/TPM) under specified conditions.

### Request

```
GET /api/log/self/stat
```

### Authentication

[Access Token](#method-1-access-token) + `New-Api-User` header

### Parameters

| Parameter | Type | Required | Description |
|------|------|------|------|
| `type` | int | No | Log type, default 0 (all) |
| `start_timestamp` | int64 | No | Start time, Unix seconds |
| `end_timestamp` | int64 | No | End time, Unix seconds |
| `model_name` | string | No | Model name, supports LIKE fuzzy matching |
| `token_name` | string | No | Token name |
| `channel` | int | No | Channel ID |
| `group` | string | No | Group name |

### Response

```json
{
  "success": true,
  "message": "",
  "data": {
    "quota": 12500000,
    "rpm": 8,
    "tpm": 4520
  }
}
```

### Response Fields

| Field | Type | Description |
|------|------|------|
| `quota` | int | Total quota consumed within the time range |
| `rpm` | int | Current requests per minute (within the last 60 seconds) |
| `tpm` | int | Current tokens per minute (within the last 60 seconds) |

> Note: `rpm` and `tpm` always count the real-time data of the last 60 seconds and are not affected by `start_timestamp`/`end_timestamp`.

### Request Example

Query the total consumption and real-time rates of the claude-sonnet series of models this month:

```bash
# 00:00:00 on the 1st of this month
START=$(date -d '2025-05-01' +%s)  # Linux
# START=$(date -j -f '%Y-%m-%d' '2025-05-01' +%s)  # macOS

curl -s "https://beeroute.ai/api/log/self/stat?type=2&model_name=claude-sonnet%25&start_timestamp=${START}" \
  -H 'Authorization: your_access_token' \
  -H 'New-Api-User: 1'
```

---

## 4. Token Usage Query (API Key Authentication)

Use the API Key (`sk-xxx`) to query the quota information of that token, without requiring a login session.

### Request

```
GET /api/usage/token/
```

### Authentication

Bearer Token (API Key)

```
Authorization: Bearer sk-xxxxxxxxxxxxxxxx
```

### Parameters

None

### Response

```json
{
  "code": true,
  "message": "ok",
  "data": {
    "object": "token_usage",
    "name": "my-api-key",
    "total_granted": 10000000,
    "total_used": 3500000,
    "total_available": 6500000,
    "unlimited_quota": false,
    "model_limits": {
      "gpt-4o": 5000000,
      "claude-sonnet-4-20250514": 3000000
    },
    "model_limits_enabled": true,
    "expires_at": 1748736000
  }
}
```

### Response Fields

| Field | Type | Description |
|------|------|------|
| `name` | string | Token name |
| `total_granted` | int | Total token quota (used + remaining) |
| `total_used` | int | Quota consumed |
| `total_available` | int | Remaining available quota |
| `unlimited_quota` | bool | Whether it is an unlimited-quota token |
| `model_limits` | object | Independent quota limits for each model (effective when enabled) |
| `model_limits_enabled` | bool | Whether per-model independent quota limits are enabled |
| `expires_at` | int64 | Token expiration time, Unix seconds (0 means never expires) |

### Request Example

```bash
curl -s 'https://beeroute.ai/api/usage/token/' \
  -H 'Authorization: Bearer sk-xxxxxxxxxxxxxxxx'
```

---

## 5. Token Log Query (API Key Authentication)

Use the API Key to query the recent request logs of that token.

### Request

```
GET /api/log/token
```

### Authentication

Bearer Token (API Key, read-only permission)

```
Authorization: Bearer sk-xxxxxxxxxxxxxxxx
```

### Parameters

None (automatically filtered based on the API Key)

### Response

```json
{
  "success": true,
  "message": "",
  "data": [
    {
      "id": 1,
      "user_id": 1,
      "created_at": 1715590123,
      "type": 2,
      "content": "模型倍率 1.25，分组倍率 1.00",
      "username": "user1",
      "token_name": "my-token",
      "model_name": "gpt-4o",
      "quota": 5000,
      "prompt_tokens": 1200,
      "completion_tokens": 800,
      "use_time": 3,
      "is_stream": true,
      "channel": 0,
      "token_id": 10,
      "group": "default",
      "request_id": "chatcmpl-abc123",
      "other": "{}"
    }
  ]
}
```

The returned fields are the same as [Consumption Log Details](#2-consumption-log-details-paginated). The number of returned items is limited by the system configuration (default the most recent 100 items).

### Request Example

```bash
curl -s 'https://beeroute.ai/api/log/token' \
  -H 'Authorization: Bearer sk-xxxxxxxxxxxxxxxx'
```

---

## Error Response Format

All interfaces return a unified format when an error occurs:

```json
{
  "success": false,
  "message": "Error description"
}
```

Common errors:

| Scenario | Status Code | message |
|------|--------|---------|
| Not logged in | 401 | Not logged in or token invalid |
| Time span exceeded (`/api/data/self`) | 200 | Time span cannot exceed 1 month |
| API Key invalid | 401 | Invalid Bearer token |
