In a typical AI workflow, you might pass the same input tokens over and over to a model. Using the Gemini API context caching feature, you can pass some content to the model once, cache the input tokens, and then refer to the cached tokens for subsequent requests. At certain volumes, using cached tokens is lower cost than passing in the same corpus of tokens repeatedly.
When you cache a set of tokens, you can choose how long you want the cache to exist before the tokens are automatically deleted. This caching duration is called the time to live (TTL). If not set, the TTL defaults to 1 hour. The cost for caching depends on the input token size and how long you want the tokens to persist.
Context caching supports both Gemini 1.5 Pro and Gemini 1.5 Flash.
When to use context caching
Context caching is particularly well suited to scenarios where a substantial initial context is referenced repeatedly by shorter requests. Consider using context caching for use cases such as:
- Chatbots with extensive system instructions
- Repetitive analysis of lengthy video files
- Recurring queries against large document sets
- Frequent code repository analysis or bug fixing
How caching reduces costs
Context caching is a paid feature designed to reduce overall operational costs. Billing is based on the following factors:
- Cache token count: The number of input tokens cached, billed at a reduced rate when included in subsequent prompts.
- Storage duration: The amount of time cached tokens are stored (TTL), billed based on the TTL duration of cached token count. There are no minimum or maximum bounds on the TTL.
- Other factors: Other charges apply, such as for non-cached input tokens and output tokens.
For up-to-date pricing details, refer to the Gemini API pricing page. To learn how to count tokens, see the Token guide.
How to use context caching
This section assumes that you've installed a Gemini SDK and configured an API key, as shown in the quickstart.
Additional considerations
Keep the following considerations in mind when using context caching:
- The minimum input token count for context caching is 32,768, and the maximum is the same as the maximum for the given model. (For more on counting tokens, see the Token guide).
- The model doesn't make any distinction between cached tokens and regular input tokens. Cached content is simply a prefix to the prompt.
- There are no special rate or usage limits on context caching; the standard
rate limits for
GenerateContent
apply, and token limits include cached tokens. - The number of cached tokens is returned in the
usage_metadata
from the create, get, and list operations of the cache service, and also inGenerateContent
when using the cache.