How nainajnaho/rag-knowledge-base works
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: main.py App main · ingest.py Ingest · chat.py Chat API · retrieval.py Retrieval
Components 21
API
FastAPI entrypoints and request boundaries
- App main · Creates and wires the application, middleware, and routes.
app/main.py - Text API · JSON text document ingestion entrypoint.
app/routes/text.py - Document API · Multipart PDF upload entrypoint.
app/routes/document.py - Search API · Hybrid search endpoint for ranked chunk retrieval.
app/routes/search.py - Chat API · Grounded question answering endpoint with citations.
app/routes/chat.py
Services
Ingestion, retrieval, graph, and answer orchestration
- Settings · Typed configuration shared across the service.
app/settings.py - Middleware · Request-level cross-cutting behavior.
app/middleware.py - Limits · Upload and text-size guardrails.
app/limits.py - Ingest · Coordinates text and PDF ingestion into the indexing pipeline.
app/ingest.py - Extraction · Server-side text extraction from uploaded documents.
app/extraction.py - Chunking · Splits normalized text into overlapping token-sized chunks.
app/chunking.py - Embeddings · Produces Voyage embeddings for chunks.
app/embeddings.py - Graph extract · Extracts entities and relations from chunk text.
app/graph_extract.py - Graph resolve · Canonicalizes extracted entities at document/type scope.
app/graph_resolve.py - Graph logic · Entity-aware retrieval constraints and co-mention logic.
app/graph.py - Retrieval · Combines lexical and vector candidates with fusion.
app/retrieval.py - Rerank · Reorders retrieved candidates using Voyage reranking.
app/rerank.py
Storage
Postgres schema and database access
External AI
Third-party model services used by the pipeline
- LLM access · Builds grounded chat prompts and talks to Anthropic.
app/llm.py
Quality
Tests and evaluation harness
- Evals · Corpus-based comparison of graph-on and graph-off behavior.
evals/run_eval.py
Connections 29
- 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.