VynarisEarly beta
Get my API key

How to Track LLM API Cost per Request (With Python)

Track LLM API cost per request: split usage into uncached, cache-write, cache-read and output tokens (reasoning included), multiply by each rate. Python code for OpenAI and Claude, plus gateways that return cost.

TL;DR: To track LLM API cost per request, read the usage object of every response, split input into uncached, cache-write and cache-read tokens, count reasoning tokens as output, and multiply each bucket by its own rate. On gpt-6.2-sol one request in our example costs $0.0367, while the naive input-plus-output formula says $0.046. Vynaris skips the rate card: every response carries its cost in x-vynaris-cost-usd and in a per-request ledger.

Get a Vynaris API key and read the cost of every call from its response headers.

LLM cost per request is the sum of each token bucket in the response's usage object times that bucket's price per million tokens. Providers bill four or five buckets now, not two: uncached input, cache writes, cache reads, output, and reasoning tokens, which are billed as output. You get the right number when you log those buckets per call with a request id and a team or feature tag, then multiply by a rate card that matches the exact model and tier. Prices below were verified on 2026-11-29.

What does Vynaris do for cost per request?

Vynaris is an OpenAI-compatible chat completions gateway at https://api.vynaris.com/v1. For this job it removes the rate card from your code:

What it does not do: Vynaris does not tag cost by team or customer for you. You store the request id next to your own tag (step 5 below works the same way). If you call providers directly, the DIY steps below give you the same number.

What you need

Model (Standard tier)InputCache writeCache readOutput
gpt-6.2-sol$2.00$2.50 (30m)$0.10$10.00
gpt-6.2-astra$8.00$10.00 (30m)$0.40$40.00
Claude Sonnet 5.5$2.00$2.50 (5m)$0.10$10.00

All prices are per 1M tokens, read 2026-11-29 from OpenAI and Anthropic. For every model in one place, see our OpenAI API pricing and Claude API pricing pages.

How do I calculate the cost of one LLM API call?

Follow these steps once and every call gets a cost.

  1. Capture the usage object on every response. With the OpenAI Responses API it sits on resp.usage:
from openai import OpenAI
client = OpenAI()
resp = client.responses.create(model="gpt-6.2-sol", input="Summarize this ticket ...")
u = resp.usage
print(u.input_tokens, u.input_tokens_details.cached_tokens,
      u.input_tokens_details.cache_write_tokens,
      u.output_tokens, u.output_tokens_details.reasoning_tokens)
  1. Split input into three buckets. OpenAI counts cached_tokens and cache_write_tokens inside input_tokens, so uncached input is what is left. Cache-write pricing "is not an additive fee": each input token is billed at exactly one of the three rates (OpenAI prompt caching).
uncached = u.input_tokens - u.input_tokens_details.cached_tokens - u.input_tokens_details.cache_write_tokens
  1. Count reasoning tokens as output. Reasoning tokens are billed as output tokens and are already inside output_tokens (OpenAI reasoning guide). Do not add them twice, and do not estimate output from the visible text.
  2. Multiply each bucket by its rate. Keep the rate card in one dict keyed by model and tier:
RATES = {  # USD per 1M tokens, OpenAI Standard tier, read 2026-11-29
    "gpt-6.2-sol": {"in": 2.00, "write": 2.50, "read": 0.10, "out": 10.00},
}

def openai_cost(model, u):
    r = RATES[model]
    d = u.input_tokens_details
    uncached = u.input_tokens - d.cached_tokens - d.cache_write_tokens
    return (uncached * r["in"] + d.cache_write_tokens * r["write"]
            + d.cached_tokens * r["read"] + u.output_tokens * r["out"]) / 1_000_000
  1. Store one row per call with an owner tag. Write the cost with the request id, model, tier, and your team, feature and customer_id tags. Cost attribution is a GROUP BY on that table:
-- cost per feature, last 30 days
SELECT feature, SUM(cost_usd) AS usd, COUNT(*) AS calls
FROM llm_calls
WHERE created_at > now() - interval '30 days'
GROUP BY feature ORDER BY usd DESC;
  1. Reconcile against the invoice monthly. Sum your rows per model and compare with the provider's usage dashboard. A gap of more than a few percent usually means a missing tier, a missing cache bucket or retried calls you did not log.
Raw usage fields are split into buckets and multiplied by their rates to give one cost
One rate per bucket; the buckets never overlap.

Worked example: one gpt-6.2-sol request

Take a request with 20,000 input tokens: 12,000 read from cache, 3,000 written to cache and 5,000 uncached. It returns 1,800 output tokens, 1,200 of them reasoning and 600 visible.

BucketTokensRate per 1MCost
Uncached input5,000$2.00$0.0100
Cache write (30m)3,000$2.50$0.0075
Cache read12,000$0.10$0.0012
Output (incl. 1,200 reasoning)1,800$10.00$0.0180
Total20,000 in / 1,800 out$0.0367

The naive formula, all 20,000 input at $2.00 plus the 600 visible output tokens at $10.00, gives $0.0400 + $0.0060 = $0.0460. That is 25% too high on input and misses two thirds of the output. Run your own token mix through the Vynaris cost calculator to see how the buckets move the total.

The naive formula and the bucketed formula give different costs for the same request
gpt-6.2-sol Standard rates, read 2026-11-29.

Through Vynaris the same call, if served by gpt-6.2-sol, bills at the provider list price plus the 3% fee: $0.0367 x 1.03 = $0.0378, and that charge comes back in the response instead of being computed by you.

Do cached and reasoning tokens change the cost per request?

Yes, in both directions. Cache reads cut input cost: on gpt-6.2-sol they are $0.10 against $2.00, a 0.05x rate that OpenAI applies to GPT-6.2 Astra, GPT-6.2 Sol, GPT-6.1 Sol and GPT-6.1 Terra (most other models read at 0.1x). Cache writes raise it: 1.25x input for the default 30-minute lifetime and 2.5x for 12 hours. Reasoning tokens raise output cost and are invisible in the reply text. OpenAI also notes a response can end at max_output_tokens before any visible output, so you pay for input and reasoning with nothing to show. Log those calls too.

Two details catch teams out. OpenAI rounds reported cached_tokens down to a multiple of 128. And a prompt below the cache minimum is simply not cached, with no error. For the mechanics, see our prompt caching examples and why cache reads dominate agent costs.

How is Anthropic's usage object different?

Anthropic reports cache tokens beside input_tokens, not inside it. Its docs give total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens (Anthropic prompt caching). If you reuse the OpenAI subtraction here, you get negative uncached input.

SONNET = {"in": 2.00, "write_5m": 2.50, "read": 0.10, "out": 10.00}  # per 1M, 2026-11-29

def claude_cost(u, r=SONNET):
    return (u.input_tokens * r["in"] + u.cache_creation_input_tokens * r["write_5m"]
            + u.cache_read_input_tokens * r["read"] + u.output_tokens * r["out"]) / 1_000_000

A Claude Sonnet 5.5 call with 4,000 input, 30,000 cache-read and 900 output tokens costs $0.0080 + $0.0030 + $0.0090 = $0.0200. Sonnet 5.5 and Opus 5.5 read cache at 0.05x; other Claude models at 0.1x. If both cache fields are 0, the prompt was not cached.

How do I attribute LLM cost to a team, feature or customer?

Tag at the call site, not later. Pass the tag into the function that makes the request and write it into the same row as the cost. Use a fixed set of keys (team, feature, customer_id, env) so the rollups stay clean. For multi-step agents, also store a trace_id so you can sum the cost of one task, not one call. With Vynaris, store x-vynaris-request-id with your tags and join it to /v1/ledger rows; the ledger already holds the cost, so your table needs only the id and the tags.

curl -s https://api.vynaris.com/v1/ledger -H "Authorization: Bearer $VYNARIS_KEY"

Which gateways return cost per request?

GatewayWhere cost appearsWhat you maintain
Vynarisvynaris.cost_usd in body, x-vynaris-cost-usd header, GET /v1/ledgerTags only
OpenRouterusage.cost and cost_details in every responseTags only
LiteLLMresponse._hidden_params["response_cost"], completion_cost()Self-hosted proxy and its price map
Direct provider APIToken counts onlyRate card per model and tier

Sources, read 2026-11-29: Vynaris docs, OpenRouter usage accounting (usage details are now always included; usage: {include: true} is deprecated), LiteLLM token usage. OpenRouter does this well with no setup. LiteLLM is open source and runs in your own network. Vynaris also returns direct_equivalent_usd, what the requested model would have cost at list price, so you see routing savings per call. More on the category in what is an LLM gateway.

How to verify it worked

Common errors and fixes

FAQ

What is the formula for LLM API cost per request?

Cost = uncached input x input rate + cache writes x write rate + cache reads x read rate + output tokens (including reasoning) x output rate, all divided by 1,000,000 when rates are per 1M tokens.

Are reasoning tokens billed?

Yes. OpenAI bills reasoning tokens as output tokens and reports them in output_tokens_details.reasoning_tokens, already counted in output_tokens.

Can I estimate cost with a tokenizer instead of usage fields?

Not reliably. Tokenizers cannot see reasoning tokens or cache hits. Use the usage object the API returns.

Does the OpenAI dashboard show cost per request?

No. It shows aggregate usage. Per-request cost needs your own logging or a gateway that returns it, like Vynaris.

How do I track cost per user?

Store a customer_id on every call row and GROUP BY it. With Vynaris, store the x-vynaris-request-id with the user id and join to the ledger.

Stop maintaining rate cards: get a Vynaris API key, set base_url to https://api.vynaris.com/v1, and read x-vynaris-cost-usd on every response.