Get started
Providers
The Token Meter SDK records the tokens and cost of every AI call your app makes, for each provider you use. This page shows how to set it up for OpenAI, Anthropic, Google Gemini, AWS Bedrock, Azure OpenAI and OpenAI-compatible providers, and what it records for each.
Related guides: OpenAI cost tracking, Anthropic API cost tracking, AWS Bedrock cost tracking, Gemini and Vertex AI cost tracking, Azure OpenAI cost tracking, OpenRouter cost tracking, Track AI spend across providers
Before you start
- A Token Meter account. To create a key you need to be an Owner, Admin or Team lead in your workspace.
- An account with the AI provider you use, and permission to create an API key there. The SDK measures calls made with your own provider key, so the provider bills those calls to you as usual.
- Python 3.9 or later, or Node.js 20.6 or later. Use the Python / TypeScript switch on the code blocks to pick your language.
- A terminal (Terminal on macOS, PowerShell on Windows), open in your project folder.
New to the SDK? The Quickstart walks through one OpenAI call in more detail. If you'd rather not change code at all, the Router records calls when you change a base URL instead.
Steps for every provider
Every provider is set up the same way. The sections below give the details for each one.
- In the Token Meter dashboard, open Governance › API keys and choose Create key. Give it a name and choose Create key again. This is your ingest key (a password that lets your app send usage to Token Meter). It starts with
tl_live_. - Copy the key straight away. It is shown once and never again. If you lose it, create a new one.
- Get an API key from your provider. Each section below says where.
- Save both keys as environment variables (settings your script reads, so keys never sit in your code). Run these in your terminal, with your real keys in place of the dots. Each section below names the provider's variable.
export TOKEN_METER_KEY="tl_live_..."
export OPENAI_API_KEY="sk-..."$env:TOKEN_METER_KEY = "tl_live_..."
$env:OPENAI_API_KEY = "sk-..."- Install the Token Meter SDK and your provider's SDK. The Token Meter SDK wraps the one you install.
- Wrap your provider client and make a call. Python uses one function,
tokenmeter.wrap(client), for every provider. TypeScript has one function per provider. Your calls work exactly as before. - In the dashboard sidebar (Home view), open Requests. Within a few seconds the top row of the table shows your call, with its model, tokens and cost.
Running the TypeScript snippets
The TypeScript SDK is an ES module only (it usesimport, not require). Save a snippet with the .mjs file name shown and run it with node. In your own project, add "type": "module" to package.json or use .mts files.OpenAI
- In the OpenAI Platform (platform.openai.com), open API keys and choose Create new secret key. The key starts with
sk-. - Save it as
OPENAI_API_KEY, next toTOKEN_METER_KEY. - Install the packages in your terminal:terminal
npm install @tokenmeter/sdk openai - Save the script below in your folder, using the file name on the code block, and run it.
import OpenAI from "openai";
import { TokenMeterClient, wrapOpenAI } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const openai = wrapOpenAI(new OpenAI(), tl); // reads OPENAI_API_KEY
const reply = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Say hello in five words." }],
});
console.log(reply.choices[0].message.content);
await tl.flush(); // a short script sends its usage before it exitsBoth the Chat Completions API and the Responses API are recorded, streaming or not. Python also wraps AsyncOpenAI.
Anthropic
- In the Claude Console (console.anthropic.com), open API keys and create a key. It starts with
sk-ant-. - Save it as
ANTHROPIC_API_KEY, next toTOKEN_METER_KEY. - Install the packages in your terminal:terminal
npm install @tokenmeter/sdk @anthropic-ai/sdk - Save the script below in your folder, using the file name on the code block, and run it.
import Anthropic from "@anthropic-ai/sdk";
import { TokenMeterClient, wrapAnthropic } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const anthropic = wrapAnthropic(new Anthropic(), tl); // reads ANTHROPIC_API_KEY
const reply = await anthropic.messages.create({
model: "claude-haiku-4-5",
max_tokens: 200,
messages: [{ role: "user", content: "Say hello in five words." }],
});
console.log(reply.content[0].text);
await tl.flush();The Messages API is recorded, streaming or not. Anthropic's Bedrock and Vertex clients (AnthropicBedrock, AnthropicVertex) are wrapped the same way. Their calls are recorded under AWS Bedrock and Google, because those are the bills they appear on. In TypeScript, if that detection can't see your client, pass it yourself: wrapAnthropic(client, tl, {}, { provider: "bedrock" }).
Google Gemini
- In Google AI Studio (aistudio.google.com), choose Get API key, then Create API key.
- Save it as
GEMINI_API_KEY, next toTOKEN_METER_KEY. - Install the packages in your terminal:terminal
npm install @tokenmeter/sdk @google/genai - Save the script below in your folder, using the file name on the code block, and run it.
import { GoogleGenAI } from "@google/genai";
import { TokenMeterClient, wrapGemini } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const ai = wrapGemini(new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }), tl);
const reply = await ai.models.generateContent({
model: "gemini-3.6-flash",
contents: "Say hello in five words.",
});
console.log(reply.text);
await tl.flush();generateContentandgenerateContentStreamare recorded (generate_contentandgenerate_content_streamin Python).- Python wraps the regular client only. The async client (
client.aio.models) is not recorded yet. - Gemini 2.5 models are no longer offered to new Google API keys. Use a newer model, as in the script.
AWS Bedrock
- Bedrock uses your AWS credentials, not an API key. The AWS user or role your code runs as needs the
bedrock:InvokeModelpermission (andbedrock:InvokeModelWithResponseStreamfor streaming). Set this in the AWS console under IAM. Then open Amazon Bedrock › Model catalog and check you can use the model in your region. Some model makers, such as Anthropic, ask for a one-time use-case form. - Make your AWS credentials available the way you usually do:
aws configure, theAWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEYenvironment variables, or an IAM role. - Install the packages in your terminal:terminal
npm install @tokenmeter/sdk @aws-sdk/client-bedrock-runtime - Save the script below in your folder, using the file name on the code block, and run it.
import { BedrockRuntimeClient, ConverseCommand } from "@aws-sdk/client-bedrock-runtime";
import { TokenMeterClient, wrapBedrock } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
// Uses your usual AWS credentials (environment variables, ~/.aws or an IAM role).
const bedrock = wrapBedrock(new BedrockRuntimeClient({ region: "us-east-1" }), tl);
const reply = await bedrock.send(
new ConverseCommand({
modelId: "amazon.nova-lite-v1:0",
messages: [{ role: "user", content: [{ text: "Say hello in five words." }] }],
}),
);
console.log(reply.output.message.content[0].text);
await tl.flush();ConverseandConverseStreamare fully recorded for every model family. Prefer them.InvokeModelis recorded too, with limits that depend on the model family. See What each provider supports.- Python wraps the regular boto3 client.
aioboto3is not recorded yet.
Azure OpenAI
- In the Azure portal, open your Azure OpenAI resource, then Resource Management › Keys and Endpoint. Copy KEY 1 and the Endpoint. Then note the name of the deployment you want to call. You find it under Deployments in the Azure AI Foundry portal.
- Save them as
AZURE_OPENAI_API_KEY,AZURE_OPENAI_ENDPOINTandAZURE_OPENAI_DEPLOYMENT, next toTOKEN_METER_KEY. - Install the packages in your terminal:terminal
npm install @tokenmeter/sdk openai - Save the script below in your folder, using the file name on the code block, and run it.
import { AzureOpenAI } from "openai";
import { TokenMeterClient, wrapAzureOpenAI } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const azure = wrapAzureOpenAI(
new AzureOpenAI({
endpoint: process.env.AZURE_OPENAI_ENDPOINT,
apiKey: process.env.AZURE_OPENAI_API_KEY,
apiVersion: "2024-10-21",
}),
tl,
);
const reply = await azure.chat.completions.create({
model: process.env.AZURE_OPENAI_DEPLOYMENT ?? "", // your deployment's name
messages: [{ role: "user", content: "Say hello in five words." }],
});
console.log(reply.choices[0].message.content);
await tl.flush();Chat Completions and the Responses API are recorded, streaming or not. If you use the Responses API, also read Azure deployment names, or its calls can't be priced.
OpenAI-compatible providers
Many providers accept the OpenAI SDK with a different base URL (the web address the SDK sends calls to). Use the provider-aware wrapper so the call is recorded, and priced, under the provider you actually pay.
- Get an API key from that provider's dashboard and save it as an environment variable.
- Install the packages:
pip install "tokenmeter-sdk[openai]"ornpm install @tokenmeter/sdk openai. - Point the OpenAI client at the provider's base URL from the table, and pass the provider's value to the wrapper. The script uses OpenRouter, with its key saved as
OPENROUTER_API_KEY.
| Provider | Value to pass | Base URL |
|---|---|---|
| OpenRouter | openrouter | https://openrouter.ai/api/v1 |
| xAI | xai | https://api.x.ai/v1 |
| Mistral | mistral | https://api.mistral.ai/v1 |
| Fireworks | fireworks | https://api.fireworks.ai/inference/v1 |
| Together AI | together | https://api.together.xyz/v1 |
| DeepInfra | deepinfra | https://api.deepinfra.com/v1/openai |
| Vercel AI Gateway | vercel_gateway | https://ai-gateway.vercel.sh/v1 |
import OpenAI from "openai";
import { TokenMeterClient, wrapOpenAICompatible } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const openrouter = wrapOpenAICompatible(
new OpenAI({ apiKey: process.env.OPENROUTER_API_KEY, baseURL: "https://openrouter.ai/api/v1" }),
tl,
"openrouter",
);
const reply = await openrouter.chat.completions.create({
model: "openai/gpt-4o-mini",
messages: [{ role: "user", content: "Say hello in five words." }],
});
console.log(reply.choices[0].message.content);
await tl.flush();The TypeScript form is wrapOpenAICompatible(client, tl, provider); the Python form is tokenmeter.wrap_openai_compatible(client, provider). In Python, any other value raises an error that lists the allowed ones; in TypeScript the allowed values are checked by the type, not at run time. Usage is read with the same rules as OpenAI. For the Vercel AI SDK and Vercel AI Gateway, see Frameworks.
What each provider supports
"Cache tokens" are input tokens the provider served from its prompt cache, which cost less. "Reasoning tokens" are the hidden thinking tokens some models bill as output.
| Provider | What is recorded | Streaming | Cache tokens | Reasoning tokens |
|---|---|---|---|---|
| OpenAI | Chat Completions and Responses API | Yes, both | Recorded | Recorded |
| Anthropic | Messages API | Yes | Recorded (reads and writes) | Not reported separately |
| Google Gemini | generateContent and generateContentStream | Yes | Recorded | Recorded |
| AWS Bedrock | Converse, ConverseStream, InvokeModel | Yes | Recorded (Converse) | Not reported (billed inside output) |
| Azure OpenAI | Chat Completions and Responses API | Yes, both | Recorded, same rule as OpenAI (not yet checked live) | Recorded, same rule as OpenAI (not yet checked live) |
| OpenAI-compatible | Chat Completions and Responses API | Yes, both | When the provider reports them | When the provider reports them |
Streaming. A streamed Chat Completions call only reports its tokens if the request asks for them. The wrapper adds stream_options.include_usage for you. In Python, if you pass your own stream_options, the wrapper leaves it alone, so include "include_usage": True yourself. The Responses API always reports tokens at the end of a stream. A stream that stops before its final chunk is recorded as incomplete, with no token counts. Token Meter never guesses them.
Bedrock InvokeModel. The response body differs by model family:
- Anthropic Claude and Amazon Nova bodies are read in both languages.
- Python also reads Meta Llama bodies.
- For any other family, Python reads the input and output counts from the
x-amzn-bedrock-input-token-countandx-amzn-bedrock-output-token-countresponse headers. That includes Mistral, whose bodies carry no counts at all. The AWS SDK for JavaScript does not expose those headers, so TypeScript records these calls as incomplete, with no token counts. InvokeModelWithResponseStreamrecords input and output tokens only, with no cache split, for every family.
Tags on a single call. Every TypeScript wrapper takes optional fixed tags for all calls through that client, as the third argument (the fourth for wrapOpenAICompatible, after the provider), for example wrapOpenAI(new OpenAI(), tl, { team: "payments" }). wrapAnthropic and wrapAzureOpenAI also take a fourth options argument ({ provider } and { deploymentModelMap }). See Attribution for tagging calls by customer, team and feature.
Azure deployment names
On Azure, you call a deployment you named yourself, such as prod-summarizer. Azure's Chat Completions API replies with the real model name, so those calls are priced with no extra work. Azure's Responses API replies with your deployment name instead. Token Meter's price list has no prod-summarizer, so those calls can't be priced until you say which model each deployment runs.
Pass a map from deployment name to model name when you wrap the client:
const azure = wrapAzureOpenAI(
new AzureOpenAI({
endpoint: process.env.AZURE_OPENAI_ENDPOINT,
apiKey: process.env.AZURE_OPENAI_API_KEY,
apiVersion: "2025-03-01-preview",
}),
tl,
{},
{ deploymentModelMap: { "prod-summarizer": "gpt-5-2025-08-07" } },
);A deployment that is not in the map keeps its own name and shows on Data health's Unpriced list (/data-health?tab=unpriced; Owners and Admins: Settings › Workspace › Data health, then Unpriced at the bottom of Readiness) until you add it. It is never priced at a guessed rate. The map only applies to Azure OpenAI; it is ignored for every other provider.
How token counts are worked out
You don't need to do anything here. This section explains how Token Meter turns each provider's numbers into one cost you can compare.
Providers report tokens in different shapes. Token Meter converts each call into five separate counts: input_tokens, output_tokens, cache_read_tokens, cache_write_tokens and reasoning_tokens. No token is in more than one count, so cost is simply each count times its price, added up. A count the provider didn't report stays empty rather than guessed. The arithmetic differs by provider:
- OpenAI and Azure OpenAI: the cached tokens are part of the prompt total, and reasoning tokens are part of the completion total, so both are subtracted:
input = prompt_tokens − cached_tokens,output = completion_tokens − reasoning_tokens. - Anthropic: cache reads and writes are already reported apart from
input_tokens. They are used as they are, with nothing subtracted. - AWS Bedrock (Converse):
inputTokensalready leaves out cache reads and writes, so it is used as it is. Bedrock has no reasoning count; Claude thinking tokens are billed insideoutputTokens. - Google Gemini: cached tokens are part of the prompt total, so
input = promptTokenCount − cachedContentTokenCount. ButthoughtsTokenCountis reported apart fromcandidatesTokenCount, so output is used as it is.
Two providers that break the pattern
OpenAI teaches the habit "cache and reasoning tokens are part of the total, so subtract them". Two providers work the other way. This is the most common place to get AI costs wrong.
Bedrock's inputTokens already leaves out the cache
SubtractingcacheReadInputTokens from Bedrock's inputTokens takes the cache off twice, and input spend comes out too low.Gemini's thoughtsTokenCount is already separate
SubtractingthoughtsTokenCount from candidatesTokenCount counts too few output tokens. Reasoning-heavy traffic then looks cheaper than it is.How each rule is checked
Not every rule above has been checked against a real provider call. Some come from the provider's own documentation. Here is where each one stands:
- OpenAI: proven with real calls. In a five-call test,
prompt_tokensstayed at 2,107 whether or not the prompt was cached. - Anthropic: stated in Anthropic's documentation and checked against saved responses.
- Google Gemini: checked against Google's documentation. That the last chunk of a stream carries the final counts is seen in practice, but Google doesn't document it.
- AWS Bedrock: the Converse shape is documented. For Amazon Nova through
InvokeModel, AWS's own documents disagree on how the cache counts are spelled. Python checks every spelling; TypeScript leaves Nova cache counts empty rather than guess. - Azure OpenAI: inferred, not yet checked with real calls. Azure uses OpenAI's field names, so the same rule is assumed. The five-call cache test has not been run on a real Azure deployment yet. Treat Azure cache figures as provisional.
Each rule has an automated test against a saved provider response, so a change that breaks one is caught before it ships.
Troubleshooting
| What you see | What to do |
|---|---|
| The reply prints, but nothing appears on Requests after a minute | In Python, check that tokenmeter.init(...) runs before your calls; without it, nothing is recorded. Then run python -c "import os, tokenmeter; tokenmeter.diagnose(os.environ['TOKEN_METER_KEY'])". It prints OK or the reason the key fails. In TypeScript, add onError: (err) => console.error(err) next to apiKey and run again. |
invalid_key, key_revoked, or batch of 1 event(s) permanently rejected | The Token Meter key is wrong, revoked or expired. Copy it again with no spaces, or create a new one at Governance › API keys. |
KeyError: 'TOKEN_METER_KEY' (Python, when the script reads the variable with os.environ[...]), or TokenMeter: no apiKey given; metering is disabled (TypeScript) | The key isn't set in this terminal window. Set it again and run the script in the same window. With SDK 0.2.2 or later, an empty key in TypeScript does not raise an error: the SDK warns once (through onError if you set one) and your app runs without metering. |
Azure calls show on Data health's Unpriced list (/data-health?tab=unpriced; Owners and Admins: Settings › Workspace › Data health, then Unpriced at the bottom of Readiness) | You are using the Responses API with a deployment name. Add it to the map in Azure deployment names. |
| A streamed call is recorded with no token counts | The stream stopped before its last chunk, or (Python) you passed your own stream_options without "include_usage": True. Add it. |
| Bedrock calls in TypeScript are not recorded, but they work | The wrapper recognises ConverseCommand and the other commands by their class name. If your build tool minifies code, keep class names (for example esbuild's keepNames: true). |
ValueError: provider must be one of: ... | Pass one of the values in the OpenAI-compatible table to wrap_openai_compatible. |
| Gemini returns 404 for a 2.5 model | Google no longer offers Gemini 2.5 to new API keys. Use a newer Gemini model. |