count_tokens
Count the number of tokens in content without making a generation request.Method Signature
Description
Counts the number of tokens in the given content. This is useful for:- Estimating API costs before making requests
- Ensuring content fits within model token limits
- Managing context windows
- Optimizing prompt engineering
Parameters
str
required
The model to use for token counting. Different models have different tokenizers.Examples:
'gemini-2.0-flash''gemini-2.0-flash-exp''gemini-1.5-pro'
ContentListUnion
required
The content to count tokens for.Can be:
- A string:
'What is your name?' - A list of Content objects
- A list of Part objects
- Multimodal content with text, images, video, and audio
CountTokensConfig
Configuration for token counting.
Response
int
Total number of tokens in the content
int
Number of tokens from cached content (if using context caching)
Code Examples
Basic Token Counting
Count Tokens in Conversation
Count Multimodal Tokens
With System Instructions (Vertex AI)
Check Before Generation
compute_tokens
Returns detailed token information including individual token IDs and strings.Method Signature
Description
Given a list of contents, returns a correspondingTokensInfo containing the list of tokens and list of token IDs.
This method is only supported by Vertex AI API (not Gemini Developer API).
Useful for:
- Understanding model tokenization
- Debugging prompt engineering
- Analyzing token distribution
- Building custom tokenization tools
Parameters
str
required
The model to use for tokenization.Examples:
'gemini-2.0-flash''gemini-1.5-pro'
ContentListUnion
required
The content to compute tokens for.
ComputeTokensConfig
Configuration for token computation (reserved for future use)
Response
list[TokensInfo]
List of token information for each content.
Code Examples
Basic Token Computation
Analyze Tokenization
Compare Tokenization Across Content
Analyze Special Characters
Async Usage
Comparison
Notes
- Token counts may vary slightly between model versions
- Multimodal tokens (images, video, audio) are counted differently than text
- Use
count_tokensbefore generation to avoid exceeding limits - Use
compute_tokensto understand how models tokenize your input compute_tokensis only available on Vertex AI- System instructions and tools can be included in token count (Vertex AI only)
- Context caching can significantly reduce token usage for repeated content
Related Methods
- generate_content - Generate content
- embed_content - Generate embeddings