# viinayakpk/rag architecture

> Architecture diagram of the GitHub repository viinayakpk/rag, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-31). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/viinayakpk/rag
- Repository: https://github.com/viinayakpk/rag

## Overview

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: [`app/retrieval.py`](https://github.com/viinayakpk/rag/blob/main/app/retrieval.py) (Retrieval service), [`app/main.py`](https://github.com/viinayakpk/rag/blob/main/app/main.py) (FastAPI app), [`app/routes/chat.py`](https://github.com/viinayakpk/rag/blob/main/app/routes/chat.py) (Chat flow), [`app/db.py`](https://github.com/viinayakpk/rag/blob/main/app/db.py) (DB access)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["API boundary"]
  node_main["FastAPI app<br/>api entrypoint<br/>[main.py]"]
  node_route_text["Text route<br/>api route<br/>[text.py]"]
  node_route_document["Document route<br/>api route<br/>[document.py]"]
  node_route_search["Search route<br/>api route<br/>[search.py]"]
  node_route_chat["Chat route<br/>api route<br/>[chat.py]"]
end

subgraph group_ingest["Ingest pipeline"]
  node_extraction["Extraction<br/>parse and extract<br/>[extraction.py]"]
  node_chunking["Chunking<br/>text splitter<br/>[chunking.py]"]
  node_embeddings(("Embeddings<br/>vector generation<br/>[embeddings.py]"))
  node_ingest["Ingest orchestrator<br/>write pipeline<br/>[ingest.py]"]
end

subgraph group_retrieval["Retrieval pipeline"]
  node_retrieval["Retrieval service<br/>search orchestration<br/>[retrieval.py]"]
  node_rerank(("Reranker<br/>second-stage ranking<br/>[rerank.py]"))
  node_chat["Chat flow<br/>rag answer flow<br/>[chat.py]"]
end

subgraph group_graph["Entity graph"]
  node_graph_extract["Graph extract<br/>entity extraction<br/>[graph_extract.py]"]
  node_graph_resolve["Graph resolve<br/>entity resolution<br/>[graph_resolve.py]"]
  node_graph{{"Graph filter<br/>entity-aware filter<br/>[graph.py]"}}
end

subgraph group_storage["Persistence"]
  node_db[("DB access<br/>postgres client<br/>[db.py]")]
  node_schema[("Schema<br/>[schema.sql]")]
  node_models["Models<br/>[models.py]"]
  node_postgres[("Postgres 16<br/>database")]
end

subgraph group_external["External services"]
  node_voyage(("Voyage AI<br/>model api"))
  node_anthropic(("Anthropic<br/>model api"))
end

subgraph group_ops["Ops and eval"]
  node_settings["Settings<br/>config<br/>[settings.py]"]
  node_limits{{"Limits<br/>guardrails<br/>[limits.py]"}}
  node_middleware["Middleware<br/>[middleware.py]"]
  node_docker["Compose<br/>deployment<br/>[docker-compose.yml]"]
  node_evals["Evals<br/>benchmark harness<br/>[run_eval.py]"]
end

node_main -->|"routes"| node_route_text
node_main -->|"routes"| node_route_document
node_main -->|"routes"| node_route_search
node_main -->|"routes"| node_route_chat
node_route_text -->|"ingests"| node_ingest
node_route_document -->|"extracts"| node_extraction
node_extraction -->|"splits"| node_chunking
node_chunking -->|"vectorizes"| node_embeddings
node_ingest -->|"extracts entities"| node_graph_extract
node_graph_extract -->|"resolves"| node_graph_resolve
node_graph_resolve -->|"indexes"| node_graph
node_ingest -->|"writes"| node_db
node_db -->|"implements"| node_schema
node_route_search -->|"queries"| node_retrieval
node_retrieval -->|"embeds query"| node_embeddings
node_retrieval -->|"reranks"| node_rerank
node_retrieval -->|"filters"| node_graph
node_route_chat -->|"orchestrates"| node_chat
node_chat -->|"retrieves"| node_retrieval
node_chat -->|"prefilters"| node_graph
node_chat -->|"generates"| node_anthropic
node_embeddings -->|"calls"| node_voyage
node_rerank -->|"calls"| node_voyage
node_graph_extract -->|"calls"| node_anthropic
node_chat -->|"reads sources"| node_db
node_retrieval -->|"reads index"| node_db
node_main -->|"wraps"| node_middleware
node_main -->|"enforces"| node_limits
node_settings -.->|"configures"| node_db
node_settings -.->|"configures"| node_voyage
node_settings -.->|"configures"| node_anthropic
node_docker -->|"provisions"| node_postgres
node_evals -.->|"benchmarks"| node_retrieval
node_evals -.->|"checks"| node_chat

click node_main "https://github.com/viinayakpk/rag/blob/main/app/main.py"
click node_route_text "https://github.com/viinayakpk/rag/blob/main/app/routes/text.py"
click node_route_document "https://github.com/viinayakpk/rag/blob/main/app/routes/document.py"
click node_route_search "https://github.com/viinayakpk/rag/blob/main/app/routes/search.py"
click node_route_chat "https://github.com/viinayakpk/rag/blob/main/app/routes/chat.py"
click node_extraction "https://github.com/viinayakpk/rag/blob/main/app/extraction.py"
click node_chunking "https://github.com/viinayakpk/rag/blob/main/app/chunking.py"
click node_embeddings "https://github.com/viinayakpk/rag/blob/main/app/embeddings.py"
click node_ingest "https://github.com/viinayakpk/rag/blob/main/app/ingest.py"
click node_retrieval "https://github.com/viinayakpk/rag/blob/main/app/retrieval.py"
click node_rerank "https://github.com/viinayakpk/rag/blob/main/app/rerank.py"
click node_chat "https://github.com/viinayakpk/rag/blob/main/app/routes/chat.py"
click node_graph_extract "https://github.com/viinayakpk/rag/blob/main/app/graph_extract.py"
click node_graph_resolve "https://github.com/viinayakpk/rag/blob/main/app/graph_resolve.py"
click node_graph "https://github.com/viinayakpk/rag/blob/main/app/graph.py"
click node_db "https://github.com/viinayakpk/rag/blob/main/app/db.py"
click node_schema "https://github.com/viinayakpk/rag/blob/main/sql/schema.sql"
click node_models "https://github.com/viinayakpk/rag/blob/main/app/models.py"
click node_settings "https://github.com/viinayakpk/rag/blob/main/app/settings.py"
click node_limits "https://github.com/viinayakpk/rag/blob/main/app/limits.py"
click node_middleware "https://github.com/viinayakpk/rag/blob/main/app/middleware.py"
click node_docker "https://github.com/viinayakpk/rag/blob/main/docker-compose.yml"
click node_evals "https://github.com/viinayakpk/rag/blob/main/evals/run_eval.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_route_text,node_route_document,node_route_search,node_route_chat,node_settings,node_limits,node_middleware,node_docker,node_evals toneBlue
class node_extraction,node_chunking,node_embeddings,node_ingest toneAmber
class node_retrieval,node_rerank,node_chat toneMint
class node_graph_extract,node_graph_resolve,node_graph toneRose
class node_db,node_schema,node_models,node_postgres toneIndigo
class node_voyage,node_anthropic toneTeal
```

## Components

### API boundary

FastAPI entrypoint and public route modules.

- [FastAPI app](https://github.com/viinayakpk/rag/blob/main/app/main.py): api entrypoint · Application startup and request boundary. · `app/main.py`
- [Text route](https://github.com/viinayakpk/rag/blob/main/app/routes/text.py): api route · POST /text ingestion endpoint. · `app/routes/text.py`
- [Document route](https://github.com/viinayakpk/rag/blob/main/app/routes/document.py): api route · POST /document PDF ingestion endpoint. · `app/routes/document.py`
- [Search route](https://github.com/viinayakpk/rag/blob/main/app/routes/search.py): api route · GET /search retrieval endpoint. · `app/routes/search.py`
- [Chat route](https://github.com/viinayakpk/rag/blob/main/app/routes/chat.py): api route · POST /chat grounded Q&A endpoint. · `app/routes/chat.py`

### Ingest pipeline

Synchronous document and text ingestion path.

- [Extraction](https://github.com/viinayakpk/rag/blob/main/app/extraction.py): parse and extract · Turns source inputs into text, especially PDFs. · `app/extraction.py`
- [Chunking](https://github.com/viinayakpk/rag/blob/main/app/chunking.py): text splitter · Splits extracted text into retrieval-sized chunks. · `app/chunking.py`
- [Embeddings](https://github.com/viinayakpk/rag/blob/main/app/embeddings.py): vector generation · Creates embeddings for chunks and queries. · `app/embeddings.py`
- [Ingest orchestrator](https://github.com/viinayakpk/rag/blob/main/app/ingest.py): write pipeline · Coordinates extraction, chunking, graph work, and durable writes. · `app/ingest.py`

### Retrieval pipeline

Hybrid search, reranking, and chat grounding.

- [Retrieval service](https://github.com/viinayakpk/rag/blob/main/app/retrieval.py): search orchestration · Builds hybrid retrieval over vector and lexical signals. · `app/retrieval.py`
- [Reranker](https://github.com/viinayakpk/rag/blob/main/app/rerank.py): second-stage ranking · Re-orders candidates before return or chat grounding. · `app/rerank.py`
- [Chat flow](https://github.com/viinayakpk/rag/blob/main/app/routes/chat.py): rag answer 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](https://github.com/viinayakpk/rag/blob/main/app/graph_extract.py): entity extraction · Identifies entities and relations from chunks. · `app/graph_extract.py`
- [Graph resolve](https://github.com/viinayakpk/rag/blob/main/app/graph_resolve.py): entity resolution · Collapses aliases into canonical entities within scope. · `app/graph_resolve.py`
- [Graph filter](https://github.com/viinayakpk/rag/blob/main/app/graph.py): entity-aware filter · Applies co-mention constraints during retrieval and chat. · `app/graph.py`

### Persistence

Postgres-backed durable state and schema.

- [DB access](https://github.com/viinayakpk/rag/blob/main/app/db.py): postgres client · Connection setup and transaction access. · `app/db.py`
- [Schema](https://github.com/viinayakpk/rag/blob/main/sql/schema.sql): postgres schema · Documents, chunks, embeddings, metadata, and graph relations. · `sql/schema.sql`
- [Models](https://github.com/viinayakpk/rag/blob/main/app/models.py): domain models · Shared request and response models. · `app/models.py`
- **Postgres 16**: database · Primary system of record with pgvector.

### External services

Model APIs used for embeddings, reranking, extraction, and answer generation.

- **Voyage AI**: model api · Embeddings and reranking service.
- **Anthropic**: model api · Chat answer generation and graph/entity extraction service.

### Ops and eval

Deployment, limits, middleware, and evaluation harness.

- [Settings](https://github.com/viinayakpk/rag/blob/main/app/settings.py): config · Environment-driven configuration and secrets. · `app/settings.py`
- [Limits](https://github.com/viinayakpk/rag/blob/main/app/limits.py): guardrails · Enforces upload and extracted-text bounds. · `app/limits.py`
- [Middleware](https://github.com/viinayakpk/rag/blob/main/app/middleware.py): api middleware · Cross-cutting request and response behavior. · `app/middleware.py`
- [Compose](https://github.com/viinayakpk/rag/blob/main/docker-compose.yml): deployment · Local Postgres and supporting infrastructure. · `docker-compose.yml`
- [Evals](https://github.com/viinayakpk/rag/blob/main/evals/run_eval.py): benchmark harness · Graph-on versus graph-off retrieval evaluation. · `evals/run_eval.py`

## Connections

- 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.
