/rag-pipeline:google-file-searchfrom rag-pipeline
Implements Google File Search API for managed RAG with Gemini. Covers TypeScript (@google/genai) and Python (google-genai) SDKs for document indexing, semantic search, and metadata filtering.
Ships in rag-pipeline. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Comprehensive skill for implementing Google File Search API with Gemini models for Retrieval-Augmented Generation (RAG).
Google File Search provides managed RAG capabilities through:
Two Official SDKs are available:
@google/genai npm packagegoogle-genai pip packageDo NOT use manual REST API calls or deprecated packages. Always use the official SDKs.
npm install @google/genai
pip install google-genai
CRITICAL: Never hardcode API keys.
// ✅ CORRECT - TypeScript
const ai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY! });
// ❌ WRONG
const ai = new GoogleGenAI({ apiKey: 'sk-abc123...' });
# ✅ CORRECT - Python
client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
# ❌ WRONG
client = genai.Client(api_key="sk-abc123...")
Get API keys from: https://aistudio.google.com/apikey
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY! });
const store = await ai.fileSearchStores.create({
config: { displayName: 'my-knowledge-base' }
});
console.log(`Store created: ${store.name}`);
Use uploadToFileSearchStore() which uploads AND indexes in one operation.
async function uploadFile(storeName: string, filePath: string, filename: string) {
let operation = await ai.fileSearchStores.uploadToFileSearchStore({
file: filePath,
fileSearchStoreName: storeName,
config: { displayName: filename }
});
// Wait for indexing to complete
while (!operation.done) {
await new Promise(resolve => setTimeout(resolve, 2000));
operation = await ai.operations.get({ operation });
}
console.log(`Indexed: ${filename}`);
}
async function search(storeName: string, query: string) {
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: query,
config: {
tools: [{
fileSearch: {
fileSearchStoreNames: [storeName]
}
}]
}
});
const sources = response.candidates?.[0]?.groundingMetadata?.groundingChunks?.map((c: any) => ({
uri: c.retrievedContext?.uri,
title: c.retrievedContext?.title
})) || [];
return { answer: response.text, sources };
}
// app/api/rag/route.ts
import { GoogleGenAI } from '@google/genai';
import { NextResponse } from 'next/server';
const ai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY! });
export async function POST(request: Request) {
const { query, storeId } = await request.json();
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: query,
config: {
tools: [{ fileSearch: { fileSearchStoreNames: [storeId] }}],
systemInstruction: 'Answer based on the documents. Cite sources.'
}
});
const sources = response.candidates?.[0]?.groundingMetadata?.groundingChunks?.map((c: any) => ({
uri: c.retrievedContext?.uri,
title: c.retrievedContext?.title
})) || [];
return NextResponse.json({ answer: response.text, sources });
}
import os
from google import genai
from google.genai import types
client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
store = client.file_search_stores.create(
config={"display_name": "my-knowledge-base"}
)
print(f"Store created: {store.name}")
Use upload_to_file_search_store() which uploads AND indexes in one operation.
import time
from pathlib import Path
def upload_file(store_name: str, file_path: str, filename: str = None):
path = Path(file_path)
operation = client.file_search_stores.upload_to_file_search_store(
file=str(path),
file_search_store_name=store_name,
config={"display_name": filename or path.name}
)
# Wait for indexing to complete
while not operation.done:
time.sleep(2)
operation = client.operations.get(operation)
print(f"Indexed: {path.name}")
def search(store_name: str, query: str, model: str = "gemini-2.5-flash"):
file_search = types.FileSearch(file_search_store_names=[store_name])
tool = types.Tool(file_search=file_search)
response = client.models.generate_content(
model=model,
contents=query,
config=types.GenerateContentConfig(tools=[tool])
)
sources = []
if response.candidates:
gm = getattr(response.candidates[0], 'grounding_metadata', None)
if gm and hasattr(gm, 'grounding_chunks'):
for chunk in gm.grounding_chunks:
rc = getattr(chunk, 'retrieved_context', None)
if rc:
sources.append({
"uri": getattr(rc, 'uri', ''),
"title": getattr(rc, 'title', '')
})
return {"answer": response.text, "sources": sources}
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from google import genai
from google.genai import types
import os
app = FastAPI()
client = genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
class RAGQuery(BaseModel):
query: str
store_id: str
@app.post("/rag/search")
async def rag_search(request: RAGQuery):
try:
file_search = types.FileSearch(file_search_store_names=[request.store_id])
tool = types.Tool(file_search=file_search)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=request.query,
config=types.GenerateContentConfig(tools=[tool])
)
sources = []
if response.candidates:
gm = getattr(response.candidates[0], 'grounding_metadata', None)
if gm and hasattr(gm, 'grounding_chunks'):
for chunk in gm.grounding_chunks:
rc = getattr(chunk, 'retrieved_context', None)
if rc:
sources.append({
"uri": getattr(rc, 'uri', ''),
"title": getattr(rc, 'title', '')
})
return {"answer": response.text, "sources": sources}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
Documents: PDF, DOCX, ODT, PPTX, XLSX, CSV, TXT, MD Code: Python, JavaScript, Java, TypeScript, Go, Rust, SQL Data: JSON, XML, YAML, HTML Archives: ZIP (automatically extracted)
Over 100 MIME types supported.
Per-Document:
Total Storage by Tier:
await ai.fileSearchStores.uploadToFileSearchStore({
file: filePath,
fileSearchStoreName: storeName,
config: {
displayName: filename,
chunkingConfig: {
whiteSpaceConfig: {
maxTokensPerChunk: 200,
maxOverlapTokens: 20
}
}
}
});
client.file_search_stores.upload_to_file_search_store(
file=file_path,
file_search_store_name=store_name,
config={
"display_name": filename,
"chunking_config": {
"white_space_config": {
"max_tokens_per_chunk": 200,
"max_overlap_tokens": 20
}
}
}
)
config: {
displayName: filename,
customMetadata: [
{ key: 'author', stringValue: 'John Doe' },
{ key: 'year', numericValue: 2024 }
]
}
config={
"display_name": filename,
"custom_metadata": [
{"key": "author", "string_value": "John Doe"},
{"key": "year", "numeric_value": 2024}
]
}
file_search = types.FileSearch(
file_search_store_names=[store_name]
)
file_search.metadata_filter = 'author="John Doe" AND year >= 2024'
Chunk Size Optimization
Metadata Strategy
Store Organization
Citation Handling
Issue: Files not uploading
Issue: Poor search results
Issue: Missing citations
templates/typescript-client.ts - Complete TypeScript clienttemplates/python-client.py - Complete Python clienttemplates/store-config.json - Store configurationtemplates/chunking-config.json - Chunking settingstemplates/env.example - Environment variablesSkill Version: 2.0.0 Last Updated: 2026-01-30 Compatible With: Gemini 2.5 Pro/Flash, @google/genai (TS), google-genai (Python)
examples/advanced-chunking.md (opens in a new tab)examples/basic-setup.md (opens in a new tab)examples/grounding-citations.md (opens in a new tab)examples/metadata-filtering.md (opens in a new tab)examples/multi-store.md (opens in a new tab)scripts/configure_chunking.py (opens in a new tab)scripts/extract_citations.py (opens in a new tab)scripts/search_query.py (opens in a new tab)scripts/setup_file_search.py (opens in a new tab)scripts/upload_documents.py (opens in a new tab)scripts/validate_setup.py (opens in a new tab)templates/chunking-config.json (opens in a new tab)templates/env.example (opens in a new tab)templates/metadata-schema.json (opens in a new tab)templates/python-client.py (opens in a new tab)templates/store-config.json (opens in a new tab)templates/typescript-client.ts (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub vanman2024/ai-dev-marketplace --plugin rag-pipeline3 skills in this plugin
/chunking-strategiesDocument chunking implementations and benchmarking tools for RAG pipelines including fixed-size, semantic, recursive, and sentence-based strategies. Use when implementing document processing, optimizing chunk sizes, comparing chunking approaches, benchmarking retrieval performance, or when user mentions chunking, text splitting, document segmentation, RAG optimization, or chunk evaluation./document-parsersMulti-format document parsing tools for PDF, DOCX, HTML, and Markdown with support for LlamaParse, Unstructured.io, PyPDF2, PDFPlumber, and python-docx. Use when parsing documents, extracting text from PDFs, processing Word documents, converting HTML to text, extracting tables from documents, building RAG pipelines, chunking documents, or when user mentions document parsing, PDF extraction, DOCX processing, table extraction, OCR, LlamaParse, Unstructured.io, or document ingestion.Other plugins' skills for the same job