
## Key usage stats

`GET /v1/ai/credentials/:id/usage`

Returns aggregated usage statistics for a specific BYOK key: total request count, token consumption, and a per-model breakdown. The period is configured via a query parameter.

## Parameters

| Parameter | Type | Required | Default | Description |
|----------|-----|:-----:|-----------|----------|
| `id` (path) | string | yes | — | Key ID from [`GET /v1/ai/credentials`](./list.md) |
| `days` (query) | number | no | `30` | Period in days. Valid range: `1..90`. Values outside the range are automatically clamped to the bounds |

## Examples

### curl — personal key

```bash
curl "https://vibecode.bitrix24.com/v1/ai/credentials/cred_abc123def456/usage?days=7" \
  -H "X-Api-Key: YOUR_API_KEY"
```

### curl — OAuth application

```bash
curl "https://vibecode.bitrix24.com/v1/ai/credentials/cred_abc123def456/usage?days=7" \
  -H "X-Api-Key: YOUR_APP_KEY" \
  -H "Authorization: Bearer USER_SESSION_TOKEN"
```

### JavaScript — personal key

```javascript
const id = 'cred_abc123def456'
const res = await fetch(`https://vibecode.bitrix24.com/v1/ai/credentials/${id}/usage?days=7`, {
  headers: { 'X-Api-Key': 'YOUR_API_KEY' },
})

const { data } = await res.json()
console.log(`Over ${data.period.days} days: ${data.requests} requests, ${data.totalTokens} tokens`)
data.byModel.forEach((m) => console.log(`  ${m.modelId}: ${m.calls} requests`))
```

### JavaScript — OAuth application

```javascript
const id = 'cred_abc123def456'
const res = await fetch(`https://vibecode.bitrix24.com/v1/ai/credentials/${id}/usage?days=30`, {
  headers: {
    'X-Api-Key': 'YOUR_APP_KEY',
    'Authorization': 'Bearer USER_SESSION_TOKEN',
  },
})

const { data } = await res.json()
console.log('Completion tokens:', data.completionTokens)
```

## Response fields

| Field | Type | Description |
|------|-----|----------|
| `success` | boolean | Always `true` on success |
| `data.period.days` | number | Actual period in days (after clamping to 1..90) |
| `data.period.since` | string | Start of the period in `ISO 8601` |
| `data.requests` | number | Total number of requests through this key over the period |
| `data.promptTokens` | number | Sum of input tokens |
| `data.completionTokens` | number | Sum of response tokens |
| `data.totalTokens` | number | Sum of all tokens |
| `data.byModel` | array | Breakdown of successful requests by model, sorted by descending call count |
| `data.byModel[].modelId` | string | Model ID |
| `data.byModel[].calls` | number | Number of requests to this model |
| `data.byModel[].promptTokens` | number | Input tokens by model |
| `data.byModel[].completionTokens` | number | Response tokens by model |

## Response example

```json
{
  "success": true,
  "data": {
    "period": {
      "days": 7,
      "since": "2026-04-20T11:30:00.000Z"
    },
    "requests": 142,
    "promptTokens": 45200,
    "completionTokens": 18300,
    "totalTokens": 63500,
    "byModel": [
      {
        "modelId": "openai/gpt-4o-mini",
        "calls": 98,
        "promptTokens": 28000,
        "completionTokens": 11000
      },
      {
        "modelId": "openai/gpt-4o",
        "calls": 44,
        "promptTokens": 17200,
        "completionTokens": 7300
      }
    ]
  }
}
```

## Error response example

`404 not_found` — the key was not found or belongs to another user:

```json
{
  "success": false,
  "error": {
    "code": "not_found",
    "message": "Credential not found"
  }
}
```

## Errors

| HTTP | Code | Description |
|------|-----|----------|
| 404 | `not_found` | A key with this `id` was not found or does not belong to you |
| 403 | `scope_missing` | The API key lacks the `vibe:ai` scope |
| 401 | `MISSING_API_KEY` | The `X-Api-Key` header was not provided |

Full list of common API errors — [Errors](/docs/errors).

## Known specifics

**Only successful calls in `byModel`.** The per-model breakdown counts only records with the `SUCCESS` status. The overall counters (`requests`, `promptTokens`, etc.) include all statuses — successful, failed, partially successful.

**Grouping by `(userId, providerId)`.** Key-level statistics are derived from logs filtered by the combination of "your `userId`" + "the key's `providerId`" + `credentialScope: USER`. If you reconnected a key for the same provider, the older records are included in the new statistics, because they are matched by provider rather than by the key's `id`.

**Difference from [`GET /v1/ai/usage`](/docs/ai/consumption/usage).** This endpoint shows statistics for a single BYOK key only. The general [`/v1/ai/usage`](/docs/ai/consumption/usage) shows all calls made with the current API key, including platform models and PORTAL credentials, not just USER BYOK.

## See also

- [Usage statistics](/docs/ai/consumption/usage)
- [List keys](./list.md)
- [Your own keys (BYOK)](/docs/ai/credentials)
