All guides

Gemini explicit caching: reuse a document and check the cache object

Create an explicit cache from the official PDF example, reference cache.name in a request, check usage_metadata, then delete the cache.

AINavWritten / Updated Sources checked
On this page

At a glance

The PDF example for explicit caching on the official Gemini API page gives the task here. You upload one PDF, create a cache object from it, refer to that object by cache.name in a later request, look at usage_metadata, and delete the cache. The behavior comes from the official page's description, and no API was run in this batch.

Mechanism overview

  1. Implicit and explicit caching

    Implicit and explicit caching:The source describes two mechanisms.

  2. The cache object and its lifetime

    The cache object and its lifetime:Explicit caching lets you pass content to the model once, cache the input tokens, and refer to them in later requests.

  3. How a request uses the cache

    How a request uses the cache:The model makes no distinction between cached and regular input tokens, because cached content works as a prefix to the prompt.

  4. Cost and size limits

    Cost and size limits:Context caching is a paid feature.

An overview of the stages and conditions; their arrangement does not imply execution order. Follow the task steps.

Prepare the input and environment

  • A Gemini SDK installed and an API key configured. The source says this section assumes both, as set out in its Get started guide. The Python code passes no key explicitly, so it relies on that existing configuration. It also imports httpx, and the source does not say how to install it.
  • Network access to the NASA PDF address and a model that supports explicit caching. The source says explicit caching works on Gemini 3 and 2.5 models and is not supported for Gemini 4 models. The example uses gemini-3.8-flash. The page does not say whether your account can use that model.
  • Caching is a paid feature. The page points to its pricing page for current prices, and this article gives none, so check them before use.

Mechanism and data flow

Implicit and explicit caching:The source describes two mechanisms. Implicit caching is enabled by default on Gemini 2.5 and newer models, needs no configuration, and passes savings on automatically when a request hits a cache, but it carries no cost saving guarantee. Explicit caching is enabled manually on Gemini 3 and 2.5 models and comes with a cost saving guarantee, at the price of extra developer work. It is not supported for Gemini 4 models, which use implicit caching by default. It is also in Beta, with endpoints and SDK methods under v1beta, which is why the Python excerpt builds its client with that API version. This article covers only the explicit path.

The cache object and its lifetime:Explicit caching lets you pass content to the model once, cache the input tokens, and refer to them in later requests. The cache is a separate object with a name. When you create it you can set a time to live (TTL), after which the tokens are deleted automatically. If you set none, the TTL defaults to 1 hour, and the PDF example sets none, so the default applies. You cannot retrieve or view the cached content, only metadata such as name, model, display_name, usage_metadata, create_time, update_time and expire_time. After creation only ttl or expire_time can be changed. A delete operation removes the cache manually.

How a request uses the cache:The model makes no distinction between cached and regular input tokens, because cached content works as a prefix to the prompt. A request opts in by setting cached_content to the cache's name, as the example does with cache.name. The number of cached tokens appears in usage_metadata on the cache service's create, get and list operations, and on GenerateContent calls that use the cache. Implicit caching does not apply to a request that uses an explicit cache, and any additional input tokens sent alongside it are billed at the standard input rate. Standard GenerateContent rate limits apply, and token limits include cached tokens.

Cost and size limits:Context caching is a paid feature. Billing depends on the cached token count, billed at a reduced rate when included in later prompts. It also depends on storage duration, which follows the TTL with no minimum or maximum bound, and on other charges such as non-cached input tokens and output tokens. The source points to its pricing page for current figures, and this article quotes none. The minimum input token count varies by model, while the maximum equals the model's own maximum. The table of minimums on the page covers implicit caching and lists 4,096 for Gemini 3.8 Flash. The page gives no separate table for explicit caching.

Workflow map

Workflow stages and responsibilities
StageWhat happens
Implicit and explicit cachingImplicit and explicit caching:The source describes two mechanisms.
The cache object and its lifetimeThe cache object and its lifetime:Explicit caching lets you pass content to the model once, cache the input tokens, and refer to them in later requests.
How a request uses the cacheHow a request uses the cache:The model makes no distinction between cached and regular input tokens, because cached content works as a prefix to the prompt.
Cost and size limitsCost and size limits:Context caching is a paid feature.

Complete the task

Confirm the model supports explicit caching:Pick a model before writing code. The source says explicit caching works on Gemini 3 and 2.5 models and not on Gemini 4 models, which are left with implicit caching only. The PDF example uses gemini-3.8-flash and stores it in model_name, and the example passes that value to both the cache creation call and the generation call. The document also has to meet the minimum token count for the chosen model, which varies by model. The source does not say whether your account can call this model.

Create the client and upload the PDF:The excerpt builds client with http_options setting the API version to v1beta, which matches the Beta status of explicit caching. It then points long_context_pdf_path at a NASA mission report PDF whose file name is a11_missionreport.pdf, downloads the bytes with httpx.get, wraps them in io.BytesIO, and uploads them through client.files.upload with mime_type set to application/pdf. The returned object is stored as document. The code passes no API key, so key configuration must already be in place, along with network access to the address and an installed httpx.

Create the cache object:Call client.caches.create with model and a types.CreateCachedContentConfig whose system_instruction is the string 'You are an expert analyzing transcripts.' and whose contents is [document]. The code sets no ttl, so the source's default of 1 hour applies. The result is stored in cache and printed with print(f'{cache=}'). Look in that printed object for the cache name and its metadata. The source does not show what the printed output looks like.

Send a request that references the cache:Call client.models.generate_content with the same model_name. The contents value is only the short prompt 'Please summarize this transcript', and config is a types.GenerateContentConfig whose cached_content is cache.name. This request does not resend the PDF or the system instruction. The cache supplies them, and the source describes cached content as a prefix to the prompt. Any extra input tokens sent with the request are billed at the standard input rate, and implicit caching does not apply to it.

Read the usage and the answer:The excerpt prints response.usage_metadata and then response.text. Per the source, usage_metadata carries the number of cached tokens when a cache is used. The excerpt does not name the exact subfield that holds that count, so inspect the printed structure yourself. The answer text is model output, and receiving a summary does not show that it is accurate, so compare any facts you rely on against the PDF itself.

Delete the cache and confirm:When you are done, run client.caches.delete(cache.name). This single line depends on the cache variable from the first excerpt, so it works only in the same runtime or when you have the cache name some other way. The source provides the delete operation for removing cached content manually, so you need not wait for the TTL. To confirm, list caches with client.caches.list() and check that the name is gone. That is an expectation drawn from the metadata operations, not a documented output. The source does not say how to delete the uploaded file.

Worked example

Taken as one task, the source example looks like this: the model is gemini-3.8-flash, the input is a PDF downloaded from the NASA address ending in a11_missionreport.pdf, the system instruction is 'You are an expert analyzing transcripts.', and the prompt is 'Please summarize this transcript'. The code creates the cache and prints it, sends the prompt with cached_content=cache.name, and prints usage_metadata and the response text. A separate one-line snippet deletes the cache. This is the official example as published, not an observation from this batch, so there is no output to quote.

Example: documented code under the stated prerequisites; not run in this batch
python
from google import genai
from google.genai import types
import io
import httpx

client = genai.Client(http_options={"api_version": "v1beta"})

long_context_pdf_path = "https://sma.nasa.gov/SignificantIncidents/assets/a11_missionreport.pdf"

# Retrieve and upload the PDF using the File API
doc_io = io.BytesIO(httpx.get(long_context_pdf_path).content)

document = client.files.upload(
  file=doc_io,
  config=dict(mime_type='application/pdf')
)

model_name = "gemini-3.8-flash"
system_instruction = "You are an expert analyzing transcripts."

# Create a cached content object
cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
      system_instruction=system_instruction,
      contents=[document],
    )
)

print(f'{cache=}')

response = client.models.generate_content(
  model=model_name,
  contents="Please summarize this transcript",
  config=types.GenerateContentConfig(
    cached_content=cache.name
  ))

print(f'{response.usage_metadata=}')

print('\n\n', response.text)
Example: documented code under the stated prerequisites; not run in this batch
python
client.caches.delete(cache.name)

Check the result and failure paths

  • Expected success, first: the printed cache after creation should show a name and the model you chose. This is expected from the metadata fields the source lists, not an actual output.
  • Expected success, second: usage_metadata in the response should report a cached token count. The source says GenerateContent returns it when a cache is used, and if it is empty or missing, do not assume reuse happened.
  • Expected success, third: after deletion, listing caches should no longer show the name. The source records no such output, so this is an expected check.
  • Failure exit, first: if creation raises an error, check whether the model is a Gemini 4 model, whether the client uses v1beta, whether the document meets the model's minimum token count, and whether the API key is configured. The source lists no specific error messages.
  • Failure exit, second: if the response shows no cached token count, treat reuse as unconfirmed. Check that cached_content was set to cache.name and that the cache has not passed its TTL, which is 1 hour when unset.

Immediately retain cache.name after creation and record model and expire_time. Check that it has not expired before reuse, then inspect the actual cached-token count. A zero, missing or unreadable count leaves reuse unconfirmed. Attempt the documented cache deletion after success, generation failure, failed acceptance or cancellation. After deletion, iterate client.caches.list() and check the retained name. A failed listing leaves deletion verification unconfirmed.

Scope and limits

  • Cached content cannot be retrieved or viewed, only its metadata. After creation only ttl or expire_time can be updated, and nothing else about the cache can be changed.
  • Gemini 4 models do not support explicit caching, and explicit caching is still Beta. The source says cached tokens cost less than resending the same tokens at certain volumes and does not say what the threshold is.
  • Neither excerpt proves the task is complete on its own. The first needs the SDK, httpx, a key and network access, and the delete line needs an existing cache. The code also cannot show that the summary is correct.
  • The source does not say how to delete the uploaded file, and this article makes no claim about it.

No Gemini API, SDK or cache operation was run in this batch, and no cache was created, no charge incurred and no output obtained. Behavior described here comes from the official page s1, and the checks are expected checks, not observations.

If download or upload fails before cache creation, retain the real error and stop; do not report a cache as created. If deletion fails after creation, retain its name and actual error and leave cleanup unconfirmed. Abrupt termination may prevent cleanup; the documented TTL remains the expiry boundary. These failure paths are editorial suggestions. The preserved code remains prerequisite-dependent official snippets.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. Google AI Studio · Official sources
    View details