Skip to content
AISpendbook

Your app's data

Ingestion API

Send request-level events from any language over HTTPS.

Send events from any language. Use POST https://www.aispendbook.com/api/v1/ingest/events for a single event or /ingest/batch with {"events": [...]} for up to 500, with Authorization: Bearer afk_…. The response reports accepted, duplicate and rejected events.

typescript
// Record AI usage from any Node 18+ backend without slowing requests down.
// recordAiUsage() only puts the event in memory; a timer sends batches in the background,
// retries with backoff, and never throws into your code. Do not await it in the request path.
const SPENDBOOK_URL = "https://www.aispendbook.com/api/v1/ingest/batch";
const BATCH_SIZE = 100; // the API accepts up to 500 events per batch
const FLUSH_MS = 2000;
const MAX_QUEUE = 10_000; // when full, new events are dropped (counted in dropped)
const MAX_ATTEMPTS = 5;

type AiEvent = Record<string, unknown>;
const queue: AiEvent[] = [];
let sending = false;
export const spendbookStats = { sent: 0, dropped: 0, failed: 0 };

export function recordAiUsage(e: {
  requestId: string; model: string; inputTokens: number; outputTokens: number;
  provider?: string; customerId?: string; feature?: string; environment?: string;
  runId?: string; latencyMs?: number; status?: "success" | "error";
}): void {
  if (queue.length >= MAX_QUEUE) { spendbookStats.dropped++; return; }
  queue.push({
    event_id: e.requestId,
    occurred_at: new Date().toISOString(),
    provider: e.provider ?? "anthropic",
    model: e.model,
    input_tokens: e.inputTokens,
    output_tokens: e.outputTokens,
    customer_id: e.customerId,
    feature: e.feature,
    environment: e.environment ?? process.env.SPENDBOOK_ENVIRONMENT,
    run_id: e.runId,
    request_id: e.requestId,
    latency_ms: e.latencyMs,
    status: e.status ?? "success",
  });
  if (queue.length >= BATCH_SIZE) void flushAiUsage();
}

export async function flushAiUsage(): Promise<void> {
  if (sending || queue.length === 0) return;
  sending = true;
  try {
    while (queue.length > 0) {
      const batch = queue.splice(0, BATCH_SIZE);
      if (!(await send(batch))) { spendbookStats.failed += batch.length; break; }
      spendbookStats.sent += batch.length;
    }
  } finally {
    sending = false;
  }
}

async function send(events: AiEvent[]): Promise<boolean> {
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
    try {
      const res = await fetch(SPENDBOOK_URL, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.SPENDBOOK_API_KEY}`, // afk_… ingestion key
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ events }),
        signal: AbortSignal.timeout(10_000),
      });
      if (res.ok) return true;
      if (res.status < 500 && res.status !== 429) return false; // a bad event or key: retrying won't help
    } catch {
      // network error or timeout: retry
    }
    await new Promise((r) => setTimeout(r, Math.min(30_000, 500 * 2 ** attempt)));
  }
  return false;
}

// Event ids make re-sends safe: the API ignores an event id it already has.
setInterval(() => void flushAiUsage(), FLUSH_MS).unref?.();
process.once("beforeExit", () => void flushAiUsage());
curl test
curl -sS -X POST "https://www.aispendbook.com/api/v1/ingest/events" \
  -H "Authorization: Bearer $SPENDBOOK_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "event_id": "test-'"$(date +%s)"'",
    "occurred_at": "'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'",
    "provider": "anthropic",
    "model": "claude-haiku-5-5",
    "input_tokens": 1200,
    "output_tokens": 300,
    "feature": "connection-test"
  }'
FieldTypeDescription
event_id *stringUnique per request; re-sending the same id is a no-op (idempotent).
occurred_at *ISO-8601 timestampWhen the request happened, with a time zone (UTC recommended).
provider *stringanthropic, openai, google, azure_openai, aws_bedrock, …
model *stringModel id as sent to the provider.
input_tokens *integerUncached input tokens.
output_tokens *integerOutput tokens (including reasoning tokens if billed as output).
cache_read_tokensintegerPrompt-cache read tokens.
cache_write_tokensintegerPrompt-cache write tokens.
customer_idstringYour customer or account ID. Powers customer economics.
end_user_idstringIndividual end user (hash it if it's personal data).
featurestringProduct feature that made the call.
categorystringUsage category; otherwise rules / classification apply.
project_idstringYour project or team. Team budgets are scoped by it, so do not put the environment here.
environmentstringDeployment environment, e.g. production or staging.
run_idstringAgent run or job id, to group the calls of one run.
request_idstringProvider request id; used to de-duplicate against provider data.
latency_msintegerEnd-to-end latency.
statusstringsuccess | error | cancelled.
metadataobjectSmall, allow-listed key/values. Never put prompts or secrets here.

project_id is your project or team, and team budgets are scoped by it. Put the deployment environment in environment, not in project_id, and group the calls of one agent run or job with run_id. Usage Explorer can group by environment and run.

provider accepts any lowercase name. Spellings of the same bill are stored under one id: bedrock and aws_bedrock as aws_bedrock, azure as azure_openai, vertex, vertex_ai and gemini as google. Claude on Bedrock and Gemini on Vertex AI are priced at the model maker's list price, and Azure OpenAI at OpenAI's, unless you set a contract rate for that provider. Amazon Nova, Titan, Cohere Embed and Meta Llama on Bedrock have their own Bedrock on-demand price for us-east-1, and Vertex AI text embeddings their own Vertex price. The same spellings are accepted on the ledger read API, filters, pricing, invoices, credits and mappings. Azure deployment names map to a model under Settings, Models. Saving, editing or deleting a contract rate, a percent-off term or a deployment mapping reprices the stored records of that provider and model from the rate's start date (at most the last 400 days); costs the sender supplied and billed amounts never change. An event for a model that has no price sheet and no contract rate is stored without a cost: its requests and tokens are counted, and it adds nothing to spend.

Prompt and completion text is optional. It is stored only when the workspace allows content capture (see Security & telemetry). OpenTelemetry users can send spans instead: see OpenTelemetry traces. For Node.js there is a ready-made client with batching and retries: the Node.js SDK.