Explainer · 11 min read
LLM cost tracking: gateway, SDK or OpenTelemetry?
By AI Spendbook · Published · Updated
Short answer
Pick a gateway when you must block requests at a budget, an SDK wrapper when model calls live in one codebase, and OpenTelemetry when you already run tracing. The SDK and OpenTelemetry add no network hop; a gateway does. All three give estimates that split the bill by customer and feature; the billed total still comes from the provider.
Key takeaways
- A gateway is the only one of the three that can reject a request when a budget is spent.
- In Node.js, set customer and feature once per request with AsyncLocalStorage or OpenTelemetry baggage instead of at every call.
- LiteLLM custom callbacks receive each request's tokens, metadata and calculated response_cost, which is an estimate, not the invoice.
- Turn off prompt and response capture at the source: cost tracking needs token counts and tags, never the text.
To split an AI bill by customer and feature you need a record of each model call with the tokens it used and who it was for. There are three common ways to capture that record. They differ in what they see, what they can control, and what they cost in latency and maintenance.
Gateway vs SDK for LLM cost tracking: what are the latency tradeoffs?
| Gateway or proxy | SDK wrapper | OpenTelemetry spans | |
|---|---|---|---|
| Examples | LiteLLM proxy, Helicone gateway, Portkey | A vendor SDK or your own wrapper around the client | OpenLLMetry, OpenInference, Vercel AI SDK telemetry, GenAI semantic conventions |
| Sits in the request path | Yes, every call goes through it | In-process, around the call | In-process; spans are exported in the background |
| Added latency | A network hop per call, plus the gateway's own processing | Usually negligible if events are sent asynchronously | Usually negligible with a batch exporter |
| Can block a request at a budget | Yes | Only if you write that logic | No |
| Sees traffic that bypasses it | No | No, only wrapped calls | No, only instrumented calls |
| Customer and feature tags | Request metadata, headers or per-key tags | Arguments to the wrapper | Span or resource attributes, or baggage from the parent span |
| Failure mode | If it is down, model calls fail unless you route around it | A bug can drop events | A misconfigured exporter drops spans silently |
Latency is the question engineers ask first. An in-process SDK or OpenTelemetry exporter that sends data asynchronously adds almost nothing to the model call. A gateway adds a hop, and its cost depends on where it runs relative to your app and the provider. Measure it on your own traffic before deciding; for most chat workloads the model's own response time dominates.
Which one should you choose?
Answer four questions in order. The first yes decides it; a later yes can add a second method rather than replace the first.
- Must a request be refused when a budget is spent, or rerouted when a provider fails? Use a gateway. Nothing else in this list can stop a call.
- Do your services already export OpenTelemetry traces? Add GenAI instrumentation and send the spans on. You reuse the exporter, the sampling rules and the request context you already have.
- Do model calls live in one or two services you control? An SDK wrapper is the least moving parts: no new network hop, no collector.
- Are calls spread across teams, languages and third-party tools? A gateway again, because it is the one place every call can be forced through, at the cost of the hop.
Many teams end with two: a gateway for production traffic that needs budgets, and an SDK or spans for batch jobs and internal tools that bypass it. That is fine as long as each call is recorded once; give each event a stable id so a call seen by both is not counted twice.
Gateway: control first, tracking second
Choose a gateway when you need to stop requests: budgets per key or team, rate limits, fallbacks between providers. LiteLLM, for example, logs spend per key, user and team, prices each request from its own model cost map, and stores request tags sent as metadata.tags. It also supports custom callbacks: a CustomLogger subclass whose async_log_success_event receives the calculated response_cost and your request metadata, which you can forward to a warehouse or another tool.
LiteLLM proxy: sending spend logs with tags to a custom callback
AI Spendbook ships such a callback in its Python SDK, so you do not have to write one. In a module next to the proxy's config.yaml, call spendbook.init() and set proxy_handler_instance = SpendbookCallback() (from spendbook.integrations.litellm), then list callbacks: spendbook_callback.proxy_handler_instance under litellm_settings. With the LiteLLM SDK instead of the proxy, litellm.callbacks = [SpendbookCallback()] is enough. The LiteLLM quickstart has the full files.
- Provider: LiteLLM's
azurebecomes Azure OpenAI,bedrockBedrock,vertex_aiVertex AI andgeminiGoogle, so usage lands under the bill it belongs to. - Tags:
customer_id,feature,environmentandrun_idcome from requestmetadata, or from tags such ascustomer:acme; LiteLLM'suserbecomes the end user. - Tokens: input, output, cache reads and cache writes. LiteLLM cache hits are not recorded.
- Cost: LiteLLM's
response_costis stored for comparison only, never used as spend. AI Spendbook prices the tokens itself, and the billed total still comes from the provider.
Two limits matter for finance. The gateway's cost is calculated from tokens and a price list, so it will not match the invoice exactly. And it only sees traffic routed through it: a script that calls the provider directly never appears.
SDK wrapper: simplest when there is one codebase
A wrapper around your model client records provider, model, tokens, latency and status, plus the customer and feature you pass in. It works well when model calls live in one service and one language. The weakness is coverage: every new call site has to use the wrapper, and calls made by a third-party library may not.
How do I tag LLM requests with customer_id and feature in Node.js without wrapping every call?
Set the customer and feature once per incoming request instead of at each call. In Node.js, AsyncLocalStorage holds a request context that follows the async call chain, so every model call made while handling that request can read it, and concurrent requests stay apart. With OpenTelemetry, the same job is done by baggage, covered below. With AI Spendbook's Node.js SDK the pattern is three steps:
- Once at startup:
import { init, wrapOpenAI, withContext } from "aispendbook";theninit();andconst openai = wrapOpenAI(new OpenAI());. The key and endpoint come fromSPENDBOOK_API_KEYandSPENDBOOK_ENDPOINT. - In the request handler, around the work:
await withContext({ customerId: req.user.orgId, feature: "support-bot" }, () => handle(req)); - Inside
handle, callopenai.chat.completions.create(...)as usual. Every wrapped call reads the context; nothing is passed to it. In a serverless function,await flush()before returning.
The same SDK wraps Anthropic and Google Gen AI clients and has a Vercel AI SDK middleware. Streamed OpenAI chat completions only carry usage when the request sets stream_options: { include_usage: true }; without it the event is recorded with zero tokens and flagged. The Python SDK does the same with with spendbook.track(customer_id=..., feature=...).
OpenTelemetry: reuse the tracing you already run
If your services already emit traces, model calls can arrive as spans. The OpenTelemetry GenAI semantic conventions name the attributes: gen_ai.provider.name, gen_ai.request.model, gen_ai.usage.input_tokens, gen_ai.usage.output_tokens, and cache read and cache creation counts. OpenLLMetry and OpenInference use their own names for the same fields. The GenAI conventions are still marked as in development, so attribute names can change between versions.
How do I add customer id to OpenTelemetry LLM spans from the parent request span?
The model span is created deep inside a library, far from the code that knows the customer. Put the customer id and feature into OpenTelemetry baggage when the request arrives, then register a baggage span processor, such as @opentelemetry/baggage-span-processor in Node.js, that copies chosen baggage keys onto every span as it starts. Copy only the keys you need: baggage also travels to downstream services in HTTP headers.
Vercel AI SDK
The Vercel AI SDK emits OpenTelemetry spans for its calls. Earlier releases enabled this with the experimental_telemetry option and wrote usage as ai.usage.promptTokens and ai.usage.completionTokens. The current telemetry docs describe a telemetry option and an OpenTelemetry integration that writes the GenAI names, including gen_ai.usage.input_tokens and the cache counts. Check the docs for the version you run.
Do LLM spans leak prompt content?
They can. The GenAI conventions treat message content as sensitive and opt-in, and content capture is off by default in instrumentations that follow them. Not every library follows that default: the Vercel AI SDK's docs say inputs and outputs are recorded by default unless you turn off recordInputs and recordOutputs. Cost tracking needs token counts and tags, never the text. Turn content capture off at the source, and check what your exporter sends before pointing it at a third party.
Count cache tokens once
Providers report cached input differently. Anthropic's input_tokens excludes cache reads and writes, which come as separate fields. OpenAI's input count includes cached tokens, reported as a subset. The GenAI conventions define input as including cache tokens. A pipeline that mixes these without adjusting counts cache tokens twice or not at all.
| Same request, as reported by | Input field | Cache field | Uncached input to price |
|---|---|---|---|
| Anthropic | input_tokens: 200 | cache_read_input_tokens: 8,000 | 200 (input already excludes the cache) |
| OpenAI | prompt_tokens: 8,200 | cached_tokens: 8,000 (a subset of the 8,200) | 8,200 - 8,000 = 200 |
| GenAI span | gen_ai.usage.input_tokens: 8,200 | gen_ai.usage.cache_read.input_tokens: 8,000 | 8,200 - 8,000 = 200 |
Each row should end as 200 uncached input tokens priced at the input rate plus 8,000 cache reads priced at the cache rate. A pipeline that adds OpenAI's 8,200 and 8,000 prices 16,200 tokens; one that ignores Anthropic's cache field prices only 200 and misses most of the cost. Billed vs estimated AI spend explains why the estimate drifts from the bill even when the counts are right.
Where should LLM usage logs go for reporting?
Gateways and observability tools can usually export logs to your own storage, and a gateway callback or an OpenTelemetry collector pipeline can write usage with estimated cost straight to Snowflake or BigQuery. Keep billed cost from the provider in its own table and join the two by day, provider and model, rather than summing them.
If you would rather not build that pipeline, AI Spendbook writes its reconciled ledger to BigQuery, Snowflake, Databricks, Redshift, S3 or Cloud Storage as daily rows: day, provider, ledger kind (billed, estimated or allocated), basis, customer, feature, category and accounting class, with cost in micros and dollars. Each run replaces the day it writes, so reruns do not duplicate rows. Never add rows of different ledger kinds together. Getting AI spend into Google Sheets, Looker or a warehouse compares this with building it yourself.
What are the common mistakes in LLM cost tracking?
- Treating tracked cost as the bill. Gateway and span cost comes from a price list; discounts, credits, non-token charges and provider corrections only show on the invoice.
- Tagging at each call site. Someone forgets one. Set customer and feature once per request with AsyncLocalStorage,
track()or baggage. - Counting wrapper spans. Agent and workflow spans often repeat the usage of the model spans under them. Count only the spans that represent a model call.
- Exporting prompt text by default. Some libraries record inputs and outputs unless told not to. Turn it off before pointing an exporter at anyone else.
- Running two methods without an event id. A call seen by both the gateway and the SDK is counted twice.
When is a gateway not worth it?
When you do not need to block or reroute requests, a gateway adds a dependency in the path of every model call for tracking you can get in-process. If it goes down, model calls fail unless you route around it. A small team with one service and one provider is usually better served by an SDK wrapper and the provider's own spend limit, which the AI spend alerts guide covers.
What finance needs from any of the three
All three produce estimates. They are the key for splitting the bill, not the bill. AI Spendbook reads billed cost from provider APIs and exports, and takes request data from its Python SDK, its Node.js SDK, the LiteLLM callback, gateway connectors such as LiteLLM and Portkey, the ingestion API, or OpenTelemetry traces over OTLP/HTTP. Its receiver reads the GenAI, OpenLLMetry and OpenInference attribute names, takes spendbook.customer_id and spendbook.feature from the span or its resource, ignores agent and workflow wrapper spans so usage is not counted twice, and maps usage and attribution attributes only. It does not proxy requests, so it adds no latency and cannot block a call; keep a gateway if you need that. The SDKs are MIT licensed and are installed from a package file supplied at onboarding; they are not on PyPI or npm yet.
Sources
- OpenTelemetry GenAI semantic conventions: attribute names, status and content capture guidance.
- LiteLLM spend tracking and custom callbacks.
- Vercel AI SDK telemetry.
- OpenTelemetry baggage span processor for Node.js.
- Node.js AsyncLocalStorage: request context that follows the async call chain.
- Anthropic prompt caching and OpenAI prompt caching: how each reports cached tokens.
Frequently asked questions
Does an LLM gateway add latency to every model call?
Yes, one network hop plus the gateway's own processing per call. How much depends on where it runs relative to your app and the provider, so measure it on your own traffic; for most chat workloads the model's response time dominates.
Can OpenTelemetry LLM spans replace the provider bill for finance?
No. Spans carry token counts that are priced from a price list, so they are estimates. They are the key for splitting the bill by customer and feature; the billed total comes from the provider's cost report or invoice.
Which Vercel AI SDK telemetry attributes carry token counts?
Earlier releases wrote ai.usage.promptTokens and ai.usage.completionTokens. Current releases write the GenAI names, such as gen_ai.usage.input_tokens and the cache counts. Check the telemetry docs for the version you run, and turn off recordInputs and recordOutputs if you do not want prompt text exported.