{"slug": "gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python", "title": "Gemini Cost Tracking: Build a Usage Logger for the Gemini API in Python", "summary": "A developer published a Python wrapper for the Gemini API that reads each response's usage_metadata, splits tokens into fresh input, cached input, visible output, thinking and tool-use buckets, prices each at Google's published rates, and logs one JSON line per call. The writeup shows that prompt_token_count already includes cached tokens and that candidates_token_count excludes thinking tokens, so naive loggers misprice a sample call at $0.018 or $0.0025 instead of the correct $0.012 on Gemini 2.5 Flash. The author notes thinking tokens accounted for nearly two-thirds of the output bill in that example.", "body_md": "*Originally published at [API Cost Lab](https://www.apicostlab.com/2026/11/gemini-cost-tracking-build-usage-logger.html).*\n\n*Last updated: November 2026*\n\nGemini 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.\n\nThe 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.\n\nEvery `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`.\n\nOn 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.\n\nNow 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.\n\nInstall 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.\n\n``` python\nimport json\nimport time\nfrom datetime import datetime, timezone\n\nfrom google import genai\n\n# Rates per 1M tokens, verified 13 November 2026 on Google's\n# Gemini API pricing page (ai.google.dev/gemini-api/docs/pricing).\n# Re-check them before you budget. From 1 December 2026,\n# gemini-2.5-flash routes to gemini-3.5-flash-lite and gemini-2.5-pro\n# routes to gemini-3.8-flash, billed at the new models' rates.\nFLASH_RATES = {\n    \"input_per_million\": 0.30,         # fresh text/image/video input\n    \"input_audio_per_million\": 1.00,   # fresh audio input\n    \"cached_per_million\": 0.03,        # cached text/image/video input\n    \"cached_audio_per_million\": 0.10,  # cached audio input\n    \"output_per_million\": 2.50,        # visible output + thinking tokens\n}\nFLASH_LITE_RATES = {\n    \"input_per_million\": 0.10,\n    \"input_audio_per_million\": 0.30,\n    \"cached_per_million\": 0.01,\n    \"cached_audio_per_million\": 0.03,\n    \"output_per_million\": 0.40,\n}\n# Pro charges one rate up to 200,000 prompt tokens and a higher rate\n# above it -- and the higher rate applies to the whole prompt, not\n# just the tokens past the line.\nPRO_RATES = {\n    \"input_per_million\": 1.25,\n    \"input_per_million_over_200k\": 2.50,\n    \"cached_per_million\": 0.125,\n    \"cached_per_million_over_200k\": 0.25,\n    \"output_per_million\": 10.00,\n    \"output_per_million_over_200k\": 15.00,\n}\n\nclient = genai.Client()  # reads GEMINI_API_KEY from the environment\n\ndef _rates_for(model, prompt_tokens, audio_input=False):\n    \"\"\"Pick the rate row for this model, prompt size, and modality.\"\"\"\n    if \"2.5-pro\" in model:\n        over = prompt_tokens > 200_000\n        return {\n            \"input\": PRO_RATES[\"input_per_million_over_200k\"] if over\n                   else PRO_RATES[\"input_per_million\"],\n            \"cached\": PRO_RATES[\"cached_per_million_over_200k\"] if over\n                    else PRO_RATES[\"cached_per_million\"],\n            \"output\": PRO_RATES[\"output_per_million_over_200k\"] if over\n                    else PRO_RATES[\"output_per_million\"],\n        }\n    base = FLASH_LITE_RATES if \"flash-lite\" in model else FLASH_RATES\n    if audio_input:\n        return {\n            \"input\": base[\"input_audio_per_million\"],\n            \"cached\": base[\"cached_audio_per_million\"],\n            \"output\": base[\"output_per_million\"],\n        }\n    return {\n        \"input\": base[\"input_per_million\"],\n        \"cached\": base[\"cached_per_million\"],\n        \"output\": base[\"output_per_million\"],\n    }\n\ndef _cost_usd(usage, rates):\n    prompt = usage.prompt_token_count or 0\n    cached = getattr(usage, \"cached_content_token_count\", 0) or 0\n    fresh = max(prompt - cached, 0)\n    candidates = getattr(usage, \"candidates_token_count\", 0) or 0\n    thoughts = getattr(usage, \"thoughts_token_count\", 0) or 0\n    tool_use = getattr(usage, \"tool_use_prompt_token_count\", 0) or 0\n    # Thinking tokens bill at the output rate. Tool-use tokens are\n    # prompt tokens fed back in, so they bill at the input rate.\n    cost = (\n        fresh * rates[\"input\"]\n        + cached * rates[\"cached\"]\n        + (candidates + thoughts) * rates[\"output\"]\n        + tool_use * rates[\"input\"]\n    ) / 1_000_000\n    return fresh, cached, candidates, thoughts, tool_use, cost\n\ndef track_content(model, contents, feature=\"unknown\",\n                  audio_input=False, **kwargs):\n    \"\"\"Drop-in replacement for client.models.generate_content.\"\"\"\n    started = time.monotonic()\n    response = client.models.generate_content(\n        model=model, contents=contents, **kwargs\n    )\n    latency_ms = round((time.monotonic() - started) * 1000)\n\n    record = {\n        \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        \"feature\": feature,\n        \"model\": model,\n        \"latency_ms\": latency_ms,\n    }\n    usage = getattr(response, \"usage_metadata\", None)\n    if usage is not None:\n        rates = _rates_for(\n            model, usage.prompt_token_count or 0, audio_input\n        )\n        fresh, cached, candidates, thoughts, tool_use, cost = _cost_usd(\n            usage, rates\n        )\n        record.update({\n            \"input_tokens\": fresh,\n            \"cached_tokens\": cached,\n            \"output_tokens\": candidates,\n            \"thinking_tokens\": thoughts,\n            \"tool_use_tokens\": tool_use,\n            \"cost_usd\": round(cost, 6),\n        })\n    else:\n        record[\"note\"] = \"no usage_metadata returned\"\n\n    with open(\"gemini_costs.jsonl\", \"a\", encoding=\"utf-8\") as f:\n        f.write(json.dumps(record) + \"\\n\")\n    return response\n```\n\nUsing 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.\n\nAfter 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:\n\n```\n{\"timestamp\": \"2026-11-13T05:00:00+00:00\", \"feature\": \"support_reply\",\n \"model\": \"gemini-2.5-flash\", \"latency_ms\": 1840, \"input_tokens\": 10000,\n \"cached_tokens\": 50000, \"output_tokens\": 1000,\n \"thinking_tokens\": 2000, \"tool_use_tokens\": 0, \"cost_usd\": 0.012}\n```\n\nRead 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.\n\nThe 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.\n\nThe 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.\n\nThe 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.\n\nA 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.\n\nWhen 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.\n\nThat 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.", "url": "https://wpnews.pro/news/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python", "canonical_source": "https://dev.to/hammad_malik_d39574d24320/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python-5bl5", "published_at": "2026-11-23 10:31:32+00:00", "updated_at": "2026-11-23 10:42:18.430371+00:00", "lang": "en", "topics": ["ai-tools", "large-language-models", "ai-products", "developer-tools"], "entities": ["Google", "Gemini API", "Gemini 2.5 Flash", "google-genai", "API Cost Lab"], "also_reported_by": [], "takeaway": "Price Gemini calls from all six usage_metadata fields: prompt_token_count already includes cached tokens, and thoughts_token_count is billed at the output rate but excluded from candidates_token_count, which in the sample call made thinking nearly two-thirds of the output cost.", "recommendation": {"advice": "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.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python", "markdown": "https://wpnews.pro/news/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python.md", "text": "https://wpnews.pro/news/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python.txt", "jsonld": "https://wpnews.pro/news/gemini-cost-tracking-build-a-usage-logger-for-the-gemini-api-in-python.jsonld"}}