BioRTC's 2025 AI Workshop
Complete Resource Guide
Activity 3: RAG System for PDF Search
Duration: 90 minutes
What This Application Does
Imagine you have hundreds of PDF documents – research papers, company policies, manuals, reports – and you need to find specific information quickly. Instead of manually searching through each document, this AI system can read all your PDFs and answer questions about their content intelligently.
Input: Multiple PDF documents and questions about their content
Process:
- Document Ingestion: AI reads and understands all your PDF files
- Smart Indexing: Creates a searchable knowledge base from the documents
- Intelligent Retrieval: When you ask a question, finds the most relevant information
- Contextual Answers: Generates accurate answers based only on your documents
- Source Attribution: Shows exactly which parts of which documents were used
Output:
- Accurate answers grounded in your specific documents
- Source citations showing exactly where information came from
- No hallucinations – only answers based on actual document content
Understanding RAG (Retrieval Augmented Generation)
What is RAG? RAG is a revolutionary AI technique that combines the power of large language models with your specific documents. It solves a major problem: LLMs have knowledge cutoffs and can hallucinate, but RAG grounds them in your actual data.
How RAG Works:
- Knowledge Base Creation: Your documents are broken into chunks and converted into mathematical representations (vectors)
- Semantic Search: When you ask a question, the system finds the most relevant chunks
- Grounded Generation: The LLM generates answers using only the retrieved information
- Source Attribution: You can see exactly which documents supported each answer
Why RAG Matters:
- Accuracy: Answers come from your actual documents, not general training data
- Up-to-date: Works with your latest documents immediately
- Transparent: You can verify every answer by checking the sources
- Secure: Your documents stay private, no data sent to external services
The AI Technologies Working Together
1. Qwen2.5 Language Models
- Qwen2.5-7B: Most intelligent, provides detailed and nuanced answers
- Qwen2.5-3B: Balanced performance, good for most use cases
- Qwen2.5-1.5B: Fastest processing, suitable for simple queries
2. Vector Embeddings (Sentence Transformers)
- Converts text into numerical representations that capture meaning
- Allows semantic search (finds similar meaning, not just exact words)
- Model:
all-MiniLM-L6-v2– efficient and accurate for English text
3. ChromaDB Vector Database
- Stores and indexes document embeddings for fast similarity search
- Persists your knowledge base so you don’t need to reprocess documents
- Optimized for retrieval speed and accuracy
4. LangChain Framework
- Orchestrates the entire RAG pipeline
- Handles document chunking, embedding, and retrieval
- Provides a standardized way to work with different AI components
Real-World Applications
- Corporate Knowledge Management: Search through company policies, procedures, and documentation
- Research & Academia: Query academic papers, research databases, and literature reviews
- Legal Services: Search legal documents, case law, and regulatory requirements
- Healthcare: Query medical literature, treatment protocols, and research studies
- Customer Support: Automated answers from product manuals and knowledge bases
- Compliance & Audit: Search regulatory documents and compliance requirements
- Technical Documentation: Query API docs, user manuals, and technical specifications
Step-by-Step Implementation
Step 1: Download the RAG Application
In your Jupyter notebook, create a new cell and run:
%cd /home
!git clone https://github.com/ictBioRtc/document_search_with_rag.gitWhat this does: Downloads the complete RAG system with all necessary components for PDF processing and intelligent search.
Step 2: Navigate to the Project
Create another cell and run:
%cd document_search_with_ragWhat this does: Changes your working directory to the RAG system folder.
Step 3: Install Required Libraries
Create a new cell and run:
!pip install -r requirements.txtWhat this installs:
- LangChain: RAG pipeline orchestration
- ChromaDB: Vector database for document storage
- Sentence-Transformers: Text embedding models
- PyPDF: PDF document processing
- LMDeploy: Efficient inference for Qwen models
- Gradio: Web interface framework
This installation takes 3-4 minutes as it downloads several AI models.
Step 4: Launch the RAG System
Create a new cell and run:
!python app.pyWhat happens:
- The system initializes the Qwen2.5-3B model (default)
- Creates the vector database infrastructure
- Builds a comprehensive web interface
- Provides a public URL (like: https://xyz123.gradio.live)
- Click the URL to access your RAG system
Step 5: Understanding the Interface
Your RAG system opens with multiple tabs:
Main Tab: Upload & Query
- Left side: Document upload and system configuration
- Right side: Question asking and answer display
Reference Sources Tab
- Shows exactly which document sections were used for each answer
- Includes relevance scores and source file information
System Info Tab
- Explains the technology stack
- Provides model comparison and memory requirements
Step 6: Building Your Knowledge Base
Step 6a: Upload Documents
- In the “Upload & Query” tab, look for “Upload PDF Files”
- Click the upload area and select PDF files:
- Use provided sample documents in the repository, or
- Upload your own PDF files (research papers, manuals, reports)
- You can upload multiple files simultaneously
- Click “Process PDFs”
What happens during processing:
- Each PDF is read and converted to text
- Documents are split into manageable chunks (1000 characters each with 200 character overlap)
- Each chunk is converted to a vector embedding
- Embeddings are stored in ChromaDB for fast retrieval
- The system creates a persistent knowledge base
Processing Status Examples:
- “Successfully processed 3 PDFs” – All documents loaded correctly
- Processing time varies with document size and number
Step 7: Asking Intelligent Questions
Step 7a: Configure Your Assistant
- System Prompt: Controls how the AI behaves
- Default: “You are a helpful assistant that answers questions based only on the provided documents. You must cite your sources.”
- You can modify this for specific use cases
Step 7b: Ask Questions
- Type your question in the “Your Question” field
- Click “Ask” or press Enter
- Watch as the system:
- Searches through all your documents
- Finds the most relevant information
- Generates a comprehensive answer
- Provides source citations
Example Questions You Can Ask:
- “What are the main conclusions of this research?”
- “What safety procedures are mentioned in the manual?”
- “Who are the authors of papers about machine learning?”
- “What budget allocations are mentioned in the report?”
- “Compare the methodologies used in different studies”
Step 8: Verifying Answers with Sources
Switch to the “Reference Sources” tab:
What you’ll see:
- Source Cards: Each showing a relevant document section
- Relevance Scores: How closely each source matches your question
- File Information: Which PDF and page number
- Content Preview: The actual text used to generate the answer
Relevance Score Interpretation:
- High (0.8+): Very relevant, directly answers your question
- Medium (0.6-0.8): Somewhat relevant, provides context
- Low (<0.6): Background information, may provide general context
Step 9: Advanced Features
Model Switching:
- Use the “Model Selection” dropdown to choose:
- Qwen2.5-1.5B: Fastest, good for simple factual questions
- Qwen2.5-3B: Balanced, recommended for most use cases
- Qwen2.5-7B: Most sophisticated, best for complex analysis
- Click “Switch Model” to change
- Switching takes 30-60 seconds as the new model loads
System Prompt Customization: Modify the system prompt for different use cases:
- “You are a legal expert. Analyze documents for compliance issues.”
- “You are a researcher. Summarize key findings and methodologies.”
- “You are a technical writer. Explain complex concepts simply.”
Understanding What Happened Behind the Scenes
The Complete RAG Pipeline:
- Document Processing Pipeline:
- PDFs are parsed to extract clean text
- Text is split into overlapping chunks for better context
- Each chunk is converted to a 384-dimensional vector using sentence transformers
- Vectors are indexed in ChromaDB for efficient similarity search
- Query Processing:
- Your question is converted to the same vector format
- ChromaDB finds the top 5 most similar document chunks
- Similarity is calculated using cosine similarity in vector space
- Context Assembly:
- Retrieved chunks are ranked by relevance score
- Context is assembled with source attribution
- Maximum context length is managed to fit model limits
- Answer Generation:
- Qwen model receives your question + relevant context
- Model generates answer using only provided information
- Response includes natural language citations
- Source Attribution:
- System tracks which chunks contributed to the answer
- Source metadata is preserved for transparency
- Users can verify every claim against original documents
Advanced Use Cases and Customization
Multi-Document Analysis:
- Upload documents from different sources
- Ask comparative questions across documents
- Identify contradictions or agreements between sources
Domain-Specific Applications:
Legal Document Review:
System Prompt: "You are a legal expert. Analyze documents for compliance issues, legal risks, and regulatory requirements. Always cite specific sections."Research Literature Review:
System Prompt: "You are a research analyst. Summarize key findings, methodologies, and identify research gaps. Provide detailed citations."Technical Documentation Search:
System Prompt: "You are a technical expert. Provide step-by-step instructions and troubleshooting guidance based on the manuals."Performance Optimization Tips
For Better Accuracy:
- Use the 7B model for complex analytical questions
- Upload high-quality, well-formatted PDFs
- Ask specific questions rather than very broad ones
- Include key terms from your documents in questions
For Faster Processing:
- Use the 1.5B model for simple factual queries
- Keep document chunks focused on specific topics
- Process documents in smaller batches
Memory Management:
- Switch to smaller models if you encounter memory issues
- The system automatically manages vector database storage
- Processed documents persist between sessions
Troubleshooting Common Issues
“No relevant documents found”
- Ensure PDFs were processed successfully
- Check that your question relates to document content
- Try rephrasing your question with different keywords
“Model loading failed”
- Try switching to a smaller model (1.5B)
- Check internet connection for model downloads
- Restart the application if memory issues persist
“Processing stuck during PDF upload”
- Ensure PDFs are not corrupted or password-protected
- Try uploading fewer files at once
- Check that files are actual PDFs, not scanned images
“Poor answer quality”
- Try the larger 7B model for better understanding
- Ensure your question is specific and clear
- Check that relevant information actually exists in your documents
“Out of memory errors”
- Switch to the 1.5B model
- Process fewer documents at once
- Restart the application to clear memory
Key Technical Insights
Vector Similarity Search: The system doesn’t just search for exact keyword matches. It understands semantic similarity – if you ask about “vehicle safety,” it will find relevant information about “car accidents,” “automotive protection,” and “transportation security.”
Chunk Overlap Strategy: Documents are split with 200-character overlap to ensure important information isn’t lost at chunk boundaries. This means context is preserved even when relevant information spans multiple chunks.
Memory-Efficient Architecture: The system uses optimized model loading and caching to work efficiently on limited GPU memory. Vector database operations are optimized for speed without sacrificing accuracy.
Real-World Impact and Applications
Business Intelligence:
- Analyze quarterly reports across multiple years
- Extract key metrics and trends from financial documents
- Compare strategies across different business units
Academic Research:
- Literature reviews across hundreds of papers
- Methodology comparisons between studies
- Identification of research gaps and opportunities
Compliance and Risk Management:
- Search regulatory documents for specific requirements
- Identify compliance gaps in current policies
- Track regulatory changes across multiple jurisdictions
Customer Support Automation:
- Instant answers from product documentation
- Troubleshooting guidance from technical manuals
- Policy explanations from company handbooks
Key Takeaways
- RAG Technology: You’ve implemented a state-of-the-art system that grounds AI in your specific documents
- Semantic Understanding: The system understands meaning, not just keywords
- Source Transparency: Every answer can be traced back to specific document sections
- Scalable Architecture: Can handle large document collections efficiently
- Practical Implementation: Built a real system that solves actual business problems
- No Hallucinations: Answers are always based on your actual documents
What You’ve Accomplished:
- Built a sophisticated information retrieval system
- Integrated multiple AI technologies into a cohesive solution
- Created a tool that can scale to handle enterprise-level document collections
- Gained hands-on experience with vector databases and semantic search
- Implemented a solution that provides transparent, verifiable AI responses
Business Value:
- Dramatically reduces time spent searching through documents
- Ensures answers are always grounded in official documentation
- Provides audit trails for all AI-generated responses
- Scales to handle thousands of documents without manual intervention
This concludes Day 1 of our workshop. You’ve now experienced three different ways AI can transform how we work with data: speech processing, computer vision, and intelligent document search. Tomorrow, we’ll dive deeper and actually train our own AI models!
