API Reference

Complete REST API reference for the AgentKavach backend. All endpoints are prefixed with /v1. Authentication uses Bearer tokens (JWT) in the Authorization header unless noted otherwise. The ingest endpoint authenticates via X-API-Key header.

ℹ️ Base URL

The default base URL for local development is http://localhost:8000. In production, replace with your deployed backend URL.

POST /v1/ingest #

Receive usage events from the SDK. Events are validated, authenticated via API key, and written to the database (directly or via Kafka in production). Enforces subscription status, agent-count limits per tier, and rate limits.

PropertyValue
MethodPOST
Path/v1/ingest
AuthX-API-Key header (API key)
Content-Typeapplication/json

Request Body

ParameterTypeRequiredDefaultDescription
eventsarrayYesArray of event objects to ingest.

Event Object

ParameterTypeRequiredDefaultDescription
agent_namestringYesName of the agent that made the LLM call.
providerstringYesLLM provider (e.g., "openai", "anthropic", "google", "mistral").
modelstringYesModel identifier (e.g., "gpt-4o", "claude-3-opus").
input_tokensintYesNumber of input/prompt tokens. Must be >= 0.
output_tokensintYesNumber of output/completion tokens. Must be >= 0.
costfloatYesComputed cost in USD. Must be >= 0.
timestampstringYesISO 8601 timestamp of the event.
idempotency_keystringNoNoneUnique key for deduplication. Duplicate keys are silently ignored.
promptstringNoNoneThe prompt text (for debugging/audit). Only sent when save_prompts=True is set in the SDK constructor. Off by default for privacy.
duration_msintNo0Duration of the LLM call in milliseconds. Used for duration budgets and dashboard tracking.
run_idstringNoNoneRun identifier to group related events into a single agent run.

Request Example

bash
curl -X POST http://localhost:8000/v1/ingest \
  -H "Content-Type: application/json" \
  -H "X-API-Key: cg_abc123..." \
  -d '{
    "events": [
      {
        "agent_name": "research-bot",
        "provider": "openai",
        "model": "gpt-4o",
        "input_tokens": 1500,
        "output_tokens": 800,
        "cost": 0.035,
        "duration_ms": 1250,
        "timestamp": "2025-01-15T14:30:00Z",
        "run_id": "run_abc123",
        "idempotency_key": "evt_unique_001"
      }
    ]
  }'

Responses

202 Accepted — Events accepted for processing.

json
{
  "accepted": 1,
  "rejected": 0,
  "mode": "direct",
  "rejected_agents": []
}

401 Unauthorized — Invalid or missing API key.

json
{
  "detail": "Invalid API key"
}

403 Forbidden — Subscription cancelled or agent limit exceeded.

json
{
  "detail": "Subscription cancelled. Reactivate to resume ingestion."
}

429 Too Many Requests — Rate limit exceeded or budget exceeded.

json
{
  "detail": "Rate limit exceeded. Daily limit: 10000 events. Resets at 2025-01-16T00:00:00Z"
}

429 Org Budget Exceeded — The organization-wide budget has been exceeded.

json
{
  "detail": "Organization budget exceeded",
  "reason": "org_budget_exceeded",
  "budget_type": "cost",
  "period": "daily",
  "limit": 50.0,
  "current_usage": 52.34
}

Org Budgets #

Organization-level budgets that apply across all agents. All endpoints require Bearer token authentication.

GET /v1/org/budgets

List all org budgets with computed current usage and utilization percentage.

bash
curl http://localhost:8000/v1/org/budgets \
  -H "Authorization: Bearer eyJ..."
json
[
  {
    "id": "budget_abc123",
    "budget_type": "cost",
    "period": "daily",
    "limit_value": 50.0,
    "unit": "USD",
    "current_usage": 23.45,
    "usage_pct": 46.9
  }
]

POST /v1/org/budgets

Create or upsert an org budget. If a budget with the same type and period already exists, it is updated with the new limit value.

ParameterTypeRequiredDefaultDescription
budget_typestringYesBudget type: "cost", "tokens_total", "tokens_input", "tokens_output", "calls", or "duration".
periodstringYesBudget period: "daily", "monthly", or "total".
limit_valuefloatYesBudget limit. Must be > 0.
bash
curl -X POST http://localhost:8000/v1/org/budgets \
  -H "Authorization: Bearer eyJ..." \
  -H "Content-Type: application/json" \
  -d '{"budget_type": "cost", "period": "daily", "limit_value": 50.0}'
json
{
  "id": "budget_abc123",
  "budget_type": "cost",
  "period": "daily",
  "limit_value": 50.0,
  "unit": "USD",
  "current_usage": 0.0,
  "usage_pct": 0.0
}

DELETE /v1/org/budgets/{id}

Delete an org budget. Returns 204 on success, 404 if the budget does not exist.

bash
curl -X DELETE http://localhost:8000/v1/org/budgets/budget_abc123 \
  -H "Authorization: Bearer eyJ..."

Authentication #

POST /v1/auth/register

Create a new organization and user account. No authentication required.

ParameterTypeRequiredDefaultDescription
emailstringYesUser email address.
passwordstringYesUser password.
org_namestringYesOrganization name.
first_namestringNo""User first name.
last_namestringNo""User last name.
bash
curl -X POST http://localhost:8000/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "alice@example.com",
    "password": "securepassword",
    "org_name": "Acme AI",
    "first_name": "Alice",
    "last_name": "Smith"
  }'
json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "bearer",
  "expires_in": 86400
}

POST /v1/auth/login

Authenticate and receive a JWT access token. No authentication required.

ParameterTypeRequiredDefaultDescription
emailstringYesUser email address.
passwordstringYesUser password.
bash
curl -X POST http://localhost:8000/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "alice@example.com",
    "password": "securepassword"
  }'
json
{
  "access_token": "eyJhbGciOiJIUzI1NiIs...",
  "token_type": "bearer",
  "expires_in": 86400
}

GET /v1/auth/me

Return the currently authenticated user profile. Requires Bearer token.

bash
curl http://localhost:8000/v1/auth/me \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
json
{
  "id": "usr_abc123",
  "email": "alice@example.com",
  "first_name": "Alice",
  "last_name": "Smith",
  "role": "owner",
  "org_id": "org_xyz789"
}

Dashboard #

All dashboard endpoints require Bearer token authentication.

GET /v1/dashboard/overview

Returns total spend, budget utilization, event counts, and tier info for the authenticated org. Supports optional start and end query parameters for custom date ranges.

bash
curl http://localhost:8000/v1/dashboard/overview \
  -H "Authorization: Bearer eyJ..."
json
{
  "total_spend_today": 12.45,
  "total_spend_week": 67.23,
  "total_spend_month": 234.56,
  "events_today": 1250,
  "events_week": 8430,
  "events_month": 31200,
  "tier": "pro",
  "active_agents": 5,
  "events_per_day": 50000,
  "max_agents": 25,
  "total_input_tokens": 4500000,
  "total_output_tokens": 1200000,
  "total_duration_ms": 3450000
}

GET /v1/dashboard/spend

Returns time-series spend data for charting. Supports granularity and date range parameters.

ParameterTypeRequiredDefaultDescription
granularitystringNo"hourly"Time bucket size: "hourly" or "daily".
daysintNo7Number of days of history to return.
startstringNoISO 8601 start date for custom range.
endstringNoISO 8601 end date for custom range.
bash
curl "http://localhost:8000/v1/dashboard/spend?granularity=daily&days=7" \
  -H "Authorization: Bearer eyJ..."
json
{
  "granularity": "daily",
  "data": [
    {
      "timestamp": "2025-01-09T00:00:00Z",
      "cost": 32.15,
      "events": 4200,
      "input_tokens": 1500000,
      "output_tokens": 400000
    },
    {
      "timestamp": "2025-01-10T00:00:00Z",
      "cost": 28.90,
      "events": 3800,
      "input_tokens": 1350000,
      "output_tokens": 370000
    }
  ]
}

GET /v1/dashboard/stats

Returns organization-level statistics including top models and agents.

bash
curl http://localhost:8000/v1/dashboard/stats \
  -H "Authorization: Bearer eyJ..."
json
{
  "org_id": "org_xyz789",
  "org_name": "Acme AI",
  "tier": "pro",
  "timezone": "America/New_York",
  "total_events": 31200,
  "total_spend": 234.56,
  "total_agents": 5,
  "top_models": [
    {"model": "gpt-4o", "cost": 150.00, "events": 12000},
    {"model": "claude-3-opus", "cost": 60.00, "events": 8000}
  ],
  "top_agents": [
    {"agent_name": "research-bot", "cost": 120.00, "events": 15000},
    {"agent_name": "code-reviewer", "cost": 80.00, "events": 10000}
  ]
}

Agents #

All agent endpoints require Bearer token authentication.

GET /v1/agents

List all agents for the authenticated org with spend summaries. Supports optional start and end query parameters for custom date ranges.

bash
curl http://localhost:8000/v1/agents \
  -H "Authorization: Bearer eyJ..."
json
{
  "agents": [
    {
      "agent_name": "research-bot",
      "provider": "openai",
      "model": "gpt-4o",
      "total_events": 15000,
      "total_cost": 120.00,
      "last_active": "2025-01-15T14:30:00Z",
      "cost_today": 12.50,
      "cost_week": 45.00,
      "cost_month": 120.00,
      "input_tokens_today": 500000,
      "output_tokens_today": 150000,
      "total_input_tokens": 3000000,
      "total_output_tokens": 800000,
      "total_duration_ms": 1500000,
      "range_events": 1200,
      "range_cost": 25.00,
      "budget_limit_usd": 50.00,
      "budget_used_pct": 25.0,
      "status": "active"
    }
  ]
}

GET /v1/agents/{name}

Get detailed information for a specific agent including spend breakdown, events, and alert history.

bash
curl http://localhost:8000/v1/agents/research-bot \
  -H "Authorization: Bearer eyJ..."
json
{
  "agent_name": "research-bot",
  "provider": "openai",
  "model": "gpt-4o",
  "total_events": 15000,
  "total_cost": 120.00,
  "last_active": "2025-01-15T14:30:00Z",
  "cost_today": 12.50,
  "cost_week": 45.00,
  "cost_month": 120.00,
  "total_duration_ms": 1500000,
  "duration_ms_today": 150000,
  "duration_ms_week": 600000,
  "duration_ms_month": 1500000,
  "budget_limit_usd": 50.00,
  "budget_used_pct": 25.0,
  "status": "active"
}

API Keys #

All API key endpoints require Bearer token authentication.

POST /v1/keys

Create a new API key. The raw key is returned only once and cannot be retrieved later.

ParameterTypeRequiredDefaultDescription
namestringYesHuman-readable name for the key (e.g., "Production", "Staging").
bash
curl -X POST http://localhost:8000/v1/keys \
  -H "Authorization: Bearer eyJ..." \
  -H "Content-Type: application/json" \
  -d '{"name": "Production"}'
json
{
  "id": "key_abc123",
  "name": "Production",
  "prefix": "cg_ab3f8",
  "is_active": true,
  "created_at": "2025-01-15T14:30:00Z",
  "last_used_at": null,
  "raw_key": "cg_ab3f8c9d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7"
}

⚠️ Save your key

The raw_key is only returned once at creation time. Store it securely — you will not be able to retrieve it again.

GET /v1/keys

List all API keys for the authenticated org. The raw key is never returned — only the prefix is shown.

bash
curl http://localhost:8000/v1/keys \
  -H "Authorization: Bearer eyJ..."
json
[
  {
    "id": "key_abc123",
    "name": "Production",
    "prefix": "cg_ab3f8",
    "is_active": true,
    "created_at": "2025-01-15T14:30:00Z",
    "last_used_at": "2025-01-15T16:45:00Z"
  },
  {
    "id": "key_def456",
    "name": "Staging",
    "prefix": "cg_de9c1",
    "is_active": true,
    "created_at": "2025-01-10T09:00:00Z",
    "last_used_at": null
  }
]

DELETE /v1/keys/{id}

Revoke (soft-delete) an API key. The key is marked as inactive and can no longer be used for authentication.

bash
curl -X DELETE http://localhost:8000/v1/keys/key_abc123 \
  -H "Authorization: Bearer eyJ..."
json
{
  "id": "key_abc123",
  "name": "Production",
  "prefix": "cg_ab3f8",
  "is_active": false,
  "created_at": "2025-01-15T14:30:00Z",
  "last_used_at": "2025-01-15T16:45:00Z"
}

POST /v1/keys/{id}/rotate

Rotate an API key — the old key is revoked and a new one is created with the same name. Returns the new raw key (shown only once).

bash
curl -X POST http://localhost:8000/v1/keys/key_abc123/rotate \
  -H "Authorization: Bearer eyJ..."
json
{
  "id": "key_ghi789",
  "name": "Production",
  "prefix": "cg_gh7a2",
  "is_active": true,
  "created_at": "2025-01-15T17:00:00Z",
  "last_used_at": null,
  "raw_key": "cg_gh7a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0"
}

Billing #

All billing endpoints require Bearer token authentication.

GET /v1/billing/plan

Returns the current subscription plan, usage stats, and upgrade eligibility.

bash
curl http://localhost:8000/v1/billing/plan \
  -H "Authorization: Bearer eyJ..."
json
{
  "tier": "pro",
  "tier_display": "Pro",
  "price_monthly": 20.00,
  "events_per_day": 50000,
  "events_today": 1250,
  "spend_today": 12.45,
  "can_upgrade": true,
  "max_agents": 25,
  "active_agents_today": 5,
  "can_downgrade": true,
  "subscription_status": "active",
  "timezone": "America/New_York",
  "trial_ends_at": null,
  "trial_active": false
}

POST /v1/billing/checkout

Create a Stripe checkout session for upgrading or changing the subscription tier.

ParameterTypeRequiredDefaultDescription
target_tierstringYesTarget subscription tier: "pro" or "max".
success_urlstringNohttp://localhost:3000/dashboard/billing?success=trueURL to redirect to after successful checkout.
cancel_urlstringNohttp://localhost:3000/dashboard/billing?canceled=trueURL to redirect to if checkout is cancelled.
bash
curl -X POST http://localhost:8000/v1/billing/checkout \
  -H "Authorization: Bearer eyJ..." \
  -H "Content-Type: application/json" \
  -d '{"target_tier": "pro"}'
json
{
  "checkout_url": "https://checkout.stripe.com/c/pay/cs_test_...",
  "session_id": "cs_test_abc123"
}

POST /v1/billing/portal

Create a Stripe billing portal session for managing payment methods, viewing invoices, and cancelling subscriptions.

bash
curl -X POST http://localhost:8000/v1/billing/portal \
  -H "Authorization: Bearer eyJ..."
json
{
  "portal_url": "https://billing.stripe.com/p/session/test_..."
}

Pricing #

GET /v1/pricing

Returns the current model pricing table. This endpoint is public — no authentication required. The SDK fetches this on initialization and caches it in memory.

bash
curl http://localhost:8000/v1/pricing
json
{
  "gpt-4o": {
    "input_per_1k": 0.005,
    "output_per_1k": 0.015
  },
  "gpt-4o-mini": {
    "input_per_1k": 0.00015,
    "output_per_1k": 0.0006
  },
  "claude-3-opus": {
    "input_per_1k": 0.015,
    "output_per_1k": 0.075
  },
  "claude-3-sonnet": {
    "input_per_1k": 0.003,
    "output_per_1k": 0.015
  },
  "gemini-1.5-pro": {
    "input_per_1k": 0.00125,
    "output_per_1k": 0.005
  }
}

ℹ️ SDK caching

The SDK calls this endpoint once on initialization. If the backend is unreachable, it falls back to its bundled static price table. You do not need to call this endpoint directly.

Error Response Format #

All error responses follow the standard FastAPI format with a detail field:

json
{
  "detail": "Human-readable error message"
}
Status CodeMeaning
400Bad request — invalid input or validation error
401Unauthorized — missing or invalid authentication credentials
403Forbidden — valid auth but insufficient permissions (e.g., cancelled subscription)
404Not found — resource does not exist
409Conflict — duplicate resource (e.g., email already registered)
422Unprocessable entity — request body fails validation
429Too many requests — rate limit exceeded (daily or burst)
500Internal server error