# nainajnaho/rag-knowledge-base architecture

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

- Interactive diagram: https://gitdiagram.com/nainajnaho/rag-knowledge-base
- Repository: https://github.com/nainajnaho/rag-knowledge-base

## Overview

1. **System boundary**
   - This repo is a single Python 3.14 FastAPI service that exposes a small RAG backend.
   - It runs against a Postgres 16 database with pgvector, started locally via Docker Compose.
   - External model services are part of the architecture: Voyage supplies embeddings and reranking, and Anthropic supplies graph extraction plus grounded chat answers with structured citations.

2. **API surface as thin entrypoints**
   - `app/routes/text.py`, `document.py`, `search.py`, and `chat.py` are the main public boundaries.
   - `app/main.py` wires the app together, while middleware and settings handle cross-cutting concerns.
   - The routes are intentionally thin; the real work is pushed into service modules under `app/`.

3. **Ingestion flow**
   - `POST /text` accepts JSON text documents.
   - `POST /document` accepts multipart PDF uploads, extracts text server-side, then feeds the same downstream pipeline as `/text`.
   - Both paths dedupe by SHA-256 of normalized content, so repeated uploads return the existing document rather than creating new rows.

4. **Chunking and persistence**
   - Raw text is split by `app/chunking.py` into token-sized overlapping chunks before indexing.
   - The database stores two core entities in `sql/schema.sql`: `documents` and `chunks`.
   - Documents carry typed fields such as title, author, published date, plus JSONB metadata; chunks carry the text, ordinal, embedding, and document foreign key.

5. **Embedding and vector index**
   - `app/embeddings.py` produces Voyage embeddings for each chunk.
   - Those embeddings are persisted in pgvector and queried with cosine distance.
   - Postgres is doing double duty here: durable storage plus vector search.

6. **Knowledge graph enrichment**
   - Ingest also triggers graph extraction.
   - `app/graph_extract.py` extracts entities per chunk, and `app/graph_resolve.py` canonicalizes them at document/type scope.
   - The resulting graph is stored back in Postgres in relation tables, so the graph is not a separate service.
   - This graph is used for entity-aware filtering, especially the chunk-level “co-mention” constraint.

7. **Search pipeline**
   - `GET /search` is a hybrid retrieval endpoint, not pure vector search.
   - `app/retrieval.py` combines lexical and vector candidates using reciprocal rank fusion.
   - `app/rerank.py` then asks Voyage rerank to reorder the candidate set.
   - Search can also apply metadata filters and graph/entity filters before final ranking.

8. **Chat pipeline**
   - `POST /chat` is the grounded QA path.
   - It retrieves relevant chunks, optionally pre-filters by entities extracted from the question, then sends evidence to Anthropic for a single-turn answer.
   - The response is structured around `answer_blocks`, `sources`, and per-claim citations with verbatim `cited_text`, so the answer is meant to be auditably traceable to chunks.

9. **Graph-aware vs baseline behavior**
   - The same chat endpoint can run with `use_graph=true` or `false`.
   - With graph mode on, entity extraction from the question narrows retrieval before the answer step.
   - With graph mode off, the system falls back to standard hybrid retrieval + rerank.
   - That makes the repo useful for comparing “baseline RAG” against “graph-augmented RAG” without changing the rest of the pipeline.

10. **Shared service layer**
   - The modules under `app/` split the pipeline into clear concerns: extraction, chunking, embeddings, retrieval, reranking, graph logic, LLM access, and database access.
   - `app/ingest.py` appears to be the orchestration layer that stitches these steps together for both text and PDF ingestion.
   - `app/models.py` and `app/settings.py` provide typed request/response/config boundaries used across routes and services.

11. **Operational constraints and middleware**
   - `app/limits.py` enforces upload/text-size bounds so oversized requests fail early.
   - `app/middleware.py` handles request-level cross-cutting behavior.
   - The repository explicitly notes one important runtime constraint: DB connections are currently held across some upstream LLM calls, which limits concurrency.

12. **Validation and evaluation**
   - The tests focus on load-bearing seams: chunking, upload-to-search, citation correctness, and graph-filter smoke tests.
   - `evals/` contains a small corpus-based harness that compares graph-on and graph-off behavior.
   - That evaluation layer is part of the architecture story because it measures whether the graph actually improves retrieval sharpness, not just whether the endpoints work.

13. **How to draw the architecture**
   - A good diagram would show four layers: API routes, orchestration/services, Postgres storage, and external AI services.
   - The main data flow is: ingest text/PDF → extract/chunk/embed → persist documents/chunks/graph → hybrid search/rerank → chat with citations.
   - The main architectural differentiator is that retrieval is not just vector search; it is vector + lexical + metadata + graph-aware filtering, all anchored in Postgres.

Main entry points: [`app/main.py`](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/main.py) (App main), [`app/ingest.py`](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/ingest.py) (Ingest), [`app/routes/chat.py`](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/chat.py) (Chat API), [`app/retrieval.py`](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/retrieval.py) (Retrieval)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_api["API"]
  node_main["App main<br/>FastAPI bootstrap<br/>[main.py]"]
  node_route_text["Text API<br/>ingest route<br/>[text.py]"]
  node_route_doc["Document API<br/>upload route<br/>[document.py]"]
  node_route_search["Search API<br/>retrieval route<br/>[search.py]"]
  node_route_chat["Chat API<br/>qa route<br/>[chat.py]"]
end

subgraph group_svc["Services"]
  node_settings["Settings<br/>config boundary<br/>[settings.py]"]
  node_middleware["Middleware<br/>cross-cutting<br/>[middleware.py]"]
  node_limits["Limits<br/>request guard<br/>[limits.py]"]
  node_ingest["Ingest<br/>orchestration<br/>[ingest.py]"]
  node_extraction["Extraction<br/>pdf text<br/>[extraction.py]"]
  node_chunking["Chunking<br/>text split<br/>[chunking.py]"]
  node_embeddings["Embeddings<br/>vector encode<br/>[embeddings.py]"]
  node_graph_extract["Graph extract<br/>entity extract<br/>[graph_extract.py]"]
  node_graph_resolve["Graph resolve<br/>entity canon<br/>[graph_resolve.py]"]
  node_graph["Graph logic<br/>filtering<br/>[graph.py]"]
  node_retrieval["Retrieval<br/>hybrid rank<br/>[retrieval.py]"]
  node_rerank["Rerank<br/>reorder<br/>[rerank.py]"]
end

subgraph group_store["Storage"]
  node_db[("Database<br/>postgres access<br/>[db.py]")]
  node_schema["Schema<br/>[schema.sql]"]
end

subgraph group_ext["External AI"]
  node_llm["LLM access<br/>answering<br/>[llm.py]"]
end

subgraph group_qa["Quality"]
  node_evals["Evals<br/>evaluation harness<br/>[run_eval.py]"]
end

node_main -->|"loads"| node_settings
node_main -->|"adds"| node_middleware
node_main -->|"mounts"| node_route_text
node_main -->|"mounts"| node_route_doc
node_main -->|"mounts"| node_route_search
node_main -->|"mounts"| node_route_chat
node_route_text -->|"guards"| node_limits
node_route_doc -->|"guards"| node_limits
node_route_doc -->|"extracts"| node_extraction
node_route_text -->|"ingests"| node_ingest
node_route_doc -->|"ingests"| node_ingest
node_ingest -->|"splits"| node_chunking
node_ingest -->|"embeds"| node_embeddings
node_ingest -->|"extracts"| node_graph_extract
node_graph_extract -->|"canonicalizes"| node_graph_resolve
node_ingest -->|"persists"| node_db
node_db -->|"implements"| node_schema
node_route_search -->|"searches"| node_retrieval
node_route_search -->|"filters"| node_graph
node_retrieval -->|"uses"| node_graph
node_retrieval -->|"queries"| node_db
node_retrieval -->|"orders"| node_rerank
node_rerank -->|"calls"| node_llm
node_route_chat -->|"optional"| node_graph
node_route_chat -->|"retrieves"| node_retrieval
node_route_chat -->|"answers"| node_llm
node_llm -->|"references"| node_db
node_evals -.->|"checks"| node_route_search
node_evals -.->|"checks"| node_route_chat

click node_main "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/main.py"
click node_route_text "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/text.py"
click node_route_doc "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/document.py"
click node_route_search "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/search.py"
click node_route_chat "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/chat.py"
click node_settings "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/settings.py"
click node_middleware "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/middleware.py"
click node_limits "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/limits.py"
click node_ingest "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/ingest.py"
click node_extraction "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/extraction.py"
click node_chunking "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/chunking.py"
click node_embeddings "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/embeddings.py"
click node_graph_extract "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/graph_extract.py"
click node_graph_resolve "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/graph_resolve.py"
click node_graph "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/graph.py"
click node_retrieval "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/retrieval.py"
click node_rerank "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/rerank.py"
click node_llm "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/llm.py"
click node_db "https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/db.py"
click node_schema "https://github.com/nainajnaho/rag-knowledge-base/blob/main/sql/schema.sql"
click node_evals "https://github.com/nainajnaho/rag-knowledge-base/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_doc,node_route_search,node_route_chat toneBlue
class node_settings,node_middleware,node_limits,node_ingest,node_extraction,node_chunking,node_embeddings,node_graph_extract,node_graph_resolve,node_graph,node_retrieval,node_rerank toneAmber
class node_db,node_schema toneMint
class node_llm toneRose
class node_evals toneIndigo
```

## Components

### API

FastAPI entrypoints and request boundaries

- [App main](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/main.py): FastAPI bootstrap · Creates and wires the application, middleware, and routes. · `app/main.py`
- [Text API](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/text.py): ingest route · JSON text document ingestion entrypoint. · `app/routes/text.py`
- [Document API](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/document.py): upload route · Multipart PDF upload entrypoint. · `app/routes/document.py`
- [Search API](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/search.py): retrieval route · Hybrid search endpoint for ranked chunk retrieval. · `app/routes/search.py`
- [Chat API](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/routes/chat.py): qa route · Grounded question answering endpoint with citations. · `app/routes/chat.py`

### Services

Ingestion, retrieval, graph, and answer orchestration

- [Settings](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/settings.py): config boundary · Typed configuration shared across the service. · `app/settings.py`
- [Middleware](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/middleware.py): cross-cutting · Request-level cross-cutting behavior. · `app/middleware.py`
- [Limits](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/limits.py): request guard · Upload and text-size guardrails. · `app/limits.py`
- [Ingest](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/ingest.py): orchestration · Coordinates text and PDF ingestion into the indexing pipeline. · `app/ingest.py`
- [Extraction](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/extraction.py): pdf text · Server-side text extraction from uploaded documents. · `app/extraction.py`
- [Chunking](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/chunking.py): text split · Splits normalized text into overlapping token-sized chunks. · `app/chunking.py`
- [Embeddings](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/embeddings.py): vector encode · Produces Voyage embeddings for chunks. · `app/embeddings.py`
- [Graph extract](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/graph_extract.py): entity extract · Extracts entities and relations from chunk text. · `app/graph_extract.py`
- [Graph resolve](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/graph_resolve.py): entity canon · Canonicalizes extracted entities at document/type scope. · `app/graph_resolve.py`
- [Graph logic](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/graph.py): filtering · Entity-aware retrieval constraints and co-mention logic. · `app/graph.py`
- [Retrieval](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/retrieval.py): hybrid rank · Combines lexical and vector candidates with fusion. · `app/retrieval.py`
- [Rerank](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/rerank.py): reorder · Reorders retrieved candidates using Voyage reranking. · `app/rerank.py`

### Storage

Postgres schema and database access

- [Database](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/db.py): postgres access · Database session and query boundary for Postgres plus pgvector. · `app/db.py`
- [Schema](https://github.com/nainajnaho/rag-knowledge-base/blob/main/sql/schema.sql): postgres schema · Defines documents, chunks, and relation tables. · `sql/schema.sql`

### External AI

Third-party model services used by the pipeline

- [LLM access](https://github.com/nainajnaho/rag-knowledge-base/blob/main/app/llm.py): answering · Builds grounded chat prompts and talks to Anthropic. · `app/llm.py`

### Quality

Tests and evaluation harness

- [Evals](https://github.com/nainajnaho/rag-knowledge-base/blob/main/evals/run_eval.py): evaluation harness · Corpus-based comparison of graph-on and graph-off behavior. · `evals/run_eval.py`

## Connections

- App main → Settings: loads · Application bootstrap reads typed configuration.
- App main → Middleware: adds · Wires middleware into the app.
- App main → Text API: mounts · Registers the text ingestion route.
- App main → Document API: mounts · Registers the document upload route.
- App main → Search API: mounts · Registers the search route.
- App main → Chat API: mounts · Registers the chat route.
- Text API → Limits: guards · Rejects oversized text requests early.
- Document API → Limits: guards · Rejects oversized uploads early.
- Document API → Extraction: extracts · PDF uploads are converted to text before indexing.
- Text API → Ingest: ingests · Hands normalized text to the ingestion pipeline.
- Document API → Ingest: ingests · Hands extracted text to the same ingestion pipeline.
- Ingest → Chunking: splits · Breaks content into overlapping chunks.
- Ingest → Embeddings: embeds · Generates embeddings for each chunk.
- Ingest → Graph extract: extracts · Pulls entities and relations from chunks.
- Graph extract → Graph resolve: canonicalizes · Resolves entities to document/type scope.
- Ingest → Database: persists · Stores documents, chunks, and graph relations.
- Database → Schema: implements · Database behavior follows the schema definition.
- Search API → Retrieval: searches · Builds hybrid candidate sets for search.
- Search API → Graph logic: filters · Can apply entity and co-mention constraints.
- Retrieval → Graph logic: uses · Retrieval can be narrowed by graph-aware filters.
- Retrieval → Database: queries · Reads lexical, vector, and metadata-backed candidates.
- Retrieval → Rerank: orders · Candidate set is reranked before response.
- Rerank → LLM access: calls · Uses Voyage reranking service.
- Chat API → Graph logic: optional · Question entities can narrow retrieval when graph mode is on.
- Chat API → Retrieval: retrieves · Fetches evidence chunks for grounded answering.
- Chat API → LLM access: answers · Sends evidence to Anthropic for a single-turn answer.
- LLM access → Database: references · Answering uses retrieved evidence stored in Postgres.
- Evals → Search API: checks · Evaluation covers retrieval behavior.
- Evals → Chat API: checks · Evaluation covers citation and graph-mode behavior.
