Skip to main content
To track LLM usage, send one event per model call with its token counts, and create a meter that sums them. Bill for the meter, or use it only to see what each customer consumes and costs you. This page shows both, plus how to record what each call cost you. The examples use the sandbox and API version 2026-10, with the sample customer user_123 and the event name ai_usage. See Usage for how events and meters work.

TypeScript: AI SDK

The LLM strategy from @polar-sh/ingestion wraps an AI SDK model. Every call through the wrapped model sends an event with its token usage. It works with AI SDK 5, 6 and 7, for generateText, streamText and anything else built on them.
Pass the user’s ID from your session instead of "user_123". With streamText, the event is sent when the stream finishes. Each call sends its event in its own request. If sending fails, the strategy logs the error and your call still succeeds, but that event is lost. Requires Node.js 24 or later. More strategies, for S3, streams and timings, are on Ingestion strategies.

The event it sends

Event
vendor is the model’s AI SDK provider ID. The _llm object is what Polar reads for the By Model and By Vendor views in Cost insights.

Record the cost

Add .cost() to attach what each call cost you, in cents. It receives the token counts:
Use your provider’s current rates. The result is added to the event as _cost.

Python: PydanticAI

There’s no strategy package for Python. Read the usage from the run and send it with polar.events.ingest.
This sends one request per call. To send fewer requests, collect events and send them in batches. See Send events in batches. This uses PydanticAI 2.x, where result.usage is a property. To record the cost, add "_cost": {"amount": ..., "currency": "usd"} next to _llm, with the amount in cents. The same pattern works for any Python LLM client: read the token counts from its response and send them.

Create the meter

Sum _llm.total_tokens across ai_usage events. The same meter works for events from both examples.
  • Open Catalog → Meters
  • Click Create Meter
  • Set Name to “AI tokens”
  • Under Filters, add a condition: Name equals ai_usage
  • Set Aggregation to Sum over the property _llm.total_tokens
  • Set Unit to Token
  • Click Create Meter
To bill input and output tokens at different prices, create two meters, one summing _llm.input_tokens and one summing _llm.output_tokens, and add a metered price for each. See Usage-based pricing.

Verify it works

Make one call as user_123, then open Catalog → Meters → AI tokens. The call’s tokens show on the Overview tab, and the event on the Events tab. Or run:

Learn more