AI / Google Antigravity Gemini Fundamentals Interview Questions
What is context caching in the Gemini API and how does it reduce costs?
Context caching stores a large stable prompt prefix (such as a system instruction, large document, or tool definitions) on Google's servers. Subsequent requests referencing that cache pay a lower price for the cached tokens rather than full input token pricing.
from google import genai from google.genai import types from datetime import timedelta client = genai.Client() # Create a cache with large stable content: large_document = open("entire-codebase.py").read() # 500k tokens cached = client.caches.create( model="gemini-3.5-flash", config=types.CreateCachedContentConfig( contents=[ types.Content( parts=[types.Part(text=large_document)] ) ], system_instruction="You are a code review expert. Always give actionable feedback.", ttl=timedelta(hours=2), # cache lives for 2 hours display_name="codebase-cache", ) ) print(f"Cache name: {cached.name}") print(f"Cached tokens: {cached.usage_metadata.total_token_count}") # Use the cache across many requests: for pr_diff in pull_requests: response = client.models.generate_content( model="gemini-3.5-flash", contents=pr_diff, # only the diff changes per request config=types.GenerateContentConfig( cached_content=cached.name ) ) # You pay full price for pr_diff tokens # but discounted price for the 500k cached codebase tokens print(response.text) # Delete cache when done: client.caches.delete(name=cached.name)
When to use context caching: it is most effective when the same large content (codebase, documentation, legal corpus) is referenced across many API calls. The cache has a minimum token size requirement (typically a few thousand tokens), and cached tokens cost less per request than fresh input tokens.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
