Skip to main content
Tokenization is the process of breaking down text into tokens that models can process. Understanding token counts is important for managing context windows and API costs.

Count tokens

Count the number of tokens in your content:
The response includes:
  • total_tokens - Total number of tokens in the content
  • cached_tokens - Number of tokens from cached content (if applicable)

Compute tokens

Compute tokens is only supported in Vertex AI.
The compute_tokens method provides more detailed token information:
This returns additional details about the tokenization, including the actual token IDs.

Async token counting

Use async methods for non-blocking token counting:

Local tokenizer

For offline token counting without making API calls, use the local tokenizer:

Local compute tokens

Compute detailed token information locally:
The local tokenizer:
  • Works offline without API calls
  • Provides faster token counting
  • Useful for preprocessing and validation
  • Returns the same counts as the API

Token counting for different content types

Count tokens for various content types:

Managing context windows

Use token counting to manage model context limits:

Estimating costs

Use token counts to estimate API costs: