google-gemini-file-search
Build document Q&A and searchable knowledge bases with Google Gemini File Search - fully managed RAG with automatic chunking, embeddings, and citations. Upload 100+ file formats (PDF, Word, Excel, code), configure semantic search, and query with natural language. Use when: building document Q&A systems, creating searchable knowledge bases, implementing semantic search without managing embeddings, indexing large document collections (100+ formats), or troubleshooting document immutability errors (delete+re-upload required), storage quota issues (3x input size for embeddings), chunking configuration (500 tokens/chunk recommended), metadata limits (20 key-value pairs max), indexing cost surprises ($0.15/1M tokens one-time), operation polling timeouts (wait for done: true), force delete errors, or model compatibility (Gemini 2.5 Pro/Flash only).
What this skill does
# Google Gemini File Search Setup
## Overview
Google Gemini File Search is a fully managed RAG (Retrieval-Augmented Generation) system that eliminates the need for separate vector databases, custom chunking logic, or embedding generation code. Upload documents (PDFs, Word, Excel, code files, etc.) and query them using natural language—Gemini automatically handles intelligent chunking, embedding with its optimized model, semantic search, and citation generation.
**What This Skill Provides:**
- Complete setup guide for @google/genai File Search API
- TypeScript/JavaScript SDK configuration patterns
- Working templates for 3 deployment scenarios (Node.js, Cloudflare Workers, Next.js)
- 8 documented common errors with prevention strategies
- Chunking best practices for optimal retrieval
- Cost optimization techniques
- Comparison guide (vs Cloudflare Vectorize, OpenAI Files API, Claude MCP)
**Key Features of File Search:**
- **100+ File Formats**: PDF, Word (.docx), Excel (.xlsx), PowerPoint (.pptx), Markdown, JSON, CSV, code files (Python, JavaScript, TypeScript, Java, C++, Go, Rust, etc.)
- **Automatic Embeddings**: Uses Google's Gemini Embedding model (no custom embedding code required)
- **Semantic Search**: Vector-based search understands meaning and context, not just keywords
- **Built-in Citations**: Grounding metadata automatically points to specific document sections
- **Custom Metadata**: Filter queries by up to 20 custom key-value pairs per document
- **Configurable Chunking**: Control chunk size (tokens) and overlap for precision tuning
- **Cost-Effective**: $0.15/1M tokens for one-time indexing, free storage (up to limits), free query-time embeddings
## When to Use This Skill
**Ideal Use Cases:**
- Building customer support knowledge bases (manuals, FAQs, troubleshooting guides)
- Creating internal documentation search (company wikis, policies, procedures)
- Legal/compliance document analysis (contracts, regulations, case law)
- Research tools (academic papers, articles, textbooks)
- Code documentation search (API docs, SDK references, examples)
- Product information retrieval (specs, datasheets, user guides)
**Use File Search When:**
- ✅ You want a fully managed RAG solution (no vector DB setup)
- ✅ Cost predictability matters (pay-per-indexing, not continuous storage fees)
- ✅ You need broad file format support (100+ types out of the box)
- ✅ Citations are important (built-in grounding metadata)
- ✅ Simple deployment is priority (single API setup)
- ✅ Documents are relatively static (updates are infrequent)
**Use Cloudflare Vectorize/AutoRAG Instead When:**
- ✅ Global edge performance is critical (low-latency worldwide)
- ✅ Building full-stack apps on Cloudflare (Workers, R2, D1)
- ✅ You need custom embedding models or retrieval logic
- ✅ Real-time data updates from R2 or external sources
**Use OpenAI Files API Instead When:**
- ✅ Already using OpenAI Assistants API (conversational threads)
- ✅ Need to attach knowledge to persistent assistant threads
- ✅ Working with very large file collections (10,000+ files per store)
- ✅ Prefer storage-based pricing model ($0.10/GB/day)
## When NOT to Use This Skill
Skip this skill if:
- ❌ Need custom embedding models (File Search locks you to Gemini Embeddings)
- ❌ Documents update frequently (no streaming updates, must delete+re-upload)
- ❌ Building conversational AI agents (use OpenAI Assistants or Claude MCP instead)
- ❌ Need BM25/hybrid search (File Search is vector-only)
- ❌ Require advanced reranking configuration (automatic only)
- ❌ Need to parse images/tables from PDFs (text extraction only)
## Prerequisites
### 1. Google AI API Key
Create an API key at https://aistudio.google.com/apikey
**Free Tier Limits:**
- 1 GB storage (total across all file search stores)
- 1,500 requests per day
- 1 million tokens per minute
**Paid Tier Pricing:**
- Indexing: $0.15 per 1M input tokens (one-time)
- Storage: Free (Tier 1: 10 GB, Tier 2: 100 GB, Tier 3: 1 TB)
- Query-time embeddings: Free (retrieved context counts as input tokens)
### 2. Node.js Environment
**Minimum Version:** Node.js 18+ (v20+ recommended)
```bash
node --version # Should be >=18.0.0
```
### 3. Install @google/genai SDK
```bash
npm install @google/genai
# or
pnpm add @google/genai
# or
yarn add @google/genai
```
**Current Stable Version:** 0.21.0+ (verify with `npm view @google/genai version`)
### 4. TypeScript Configuration (Optional but Recommended)
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true
}
}
```
## Common Errors Prevented
This skill prevents 8 common errors encountered when implementing File Search:
### Error 1: Document Immutability
**Symptom:**
```
Error: Documents cannot be modified after indexing
```
**Cause:** Documents are immutable once indexed. There is no PATCH or UPDATE operation.
**Prevention:**
Use the delete+re-upload pattern for updates:
```typescript
// ❌ WRONG: Trying to update document (no such API)
await ai.fileSearchStores.documents.update({
name: documentName,
customMetadata: { version: '2.0' }
})
// ✅ CORRECT: Delete then re-upload
const docs = await ai.fileSearchStores.documents.list({
parent: fileStore.name
})
const oldDoc = docs.documents.find(d => d.displayName === 'manual.pdf')
if (oldDoc) {
await ai.fileSearchStores.documents.delete({
name: oldDoc.name,
force: true
})
}
await ai.fileSearchStores.uploadToFileSearchStore({
name: fileStore.name,
file: fs.createReadStream('manual-v2.pdf'),
config: { displayName: 'manual.pdf' }
})
```
**Source:** https://ai.google.dev/api/file-search/documents
### Error 2: Storage Quota Exceeded
**Symptom:**
```
Error: Quota exceeded. Expected 1GB limit, but 3.2GB used.
```
**Cause:** Storage calculation includes input files + embeddings + metadata. Total storage ≈ 3x input size.
**Prevention:**
Calculate storage before upload:
```typescript
// ❌ WRONG: Assuming storage = file size
const fileSize = fs.statSync('data.pdf').size // 500 MB
// Expect 500 MB usage → WRONG
// ✅ CORRECT: Account for 3x multiplier
const fileSize = fs.statSync('data.pdf').size // 500 MB
const estimatedStorage = fileSize * 3 // 1.5 GB (embeddings + metadata)
console.log(`Estimated storage: ${estimatedStorage / 1e9} GB`)
// Check if within quota before upload
if (estimatedStorage > 1e9) {
console.warn('⚠️ File may exceed free tier 1 GB limit')
}
```
**Source:** https://blog.google/technology/developers/file-search-gemini-api/
### Error 3: Incorrect Chunking Configuration
**Symptom:**
Poor retrieval quality, irrelevant results, or context cutoff mid-sentence.
**Cause:** Default chunking may not be optimal for your content type.
**Prevention:**
Use recommended chunking strategy:
```typescript
// ❌ WRONG: Using defaults without testing
await ai.fileSearchStores.uploadToFileSearchStore({
name: fileStore.name,
file: fs.createReadStream('docs.pdf')
// Default chunking may be too large or too small
})
// ✅ CORRECT: Configure chunking for precision
await ai.fileSearchStores.uploadToFileSearchStore({
name: fileStore.name,
file: fs.createReadStream('docs.pdf'),
config: {
chunkingConfig: {
whiteSpaceConfig: {
maxTokensPerChunk: 500, // Smaller chunks = more precise retrieval
maxOverlapTokens: 50 // 10% overlap prevents context loss
}
}
}
})
```
**Chunking Guidelines:**
- **Technical docs/code:** 500 tokens/chunk, 50 overlap
- **Prose/articles:** 800 tokens/chunk, 80 overlap
- **Legal/contracts:** 300 tokens/chunk, 30 overlap (high precision)
**Source:** https://www.philschmid.de/gemini-file-search-javascript
### Error 4: Metadata Limits Exceeded
**Symptom:**
```
Error: Maximum 20 custom metadata key-value pairs allowed
```
**Cause:** Each document can have at most 20 metadata fields.
**Prevention:**
Design compact metadata schema:
```Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.