Source Code:
src/gaia/rag/sdk.pyWhat You’ll Learn: What RAG is and why you need it, how documents become searchable through chunking and embeddings, how to configure RAG for different use cases, how to tune parameters for quality vs. speed, what Agentic RAG is and how it differs from traditional RAG, how to implement multi-step retrieval patterns, and common pitfalls and how to avoid them.
The Problem RAG Solves
LLMs have a knowledge cutoff—they don’t know about your company’s documents, your project’s codebase, or yesterday’s meeting notes.- Without RAG
- With RAG
- Retrieval → Find relevant information from your documents
- Augmented → Add that information to the LLM’s context
- Generation → LLM generates an answer using your documents
Supported document formats: PDF, Word (
.docx), PowerPoint (.pptx),
Excel (.xlsx), plus plain text, Markdown, CSV, JSON, HTML, and common source
code files. Legacy binary Office formats (.doc, .ppt, .xls) are not
supported — re-save them as the modern .docx / .pptx / .xlsx formats.How RAG Works: A Mental Model
Think of RAG as a smart research assistant:Phase 1: Preparation (Indexing)
This happens once when you index documents:Phase 2: Query (Retrieval)
This happens each time you ask a question:Key Insight: The magic is in the vectors. Text that has similar meaning ends up with similar vectors—even if the words are different. “System requirements” and “hardware needed” would have similar vectors because they mean similar things.
Getting Started with RAG
Quick RAG: One-Line Document Q&A
For simple use cases,quick_rag handles everything in one call:
- Extracts text from the PDF
- Splits into chunks (default: 500 tokens each)
- Generates embeddings for all chunks
- Creates temporary FAISS index
- Searches for relevant chunks
- Sends chunks + question to LLM
- Returns the generated answer as a string
RAG SDK: Persistent Index
For applications where you’ll ask multiple questions, create a persistent RAG instance:Understanding Chunks
Chunking is the most important concept in RAG. Let’s understand it deeply.Why Do We Need Chunks?
LLMs have limited context windows. You can’t send a 500-page PDF directly. Instead:What is chunk_size?
chunk_size controls how many tokens (roughly 3/4 of a word) go into each chunk:
Trade-offs:
Small Chunks (256)
Pros: Precise matching, less noise in results, faster embedding.Cons: May miss surrounding context, more chunks to search, fragmented information.
Large Chunks (1024+)
Pros: More context preserved, fewer chunks overall, complete ideas captured.Cons: Less precise matching, more irrelevant text included, slower embedding.
What is chunk_overlap?
Overlap ensures information isn’t lost at chunk boundaries:
chunk_overlap to 10-20% of chunk_size:
chunk_size=500→chunk_overlap=50-100chunk_size=1000→chunk_overlap=100-200
Configuration Deep Dive
Here’s the fullRAGConfig with explanations:
The default embedder is now
user.embeddinggemma-300m-GGUF (EmbeddingGemma 300M), replacing nomic-embed-text-v2-moe-GGUF because the current llama.cpp server cannot load the nomic MOE embedder. Both are 768-dim, so retrieval behavior is unchanged. No manual cache clearing is needed after the switch: the on-disk cache under cache_dir stores only extracted document text and chunks (content-hashed, independent of the embedder), and vectors are regenerated via Lemonade on every index — so the next run embeds with EmbeddingGemma automatically.Tuning max_chunks
max_chunks controls how many chunks are sent to the LLM:
Visualization:
RAG Response Object
When you query, you get back a rich response object:Interpreting Relevance Scores
Beyond Basic RAG: Agentic RAG
Traditional RAG follows a simple pattern: one question → one search → one answer. But real-world information needs are rarely that simple. Agentic RAG adds intelligent reasoning to the retrieval process, allowing the agent to:- Make multiple retrieval calls when needed
- Refine queries based on initial results
- Combine information from multiple documents
- Know when it has enough information to answer
- Recognize when documents don’t contain the answer
Traditional RAG vs. Agentic RAG
- Traditional RAG
- Agentic RAG
How it works: User asks a question, system searches once for relevant chunks, top chunks are sent to LLM, LLM generates answer from those chunks.Limitations: If initial search misses relevant info it’s gone, can’t handle multi-part questions, no ability to refine or dig deeper, doesn’t know when it lacks information.
When Agentic RAG Shines
The Agentic RAG Mental Model
Think of the difference like this: Traditional RAG = A librarian who:- Takes your question
- Goes to one shelf
- Grabs the first 5 books that seem related
- Hands them to you
- Discusses your question to understand what you really need
- Searches multiple sections of the library
- Evaluates if the books actually answer your question
- Goes back for more if needed
- Tells you honestly if the library doesn’t have what you need
- Synthesizes findings into a coherent answer
How GAIA Implements Agentic RAG
GAIA’s agents use RAG as a tool, not just a pipeline. This is the key architectural difference:The RAG Tool Interface
When RAG is used as an agent tool, the LLM can make intelligent decisions:Multi-Step Retrieval Example
Here’s how an agent handles a complex question: Question: “What were our top 3 product launches this year and how did each perform?” Traditional RAG would:- Search “top product launches performance”
- Return 5 random chunks about products
- Generate a potentially incomplete answer
Implementing Agentic RAG Patterns
Pattern 1: Iterative Refinement
Pattern 1: Iterative Refinement
When initial results are insufficient, refine and search again:
Pattern 2: Multi-Aspect Search
Pattern 2: Multi-Aspect Search
For questions with multiple parts, search each aspect:Usage by agent:
Pattern 3: Confidence-Aware Responses
Pattern 3: Confidence-Aware Responses
Always check confidence before making claims:
Pattern 4: Source Triangulation
Pattern 4: Source Triangulation
Verify information appears in multiple sources:
When to Use Each Approach
Key Takeaways: Agentic RAG
RAG as a Tool, Not Pipeline
In Agentic RAG, retrieval is a tool the agent chooses to use—not a fixed pipeline.
Multiple Searches Are Normal
Complex questions often need 3-5 searches to gather complete information.
Confidence Matters
Agents should check relevance scores and admit when documents don’t have the answer.
Synthesis Over Retrieval
The agent’s job is to synthesize information, not just return search results.
Tuning RAG for Your Use Case
Use Case: Customer Support FAQ Bot
Use Case: Customer Support FAQ Bot
FAQs are short, focused questions with direct answers:Why these settings:
- Small chunks match FAQ Q&A pairs precisely
- Low max_chunks prevents mixing unrelated FAQs
- Focused answers are better for support
Use Case: Research Paper Analysis
Use Case: Research Paper Analysis
Academic papers need more context to understand concepts:Why these settings:
- Large chunks capture complete methodologies
- High overlap preserves logical flow
- Fewer chunks focus on key passages
Use Case: Codebase Documentation
Use Case: Codebase Documentation
Code docs mix short references with detailed explanations:Why these settings:
- Medium chunks handle both code and prose
- More chunks show multiple code examples
- Balanced for API reference + tutorials
Use Case: Legal Document Review
Use Case: Legal Document Review
Legal documents need precise, complete clause retrieval:Why these settings:
- Larger chunks capture complete clauses
- High overlap prevents splitting conditions
- Legal answers need complete context
Security: Restricting Document Access
RAG can be restricted to specific directories for security:Common Pitfalls and Solutions
Pitfall 1: RAG returns irrelevant information
Pitfall 1: RAG returns irrelevant information
Symptom: Asking about weather, but RAG returns technical documentation.Cause: RAG always retrieves the “most similar” chunks, even if similarity is low.Solutions:
Pitfall 2: Answers are missing context
Pitfall 2: Answers are missing context
Symptom: Answer is technically correct but missing important details.Cause: Chunks are too small, cutting off important context.Solutions:
Pitfall 3: Indexing is slow
Pitfall 3: Indexing is slow
Symptom: Indexing 100 documents takes 30+ minutes.Cause: Embedding generation is CPU/GPU intensive.Solutions:
Pitfall 4: Out of memory with large documents
Pitfall 4: Out of memory with large documents
Symptom: Python crashes or hangs when indexing large PDFs.Cause: Large documents create many chunks that consume memory.Solutions:
Practice Challenge
Build a Document Q&A System
Create a RAG system that: (1) Indexes multiple PDF documents, (2) Answers questions with source citations, (3) Indicates confidence based on relevance scores, (4) Handles missing information gracefully.Requirements: Configure appropriate chunk size for your documents, include relevance score checking, show which documents the answer came from.
Why this solution works:
Hints
Hints
Use
response.source_files for citations. Check response.chunk_scores[0] for confidence. Use a threshold (e.g., 0.6) to detect unreliable answers.Solution
Solution
- Confidence scoring: Users know when to trust the answer
- Citations: Users can verify information
- Graceful handling: Low confidence triggers a warning instead of wrong answer
- Configurable: Chunk settings can be adjusted for document types
- Statistics: Helps monitor and debug the system
Deep Dive: How Vector Similarity Works
Understanding Embeddings and Cosine Similarity
Understanding Embeddings and Cosine Similarity
What are embeddings?Embeddings convert text into vectors (lists of numbers) where similar meanings are close together:How similarity is calculated:FAISS uses cosine similarity—measuring the angle between vectors:Why this works for search:When you ask “What are the hardware specs?”, it becomes a vector that’s mathematically close to chunks about “system requirements”, “hardware needed”, “computer specifications”, etc.—even if none of those exact words appear in your question!
Key Takeaways
RAG = Search + Generate
Find relevant chunks from your documents, then use LLM to synthesize an answer.
Chunks are Everything
How you split documents determines what RAG can find. Tune
chunk_size for your use case.Check Confidence
Use
chunk_scores to know when answers are reliable vs. when documents don’t have the info.Index Once, Query Many
Use
RAGSDK for applications—documents are indexed once, then queried unlimited times.Next Steps
Agent SDK
Combine RAG with conversational memory
Security
Path validation and security best practices
Examples
Complete document Q&A examples