Hiren158/rag-microservice
RAG Microservice
A standalone FastAPI microservice for Retrieval Augmented Generation (RAG) functionality. This service handles PDF document processing, embedding generation, vector storage, and question answering using ChromaDB and Gemini AI.
Features
- PDF Upload & Processing: Extract text from PDF documents and create semantic chunks
- Embedding Generation: Generate embeddings using sentence-transformers (BAAI/bge-small-en-v1.5)
- Vector Storage: Store and retrieve document chunks using ChromaDB
- Question Answering: Answer questions about uploaded documents using Gemini AI
- API Key Authentication: Secure endpoints with API key-based authentication
API Endpoints
Health Check
GET /healthNo authentication required. Returns service status.
Upload PDF
POST /upload
Headers: X-API-Key: <your-api-key>
Form Data:
- file: PDF file
- doc_id: Integer document ID from main applicationUploads a PDF, generates embeddings, and stores in vector database.
Ask Question
POST /ask
Headers: X-API-Key: <your-api-key>
JSON Body:
{
"question": "Your question here",
"top_k": 5,
"doc_id": 123, // Optional: single document ID
"doc_ids": [123, 124, 125] // Optional: multiple document IDs
}Answers questions based on uploaded documents.
Delete Document
DELETE /documents/{document_id}
Headers: X-API-Key: <your-api-key>Deletes all chunks for a document from vector storage.
Environment Variables
Create a .env file with the following:
# Required: API key for authentication
API_KEY=your-secure-api-key
# Required: Gemini API key for AI responses
GEMINI_API_KEY=your-gemini-api-key
# Optional: ChromaDB storage directory (default: ./chroma_db)
CHROMA_DIR=/data/chroma_dbLocal Development
Installation
# Install dependencies
pip install -r requirements.txt
# Create .env file
cp .env.example .env
# Edit .env with your API keysRun Locally
# Start the service
uvicorn main:app --reload --port 7860
# Or using Python
python main.pyThe service will be available at http://localhost:7860
Test the API
Visit http://localhost:7860/docs for interactive Swagger documentation.
Docker Deployment
Build Image
docker build -t rag-microservice .Run Container
docker run -p 7860:7860 \
-e API_KEY=your-api-key \
-e GEMINI_API_KEY=your-gemini-key \
-v $(pwd)/chroma_db:/data/chroma_db \
rag-microserviceHugging Face Spaces Deployment
Prerequisites
- Create a Hugging Face account at https://huggingface.co
- Create a new Space (Docker-based)
Deployment Steps
- Create Space:
- Go to https://huggingface.co/new-space
- Select "Docker" as the SDK
- Name your space (e.g.,
rag-microservice)
- Set Secrets:
- Go to Space Settings → Repository Secrets
- Add
API_KEYwith a secure random string - Add
GEMINI_API_KEYwith your Gemini API key
- Push Code:
# Initialize git (if not already)
git init
# Add HF Space as remote
git remote add hf https://huggingface.co/spaces/<username>/rag-microservice
# Push code
git add .
git commit -m "Initial deployment"
git push hf main- Verify Deployment:
- Visit
https://<username>-rag-microservice.hf.space/health - Should return
{"status": "healthy", ...}
HF Spaces Configuration
The Dockerfile is pre-configured for HF Spaces:
- Uses port 7860 (HF Spaces requirement)
- Includes health check endpoint
- Persistent storage at
/data/chroma_db
Architecture
┌─────────────┐
│ FastAPI │
│ Server │
└──────┬──────┘
│
├─────► PDF Service (PyMuPDF)
│ └─► Text Chunker
│
├─────► Embedding Service (sentence-transformers)
│ └─► BAAI/bge-small-en-v1.5
│
├─────► Vector Store (ChromaDB)
│ └─► Persistent Storage
│
└─────► AI Search (Gemini API)
└─► Question AnsweringDependencies
- FastAPI: Web framework
- ChromaDB: Vector database
- sentence-transformers: Embedding generation
- PyMuPDF: PDF text extraction
- wordninja: Word segmentation
- google-generativeai: Gemini AI integration
Security
- All endpoints (except
/health) require API key authentication viaX-API-Keyheader - API key must be set in environment variables
- Use strong, randomly generated API keys in production
Performance
- Embedding generation may take 30-60 seconds for large PDFs
- Timeout set to 60 seconds for embedding generation
- ChromaDB provides fast vector similarity search
- Recommended: Use on GPU-enabled infrastructure for faster embeddings
Troubleshooting
Embedding Timeout
If you get timeout errors:
- Reduce PDF size or page count
- Increase timeout in
main.py(line withasyncio.wait_for) - Use GPU-enabled environment
ChromaDB Errors
Ensure:
CHROMA_DIRdirectory exists and is writable- Sufficient disk space for vector storage
Gemini API Errors
Check:
GEMINI_API_KEYis set correctly- API quota hasn't been exceeded
- Network connectivity to Gemini API
License
Same as parent project.
Support
For issues related to the RAG microservice, check logs for detailed error messages.
