How viinayakpk/rag-pipeline works
1. What this repository is
- A FastAPI-based knowledge-retrieval backend, not a generic web app.
- Its core contract is: ingest documents, index them in PostgreSQL/pgvector, retrieve relevant chunks with hybrid search, then optionally generate grounded answers with citations.
2. Top-level request boundary
- app/main.py wires the application together.
- app/api/* contains the HTTP boundary split by capability: text upload, PDF upload, search, chat, single-document lookup, and document/entity-related endpoints.
- app/schemas/* defines the Pydantic request/response shapes that validate and constrain the API surface.
3. Ingestion pipeline
- POST /text and POST /document both feed the same ingestion service path in app/services/ingestion.py.
- The pipeline is: deduplicate via SHA-256 → detect/resolve language → normalize metadata → chunk text → embed chunks → persist document/chunks/vectors → best-effort entity extraction.
- This means ingestion is the main write path into the system.
4. Document processing responsibilities
- app/services/chunking.py owns text splitting.
- app/services/embeddings.py produces vector representations using the multilingual E5 model.
- app/services/entities.py performs language-aware NER enrichment.
- These are separate service boundaries so the ingestion flow can orchestrate them without embedding model or NLP details leaking into API code.
5. Persistence layer
- app/db/models.py defines the schema for documents, chunks, embeddings, entities, and their linking tables.
- app/db/session.py manages database sessions; app/db/base.py centralizes model registration.
- Alembic migrations live under app/db/migrations/, so schema evolution is explicit and versioned.
- PostgreSQL is the single system of record, with pgvector storing embeddings and SQL/JSONB handling metadata.
6. Retrieval/search pipeline
- GET /search is implemented through app/services/retrieval.py.
- The pipeline combines vector similarity and PostgreSQL full-text search, applies metadata filters, merges candidate lists with reciprocal rank fusion, then reranks the short list with a cross-encoder.
- This is the key read path and the main place where retrieval quality is enforced.
7. Chat/QA pipeline
- POST /chat reuses the retrieval pipeline, then hands the top chunks to app/services/chat.py.
- app/services/llm.py abstracts the provider boundary: mock by default, with Ollama or OpenRouter as optional real LLM backends.
- The answer is intentionally grounded in retrieved context and returns source citations plus retrieval notes, so the LLM is downstream of retrieval rather than the source of truth.
8. Language and multilingual design
- The system is built for EN, SV, DE, NO, and FR.
- Language affects multiple subsystems: metadata validation, FTS configuration, chunking/ingestion assumptions, entity extraction models, and cross-lingual embedding retrieval.
- This multilingual support is architectural, not cosmetic: an English query can retrieve Swedish/Norwegian/French documents through the shared embedding space.
9. Configuration and operational boundaries
- app/config.py centralizes environment-driven settings such as LLM provider, model names, candidate counts, ports, and auth.
- app/errors.py likely standardizes API error mapping so upload/search/chat failures return consistent HTTP responses.
- The repo is container-first: Dockerfile and docker-compose.yml package the app, PostgreSQL, and optional LLM runtime into a single deployable unit.
10. Auth and public health endpoints
- API key protection is optional and configured via environment variables, so it is an operational toggle rather than a hard dependency.
- /health and /ready remain open for monitoring regardless of auth.
- That creates a clean separation between business endpoints and infrastructure probes.
11. Tests and evaluation as part of architecture
- tests/ covers the major boundaries: config, health, chunking, ingestion, retrieval, and API behavior.
- examples/*.sh provide reproducible benchmark and robustness checks, which function as an evaluation harness around the retrieval system.
- This repo is therefore built around measurable retrieval quality, not just endpoint correctness.
12. Important architectural shape to diagram
- One can draw it as: HTTP API layer → service layer → PostgreSQL/pgvector + NLP/embedding/rerank components → LLM provider for chat output.
- The critical data flow is document ingestion into DB-backed indexed chunks, then hybrid retrieval from that store, then optional LLM synthesis over retrieved evidence.
Main entry points: main.py App wire-up · ingestion.py Ingestion · retrieval.py Retrieval · models.py DB models
Components 23
HTTP API
FastAPI routes and request/response schemas
- App wire-up · Creates the application and connects routes, config, and middleware.
app/main.py - Text ingest · Endpoint for raw text upload and ingestion.
app/api/text.py - PDF ingest · Endpoint for document upload and ingestion.
app/api/document.py - Search API · Hybrid retrieval endpoint for ranked chunk lookup.
app/api/search.py - Chat API · Grounded QA endpoint that answers from retrieved context.
app/api/chat.py - Docs API · Document and entity lookup endpoints.
app/api/documents.py - Ingest schemas · Validation shapes for ingestion requests and responses.
app/schemas/ingest.py - Search schemas · Validation shapes for search requests and results.
app/schemas/search.py - Chat schemas · Validation shapes for chat requests and answers.
app/schemas/chat.py
Service Layer
Ingestion, retrieval, chat, and NLP orchestration
- Ingestion · Deduplicates, normalizes, chunks, embeds, persists, and enriches documents.
app/services/ingestion.py - Chunking · Splits documents into retrieval-friendly chunks.
app/services/chunking.py - Embeddings · Produces multilingual E5 embeddings for chunks and queries.
app/services/embeddings.py - Entity NER · Performs language-aware entity extraction during ingestion.
app/services/entities.py - Retrieval · Combines vector search, full-text search, fusion, and filtering.
app/services/retrieval.py - Reranking · Scores the shortlist to improve result ordering.
app/services/reranking.py - Chat synthesis · Builds grounded answers from retrieved chunks and citations.
app/services/chat.py - LLM provider · Abstracts mock, Ollama, and OpenRouter backends.
app/services/llm.py
Persistence
Database models, session management, and migrations
- DB models · Defines documents, chunks, embeddings, entities, and links.
app/db/models.py - DB session · Creates and manages PostgreSQL sessions.
app/db/session.py - Migrations · Versioned schema evolution for the database.
app/db/migrations/env.py
Operations
Runtime config, app wiring, and deployment packaging
- Config · Environment-driven settings for providers, auth, and runtime limits.
app/config.py - Errors · Normalizes failures into API responses.
app/errors.py - Container stack · Docker packaging for the app, PostgreSQL, and optional LLM runtime.
docker-compose.yml
Connections 29
- App wire-up → Text ingest: mounts · Registers the text ingest route.
- App wire-up → PDF ingest: mounts · Registers the PDF/document ingest route.
- App wire-up → Search API: mounts · Registers the search route.
- App wire-up → Chat API: mounts · Registers the chat route.
- App wire-up → Docs API: mounts · Registers document lookup routes.
- App wire-up → Config: loads · Pulls runtime settings into the app.
- App wire-up → Errors: uses · Maps exceptions to consistent HTTP responses.
- Text ingest → Ingest schemas: validates · Validates text ingestion payloads.
- PDF ingest → Ingest schemas: validates · Validates document upload payloads.
- Search API → Search schemas: validates · Validates search requests and result shapes.
- Chat API → Chat schemas: validates · Validates chat requests and responses.
- Text ingest → Ingestion: calls · Hands text uploads to the ingestion pipeline.
- PDF ingest → Ingestion: calls · Hands document uploads to the ingestion pipeline.
- Search API → Retrieval: calls · Executes hybrid retrieval for search.
- Chat API → Chat synthesis: calls · Starts grounded answer generation.
- Docs API → DB models: reads · Fetches persisted documents and entities.
- Ingestion → Chunking: orchestrates · Splits normalized text into chunks.
- Ingestion → Embeddings: orchestrates · Creates embeddings for chunks.
- Ingestion → Entity NER: orchestrates · Optionally enriches chunks with entities.
- Ingestion → DB session: persists via · Writes documents, chunks, vectors, and entities.
- Ingestion → DB models: writes · Uses the relational schema for stored knowledge.
- Retrieval → DB session: queries · Reads indexed chunks and metadata from PostgreSQL.
- Retrieval → Reranking: feeds · Sends candidate chunks to reranking.
- Retrieval → DB models: reads · Uses document/chunk/embedding schema for search.
- Chat synthesis → Retrieval: reuses · Retrieves evidence before answering.
- Chat synthesis → LLM provider: calls · Delegates synthesis to the configured model backend.
- DB models → Migrations: evolves through · Schema changes are tracked in Alembic.
- Container stack → App wire-up: runs · Packages the API service for deployment.
- Container stack → DB session: provisions · Connects the app to PostgreSQL.