Spaces:
Runtime error
Runtime error
Commit ·
e99563f
0
Parent(s):
Initialize Production-Ready RAG Pipeline
Browse filesFiles changed (22)
- .dockerignoreAdded+17
- .env.exampleAdded+9
- .gitignoreAdded+25
- DEPLOY_HUGGINGFACE.mdAdded+101
- DockerfileAdded+37
- README.mdAdded+21
- SUPABASE_SETUP.mdAdded+46
- app/__init__.pyAdded
- app/api/metadata.pyAdded+57
- app/api/query.pyAdded+80
- app/api/upload.pyAdded+128
- app/config.pyAdded+15
- app/main.pyAdded+84
- app/services/__init__.pyAdded
- app/services/doc_store.pyAdded+146
- app/services/llm_providers.pyAdded+96
- app/services/vector_store.pyAdded+127
- app/utils/text_processing.pyAdded+60
- docker-compose.ymlAdded+36
- pytest.iniAdded+7
- requirements.txtAdded+16
- tests/test_basic.pyAdded+117
1234567891011121314151617__pycache__/*.py[cod]*$py.classvenv/.envdata/uploads/metadata.dbchroma_data/tests/.git/.gitignoreimplementation_plan.mdtask.mdrag_pipeline_project.mdworking.mdfiles_list.txt123456789# API keysOPENAI_API_KEY=your_openai_api_key_hereGOOGLE_GEMINI_API_KEY=your_google_gemini_api_key_hereCOHERE_API_KEY=your_cohere_api_key_here
# Other configDEBUG=True
PROVIDER_PRIORITY=gemini,openai,cohere12345678910111213141516171819202122232425# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Project specificsuploads/data/chroma_data/metadata.db*.log
# IDEs.vscode/.idea/.DS_Store123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# Deploying RAG Pipeline to Hugging Face Spaces (No Credit Card)
This guide walks you through hosting your optimized RAG Pipeline on **Hugging Face Spaces**. This is a truly free, no-credit-card-required environment perfect for AI-powered Python apps.
---
## Prerequisites1. A **[Hugging Face Account](https://huggingface.co/join)** (Free).2. Your project pushed to a **GitHub** repository (or uploaded directly to HF).3. Your **Google Gemini API Key**.4. Your **Supabase DB_URL** (from [SUPABASE_SETUP.md](SUPABASE_SETUP.md)).
---
## Step 1: Create a New Space1. Log in to Hugging Face and click your profile icon -> **"New Space"**.2. **Space Name**: `rag-pipeline-api` (or any name you like).3. **License**: `apache-2.0` (or your choice).4. **SDK**: Select **Docker**.5. **Docker Template**: Select **Blank**.6. **Visibility**: Public or Private.7. Click **"Create Space"**.
---
## Step 2: Add Your Code to the SpaceThere are two ways to get your code into Hugging Face. **I recommend Method A** if you don't use Git.
### Method A: Upload Directly (Easiest)1. On your new Space page, click the **"Files and versions"** tab (near the top).2. Click the **"Add file"** button -> **"Upload files"**.3. **Drag and drop** all the local files from your project folder into the browser: - `app/` (the whole folder) - `Dockerfile` - `requirements.txt` - `README.md`4. Scroll down and click **"Commit changes to main"**.
### Method B: Use GitHub (Permanent Connection)If you already have a GitHub repository, follow these steps to push your new files:
1. **Initialize Git** (if not already done): ```bash git init git add . git commit -m "Initialize Production-Ready RAG Pipeline" ```2. **Push to GitHub**: - Create a **New Repository** at [github.com/new](https://github.com/new). - Run: ```bash git remote add origin https://github.com/[your-username]/[your-repo-name].git git branch -M main git push -u origin main ```
3. **Link Hugging Face to GitHub**: - In your Hugging Face Space, click the **Settings** tab. - Scroll down to the **"Connected GitHub Repository"** section. - Click **"Connect a GitHub repository"**. - Select your new repository. - Hugging Face will now automatically build and deploy every time you "push" to GitHub!
---
## Step 3: Add Your "Secrets" (API Keys)This is the most important step. **The app will not start without these.**
1. In your Space, click the **Settings** tab (top right).2. On the left sidebar, click **"Variables and secrets"**.3. Look for the section called **"Secrets"** (not Variables).4. Click **"New secret"** and add these one by one:
| Secret Name (Key) | Secret Value || :--- | :--- || `GOOGLE_GEMINI_API_KEY` | (Your API Key from Google AI Studio) || `DB_URL` | (Your Connection URI from **Supabase**) |
> [!TIP]> **What is the DB_URL?**> It's the long text you copied from Step 3 of the [Supabase Setup Guide](SUPABASE_SETUP.md). It looks like `postgresql://postgres:password@...`
---
## Step 4: Deployment1. Once you save your secrets and upload your code, Hugging Face will automatically detect the `README.md` frontmatter and start building the Docker image.2. The logs will show the progress.3. Once finished, your API will be live!
---
## Usage- Your API will be available at `https://huggingface.co/spaces/[username]/[spacename]`.- To use the API from code, use the **Direct Link** (e.g., `https://[username]-[spacename].hf.space`).- Interactive docs: `https://[username]-[spacename].hf.space/docs`.
---
## PersistenceWait, **is it persistent?**Yes! Because we integrated **Supabase**, your document metadata and AI search vectors are stored in the cloud. Even when the Hugging Face Space restarts, your data stays safe.12345678910111213141516171819202122232425262728293031323334353637# Stage 1: Build stageFROM python:3.11-slim-bookworm as builder
WORKDIR /app
# Install build dependencies if needed (none currently for our lean requirements)# but good for future-proofingRUN apt-get update && apt-get install -y --no-install-recommends \ build-essential \ && rm -rf /var/lib/apt/lists/*
# Install python dependencies into a local directoryCOPY requirements.txt .RUN pip install --no-cache-dir --prefix=/install -r requirements.txt
# Stage 2: Final runtime stageFROM python:3.11-slim-bookworm
WORKDIR /app
# Copy installed dependencies from builderCOPY --from=builder /install /usr/local
# Copy application source codeCOPY ./app ./app
# Create necessary directories for local storage with proper permissionsRUN mkdir -p /app/uploads /app/data /app/chroma_data && \ chmod 777 /app/uploads /app/data /app/chroma_data
# Use a default port which can be overridden by environment variable# Hugging Face Spaces default port is 7860ENV PORT=7860EXPOSE 7860
# Run using the uvicorn server, binding to the PORT environment variableCMD ["sh", "-c", "uvicorn app.main:app --host 0.0.0.0 --port ${PORT}"]123456789101112131415161718192021---title: RAG Pipeline APIemoji: 🚀colorFrom: bluecolorTo: indigosdk: dockerapp_port: 7860pinned: false---
# RAG Pipeline API
This is a production-ready, cloud-persistent RAG (Retrieval-Augmented Generation) pipeline built with **FastAPI**, **Google Gemini**, and **Supabase**.
## Key Features- **AI-Powered Search**: Uses Gemini's high-performance embeddings.- **Persistent Storage**: Document metadata and vectors are stored permanently in **Supabase**.- **Fast & Lean**: Optimized Docker image that runs efficiently on free-tier CPU instances.
## API DocumentationOnce the space is running, you can access the interactive Swagger documentation at the `/docs` endpoint.12345678910111213141516171819202122232425262728293031323334353637383940414243444546# Setting Up Supabase for RAG Persistence
This project uses **Supabase** (PostgreSQL + pgvector) to provide permanent cloud storage for your document metadata and vector embeddings. This ensures your data is preserved even when your hosting (Koyeb) restarts.
---
## 1. Create a Supabase Project1. Go to **[Supabase.com](https://supabase.com/)** and sign up for a free account.2. Click **"New Project"**.3. Fill in the **Project Name** (e.g., `rag-pipeline`) and **Database Password**. - *Save the password! You'll need it for the connection string.*4. Wait for the project to finish provisioning.
---
## 2. Enable pgvector ExtensionThe `pgvector` extension allows Postgres to handle high-dimensional AI vectors.1. In the Supabase Sidebar, go to **SQL Editor**.2. Paste the following command and click **Run**: ```sql CREATE EXTENSION IF NOT EXISTS vector; ```
---
## 3. Get Your Connection String (URI)You need the **DB_URL** to connect your app to the database.1. In the Sidebar, go to **Project Settings** -> **Database**.2. Scroll down to **Connection String**.3. Select the **URI** tab.4. Copy the URL. It will look like this: `postgresql://postgres:[YOUR-PASSWORD]@[HOST]:5432/postgres`5. **Replace `[YOUR-PASSWORD]`** with the real password you set in Step 1.
---
## 4. Environment ConfigurationWhen deploying to **Koyeb**, add this connection string as an environment variable:
- **Key**: `DB_URL`- **Value**: `postgresql://postgres:yourpassword@db.xxxxxx.supabase.co:5432/postgres`
---
## 5. (Self-Correction) Connection PoolingNote: Supabase provides a connection pooler if you run out of direct connections. For small projects, the direct connection (Step 3) is fine. If you see "connection limit exceeded" errors, switch to the **Pooler** connection string on port `6543`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657from fastapi import APIRouter, HTTPExceptionfrom ..services.doc_store import list_documents, delete_document, get_document_stats
router = APIRouter(prefix="/metadata", tags=["Document Metadata"])
@router.get("")async def get_all_metadata(): """Get metadata for all uploaded documents""" try: documents = list_documents() stats = get_document_stats() return { "documents": documents, "stats": stats } except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to retrieve metadata: {str(e)}")
@router.get("/stats")async def get_metadata_stats(): """Get document statistics""" try: return get_document_stats() except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to retrieve stats: {str(e)}")
@router.delete("/{doc_id}")async def delete_document_metadata(doc_id: str): """Delete document metadata (note: does not remove from vector store)""" try: success = delete_document(doc_id) if success: return {"message": f"Document {doc_id} metadata deleted successfully"} else: raise HTTPException(status_code=404, detail="Document not found") except HTTPException: raise except Exception as e: raise HTTPException(status_code=500, detail=f"Failed to delete document: {str(e)}")
@router.get("/health")async def metadata_health(): """Health check for metadata service""" try: stats = get_document_stats() return { "status": "healthy", "database": "connected", "stats": stats } except Exception as e: return { "status": "unhealthy", "database": "error", "error": str(e) }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980from typing import Optionalfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModelimport loggingfrom ..services.vector_store import search_similar_chunksfrom ..services.llm_providers import LLMRequest, generate_with_fallback
logger = logging.getLogger("rag-pipeline.query")router = APIRouter(prefix="/query", tags=["Document Query"])
class QueryRequest(BaseModel): question: str max_chunks: int = 5
class QueryResponse(BaseModel): answer: str provider_used: str success: bool relevant_chunks: list[str] error: Optional[str] = None
@router.post("", response_model=QueryResponse)async def query_documents(request: QueryRequest): if not request.question.strip(): logger.warning("Empty question received") raise HTTPException(status_code=400, detail="Question cannot be empty") try: logger.info(f"Processing query: {request.question[:50]}...") # Search for relevant document chunks chunks = search_similar_chunks(query=request.question, k=request.max_chunks) # Flatten chunks if nested lists (ChromaDB sometimes returns nested results) flattened_chunks = [] for c in chunks: if isinstance(c, list): flattened_chunks.extend(c) else: flattened_chunks.append(c) if not flattened_chunks: logger.info("No relevant chunks found in vector store") return QueryResponse( answer="No relevant documents found. Please upload documents first.", provider_used="none", success=False, relevant_chunks=[], error="No documents in database" ) logger.info(f"Retrieved {len(flattened_chunks)} relevant chunks") # Join chunks with double newlines context = '\n\n'.join(flattened_chunks) # Generate answer using LLM llm_request = LLMRequest(query=request.question, context=context) result = generate_with_fallback(llm_request) if result["success"]: logger.info(f"Query successful using {result['provider_used']}") else: logger.error(f"Query generation failed: {result.get('error')}") return QueryResponse( answer=result["answer"], provider_used=result["provider_used"], success=result["success"], relevant_chunks=flattened_chunks, error=result.get("error") ) except Exception as e: logger.exception("Unexpected error during query processing") raise HTTPException(status_code=500, detail=f"Query processing failed: {str(e)}")
@router.get("/test")async def test_query(): return {"message": "Query service is working", "status": "healthy"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128from fastapi import APIRouter, UploadFile, File, HTTPExceptionfrom ..services.vector_store import add_document_chunks, get_collection_statsfrom ..services.doc_store import save_metadata, count_documents, DOC_LIMITfrom ..utils.text_processing import extract_pdf_text, chunk_text, clean_textimport uuidimport osimport logging
logger = logging.getLogger("rag-pipeline.upload")router = APIRouter(prefix="/upload", tags=["Document Upload"])
@router.post("")async def upload_document(file: UploadFile = File(...)): """Upload and process a PDF document with limits enforcement""" # Check document limit current_count = count_documents() if current_count >= DOC_LIMIT: logger.warning(f"Upload blocked: Document limit ({DOC_LIMIT}) reached.") raise HTTPException( status_code=400, detail=f"Document limit reached. Maximum {DOC_LIMIT} documents allowed. Currently have {current_count} documents." ) # Validate file type if not file.filename.endswith('.pdf'): logger.warning(f"Upload blocked: Invalid file type {file.filename}") raise HTTPException(status_code=400, detail="Only PDF files are supported") # Validate file size (max 50MB) file_content = await file.read() if len(file_content) > 50 * 1024 * 1024: # 50MB logger.warning(f"Upload blocked: File too large ({len(file_content)} bytes)") raise HTTPException(status_code=400, detail="File too large. Maximum size is 50MB") try: # Generate unique document ID doc_id = str(uuid.uuid4()) logger.info(f"Processing upload: {file.filename} (ID: {doc_id})") # Save file temporarily temp_path = f"/app/uploads/{doc_id}_{file.filename}" os.makedirs("/app/uploads", exist_ok=True) with open(temp_path, "wb") as f: f.write(file_content) # Extract text from PDF text_content = extract_pdf_text(temp_path) if not text_content: logger.error(f"Text extraction failed for {file.filename}") raise HTTPException(status_code=400, detail="Could not extract text from PDF") # Count pages (approximate based on text length) estimated_pages = max(1, len(text_content) // 2000) # Check page limit if estimated_pages > 1000: logger.warning(f"Upload blocked: Too many pages (~{estimated_pages})") raise HTTPException( status_code=400, detail=f"Document too large. Maximum 1000 pages allowed. This document has approximately {estimated_pages} pages." ) # Clean and chunk the text cleaned_text = clean_text(text_content) chunks = chunk_text(cleaned_text) if not chunks: logger.error(f"No chunks created for {file.filename}") raise HTTPException(status_code=400, detail="No text content found in document") # Add chunks to vector database success = add_document_chunks(doc_id, chunks) if not success: logger.error(f"Vector store indexing failed for {doc_id}") raise HTTPException(status_code=500, detail="Failed to process document in vector store") # Save metadata to database metadata_saved = save_metadata( doc_id=doc_id, filename=file.filename, pages=estimated_pages, chunks=len(chunks), text_length=len(cleaned_text) ) if not metadata_saved: logger.warning(f"Failed to save metadata for document {doc_id}") # Clean up temporary file if os.path.exists(temp_path): os.remove(temp_path) logger.info(f"Upload successful: {file.filename} ({len(chunks)} chunks)") return { "document_id": doc_id, "filename": file.filename, "chunks_created": len(chunks), "text_length": len(cleaned_text), "estimated_pages": estimated_pages, "status": "success" } except HTTPException: raise except Exception as e: logger.exception(f"Unexpected error during upload of {file.filename}") # Clean up temp file if it exists if 'temp_path' in locals() and os.path.exists(temp_path): os.remove(temp_path) raise HTTPException(status_code=500, detail=f"Processing failed: {str(e)}")
@router.get("/stats")async def get_upload_stats(): """Get statistics about uploaded documents""" from ..services.doc_store import get_document_stats stats = get_document_stats() vector_stats = get_collection_stats() return { **stats, "vector_chunks": vector_stats.get("total_chunks", 0) }123456789101112131415from pydantic_settings import BaseSettings
class Settings(BaseSettings): OPENAI_API_KEY: str GOOGLE_GEMINI_API_KEY: str COHERE_API_KEY: str DEBUG: bool = False
class Config: env_file = ".env"
settings = Settings()
# Usage example:#print(settings.OPENAI_API_KEY)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384from fastapi import FastAPIimport loggingfrom .config import settingsfrom .api import upload, query, metadata
# Configure logginglogging.basicConfig( level=logging.INFO if not settings.DEBUG else logging.DEBUG, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",)logger = logging.getLogger("rag-pipeline")
app = FastAPI( title="RAG Pipeline API", description="Document upload and intelligent querying system with metadata management", version="1.0.0", docs_url="/docs", redoc_url="/redoc")
# Include API routersapp.include_router(upload.router)app.include_router(query.router)app.include_router(metadata.router)
@app.on_event("startup")async def startup_event(): logger.info("Initializing RAG Pipeline...") logger.info(f"Debug mode: {settings.DEBUG}")
@app.get("/")async def root(): return { "message": "RAG Pipeline API", "debug": settings.DEBUG, "version": "1.0.0", "endpoints": [ "/docs - API Documentation", "/upload - Upload PDF documents", "/query - Query documents", "/metadata - Document metadata", "/health - Health check" ] }
@app.get("/health")async def health(): """Comprehensive health check""" try: from .services.doc_store import get_document_stats from .services.vector_store import get_collection_stats doc_stats = get_document_stats() vector_stats = get_collection_stats() return { "status": "healthy", "services": { "api": "running", "database": "connected", "vector_store": "connected", "llm_providers": "configured" }, "stats": { "documents": doc_stats.get("total_documents", 0), "chunks": vector_stats.get("total_chunks", 0) } } except Exception as e: logger.error(f"Health check failed: {str(e)}") return { "status": "degraded", "error": str(e) }
@app.get("/config-test")async def config_test(): """Test configuration and API keys""" return { "gemini_key_loaded": bool(settings.GOOGLE_GEMINI_API_KEY), "openai_key_loaded": bool(settings.OPENAI_API_KEY), "cohere_key_loaded": bool(settings.COHERE_API_KEY), "debug_mode": settings.DEBUG }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146from sqlalchemy import create_engine, Column, String, Integer, DateTime, funcfrom sqlalchemy.orm import declarative_base, sessionmakerfrom datetime import datetimeimport osimport logging
logger = logging.getLogger("rag-pipeline.doc_store")
# Database configuration - defaults to local sqlite for dev, but REQUIRES postgres for prodDB_URL = os.getenv("DB_URL", "sqlite:///./data/metadata.db")DOC_LIMIT = 0 # Currently no limit, or fetch from envtry: DOC_LIMIT = int(os.getenv("DOC_LIMIT", "20"))except ValueError: DOC_LIMIT = 20
# SQLAlchemy setup# For Postgres, we don't need check_same_threadconnect_args = {}if DB_URL.startswith("sqlite"): connect_args["check_same_thread"] = False
engine = create_engine( DB_URL, connect_args=connect_args, pool_pre_ping=True, # Check connection health before using pool_recycle=300 # Recycle connections every 5 minutes)SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)Base = declarative_base()
class DocumentMetadata(Base): __tablename__ = "documents" doc_id = Column(String, primary_key=True, index=True) filename = Column(String, nullable=False) pages = Column(Integer, nullable=False) chunks = Column(Integer, nullable=False) text_length = Column(Integer, nullable=False) upload_time = Column(DateTime, default=datetime.utcnow)
# Create tablestry: Base.metadata.create_all(bind=engine) logger.info("Database tables verified/created successfully.")except Exception as e: logger.error(f"Failed to initialize database tables: {e}")
def get_db(): """Get database session""" db = SessionLocal() try: yield db finally: db.close()
def save_metadata(doc_id: str, filename: str, pages: int, chunks: int, text_length: int): """Save document metadata to database""" db = SessionLocal() try: doc_meta = DocumentMetadata( doc_id=doc_id, filename=filename, pages=pages, chunks=chunks, text_length=text_length ) db.add(doc_meta) db.commit() return True except Exception as e: db.rollback() logger.error(f"Error saving metadata to database: {e}") return False finally: db.close()
def count_documents() -> int: """Count total documents in database""" db = SessionLocal() try: return db.query(DocumentMetadata).count() except Exception as e: logger.error(f"Error counting documents: {e}") return 0 finally: db.close()
def list_documents() -> list: """List all documents with metadata""" db = SessionLocal() try: docs = db.query(DocumentMetadata).all() return [ { "doc_id": doc.doc_id, "filename": doc.filename, "pages": doc.pages, "chunks": doc.chunks, "text_length": doc.text_length, "upload_time": doc.upload_time.isoformat() } for doc in docs ] except Exception as e: logger.error(f"Error listing documents: {e}") return [] finally: db.close()
def delete_document(doc_id: str) -> bool: """Delete document metadata""" db = SessionLocal() try: doc = db.query(DocumentMetadata).filter(DocumentMetadata.doc_id == doc_id).first() if doc: db.delete(doc) db.commit() return True return False except Exception as e: db.rollback() logger.error(f"Error deleting document {doc_id}: {e}") return False finally: db.close()
def get_document_stats(): """Get document statistics""" db = SessionLocal() try: total_docs = db.query(DocumentMetadata).count() total_pages = db.query(func.sum(DocumentMetadata.pages)).scalar() or 0 total_chunks = db.query(func.sum(DocumentMetadata.chunks)).scalar() or 0 return { "total_documents": total_docs, "total_pages": int(total_pages), "total_chunks": int(total_chunks), "documents_remaining": max(0, DOC_LIMIT - total_docs) } except Exception as e: logger.error(f"Error retrieving document statistics: {e}") return {"error": str(e)} finally: db.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596import osfrom typing import Listfrom pydantic import BaseModelimport google.generativeai as genaiimport openaiimport cohere
# Configure API clientsgenai.configure(api_key=os.getenv("GOOGLE_GEMINI_API_KEY"))openai_client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY"))cohere_client = cohere.Client(os.getenv("COHERE_API_KEY"))
class LLMRequest(BaseModel): query: str context: str
class LLMProvider: def __init__(self, name: str, priority: int): self.name = name self.priority = priority def generate(self, request: LLMRequest) -> str: raise NotImplementedError
class GeminiProvider(LLMProvider): def __init__(self): super().__init__("gemini", 1) # Priority 1 (highest) self.model = genai.GenerativeModel("gemini-2.0-flash-lite") def generate(self, request: LLMRequest) -> str: prompt = f"Context: {request.context}\n\nQuestion: {request.query}\n\nAnswer:" response = self.model.generate_content(prompt) return response.text
class OpenAIProvider(LLMProvider): def __init__(self): super().__init__("openai", 2) # Priority 2 def generate(self, request: LLMRequest) -> str: messages = [ {"role": "user", "content": f"Context: {request.context}\n\nQuestion: {request.query}"} ] response = openai_client.chat.completions.create( model="gpt-3.5-turbo", messages=messages, temperature=0.2, max_tokens=500 ) return response.choices[0].message.content
class CohereProvider(LLMProvider): def __init__(self): super().__init__("cohere", 3) # Priority 3 def generate(self, request: LLMRequest) -> str: prompt = f"Context: {request.context}\n\nQuestion: {request.query}\n\nAnswer:" response = cohere_client.generate( model="command-r", prompt=prompt, max_tokens=400, temperature=0.2 ) return response.generations[0].text
# Initialize providers in priority orderPROVIDERS: List[LLMProvider] = [ GeminiProvider(), OpenAIProvider(), CohereProvider()]
def generate_with_fallback(request: LLMRequest) -> dict: """Try providers in order until one succeeds""" last_error = None for provider in PROVIDERS: try: print(f"Trying {provider.name}...") response = provider.generate(request) return { "answer": response, "provider_used": provider.name, "success": True } except Exception as e: print(f"{provider.name} failed: {str(e)}") last_error = str(e) continue # If all providers fail return { "answer": "Sorry, all AI providers are currently unavailable.", "provider_used": "none", "success": False, "error": last_error }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127import vecsimport google.generativeai as genaiimport osimport loggingfrom typing import List
logger = logging.getLogger("rag-pipeline.vector_store")
# Configure Google Generative AI for embeddingsgenai.configure(api_key=os.getenv("GOOGLE_GEMINI_API_KEY"))EMBEDDING_MODEL = "models/embedding-001"VECTOR_DIMENSION = 768 # models/embedding-001 dimension
# DB URL for SupabaseDB_URL = os.getenv("DB_URL")COLLECTION_NAME = "document_embeddings"
def _get_vecs_collection(): """Helper to get/create a vecs collection""" if not DB_URL: logger.error("DB_URL not found in environment variables.") return None try: # Create a vecs client vx = vecs.create_client(DB_URL) # Get or create the collection return vx.get_or_create_collection(name=COLLECTION_NAME, dimension=VECTOR_DIMENSION) except Exception as e: logger.error(f"Failed to connect to Supabase pgvector: {e}") return None
def _get_embeddings(texts: List[str]) -> List[List[float]]: """Helper to get embeddings from Gemini API with batching""" try: result = genai.embed_content( model=EMBEDDING_MODEL, content=texts, task_type="retrieval_document" ) return result['embedding'] except Exception as e: logger.error(f"Gemini Embedding API error: {e}") raise
def add_document_chunks(doc_id: str, chunks: List[str]) -> bool: """Add document chunks to Supabase using Gemini Embeddings""" collection = _get_vecs_collection() if not collection: return False try: if not chunks: return True # Generate embeddings via API embeddings = _get_embeddings(chunks) # Prepare data for vecs (id, vector, metadata) # vecs expects a list of tuples: (id, vector, metadata) records = [] for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)): chunk_id = f"{doc_id}_chunk_{i}" records.append(( chunk_id, embedding, {"document_id": doc_id, "chunk_index": i, "content": chunk} )) # Upsert into pgvector collection.upsert(records=records) # Create an index if it doesn't exist (optional, but good for performance) # For small datasets, this is fast. collection.create_index() return True except Exception as e: logger.error(f"Error adding chunks to Supabase: {e}") return False
def search_similar_chunks(query: str, k: int = 5) -> List[str]: """Search for similar document chunks using Gemini Embedding API and Supabase""" collection = _get_vecs_collection() if not collection: return [] try: # Generate query embedding result = genai.embed_content( model=EMBEDDING_MODEL, content=query, task_type="retrieval_query" ) query_embedding = result['embedding'] # Search in pgvector # results = collection.query(data=query_embedding, limit=k, include_value=False, include_metadata=True) # Note: vecs.query returns IDs by default, but we want the metadata/text results = collection.query( data=query_embedding, limit=k, include_metadata=True ) # Extract text from metadata # vecs metadata is stored in the metadata column return [res[1].get("content", "") for res in results if res[1]] except Exception as e: logger.error(f"Error searching Supabase: {e}") return []
def get_collection_stats() -> dict: """Get statistics about the document collection""" collection = _get_vecs_collection() if not collection: return {"total_chunks": 0} try: # Get count of documents in the collection # vecs doesn't have a direct count() on collection in all versions, # but we can query or use the metadata total = collection.count() # Some versions of vecs support count() return {"total_chunks": total} except Exception as e: logger.error(f"Error retrieving collection stats: {e}") return {"total_chunks": 0, "error": str(e)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960def chunk_text(text: str, chunk_size: int = 1000, overlap: int = 200) -> list[str]: """Split text into overlapping chunks""" if not text.strip(): return [] words = text.split() chunks = [] start = 0 while start < len(words): # Calculate end position end = start + chunk_size # Get chunk words chunk_words = words[start:end] chunk_text = " ".join(chunk_words) # Add chunk if it has content if chunk_text.strip(): chunks.append(chunk_text) # Move start position (with overlap) start = end - overlap # Break if we've processed all words if end >= len(words): break return chunks
def extract_pdf_text(file_path: str) -> str: """Extract text from PDF file""" try: from pypdf import PdfReader reader = PdfReader(file_path) text_content = "" for page in reader.pages: page_text = page.extract_text() if page_text: text_content += page_text + "\n" return text_content.strip() except Exception as e: print(f"Error extracting PDF text: {e}") return ""
def clean_text(text: str) -> str: """Clean and normalize text""" if not text: return "" # Remove extra whitespace text = " ".join(text.split()) # Remove special characters if needed # Add more cleaning rules here as needed return text123456789101112131415161718192021222324252627282930313233343536version: "3.9"
services: web: build: . ports: - "8000:8000" volumes: - ./app:/app/app - ./uploads:/app/uploads - ./data:/app/data - ./tests:/app/tests env_file: - .env environment: - GOOGLE_GEMINI_API_KEY - OPENAI_API_KEY - COHERE_API_KEY - DEBUG command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
test: build: . volumes: - ./app:/app/app - ./tests:/app/tests env_file: - .env environment: - GOOGLE_GEMINI_API_KEY - OPENAI_API_KEY - COHERE_API_KEY - DEBUG command: pytest tests/ -v profiles: - test1234567[tool:pytest]testpaths = testspython_files = test_*.pypython_classes = Test*python_functions = test_*addopts = -v --tb=shortasyncio_mode = auto12345678910111213141516fastapiuvicorn[standard]httpxpsycopg2-binaryvecsopenaipydanticpydantic-settingspython-multipartsqlalchemycoherepython-dotenvgoogle-generativeaipypdfpytestpytest-asyncio123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import sysimport ossys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'app')))
import pytestimport jsonfrom fastapi.testclient import TestClientfrom app.main import app
client = TestClient(app)
def test_root_endpoint(): """Test root endpoint returns correct information""" response = client.get("/") assert response.status_code == 200 data = response.json() assert "message" in data assert "version" in data assert data["message"] == "RAG Pipeline API"
def test_health_endpoint(): """Test health endpoint""" response = client.get("/health") assert response.status_code == 200 data = response.json() assert "status" in data
def test_config_test_endpoint(): """Test config test endpoint""" response = client.get("/config-test") assert response.status_code == 200 data = response.json() assert "debug_mode" in data
def test_metadata_stats(): """Test metadata stats endpoint""" response = client.get("/metadata/stats") assert response.status_code == 200 data = response.json() assert "total_documents" in data
def test_upload_stats(): """Test upload stats endpoint""" response = client.get("/upload/stats") assert response.status_code == 200
def test_query_endpoint_no_documents(): """Test query endpoint with no documents""" query_data = {"question": "What is AI?"} response = client.post( "/query", json=query_data, headers={"Content-Type": "application/json"} ) assert response.status_code == 200 data = response.json() assert "answer" in data
def test_upload_invalid_file(): """Test upload with invalid file type""" # Create a temporary text file with tempfile.NamedTemporaryFile(suffix=".txt", mode="w", delete=False) as f: f.write("This is a test file") temp_file_path = f.name try: with open(temp_file_path, "rb") as f: response = client.post( "/upload", files={"file": ("test.txt", f, "text/plain")} ) assert response.status_code == 400 assert "Only PDF files are supported" in response.json()["detail"] finally: os.unlink(temp_file_path)
@pytest.mark.asyncioasync def test_vector_store_functions(): """Test vector store basic functions""" from app.services.vector_store import get_collection_stats stats = get_collection_stats() assert "total_chunks" in stats
@pytest.mark.asyncio async def test_text_processing(): """Test text processing functions""" from app.utils.text_processing import chunk_text, clean_text test_text = "This is a test document. " * 100 cleaned = clean_text(test_text) chunks = chunk_text(cleaned, chunk_size=50) assert len(cleaned) > 0 assert len(chunks) > 0 assert all(isinstance(chunk, str) for chunk in chunks)
def test_llm_providers_import(): """Test that LLM providers can be imported""" try: from app.services.llm_providers import PROVIDERS, generate_with_fallback assert len(PROVIDERS) > 0 assert callable(generate_with_fallback) except ImportError as e: pytest.fail(f"Could not import LLM providers: {e}")
def test_doc_store_functions(): """Test document store functions""" from app.services.doc_store import count_documents, get_document_stats count = count_documents() assert isinstance(count, int) assert count >= 0 stats = get_document_stats() assert "total_documents" in stats assert "documents_remaining" in stats.dockerignoreAdded+17
.env.exampleAdded+9
.gitignoreAdded+25
DEPLOY_HUGGINGFACE.mdAdded+101
DockerfileAdded+37
README.mdAdded+21
SUPABASE_SETUP.mdAdded+46
app/__init__.pyAdded
app/api/metadata.pyAdded+57
app/api/query.pyAdded+80
app/api/upload.pyAdded+128
app/config.pyAdded+15
app/main.pyAdded+84
app/services/__init__.pyAdded
app/services/doc_store.pyAdded+146
app/services/llm_providers.pyAdded+96
app/services/vector_store.pyAdded+127
app/utils/text_processing.pyAdded+60
docker-compose.ymlAdded+36
pytest.iniAdded+7
requirements.txtAdded+16
tests/test_basic.pyAdded+117