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

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.
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:
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/Three decisions in this tree that apply to any language:
storage/with an interface. Search callsvector_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.pyreading from the environment. Model, dimension, chunk size, API key, all through variables. It's the third of the twelve factors, and in Pythonpydantic-settingsvalidates it at startup.

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:
- A file with 20 to 50 real questions and the expected answer, taken from actual questions people asked.
- 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.
- 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.

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
- LangChain, Build a RAG App and Text splitters, accessed in 2026; LlamaIndex, Ingestion Pipeline.
- pgvector, version 0.8; Chroma, FAISS, Qdrant, Weaviate and Pinecone, accessed in 2026.
- OpenAI, Embeddings; Cohere, Rerank.
- Anthropic, Introducing Contextual Retrieval, 2024.
- Gordon Cormack, Charles Clarke and Stefan Büttcher, Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods, SIGIR 2009.
- Nelson Liu et al., Lost in the Middle: How Language Models Use Long Contexts, 2023.
- Ragas, version 0.4; Langfuse; OpenTelemetry, semantic conventions for generative AI.
- OWASP, Top 10 for LLM Applications 2025.
- The Twelve-Factor App: Config; Pydantic, Settings Management.