Usage API - Track AI API Costs Programmatically
Query your AI API usage and costs programmatically. Get detailed breakdowns by model, type, time period. Perfect for AI agents, cost monitoring, budget alerts.
Quick Answer: The Usage API lets you query your SkillBoss usage via API. Get breakdowns by model, type, daily trends, and recent requests. Perfect for AI agents monitoring their own costs.
For AI Agents: This API allows autonomous agents to monitor their own usage and costs without accessing a dashboard.
Quick Start
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage?period=day"
Returns:
{
"summary": {
"total_requests": 142,
"total_usd": 3.54,
"total_credits": 35420
},
"by_model": [...],
"by_type": [...],
"daily": [...]
}
Endpoint
GET https://skillboss.co/api/me/usage
Authentication
Two methods supported:
| Method | Header | Use Case |
|---|---|---|
| Bearer Token | Authorization: Bearer sk-xxx | AI agents, scripts |
| Session Cookie | (automatic) | Browser/dashboard |
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage"
import requests
response = requests.get(
"https://skillboss.co/api/me/usage",
headers={"Authorization": "Bearer sk-xxx"}
)
usage = response.json()
print(f"Total spend: ${usage['summary']['total_usd']}")
const response = await fetch('https://skillboss.co/api/me/usage', {
headers: { 'Authorization': 'Bearer sk-xxx' }
})
const usage = await response.json()
console.log(`Total spend: $${usage.summary.total_usd}`)
Query Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
period | string | month | Time period: day, week, month, or all |
model | string | - | Filter by model name (case-insensitive, supports partial match) |
type | string | - | Filter by type: chat, image, video, audio, scraper, search |
Period Examples
# Today's usage
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage?period=day"
# Last 7 days
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage?period=week"
# Last 30 days (default)
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage?period=month"
# All time
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage?period=all"
Model Filter Examples
# All Claude models
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage?model=claude"
# All GPT models
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage?model=gpt"
# Specific model
curl -H "Authorization: Bearer sk-xxx" \
"https://skillboss.co/api/me/usage?model=claude-4-5-sonnet"
Response Format
{
"period": "month",
"time_range": {
"start": "2025-02-02T00:00:00.000Z",
"end": "2025-03-04T00:00:00.000Z"
},
"summary": {
"total_requests": 1423,
"total_usd": 12.5420,
"total_credits": 125420,
"total_input_tokens": 2500000,
"total_output_tokens": 850000,
"avg_cost_per_request": 0.008815
},
"by_model": [
{
"model": "claude-4-5-sonnet",
"requests": 523,
"usd": 5.2340,
"credits": 52340,
"input_tokens": 1200000,
"output_tokens": 400000,
"avg_latency_ms": 2340
}
],
"by_type": [
{
"type": "chat",
"requests": 1200,
"usd": 10.5000,
"credits": 105000
},
{
"type": "image",
"requests": 150,
"usd": 1.5000,
"credits": 15000
}
],
"daily": [
{
"date": "2025-03-01",
"requests": 89,
"usd": 0.7520
}
],
"hourly": [
{
"hour": "2025-03-04 09:00",
"requests": 15,
"usd": 0.1230
}
],
"recent_requests": [
{
"model": "claude-4-5-sonnet",
"time": 1709550000000,
"usd": 0.0123,
"input_tokens": 1500,
"output_tokens": 500,
"latency_ms": 2100
}
]
}
Response Fields Explained
Summary
| Field | Type | Description |
|---|---|---|
total_requests | number | Total API calls in period |
total_usd | number | Total cost in USD |
total_credits | number | Total credits consumed |
total_input_tokens | number | Total input tokens processed |
total_output_tokens | number | Total output tokens generated |
avg_cost_per_request | number | Average cost per request in USD |
By Model
Breakdown per model, sorted by cost (highest first):
model: Model identifierrequests: Number of callsusd/credits: Costinput_tokens/output_tokens: Token usageavg_latency_ms: Average response time
By Type
Automatic categorization based on model:
| Type | Models Included |
|---|---|
chat | GPT, Claude, Gemini, Llama, DeepSeek |
image | DALL-E, Flux, Stable Diffusion |
video | Veo, MiniMax |
audio | Whisper, ElevenLabs, TTS |
scraper | Firecrawl, LinkedIn scraper |
search | Perplexity, Sonar |
Time Breakdowns
- daily: Per-day totals for the selected period
- hourly: Per-hour totals for the last 24 hours only
Recent Requests
Last 10 API calls with full details including latency metrics.
Use Pages
1. AI Agent Self-Monitoring
AI agents can check their own spending before expensive operations:
class CostAwareAgent:
def __init__(self, api_key, daily_budget=5.0):
self.api_key = api_key
self.daily_budget = daily_budget
def check_budget(self):
"""Check remaining budget before expensive operations"""
response = requests.get(
"https://skillboss.co/api/me/usage?period=day",
headers={"Authorization": f"Bearer {self.api_key}"}
)
usage = response.json()
spent = usage["summary"]["total_usd"]
if spent >= self.daily_budget:
raise Exception(f"Daily budget exceeded: ${spent:.2f}")
remaining = self.daily_budget - spent
print(f"Budget remaining: ${remaining:.2f}")
return remaining
def run_expensive_task(self, task):
remaining = self.check_budget()
if remaining < 1.0:
print("Warning: Low budget, using cheaper model")
return self.run_with_cheap_model(task)
return self.run_with_best_model(task)
2. Cost Analysis & Reporting
Generate spending reports for stakeholders:
def generate_cost_report():
"""Generate monthly cost analysis"""
response = requests.get(
"https://skillboss.co/api/me/usage?period=month",
headers={"Authorization": f"Bearer {API_KEY}"}
)
usage = response.json()
print("=" * 50)
print("MONTHLY AI COST REPORT")
print("=" * 50)
print(f"Total Spend: ${usage['summary']['total_usd']:.2f}")
print(f"Total Requests: {usage['summary']['total_requests']:,}")
print(f"Avg Cost/Request: ${usage['summary']['avg_cost_per_request']:.4f}")
print()
print("TOP 5 MODELS BY COST:")
for i, model in enumerate(usage["by_model"][:5], 1):
pct = (model["usd"] / usage["summary"]["total_usd"]) * 100
print(f" {i}. {model['model']}: ${model['usd']:.2f} ({pct:.1f}%)")
print()
print("BY TYPE:")
for t in usage["by_type"]:
print(f" {t['type']}: ${t['usd']:.2f} ({t['requests']} calls)")
return usage
3. Automated Alerting
Detect unusual spending patterns:
def check_usage_anomaly():
"""Alert if today's usage is abnormally high"""
# Get today's usage
today_resp = requests.get(
"https://skillboss.co/api/me/usage?period=day",
headers={"Authorization": f"Bearer {API_KEY}"}
)
today = today_resp.json()["summary"]["total_usd"]
# Get weekly average
week_resp = requests.get(
"https://skillboss.co/api/me/usage?period=week",
headers={"Authorization": f"Bearer {API_KEY}"}
)
weekly_avg = week_resp.json()["summary"]["total_usd"] / 7
# Alert if 3x normal
if today > weekly_avg * 3:
send_slack_alert(
f"Usage spike detected!\n"
f"Today: ${today:.2f}\n"
f"Normal: ${weekly_avg:.2f}/day\n"
f"Ratio: {today/weekly_avg:.1f}x"
)
return True
return False
4. Model Performance Tracking
Compare model costs and latencies:
def analyze_model_efficiency():
"""Find most cost-effective models"""
response = requests.get(
"https://skillboss.co/api/me/usage?period=week",
headers={"Authorization": f"Bearer {API_KEY}"}
)
models = response.json()["by_model"]
print("MODEL EFFICIENCY ANALYSIS:")
print("-" * 60)
print(f"{'Model':<30} {'$/1K tokens':<15} {'Latency':<10}")
print("-" * 60)
for m in models:
total_tokens = m["input_tokens"] + m["output_tokens"]
if total_tokens > 0:
cost_per_1k = (m["usd"] / total_tokens) * 1000
print(f"{m['model']:<30} ${cost_per_1k:<14.4f} {m['avg_latency_ms']}ms")
Error Handling
| Status Code | Description | Solution |
|---|---|---|
| 401 | Unauthorized | Check API key is valid |
| 500 | Server error | Retry with exponential backoff |
def get_usage_with_retry(max_retries=3):
for attempt in range(max_retries):
try:
response = requests.get(
"https://skillboss.co/api/me/usage",
headers={"Authorization": f"Bearer {API_KEY}"},
timeout=10
)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
if attempt < max_retries - 1:
time.sleep(2 ** attempt)
else:
raise
Rate Limits
This endpoint follows standard SkillBoss rate limits:
| Plan | Requests/min |
|---|---|
| Free | 10 |
| Starter | 60 |
| Pro | Negotiable |
FAQ
Yes! This API is designed for programmatic access. Use Bearer token authentication with your SkillBoss API key.
Usage data is updated in real-time. There may be a few seconds delay for very recent requests.
Credits are SkillBoss's internal unit. 10,000 credits = $1 USD. The API returns both for convenience.
Yes, the JSON response can be easily exported. Use period=all to get complete history.
Use period=all to query your entire usage history since account creation.
Related
API Authentication
Learn about API key management
For AI Agents
Complete guide for autonomous agents
Billing Overview
Understand credits and billing
Cost Optimization
Tips to reduce API costs
Agent-Readable Summary:
{
"endpoint": "GET https://skillboss.co/api/me/usage",
"authentication": "Bearer token",
"parameters": {
"period": ["day", "week", "month", "all"],
"model": "filter by model name",
"type": "filter by type"
},
"returns": {
"summary": "totals (requests, usd, credits, tokens)",
"by_model": "breakdown per model",
"by_type": "breakdown per type (chat/image/video/audio)",
"daily": "per-day breakdown",
"hourly": "last 24h per-hour breakdown",
"recent_requests": "last 10 requests with details"
},
"use_cases": [
"ai_agent_self_monitoring",
"cost_analysis",
"budget_alerts",
"model_comparison"
]
}