Overview
For repeatedly querying a ~500k-token codebase against Gemini on Google Vertex AI, explicit context caching precomputes and stores the key-value (KV) state of your static codebase prefix so repeated queries avoid re-processing 500k tokens on every turn. A 500k-token repository easily clears minimum cache token thresholds (typically a few thousand tokens depending on model family), delivering lower time-to-first-token latency and discounted cached input token rates (commonly 75%–90% off standard input rates on supported Gemini models, offset by per-hour TTL storage billing and initial cache write/creation costs).
- Explicit cache vs. implicit caching: Implicit caching works automatically on matching prefixes without code changes, but retention is best-effort/eviction-driven (up to 24 hours). For repeated codebase Q&A, code review, or agentic queries over a pinned commit/snapshot, explicit caching via
client.caches.create(...)gives deterministic cache retention (ttl), predictable reuse viacached_content, and explicit cleanup or TTL extension. - Static prefix vs. dynamic query separation: Place the stable repository dump, architectural rules, and any shared
system_instructionortoolsinside the cache object, and pass only the per-query question or diff incontentsduringgenerate_content. - Cache exclusivity rules: When a request references
cached_content, do not re-passsystem_instruction,tools, ortool_configinGenerateContentConfigif those were already set when creating the cache.
Steps
- Assemble and bound the codebase context cleanly: Serialize relevant source files with clear file-path headers and line/symbol markers, excluding lockfiles, build artifacts, binaries, and secrets so you do not waste 500k tokens or hourly TTL storage on noise.
- Create an explicit cache with
client.caches.create: Initializegenai.Client(vertexai=True, project=..., location=...)(usinggoogle-genai), supply the static codebasecontents, optionalsystem_instruction/tools, and attl(such as"3600s"), and recordcache.name(projects/.../locations/.../cachedContents/...). - Query repeatedly using
cached_contentinGenerateContentConfig: Callclient.models.generate_content(orgenerate_content_stream) withcached_content=cache.nameand only the new user prompt incontents, inspectingresponse.usage_metadata.cached_content_token_countto verify cache hits. - Manage TTL, invalidation, and deletion on repo updates: Extend
ttlviaclient.caches.updateduring active sessions, create a new cache when the codebase commit changes (rather than mutating underlying Cloud Storage objects in place), and callclient.caches.deletewhen finished to stop storage charges.
Example
import os
from pathlib import Path
from google import genai
from google.genai import types
def build_codebase_bundle(repo_root: Path, max_chars: int = 1_900_000) -> str:
"""Concatenates selected source files with file-path delimiters for caching."""
allowed_exts = {".py", ".ts", ".tsx", ".js", ".go", ".rs", ".java", ".sql", ".md"}
excluded_dirs = {".git", "node_modules", "dist", "build", ".venv", "__pycache__"}
parts: list[str] = []
total_chars = 0
for file_path in sorted(repo_root.rglob("*")):
if not file_path.is_file():
continue
if any(part in excluded_dirs for part in file_path.parts):
continue
if file_path.suffix.lower() not in allowed_exts:
continue
rel_path = file_path.relative_to(repo_root).as_posix()
content = file_path.read_text(encoding="utf-8", errors="replace")
block = f"=== FILE: {rel_path} ===\n{content}\n"
if total_chars + len(block) > max_chars:
break
parts.append(block)
total_chars += len(block)
return "\n".join(parts)
def create_codebase_cache(
client: genai.Client,
model: str,
repo_bundle: str,
display_name: str = "repo-500k-cache",
ttl_seconds: int = 3600,
) -> str:
"""Creates an explicit Vertex AI context cache for a large codebase."""
system_instruction = (
"You are a senior software engineer analyzing the cached repository. "
"Cite exact file paths and symbol names when answering questions."
)
cache = client.caches.create(
model=model,
config=types.CreateCachedContentConfig(
display_name=display_name,
system_instruction=system_instruction,
contents=[
types.Content(
role="user",
parts=[types.Part.from_text(text=repo_bundle)],
)
],
ttl=f"{ttl_seconds}s",
),
)
return cache.name
def query_cached_codebase(
client: genai.Client,
model: str,
cache_name: str,
question: str,
) -> tuple[str, int | None]:
"""Runs a query against an existing explicit cache without resending the codebase."""
response = client.models.generate_content(
model=model,
contents=question,
config=types.GenerateContentConfig(
cached_content=cache_name,
temperature=0.1,
),
)
cached_tokens = getattr(response.usage_metadata, "cached_content_token_count", None)
return (response.text or ""), cached_tokens
if __name__ == "__main__":
project_id = os.environ["GOOGLE_CLOUD_PROJECT"]
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "us-central1")
model_id = os.environ.get("VERTEX_GEMINI_MODEL", "gemini-2.5-pro")
client = genai.Client(
vertexai=True,
project=project_id,
location=location,
)
bundle = build_codebase_bundle(Path("./src"))
cache_name = create_codebase_cache(
client=client,
model=model_id,
repo_bundle=bundle,
display_name="my-service-snapshot",
ttl_seconds=3600,
)
try:
for q in [
"Where are authentication tokens validated and refreshed?",
"List all background job queues and their retry/dead-letter behavior.",
]:
answer, cached_count = query_cached_codebase(client, model_id, cache_name, q)
print(f"Q: {q}\nCached tokens: {cached_count}\nA: {answer}\n{'-' * 40}")
finally:
# Delete the explicit cache when batch/session work finishes to avoid idle TTL charges
client.caches.delete(name=cache_name)
Tips
- Scope caches per user/tenant and commit SHA: Never share a single codebase or workspace cache across users with different repository/tenant permissions, and key caches by commit SHA or snapshot ID so stale code is never queried after a push.
- Match
locationandmodelbetween cache creation and queries: A cached content resource is bound to its project, region/location, and model—ensure yourgenerate_contentcalls target the exact samecache.name,location, and compatiblemodel. - Balance TTL against query burstiness: A 500k-token explicit cache accrues storage charges per hour (prorated by minute) for its full
ttl—use a shorter TTL withclient.caches.updatefor intermittent interactive sessions, and a longer TTL when running high-volume bursts of queries back-to-back.
You must log in or register to comment.
