In short: your backend reports each user's AI usage with one line of code, and RevenueCat or Stripe reports their plan and what they paid. FiscaLLM then limits AI usage by plan (and tells your app what is left, for the paywall) and shows the margin per user, plan and trial. Setup takes about ten minutes. Curious what happens under the hood? How it works.
Fastest: let your AI coding assistant do it. Otherwise follow the quickstart below.
FISCALLM_KEY.The Setup page shows when the first event and the first webhook arrive, and how many of your AI users it could match to RevenueCat. No RevenueCat? Send revenue with the API.
You can skip the SDK. Step 2 of the quickstart becomes one of these:
https://fiscallm.com/api/v1/otel with Authorization: Bearer <FISCALLM_KEY> and set user.id on your spans.generic_api callback in the proxy config that posts to https://fiscallm.com/api/v1/litellm.Revenue, alerts and the dashboard work the same whichever way usage arrives.
Tracking a team's coding agents instead of an app's users? Claude Code can send its usage straight to https://fiscallm.com/api/v1/otel/v1/logs, for spend per developer and team.
The FiscaLLM setup skill tells a coding assistant how to find your AI calls, add the SDK, pass the RevenueCat user ID through and leave the keys to you. In Claude Code, install it in your project and ask it to "set up FiscaLLM":
mkdir -p .claude/skills/fiscallm-setup && curl -fsSL https://fiscallm.com/skill.md -o .claude/skills/fiscallm-setup/SKILL.mdIn Cursor, Copilot or another assistant, paste:
Read https://fiscallm.com/skill.md and follow it to set up FiscaLLM in this project.What is res? And what do we read from it?
res is the object your AI provider's SDK returned for the call you just made. FiscaLLM reads exactly two things from it: the model name and the token counts (res.usage).
It never reads the answer text, the prompt or any message content, and none of that is sent. Only the model name and the counts leave your backend.
npm install fiscallmZero dependencies. Runs on Node 20+, Cloudflare Workers, Vercel, Supabase Edge Functions (Deno), Bun and Firebase. It never throws, never blocks your response, and sends only token counts: prompts and responses never leave your backend.
import { createMeter } from "fiscallm";
const meter = createMeter({
apiKey: env.FISCALLM_KEY,
waitUntil, // optional, see "Serverless platforms"
});
// userId: the user's RevenueCat app user ID
const res = await openai.chat.completions.create({ model, messages });
meter.trackOpenAI(res, { userId, feature: "chat" });| Call | Pass |
|---|---|
meter.trackOpenAI(res, ctx) | A Chat Completions or Responses API result, from the SDK or await r.json() |
meter.trackAnthropic(res, ctx) | A Messages API result |
meter.trackGemini(res, ctx) | A generateContent result, from @google/genai or REST |
meter.track(event) | Anything else: tokens, or an exact costUsd for images and voice |
ctx is { userId, feature?, provider?, model? }. feature is your own label ("chat", "summary") to break cost down by. For OpenAI-compatible APIs such as Groq, OpenRouter or DeepSeek, use trackOpenAI(res, { userId, provider: "groq" }).
Image and speech models that report tokens (gpt-image-*, gpt-4o-mini-tts, realtime voice, Gemini image, TTS and Live models) work with the helpers above and are priced at their media rates. For usage billed per unit, pass units and a unit of minute, second, character or image; add a variant where the price depends on resolution or size. FiscaLLM prices Whisper and other transcription per minute, tts-1 per character, Veo video per second and Gemini images per image.
meter.track({ userId, provider: "openai", model: "whisper-1", units: 12.5, unit: "minute" });
meter.track({ userId, provider: "openai", model: "tts-1", units: text.length, unit: "character" });
meter.track({ userId, provider: "google", model: "veo-3.1-fast-generate-preview",
units: 8, unit: "second", variant: "1080p" });
meter.track({ userId, provider: "google", model: "gemini-3-pro-image", units: 1, unit: "image", variant: "4k" });
// Anything else: the exact cost, which wins over FiscaLLM's prices
meter.track({ userId, provider: "fal", model: "flux-pro", costUsd: 0.05, feature: "avatar" });Wrap the stream; chunks pass through unchanged and usage is recorded when it ends. OpenAI Chat Completions only reports usage with stream_options: { include_usage: true }.
const stream = meter.trackStream(
await openai.chat.completions.create({
model, messages, stream: true,
stream_options: { include_usage: true },
}),
{ userId },
);
for await (const chunk of stream) { /* ... */ }If your backend proxies a provider's raw server-sent events straight to the app, wrap the response instead:
const upstream = await fetch("https://api.anthropic.com/v1/messages", init);
return meter.trackSSE(upstream, { userId });Events are batched and sent in the background. On serverless platforms, tell the SDK how to keep the function alive until they are sent:
| Cloudflare Workers | createMeter({ apiKey, waitUntil: ctx.waitUntil.bind(ctx) }) |
| Vercel | import { waitUntil } from "@vercel/functions", then pass waitUntil |
| Supabase Edge Functions | waitUntil: (p) => EdgeRuntime.waitUntil(p) |
| Firebase, AWS Lambda | await meter.flush() before returning |
| Long-running Node server | Nothing: events are sent every two seconds |
Each request has a two-second timeout and one retry. If FiscaLLM is unreachable, events are dropped and your app is unaffected.
pip install fiscallmSame helpers and guarantees as the TypeScript SDK, with no dependencies, on Python 3.9+. Tracking only queues; a background thread sends.
import os
from fiscallm import Meter
meter = Meter(api_key=os.environ["FISCALLM_KEY"]) # one per process
res = client.chat.completions.create(model=model, messages=messages)
meter.track_openai(res, user_id=user_id, feature="chat")
# also: track_anthropic, track_gemini, track(...)
# Streams, sync or async: iterate the returned stream
stream = meter.track_stream(response_stream, user_id=user_id)
# AWS Lambda, Cloud Functions: before returning
meter.flush() # or: await meter.aflush()The userId you send must be the user's RevenueCat app user ID. That is how AI cost is joined to revenue.
Purchases.shared.appUserID (iOS), Purchases.sharedInstance.appUserID (Android) or the equivalent from the app to your backend with each request.Users with AI cost but no RevenueCat record appear as "free or unmatched". Free users never reach RevenueCat, so some unmatched cost is expected. A low match rate on the Setup page usually means the IDs differ.
Connect RevenueCat (on fiscallm.com): press the button on your app's Setup page and approve access in RevenueCat. FiscaLLM then adds its webhook to your project and imports your past subscribers. Nothing to copy or paste. It asks for read-only access to customers, subscriptions and purchases, read access to your project list, and permission to manage webhooks (to add its own). Tokens are stored encrypted; Disconnect on the Setup page removes FiscaLLM's webhook and deletes them. If your account has several projects, you pick one. On RevenueCat's approval screen, keep Read & Write. FiscaLLM only ever requests read access to customer data; the write permission is what lets it add its webhook, and with Read only the connection stops and asks you to try again. The webhook covers production and sandbox; sandbox purchases count only while test mode is on (Settings).
Or set it up by hand (and on self-hosted copies, which have no RevenueCat OAuth client):
Revenue is net: price × (1 − tax − store commission), as RevenueCat reports them. Refunds subtract on the day they happen.
RevenueCat sends only new events. Connect RevenueCat imports past subscribers by itself; with the manual setup, use Settings → Import past subscribers: paste your RevenueCat project ID and a v2 secret key with read-only access to customer information and project configuration, and FiscaLLM imports their purchases, renewals and trials from RevenueCat's API. Purchases the webhook already delivered are skipped, so nothing counts twice. App Store and Play Store subscriptions come in renewal by renewal; for other stores (Stripe, Web Billing) RevenueCat only reports each subscription's total, which is counted on its start date. The key is stored encrypted only while the import runs.
If you bill through Stripe, connect it from your app's Setup page: add a Stripe webhook endpoint with the URL shown there, choose invoice.paid, customer.subscription.created, customer.subscription.updated, customer.subscription.deleted, charge.refunded and charge.dispute.closed, then paste the endpoint's signing secret. Requests are verified with Stripe's signature, and the secret is stored encrypted.
metadata.user_id (or fiscallm_user_id) on the Stripe subscription or customer to the same user ID your backend sends with each AI call. Without it, the Stripe customer ID (cus_…) is used, so send that as the userId instead.The webhook sees only new events. To include the last 12 months, create a Stripe restricted key with Read access to Invoices, Charges and Refunds, and Subscriptions, and paste it under Setup → Import the last 12 months. FiscaLLM imports paid invoices, refunds, current trials and ended subscriptions through the same rules as the webhook. The key is used for that import only and is never stored; you can delete it in Stripe once the numbers appear. An invoice is counted once whether it came from the webhook or the import, so running the import again is safe.
If your app does not use RevenueCat, or some payments go through another system (Stripe on the web, your own App Store server notifications), send them yourself. They count exactly like RevenueCat events. Use one source per payment: sending the same payment from RevenueCat and the API counts it twice.
meter.trackRevenue({
id: invoice.id, // unique; retries are ignored
userId, // same id you pass to trackOpenAI
type: "renewal", // trial_started | purchase | renewal | refund | cancellation | expiration
productId: "pro_monthly",
amountUsd: 9.99, // gross, USD; required for purchase, renewal, refund
feePct: 0.15, taxPct: 0.1, // or netUsd: 7.49
periodEnd: subscription.current_period_end,
isTrialConversion: true, // first paid period after a trial
});
# Python
meter.track_revenue(id=invoice.id, user_id=user_id, type="purchase",
amount_usd=9.99, net_usd=7.49, period_end=period_end)Or POST https://fiscallm.com/api/v1/revenue with { "events": [ … ] } and the same fields, using your ingest key. Use oneTime: true for lifetime or credit purchases, and amountUsd as a positive number for refunds.
For payments that never went through a webhook (an export from Stripe, Paddle, Lemon Squeezy, or a spreadsheet), upload a CSV on the Setup page. One row per event, with the same fields as the revenue API:
id,user_id,type,ts,amount_usd,net_usd,product_id,period_end
in_001,user_42,purchase,2026-10-01,20,17.12,pro_monthly,2026-11-01
in_002,user_42,renewal,2026-11-01,20,17.12,pro_monthly,2026-12-01
re_001,user_7,refund,2026-10-12,20,20,pro_monthly,Required: id, user_id, type, ts (a date or ISO time), and amount_usd for purchases, renewals and refunds. Optional: net_usd, tax_pct, fee_pct, product_id, period_end, is_trial_conversion, one_time. Common names such as customer, date and amount are understood too. Up to about 5,000 rows per file; rows with a problem are skipped and listed by line number, and uploading the same rows again does not count them twice.
Cost is calculated on our side from the providers' public list prices, including cached tokens, cache writes and long-prompt pricing, and the price that applied on the day of each call. If you pay less, add a discount for a provider or your own prices for a model under Settings → Your AI prices. Models without a price are listed there too; their cost counts as zero until you add one or send costUsd.
The same table ships in the TypeScript SDK (0.7.0 and later) for your own code, with no network call:
import { estimateCost, priceOf } from "fiscallm/prices";
priceOf("gpt-4o"); // { provider: "openai", input: 2.5, cached: 1.25, output: 10, … } USD per 1M tokens
estimateCost({ model: "claude-sonnet-4-5", inputTokens: 12_000, outputTokens: 800 })?.costUsd;It is as current as the package version you installed. For prices that are always current, use the pricing API.
In Settings → Budgets and alerts, get an email, a Slack message or a webhook when a user's AI cost passes a budget (today or over 30 days), a user uses more tokens in 5 minutes than you allow (a runaway loop), a paying user loses you more than a set amount, AI cost passes a share of revenue, the app's daily spend passes a limit, or a model without a price appears. Per-user budgets and the 5-minute limit are checked within seconds of usage arriving; the others once a day. Each alert fires at most once per user (or app) per day.
Slack: create an incoming webhook in Slack (Apps → Incoming Webhooks), and paste its URL (https://hooks.slack.com/services/…) as the alert's webhook. FiscaLLM then posts a plain message with a link to the dashboard. "Send test" shows how it looks.
Other webhooks are a signed JSON POST your backend can act on, for example to slow down or pause a user over budget:
POST <your URL>
X-FiscaLLM-Signature: t=1792200000,v1=5f2c…
{
"type": "alert.user_daily_cost",
"appId": "…", "ruleId": "…",
"userId": "rc-app-user-id",
"value": 6.12, "threshold": 5,
"period": "2026-10-17",
"message": "User rc-app-user-id spent $6.12 on AI today (budget $5.00)."
}Verify it with the signing secret shown in Settings: v1 is the hex HMAC-SHA256 of `${t}.${rawBody}`.
// TypeScript (Node)
import { createHmac, timingSafeEqual } from "node:crypto";
function verify(rawBody: string, header: string, secret: string) {
const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;
return fresh && timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
}
# Python
import hmac, hashlib, time
def verify(raw_body: bytes, header: str, secret: str) -> bool:
parts = dict(p.split("=", 1) for p in header.split(","))
expected = hmac.new(secret.encode(), f"{parts['t']}.".encode() + raw_body, hashlib.sha256).hexdigest()
return abs(time.time() - int(parts["t"])) < 300 and hmac.compare_digest(expected, parts["v1"])Give each plan its own AI allowance: 20 calls a day on free, 500 a month on Pro, $5 of AI a month on any paid plan. FiscaLLM knows each user's plan from RevenueCat or Stripe, counts their AI calls and cost, and tells your backend whether to allow the next call and how much is left. You keep no quota table and no reset job. Full guide: AI usage limits per subscription plan.
const { allow, plan, limits } = await meter.check(userId);
if (!allow) return respond(402, { paywall: true, plan, resetsAt: limits[0]?.resetsAt });
const reply = await openai.chat.completions.create({ ... });
meter.trackOpenAI(reply, { userId });
return { reply, remaining: limits[0]?.remaining }; // show "3 left today" in the app
# Python
r = meter.check(user_id) # await meter.acheck(user_id) in async code
if not r.allow:
return paywall(r.plan, r.limits[0].resets_at)| Plan name | Who it covers |
|---|---|
free | Anyone without an active purchase, including users whose subscription ended |
trial | Users in a free trial. Without a trial limit they get their product's limits |
paid | Every paying user, including one who cancelled but still has time left |
| A product ID | Users on that product, for example pro_yearly. Overrides paid for them |
resetsAt says when the count starts again. "In total" never resets, for "5 free tries, then subscribe".meter.check(userId, { plan: "team" }) (plan="team" in Python) and add a limit for team.Without the SDK:
POST https://fiscallm.com/api/v1/check
Authorization: Bearer fsk_…
{ "userId": "rc-app-user-id" } // optional: "plan": "team"
200 { "allow": false, "reason": "free plan limit reached (20 of 20 AI calls today)",
"plan": "free", "productId": null, "limitsFrom": "free",
"limits": [{ "period": "day", "unit": "requests", "limit": 20, "used": 20,
"remaining": 0, "resetsAt": "2026-11-12T00:00:00.000Z" }],
"spentToday": 0.21, "spent30d": 1.9, "dailyLimit": null, "monthlyLimit": null }Alerts tell you; caps let your backend say no. When you add a daily or 30-day per-user budget in Settings, tick Block. Your backend then asks FiscaLLM before each AI call, and refuses the user (or switches to a cheaper model) once they reach the amount:
const { allow, reason } = await meter.check(userId);
if (!allow) return respond(429, "You have reached today's AI limit");
// or keep them going on a cheaper model instead of refusing
const model = allow ? "gpt-5" : "gpt-5-mini";
# Python
r = meter.check(user_id) # await meter.acheck(user_id) in async code
if not r.allow:
return refuse(r.reason)checkOnError: "deny" (check_on_error="deny" in Python) to refuse instead. The result's source says which case applied.check refuses past the limit, so a runaway loop is stopped even while FiscaLLM is unreachable:createMeter({ apiKey, localLimit: { requests: 60, tokens: 500_000, windowSeconds: 300 } })
# Python
Meter(api_key, local_limit=LocalLimit(requests=60, tokens=500_000, window_seconds=300))It counts only calls tracked by this process, so with several servers each one enforces it separately. costUsd counts only events tracked with an exact cost.check always allows.Without the SDK:
POST https://fiscallm.com/api/v1/check
Authorization: Bearer fsk_…
{ "userId": "rc-app-user-id" }
200 { "allow": false, "reason": "daily AI budget reached ($6.12 of $5.00)",
"spentToday": 6.12, "spent30d": 26.4, "dailyLimit": 5, "monthlyLimit": null }For apps that charge per job (credits for a video render, an image, a report): tag the job's AI calls with your job id, and report what happened to the user's payment. The Jobs page then shows the AI cost of jobs you refunded, and of jobs that never resolved, per user.
meter.trackJob({ jobId, userId, status: "pending" }); // credits held, job started
meter.track({ userId, provider: "fal", model: "veo-3", units: 15, unit: "second", jobId });
meter.trackJob({ jobId, userId, status: "captured" }); // clip stored, credits taken
// or, on a definite failure:
meter.trackJob({ jobId, userId, status: "refunded" }); // credits returned
# Python
meter.track(user_id=user_id, provider="fal", model="veo-3", units=15, unit="second", job_id=job_id)
meter.track_job(job_id=job_id, user_id=user_id, status="refunded")jobId also works on trackOpenAI, trackStream and the other helpers (job_id in Python).pending never reopens a job that was captured or refunded, so retries and out-of-order deliveries are safe.// The render failed; the user gets their credits back, but the provider billed it.
meter.track({ userId, provider: "fal", model: "veo-3", units: 15, unit: "second", jobId });
// or, if you know the exact charge:
meter.track({ userId, provider: "fal", model: "veo-3", costUsd: 0.75, jobId });
meter.trackJob({ jobId, userId, status: "refunded" });POST /api/v1/jobs { "jobs": [{ "jobId", "userId", "status", "ts"? }] }, up to 100 per request.For backends not written in TypeScript, send events directly:
POST https://fiscallm.com/api/v1/events
Authorization: Bearer <FISCALLM_KEY>
Content-Type: application/json
{
"events": [{
"id": "9b2c6f0e-3f7c-4d8a-9a51-2f0a4f1c7e21", // a UUID you generate; retries reuse it
"userId": "rc-app-user-id",
"ts": "2026-10-17T12:00:00Z",
"provider": "openai",
"model": "gpt-5-mini",
"inputTokens": 1200, // excluding cache reads and writes
"outputTokens": 300,
"cachedTokens": 0,
"cacheWriteTokens": 0,
"units": 12.5, // optional, with "unit": "minute" | "second" | "character" | "image"
"costUsd": 0.0012, // optional: overrides our price
"feature": "chat" // optional
}]
}Up to 100 events per request. The response is 202 with { accepted, duplicates, unpriced }. Events with anid already received are counted as duplicates and ignored, so retrying is safe. Timestamps may be up to 90 days old.
The dashboard's numbers as JSON, for scripts, internal tools and AI agents. Send the same key. Each takes ?days= (1 to 365, default 30).
GET https://fiscallm.com/api/v1/metrics/overview cost, revenue, margin, AI's share of revenue, daily series
GET https://fiscallm.com/api/v1/metrics/users per user, worst margin first (&limit=50, &losing=1 for only users losing money)
GET https://fiscallm.com/api/v1/metrics/plans per plan or product
GET https://fiscallm.com/api/v1/metrics/breakdown cost by model and by feature
Authorization: Bearer <FISCALLM_KEY>curl -H "Authorization: Bearer $FISCALLM_KEY" "https://fiscallm.com/api/v1/metrics/users?days=30&losing=1"AI assistants can read the same numbers through the MCP server. Model prices and cost estimates are a separate public API that needs no key. Everything is described in openapi.json.
To turn reporting off without a deploy, set FISCALLM_DISABLED=1 in your environment, or pass disabled: true (TypeScript) or disabled=True (Python) when you create the meter. A disabled meter does nothing: nothing is queued or sent, and streams and responses pass through untouched. See what FiscaLLM covers and what it doesn't.
The hosted service accepts up to 1,000,000 events per app per calendar month (UTC). After that the API answers 403 until the 1st, and the SDKs print the message once. Self-hosted copies have no limit by default. Need more? Open an issue or self-host.