# Gemini Cost Tracking: Build a Usage Logger for the Gemini API in Python

> Source: <https://dev.to/hammad_malik_d39574d24320/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python-5bl5>
> Published: 2026-11-23 10:31:32+00:00

**Recommendation:** Log fresh, cached, visible-output and thinking tokens separately from usage_metadata and price each at its own rate, since prompt_token_count includes cache hits and candidates_token_count omits thinking.
More in the playbook "Controlling LLM cost": <https://wpnews.pro/playbooks/llm-cost>

*Originally published at [API Cost Lab](https://www.apicostlab.com/2026/11/gemini-cost-tracking-build-usage-logger.html).*

*Last updated: November 2026*

Gemini cost tracking is a small wrapper around your Gemini API calls that reads the `usage_metadata` on every response, splits it into fresh input, cached input, visible output, thinking tokens, and tool-use tokens, prices each bucket at the rate Google publishes for your model, and writes one JSON line per call to a file. Put it between your code and the `google-genai` client, and the next time your Gemini bill looks wrong you can point at the exact feature and the exact token bucket that produced it. If you already built the [OpenAI version of this wrapper](https://www.apicostlab.com/2026/10/openai-cost-tracking-middleware-build.html) or the [Claude version](https://www.apicostlab.com/2026/11/anthropic-cost-tracking-build-claude.html), this is the Gemini twin — the same sixty-line shape, but Gemini's usage object hides its two most expensive surprises inside totals that look innocent.

The first surprise is thinking tokens. The second is cached tokens folded into the prompt total. A logger that reads the two fields that look like totals — prompt tokens and output tokens — gets both wrong at once, in opposite directions, and the errors cancel just enough that the monthly total looks plausible while every per-feature number is fiction.

Every `generate_content` response carries a `usage_metadata` object with six fields that matter for pricing: `prompt_token_count` for everything sent in, `cached_content_token_count` for the part of the prompt served from cache, `candidates_token_count` for the visible answer, `thoughts_token_count` for the model's hidden reasoning, `tool_use_prompt_token_count` for tool results fed back in as input, and `total_token_count`, which is the sum of the first four groups. Two facts about that list do all the damage. First, `prompt_token_count` already includes the cached tokens, so it is not the fresh-input count. Second, `candidates_token_count` does not include thinking — thoughts are a separate field, billed at the output rate, and they never appear in `response.text`.

On Gemini 2.5 Flash, verified 13 November 2026 on Google's pricing page, fresh text input costs $0.30 per million tokens, cached input costs $0.03, and output — visible answer plus thinking — costs $2.50. Audio input is a different price entirely at $1.00 per million, more than triple the text rate, with cached audio at $0.10. Take one call with 10,000 fresh text tokens, a 50,000-token document served from cache, 1,000 tokens of visible answer, and 2,000 thinking tokens. The arithmetic on the published rates is: fresh input 10,000 × $0.30 ÷ 1,000,000 = $0.003; cached input 50,000 × $0.03 ÷ 1,000,000 = $0.0015; output (1,000 + 2,000) × $2.50 ÷ 1,000,000 = $0.0075. Total: $0.012 — and thinking is nearly two-thirds of the output bill on a call whose answer is only 1,000 tokens long.

Now watch what two naive loggers report for that same call. One prices the whole `prompt_token_count` of 60,000 at the fresh rate and reports $0.018 of input — four times the real $0.0045. The other counts only `candidates_token_count` as output and reports $0.0025 instead of $0.0075 — missing two-thirds of the output cost. The first logger over-reports, the second under-reports, and both are reading fields whose names sound like exactly what they want. That is the same invisible-output pattern our [reasoning-tokens investigation](https://www.apicostlab.com/2026/11/reasoning-tokens-invisible-output.html) found on OpenAI: the tokens you pay for are not the tokens you can see.

Install the SDK with `pip install google-genai` and set `GEMINI_API_KEY` in your environment. Save the code below as `gemini_tracker.py` next to your app, and call `track_content()` instead of calling `client.models.generate_content` directly. It appends one JSON line per call to `gemini_costs.jsonl`, stores no prompt or answer text, and returns the original response untouched, so the rest of your code does not change.

``` python
import json
import time
from datetime import datetime, timezone

from google import genai

# Rates per 1M tokens, verified 13 November 2026 on Google's
# Gemini API pricing page (ai.google.dev/gemini-api/docs/pricing).
# Re-check them before you budget. From 1 December 2026,
# gemini-2.5-flash routes to gemini-3.5-flash-lite and gemini-2.5-pro
# routes to gemini-3.8-flash, billed at the new models' rates.
FLASH_RATES = {
    "input_per_million": 0.30,         # fresh text/image/video input
    "input_audio_per_million": 1.00,   # fresh audio input
    "cached_per_million": 0.03,        # cached text/image/video input
    "cached_audio_per_million": 0.10,  # cached audio input
    "output_per_million": 2.50,        # visible output + thinking tokens
}
FLASH_LITE_RATES = {
    "input_per_million": 0.10,
    "input_audio_per_million": 0.30,
    "cached_per_million": 0.01,
    "cached_audio_per_million": 0.03,
    "output_per_million": 0.40,
}
# Pro charges one rate up to 200,000 prompt tokens and a higher rate
# above it -- and the higher rate applies to the whole prompt, not
# just the tokens past the line.
PRO_RATES = {
    "input_per_million": 1.25,
    "input_per_million_over_200k": 2.50,
    "cached_per_million": 0.125,
    "cached_per_million_over_200k": 0.25,
    "output_per_million": 10.00,
    "output_per_million_over_200k": 15.00,
}

client = genai.Client()  # reads GEMINI_API_KEY from the environment

def _rates_for(model, prompt_tokens, audio_input=False):
    """Pick the rate row for this model, prompt size, and modality."""
    if "2.5-pro" in model:
        over = prompt_tokens > 200_000
        return {
            "input": PRO_RATES["input_per_million_over_200k"] if over
                   else PRO_RATES["input_per_million"],
            "cached": PRO_RATES["cached_per_million_over_200k"] if over
                    else PRO_RATES["cached_per_million"],
            "output": PRO_RATES["output_per_million_over_200k"] if over
                    else PRO_RATES["output_per_million"],
        }
    base = FLASH_LITE_RATES if "flash-lite" in model else FLASH_RATES
    if audio_input:
        return {
            "input": base["input_audio_per_million"],
            "cached": base["cached_audio_per_million"],
            "output": base["output_per_million"],
        }
    return {
        "input": base["input_per_million"],
        "cached": base["cached_per_million"],
        "output": base["output_per_million"],
    }

def _cost_usd(usage, rates):
    prompt = usage.prompt_token_count or 0
    cached = getattr(usage, "cached_content_token_count", 0) or 0
    fresh = max(prompt - cached, 0)
    candidates = getattr(usage, "candidates_token_count", 0) or 0
    thoughts = getattr(usage, "thoughts_token_count", 0) or 0
    tool_use = getattr(usage, "tool_use_prompt_token_count", 0) or 0
    # Thinking tokens bill at the output rate. Tool-use tokens are
    # prompt tokens fed back in, so they bill at the input rate.
    cost = (
        fresh * rates["input"]
        + cached * rates["cached"]
        + (candidates + thoughts) * rates["output"]
        + tool_use * rates["input"]
    ) / 1_000_000
    return fresh, cached, candidates, thoughts, tool_use, cost

def track_content(model, contents, feature="unknown",
                  audio_input=False, **kwargs):
    """Drop-in replacement for client.models.generate_content."""
    started = time.monotonic()
    response = client.models.generate_content(
        model=model, contents=contents, **kwargs
    )
    latency_ms = round((time.monotonic() - started) * 1000)

    record = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "feature": feature,
        "model": model,
        "latency_ms": latency_ms,
    }
    usage = getattr(response, "usage_metadata", None)
    if usage is not None:
        rates = _rates_for(
            model, usage.prompt_token_count or 0, audio_input
        )
        fresh, cached, candidates, thoughts, tool_use, cost = _cost_usd(
            usage, rates
        )
        record.update({
            "input_tokens": fresh,
            "cached_tokens": cached,
            "output_tokens": candidates,
            "thinking_tokens": thoughts,
            "tool_use_tokens": tool_use,
            "cost_usd": round(cost, 6),
        })
    else:
        record["note"] = "no usage_metadata returned"

    with open("gemini_costs.jsonl", "a", encoding="utf-8") as f:
        f.write(json.dumps(record) + "\n")
    return response
```

Using it is one line different from a normal call. Replace `client.models.generate_content(model="gemini-2.5-flash", contents=prompt)` with `track_content("gemini-2.5-flash", prompt, feature="support_reply")`. The `feature` label is the most important parameter in the file: it is what you will group by later, so name it after your product ("support_reply", "summariser", "nightly_report"), not your code. Pass `audio_input=True` when the prompt is audio — the wrapper cannot tell from the usage object which modality the prompt tokens were, so you declare it, exactly as the Claude wrapper asks you to declare the cache lifetime. If you send a voice note through the API and leave the default, the input column is priced at $0.30 instead of $1.00 and your log under-reports by two-thirds on that bucket.

After a few calls, `gemini_costs.jsonl` holds lines shaped like the worked example above, with the numbers shown only to illustrate the shape of a record:

```
{"timestamp": "2026-11-13T05:00:00+00:00", "feature": "support_reply",
 "model": "gemini-2.5-flash", "latency_ms": 1840, "input_tokens": 10000,
 "cached_tokens": 50000, "output_tokens": 1000,
 "thinking_tokens": 2000, "tool_use_tokens": 0, "cost_usd": 0.012}
```

Read it from right to left. The cost is the headline, but the five token numbers are the diagnosis. Here thinking is double the visible output, which is normal on a reasoning model with a default thinking budget — but if `thinking_tokens` ever runs ten times the visible answer on a one-line classification, the budget is doing work nobody asked for. If `cached_tokens` sits near `input_tokens` plus the cache, the cache is working; if it stays at zero while you keep sending the same long document, the cache never engaged — on the free tier it cannot, because context caching is a paid-tier feature, which is the first trap below. And if `tool_use_tokens` climbs every turn, an agent loop is feeding tool results back into the prompt, and the cost of that loop belongs to the feature that owns it.

The first trap is the thinking budget. Gemini 2.5 Flash reasons by default, and every thinking token bills at the $2.50 output rate while staying invisible in the answer. When a short reply suddenly costs what a long one used to, check the budget before blaming the model: pass `config=types.GenerateContentConfig(thinking_config=types.ThinkingConfig(thinking_budget=0))` to switch thinking off, or a small number to cap it. The wrapper records the total honestly, because it reads the field the API returns — but it cannot tell you the budget was the problem unless you also log the config you sent, so keep the budget in the same place you keep the model ID.

The second trap is the free tier, and the calendar. The same code costs exactly $0 on the free tier, which makes it tempting to treat the log's dollar column as decoration — until the day you upgrade to paid and identical traffic starts billing, with no code change and no warning in the log. Note the date you flip tiers next to the log file. The same kind of silent change arrives on 1 December 2026, when Google routes `gemini-2.5-flash` requests to `gemini-3.5-flash-lite` and `gemini-2.5-pro` requests to `gemini-3.8-flash`, billed at the new models' rates. The wrapper logs the model ID you asked for, not the one that answered, so after that date re-check the rates dict against Google's pricing page or your log will keep pricing a model you are no longer running. The same date logic applies to Pro's 200,000-token cliff: one token over the line reprices the whole prompt from $1.25 to $2.50 input and $10.00 to $15.00 output, which is why `_rates_for` picks the band from the prompt size instead of trusting a single rate.

The third trap is streaming. A streamed Gemini response does not hand you a complete `usage_metadata` in the normal way: with `client.models.generate_content_stream`, the usage object arrives on the final chunk only. Wrap a streaming call with the code above and log every chunk, and you count one call many times over — or log nothing at all, if you only read the first chunk. Collect the chunks, read usage from the last one, and log once.

A log file nobody reads is decoration. The wrapper earns its keep when a tiny script reads it once a day and tells you only what changed. Start with three summaries, and nothing more: total cost per feature for the last 24 hours, the ten most expensive single calls, and any feature whose daily cost doubled compared with its seven-day average. The first tells you where the money goes, the second tells you what to fix next, and the third is the early warning that catches a runaway job before the month ends.

When a summary surprises you, the log already holds the feature, model, token split, and timestamp you need to act — and if the surprise is one user rather than one feature, the same per-call records feed directly into the [per-user spending guard](https://www.apicostlab.com/2026/11/stop-one-user-from-eating-your-ai.html) we built for that exact problem. To sanity-check the totals against your own token mix, our [AI API Cost Calculator](https://www.apicostlab.com/2026/10/ai-api-cost-calculator-estimate-your.html) lets you plug in your own numbers and compare them with what the log reports. Rates in this tutorial were verified 13 November 2026 on Google's Gemini API pricing page; re-check them before you budget, because Google changes them — the 1 December reroute is the live example.

That measurement habit is the real point of this tutorial, and it completes the set: the OpenAI wrapper, the Claude wrapper, and now the Gemini one, all logging the same shape — one line per call, priced per bucket. Pricing pages tell you what a token costs; only your own log tells you what your app actually spends tokens on — and on Gemini, "what it spends" is five different numbers hiding inside two innocent-looking totals.
