Gemini-Kosten im Blick: Usage-Logger für die Gemini API in Python
Ein Python-Wrapper liest die usage_metadata jeder Gemini-API-Antwort und trennt sie in neue Eingaben, zwischengespeicherte Eingaben und weitere Kategorien, um API-Kosten präzise nachzuverfolgen.

Veröffentlicht am 23. November, ursprünglich publiziert auf apicostlab.com
Gemini-Kostenerfassung ist ein kleiner Wrapper um Ihre Gemini-API-Aufrufe, der bei jeder Antwort die usage_metadata ausliest, sie in neue Eingabe, zwischengespeicherte Eingabe, sichtbare Ausgabe, Thinking-Tokens und Tool-Nutzungs-Tokens aufteilt, jede dieser Kategorien mit dem Tarif abrechnet, den Google für Ihr Modell veröffentlicht, und pro Aufruf eine JSON-Zeile in eine Datei schreibt. Setzen Sie ihn zwischen Ihren Code und den google-genai-Client, und wenn Ihre Gemini-Rechnung das nächste Mal falsch aussieht, können Sie auf das exakte Feature und die exakte Token-Kategorie verweisen, die sie verursacht haben. Wenn Sie die OpenAI-Version dieses Wrappers oder die Claude-Version bereits gebaut haben, ist dies das Gemini-Gegenstück: dieselbe Struktur von rund sechzig Zeilen, aber Geminis Nutzungsobjekt versteckt seine zwei teuersten Überraschungen in Totalen, die harmlos aussehen.
Die erste Überraschung sind Thinking-Tokens. Die zweite sind zwischengespeicherte Tokens, die in die Prompt-Summe eingerechnet sind. Ein Logger, der die beiden Felder liest, die wie Summen aussehen, Prompt-Tokens und Output-Tokens, bekommt beide gleichzeitig falsch, in entgegengesetzte Richtungen, und die Fehler heben sich gerade genug auf, dass die Monatssumme plausibel wirkt, während jede Zahl pro Feature frei erfunden ist.
Jede generate_content-Antwort enthält ein usage_metadata-Objekt mit sechs Feldern, die für die Abrechnung relevant sind: prompt_token_count für alles Gesendete, cached_content_token_count für den Teil des Prompts, der aus dem Cache kommt, candidates_token_count für die sichtbare Antwort, thoughts_token_count für das verborgene Reasoning des Modells, tool_use_prompt_token_count für Tool-Ergebnisse, die als Eingabe zurückgespielt werden, und total_token_count, das die Summe der ersten vier Gruppen ist. Zwei Fakten über diese Liste richten den ganzen Schaden an. Erstens enthält prompt_token_count bereits die zwischengespeicherten Tokens, es ist also nicht die Anzahl frischer Eingabetokens.
Zweitens enthält candidates_token_count kein Thinking: Thoughts sind ein separates Feld, das zum Ausgabetarif abgerechnet wird, und sie erscheinen nie in response.text.
Bei Gemini 2.5 Flash, verifiziert am 13. November 2026 auf Googles Preisseite, kostet frische Texteingabe 0,30 US-Dollar pro Million Tokens, zwischengespeicherte Eingabe 0,03 US-Dollar und Ausgabe, also sichtbare Antwort plus Thinking, 2,50 US-Dollar. Audioeingabe kostet mit 1,00 US-Dollar pro Million einen völlig anderen Preis, mehr als das Dreifache des Texttarifs, mit zwischengespeichertem Audio bei 0,10 US-Dollar.
Nehmen Sie einen Aufruf mit 10.000 frischen Text-Tokens, einem 50.000-Token-Dokument aus dem Cache, 1.000 Tokens sichtbarer Antwort und 2.000 Thinking-Tokens. Die Rechnung mit den veröffentlichten Tarifen lautet: frische Eingabe 10.000 × 0,30 ÷ 1.000.000 = 0,003 US-Dollar; zwischengespeicherte Eingabe 50.000 × 0,03 ÷ 1.000.000 = 0,0015 US-Dollar; Ausgabe (1.000 + 2.000) × 2,50 ÷ 1.000.000 = 0,0075 US-Dollar. Gesamt: 0,012 US-Dollar, wobei Thinking fast zwei Drittel der Ausgabekosten ausmacht, bei einem Aufruf, dessen Antwort nur 1.000 Tokens lang ist.
Sehen Sie nun, was zwei naive Logger für denselben Aufruf melden. Einer berechnet den kompletten prompt_token_count von 60.000 zum frischen Tarif und meldet 0,018 US-Dollar Eingabekosten, das Vierfache der tatsächlichen 0,0045 US-Dollar. Der andere zählt nur candidates_token_count als Ausgabe und meldet 0,0025 statt 0,0075 US-Dollar, womit zwei Drittel der Ausgabekosten fehlen. Der erste Logger meldet zu viel, der zweite zu wenig, und beide lesen Felder, deren Namen exakt nach dem klingen, was sie suchen. Das ist dasselbe Muster unsichtbarer Ausgabe, das unsere Untersuchung zu Reasoning-Tokens bei OpenAI zutage förderte: Die Tokens, die Sie bezahlen, sind nicht die Tokens, die Sie sehen können.
Installieren Sie das SDK mit pip install google-genai und setzen Sie GEMINI_API_KEY in Ihrer Umgebung. Speichern Sie den untenstehenden Code als gemini_tracker.py neben Ihrer Anwendung und rufen Sie track_content() auf, statt client.models.generate_content direkt aufzurufen. Der Wrapper hängt pro Aufruf eine JSON-Zeile an gemini_costs.jsonl an, speichert keinen Prompt- und keinen Antworttext und gibt die Originalantwort unverändert zurück, sodass der Rest Ihres Codes unverändert bleibt.
import json import time from datetime import datetime, timezone from google import genai # Tarife pro 1M Tokens, verifiziert am 13. November 2026 auf # Googles Gemini-API-Preisseite (ai.google.dev/gemini-api/docs/pricing). # Prüfen Sie sie nach, bevor Sie budgetieren. Ab dem 1.
Dezember 2026 # leitet gemini-2.5-flash auf gemini-3.5-flash-lite und gemini-2.5-pro # auf gemini-3.8-flash um, abgerechnet zu den Tarifen der neuen Modelle. FLASH_RATES = { "input_per_million": 0.30, # frische Text-/Bild-/Videoeingabe "input_audio_per_million": 1.00, # frische Audioeingabe "cached_per_million": 0.03, # zwischengespeicherte Text-/Bild-/Videoeingabe "cached_audio_per_million": 0.10, # zwischengespeicherte Audioeingabe "output_per_million": 2.50, # sichtbare Ausgabe + 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 berechnet einen Tarif bis 200.000 Prompt-Tokens und einen # hoeheren Tarif darueber -- und der hoehere Tarif gilt fuer den # gesamten Prompt, nicht nur fuer die Tokens jenseits der Grenze.
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 ( ) # liest GEMINI_API_KEY aus der Umgebung def _rates_for ( model, prompt_tokens, audio_input = False ): """Waehlt die Tarifzeile fuer dieses Modell, diese Prompt-Groesse und Modalitaet.""" 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 werden zum Ausgabetarif abgerechnet. Tool-Nutzungs- # Tokens sind zurueckgespielte Prompt-Tokens und werden zum Eingabetarif # abgerechnet. 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-Ersatz fuer 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 Vollbildmodus öffnen Vollbildmodus schließen Die Nutzung unterscheidet sich in einer Zeile von einem normalen Aufruf.
Ersetzen Sie client.models.generate_content(model="gemini-2.5-flash", contents=prompt) durch track_content("gemini-2.5-flash", prompt, feature="support_reply"). Das Feature-Label ist der wichtigste Parameter in der Datei: Danach gruppieren Sie später, benennen Sie es also nach Ihrem Produkt ("support_reply", "summariser", "nightly_report"), nicht nach Ihrem Code. Übergeben Sie audio_input=True, wenn der Prompt Audio enthält. Der Wrapper kann dem Nutzungsobjekt nicht entnehmen, welcher Modalität die Prompt-Tokens angehörten, Sie deklarieren es also, ganz so wie der Claude-Wrapper verlangt, die Cache-Lebensdauer zu deklarieren.
Wenn Sie eine Sprachnachricht über die API senden und die Standardeinstellung lassen, wird die Eingabespalte mit 0,30 statt 1,00 US-Dollar berechnet, und Ihr Log meldet für diese Kategorie um zwei Drittel zu wenig.
Nach einigen Aufrufen enthält gemini_costs.jsonl Zeilen in der Form des obigen Rechenbeispiels, wobei die Zahlen nur zur Veranschaulichung des Aufbaus eines Datensatzes gezeigt werden:
{ "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 } Vollbildmodus öffnen Vollbildmodus schließen Lies es von rechts nach links. Die Kosten sind die Schlagzeile, aber die fünf Token-Zahlen sind die Diagnose. Hier ist thinking doppelt so hoch wie die sichtbare Ausgabe, was bei einem Reasoning-Modell mit Standard-Denkbudget normal ist. Wenn thinking_tokens bei einer einzeiligen Klassifikation jedoch jemals das Zehnfache der sichtbaren Antwort erreicht, verrichtet das Budget Arbeit, die niemand angefordert hat.
Wenn cached_tokens nahe an input_tokens plus dem Cache liegt, funktioniert der Cache. Bleibt der Wert bei null, obwohl du immer wieder dasselbe lange Dokument sendest, wurde der Cache nie aktiviert. Im Free Tier kann er das auch gar nicht, denn Context Caching ist eine Funktion des Paid Tiers, und genau das ist die erste Falle weiter unten. Und wenn tool_use_tokens in jeder Runde steigt, speist eine Agent-Schleife Tool-Ergebnisse zurück in den Prompt, und die Kosten dieser Schleife gehören zu dem Feature, das sie verursacht.
Die erste Falle ist das Denkbudget. Gemini 2.5 Flash arbeitet standardmäßig mit Reasoning, und jedes Thinking-Token wird zum Ausgabepreis von 2,50 Dollar abgerechnet, ohne in der Antwort sichtbar zu sein. Wenn eine kurze Antwort plötzlich so viel kostet wie früher eine lange, prüfe das Budget, bevor du dem Modell die Schuld gibst: Übergib config=types.GenerateContentConfig(thinking_config=types.ThinkingConfig(thinking_budget=0)), um das Thinking ganz abzuschalten, oder eine kleine Zahl, um es zu begrenzen.
Der Wrapper erfasst die Gesamtsumme ehrlich, weil er das von der API zurückgegebene Feld ausliest. Er kann dir aber nicht verraten, dass das Budget das Problem war, solange du nicht auch die gesendete Konfiguration protokollierst. Bewahre das Budget also an demselben Ort auf wie die Modell-ID.
Die zweite Falle ist das Free Tier, und der Kalender. Derselbe Code kostet im Free Tier exakt 0 Dollar, was verführerisch macht, die Dollar-Spalte des Logs als Dekoration zu betrachten. Bis zu dem Tag, an dem du auf das Paid Tier wechselst und identischer Traffic ohne Codeänderung und ohne Warnung im Log plötzlich Kosten verursacht. Notiere das Datum des Tier-Wechsels neben der Logdatei.
Derselben Art stiller Wandel tritt am 1. Dezember 2026 ein, wenn Google Anfragen an gemini-2.5-flash zu gemini-3.5-flash-lite und Anfragen an gemini-2.5-pro zu gemini-3.8-flash umleitet, abgerechnet zu den Preisen der neuen Modelle. Der Wrapper protokolliert die Modell-ID, die du angefordert hast, nicht die, die geantwortet hat.
Prüfe daher nach diesem Datum das Rates-Dict gegen Googles Preisseite, sonst preist dein Log weiterhin ein Modell, das du gar nicht mehr betreibst. Dieselbe Datumslogik gilt für die 200.000-Token-Grenze von Pro: Ein Token über der Linie verteuert den gesamten Prompt von 1,25 auf 2,50 Dollar bei der Eingabe und von 10,00 auf 15,00 Dollar bei der Ausgabe. Deshalb wählt _rates_for die Preisklasse anhand der Prompt-Größe, statt sich auf einen einzelnen Tarif zu verlassen.
Die dritte Falle ist Streaming. Eine gestreamte Gemini-Antwort übergibt dir die vollständigen usage_metadata nicht auf dem üblichen Weg: Bei client.models.generate_content_stream kommt das Usage-Objekt nur im letzten Chunk an. Hüllst du einen Streaming-Aufruf mit dem obigen Code und protokollierst jeden Chunk, zählst du einen Aufruf gleich mehrfach, oder du protokollierst gar nichts, wenn du nur den ersten Chunk liest. Sammle die Chunks, lies usage aus dem letzten und protokolliere einmal.
Eine Logdatei, die niemand liest, ist Dekoration. Der Wrapper zahlt sich aus, wenn ein kleines Skript sie einmal täglich liest und dir nur mitteilt, was sich geändert hat. Beginne mit drei Zusammenfassungen, nicht mehr: Gesamtkosten pro Feature der letzten 24 Stunden, die zehn teuersten Einzelaufrufe und jedes Feature, dessen Tageskosten sich gegenüber dem Sieben-Tage-Durchschnitt verdoppelt haben. Die erste sagt dir, wohin das Geld fließt, die zweite, was du als Nächstes reparieren solltest, und die dritte ist die Frühwarnung, die einen entgleisten Job abfängt, bevor der Monat vorbei ist.
Wenn dich eine Zusammenfassung überrascht, enthält das Log bereits das Feature, das Modell, die Token-Aufteilung und den Zeitstempel, die du zum Handeln brauchst. Und wenn die Überraschung ein einzelner Nutzer statt eines Features ist, speisen dieselben pro-Aufruf-Daten direkt das Ausgaben-Limit pro Nutzer, das wir genau für dieses Problem gebaut haben. Um die Summen gegen deinen eigenen Token-Mix abzugleichen, erlaubt dir unser AI API Cost Calculator, eigene Zahlen einzugeben und mit den Werten des Logs zu vergleichen. Die Tarife in diesem Tutorial wurden am 13. November 2026 auf Googles Gemini-API-Preisseite verifiziert. Prüfe sie vor der Budgetplanung erneut, denn Google ändert sie. Die Umleitung am 1. Dezember ist das lebende Beispiel.
Diese Messgewohnheit ist der eigentliche Kern dieses Tutorials, und sie vervollständigt die Reihe: der OpenAI-Wrapper, der Claude-Wrapper und nun der Gemini-Wrapper, alle mit derselben Log-Struktur, eine Zeile pro Aufruf, pro Bucket bepreist. Preisseiten sagen dir, was ein Token kostet. Nur dein eigenes Log sagt dir, wofür deine App tatsächlich Tokens ausgibt. Und bei Gemini ist das, was sie ausgibt, gleich fünf verschiedene Zahlen, die in zwei harmlos wirkenden Summen versteckt sind.
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
Posted on Nov 23 • Originally published at apicostlab.com
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 or the Claude version, 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 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.
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 Enter fullscreen mode Exit fullscreen mode 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 } Enter fullscreen mode Exit fullscreen mode 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 we built for that exact problem. To sanity-check the totals against your own token mix, our AI API Cost Calculator 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.