The Countly AI SDK calculates the cost of every LLM generation it tracks, so you can see what your AI features spend without exporting provider invoices. It prices each call from the token counts the provider reports, splits the result into components you can analyze separately, and lets you supply your own rates.
This article explains how tokens are counted, how cost is split, and what the cost markers mean. It then shows how to price a fine-tuned or unlisted model and how to confirm the numbers are right.
Before you start
This article assumes you have already installed an AI SDK adapter and wrapped your AI client. Cost calculation works the same way in every adapter: OpenAI, Anthropic, Google GenAI, Cohere, Vercel AI SDK, LangChain, Mastra, and LlamaIndex.
Understanding the Cost Model
Cost is calculated inside your application, at the moment each generation is recorded, and sent to your Countly Server on the [CLY]_llm_interaction event. Each call is therefore priced with the rates your SDK version and configuration held when the call was made.
Using the Built-in Pricing Table
The SDK ships with prices for 47 models and applies them automatically, with no configuration. The table covers the following families:
- OpenAI: GPT-4.x, GPT-5.x, and the o-series
- Anthropic: Claude 3.x and 4.x
- Google: Gemini 2.x and 3.x
- Cohere: Command
All prices are in US dollars per million tokens. The table is generated from LiteLLM's published price data rather than maintained by hand, so it changes when you upgrade the SDK, not when a provider changes its prices. If a provider changes a price between releases, or you have negotiated rates, use a custom price as described in Customizing Pricing below.
Counting Tokens
Every provider reports tokens differently. The SDK normalizes them to one shape, built around two totals:
-
usage_inputis the provider's total input count, including cache reads and cache writes. It therefore matches the input figure in your provider's console. -
usage_outputis the provider's total output count, including reasoning (thinking) tokens.
Every other token field is a subset of one of those two totals. The SDK derives the subsets itself, so the following identities always hold on the event:
| Total | Made Up Of |
|---|---|
usage_total |
usage_input + usage_output
|
usage_input |
usage_input_fresh + usage_cache_read + usage_cache_write + input audio + input image |
usage_output |
usage_output_text + usage_reasoning + output audio + output image |
usage_input_fresh is what is left of the input once cache and modality tokens are taken out. A subset field that is absent means the provider does not report that bucket, while a reported 0 is a real measurement, such as a cache miss.
Token Reporting by Provider
Not every provider reports every bucket. The table shows what each adapter can see.
| Adapter | Cache Reads | Cache Writes | Reasoning | Notes |
|---|---|---|---|---|
| OpenAI | Yes | No such bucket | Yes | Streams report tokens only with stream_options: { include_usage: true }. Audio tokens are reported. |
| Anthropic | Yes | Yes | Not reported separately | Thinking tokens are part of the output total and billed at the output rate. |
| Google GenAI | Yes | No such bucket | Yes | Gemini reports thinking tokens (thoughtsTokenCount) apart from output, so the SDK adds them into usage_output. Audio and image tokens are reported. |
| Cohere | Yes | No such bucket | No | Both v1 and v2 response shapes are supported. |
| Vercel AI SDK, LangChain, LlamaIndex, Mastra | Yes | Yes | Yes | Buckets depend on what the underlying provider reports. Mastra needs @mastra/observability 1.11.0 or later to report cache tokens. |
Splitting Cost into Disjoint Components
The SDK splits every cost into components that do not overlap. Each token is billed in exactly one component, so cost_total is their plain sum.
| Field | Tokens Billed | Rate Used |
|---|---|---|
cost_input |
Fresh input only | Input rate |
cost_cache_read |
Cache reads | Cache read rate, or the input rate if the model has none |
cost_cache_write |
Cache writes | Cache write rate, or the input rate if the model has none |
cost_output |
Output, minus any reasoning that is priced separately | Output rate |
cost_reason |
Reasoning, only for models that price it separately | Reasoning rate |
cost_total |
The sum of the five fields above | |
Only models whose pricing lists a separate reasoning rate, currently the Gemini thinking models, produce a cost_reason. For every other model, including the OpenAI o-series, reasoning tokens stay in cost_output and are billed once, at the output rate.
The SDK also reports cost_cache_saved: what your cache reads saved compared with paying the fresh input rate. It is a saving, not a charge, so it is not part of cost_total. There is no cost_cached field. Use cost_cache_read for what cache reads cost and cost_cache_saved for what they saved.
cost_input, cost_output, and cost_total are always sent on a priced event. cost_cache_read, cost_cache_write, cost_reason, and cost_cache_saved appear only when they are not zero.
Changed in version 0.0.6
Earlier versions billed cache-write tokens on top of an input total that already contained them, and added reasoning on top of an output total that already contained it. From 0.0.6, cost on Anthropic prompt-cached calls and Gemini thinking-model calls is lower and correct, so expect a step change when you compare periods before and after the upgrade.
Reading the Cost Markers
The SDK never reports a cost it could not calculate. When a measure is missing, the field is left out entirely and a marker says why. Two markers are always present on [CLY]_llm_interaction:
| Marker | Value | What It Means |
|---|---|---|
usage_state |
reported |
The provider reported token counts, so the usage_* fields are present. |
usage_state |
not_reported |
The provider reported no usage. Every usage_* and cost_* field is omitted. |
cost_priced |
priced |
Every token bucket had a rate. The cost is exact. |
cost_priced |
priced_modality_approx |
The call included audio or image tokens, which were billed at the text rate. The cost is an approximation. |
cost_priced |
unpriced_model |
Tokens were reported, but no price matched the model. Every cost_* field is omitted. |
cost_priced |
no_usage |
There were no token counts to price. Every cost_* field is omitted. |
An unpriced model shows no cost rather than $0 on purpose. A $0 that means "we have no price for this model" cannot be told apart from a call that was genuinely free, and it would quietly pull down every cost average. When you build a report on cost, break it down by cost_priced first, so you can see how much of your traffic is not priced at all.
For every field on the event, including the token and cost fields above, see AI SDK Event Data Reference.
Customizing Pricing
Use the costModel setting to price a model the built-in table does not know, such as a fine-tuned model or a self-hosted one, or to replace a built-in rate with your own.
Pricing an Unlisted or Fine-Tuned Model
- Find the exact model name the provider returns for the call. This is the value of the
modelfield on the event. - Add an entry for that name to
costModel, with the input and output rates in US dollars per million tokens. - Deploy the change. Calls made from then on are priced, and earlier events keep the values they were sent with.
import OpenAI from "openai";
import { observeOpenAI } from "@countly/ai-sdk-openai";
const openai = observeOpenAI(new OpenAI(), {
appKey: "YOUR_APP_KEY",
url: "https://your-countly-server.com",
costModel: {
"ft:gpt-4o-mini:my-org": { input_per_mtok: 0.3, output_per_mtok: 1.2 },
"my-fine-tuned-model": { input_per_mtok: 0.5, output_per_mtok: 1.5 },
},
});
Every adapter accepts costModel in the same configuration object, including the Mastra exporter and the Vercel AI SDK, LangChain, and LlamaIndex integrations.
Always set both rates for a new model
For a model the built-in table does not know, a rate you leave out counts as zero. An entry with only input_per_mtok bills every output token at $0 and still marks the call as priced.
Matching Model Names by Prefix
You do not need an entry for every dated version of a model. Names are matched by prefix, so gpt-4.1-mini-2025-XX uses the price of gpt-4.1-mini, and my-fine-tuned-model-v2 uses your my-fine-tuned-model entry. The longest matching name wins, so gpt-4o-mini-… never falls back to gpt-4o.
An exact match always comes first. If your model's name begins with the name of a built-in model, give your entry the model's full, exact name, because a prefix match against the built-in table is tried before a prefix match against your own entries.
Overriding Individual Rates
A costModel entry accepts five rates, all in US dollars per million tokens:
| Field | Rate For | If Left Out |
|---|---|---|
input_per_mtok |
Fresh input tokens | Built-in rate, or zero for a new model |
output_per_mtok |
Output tokens | Built-in rate, or zero for a new model |
cached_per_mtok |
Cache reads | Built-in rate, or the input rate |
cache_write_per_mtok |
Cache writes | Built-in rate, or the input rate |
reason_per_mtok |
Reasoning tokens, billed separately from output | Built-in rate, or none, so reasoning is billed at the output rate |
When you override a built-in model, your entry is merged with its built-in rates, so you only need to set the rates you want to change. The override also applies to every dated version that matches the model by prefix.
costModel: {
// Your own model, with prompt caching
"my-cached-model": {
input_per_mtok: 1.0,
output_per_mtok: 4.0,
cached_per_mtok: 0.1,
cache_write_per_mtok: 1.25,
},
// A negotiated output rate for a built-in model: other rates stay as built in
"gpt-4o": { output_per_mtok: 9 },
}
Verifying Cost Data
After you set up your adapter, or after you add a custom price, confirm the cost is what you expect.
- Add
debug: trueto your configuration. If an adapter ever breaks one of the token identities, the SDK logs it. - Make one call to the model you want to check. If it is an OpenAI stream, include
stream_options: { include_usage: true }. - Wait up to ten seconds for the batch to be sent, or call
flush(). - In Countly, find the
[CLY]_llm_interactionevent for that call in Drill and check its segments:-
usage_stateisreported. -
cost_pricedispriced, notunpriced_model. -
cost_totalequals the sum of the component fields that are present. - For a text-only call,
cost_inputequalsusage_input_freshmultiplied by your input rate, divided by one million.
-
- Compare
usage_inputandusage_outputwith the same call in your provider's console. Because both are provider totals, they should match.
FAQ and Troubleshooting
Why Do My OpenAI Streaming Calls Show No Tokens or Cost?
OpenAI only includes token usage in a stream when you ask for it. Without it, the event carries usage_state: "not_reported" and no token or cost fields. Add stream_options to every streaming call:
const stream = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello" }],
stream: true,
stream_options: { include_usage: true },
});
Why Is There No cost_reason on My Reasoning Model?
The model has no separate reasoning rate. Its reasoning tokens are part of usage_output and are billed once, at the output rate, inside cost_output. This is the case for the OpenAI o-series and for Anthropic, which does not report thinking tokens separately. If your contract prices reasoning separately, set reason_per_mtok for the model in costModel.
Why Do My Mastra Calls Report Zero Cache Tokens?
Check your @mastra/observability version. The adapter reads cache tokens from a shape that @mastra/observability only produces from version 1.11.0. An older version installs without an error and then reports zero cache tokens, which misprices every prompt-cached call. Upgrade @mastra/core to 1.26.0 or later and @mastra/observability to 1.11.0 or later. For the rest of the setup, see Integrating the Countly AI SDK with Mastra.