Docs

Get started

Frameworks & runtimes

The SDK records a call by wrapping a provider client you create yourself. Some frameworks create their own client, and serverless platforms can freeze your code before usage is sent. This page shows what to do in each case, and where the SDK can't reach yet.

Related guides: Vercel AI Gateway cost tracking, AWS Bedrock cost tracking

Before you start

  • A Token Meter ingest key (a password that lets your app send usage to Token Meter, starting tl_live_). Create one at Governance › API keys › Create key; you need to be an Owner, Admin or Team lead. Save it as the environment variable TOKEN_METER_KEY. The Quickstart shows how, step by step.
  • Node.js 20.6 or later for the TypeScript SDK. It is an ES module only (it uses import, not require). Python examples need Python 3.9 or later.
  • To connect Vercel AI Gateway's spend report: you need to be an Owner or Admin in Token Meter, and your Vercel team must be on the Pro or Enterprise plan.

Vercel AI SDK

The Vercel AI SDK (the ai package) creates its own provider clients, so there is no client for you to wrap. Add Token Meter's middleware (a plug-in that sees every call the model makes) instead. It works with AI SDK versions 3 to 7. It is TypeScript only, because the AI SDK is; in Python, wrap your provider client as shown on Providers.

  1. In your terminal, install the packages: npm install @tokenmeter/sdk ai @ai-sdk/openai.
  2. Save your provider key as OPENAI_API_KEY, next to TOKEN_METER_KEY.
  3. Wrap the model with wrapLanguageModel and tokenmeterMiddleware, as below. Save it as ai-sdk-call.mjs and run node ai-sdk-call.mjs. (On AI SDK 3, the function is called experimental_wrapLanguageModel.)
  4. Open Requests in the sidebar. The call appears in the table within a few seconds.
ai-sdk-call.mjs
import { generateText, wrapLanguageModel } from "ai";
import { openai } from "@ai-sdk/openai";
import { TokenMeterClient, tokenmeterMiddleware } from "@tokenmeter/sdk";

const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });

// Wrap the model once; use it everywhere you used the plain model before.
const model = wrapLanguageModel({
  model: openai("gpt-4o-mini"), // reads OPENAI_API_KEY
  middleware: tokenmeterMiddleware(tl),
});

const { text } = await generateText({ model, prompt: "Say hello in five words." });
console.log(text);

await tl.flush(); // a short script sends its usage before it exits

Which provider a call is recorded under. The middleware reads the provider from the AI SDK model:

  • @ai-sdk/openai, @ai-sdk/anthropic, @ai-sdk/google (and Gemini through @ai-sdk/google-vertex), @ai-sdk/azure and OpenRouter's AI SDK provider are recorded under that provider.
  • Vercel's gateway provider is recorded as Vercel AI Gateway. See the next section.
  • Amazon Bedrock (@ai-sdk/amazon-bedrock) is recorded as Bedrock, and Claude through @ai-sdk/google-vertex/anthropic as Google. Mistral, xAI, Fireworks, DeepInfra and Together AI are recorded under their own names.
  • Everything else, Groq for example, is recorded with provider other. Token Meter has no price list for other, so those calls usually 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).
  • SDK 0.2.0 recorded Bedrock, Claude on Vertex and the five providers above as other too. Use 0.2.1 or later to have them priced.

AI SDK 3 and 4 don't report cache and reasoning tokens

AI SDK 5 and later report cached and reasoning tokens when the provider does, and the middleware records them (cache writes from version 6). AI SDK 3 and 4 only give the middleware a prompt total and a completion total. On those versions the cache and reasoning counts stay empty, never guessed. The total cost is still right; the cache discount and reasoning split are only exact on version 5 and later.

Vercel AI Gateway

Vercel AI Gateway is Vercel's service for calling many AI providers through one key. Token Meter can show its spend in two ways, and you can use both: the daily spend report Vercel keeps, and a record of each call your app makes.

Connect the daily spend report

Token Meter reads your Vercel team's Gateway spend every hour, per model and per day, with up to 90 days of history. It shows as its own provider and is kept apart from any direct OpenAI or Anthropic connection, so the same request is never counted twice.

  1. In Vercel, open the team you want to report on, then AI Gateway › API Keys, and create a key. The key reads spend for the whole team.
  2. In the Token Meter dashboard, open Settings › Connections and choose Connect an account.
  3. Under Provider, choose Vercel AI Gateway.
  4. Enter your Vercel team slug (the part after vercel.com/ in your team's address) and paste the key into AI Gateway API key. To rename the connection, open Advanced and change Connection name (it defaults to Vercel AI Gateway).
  5. Optionally, tick Extra breakdowns: by tag, by user, by API key, and own keys vs Vercel credits. Each one adds a report query per day with traffic.
  6. Choose Connect and sync. The button reads Validating credentials… while Token Meter checks the key. You then land on the Connections tab with the message Connection saved. A sync is running. The card shows Syncing… until the last week has landed, then Filling in older history… while the rest of the provider's history imports. Both update without a reload.

What it costs and what to expect:

  • Vercel serves these reports to Pro and Enterprise teams only. A Hobby or Pro trial key is refused when you connect.
  • Vercel bills each report query to your team ($5 per 1,000). Syncs run every hour and read the last 3 days again, so each sync makes one query to find the days with traffic in that window, then one per such day. The first import makes at most 91.
  • Requests that use your own provider keys (BYOK, "bring your own key") show as $0, because that spend is billed on your provider account. Connect that provider directly to see it. The own-keys breakdown shows the list value of that traffic.
  • The breakdowns appear on Analytics › Spend when you pick Vercel AI Gateway in the provider row, under its model list. They are never added to its total, because a request counts under every tag it carries.

Record each call

The AI SDK middleware above already records calls to gateway(...) models as Vercel AI Gateway, keeping Vercel's creator/model name. If you call the Gateway with the OpenAI SDK instead, use the OpenAI-compatible wrapper. Save your Gateway key as AI_GATEWAY_API_KEY first.

gateway-call.mjs
import OpenAI from "openai";
import { TokenMeterClient, wrapOpenAICompatible } from "@tokenmeter/sdk";

const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const gatewayClient = wrapOpenAICompatible(
  new OpenAI({ apiKey: process.env.AI_GATEWAY_API_KEY, baseURL: "https://ai-gateway.vercel.sh/v1" }),
  tl,
  "vercel_gateway",
);

const reply = await gatewayClient.chat.completions.create({
  model: "anthropic/claude-sonnet-4.5",
  messages: [{ role: "user", content: "Say hello in five words." }],
});
console.log(reply.choices[0].message.content);

await tl.flush();

These calls are priced from Vercel's public model list, synced daily. On Analytics › Spend, filtered to Vercel AI Gateway, each model in the report shows the cost the SDK recorded for the same days beside it. A model the SDK recorded that is missing from the report is listed as such.

Line up Vercel's tag report with Token Meter

The middleware can send each call's team, project, feature and environment to the Gateway as reporting tags (team:payments, env:prod), so Vercel's tag breakdown matches Token Meter. It is off by default, because Vercel charges for each tag written ($0.075 per 1,000). It needs AI SDK 5 or later, only touches Gateway models, keeps any tags you already send, and stays within Vercel's limit of 10 tags. Customer references are never sent. In Python, send the ai-reporting-tags header yourself.

gateway-tags.mjs
import { gateway, generateText, wrapLanguageModel } from "ai";
import { TokenMeterClient, tokenmeterMiddleware } from "@tokenmeter/sdk";

const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });

const model = wrapLanguageModel({
  model: gateway("anthropic/claude-sonnet-4.5"), // reads AI_GATEWAY_API_KEY
  middleware: tokenmeterMiddleware(tl, { team: "payments" }, { gatewayReportingTags: true }),
});

// Sends ai-reporting-tags: team:payments (plus project:, feature:, env: when set).
const { text } = await generateText({ model, prompt: "Say hello in five words." });
console.log(text);

await tl.flush();

Serverless functions

Normally the SDK sends usage in the background every 2 seconds. Serverless platforms (AWS Lambda, Vercel functions, Cloudflare Workers) freeze your code as soon as it returns a response, so that background send may never run. On these platforms:

  1. In TypeScript, create the client with createServerlessClient instead of new TokenMeterClient. It turns the background timer off.
  2. Send the usage yourself at the end of every request, using the pattern for your platform below.

AWS Lambda

Wait for the send as the last line before you return. Lambda freezes as soon as the handler finishes. If you use the older callback style, leave callbackWaitsForEmptyEventLoop at its default (true).

index.mjs
import OpenAI from "openai";
import { createServerlessClient, flushBeforeReturn, wrapOpenAI } from "@tokenmeter/sdk";

const tl = createServerlessClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const openai = wrapOpenAI(new OpenAI(), tl);

export const handler = async (event) => {
  const reply = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: event.prompt ?? "Say hello" }],
  });
  await flushBeforeReturn(tl); // the last line before return
  return { statusCode: 200, body: reply.choices[0].message.content };
};

Next.js on Vercel

In Next.js 15.1 or later, send the usage in after(), which runs once the response has gone. Don't set export const runtime = "edge" on this route (see Which runtimes work).

app/api/chat/route.ts
import { after } from "next/server";
import OpenAI from "openai";
import { createServerlessClient, wrapOpenAI } from "@tokenmeter/sdk";

const tl = createServerlessClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const openai = wrapOpenAI(new OpenAI(), tl);

export async function POST(request: Request) {
  const { prompt } = await request.json();
  const reply = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: prompt }],
  });
  after(() => tl.flush()); // runs after the response is sent
  return Response.json({ text: reply.choices[0].message.content });
}

Other Vercel functions

Install @vercel/functions and pass its waitUntil to flushOnWaitUntil. The function stays alive until the usage is sent, up to the function's own time limit.

api/chat.ts
import { waitUntil } from "@vercel/functions";
import OpenAI from "openai";
import { createServerlessClient, flushOnWaitUntil, wrapOpenAI } from "@tokenmeter/sdk";

const tl = createServerlessClient({ apiKey: process.env.TOKEN_METER_KEY ?? "" });
const openai = wrapOpenAI(new OpenAI(), tl);

export default {
  async fetch(request: Request) {
    const { prompt } = await request.json();
    const reply = await openai.chat.completions.create({
      model: "gpt-4o-mini",
      messages: [{ role: "user", content: prompt }],
    });
    flushOnWaitUntil(tl, { waitUntil }); // keeps the function alive until usage is sent
    return Response.json({ text: reply.choices[0].message.content });
  },
};

Cloudflare Workers

Pass the Worker's ctx to flushOnWaitUntil. The SDK needs Cloudflare's Node.js compatibility, so add these lines to your wrangler.toml, and store your keys as Worker secrets (npx wrangler secret put TOKEN_METER_KEY, then the same for OPENAI_API_KEY).

wrangler.toml
compatibility_date = "2025-09-01"
compatibility_flags = ["nodejs_compat"]
src/index.js
import OpenAI from "openai";
import { createServerlessClient, flushOnWaitUntil, wrapOpenAI } from "@tokenmeter/sdk";

let tl;
let openai;

export default {
  async fetch(request, env, ctx) {
    // Create the clients once per Worker instance, from the Worker's secrets.
    tl ??= createServerlessClient({ apiKey: env.TOKEN_METER_KEY });
    openai ??= wrapOpenAI(new OpenAI({ apiKey: env.OPENAI_API_KEY }), tl);

    const { prompt } = await request.json();
    const reply = await openai.chat.completions.create({
      model: "gpt-4o-mini",
      messages: [{ role: "user", content: prompt }],
    });
    flushOnWaitUntil(tl, ctx); // ctx.waitUntil keeps the Worker alive until usage is sent
    return Response.json({ text: reply.choices[0].message.content });
  },
};

Python

Python has no separate serverless client. Call tokenmeter.flush(deadline_s=2.0) as the last line before your handler returns, as in the Lambda example. It keeps sending until nothing is left, 2 seconds pass, or a send fails.

What can still be lost

Usage recorded after the last flush of a request is lost if the request ends without flushing. With the timer off, nothing else will send it.

In TypeScript, flush() sends everything still buffered and first waits for a send that is already running. SDK 0.2.0 sent only one batch of up to 500 events per call. If you can't upgrade yet, loop until the buffer is empty:

flush-all.mjs
// Only needed on SDK 0.2.0: sends everything still buffered, one batch of up to 500 events at a time.
while (tl.pending > 0) {
  const { sent } = await tl.flush();
  if (sent === 0) break;
}

Which runtimes work

The TypeScript SDK uses three Node.js built-in modules: node:crypto, node:zlib and node:async_hooks. It runs anywhere those exist.

RuntimeWorks?
Node.js 20.6 or later: servers, containers, AWS Lambda, Vercel functions on the Node.js runtimeYes.
Cloudflare WorkersShould work with Node.js compatibility on: the nodejs_compat flag with a compatibility date of 2024-09-23 or later (on by default from 2026-08-04). Token Meter hasn't tested it on Workers yet.
Vercel Edge runtime (runtime = "edge"), and other edge runtimes without node:crypto and node:zlibNo. Use the Node.js runtime for routes that call AI models. Vercel recommends it over Edge anyway.
BrowsersNo, and you shouldn't try: it would put your ingest key in front of every visitor.

Agent steps

An agent request is more than its model calls: it plans, searches, calls tools and hands work to other agents. Steps record those parts, so the trace page shows each step with the model calls it made nested under it, how long each took, and what its calls cost. Steps carry a name, a kind, a start and a duration. They never carry tokens, cost, prompts, tool arguments or results; a step's cost is the sum of the calls under it.

From the SDK

Every action() sends one step of kind action when it closes (TypeScript SDK 0.2.4 and Python SDK 0.2.5 or later). For the parts in between, wrap them in step(name, kind), where kind is tool, retrieval, plan, agent or other. Model calls made inside a step attach to it. See step() in the reference.

agent.ts
await action("answer ticket", { customerRef: "acme" }, async () => {
  const hits = await step("search help center", "retrieval", () => index.search(question), { tool_name: "help_center_index" });
  await step("draft reply", "agent", () =>
    openai.chat.completions.create({ model: "gpt-4o-mini", messages: build(hits) }), { agent_name: "writer" });
});

Retrieval detail: which documents a search returned

A retrieval step can also record how it searched and what came back: mode (keyword, vector or hybrid), top_k, the index name, and documents, the ranked results as rank, document_id, score and an optional source (keyword, vector or fused, for the list a hybrid result came from). Up to 50 documents are kept, best rank first. Pass them to step(), or call record_retrieval() (Python) or recordRetrieval() (TypeScript) inside the step once the search has run. The trace page lists them under the step.

Send opaque document ids, such as a hash or your database row id, not file paths, URLs or emails: ids are stored as your code sends them and shown to anyone who can see the trace. Only ids and scores are kept. Any text field on a document is dropped, and the query is never sent. The workspace owner, CTO or CFO can turn retrieval detail off under Settings › Workspace › Trace data; new steps are then stored without it, and steps already stored keep theirs. It is never shown on a public trace link, and steps from OpenTelemetry do not carry it.

search.ts
const hits = await step("search help center", "retrieval", async () => {
  const hits = await index.hybridSearch(question, { k: 10 });
  recordRetrieval({
    mode: "hybrid", top_k: 10,
    documents: hits.map((h, i) => ({ rank: i + 1, document_id: h.id, score: h.score, source: "fused" })),
  });
  return hits;
}, { index: "help-center" });

From OpenTelemetry: which spans to forward

If your agent framework already emits OpenTelemetry GenAI spans, send them to /v1/otlp/v1/traces with an OpenTelemetry connector and turn on Agent steps for that connector in its row in the Connectors table under Coding tools › Connect. It is off by default. With it on, these spans become steps:

  • gen_ai.operation.name = invoke_agent or create_agent: an agent step, named by gen_ai.agent.name.
  • gen_ai.operation.name = execute_tool: a tool step, named by gen_ai.tool.name.
  • Any span with tokenmeter.step.kind set to action, agent, plan, tool, retrieval or other, named by tokenmeter.step.name or else the span name. Use it for your own spans, such as a reranker.

Forward those spans and the model-call spans (chat, text_completion, generate_content, embeddings). HTTP client spans to AI providers only count toward the daily check for AI calls made without instrumentation; database and other spans are not used, so there is no need to send them. Token counts on an agent or tool span are ignored, so a framework that sums its calls' tokens onto the agent span is not counted twice: only model calls are metered. Tool arguments and results are never kept; a step keeps identifiers only (agent and tool names and ids, the tool type and call id).

Limits

  • Up to 500 steps per trace. Steps past that are dropped and counted.
  • Up to 10,000 steps a minute per workspace. Past that, POST /v1/steps:batch answers 429 with Retry-After and the SDKs retry; steps from an OpenTelemetry export are dropped and counted, and the export itself still succeeds.
  • Steps are kept for 90 days.

Not supported yet

A framework that creates its own provider client hides the call from the SDK, unless the framework lets you pass in a client you created.

FrameworkWhy notWhat you can do today
LangChainCreates its own provider clients (ChatOpenAI, ChatAnthropic). A callback handler for the SDK is not built yet.Pass in a wrapped client where LangChain accepts one, or use the router (below).
LlamaIndexSame as LangChain.Same as LangChain.
CrewAIPython only, and creates its own clients.Same as LangChain.
LangGraphBuilt on LangChain's clients.Same as LangChain.

Use the router instead of the SDK. Any framework that lets you set an OpenAI base URL can send its calls through the Token Meter router, which records every call with no SDK. Point it at https://router.timewastevc.com/v1 with your tl_live_ key, as below. On Growth, Scale and Enterprise, model: "auto" lets the router pick a model on Token Meter's keys with no provider key of your own, up to US$25 of auto traffic a month (a workspace paying from router credits has no allowance: its balance is the limit). On Free, an auto request gets 402 platform_keys_require_paid_plan unless a routing policy sends it to a model on your own provider key (or your workspace pays from router credits). To use the router on Free, an Owner or Admin adds your provider key and the model's capability record under Router › Providers, and you name that model. See Router for naming a specific model and for what auto routing costs.

langchain-router.mjs
import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "auto",
  apiKey: process.env.TOKEN_METER_KEY,
  configuration: { baseURL: "https://router.timewastevc.com/v1" },
});
console.log((await llm.invoke("Say hello in five words.")).content);

Where a framework neither accepts your client nor lets you change its base URL, the SDK can't see those calls. Connect the provider's billing under Settings › Connections to see that spend (see AI Bill).

Troubleshooting

What you seeWhat to do
A serverless function works, but only some calls (or none) reach RequestsUse createServerlessClient and flush at the end of every request, as in Serverless functions.
A build or start-up error saying a Node.js module (zlib or crypto) is not supportedThe route runs on an edge runtime. Remove runtime = "edge", or on Cloudflare turn on nodejs_compat.
AI SDK calls show provider other, or on Data health's Unpriced listThe AI SDK provider isn't one Token Meter maps yet (for example Groq), or you are on SDK 0.2.0, which recorded Bedrock, Claude on Vertex, Mistral, xAI, Fireworks, DeepInfra and Together AI as other. Upgrade the SDK, or call that provider through its own SDK and wrapper. See Providers.
Vercel AI Gateway connection is refused when you connect itThe Vercel team is on Hobby or a Pro trial. Vercel only serves spend reports to Pro and Enterprise teams.
Gateway BYOK requests show $0That spend is billed on your own provider account. Connect that provider under Settings › Connections.
await is only valid in async functions, or an error about require() of an ES moduleName the file .mjs, or add "type": "module" to package.json.