In this categoryGemini ยท 24
- How to Install the Gemini CLI and Run Your First PromptStart
- How to Get a Gemini API Key from Google AI Studio
- How to Call the Gemini API from Python
- How to Give Gemini CLI Project Context with a GEMINI.md File
- How to Choose the Right Gemini Model for Coding Tasks
- How to Fix a Bug in Your Codebase with the Gemini CLI
- How to Set Up Gemini Code Assist in VS Code
- How to Stream Gemini Responses in Node.js
- How to Feed a Long Document into Gemini's Long Context
- How to Run the Gemini CLI Non-Interactively in Scripts
- How to Analyze a Video File with the Gemini API
- How to Connect an MCP Server to the Gemini CLI
- How to Fix Common Gemini CLI Authentication Errors
- How to Cache Long Context in the Gemini API to Cut Costs
- How to Summarize a YouTube Video with Gemini
- How to Analyze PDFs and Docs in the Gemini Chat App
- How to Extract Data from Images and Screenshots with Gemini
- How to Generate a Short Video with Veo in Gemini
- How to Ground Gemini Answers in Your Own Documents
- How to Use Gemini Inside Google Docs to Draft Faster
How to Cache Long Context in the Gemini API to Cut Costs
Set up explicit context caching so repeated questions about the same large document cost a fraction of the price.
If you ask many questions about the same large document, re-sending it every time wastes tokens and money. Gemini's context caching lets you process a big input once, store it for a set time, and reuse it across requests at a reduced rate. This guide creates a cache, queries it, and cleans it up.
What you need
- A Gemini API key and the google-genai SDK
- A large input you will reuse: a long PDF, transcript, or codebase dump
- A model that supports caching, such as gemini-2.5-flash or gemini-2.5-pro
Step 1: Upload the document
Use the File API to upload the large file, exactly as you would for a normal long-context request. You will reference this handle when creating the cache.
import os
from google import genai
from google.genai import types
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
doc = client.files.upload(file="handbook.pdf")Step 2: Create the cache
Create a cached content object that holds the document plus a system instruction. Set a time-to-live (TTL) so it expires automatically. You are billed to create the cache and a small amount to store it, but each query that uses it is cheaper.
cache = client.caches.create(
model="gemini-2.5-flash",
config=types.CreateCachedContentConfig(
system_instruction="You are a precise assistant. Answer only from the handbook.",
contents=[doc],
ttl="3600s", # keep for one hour
),
)
print("cache name:", cache.name)Step 3: Query against the cache
Now send questions that reference the cache instead of re-uploading the document. The cached tokens are billed at the lower cached rate, and you only pay full price for the new question and the answer.
resp = client.models.generate_content(
model="gemini-2.5-flash",
contents="What is the refund window described in the handbook?",
config=types.GenerateContentConfig(cached_content=cache.name),
)
print(resp.text)
print("cached tokens:", resp.usage_metadata.cached_content_token_count)Step 4: Delete the cache when done
Caches expire on their own at the TTL, but you can delete one early to stop paying storage. Always clean up caches your script no longer needs.
Result
Repeated questions about the same big document now reuse the cached tokens, often cutting the per-query input cost substantially. The usage metadata's cached_content_token_count confirms the cache is actually being hit.
Watch related tutorials
16:12
3:58:44
2:14
23:41
12:00
09:00New guides in your inbox
Fresh step-by-step how-to guides as we publish them. One email a week, no more.