Gemini token counting: estimate input and reconcile API costs
Estimate Gemini input tokens, budget long-context prompts against 200K pricing tiers and TPM limits, and reconcile post-call API usage.

Count the exact Gemini input you intend to send, budget output and reasoning tokens separately, and reconcile reported usage after generation. A pre-call token estimate helps your application decide whether a long-context prompt fits its context window, rate-limit headroom, and cost tier; it is not a final bill or a reservation of provider capacity.
This guide consolidates Gemini token counting and long-context token budgeting into one operational reference. Review the API429 documentation and model catalog to inspect published context limits and per-million-token rates before dispatching large payloads.
What countTokens measures and what it omits
Google documents token counting for text and multimodal inputs in its tokens guide and long-context documentation. A preflight count_tokens operation measures the input payload only. Output completions, internal thinking tokens, cached-content storage, and tool invocations require separate allowances when budgeting the request and reconciling the final bill.
Always count the complete assembled payload rather than only the latest user message. System instructions, multi-turn conversation history, JSON Schema definitions, few-shot examples, and attached PDFs, images, or audio all contribute to input tokens. An estimate from a different model family or a stripped prompt should never be treated as an exact count for the production call.
Turn a token count into a tier-aware cost estimate
First select the exact model and inspect its pricing structure. The Gemini API pricing comparison and pricing page distinguish input, output, and context-length conditions; the current model catalog lists published API429 rates.
On several direct provider tariffs, crossing a long-context boundary (such as 200,000 input tokens on specific models where applicable) changes both the input rate and the output rate for the entire request, whereas other reviewed models charge a flat rate across the full window. Check the exact model's tariff table rather than inventing a universal multiplier.
For a hypothetical model charging $1.00 per million input tokens and $5.00 per million output tokens up to 200,000 input tokens, an input count of 8,000 plus an allowance of 1,000 output tokens yields:
8_000 * $1.00 / 1_000_000 + 1_000 * $5.00 / 1_000_000 = $0.013
This is a worked arithmetic example, not a live Gemini tariff. Add applicable cache operations, tools, and media charges. Do not reuse a text-token estimate as an image-generation price; use the Nano Banana comparison for image workloads.
Context windows, input TPM limits, and long-context routing
A prompt can fit comfortably inside a model's 1M-token context window while still exhausting your input tokens per minute (input TPM) quota on the very first call. Conversely, lowering request concurrency does not make an oversized 1.2M-token payload fit a 1M-token context window.
| Prompt size and workload shape | Primary risk | Application control action |
|---|---|---|
| Single prompt exceeds model context window | Immediate 400 validation failure | Split document, retrieve top chunks via RAG embeddings, or summarize sections |
| Large prompt (100K–900K tokens) repeated across many questions | High input TPM burn and repeated input cost | Evaluate Gemini context caching or pre-indexed retrieval |
| Concurrent long-context requests during peak hours | Input TPM saturation and 429 RESOURCE_EXHAUSTED |
Gate dispatch through queue admission controls using estimated input tokens |
| Retrying a failed 400K-token call immediately | Rapid quota and budget exhaustion | Check retry budget deadlines and cost guardrails before any replay |
Direct Google calls and gateway calls
Use Google's documented countTokens method with the direct Google Gemini API when your integration targets Google directly. When routing through an OpenAI-compatible gateway such as API429 (POST /v1/chat/completions), verify which endpoints and usage fields are exposed in the API429 API reference and public OpenAPI specification. Do not assume that changing a base URL exposes provider-specific auxiliary endpoints.
When a native preflight token-counter endpoint is not used on an OpenAI-compatible route, apply a conservative local tokenizer or character/byte heuristic with a safety margin before dispatch, cap max_tokens explicitly, and calibrate your estimator against the exact usage.prompt_tokens and usage.completion_tokens returned in the response.
Runnable offline Python token budget and reconciliation calculator
The standalone Python module below evaluates whether an estimated request fits the model's context window, input TPM headroom, and task cost ceiling (including optional long-context tier thresholds), and reconciles the estimate against reported response usage:
from dataclasses import dataclass
@dataclass(frozen=True)
class ModelTariff:
model_id: str
context_window: int
max_output_limit: int
short_input_per_1m: float
short_output_per_1m: float
long_context_threshold: int | None = None
long_input_per_1m: float | None = None
long_output_per_1m: float | None = None
def estimate_request_budget(
tariff: ModelTariff,
*,
estimated_input_tokens: int,
requested_max_output: int,
available_input_tpm: int,
task_budget_usd: float,
) -> dict:
if requested_max_output > tariff.max_output_limit:
return {"admitted": False, "reason": "exceeds_model_output_limit"}
if estimated_input_tokens + requested_max_output > tariff.context_window:
return {"admitted": False, "reason": "exceeds_context_window"}
if estimated_input_tokens > available_input_tpm:
return {"admitted": False, "reason": "exceeds_available_input_tpm"}
use_long_tier = (
tariff.long_context_threshold is not None
and estimated_input_tokens > tariff.long_context_threshold
)
in_rate = tariff.long_input_per_1m if use_long_tier and tariff.long_input_per_1m is not None else tariff.short_input_per_1m
out_rate = tariff.long_output_per_1m if use_long_tier and tariff.long_output_per_1m is not None else tariff.short_output_per_1m
reserved_usd = round(
(estimated_input_tokens / 1_000_000) * in_rate
+ (requested_max_output / 1_000_000) * out_rate,
6,
)
if reserved_usd > task_budget_usd:
return {"admitted": False, "reason": "exceeds_task_cost_budget", "reserved_usd": reserved_usd}
return {
"admitted": True,
"reason": "fits_window_tpm_and_budget",
"tier": "long_context" if use_long_tier else "standard",
"reserved_usd": reserved_usd,
}
def reconcile_token_usage(
estimated_input_tokens: int,
usage_payload: dict,
) -> dict:
actual_in = int(usage_payload.get("prompt_tokens", 0))
actual_out = int(usage_payload.get("completion_tokens", 0))
cached_in = int(usage_payload.get("cached_tokens", 0))
drift_ratio = round((actual_in - estimated_input_tokens) / max(1, actual_in), 4)
return {
"actual_input_tokens": actual_in,
"actual_output_tokens": actual_out,
"cached_input_tokens": cached_in,
"input_estimation_drift": drift_ratio,
}
if __name__ == "__main__":
sample_tariff = ModelTariff(
model_id="demo-gemini-long",
context_window=1_000_000,
max_output_limit=64_000,
short_input_per_1m=1.25,
short_output_per_1m=5.00,
long_context_threshold=200_000,
long_input_per_1m=2.50,
long_output_per_1m=10.00,
)
decision = estimate_request_budget(
sample_tariff,
estimated_input_tokens=240_000,
requested_max_output=4_000,
available_input_tpm=500_000,
task_budget_usd=1.00,
)
reconciled = reconcile_token_usage(
240_000,
{"prompt_tokens": 243_120, "completion_tokens": 1_450, "cached_tokens": 0},
)
print("Budget decision:", decision)
print("Reconciliation:", reconciled)
A repeatable reconciliation record
Store the model ID, input estimate, output allowance, request timestamp, and returned usage fields (prompt_tokens, completion_tokens, and any documented reasoning or cache fields). Include any request identifier offered by the service, and exclude secret API keys and sensitive prompt contents from routine logs.
After a timeout, check the operation record before repeating paid work. For larger workflows, the cost guardrails guide explains task allowances and bounded retries, and the Google provider overview and FAQ summarize connection and billing boundaries.
FAQ
Does countTokens reserve capacity or guarantee a request will not hit HTTP 429?
No. Token counting only measures the input size of the payload you submit. Your application must still check queue admission, input TPM headroom, and retry budgets before dispatching the generation request.
Why can actual billed tokens exceed a pre-call countTokens estimate?
countTokens measures input tokens only. The completed call also bills for generated output tokens, internal thinking tokens on reasoning models, and any tool-call turns added during execution.
Does every Gemini model double its price above 200,000 input tokens?
No. Pricing tiers depend on the specific model and provider tariff table. Always check the Gemini API pricing comparison and model catalog for the exact model ID you plan to call.
Should long prompts always use a 1M-token context window instead of RAG?
Not by default. Sending hundreds of thousands of tokens on every user turn increases latency, cost, and input TPM pressure. Use long context when full-document synthesis is required, and use cached context or RAG retrieval when queries only need targeted passages.
Sources & further reading
Put the next step into practice.
Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.

