How viinayakpk/rag works
1. Overall shape
- This is a Python FastAPI backend for a RAG knowledge base.
- The system has three core pipelines: ingest, retrieve/search, and chat with citations.
- Persistent state lives in Postgres 16 with pgvector; external AI services are used for embeddings, reranking, entity extraction/resolution, and answer generation.
2. API surface
- The request boundary is app/main.py plus route modules under app/routes/.
- Public endpoints are:
- POST /text for plain-text ingestion
- POST /document for PDF ingestion
- GET /search for hybrid retrieval
- POST /chat for grounded Q&A with citations
- GET /health for liveness
- Route modules separate the user-facing workflows: chat.py, document.py, search.py, and text.py.
3. Ingestion pipeline
- Ingest starts with app/extraction.py for turning source input into text, especially PDFs.
- app/chunking.py splits the extracted text into retrieval-sized chunks.
- app/embeddings.py generates vector embeddings for chunks.
- app/ingest.py coordinates the end-to-end write path into the database.
- The README indicates ingest is synchronous and includes graph extraction work inline, so upload latency includes embedding plus entity processing.
4. Document and chunk storage
- sql/schema.sql defines the durable model.
- The main storage boundary is a documents table plus a chunks table.
- Documents carry metadata such as title, author, published date, content hash, and JSONB metadata.
- Chunks store retrievable text and their vector embeddings, with a foreign key back to the parent document.
- Dedupe is content-hash based, so repeated uploads short-circuit to the existing document.
5. Database access layer
- app/db.py handles connection setup and transaction access.
- app/models.py likely contains the Pydantic/domain models used across routes and internal services.
- app/settings.py centralizes environment-driven configuration such as database URL and API keys.
- The architecture depends on Postgres for both transactional data and retrieval indexes, rather than splitting those responsibilities across multiple systems.
6. Retrieval architecture
- app/retrieval.py is the search orchestration layer.
- Retrieval is hybrid: vector similarity via pgvector plus lexical ranking over text, fused with reciprocal rank fusion.
- app/rerank.py applies a second-stage reranker from Voyage to re-order the candidate chunks.
- app/search.py exposes this to clients as the /search endpoint, including metadata filters.
7. Knowledge graph subsystem
- The graph pipeline is split across app/graph_extract.py, app/graph_resolve.py, and app/graph.py.
- Extraction identifies entities from chunks; resolution collapses aliases into canonical entities across a document/type scope.
- The resulting relations support entity-aware filtering, where queries can require chunk-level co-mention of one or more entities.
- This graph is not a separate database: it is persisted in Postgres alongside the document/chunk model.
8. Chat and citation flow
- app/llm.py wraps the Anthropic chat model used for answer generation.
- app/chat.py builds the RAG request: it retrieves candidate chunks, optionally applies graph-aware pre-filtering, then asks the model to answer using those sources.
- The important contract is structured citations: answer blocks carry verbatim cited_text tied back to source chunks, not just opaque footnotes.
- This makes verification a data check against retrieved text rather than a parsing problem.
9. Cross-cutting controls
- app/limits.py enforces ingestion bounds such as upload size and extracted-text caps.
- app/middleware.py likely handles request/response cross-cutting behavior for the API boundary.
- These limits matter architecturally because they protect the synchronous ingest path from oversized uploads and keep the demo bounded.
10. Execution and deployment
- docker-compose.yml stands up the local infrastructure, primarily Postgres + pgvector.
- The project is managed with uv and targets Python 3.14.
- The runtime topology is therefore simple: a FastAPI app process talking to a single Postgres-backed datastore, with outbound calls to Voyage and Anthropic.
11. Evaluation and validation
- tests/ contains smoke tests that exercise the load-bearing seams: chunking, ingest→search, chat citations, and graph filtering.
- evals/ adds a small benchmark harness for comparing graph-on versus graph-off retrieval behavior on a fixed corpus.
- These are architectural tests, not unit tests only; they verify the end-to-end contracts between subsystems.
12. Main data flows to diagram
- Ingest flow: client upload → extraction → chunking → embeddings → graph extraction/resolution → Postgres write.
- Search flow: query + optional metadata/entity filters → hybrid candidate retrieval → reranking → ranked chunk results.
- Chat flow: question → optional entity pre-filter → retrieval → LLM answer generation with structured citations → response containing answer, sources, and cited substrings.
- The key architectural boundary is that retrieval produces the evidence set, and the LLM is constrained to answer from that evidence.
13. Important external dependencies
- Voyage AI is used for embeddings and reranking.
- Anthropic is used for answer generation and graph/entity extraction.
- Postgres + pgvector is the primary persistence and retrieval engine.
- These services materially shape the design: the repo is optimized around a single relational store plus model APIs, not around a separate vector DB or graph DB.
14. What to emphasize in a diagram
- Show FastAPI as the entry point.
- Split the backend into ingest, retrieval, chat/citations, and graph/entity filtering.
- Show Postgres as the shared system of record for documents, chunks, embeddings, metadata, and graph relations.
- Show outbound arrows to Voyage and Anthropic from the relevant pipeline stages.
Main entry points: retrieval.py Retrieval service · main.py FastAPI app · chat.py Chat flow · db.py DB access
Components 26
API boundary
FastAPI entrypoint and public route modules.
- FastAPI app · Application startup and request boundary.
app/main.py - Text route · POST /text ingestion endpoint.
app/routes/text.py - Document route · POST /document PDF ingestion endpoint.
app/routes/document.py - Search route · GET /search retrieval endpoint.
app/routes/search.py - Chat route · POST /chat grounded Q&A endpoint.
app/routes/chat.py
Ingest pipeline
Synchronous document and text ingestion path.
- Extraction · Turns source inputs into text, especially PDFs.
app/extraction.py - Chunking · Splits extracted text into retrieval-sized chunks.
app/chunking.py - Embeddings · Creates embeddings for chunks and queries.
app/embeddings.py - Ingest orchestrator · Coordinates extraction, chunking, graph work, and durable writes.
app/ingest.py
Retrieval pipeline
Hybrid search, reranking, and chat grounding.
- Retrieval service · Builds hybrid retrieval over vector and lexical signals.
app/retrieval.py - Reranker · Re-orders candidates before return or chat grounding.
app/rerank.py - Chat flow · Retrieves evidence, applies graph-aware prefiltering, and asks the model to answer with citations.
app/routes/chat.py
Entity graph
Entity extraction, alias resolution, and graph-aware filtering.
- Graph extract · Identifies entities and relations from chunks.
app/graph_extract.py - Graph resolve · Collapses aliases into canonical entities within scope.
app/graph_resolve.py - Graph filter · Applies co-mention constraints during retrieval and chat.
app/graph.py
Persistence
Postgres-backed durable state and schema.
External services
Model APIs used for embeddings, reranking, extraction, and answer generation.
- Voyage AI · Embeddings and reranking service.
- Anthropic · Chat answer generation and graph/entity extraction service.
Ops and eval
Deployment, limits, middleware, and evaluation harness.
- Settings · Environment-driven configuration and secrets.
app/settings.py - Limits · Enforces upload and extracted-text bounds.
app/limits.py - Middleware · Cross-cutting request and response behavior.
app/middleware.py - Compose · Local Postgres and supporting infrastructure.
docker-compose.yml - Evals · Graph-on versus graph-off retrieval evaluation.
evals/run_eval.py
Connections 34
- FastAPI app → Text route: routes · Registers text ingestion endpoint.
- FastAPI app → Document route: routes · Registers document ingestion endpoint.
- FastAPI app → Search route: routes · Registers search endpoint.
- FastAPI app → Chat route: routes · Registers chat endpoint.
- Text route → Ingest orchestrator: ingests · Submits plain-text uploads to the ingest pipeline.
- Document route → Extraction: extracts · Parses uploaded PDFs into text.
- Extraction → Chunking: splits · Produces retrieval-sized chunks from extracted text.
- Chunking → Embeddings: vectorizes · Embeds chunks for retrieval.
- Ingest orchestrator → Graph extract: extracts entities · Runs graph extraction inline during ingest.
- Graph extract → Graph resolve: resolves · Collapses aliases to canonical entities.
- Graph resolve → Graph filter: indexes · Persists graph-aware entity mappings.
- Ingest orchestrator → DB access: writes · Stores documents, chunks, embeddings, and graph records.
- DB access → Schema: implements · Database access follows the declared schema.
- Search route → Retrieval service: queries · Runs hybrid retrieval for clients.
- Retrieval service → Embeddings: embeds query · Generates query vectors for similarity search.
- Retrieval service → Reranker: reranks · Applies second-stage reranking to candidates.
- Retrieval service → Graph filter: filters · Optionally applies entity-aware prefiltering.
- Chat route → Chat flow: orchestrates · Builds grounded Q&A responses.
- Chat flow → Retrieval service: retrieves · Fetches evidence chunks for the prompt.
- Chat flow → Graph filter: prefilters · Uses entity constraints before retrieval when requested.
- Chat flow → Anthropic: generates · Produces answer text and structured citations.
- Embeddings → Voyage AI: calls · Uses Voyage for embedding generation.
- Reranker → Voyage AI: calls · Uses Voyage for reranking.
- Graph extract → Anthropic: calls · Uses Anthropic for entity and relation extraction.
- Chat flow → DB access: reads sources · Looks up candidate chunks and metadata.
- Retrieval service → DB access: reads index · Queries vector and lexical indexes from Postgres.
- FastAPI app → Middleware: wraps · Applies cross-cutting request handling.
- FastAPI app → Limits: enforces · Protects synchronous ingest and upload bounds.
- Settings → DB access: configures · Supplies database connection settings.
- Settings → Voyage AI: configures · Supplies Voyage credentials and model settings.
- Settings → Anthropic: configures · Supplies Anthropic credentials and model settings.
- Compose → Postgres 16: provisions · Starts local Postgres with pgvector.
- Evals → Retrieval service: benchmarks · Compares retrieval behavior across graph settings.
- Evals → Chat flow: checks · Exercises grounded citation behavior.