---
title: "How to Track LLM API Cost per Request (With Python)"
description: "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."
canonical: https://vynaris.com/blog/track-llm-api-cost-per-request
author: "Dhrumil Barot"
author_bio: "Dhrumil is an AI inference and LLM infrastructure expert. Dhrumil built Vynaris to make model access, routing and pricing simple and transparent for developers."
published: 2026-11-29
updated: 2026-11-29
---

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

Published 2026-11-29 · By [Dhrumil Barot](https://vynaris.com/about#founder), Founder

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](https://app.vynaris.com/signin) 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:

- Every response body includes a `vynaris` block with `request_id`, `requested_model`, `served_model`, `cost_usd` and `direct_equivalent_usd` ([Vynaris docs](https://vynaris.com/docs)).
- The same facts come back as headers: `x-vynaris-request-id`, `x-vynaris-served-model`, `x-vynaris-cost-usd`, `x-vynaris-baseline-usd` and `x-vynaris-saved`.
- `GET /v1/ledger` returns per-request history: request id, requested and served model, cost, and direct-equivalent cost for each call. `GET /v1/usage` returns balance and aggregate usage.
- Billing is provider list price plus a 3% fee until monthly usage reaches $500, then 1% ([pricing](https://vynaris.com/pricing)). The headers and exportable ledger show the model, provider cost, Vynaris fee and final charge.

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

- Python 3.10+ and the `openai` SDK (or `anthropic` for Claude).
- A rate card per model and tier. OpenAI lists Standard, Batch, Flex, Fast and Ultrafast prices separately ([OpenAI pricing](https://developers.openai.com/api/docs/pricing)); gpt-6.2-sol on Batch is $1.00/$5.00, half of Standard.
- A place to store one row per call: Postgres, ClickHouse or a log pipeline.

| Model (Standard tier) | Input | Cache write | Cache read | Output |
| --- | --- | --- | --- | --- |
| 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](https://developers.openai.com/api/docs/pricing) and [Anthropic](https://platform.claude.com/docs/en/about-claude/pricing). For every model in one place, see our [OpenAI API pricing](https://vynaris.com/blog/openai-api-pricing) and [Claude API pricing](https://vynaris.com/blog/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`:

```python
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](https://developers.openai.com/api/docs/guides/prompt-caching)).

```python
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](https://developers.openai.com/api/docs/guides/reasoning)). 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:

```python
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:

```sql
-- 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](https://cdn.sanity.io/images/u1qdn8dx/production/5b56f92fbd6f2da1be00c34464bd2b0f8ebc9826-1344x326.png?w=1440&fit=max&auto=format)

*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.

| Bucket | Tokens | Rate per 1M | Cost |
| --- | --- | --- | --- |
| Uncached input | 5,000 | $2.00 | $0.0100 |
| Cache write (30m) | 3,000 | $2.50 | $0.0075 |
| Cache read | 12,000 | $0.10 | $0.0012 |
| Output (incl. 1,200 reasoning) | 1,800 | $10.00 | $0.0180 |
| Total | 20,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](https://vynaris.com/calculator) to see how the buckets move the total.

![The naive formula and the bucketed formula give different costs for the same request](https://cdn.sanity.io/images/u1qdn8dx/production/dd8b0ab09d9fbd71e154cd8c56a2972fa9a35ea8-1344x502.png?w=1440&fit=max&auto=format)

*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](https://vynaris.com/blog/prompt-caching-examples) and why [cache reads dominate agent costs](https://vynaris.com/blog/cache-reads-dominate-agent-costs-quadratic-break-even-across-models).

## 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](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)). If you reuse the OpenAI subtraction here, you get negative uncached input.

```python
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.

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

## Which gateways return cost per request?

| Gateway | Where cost appears | What you maintain |
| --- | --- | --- |
| Vynaris | vynaris.cost_usd in body, x-vynaris-cost-usd header, GET /v1/ledger | Tags only |
| OpenRouter | usage.cost and cost_details in every response | Tags only |
| LiteLLM | response.\_hidden_params\["response_cost"\], completion_cost() | Self-hosted proxy and its price map |
| Direct provider API | Token counts only | Rate card per model and tier |

Sources, read 2026-11-29: [Vynaris docs](https://vynaris.com/docs), [OpenRouter usage accounting](https://openrouter.ai/docs/use-cases/usage-accounting) (usage details are now always included; `usage: {include: true}` is deprecated), [LiteLLM token usage](https://docs.litellm.ai/docs/completion/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](https://vynaris.com/blog/what-is-an-llm-gateway).

## How to verify it worked

- Send one call with a known prompt, compute its cost by hand from the usage object, and compare with your stored row.
- Send the same long prompt twice within 30 minutes. The second row should show `cached_tokens` above 0 and a lower cost.
- At month end, your summed rows should match the provider dashboard within a few percent.

## Common errors and fixes

- **Negative uncached input on Claude:** you subtracted cache fields that Anthropic reports separately. Use `input_tokens` as is.
- **\`KeyError: 'gpt-6.2-sol-...'\`:** the response model name is a dated snapshot. Map snapshots to the base model in your rate card.
- **Costs 2x too high after switching to Batch:** your rate card has only Standard prices. Key rates by model and tier.
- **\`402\` from Vynaris:** balance or the key's spend cap hit zero; nothing was charged. Top up, then send a new request.

## 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](https://app.vynaris.com/signin), set `base_url` to `https://api.vynaris.com/v1`, and read `x-vynaris-cost-usd` on every response.

## About the author

[Dhrumil Barot](https://vynaris.com/about#founder), Founder. Dhrumil is an AI inference and LLM infrastructure expert. Dhrumil built Vynaris to make model access, routing and pricing simple and transparent for developers. [LinkedIn](https://www.linkedin.com/in/bdhrumil) · [X](https://x.com/fyidhrumil)
