Reference
API reference
Every way to talk to Token Meter from code: the three web services, what they send back, and the main SDK functions. Signatures and examples follow the language switch at the top of the page.
Start here
Token Meter has three web services. Most people never call them directly. The SDK (a small library you add to your app) talks to ingest for you, and your OpenAI or Anthropic SDK talks to the router. Use this page when you want the exact details, or want to call a service from your own code.
Before you start
- A Token Meter workspace you can sign in to at
https://timewastevc.com. - The right key for the service you want (see the table). A key is shown once, when you create it, so copy it then.
- For the
curlexamples: a terminal (Terminal on macOS or Linux; Git Bash or WSL on Windows) with your key saved in an environment variable, for exampleexport TOKEN_METER_KEY=tl_live_….
| Service | What it's for | Address | Key | Where to create the key |
|---|---|---|---|---|
| Ingest | Receives usage records (events) from the SDK, your own code and connectors. | https://ingest.timewastevc.com | Ingest key, tl_live_… | Governance › API keys › Create key. Owners, Admins and Team leads. |
| Router | Sends your AI requests to OpenAI, Anthropic or Google in their own formats, and meters them. | https://router.timewastevc.com | The same ingest key, tl_live_… | Governance › API keys › Create key. |
| Read API | Exports your daily usage and cost, for a spreadsheet or data warehouse. | https://timewastevc.com | Read key, tl_admin_… | Governance › API keys › Create a read key (link below the keys table). Owners and Admins. |
How to send the key. Ingest and the read API take Authorization: Bearer <key>. The router takes the same header, or x-api-key: <key> (the header the Anthropic SDK sends). An ingest key does not work on the read API, and a read key does not work on ingest or the router.
Connector tokens. A few ingest addresses are for tools that push data on their own. Each uses its own token, not an ingest key:
| Token | Used by | Where to create it |
|---|---|---|
| tlotel_… | OpenTelemetry exports from coding tools (/v1/otlp/v1/metrics, /logs, /traces), Continue (/v1/connectors/continue), and the Claude Code status-line reporter (/v1/quota-samples, which reports a seat's weekly percentage used). | Coding tools › Connect › All data sources › Any OpenTelemetry tool › Connect › Open OpenTelemetry setup, then Create key. Owners and Admins. See Coding agents. |
| tlzsc_… | A Zscaler Cloud NSS web-log feed (/v1/connectors/zscaler-nss), for spotting unapproved AI tools. | Governance › Rules › Shadow AI › Add a source (Connect a source while there are no sources or findings yet), then Add connection, Source Zscaler, Create feed token. Owners and Admins. |
| tlgitai_… | The Token Meter agent on each developer's machine. It sets itself up; you never call these addresses yourself. | Coding tools › Connect › Create key (the "Set up this machine" page). Any member. |
| What you see | What to do |
|---|---|
| 401 invalid_key | The key is missing, mistyped, or the wrong kind for this service. Check the prefix against the table above. |
| 403 key_revoked | The key was revoked or has expired. Create a new one under Governance › API keys. |
| 401 unauthorized (read API) | The read API answers 401 for a missing, wrong or revoked read key. Create a new read key. |
HTTP: send events
Send usage records yourself, without the SDK, with one HTTP call: POST https://ingest.timewastevc.com/v1/events:batch. Each call carries a batch: an envelope (the wrapper) holding 1 to 1,000 events. The SDKs send exactly this.
This example sends one event. Paste it into a terminal where TOKEN_METER_KEY is set. (Git Bash has no uuidgen; the fallback uses Node.js 18 or newer.)
BATCH_ID=$(uuidgen 2>/dev/null || node -e 'console.log(crypto.randomUUID())')
EVENT_ID=$(uuidgen 2>/dev/null || node -e 'console.log(crypto.randomUUID())')
NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ)
curl -sS -X POST https://ingest.timewastevc.com/v1/events:batch \
-H "Authorization: Bearer $TOKEN_METER_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{
"batch_id": "$BATCH_ID",
"sdk": { "name": "my-app", "version": "1.0.0", "schema_hash": "v1" },
"events": [
{
"event_id": "$EVENT_ID",
"occurred_at": "$NOW",
"provider": "openai",
"model_raw": "gpt-4o-mini",
"input_tokens": 812,
"output_tokens": 143,
"customer_ref": "acme",
"feature": "reports"
}
]
}
EOFYou should get status 202 and this body. The call appears in the dashboard within a minute or two.
{
"kind": "accepted",
"batch_id": "6f1c2a7e-3b9d-4c1e-9a52-0d4f8b7e2c11",
"received": 1,
"accepted": 1,
"duplicates": 0,
"quarantined": 0,
"server_time": "2026-11-14T10:03:12.004Z",
"warnings": []
}The envelope
batch_id(required): a new UUID for every batch. Reuse the same one only when you resend the same batch.sdk.nameandsdk.version(required): any non-empty text that names your sender.sdk.schema_hashis optional; without it,warningscontainsunknown_schema_hash, which is harmless.events(required): 1 to 1,000 events. The fields of one event are listed under Wire event shape. Onlyevent_id,occurred_at,providerandmodel_raware required.dropped_since_last_ack(optional): how many events your sender had to throw away since its last accepted batch, so the gap shows up on the dashboard.
The request body may be at most 1 MB as sent. To fit more, compress it with gzip and add Content-Encoding: gzip, as the SDKs do. A body that is not gzip must be plain JSON with no Content-Encoding header.
Good to know
- Resending an event with the same
event_idis safe. It is counted underduplicatesand never twice. - One bad event does not fail the batch. It is held back, counted under
quarantined, and listed under Calls held for review, behind the Quality link at the foot of Data health › Readiness. - A label in the wrong format (
team,environment,project,member_ref) is dropped from the event, which is still stored. Each drop is named inwarnings.
Error responses
An ingest error body is a small object whose error is the code, as plain text, sometimes with extra fields:
{
"error": "invalid_envelope",
"detail": "batch_id missing or not a UUID"
}| Status and error | What it means | What to do |
|---|---|---|
| 202 | Stored. This is the only answer that means the batch is safe. | Nothing. |
| 400 invalid_envelope | The envelope is wrong: batch_id missing or not a UUID, sdk.name or sdk.version missing, events empty, or the body is not JSON (or not valid gzip). detail says which. | Fix the request. Resending it unchanged fails the same way. |
| 401 invalid_key | No key, a key that does not start with tl_live_, or an unknown key. | Check the key. |
| 403 key_revoked | The key was revoked or has expired. | Create a new key under Governance › API keys. |
| 413 batch_too_large | More than 1,000 events, or a body over 1 MB (10 MB after gzip is undone). The body carries max_events and max_bytes. | Split the batch and send the halves. |
| 429 rate_limited | Traffic far above the per-minute limits (see below). Has a Retry-After header and retry_after_s. | Wait that many seconds, then resend the same batch. |
| 503 unavailable | Ingest could not store the batch just now. Has Retry-After: 5. | Wait, then resend the same batch. Nothing is double-counted. |
Rate limits
Each key gets, per minute: 100 batches and 20,000 events, and each workspace 60,000 events. These are quotas, not walls. Traffic above them is still accepted and stored. Ingest only answers 429 rate_limited at five times those numbers: 500 batches or 100,000 events per key, or 300,000 events per workspace, in one minute. A key can carry its own higher limits. Counting restarts at the top of each minute.
HTTP: read usage
Pull your daily usage and cost into a spreadsheet, a script or a data warehouse: GET https://timewastevc.com/api/v1/usage/daily. It needs a read key (tl_admin_…), not an ingest key. The read client in both SDKs wraps this call.
curl -sS "https://timewastevc.com/api/v1/usage/daily?start=2026-10-01&end=2026-10-31&limit=100" \
-H "Authorization: Bearer $TOKEN_METER_READ_KEY"| Parameter | Required | Rules |
|---|---|---|
| start | yes | First day, YYYY-MM-DD, in UTC. |
| end | yes | Last day, YYYY-MM-DD, in UTC. Not before start; at most 366 days after it, counting both days. |
| limit | no | Rows per page, 1 to 500. Default 100. |
| cursor | no | The nextCursor from the previous page. It only works with the same start and end. |
The answer has one row per day, provider, model, customer, feature, action, team and environment, newest day first. Project and member are not split out. pricedCostUsd is an exact decimal string; check unpricedEventCount before treating it as the full cost, because calls with no known price are not in it.
{
"data": [
{
"date": "2026-10-31",
"source": "metered",
"provider": "openai",
"model": "gpt-4o-mini",
"customerRef": "acme",
"feature": "reports",
"action": "generate-report",
"team": null,
"environment": null,
"requestCount": 42,
"errorCount": 0,
"inputTokens": 34104,
"outputTokens": 6006,
"cacheReadTokens": 0,
"cacheWriteTokens": 0,
"reasoningTokens": 0,
"pricedCostUsd": "0.0087192",
"unpricedEventCount": 0
}
],
"pagination": { "limit": 100, "nextCursor": "WyIyMDI2LTEwLTAxIiwiMjAyNi0xMC0zMSIs..." },
"meta": { "start": "2026-10-01", "end": "2026-10-31", "currency": "USD" }
}When nextCursor is null, you have every row. Every successful answer (and every 429) carries x-ratelimit-limit: 120 and x-ratelimit-remaining.
Errors and limits
A read API error body puts the code and a sentence inside error:
{
"error": {
"code": "range_too_large",
"message": "Date range may not exceed 366 days."
}
}| Status and code | What it means |
|---|---|
| 401 unauthorized | No read key, a wrong or revoked one, or a key without read access. |
| 400 invalid_range | start or end is not a real YYYY-MM-DD date, or start is after end. |
| 400 range_too_large | More than 366 days. |
| 400 invalid_limit | limit is not a whole number from 1 to 500. |
| 400 invalid_cursor | The cursor is damaged, or was made for a different start and end. |
| 429 rate_limited | More than 120 requests in one minute with this key. Wait the seconds in the retry-after header. |
HTTP: router
The router takes requests in OpenAI's and Anthropic's own formats, so their official SDKs work by changing two settings: the address and the key. Point the OpenAI SDK at https://router.timewastevc.com/v1 and the Anthropic SDK at https://router.timewastevc.com (no /v1), and use your tl_live_… key as the API key. The full guide, with every field, header and error code, is on Router; what the router does with your traffic (policies, caching, limits) is on Gateway & routing.
This request uses model: "auto", which lets Token Meter pick the model. On a paid plan, or a workspace paying from router credits, it runs on Token Meter's own provider keys, so it needs no provider key of yours. Without credits, on a paid plan it stops at the plan's monthly allowance with auto_monthly_limit_reached. On Free without credits, unless a routing policy claims the request, it is refused with 402 platform_keys_require_paid_plan: add your own provider key on Router › Providers (Add provider key) and send a model name such as "gpt-4o-mini" instead.
curl -sS https://router.timewastevc.com/v1/chat/completions \
-H "Authorization: Bearer $TOKEN_METER_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "auto", "messages": [{"role": "user", "content": "Say hello in five words."}]}'Success is the provider's normal answer: OpenAI's chat.completion shape on /v1/chat/completions, Anthropic's message shape on /v1/messages. The headers add x-tokenmeter-routing-decision (an id you can look up), and for auto also x-tokenmeter-model (the model that answered) and x-tokenmeter-route.
{
"id": "chatcmpl-AT2kq9xYb3",
"object": "chat.completion",
"created": 1763114592,
"model": "gpt-4o-mini-2024-07-18",
"choices": [
{
"index": 0,
"message": { "role": "assistant", "content": "Hello there, nice to meet!" },
"finish_reason": "stop"
}
],
"usage": { "prompt_tokens": 14, "completion_tokens": 7, "total_tokens": 21 }
}A router error carries the code twice (error.code and error_code) plus a sentence a person can act on. Match on error_code, never on the sentence. A provider's own error is passed through with the provider's status and body. All codes are listed under Router › Errors.
{
"error": {
"message": "Send a \"model\": either a model this workspace has configured, or \"auto\" to let routing choose.",
"type": "invalid_request_error",
"code": "model_required"
},
"error_code": "model_required",
"message": "Send a \"model\": either a model this workspace has configured, or \"auto\" to let routing choose.",
"type": "error"
}On /v1/messages, error.type uses Anthropic's names, so the Anthropic SDK reads the error as it expects. For example, a 402 has the type billing_error there, where other addresses send insufficient_quota. The error_code is the same on every address. Claude Code also gets a 402 as 429 and a 503 as 529; see Coding agents › Troubleshooting.
Router addresses
| Address | What it's for |
|---|---|
| POST /v1/chat/completions | OpenAI Chat Completions format. |
| POST /v1/messages | Anthropic Messages format. Claude Code uses it too. |
| POST /v1/responses | OpenAI Responses format, used by the Codex CLI. |
| GET /v1/models, POST /v1/messages/count_tokens | Model list and token counting. The list has every model the workspace can call by name, and auto when it is on; Claude Code, and any caller that sends anthropic-version, gets the Claude models only. |
| POST /v1/batches, GET /v1/batches/{id}, GET /v1/batches/{id}/items | Batch requests at batch prices. See Router › Batches. |
| GET /v1/routing-decisions/{id} | Look up one routing decision. See Router › Responses. |
| POST /v1/governance/preflight | Asks whether a direct provider call is allowed. The SDKs call it for you: see Governance preflight. |
| POST /v1/recall/retrieve | Fetches an archived tool result. The SDK calls it for you: see Recall. |
| POST /v1/prompt-experiments/assignment | Picks a prompt variant for an experiment. See Experiments on the Gateway and routing page. |
Request bodies may be up to 32 MB on /v1/messages and 2 MB elsewhere, measured after decompression. The router accepts bodies sent plain or with Content-Encoding gzip, deflate or br. Request and response headers are listed under Router › Headers.
Error bodies compared
The three services shape their errors differently. If your code talks to more than one, read the code from the right place for each.
| Service | Error body | Read the code from |
|---|---|---|
| Ingest | {"error": "invalid_key"} | error (plain text) |
| Router | {"error": {"message", "type", "code"}, "error_code", "message", "type": "error"} | error_code (or error.code) |
| Read API | {"error": {"code", "message"}} | error.code |
Only the router has error_code. Code that checks body.error === "invalid_key" works on ingest only; on the router and the read API, error is an object.
init / TokenMeterClient
new TokenMeterClient(config)Sets up the SDK. In Python, call tokenmeter.init() once when your program starts; it keeps one shared client. In TypeScript, create one TokenMeterClient and pass it to every wrap* call; there is no shared global. Install with pip install tokenmeter-sdk or npm install @tokenmeter/sdk. Every option is listed under Config options.
import { TokenMeterClient } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({
apiKey: process.env.TOKEN_METER_KEY!, // your tl_live_… key
flushIntervalMs: 2000, // optional; every option is under Config options
});wrap
wrapOpenAI / wrapAnthropic / wrapGemini / wrapBedrock(client, tl, defaults?) · wrapAzureOpenAI(client, tl, defaults?, { deploymentModelMap? })Turns on metering for a provider client. Python has one wrap() that recognises the client. TypeScript has one function per provider; each takes the TokenMeterClient plus optional default tags applied to every call from that client.
import OpenAI, { AzureOpenAI } from "openai";
import { TokenMeterClient, wrapOpenAI, wrapAzureOpenAI } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY! });
const openai = wrapOpenAI(new OpenAI(), tl);
const growth = wrapOpenAI(new OpenAI(), tl, { team: "growth" }); // tags every call from this client
// Azure OpenAI. Reads AZURE_OPENAI_API_KEY and AZURE_OPENAI_ENDPOINT from the environment.
const azure = wrapAzureOpenAI(new AzureOpenAI({ apiVersion: "2024-10-21" }), tl, undefined, {
deploymentModelMap: { "prod-summarizer": "gpt-4o-mini" },
});wrap() changes and returns the same client object, not a copy. In Python, wrapping a client twice does nothing the second time; in TypeScript, wrap each client once (a second wrap records every call twice). On Azure, the map matters for the Responses API, which reports your deployment name instead of the model; a deployment that is not in the map is recorded under its own name and shows as unpriced.
OpenAI-compatible providers. wrapOpenAICompatible(client, tl, provider, defaults?) (TypeScript) or tokenmeter.wrap_openai_compatible(client, provider) (Python) records an OpenAI client pointed at another provider's address under that provider: openrouter, xai, mistral, fireworks, together, deepinfra or vercel_gateway.
Anthropic on Bedrock or Vertex. wrapAnthropic(client, tl, defaults?, { provider }) records AnthropicBedrock calls as bedrock and AnthropicVertex calls as google on its own. Pass provider only when it can't tell the class (a subclass or a minified build).
Vercel AI SDK. tokenmeterMiddleware(tl, defaults?, options?), used with wrapLanguageModel. See Frameworks.
action
action(name, attrs, fn)Names a piece of work and tags every metered call inside it, for example with the customer it was for. See Attribution for every field and how tags pass to nested work. TypeScript's attrs takes customerRef, feature, team, environment, project, memberRef, tags and optimization. Python accepts customer_ref as another name for customer_id.
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: "acme", feature: "reports" }, async () => {
await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Write a one-line status update." }],
});
});current
current(): ActionContext | undefinedReturns the tags of the action() you are inside, or nothing when you are not inside one.
import { action, current } from "@tokenmeter/sdk";
await action("nightly-export", { customerRef: "acme" }, async () => {
console.log(current()?.customerRef); // "acme"
});
console.log(current()); // undefined: no action() is open herestep
step(name, kind, fn, attrs?)Marks one step of an agent request that is not an action: a tool call, a retrieval, a plan or a hand-off to another agent. kind is tool, retrieval, plan, agent or other. Model calls made inside it attach to it on the trace page, and it keeps the enclosing action()'s tags. attrs takes identifiers only: tool_name, tool_type, tool_call_id, agent_name, agent_id, step_index. A retrieval step also takes mode, top_k, index and documents (ranked ids and scores, up to 50), or sets them from inside the step with record_retrieval() / recordRetrieval(); see Retrieval detail. Every action() also sends a step when it closes. Steps go to POST /v1/steps:batch with their own small buffer, after usage records, and never carry tokens or cost. See Agent steps.
import { action, step } from "@tokenmeter/sdk";
await action("answer ticket", { customerRef: "acme" }, async () => {
const order = await step("look up order", "tool", () => orders.get(orderId), { tool_name: "orders_api" });
});attach
attach(ctx, fn): TCarries an action()'s tags across a hop they can't follow on their own, such as a job queue or a thread pool. Capture them with current() where the work is created, and restore them where it runs. See the escape hatch example.
import { action, current, attach } from "@tokenmeter/sdk";
// Where the work is created, inside an action():
const ctx = await action("nightly-export", { customerRef: "acme" }, async () => current());
// Later, on the far side of a queue or timer:
if (ctx) {
attach(ctx, () => {
// metered calls made in here carry ctx's tags
});
}flush
client.flush(): Promise<FlushResult>Sends buffered events now instead of waiting for the next background send. It never raises an error into your code. Call it before a short script exits. The two languages behave differently:
- Python sends batch after batch until the buffer is empty, a send fails, or
deadline_sseconds have passed. - TypeScript first waits for a send that is already running, then sends batch after batch until the buffer is empty or a send fails. It resolves
{ sent, ok }:sentis how many events this call delivered, andokis false if a send failed.
tokenmeter.shutdown() (Python) and await client.shutdown() (TypeScript) do a flush and then stop the background sender. SDK 0.2.2 or later.
In SDK 0.2.0, TypeScript flush() sent one batch per call and returned at once while another send was running. Use 0.2.1 or later.
import { TokenMeterClient } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY! });
// ... your script's work ...
const { sent, ok } = await tl.flush(); // sends everything still buffered
if (!ok) console.warn(`Token Meter: ${sent} events sent, then a send failed`);On serverless Node, use the helpers flushOnWaitUntil, flushBeforeReturn or createServerlessClient. They call flush(), which sends everything the request recorded. See Frameworks › Serverless.
diagnose
diagnose(ingest_key=None, endpoint=None) -> dictPython onlyAnswers "why do I see no data in my dashboard?". It checks your key against ingest right away, prints a clear verdict, and returns { ok, status, message }. Unlike the rest of the SDK, it is meant to be loud. Python only.
import os
import tokenmeter
tokenmeter.init(ingest_key=os.environ["TOKEN_METER_KEY"])
result = tokenmeter.diagnose()
# A good key prints:
# [tokenmeter diagnose] OK: tokenmeter: ingest key valid, endpoint reachable (https://ingest.timewastevc.com).
# and returns {"ok": True, "status": 400, ...}
#
# A wrong key prints:
# [tokenmeter diagnose] FAILED: tokenmeter: invalid_key: the ingest key is wrong or malformed. Check tokenmeter.init(ingest_key=...).status: 400 with ok: True is the expected answer for a good key. diagnose() sends an empty batch, which ingest refuses as invalid_envelope only after the key has passed. Nothing is stored.
TypeScript has no diagnose() yet. Pass an onError function to TokenMeterClient to see failures, or run the ingest curl example with the same key.
Governance preflight
new GovernanceClient(config).preflight(req) / .guard(req, call)For calls you make to a provider directly (not through the router). Preflight first asks the router whether the call is allowed, under the same model, provider, data and cost rules a routed call gets. Calls made inside governed() / guard() carry the decision id as tags.preflight_id, so the dashboard can show them as checked.
Preflight is on the request path
Unlike metering, preflight adds one request to the router before your call (2-second timeout by default), and it can stop the call. In the defaultenforce mode, a denial raises GovernanceDenied / GovernanceDeniedError. No answer counts as "router unavailable": no network, a timeout, or a router outage (503). In Python, a missing router_url counts too. With the default fail mode closed, that raises GovernanceUnavailable / GovernanceUnavailableError. With fail mode open, the call goes ahead unchecked and the decision has failedOpen / failed_open set to true. If you use open, check that flag. A wrong or revoked key (401, 403) or a bad request (400) is different: it raises GovernanceRejected / GovernanceRejectedError in either fail mode, because it is not an outage. (SDK 0.2.0 counted those as "router unavailable" too.)import OpenAI from "openai";
import { TokenMeterClient, wrapOpenAI, GovernanceClient } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({ apiKey: process.env.TOKEN_METER_KEY! });
const openai = wrapOpenAI(new OpenAI(), tl); // calls OpenAI directly, with OPENAI_API_KEY
const gov = new GovernanceClient({
apiKey: process.env.TOKEN_METER_KEY!,
routerUrl: "https://router.timewastevc.com",
mode: "enforce", // or "advisory"
failMode: "closed", // or "open"
timeoutMs: 2000,
});
const prompt = "Summarise this quarter's support tickets.";
const reply = await gov.guard(
{ provider: "openai", model: "gpt-4o-mini", content: prompt, maxOutputTokens: 800 },
() =>
openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: prompt }],
max_tokens: 800,
}),
);
console.log(reply.choices[0].message.content);The request takes provider, model and, optionally: team and environment (both default to the open action()), dataClassification / data_classification, content (the router classifies it in memory and stores only the class labels), estimatedInputTokens / estimated_input_tokens and maxOutputTokens / max_output_tokens.
| TypeScript | Python | Meaning |
|---|---|---|
| allowed | allowed | Whether the call may go ahead. |
| preflightId | preflight_id | The decision id, attached to the usage. |
| expiresAt | expires_at | When the decision stops being valid. |
| violations | violations | The rules the call breaks: policyId, kind, severity, reason (Python: plain dicts with policy_id). |
| dataClasses | data_classes | Data classes found in content. |
| estimatedTotalTokens, estimatedMaxCostUsd | estimated_total_tokens, estimated_max_cost_usd | The router's token and cost estimate. |
| failedOpen | failed_open | true when fail mode open let the call through unchecked. |
In TypeScript, withPreflight(id, fn) and activePreflightId() attach or read a decision id yourself.
Optimization & topics
optimization: { promptCaching?, maxCompletionDelayMs?, topicClassifier? }Opt-in measurements that feed the dashboard's Improvements. They never change the request you send. Set them on the client or on any action() (an inner action() overrides an outer one, and null / None turns an inherited setting off). Python uses the keys prompt_caching, max_completion_delay_ms and topic_classifier.
promptCaching: truefingerprints the opening system and developer instructions on your machine. Only a keyed hash and size ranges are sent, never the text.maxCompletionDelayMs(1,000 to 86,400,000) says how long this work could wait, so savings from cheaper batch prices can be estimated.topicClassifieris a function you supply. It gets the latest user message (first 2,000 characters) inside your process and returns a topic key matching^[a-z][a-z0-9_]{1,39}$, sent astags.prompt_topic. The text never leaves your process. A classifier that throws, returns a Promise, or returns anything else is ignored.keywordTopicClassifier/keyword_topic_classifieris a built-in one that matches keywords, andlatestUserText/latest_user_textpulls out the same text the SDK would hand your classifier.
import { TokenMeterClient, keywordTopicClassifier } from "@tokenmeter/sdk";
const tl = new TokenMeterClient({
apiKey: process.env.TOKEN_METER_KEY!,
optimization: { promptCaching: true, topicClassifier: keywordTopicClassifier },
});Read API
new TokenMeterReadClient({ apiKey, baseUrl }).listDailyUsage({ start, end, limit?, cursor? })Reads your daily usage and cost back out, page by page. It calls the read API, so the rows, limits and errors are the same. It needs a read key (tl_admin_…); the client refuses any other key when you create it. baseUrl is https://timewastevc.com. Errors raise ReadApiError with status and code (status 0 in Python when the address can't be reached). Python also exports the class as ReadApiClient.
import { TokenMeterReadClient } from "@tokenmeter/sdk";
const reader = new TokenMeterReadClient({
apiKey: process.env.TOKEN_METER_READ_KEY!,
baseUrl: "https://timewastevc.com",
});
let cursor: string | undefined;
do {
const page = await reader.listDailyUsage({ start: "2026-10-01", end: "2026-10-31", limit: 500, cursor });
for (const row of page.data) console.log(row.date, row.model, row.pricedCostUsd);
cursor = page.pagination.nextCursor ?? undefined;
} while (cursor);Recall
new RecallClient({ routerUrl, apiKey, sessionId, minToolResultBytes?, retentionDays? })TypeScript onlyFor AI agents that run through the router. With Agent Recall on, the router moves large tool results out of the conversation and leaves a short recall_id in their place, which keeps each request smaller. The model gets a tokenmeter_recall tool to fetch one back when it needs the exact text, and your loop runs that tool with execute(). Turn Recall on first under Router › Caching › Advanced › Agent Recall, and list the tools it may archive (see Gateway & routing › Agent Recall). Without the SDK, that docs section also has the JSON definition of the tokenmeter_recall tool and the retrieve request.
apiKeymust be yourtl_live_…key; any other key is refused when you create the client. Use the same key that sent the agent's requests: the router returns an archived result only to the key that sent it, in the same session. Any other key gets404 recall_not_found.sessionIdis 1 to 200 characters. Use a new one for each agent run, and keep it for the whole run.minToolResultBytesis 1,024 to 1,000,000 andretentionDaysis 1 to 30.execute()throws if the id is malformed, or if the router answers with an error, such as404 recall_not_foundonce the item has expired. Catch it and give the model a short message instead, so one expired item doesn't stop the run.
import OpenAI from "openai";
import { randomUUID } from "node:crypto";
import { createRecallClient } from "@tokenmeter/sdk";
const openai = new OpenAI({
apiKey: process.env.TOKEN_METER_KEY!, // the router takes your tl_live_… key
baseURL: "https://router.timewastevc.com/v1",
});
const recall = createRecallClient({
routerUrl: "https://router.timewastevc.com",
apiKey: process.env.TOKEN_METER_KEY!,
sessionId: randomUUID(), // one id per agent run
});
const myTools: OpenAI.Chat.ChatCompletionTool[] = []; // your own tools go here
const messages: OpenAI.Chat.ChatCompletionMessageParam[] = [
{ role: "user", content: "Look up order 1042 and summarise its history." },
];
const res = await openai.chat.completions.create({
model: "auto",
messages,
tools: [...myTools, recall.tool],
...recall.requestMetadata(), // adds { recall: { enabled: true, session_id, ... } }
} as OpenAI.Chat.ChatCompletionCreateParamsNonStreaming);
const reply = res.choices[0].message;
messages.push(reply);
for (const call of reply.tool_calls ?? []) {
if (call.type === "function" && call.function.name === "tokenmeter_recall") {
try {
const item = await recall.execute(JSON.parse(call.function.arguments)); // { recallId, toolName, content, contentSha256 }
messages.push({ role: "tool", tool_call_id: call.id, content: item.content });
} catch {
messages.push({ role: "tool", tool_call_id: call.id, content: "That archived result is no longer available." });
}
}
}
// Send messages back in your next request to continue the run.Config options
Both SDKs share the same defaults. Names follow each language's style, and a few options exist in only one. In Python, pass buffer_size, flush_interval_s and flush_batch_size as extra keyword arguments to tokenmeter.init().
| TypeScript | Python | Default | Meaning |
|---|---|---|---|
| apiKey | ingest_key | none | Your tl_live_… ingest key. Empty or missing turns metering off: a warning, no network calls, and wrappers return your client unchanged (SDK 0.2.2 or later). TypeScript's apiKey is optional; Python's ingest_key is a required argument, but an empty string or None turns metering off the same way. |
| endpoint | endpoint | https://ingest.timewastevc.com/v1/events:batch (TS) · https://ingest.timewastevc.com (Python) | Where events go. TypeScript takes the full batch URL; Python takes the address only. You only change it if Token Meter gives you a different address. |
| flushIntervalMs | flush_interval_s | 2000 ms / 2.0 s | How often the SDK sends in the background. The unit differs by language. |
| flushBatchSize | flush_batch_size | 500 | Events per batch, capped at 1,000, and the SDK sends early once this many are waiting. (Python 0.2.0 sent the whole buffer in one request; see the note below.) |
| bufferCapacity | buffer_size | 10,000 | How many events the SDK holds while waiting to send. Past it, the oldest are dropped and the drop is counted. |
| optimization | optimization | off | Opt-in measurements. See Optimization & topics. |
| disableBackgroundFlush | n/a | false | Turn off background sending. Needed on serverless runtimes that freeze between requests. See Frameworks. |
| onError | n/a | does nothing | Called with any error the SDK swallows. Python logs to the tokenmeter logger instead. |
| fetchImpl | n/a | global fetch | A replacement fetch, mainly for tests. |
| n/a | router_url | unset | The router address (https://router.timewastevc.com). Turns on tokenmeter.preflight() and governed(). |
| n/a | governance_mode | "enforce" | Python preflight: "enforce" raises on a denial, "advisory" only records it. TypeScript sets mode on GovernanceClient. |
| n/a | governance_fail_mode | "closed" | What preflight does when it gets no clean answer (router unreachable, a timeout, a server error): "closed" raises, "open" lets the call through unprotected. TypeScript sets failMode on GovernanceClient. |
Python SDK 0.2.0: a backlog over 1,000 events stopped delivery
Version 0.2.1 sends a backlog as several batches; upgrade withpip install -U tokenmeter-sdk. On 0.2.0: each send takes everything in the buffer, whatever flush_batch_size says. Ingest accepts at most 1,000 events per batch. So if more than 1,000 events pile up (for example while ingest was unreachable, or in a very busy process), ingest refuses the batch with 413 batch_too_large. The SDK then retries the same batch every 2 seconds and delivers nothing more until the process restarts. It logs this only at debug level. If you can't upgrade yet, pass buffer_size=1000 to tokenmeter.init(). A send can then never exceed the limit; in a long outage the oldest events are dropped and the drop is counted on the dashboard. The TypeScript SDK is not affected. See Reliability › Delivery model.Wire event shape
WireEvent is one entry in a batch's events list: one AI call, with its token counts and tags. It is what the SDK sends and what you send in the ingest request. A null means "not known", not zero; the SDK never guesses.
{
"event_id": "0193a8f4-6c1e-7b2a-9f3d-2e5b7c8d9a01",
"occurred_at": "2026-11-14T10:03:11.482Z",
"provider": "openai",
"model_raw": "gpt-4o-mini",
"input_tokens": 812,
"output_tokens": 143,
"cache_read_tokens": null,
"cache_write_tokens": null,
"reasoning_tokens": null,
"latency_ms": 641,
"is_batch": false,
"usage_complete": true,
"error_code": null,
"trace_id": "0193a8f4-6c1d-7f00-8a11-4b2c3d4e5f60",
"parent_span_id": null,
"action": "generate-report",
"customer_ref": "acme",
"feature": "reports",
"team": null,
"environment": null,
"project": null,
"member_ref": null,
"tags": {},
"sdk_version": "0.2.2"
}- Required:
event_id(a UUID; the SDK uses UUIDv7),occurred_at(an ISO 8601 time),providerandmodel_raw. Everything else is optional. provideris one ofopenai,anthropic,google,bedrock,azure_openai,openrouter,xai,mistral,fireworks,together,deepinfra,vercel_gateway,litellmorother.team,environmentandprojectare trimmed and lowercased, then must match^[a-z0-9][a-z0-9_.:-]{0,63}$; a value that still doesn't is dropped (and named in the batch'swarnings).- This is the TypeScript SDK's shape. The Python SDK leaves out
sdk_version, sendstagsonly when it has some, and adds"provenance": "sdk". Ingest accepts both.
An event is held back (stored for review, not counted) when:
event_idis missing or not a UUID;occurred_atis missing, unreadable, before midnight UTC 90 days ago, or more than 2 hours ahead;provideris missing or not in the list, ormodel_rawis missing;- a token count is negative, not a whole number, or over 10^15;
unitsis negative or over 10^12;authoritative_cost_usdis negative or over 1,000,000,000 (held asnumber_out_of_range);tagsis over 2,048 bytes.
Some fields are dropped instead, and named in the batch's warnings, so the event is still counted: a trace_id or parent_span_id over 128 characters, a latency_ms that is negative or over 2,147,483,647, an authoritative_cost_usd that is not a number, and web_search_requests on any provider other than anthropic (only Anthropic has a per-search price). Null characters are removed from every string before it is stored.
Held events are listed under Calls held for review, behind the Quality link at the foot of Data health › Readiness. A problem with the batch itself rather than one event (a missing or non-UUID batch_id, a missing sdk.name or sdk.version, an empty events list) rejects the whole request with 400 invalid_envelope, and nothing is held.
The SDK adds some tags on its own: preflight_id inside a governed call, prompt_topic and the optimization measurements when you opt in, and otel_trace_id / otel_span_id when an OpenTelemetry span is active. The OpenTelemetry ids let ingest spot the same call arriving through an OpenTelemetry instrumentation too, and keep only one copy.
Other exports
The main exports are documented above. The rest:
normalizeOpenAIUsage,normalizeAnthropicUsage,mergeAnthropicStreamUsage,normalizeGeminiUsage,normalizeBedrockConverseUsage,normalizeBedrockInvokeAnthropicUsage,normalizeBedrockInvokeNovaUsage,normalizeBedrockInvocationMetrics,bedrockInvokeFamilyOfandnormalizeAzureOpenAIUsage(TypeScript): the per-provider token counters the wrappers use, exported so you can build events by hand. See how token counts are worked out on Providers.uuidv7()(TypeScript): the id generator used forevent_idand trace ids.- Types (TypeScript):
WireEvent,BatchPayload,BatchAck,DailyUsage,DailyUsagePage,PreflightDecision,TokenMeterConfig,FlushResultand the others named on this page. - Python classes:
TraceContext(whatcurrent()returns),PreflightDecisionandReadApiError. SDK_NAME,SDK_VERSION,SCHEMA_HASH(TypeScript) and the Python package's__version__.