The Gemini API has a built-in RAG system called the File Search tool. You upload documents to a store, Google chunks and indexes them, and Gemini answers questions from them with citations.
This tutorial walks through the whole thing in Python, with code copied from the current docs. It also covers the real costs, the limits, and the errors you are likely to hit.
- What it is: managed RAG inside the Gemini API. No vector database, no chunking code, no embedding calls.
- Cost: you pay only to embed files when you index them ($0.15 per 1M tokens with gemini-embedding-001, $0.20 with gemini-embedding-2 text). Storage and query embeddings are free.
- Catch: retrieved chunks are billed as normal input tokens on the model you call.
- Limits: 100 MB per file, 1 GB of stores on the Free tier, up to 1 TB on Tier 3.
- SDK:
google-genai(version 3.7.0 was current on 3 Dec 2026).
What the File Search Tool Is (and When to Use It)
File Search is Google’s managed Retrieval Augmented Generation tool for the Gemini API. It launched in public preview on 6 November 2025. Since then it has gained image search (May 2026) and support in the newer Interactions API.
Normally RAG means you build a pipeline yourself. File Search replaces that pipeline with a few API calls.
- Chunking: your files are split into pieces automatically, or with your own token sizes.
- Embeddings: each chunk is embedded with gemini-embedding-001 or gemini-embedding-2.
- Storage: the embeddings live in a File Search store that never expires.
- Retrieval: Gemini runs a semantic search when it needs facts and grounds its answer on the best chunks.
- Citations: the response tells you which file (and which PDF page) each fact came from.
Use it for internal docs chatbots, support bots over a help centre, policy and contract Q&A, or code search over a repository. If you only need to ask about one file once, simply passing the file in the prompt is easier. See my Gemini API Python tutorial for that.
How File Search Works
File Search uses semantic search, not keyword search. Your query is turned into an embedding and compared with the stored chunk embeddings, so it finds text that means the same thing even when the words differ.
There are three moving parts:
- File Search store: a persistent container for your document embeddings. Store names are globally scoped.
- Documents: each file you import becomes a document inside a store. You can list, get and delete them.
- The file_search tool: you pass the store name as a tool in a model call, and the model decides when to search it.
Note: Raw files uploaded through the Files API are deleted after 48 hours. The data imported into a File Search store stays until you delete it. Embeddings have no expiry, though they go away if the embedding model is deprecated.
Setup: API Key, SDK and Your First Store
You need Python 3.9 or newer, a Gemini API key from Google AI Studio, and the official google-genai SDK. I checked the examples below against the docs on 3 December 2026, when version 3.7.0 was the latest on PyPI.
- Get an API key. Open Google AI Studio, click Get API key, and create one. My Google AI Studio guide shows the screens.
- Save it as an environment variable. On Mac or Linux run
export GEMINI_API_KEY="your-key". On Windows PowerShell run$env:GEMINI_API_KEY="your-key". The SDK reads it automatically. - Install the SDK. Run
pip install -U google-genaiin a virtual environment. - Prepare a test file. Any PDF, DOCX, TXT, Markdown or code file under 100 MB works. The examples use
handbook.pdf. - Pick a model. The docs use
gemini-4-hydrogen, which also works on the free tier. Any model in the supported list below works too.
Warning: Never paste your key into code or commit it to Git. Google blocks keys that it detects as leaked, and you will get a 403 error.
Example 1: Upload a File and Ask a Question
This is the shortest path. It creates a store, uploads and indexes a file in one call, waits for indexing to finish, then asks a question. The docs now mark the Interactions API as recommended, so this example uses client.interactions.create.
import time
from google import genai
client = genai.Client() # reads GEMINI_API_KEY
# 1. Create a store
store = client.file_search_stores.create(
config={
"display_name": "company-handbook",
"embedding_model": "models/gemini-embedding-2",
}
)
print("Store:", store.name)
# 2. Upload + index in one step (the display name shows in citations)
operation = client.file_search_stores.upload_to_file_search_store(
file="handbook.pdf",
file_search_store_name=store.name,
config={"display_name": "Employee Handbook 2026"},
)
# 3. Wait for indexing
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
# 4. Ask a question grounded on the store
interaction = client.interactions.create(
model="gemini-4-hydrogen",
input="How many days of paid leave do new employees get?",
tools=[{
"type": "file_search",
"file_search_store_names": [store.name],
}],
)
for step in interaction.steps:
if step.type == "model_output":
for block in step.content:
if block.type == "text":
print(block.text)
for ann in block.annotations or []:
if ann.type == "file_citation":
print(" -", ann.file_name, ann.source)
Save store.name (it looks like fileSearchStores/...). You reuse it for every future query, so you only pay to index once.
The same query with generate_content
If your app still uses the older generateContent API, File Search works there too. You pass a types.Tool with a types.FileSearch inside.
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-4-hydrogen",
contents="How many days of paid leave do new employees get?",
config=types.GenerateContentConfig(
tools=[
types.Tool(
file_search=types.FileSearch(
file_search_store_names=["fileSearchStores/your-store-id"]
)
)
]
),
)
print(response.text)
Example 2: Import Files with Custom Chunking
The second route is to upload with the Files API first, then import the file into a store. This is handy when the same file is also used in normal prompts, or when you import one file into several stores.
By default the service picks chunk sizes for you. You can control them with chunking_config. The docs example uses 200 tokens per chunk with 20 tokens of overlap.
import time
from google import genai
client = genai.Client()
STORE = "fileSearchStores/your-store-id"
# Upload to the Files API (raw file is deleted after 48 hours)
sample = client.files.upload(
file="refund-policy.md",
config={"display_name": "Refund Policy"},
)
# Import into the store with custom chunking and metadata
operation = client.file_search_stores.import_file(
file_search_store_name=STORE,
file_name=sample.name,
config={
"chunking_config": {
"white_space_config": {
"max_tokens_per_chunk": 200,
"max_overlap_tokens": 20,
}
},
"custom_metadata": [
{"key": "department", "string_value": "support"},
{"key": "year", "numeric_value": 2026},
],
},
)
while not operation.done:
time.sleep(5)
operation = client.operations.get(operation)
print("Imported:", sample.name)
Tip: Use file= with upload_to_file_search_store and file_name= with import_file. Mixing them up is a common cause of “unexpected keyword” errors. Small chunks give precise citations, while bigger chunks keep more context for long policy text.
Example 3: Search Only Some Files with Metadata Filters
Custom metadata is a list of key-value pairs. Each value is either a string_value or a numeric_value. At query time, metadata_filter limits the search to matching documents.
from google import genai
client = genai.Client()
STORE = "fileSearchStores/your-store-id"
interaction = client.interactions.create(
model="gemini-4-hydrogen",
input="What is our refund window for annual plans?",
tools=[{
"type": "file_search",
"file_search_store_names": [STORE],
"metadata_filter": 'department="support" AND year >= 2026',
}],
)
print(interaction.output_text)
The filter syntax follows Google’s AIP-160 list filtering standard. Put string values in double quotes, as in the official author="Robert Graves" example. Numbers can use comparison operators.
- Multi-tenant apps: tag each file with a
customer_idand filter on it, so one customer never sees another’s chunks. - Versioned docs: tag with
yearorversionand filter to the latest. - Departments: tag HR, legal and support files and let users pick a scope.
Example 4: Read Citations, Page Numbers and Metadata
Citations are the main reason to use File Search over stuffing text into a prompt. With the Interactions API they arrive as file_citation annotations on each text block.
for step in interaction.steps:
if step.type != "model_output":
continue
for block in step.content:
if block.type != "text" or not block.annotations:
continue
for ann in block.annotations:
if ann.type == "file_citation":
print("File:", ann.file_name)
if ann.page_number:
print(" Page:", ann.page_number)
if ann.media_id:
# image chunk from a gemini-embedding-2 store
blob = client.file_search_stores.download_media(
media_id=ann.media_id
)
With generate_content, the same data lives in response.candidates[0].grounding_metadata. Loop over grounding_chunks and read retrieved_context, which holds text, title, page_number, media_id and custom_metadata.
gm = response.candidates[0].grounding_metadata
for chunk in gm.grounding_chunks:
ctx = chunk.retrieved_context
if ctx:
print(ctx.title, "page", ctx.page_number)
for m in ctx.custom_metadata or []:
print(" ", m.key, m.string_value or m.numeric_value)
File Search also works with structured output on Gemini 3 and newer models. Pass a JSON schema (for example from a Pydantic model) and you get grounded JSON back. My structured outputs guide covers the schema side.
Querying a Store with curl (REST)
You can create the store and upload files from Python, then query from any language over REST. This call uses the generateContent endpoint with a metadata filter.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-4-hydrogen:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X POST \
-d '{
"contents": [{"parts": [{"text": "What is our refund window?"}]}],
"tools": [{
"file_search": {
"file_search_store_names": ["fileSearchStores/your-store-id"],
"metadata_filter": "department = \"support\""
}
}]
}'
The citations come back under candidates[0].groundingMetadata in camelCase.
Managing Stores and Documents
Stores and documents have simple list, get and delete calls. This is how you clean up test data and avoid hitting your storage cap.
from google import genai
client = genai.Client()
# List all stores in the project
for s in client.file_search_stores.list():
print(s.name, s.display_name)
STORE = "fileSearchStores/your-store-id"
# List documents in one store
for doc in client.file_search_stores.documents.list(parent=STORE):
print(doc.name)
# Delete one document
client.file_search_stores.documents.delete(
name=f"{STORE}/documents/your-doc-id",
config={"force": True},
)
# Delete a whole store, including its documents
client.file_search_stores.delete(name=STORE, config={"force": True})
Warning: Deleting a store removes its embeddings for good. You will pay the indexing cost again if you re-import the files.
Supported File Types and Models
File Search accepts a long list of MIME types. The docs list about 30 application types and over 150 text types. Audio and video are not supported.
| Group | Examples |
|---|---|
| Documents | PDF, DOC/DOCX, ODT, XLS/XLSX, PPTX, HWP, LaTeX |
| Data | JSON, XML, CSV, TSV, YAML, SQL, Jupyter notebooks, ZIP |
| Text and web | TXT, Markdown, HTML, CSS, RTF, calendar files, VTT subtitles |
| Code | Python, JavaScript, TypeScript, Java, C, Dart, PHP, shell and PowerShell scripts |
| Images (multimodal stores only) | PNG and JPEG, up to 4K x 4K pixels, with gemini-embedding-2 |
For image search, create the store with "embedding_model": "models/gemini-embedding-2". The default embedding model is text-only. My Gemini Embedding 2 tutorial explains that model in depth.
Models that support File Search
The docs list these models as of 3 December 2026:
- Gemini 4: Carbon, Neon, Hydrogen, and Argon (Argon is deprecated and routes to Carbon from 15 December 2026).
- Gemini 3.x: 3.8 Flash, 3.6 Flash, 3.5 Flash-Lite, 3.1 Pro Preview, 3.1 Flash-Lite, 3 Flash Preview.
- Gemini 2.5: 2.5 Flash-Lite only. Gemini 2.5 Pro and 2.5 Flash now route to newer models since 1 December 2026.
Pricing and a Worked Cost Example
File Search has an unusual pricing model. Google charges once, when you index, and then only for normal model tokens. I re-checked these numbers on the official pricing page on 3 December 2026, after the 1 December price changes.

| Cost item | Free tier | Paid tier |
|---|---|---|
| Indexing with gemini-embedding-001 | Free | $0.15 per 1M tokens |
| Indexing with gemini-embedding-2 (text) | Free | $0.20 per 1M tokens |
| Indexing with gemini-embedding-2 (images) | Free | $0.45 per 1M tokens (about $0.00012 per image) |
| Storage | Free | Free |
| Query-time embeddings | Free | Free |
| Retrieved chunks + your prompt | Free (free models) | Input token rate of the model |
| Model answer | Free (free models) | Output token rate of the model |
The model rates matter more than indexing. On 3 December 2026, Gemini 4 Hydrogen costs $1.50 input and $7.50 output per 1M tokens. Gemini 3.8 Flash costs $0.75 and $3.75 until 31 December 2026, then doubles to $1.50 and $7.50 from 1 January 2027.
Worked example
Say you index a help centre of 10 million tokens and then answer 10,000 questions a month on Gemini 4 Hydrogen. Assume each question pulls about 5,000 tokens of chunks, adds a 200-token prompt, and gets a 500-token answer. The real retrieved amount varies by query.
- Indexing (one time): 10M x $0.15/1M = $1.50 with gemini-embedding-001, or $2.00 with gemini-embedding-2.
- Input per query: 5,200 x $1.50/1M = $0.0078.
- Output per query: 500 x $7.50/1M = $0.00375.
- Monthly queries: 10,000 x $0.01155 = about $115.50.
The same workload on Gemini 3.8 Flash comes to about $57.75 a month in December 2026. So the model choice, and how many chunks get retrieved, drive almost all of the bill. Compare all model rates in my Gemini API pricing guide.
Limits You Need to Know
The limits are mostly about size, and they depend on your usage tier.

| Limit | Value |
|---|---|
| Max size per file | 100 MB |
| Total store size, Free tier | 1 GB |
| Total store size, Tier 1 | 10 GB |
| Total store size, Tier 2 | 100 GB |
| Total store size, Tier 3 | 1 TB |
| Recommended size per store | Under 20 GB, for fast retrieval |
| Image size (multimodal) | Up to 4K x 4K, PNG or JPEG |
| Raw file retention | 48 hours (store data stays until deleted) |
Note: Store size counts your input plus the embeddings, which is usually about 3 times the input. So 300 MB of PDFs can use roughly 900 MB of a 1 GB Free tier quota.
Two feature limits matter as well:
- No Live API: File Search does not work in the Live API.
- No mixing with search tools: you cannot combine it with Grounding with Google Search or URL Context in the same request. You can combine it with your own function calling on Gemini 3 and 4 models (see my function calling tutorial).
File Search vs Building Your Own RAG
File Search is not always the right call. Here is how it compares with a do-it-yourself stack (an embedding model plus a vector database such as pgvector, Pinecone or Chroma).
| Factor | Gemini File Search | Your own RAG |
|---|---|---|
| Setup time | Minutes, a few API calls | Days: parsers, chunker, vector DB, retriever |
| Storage cost | Free | You pay for the vector database |
| Chunking control | Token size and overlap only | Any strategy (by heading, semantic, hybrid) |
| Retrieval control | Model decides; metadata filters | Full control: top-k, reranking, hybrid keyword search |
| Citations | Built in, with page numbers | You build them |
| Model choice | Gemini models only | Any LLM |
| Data location | Google’s servers | Wherever you host it |
Troubleshooting: Common Problems and Fixes
These are the errors and odd results you are most likely to see. The status codes come from the official Gemini API troubleshooting guide. For more general fixes, see my Gemini API errors guide.
| Error or symptom | Likely cause | Fix |
|---|---|---|
429 RESOURCE_EXHAUSTED |
Rate limit for your tier | Retry with exponential backoff and jitter. The Python SDK already retries up to four times. |
503 UNAVAILABLE |
Temporary overload | Retry with backoff. Do not retry 400 or 403 errors. |
403 PERMISSION_DENIED, “Your project has been denied access” |
Project needs verification, billing, or is restricted | Check the project status in AI Studio. Verify the account or link billing. |
| “Your API key was reported as leaked. Please use another API key.” | Key found in public code | Create a new key and store it in an environment variable. |
400 INVALID_ARGUMENT with Google Search or URL Context |
Those tools cannot be combined with File Search | Send them in separate requests. |
404 NOT_FOUND on a store |
Wrong name or store was deleted | Use the full name, such as fileSearchStores/abc123, from list(). |
| Upload rejected | File over 100 MB, audio/video, or an unsupported MIME type | Split the file or convert it to PDF, DOCX or TXT. |
| Image import fails | Store uses the text-only embedding model | Create a new store with models/gemini-embedding-2. |
| Answer ignores your files | Query ran before indexing finished | Poll until operation.done is true before querying. |
| Wrong or empty citations | Filter excluded everything, or chunks too small | Test without metadata_filter, then try larger chunks. |
| Store quota reached | Embeddings make stores about 3x the input size | Delete old documents or move up a usage tier. |
Frequently Asked Questions
Is the Gemini File Search tool free?
On the free tier, indexing and queries are free with the free models. On the paid tier, storage and query embeddings are free, but indexing costs $0.15 per 1M tokens with gemini-embedding-001, and retrieved chunks are billed as input tokens.
Do File Search stores expire?
No. Data in a File Search store stays until you delete it, or until its embedding model is deprecated. Only the raw files in the Files API are deleted after 48 hours.
Which embedding model should I choose?
Use gemini-embedding-001 for text-only stores, since it is the cheapest at $0.15 per 1M tokens. Choose gemini-embedding-2 ($0.20 per 1M text tokens) if you need image search or want the newer model.
Can I use File Search with Google Search grounding?
Not in the same request. The docs say File Search cannot be combined with Grounding with Google Search or URL Context yet. It can be combined with your own function calls on Gemini 3 and 4 models.
Can File Search read audio or video files?
No. Audio and video are not supported. Images work only as PNG or JPEG in a store that uses gemini-embedding-2.
How big can my knowledge base be?
Each file can be up to 100 MB. Total store size per project ranges from 1 GB on the Free tier to 1 TB on Tier 3, and Google suggests keeping each store under 20 GB.
Should I use the Interactions API or generate_content?
Both support File Search. The docs mark the Interactions API as recommended for new projects, but generate_content works fine if your app already uses it.



