Docs

Get started

Attribution

Token counts tell you what you spent. Attribution tells you what it cost to serve one customer, run one feature or support one team. You get it by tagging each AI call in your code, because that split exists nowhere in your provider's own data.

Before you start

  • Finish the Quickstart: the SDK is installed, and TOKEN_METER_KEY and your provider key are set.
  • Decide the names you'll use for your teams, environments and projects (see Format rules below).

Why attribution matters

Provider invoices and usage exports have no customer field. They know an API key spent $4.02 on gpt-4.1 today. They don't know whether that was one customer running a heavy report or a thousand customers sending one message each. The only place that information exists is your code, at the moment it makes the call.

Tag at the call, not after

Attribution can't be rebuilt later from billing data. An untagged call still counts in every total (Token Meter never hides spend), but it can't be split by customer. It shows as Unattributed in the Customer column on Requests, and on the Unattributed tab of Data health.

The tags

Wrap the code that makes AI calls in an action(). Every wrapped call inside it gets these tags. It also gets a trace_id and parent_span_id (ids that link the calls of one action together), so nested actions form a chain.

TagPython argumentTypeScript fieldMeaning
actionname (first argument)name (first argument)A short label for what the code is doing, for example generate-report.
customer_refcustomer_id or customer_refcustomerRefThe end customer this call serves. This is the tag that makes cost per customer possible. Use an id such as cus_123, not an email address or a name (see Format rules).
featurefeaturefeatureThe part of your product making the call, for example reports.
teamteamteamThe internal team that owns this code.
environmentenvironmentenvironmentFor example production or staging. Keeps test traffic out of real margin numbers.
projectprojectprojectA grouping that can span teams: several teams can share one project.
member_refmember_refmemberRefThe person making the call: their email address, matching their Token Meter login. Used for usage per person.
tagsnot availabletagsYour own extra key/value pairs. Inner scopes add to outer ones. TypeScript only.

In Python, customer_id and customer_ref are the same argument. Use either.

action.mjs
import OpenAI from "openai";
import { TokenMeterClient, wrapOpenAI, action } from "@tokenmeter/sdk";

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

await action(
  "generate-report",
  { customerRef: "cus_123", feature: "reports", team: "growth", environment: "production" },
  () =>
    openai.chat.completions.create({
      model: "gpt-4o-mini",
      messages: [{ role: "user", content: "hi" }],
    }),
);

await tl.flush();

The tags appear as columns on Requests: Customer, Team and Tags by default, and Feature and Environment once you switch them on from the Columns menu. Customer cost feeds Customers.

Format rules

Token Meter checks every tag when usage arrives. A value that breaks a rule is dropped without an error: the call is still recorded, just without that tag. Check your values against this table.

TagRuleIf it breaks the rule
team, environment, projectTurned to lowercase first. Then: starts with a letter or digit; uses only a–z, 0–9 and _ . : -; at most 64 characters. No spaces. growth and q3-launch work; Growth Team does not.The tag is dropped. If the key has a default for it, the default is used instead.
action, customer_ref, featureAny text. Turned to lowercase, trimmed and cut to 200 characters, so Acme and acme count as one customer.Never dropped for format.
member_refMust look like an email address (at most 254 characters). Turned to lowercase.The tag is dropped.
customer_ref, feature, tag valuesEmail addresses, phone numbers, IP addresses, card numbers written in groups of four, sk-… keys and any 40-character run of letters, digits, / and + that isn't pure hex (it looks like an AWS secret) are make the whole value a keyed pseudonym, for example email~3f9a1c2b7d5e0a41: a hash under your workspace's own key, never the raw value. AWS key ids and Bearer tokens are caught only in tag values.Each email customer keeps its own row, shown as “Email customer 3f9a1c2b”; search Customers with the email to find it. Revenue, rules and budgets typed with the email land on the same key. Rows stored before keyed ids read “Merged before <date>” and can't be split.
tags (TypeScript)All your extra tags together must be at most 2,048 bytes as JSON.The whole call is held back, not recorded. Held-back calls from the last 7 days are listed under Calls held for review on Data health's Quality view (/data-health?tab=quality; Owners and Admins reach it from Settings › Workspace › Data health, then Quality at the bottom of Readiness).

Which value wins

A tag can be set in three places. When more than one sets it, this is what the call records:

  • Nested actions: the innermost wins. A tag set on an inner action() beats the same tag on an outer one. A tag the inner action doesn't set is taken from the nearest outer action that did.
  • Wrapper tags (TypeScript): the wrapper wins. You can pass tags when you wrap a client, for example wrapOpenAI(new OpenAI(), tl, { team: "growth" }). They apply to every call from that client and override the same tag set by any action(). Use them only for values that never change for that client. Python's wrap() takes no tags.
  • Key defaults: used only when nothing else is set. A key created with an Environment or Team on Governance › API keys fills that tag on calls that don't carry one, including calls whose value was dropped by the format rules. It never replaces a valid value. There is no key default for member_ref.

Context propagation

The tags of the current action() follow your code automatically, even through async work. Under the hood it uses each language's built-in context storage (Python's contextvars, Node's AsyncLocalStorage). It carries through:

  • Async fan-out: asyncio.gather and create_task in Python, Promise.all in TypeScript.
  • Nested actions: an inner action() takes any tag it doesn't set from its parent.
  • Streams read later: the tags are captured when the call starts, so they stay right even if you read the stream after the action has ended.

Where it stops

The context does not cross a real thread or a process boundary. In Python, ThreadPoolExecutor.submit does not carry it. In both languages it is lost across a queue, a background worker or a message broker. Use current() and attach(), below, for those.

current() / attach()

On the side that queues the job, read the active context with current() and put it in the job payload. On the worker side, restore it with attach() around the AI call. Python's TraceContext turns into a plain dictionary with to_dict() and back with from_dict(). TypeScript's context is already a plain object, so it goes straight into JSON.

If the code that queues the job makes no AI call itself, open an action() there anyway. That is what gives the job its tags.

queue-worker.mjs
import OpenAI from "openai";
import { TokenMeterClient, wrapOpenAI, action, attach, current } from "@tokenmeter/sdk";

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

// Producing side: inside an action(), copy the context into the job payload.
const raw = action("generate-report", { customerRef: "cus_123", feature: "reports" }, () =>
  JSON.stringify({ reportId: 42, traceCtx: current() ?? null }),
);

// Consuming side: the worker parses the payload and restores the context
// only around the call, so nothing carries over to the next job.
const payload = JSON.parse(raw);
const work = () =>
  openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: "hi" }],
  });
await (payload.traceCtx ? attach(payload.traceCtx, work) : work());

await tl.flush();

Python: always reset what you attach

In Python, attach() sets the context until something changes it. On a long-running worker that handles many jobs, a job with no context would otherwise inherit the previous job's customer. Keep the token attach() returns and reset it when the job ends, as above. TypeScript's attach(ctx, fn) only applies inside fn, so it can't leak.