API Usage Tracking

These endpoints allow you to monitor, analyze, and manage API consumption on a per-user basis. Each request to endpoints like /chat, /audio-chat, or /tts is automatically logged here.

🔐 Most endpoints require user or admin authentication. Some require admin-only access.


🔸 POST /usage – Manually Log Usage

Typically handled automatically, but can be used manually (e.g., for testing or internal operations).

📥 Request Body:

{
  "api_name": "llm_query",
  "endpoint": "/chat",
  "units_used": 346,
  "cost_usd": 0.0043,
  "api_key_used": "pk_live_abc123"
}

🔐 Auth Required: ✅ Yes

📤 Response:

{
  "usage_id": "uuid",
  "user_id": "uuid",
  "api_name": "llm_query",
  "endpoint": "/chat",
  "units_used": 346,
  "cost_usd": 0.0043,
  "api_key_used": "pk_live_abc123",
  "status_active": true,
  "created_at": "2025-07-04T12:00:00Z"
}

✅ cURL Example:

curl -X POST https://api.yourdomain.com/usage \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "api_name": "llm_query",
    "endpoint": "/chat",
    "units_used": 346,
    "cost_usd": 0.0043,
    "api_key_used": "pk_live_abc123"
  }'

✅ JavaScript (fetch):

await fetch("https://api.yourdomain.com/usage", {
  method: "POST",
  headers: {
    Authorization: "Bearer " + token,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    api_name: "llm_query",
    endpoint: "/chat",
    units_used: 346,
    cost_usd: 0.0043,
    api_key_used: "pk_live_abc123"
  })
});

🔸 GET /usage – Get All Usage Logs

Retrieve all usage logs (supports pagination).

🔐 Auth Required: ✅ Yes Supports query params: skip, limit

✅ cURL:

curl "https://api.yourdomain.com/usage?skip=0&limit=50" \
  -H "Authorization: Bearer <token>"

🔸 GET /usage/user/{user_id} – Get Logs by User

Retrieve usage logs specific to a user.

🔐 Auth Required: ✅ Yes (Admin or Self)

✅ cURL:

curl https://api.yourdomain.com/usage/user/uuid123 \
  -H "Authorization: Bearer <admin_or_user_token>"

🔸 GET /usage/{usage_id} – Get Usage Entry by ID

Returns details for a specific usage record.

✅ cURL:

curl https://api.yourdomain.com/usage/usage-uuid \
  -H "Authorization: Bearer <token>"

🔸 PUT /usage/{usage_id} – Update Usage Record

Used to mark as refunded or adjust billing values.

📥 Request:

{
  "units_used": 0,
  "cost_usd": 0.00
}

✅ cURL:

curl -X PUT https://api.yourdomain.com/usage/usage-uuid \
  -H "Authorization: Bearer <admin_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "units_used": 0,
    "cost_usd": 0.00
  }'

🔸 DELETE /usage/{usage_id} – Delete Usage Record

Deletes a log entry. Recommended for admin use only.

✅ cURL:

curl -X DELETE https://api.yourdomain.com/usage/usage-uuid \
  -H "Authorization: Bearer <admin_token>"

Last updated