Skip to content

RAG project structure: folders, modules and the path from indexing to answer

How to organize a RAG project into single-purpose modules, keep indexing apart from querying, hide the database and model behind interfaces and measure quality from day one.

Ramon Gomes 11 min read Level: Intermediate

Also available in: Español, Français, Português

The first RAGTechnique that retrieves relevant passages from a document base and hands them to the model with the question, so it answers from sources, not memory alone. prototype fits in a notebook: read a PDF, split it, generate embeddings, search and call the model. It works in the demo. The trouble shows up in week two, when someone asks you to accept Word files, switch the embedding model, filter by date and figure out why yesterday's answer was better than today's. If everything lives in one function, every request turns into a rewrite.

This article is about how to organize the code: which modules a RAG project needs, where each thing lives and what goes behind an interface. The search and generation techniques themselves are in the article on RAG techniques, and the choice between RAG and putting everything in the context is in RAG or CAG. The examples come from a RAG app I maintain, built with Next.js and Postgres.

Animation of the two paths in a RAG project: on top, indexing takes a document through extraction, chunking and embeddings to the vector database; below, querying takes the question through embedding, search, reranking and prompt assembly to the model, which returns the answer
The two paths only meet at the database. That's why indexing can run in a separate worker without slowing down whoever is asking.

The Two Paths

Indexing Querying
When it runs When a document comes in or changes On every question
Who waits Nobody (it runs in the background) The person, staring at the screen
What matters Quality of the extracted text, total cost Latency, answer quality
Where it runs Worker, queue, scheduled job API

That difference is the reason for the first split: indexing goes to a worker with a queue, and the APIContract that defines how one program asks another for data or actions: which endpoints to call, what to send and what comes back. On the web, usually HTTP with JSON. only queries. In my app, the upload returns right away and the file goes into a queue; a worker extracts, splits and generates the embeddings. If the PDF has 300 pages, nobody sits watching a spinner.

Professional kitchen in the middle of service, with separate stations side by side: one person chops vegetables, another works the griddle and another plates dishes at the pass, each station with its own tools
In a professional kitchen, prep happens before service, at separate stations. When the order comes in, you just assemble and serve.

The Modules, One Per Job

Module Does Common mistake
Extraction Turns PDF, Word, spreadsheet, image into clean text Assuming every PDF has text (many are images)
Chunking Splits the text into overlapping chunks Cutting in the middle of a table or sentence
Embeddings Turns each chunk into a vector Mixing vectors from different models in the same index
Storage Keeps the vector, text and metadata Storing only the vector and losing the source
Search Finds the closest chunks, with filters Ignoring metadata filters (date, category, permission)
Reranking Reorders candidates by how well they answer the question Sending 50 chunks to the model "just in case"
Prompt Assembles instructions, context and question Prompts scattered as strings across the code
Generation Calls the model, streams, falls back to another one on failure Tying the code to one provider
Evaluation Checks whether the answer is right and came from the context Eyeballing it after every change
Observability Logs tokens, latency, chunks used and rating Finding out the cost from the invoice

Extraction is where you lose the most quality without noticing. In my app, it's a folder with one extractor per format (PDF, Word, PowerPoint, spreadsheet, ODT, image with OCR, plain text) and a quality checker that detects when a PDF came back nearly empty and sends it to OCR.

Chunking starts simple. The LangChain docs recommend starting with RecursiveCharacterTextSplitter, which tries to split by paragraph first, then by line, then by word. My app uses 1,000-character chunks with 200 of overlap, and I only changed that after measuring.

Embeddings have one unforgiving rule: every vector in an index comes from the same model, with the same dimension. Switching models means reindexing everything. OpenAI's text-embedding-3-small produces 1,536 dimensions and accepts a dimensions parameter to shorten the vector when storage cost matters.

Storage keeps, next to the vector, the chunk text, the source document, the position and the metadata the search will filter on. Without that, the answer can't cite its source.

Animation of a search funnel: thousands of chunks in the database, a metadata filter leaves hundreds, vector search leaves 20 candidates, reranking leaves 5, and only those go into the prompt
Each step cuts more. The model only sees what's left at the end, and that's what it uses to answer.

Search almost always combines vectors with filters. My app filters by category and date before the vector search, using the São Paulo time zone, because "yesterday's documents" depends on where yesterday is. Hybrid searchCombining exact keyword search with meaning-based search (embeddings), getting the best of both to find names, codes and similar ideas. (keyword and vector together, combined with Reciprocal Rank Fusion) is the next step when proper names and codes start getting lost.

Reranking takes the candidates and reorders them by how well they answer the question, with a rerank model like Cohere's. My app has a second layer: people's 👍 and 👎 adjust the order, using the Wilson lower bound, so a chunk with a single rating doesn't jump ahead of one with fifty.

Generation sits behind an interface. My app uses Groq by default and falls back to Gemini when streaming fails at startup; the rest of the code doesn't know which model answered.

The Folder Structure

A proposal in Python, which works the same in TypeScript with the names swapped:

text
rag-app/
├── app/
│   ├── api/              # HTTP routes: /ask (streaming), /documents
│   ├── config.py         # everything comes from environment variables
│   └── deps.py           # injection: which database, which model
├── ingestion/
│   ├── extract/          # one extractor per format + quality check
│   ├── chunk.py
│   ├── embed.py
│   └── worker.py         # consumes the document queue
├── retrieval/
│   ├── search.py         # filters + vector search (+ hybrid)
│   ├── rerank.py
│   └── context.py        # builds the context within the token limit
├── generation/
│   ├── prompts/          # versioned prompts, one file per prompt
│   ├── llm.py            # interface + providers + fallback
│   └── answer.py         # orchestrates search, prompt and generation
├── storage/
│   ├── vector_store.py   # interface
│   └── pgvector.py       # implementation
├── evaluation/
│   ├── dataset.jsonl     # real questions with expected answers
│   └── run_eval.py
├── observability/
│   └── tracing.py        # tokens, latency, chunks used
├── migrations/
└── tests/
Map of rag-app/ with three folder groups: indexing contains ingestion/; querying contains app/, retrieval/ and generation/; both use storage/, evaluation/, observability/ and tests/. Each folder shows its responsibility, illustrated with documents, a server, a database and evaluation and observability instruments.
The folder tells you which path the code belongs to. Whoever works on search doesn't need to open ingestion.

Three decisions in this tree that apply to any language:

  • storage/ with an interface. Search calls vector_store.search(...), not pgvector's SQL. Moving to Qdrant or Pinecone becomes a new implementation, not a rewrite. It's the ports and adapters idea applied to a single spot, without needing hexagonal architecture across the whole project.
  • prompts/ as files. A prompt is code: it changes behavior and needs review and history. Tools like Langfuse version prompts with labels (production, staging) so you can swap them without a deploy.
  • config.py reading from the environment. Model, dimension, chunk size, API key, all through variables. It's the third of the twelve factors, and in Python pydantic-settings validates it at startup.
Archive room in an old library, with a wooden card catalog of dozens of small drawers, one drawer open and a librarian's hand pulling out three cards at once
The card catalog only works because every card says where it came from. A chunk without metadata is a card without a label.

Which Vector Database

Option What it is When it makes sense
pgvector Postgres extension You already use Postgres; you want vectors and relational data in the same query
Chroma Open source vector database (Apache 2.0) Local prototype, quick to spin up
FAISS Library (MIT), not a database In-memory search inside your process
Qdrant Open source vector database Strong payload filters and hybrid search
Weaviate Open source vector database Schema and ready-made vectorization modules
Pinecone Managed service You don't want to run a database

My app uses pgvector with an HNSW index and cosine distance. One detail that tends to surprise people: in pgvector 0.8, the index accepts vectors up to 2,000 dimensions with the vector type and up to 4,000 with halfvec. A 3,072-dimension model needs halfvec or a shortened vector.

Evaluate and Observe from Day One

Without evaluation, every change is a guess. The minimum:

  1. A file with 20 to 50 real questions and the expected answer, taken from actual questions people asked.
  2. A script that runs them all and checks whether the answer is right and whether it's grounded in the context. Ragas has ready-made metrics for that, like faithfulness to the context and answer relevance.
  3. Run it before every change to chunking, model or prompt.

And in production, log per call the input and output tokens, latency, which chunks were used and the person's rating. My app stores the tokens along with the purpose of each call, and that's how I saw which feature was driving the bill. Langfuse does this as a service and can run on your own infrastructure (MIT license, except for the ee folder). The OpenTelemetry conventions for generative AI exist, but they're still in development.

Cartoon of a developer nearly buried under a giant roll of continuous paper that comes out of the computer and winds around the room, while a coworker at the door offers a small organizer box with dividers
Single-file RAG works until the first change. After that, every request unrolls more paper.

Security: The Document Can Lie Too

The 2025 OWASP Top 10 for LLMAI model trained on large amounts of text to predict the next word, which lets it chat, summarize, translate and write code. Applications has two items that hit RAG directly: prompt injection (LLM01), because an indexed document can carry hidden instructions, and vector and embedding weaknesses (LLM08), which includes leaks between users when search doesn't filter by permission. In practice: filter by who can see the document before the search, not after, and treat retrieved text as data, never as instructions.

Free Resources to Go Further

Resource What it has
LlamaIndex docs: Ingestion Pipeline Ingestion pipeline with caching and duplicate handling
LangChain docs: text splitters and RAG Full RAG tutorial and splitting strategies
pgvector on GitHub Indexes, vector types, limits and query examples
Ragas Metrics and eval set generation
Anthropic: Contextual Retrieval How to add context to chunks before indexing, with measured numbers
DeepLearning.AI: Retrieval Augmented Generation Full course; the first module is free

Anthropic's September 2024 article on Contextual Retrieval is the best example of why you measure: the retrieval failure rate dropped from 5.7% to 3.7% with contextual embeddings, to 2.9% adding BM25, and to 1.9% with reranking. A 67% improvement, with each step measured on the same set.

Frequently Asked Questions

How do you organize a RAG project?

Separate indexing from querying, and split each into modules with one job: extraction, chunking, embeddings and storage on one side; search, reranking, prompt and generation on the other. Evaluation and observability wrap around both.

Which vector database should I use for RAG?

If you already use Postgres, pgvector is usually enough and lets you filter vectors and relational data in the same query. Chroma works for local prototypes; Qdrant and Weaviate when filtered search matters a lot; Pinecone when you don't want to run a database.

What's the ideal chunk size?

There's no universal value. A common starting point is around 1,000 characters with 10% to 20% overlap, splitting by paragraph first. The right value comes from your eval set.

Can I switch the embedding model later?

Yes, but you have to reindex every document, because vectors from different models can't be compared. Keep the original chunk text so you don't have to extract everything again.

How do you evaluate a RAG system?

With a fixed set of real questions and expected answers, run on every change. Check whether the answer is correct and whether it's grounded in the retrieved context. Ragas has ready-made metrics for that.

References

Source: https://ramongomessilva.com.br/blog/rag-project-structure · Accessed on December 02, 2026

Share Share on LinkedIn Share on X
Cite this article

Ready-made reference, with today as the access date.

ABNT

Brazilian standard (NBR 6023). Use it in theses and academic papers submitted in Brazil.

GOMES, Ramon. RAG project structure: folders, modules and the path from indexing to answer. Ramon Gomes, 22 nov. 2026. Disponível em: https://ramongomessilva.com.br/blog/rag-project-structure. Acesso em: 2 dez. 2026.

APA

American Psychological Association style. Common in scientific papers and journals, especially in the social, behavioral and health sciences.

Gomes, R. (2026, November 22). RAG project structure: folders, modules and the path from indexing to answer. Ramon Gomes. https://ramongomessilva.com.br/blog/rag-project-structure

BibTeX

Format for LaTeX users (Overleaf, for example). Paste it into your .bib file or import it into Zotero or Mendeley.

@online{gomes2026ragprojectstructure,
  author = {Gomes, Ramon},
  title = {{RAG project structure: folders, modules and the path from indexing to answer}},
  organization = {Ramon Gomes},
  year = {2026},
  month = nov,
  date = {2026-11-22},
  url = {https://ramongomessilva.com.br/blog/rag-project-structure},
  urldate = {2026-12-02}
}
Found a mistake?

Wrong fact, broken link, outdated information: tell me and I will fix it.

10 to 2,000 characters. If you can, point to the right source.

Only so I can reply. It never shows on any page of the site.

Written by

Ramon Gomes

Software Engineer

Full stack software engineer. I like taking a messy problem, listening to the people who live with it and shipping something that holds up day to day. These days I split my time between my own products, applied AI and client work.

Available for projects

Need Something Like This Built?

I build websites, systems, apps and AI automations, from design to deploy. Tell me what you need or see what I offer.

Related Articles