
Gemini 3.5 Pro: Feed a 2M-Token Codebase in One Call
Summary
Load a whole repo into Gemini 3.5 Pro's 2M context, query it without RAG, and cache to cut cost.
Google started rolling Gemini 3.5 Pro into general availability in the last week of June 2026, and the headline spec is the one every developer fixated on: a 2,000,000-token context window, the largest of any production frontier model right now. June 2026 is already being called the biggest model-launch month ever, and this is the release that actually changes how you architect an app.
Two million tokens is not a bigger version of the same thing. It is a different design point. A single request can now hold an entire mid-size codebase, several full SEC filings, or years of chat history without chunking, embeddings, or a vector database. The paradigm the Gemini docs push is blunt: instead of retrieving the relevant slice, just put all the relevant information in the prompt and let the model reason over it.
This guide teaches one concrete, high-value workflow end to end: pack a real code repository into a single Gemini 3.5 Pro call, ask questions that span dozens of files, and then cache the codebase so follow-up questions cost a fraction of the first. Every code sample uses the official google-genai SDK and the patterns Google documents. By the end you will have a small script you can point at your own repo.
Prerequisites
- Python 3.9+ and a terminal.
- A Gemini API key from Google AI Studio (aistudio.google.com/apikey). The free tier is enough to test the workflow on a small repo.
- The official SDK:
pip install google-genai(this guide was written against google-genai 2.10). - Basic comfort reading Python. No ML background needed.
One note on the model name: use the exact model string shown in AI Studio for your account. During the GA rollout Google lists it as gemini-3-5-pro; the code below reads it from a single MODEL constant so you can swap it without touching anything else. Crucially, the long-context docs confirm the API surface is identical across models, so this same code works on Gemini 3 Flash or 2.5 Pro if you do not yet have 3.5 Pro access.
Step 1 - Install the SDK and make one call
Set your key as an environment variable so it never lands in source control, then confirm the client works:
export GEMINI_API_KEY="your_key_here"
from google import genai
from google.genai import types
# The client automatically reads GEMINI_API_KEY from the environment.
client = genai.Client()
MODEL = "gemini-3-5-pro" # swap for the exact string shown in AI Studio
resp = client.models.generate_content(
model=MODEL,
contents="In one sentence, what is a context window?",
)
print(resp.text)
Example output:
A context window is the maximum amount of text (measured in tokens) a
model can consider at once when generating a response.
If that prints, your key and model string are good. Everything else in this guide builds on the same client.models.generate_content call.
Step 2 - Count tokens before you send
The single most useful habit with long context is measuring your payload before you pay for it. Gemini bills per input token, and pricing steps up for very large prompts, so you want to know whether you are sending 40K tokens or 1.9M. The SDK exposes an exact server-side count:
def count_tokens(client, model, text):
result = client.models.count_tokens(model=model, contents=text)
return result.total_tokens
sample = "def add(a, b):\n return a + b\n" * 500
print(count_tokens(client, MODEL, sample)) # -> exact token count
Rule of thumb for a quick local estimate without an API round-trip: roughly 4 characters per token for code and English prose. That means 2M tokens is on the order of 8MB of source text. Use the estimate to decide whether to send, and count_tokens to confirm before a big or repeated job.
As a reference point, the Gemini team describes 1M tokens as about 50,000 lines of code or eight average novels. Two million doubles that headroom, which is what makes whole-repo prompting realistic rather than a demo trick.
Step 3 - Pack an entire repository into one prompt
Here is the core move. Walk the repo, keep only real source files, and concatenate them into one string with a clear delimiter before each file so the model knows where boundaries are. Skipping node_modules, .git, build artifacts, and lockfiles is not optional. That junk can be 10x your real code and will blow your token budget.
import pathlib
CODE_EXTS = {".py", ".js", ".ts", ".tsx", ".jsx", ".go",
".rs", ".java", ".rb", ".md"}
SKIP_DIRS = {".git", "node_modules", "__pycache__",
".venv", "venv", "dist", "build", ".next"}
def pack_repo(root: str) -> str:
root = pathlib.Path(root)
chunks = []
for path in sorted(root.rglob("*")):
if any(part in SKIP_DIRS for part in path.parts):
continue
if path.is_file() and path.suffix in CODE_EXTS:
rel = path.relative_to(root)
text = path.read_text(encoding="utf-8", errors="ignore")
chunks.append(f"===== FILE: {rel} =====\n{text}\n")
return "\n".join(chunks)
codebase = pack_repo("./my-project")
print("Estimated tokens:", len(codebase) // 4)
print("Exact tokens:", count_tokens(client, MODEL, codebase))
The FILE: headers matter more than they look. They give the model a stable way to cite exactly where an answer came from, which turns vague summaries into 'the bug is in src/auth/session.py, line ~40.'
Now ask a question that no single file can answer. Put the codebase first and your question last - Google's own guidance is that, for long prompts, the model performs measurably better when the query comes after all the context:
PROMPT = f"""You are a senior engineer reviewing this codebase.
{codebase}
Based on ALL the files above, answer:
Trace how a user request flows from the HTTP route to the database.
Name the exact files and functions involved, in order."""
resp = client.models.generate_content(model=MODEL, contents=PROMPT)
print(resp.text)
print("Input tokens used:", resp.usage_metadata.prompt_token_count)
Step 4 - A worked example: find a cross-file bug
Say a small FastAPI service intermittently returns stale data. The cause is spread across three files: a cache decorator in cache.py, a route in routes/items.py that forgets to pass a version key, and a config default in settings.py. A grep for 'cache' finds all three but cannot connect them. Long context can. Pack the repo (about 38K tokens for this service) and ask:
question = (
"Users report stale data on GET /items. Find the root cause. "
"Explain the interaction across files and give the exact fix."
)
prompt = f"{codebase}\n\n{question}"
resp = client.models.generate_content(model=MODEL, contents=prompt)
print(resp.text)
Representative output:
Root cause: the cache key in cache.py is built only from the path,
not the item version.
- settings.py sets CACHE_TTL = 3600 (1 hour), so entries live long.
- cache.py @cached() hashes only request.url.path as the key.
- routes/items.py updates an item but never invalidates or versions
the cache, so GET /items keeps returning the pre-update value.
Fix: include a version/updated_at value in the cache key, or call
cache.invalidate("/items") inside the update handler in
routes/items.py. Minimal change: add `version=item.updated_at` to
the key builder in cache.py.
That answer required reasoning over three files at once. That is the class of problem long context is genuinely good at, and it is why 'chat with your whole repo' took off the moment 2M windows shipped.
Step 5 - Cache the codebase to slash repeat-query cost
The first question pays full price for every input token. The second, third, and tenth question should not re-pay for the same 40K-token codebase. That is exactly what explicit context caching solves: upload the big prefix once, store it for a chosen time-to-live, and reference it cheaply on later calls.
There are two flavors. Implicit caching is on by default for Gemini 2.5 and newer and can give automatic discounts when requests share a prefix, but with no guarantee. Explicit caching takes a little more code and guarantees the savings. For a repeated whole-repo Q&A session, use explicit:
# Create a cache holding the codebase as a reusable prefix.
cache = client.caches.create(
model=MODEL,
config=types.CreateCachedContentConfig(
display_name="my-project-snapshot",
system_instruction="You are a senior engineer reviewing this repo.",
contents=[codebase],
ttl="1800s", # keep the cache alive for 30 minutes
),
)
print("Cache:", cache.name)
# Every follow-up question references the cache instead of resending code.
for q in [
"List every place we read an environment variable.",
"Where is authentication enforced, and where is it missing?",
"Which functions lack error handling on network calls?",
]:
r = client.models.generate_content(
model=MODEL,
contents=q,
config=types.GenerateContentConfig(cached_content=cache.name),
)
print("Q:", q)
print(r.text)
print("Cached tokens:", r.usage_metadata.cached_content_token_count)
client.caches.delete(cache.name) # clean up when done
The cached tokens are billed at a reduced rate plus a small storage charge for the TTL window, while your actual question each time is only a few dozen tokens. For code-review or 'chat with the repo' loops, this is the difference between a workflow you run once and one you run all day.
Common pitfalls and gotchas
- Multi-needle degradation. Single-fact retrieval hits ~99% accuracy, but asking for 20 separate facts in one shot drops precision. Split multi-part extraction into targeted questions (a cache makes this cheap) instead of one mega-prompt.
- Query at the top. Putting your question before a huge block of context measurably hurts answers. Always append the question after the context.
- Sending junk. If you forget to skip node_modules, vendored code, or minified bundles, you will pay for hundreds of thousands of useless tokens and dilute the signal. Filter aggressively.
- Cost above the long-context threshold. Pricing steps up past a high token threshold (around 200K on current Gemini tiers). Filling all 2M tokens on every call gets expensive fast - measure with count_tokens and cache anything reused.
- Inline size limits. Passing text directly in contents works up to the request-size limit. For very large or binary inputs (big PDFs, video, multi-hundred-MB dumps), upload with the Files API (client.files.upload) and pass the file handle instead.
- Cache minimums and TTL. Explicit caching has a per-model minimum token count (a few thousand tokens), so it is not worth it for tiny prompts. Caches also expire at their TTL - set it to cover your session and delete early to stop storage charges.
- Latency scales with input. A 1.5M-token prompt has a real time-to-first-token cost. For interactive UX, cache the prefix and keep per-turn questions short.
Quick reference
| Task | SDK call |
|---|---|
| Basic generation | client.models.generate_content(model, contents) |
| Count tokens first | client.models.count_tokens(model, contents) |
| Read tokens actually billed | resp.usage_metadata.prompt_token_count |
| Create explicit cache | client.caches.create(model, config=CreateCachedContentConfig(...)) |
| Query against a cache | GenerateContentConfig(cached_content=cache.name) |
| Check cache hit size | resp.usage_metadata.cached_content_token_count |
| Upload a huge file | client.files.upload(file=...) |
| Delete a cache | client.caches.delete(cache.name) |
Next steps
- Point pack_repo at one of your own projects and ask it to write missing docstrings or a README from the actual code.
- Add the Files API path so you can drop in PDFs and design docs alongside code for whole-context product Q&A.
- Wrap the cache-and-ask loop in a small CLI so teammates can 'chat with the repo' from the terminal.
- Benchmark a long-context prompt against your existing RAG pipeline on the same questions - many teams find they can retire a vector DB for internal tools.
- Read Google's long-context and context-caching docs for the current per-model token minimums and pricing tiers before you ship to production.
Gemini 3.5 Pro pricing and the exact GA model string were still settling during the late-June 2026 rollout; confirm both in Google AI Studio and the official pricing page before you budget a production workload.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,604 newsletter subscribers.