How do you use Google Vertex AI Context Caching for querying 500k-token codebases repeatedly? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you use Google Vertex AI Context Caching for querying 500k-token codebases repeatedly?

message-square
0

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 via cached_content, and explicit cleanup or TTL extension.
  • Static prefix vs. dynamic query separation: Place the stable repository dump, architectural rules, and any shared system_instruction or tools inside the cache object, and pass only the per-query question or diff in contents during generate_content.
  • Cache exclusivity rules: When a request references cached_content, do not re-pass system_instruction, tools, or tool_config in GenerateContentConfig if those were already set when creating the cache.

Steps

  1. 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.
  2. Create an explicit cache with client.caches.create: Initialize genai.Client(vertexai=True, project=..., location=...) (using google-genai), supply the static codebase contents, optional system_instruction / tools, and a ttl (such as "3600s"), and record cache.name (projects/.../locations/.../cachedContents/...).
  3. Query repeatedly using cached_content in GenerateContentConfig: Call client.models.generate_content (or generate_content_stream) with cached_content=cache.name and only the new user prompt in contents, inspecting response.usage_metadata.cached_content_token_count to verify cache hits.
  4. Manage TTL, invalidation, and deletion on repo updates: Extend ttl via client.caches.update during active sessions, create a new cache when the codebase commit changes (rather than mutating underlying Cloud Storage objects in place), and call client.caches.delete when 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 location and model between cache creation and queries: A cached content resource is bound to its project, region/location, and model—ensure your generate_content calls target the exact same cache.name, location, and compatible model.
  • 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 with client.caches.update for intermittent interactive sessions, and a longer TTL when running high-volume bursts of queries back-to-back.