#!/usr/bin/env python3 # STATUS: LIVE_VERIFIED — executed 2026-09-18 (exit 0 in 0.6s) — ACCOUNT_RESTRICTED path taken (free tier) # Explicit caching lifecycle: create (~5k tokens, ttl 120s) -> generateContent with cachedContent -> get -> patch ttl -> delete. On the free tier creation fails with 429 TotalCachedContentStorageTokensPerModelFreeTier limit=0 (ACCOUNT_RESTRICTED) and the script exits 0 after printing the error. # Run: .venv/bin/python examples/gemini/context-caching/cache_lifecycle.py (GEMINI_API_KEY read from .env via scripts.live; google-genai 2.24) import pathlib import sys ROOT = pathlib.Path(__file__).resolve().parents[3] sys.path.insert(0, str(ROOT)) from scripts import live # noqa: E402 loads .env, provides log_request from google import genai # noqa: E402 from google.genai import types # noqa: E402,F401 client = genai.Client() MODEL = "gemini-3.5-flash" from google.genai import errors # noqa: E402 filler = " ".join(f"Section {i}: The Atlas reference corpus documents the public API surface of large language model providers, including endpoints, parameters, streaming events, objects, errors and pricing, verified experimentally." for i in range(1, 121)) try: cache = client.caches.create(model=MODEL, config=types.CreateCachedContentConfig(display_name="atlas-example", ttl="120s", system_instruction="Answer with one word.", contents=[filler])) except errors.ClientError as e: live.log_request("gemini", "POST", "/v1beta/cachedContents", e.code, 0.0, "example context-caching/cache_lifecycle.py create (restricted)") print("ACCOUNT_RESTRICTED:", e.code, str(e)[:200]) sys.exit(0) live.log_request("gemini", "POST", "/v1beta/cachedContents", 200, 0.0015, "example context-caching/cache_lifecycle.py create") print(cache.name, cache.expire_time, cache.usage_metadata) r = client.models.generate_content(model=MODEL, contents="Reply with OK.", config=types.GenerateContentConfig(cached_content=cache.name, max_output_tokens=8)) live.log_request("gemini", "POST", "/v1beta/models/{model}:generateContent", 200, 0.0001, "example cache use") print(r.text, r.usage_metadata.cached_content_token_count, r.usage_metadata.prompt_token_count) print(client.caches.get(name=cache.name).expire_time) print(client.caches.update(name=cache.name, config=types.UpdateCachedContentConfig(ttl="300s")).expire_time) client.caches.delete(name=cache.name) live.log_request("gemini", "DELETE", "/v1beta/cachedContents/{id}", 200, 0, "example cache delete") print("deleted")