AI for developers
How to Count Tokens Before Sending a Request to OpenAI, Claude or Gemini
In short
Send the same payload to the vendor's counting call first: OpenAI's POST /v1/responses/input_tokens, Claude's POST /v1/messages/count_tokens or Gemini's countTokens. All three count system prompts, tools and images. A local tokenizer such as tiktoken cannot count images and can miss formatting and tool tokens, Claude labels its own figure an estimate, and the usage blocks do not define input the same way once caching is involved.
Which call returns the input count on each API?
Each vendor offers a counting call that takes the request you were about to send and answers with a number instead of a completion.
Of the pages I read, only Claude's put numbers on the counter itself: 5,000 requests a minute in the Start tier, 10,000 in Build and 20,000 in Scale. Those limits are separate from message creation, so a count takes nothing from the real call's budget.
| Detail | OpenAI | Claude | Gemini |
|---|---|---|---|
| Endpoint | `POST /v1/responses/input_tokens` | `POST /v1/messages/count_tokens` | `POST /v1beta/models/{model}:countTokens` |
| Python SDK call | `client.responses.input_tokens.count` | `client.messages.count_tokens` | `client.models.count_tokens` |
| What you send | The same input format as the Responses API | The same structured inputs as the Messages API | `contents`, or a whole `generateContentRequest`, never both |
| What comes back | `input_tokens`, with `object` set to `response.input_tokens` | `input_tokens` across messages, system prompt and tools | `totalTokens`, `cachedContentTokenCount` and a per-modality `promptTokensDetails` list |
| Price and limits | Not stated on the pages I read | Free, with its own requests-per-minute limit | Not stated on the pages I read |
Checked against: source 1, source 2, source 5, source 6, source 9, source 10
Why does a local tiktoken count drift from the API's number?
OpenAI's counting guide says tiktoken handles plain text but cannot see images or files, tool schemas add tokens that are awkward to reproduce, and model behaviour such as reasoning or caching can change tokenization. The endpoint's figure also includes formatting tokens for message roles and boundaries, which might not appear in the strings a local tokenizer is given.
OpenAI's tiktoken cookbook recipe now carries an archived banner. Its helper for chat messages describes its own output as an estimate that can shift from model to model, and warns that function definitions cost extra tokens beyond what it calculates. Its encoding table stops at the gpt-4o generation, mapping o200k_base to gpt-4o and gpt-4o-mini, so I would not lean on it for a newer model.
The Claude and Gemini pages I read do not describe a local tokenizer, so for Gemini they leave you with a rule of thumb: about 4 characters per token, or 60 to 80 English words per 100 tokens. That is fine for a rough progress bar, not for a limit check. Claude adds a migration trap: Claude 4.7 and later use a newer tokenizer that yields roughly 30 percent more tokens for the same text, and Anthropic asks you to recount with the model ID you plan to use.
Is the pre-send count exact or an estimate?
The wording differs, which matters if you reject requests close to a limit. OpenAI's guide says its endpoint returns the exact count the model will receive. Claude's page calls its figure an estimate that may be off by a small amount, and says it can include tokens Anthropic adds for system optimizations, which are not billed.
Caching is a second gap on Claude: cache_control blocks are accepted, but the count runs without caching logic, so it cannot show what will later be a cache read. Gemini's countTokens does report a cachedContentTokenCount. The Gemini pages I read neither promise an exact figure nor call it an estimate.
What gets counted, and what does each counting call refuse?
The Gemini and Claude pages I read let you estimate media by arithmetic. Gemini counts an image no larger than 384 pixels on either side as 258 tokens and cuts bigger ones into 768 by 768 pixel tiles of 258 tokens each, with audio at 32 tokens a second. Claude costs an image at ⌈width / 28⌉ × ⌈height / 28⌉ visual tokens after downscaling to its tier's cap: 1,568 visual tokens on most models, 4,784 on Claude 4.7 and later. OpenAI's counting guide says image tokens depend on size and detail level and points you to the endpoint for the figure.
Gemini's page gives video two ways, both for its default static processing: 263 tokens a second in its summary, and about 100 a second at default resolution (about 300 at high) in its table. With that conflict, I would count video through the endpoint. On Claude, thinking blocks from earlier assistant turns count as input on models that keep every prior turn and are stripped on models that keep only the last one, while for a request that uses web search or another refused server tool the page points you to the usage object of the real response.
System prompts and tool definitions count on all three; the table shows where attachments, tools and earlier turns differ.
A file uploaded once and referenced by ID also has size and expiry rules of its own, set out in Files API limits and retention.
| Input | OpenAI | Claude | Gemini |
|---|---|---|---|
| System prompt | `instructions` field | `system` field | Inside `generateContentRequest`, counted as input |
| Tool definitions | Function schemas and MCP servers add tokens; include them in the count request | Client tools and the advisor tool; other server tools and the MCP connector are refused | Function declarations inside `generateContentRequest`; the guide says functions, code execution and Google Search count |
| Images and files | `file_id` or `image_url` for images; `file_id`, `file_url` or `file_data` for files | Base64 only; a `url` or `file` source returns `invalid_request_error` | Inline bytes, or the URI of a file uploaded first |
| Earlier turns | `conversation` or `previous_response_id`, not both | Send the full message list; the API is stateless | `previous_interaction_id` in the guide's multi-turn example |
Checked against: source 1, source 2, source 5, source 7, source 8, source 9, source 10
How does each response report tokens after the call?
Log the usage block, but note that its headline input figure is not defined the same way on each API, so comparing it with the pre-send count takes vendor-specific arithmetic.
- OpenAI Responses API:
usage.input_tokens, withcached_tokensandcache_write_tokensinsideinput_tokens_details, which the reference calls a breakdown of the input tokens. Output comes asoutput_tokens, withreasoning_tokensbroken out, plustotal_tokens. Chat Completions names the output figurecompletion_tokens. - Claude:
usage.input_tokensis only the uncached part. The reference defines total input asinput_tokenspluscache_creation_input_tokenspluscache_read_input_tokens, so add all three before comparing withcount_tokens. It also warns that usage does not map one to one onto the visible request and response. - Gemini generateContent:
usageMetadata.promptTokenCountstill includes cached content whencached_contentis set. Beside it sitcachedContentTokenCount,candidatesTokenCount,toolUsePromptTokenCountandthoughtsTokenCount, andtotalTokenCountadds prompt, tool-use prompt, thoughts and candidates. - Gemini Interactions API:
interaction.usagereportstotal_input_tokens,total_output_tokens,total_thought_tokens,total_cached_tokens,total_tool_use_tokensandtotal_tokens. Google's documentation index makes this API the default and calls generateContent legacy, so new code will mostly read this shape. - Where the hidden thinking lands in these blocks is covered in reasoning tokens vs output tokens, and how long a cached prefix survives in prompt caching lifetimes.
Checked against: source 1, source 3, source 7, source 9, source 11, source 12
When is a pre-flight count worth the extra call?
I would count first whenever a request carries tools, images or files, or sits near a context limit, and skip the call for short plain-text prompts where a heuristic is enough. OpenAI shows why: with truncation at its default of disabled, input larger than the context window fails with a 400 error, while auto drops items from the start of the conversation to make it fit.
On Claude the count is free and limited separately, so counting each large request costs an extra round trip, not message-creation quota. Recount whenever you move to Claude 4.7 or later, because counts saved under the older tokenizer will understate the new figure. Rate limiters meter tokens by their own rules; see how each vendor meters tokens per minute.
What else do people ask?
Does counting tokens cost anything?
Claude's documentation says token counting is free, with a requests-per-minute limit of its own. The OpenAI and Gemini pages I read state neither a price nor a limit for their counting calls.
Can I count a Claude request that uses web search?
Not with the counting endpoint, which refuses server tools other than the advisor tool. Send the real request and read its usage object instead.
Sources
- OpenAI API docs, Counting tokens, fetched 2026-11-21
- OpenAI API reference, Get input token counts, fetched 2026-11-21
- OpenAI API reference, Create a model response, fetched 2026-11-21
- OpenAI Cookbook, How to count tokens with tiktoken, fetched 2026-11-21
- Claude Platform docs, Token counting, fetched 2026-11-21
- Claude API reference, Count tokens in a Message, fetched 2026-11-21
- Claude API reference, Create a Message, fetched 2026-11-21
- Claude Platform docs, Vision, fetched 2026-11-21
- Gemini API docs, Understand and count tokens, fetched 2026-11-21
- Gemini API reference, Counting tokens, fetched 2026-11-21
- Gemini API reference, Generating content, fetched 2026-11-21
- Gemini API documentation index (llms.txt), fetched 2026-11-21
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. This page compares OpenAI, Anthropic and Google documentation fetched on 21 Nov 2026. I did not send counting or generation requests for it, so no figure here is a measured token count. It does not cover prices, Batch APIs, Bedrock, Vertex AI or other cloud resellers, audio and video edge cases beyond the quoted rates, or per-model context windows. Found a mistake? Tell me.