Integration Guide for AI Coding Agents

Point your AI coding agent at this page (or /docs/agent) to integrate CodingVibez cost and token tracking. Canonical: https://codingvibez.com/docs/agent

CodingVibez Cost Tracking – Integration Guide for AI Coding Agents

Canonical URL for AI agents: https://codingvibez.com/docs/agent

Integrate the CodingVibez Data Ingest API to track costs and AI token usage from any application. The API is push-based: your app sends JSON to POST /api/ingest; data appears in the user's CodingVibez dashboard. Use this guide to add cost/token tracking to backends, scripts, AI pipelines, or serverless functions.

2. Prerequisites

  • User has a CodingVibez account and belongs to an organization.
  • An API key for the Data Ingest API. Keys are created in the dashboard (API Docs → Authentication) or via POST /api/ingest/generate-key when the user is logged in. The key is shown only once; it must be stored in the application (e.g. env CODINGVIBEZ_API_KEY or INGEST_API_KEY).
  • Keys are org-scoped; the API attributes all ingested data to that organization. No organization_id is sent in ingest requests.

3. Base URL and Authentication

ItemValue
Production basehttps://codingvibez.com
Ingest endpointhttps://codingvibez.com/api/ingest
Generate-key endpointhttps://codingvibez.com/api/ingest/generate-key

All ingest requests require: Authorization: Bearer <API_KEY> and Content-Type: application/json. The generate-key endpoint uses the user's session (cookies), not a Bearer key.

4. Endpoints

4.1 POST /api/ingest (main)

Send cost or token usage. Body: JSON with type, service, data; optional project (default "Production"), product (default "default").

type: "cost"

data required: amount (number, USD), month (1–12), year (4-digit).

Optional: payment_source, breakdown (object), notes, tokens_used, tokens_limit.

type: "tokens"

data required: month, year, tokens_used (number).

Optional: cost (default 0), input_tokens, output_tokens, cached_tokens, billing_start_date, billing_end_date (YYYY-MM-DD).

service (string): AI names such as OpenAI, Anthropic, Google, Mistral, Cohere, Amazon, Bedrock are normalized; any string is accepted.

4.2 POST /api/ingest/generate-key

Creates an API key. Auth: Supabase session (logged-in user). Body: { "keyName": string, "description"?: string }. 200: { success, message, keyName, apiKey, instructions }apiKey is returned only here; user must save it. 400: keyName missing or no org. 401: not logged in.

5. Request and Response Schemas

Cost request (minimal)

{
  "type": "cost",
  "service": "OpenAI",
  "data": { "amount": 125.5, "month": 1, "year": 2026 }
}

Tokens request (minimal)

{
  "type": "tokens",
  "service": "Anthropic",
  "data": { "month": 1, "year": 2026, "tokens_used": 2500000 }
}

Success response (200)

{ "success": true, "message": "Cost data ingested successfully", "recordId": "uuid-or-null" }

Error response (4xx/5xx)

{ "error": "Bad request", "message": "Required: amount (number), month (number), year (number)" }

6. Error Handling and Status Codes

CodeCauseAction
400Missing/invalid type, service, or data; malicious payloadFix payload; avoid injecting user input into JSON
401Missing key, invalid/revoked key, key not linked to orgUser must create a new key in dashboard; ensure org exists
429Rate limited (per IP and per org)Wait Retry-After seconds; retry with backoff; check X-RateLimit-*
500Server errorRetry with exponential backoff

7. Rate Limits and Retries

The API is rate-limited per IP and per organization. On 429, the response includes a Retry-After header (seconds) and body { error, retryAfter }. Implement exponential backoff (e.g. 1s, 2s, 4s) and respect Retry-After when present. For batch ingestion, add a small delay between requests (e.g. 100–200 ms) to avoid hitting limits.

8. Integration Checklist for AI Agents

  1. Obtain API key. If the user does not have one: have them log in at https://codingvibez.com, go to API Docs (or /api-docs) → Authentication, generate a key, and copy it into the app's environment (e.g. CODINGVIBEZ_API_KEY). The agent cannot call generate-key without the user's session.
  2. Configure. Store the key in an environment variable. Never hardcode. Use https://codingvibez.com (or the user's self-hosted URL) as the base.
  3. Send cost data when the app incurs a cost: POST /api/ingest with type: "cost", service, data: { amount, month, year }. Add project if needed (e.g. "Staging").
  4. Send token usage after AI API calls that return usage (e.g. usage.prompt_tokens, usage.completion_tokens): POST /api/ingest with type: "tokens", service (e.g. "OpenAI", "Anthropic"), data: { month, year, tokens_used, cost?, input_tokens?, output_tokens?, cached_tokens? }.
  5. Error handling. On 429: wait Retry-After and retry. On 401: prompt user to check key and org. On 400: fix required fields and ensure payload is valid JSON.

9. Code Examples (Copy-Paste Ready)

cURL – Cost

curl -X POST https://codingvibez.com/api/ingest \
  -H "Authorization: Bearer $CODINGVIBEZ_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type":"cost","service":"OpenAI","data":{"amount":125.5,"month":1,"year":2026}}'

cURL – Tokens

curl -X POST https://codingvibez.com/api/ingest \
  -H "Authorization: Bearer $CODINGVIBEZ_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type":"tokens","service":"Anthropic","data":{"month":1,"year":2026,"tokens_used":2500000,"cost":45.75}}'

JavaScript / Node

const BASE = process.env.CODINGVIBEZ_BASE || "https://codingvibez.com";
const KEY = process.env.CODINGVIBEZ_API_KEY;

async function ingestCost(service, amount, month, year, extra = {}) {
  const res = await fetch(`${BASE}/api/ingest`, {
    method: "POST",
    headers: { "Authorization": `Bearer ${KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ type: "cost", service, data: { amount, month, year, ...extra } }),
  });
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}

async function ingestTokens(service, month, year, tokens_used, extra = {}) {
  const res = await fetch(`${BASE}/api/ingest`, {
    method: "POST",
    headers: { "Authorization": `Bearer ${KEY}`, "Content-Type": "application/json" },
    body: JSON.stringify({ type: "tokens", service, data: { month, year, tokens_used, ...extra } }),
  });
  if (!res.ok) throw new Error(await res.text());
  return res.json();
}

// After an OpenAI completion with usage:
// await ingestTokens("OpenAI", d.getMonth()+1, d.getFullYear(), u.prompt_tokens+u.completion_tokens, { cost: 0.02, input_tokens: u.prompt_tokens, output_tokens: u.completion_tokens });

Python

import os
import requests
from datetime import datetime

BASE = os.getenv("CODINGVIBEZ_BASE", "https://codingvibez.com")
KEY = os.getenv("CODINGVIBEZ_API_KEY")

def ingest_cost(service: str, amount: float, month: int, year: int, **kwargs):
    r = requests.post(f"{BASE}/api/ingest", headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"},
        json={"type": "cost", "service": service, "data": {"amount": amount, "month": month, "year": year, **kwargs}})
    r.raise_for_status()
    return r.json()

def ingest_tokens(service: str, month: int, year: int, tokens_used: int, **kwargs):
    r = requests.post(f"{BASE}/api/ingest", headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"},
        json={"type": "tokens", "service": service, "data": {"month": month, "year": year, "tokens_used": tokens_used, **kwargs}})
    r.raise_for_status()
    return r.json()

# After an AI call with usage: ingest_tokens("OpenAI", now.month, now.year, used, cost=0.02, input_tokens=in_t, output_tokens=out_t)

10. When to Send Data

  • Cost: When a known expense is incurred (e.g. after a bill, end-of-day batch, or on a schedule for estimated costs).
  • Tokens: After each AI completion that returns usage (prompt_tokens, completion_tokens, etc.), or batched every N requests / every M minutes. Include cost if the provider or your pricing gives a USD value; otherwise omit (default 0).

11. SDK

There is no official npm or pip package. The HTTP API and the examples in §9 are the "SDK." Use fetch, axios, requests, or any HTTP client. For interactive key management and more examples, use the dashboard: https://codingvibez.com/api-docs.

12. Quick Reference

ItemValue
Ingest URLPOST https://codingvibez.com/api/ingest
AuthAuthorization: Bearer <KEY>
Cost requiredtype, service, data.{ amount, month, year }
Tokens requiredtype, service, data.{ month, year, tokens_used }
Success200 { success: true, recordId }
Errors400, 401, 429, 500 { error, message? }