RAG Pipeline, How Retrieval and Generation Turn Your Documents Into Answers

Diagram of the 67 percent fall in top-20 retrieval failures when contextual retrieval and reranking are added, from 5.7 percent down to 1.9 percent

A support agent opens the Monday queue. A customer asks for the refund deadline on an order placed 14 months ago. The chatbot answers in one smooth paragraph, names a policy page, and gets the deadline wrong by 30 days. The policy changed in March. The model never saw the change.

That is the exact failure this system is built to fix. What follows is the full working picture. How the two parts fit, what each stage costs, how to measure whether answers got better, and the mistakes that sink most first builds.

A rag pipeline is a system that searches your own documents for passages that answer a question, adds those passages to the prompt, and lets a language model write an answer grounded in your data. It has two parts, an indexing path that prepares documents ahead of time and a query path that retrieves and generates on each question.

If you would rather have this built and run as a service, let us discuss your project. Write to sales@denebly.com or call +1 (214) 896-2906.

What a retrieval pipeline is, and what it is not

It is one system with two jobs. First it finds passages in your documents that speak to the question. Then it hands those passages to a language model so the answer is built from your data. The model still writes the words. The documents supply the facts.

What people think it isWhat it actually is
A search box with a chatbot on topSearch plus generation, with the retrieved passages inside the prompt
Fine tuning by another nameNo weights change, the model reads your documents at query time
Semantic search on its ownRetrieval plus generation, the model writes an answer from what was found
A bigger model with a longer memoryThe same model, with fresh facts supplied per question
Prompt engineering with cleverer wordingThe prompt is assembled from retrieved passages; the gain comes from the facts supplied, not the phrasing

The name comes from a 2020 paper by Patrick Lewis and colleagues, presented at NeurIPS 2020. The paper gave the method its name, retrieval-augmented generation. Since then the shape has stayed the same while the parts inside have changed.

The test that matters is simple. Ask a question whose answer changed after the model was trained. If the answer uses the new fact, the system works. If it quotes the old fact, retrieval failed or the index is stale.

The two paths, indexing and query time

Every working system has two paths that never share a schedule. The indexing path runs when documents change. The query path runs when a user asks a question. Mix them and a re-index takes search offline.

StageTimeNote
Embed the query120 msOne call, same model as the chunks
Vector search180 msTop 50 by cosine similarity
Keyword search60 msTop 50 by BM25, runs beside the vector search
Fuse the two lists15 msReciprocal rank fusion, constant 60
Rerank the top 5090 msCross-encoder, keeps the top 5
Generate the answer1,800 msLargest share, set by the model and the reply length
Total2,265 msUnder the 3 second target

The total latency is 2,265 ms, inside the 3 second target that Datarmatics sets for the query path. Generation takes the largest share at 1,800 ms, so a faster model moves the total more than a faster index.

Ingestion and extraction, where bad answers start

Ingestion turns raw files into clean text. PDFs, HTML pages, wiki exports, ticket exports and database rows all arrive in different shapes. Each format needs its own parser, and the parser decides how much of the document survives.

Source typeCheck before indexingFailure if skipped
PDF manualsText extracts in reading order, tables kept wholeSteps arrive out of order
HTML help pagesNavigation and footer text strippedMenus pollute every chunk
Support ticketsPersonal data removed, resolution keptPrivate data leaks into answers
Database exportsOne row becomes one readable sentenceNumbers lose their labels

Metadata is carried with every chunk. Document title, section heading, page number, last changed date and who may read it. A chunk without its source title cannot be cited, and a chunk without permission data cannot be filtered.

Diagram of the six steps one question takes, load, chunk, embed, store, retrieve, generate

Chunking, the size decision that decides retrieval quality

Chunking splits clean text into passages small enough to embed and retrieve. The size is a trade. Small chunks retrieve precisely but lose setting. Large chunks keep setting but dilute the match with extra text.

The common default is 512 tokens with 10 to 20 percent overlap, from the Datarmatics guide. Technical documentation often does better at 256 tokens. Narrative content such as policies and reports often does better at 1,024 tokens. Test both on your own questions before you lock the size.

Here is the arithmetic on a real support corpus. Take 10,000 documents at 1,200 tokens each. That is 12 million tokens. At 512 tokens per chunk the corpus becomes 23,438 chunks. Each chunk carries about 50 to 100 tokens of overlap with its neighbour, so the true count runs a little higher.

Document typeChunk sizeWhy
API reference256 tokensOne function per chunk, exact names match
Support articles512 tokensOne procedure per chunk, the default
Policy documents1,024 tokensClauses need the surrounding text
Meeting notes512 tokensOne decision per chunk, names kept in the text

Two rules hold at any size. Never split a table across chunks, and keep each heading with its text. A chunk that starts mid-sentence answers neither half well.

Anthropic added a stronger step in September 2024. Contextual retrieval writes 50 to 100 tokens that place each chunk in its document, then prepends that text before embedding, which produces contextual embeddings instead of bare ones. The cost is 1.02 dollars per million document tokens with prompt caching. On Anthropic’s own test sets it cut top-20 retrieval failures from 5.7 percent to 3.7 percent on its own, to 2.9 percent with contextual BM25, and to 1.9 percent with reranking added. Those are Anthropic numbers on its own test sets, not a promise for your corpus.

Embeddings and the vector store

An embedding turns a chunk of text into a list of numbers that captures what the text means. Chunks with close meanings get close numbers. The query is embedded with the same model, and the store returns the chunks whose numbers sit nearest to the query, nearest measured by cosine similarity.

Use one embedding model for documents and queries. Two models means two different number systems, and the search will miss. OpenAI text-embedding-3-small returns 1,536 dimensions per chunk at 0.02 dollars per million tokens. The large model, text-embedding-3-large, returns 3,072 dimensions at 0.13 dollars per million tokens.

The vector database holds the numbers with their text and metadata. Pinecone, Weaviate, Qdrant, Chroma and pgvector all do this job. FAISS and Milvus cover the self-hosted side. The choice turns on scale and on whether a team already runs PostgreSQL. Most of these stores index the vectors with HNSW, a graph index that walks a small neighbourhood of linked vectors instead of scanning every vector, which is what keeps a search fast at scale.

Corpus sizePickWhy
Under 10,000 documentsIn-memory FAISS or plain similarity searchNo server to run, fast to start
Under 100,000 vectorsQdrant or ChromaDBSmall ops load, easy to run
On PostgreSQL alreadypgvectorNo new database, filters in SQL
Production at scalePinecone or WeaviateManaged ops, filters and scale

Storage arithmetic keeps the bill honest. Our worked corpus has 23,438 chunks at 1,536 dimensions each, four bytes per dimension, which is about 144 MB. At 0.33 dollars per GB per month the storage line is 0.05 dollars a month. The vectors are the cheap part. The model calls are not.

One limit to respect. A model such as e5-large-v2 takes at most 512 tokens per input, so a chunk longer than that is cut silently. Size the chunks to the model, not the other way round.

Retrieval, from one similarity search to a fused ranking

Retrieval starts with the query embedding and returns the top-k chunks. Pure vector search misses exact strings, so production systems add a keyword leg and fuse the two lists. Our hybrid search guide works the full fusion arithmetic.

The merge uses reciprocal rank fusion. Each document scores 1 divided by 60 plus its rank in each list, and the scores are added. The constant 60 comes from the 2009 paper by Cormack, Clarke and Buettcher.

DocumentKeyword rankVector rankFused score
A, refund policy page120.032522
C, returns FAQ310.032266
B, order 8814 shipping notice240.031754
E, loyalty program terms530.031258
D, warranty terms450.031010

Doc A wins with 1 divided by 61 plus 1 divided by 62, which is 0.016393 plus 0.016129, giving 0.032522. Doc C is second at 0.032266. The policy page won the keyword list, the FAQ won the vector list, and the page liked by both legs takes the top spot.

The funnel after fusion is where quality is won. Take the top 50 fused candidates into a cross-encoder reranker and keep the top 5 to 8 for the prompt. Datarmatics puts the gain at 10 to 30 percent precision for under 100 ms of latency. Skip the reranker and the prompt fills with near-duplicates.

Artwork of a support desk at night with data chips showing the default chunk size, the rerank window and the contextual pass cost

Prompt assembly and generation

The prompt has four parts in a fixed order. A system prompt that sets the rules, the retrieved chunks with their source labels, the user question unchanged, and a short instruction on format. Temperature stays low, 0 to 0.3, for factual questions.

Copy this system prompt. Answer only from the context below. Cite the source of each fact by its label. If the context does not hold the answer, say you do not have enough information. Do not guess.

Citations are the point of the whole system. Each chunk carries its source label, document title, section and page, so the answer can name where each fact came from. A claim without a source label is a claim the reader cannot check.

The refusal rule is the trust rule. When the retrieved chunks do not hold the answer, the model must say so. A made-up deadline with a citation to the wrong page is worse than no answer, because it looks checked. Our structured outputs guide shows how typed fields make source labels and refusal checks easier to enforce.

Here is the rule working. A customer asks for the refund deadline on a plan that was retired in March. The retrieved chunks cover only current plans. The answer comes back short, along the lines of, the documents I can see do not cover that plan, so I cannot give its deadline. No guessed date, and no date borrowed from a similar plan.

Generation settings stay plain. Temperature 0 to 0.3, streaming on for user-facing chat, and the model’s native structured output mode when the reply must be JSON or a table.

Retrieval against fine tuning, and when to use each

Fine tuning changes the model weights. Retrieval leaves the weights alone and supplies facts per question. The two solve different problems, and most production systems use both, RAG for knowledge and fine tuning for tone and format.

SituationWinnerWhy
Facts change weeklyRetrievalNew documents index without retraining
Answers need citationsRetrievalEach fact traces to a source chunk
Tone must stay fixedFine tuningBehaviour is baked into the weights
No source documents existFine tuningThere is nothing to retrieve
One narrow task, stable factsFine tuningSmall model, fast replies
Mixed needs, facts plus toneBothRetrieval for knowledge, tuning for behaviour

Cost decides many ties. Fine tuning a model costs real money up front and must be repeated when the facts change. Retrieval costs pennies per document and updates with a re-index. A team that retrains monthly for changing facts is paying to solve a retrieval problem with training.

The boundary to keep in mind. Retrieval cannot teach a model a skill, and fine tuning cannot supply a fact the model never saw. Pick the tool by what is missing, knowledge or behaviour.

What it costs to run for a small business

The vector side of the bill is small. Embedding is measured in cents, storage in cents, and the monthly minimum is usually the number that decides the invoice.

Line itemArithmeticAmount
Embedding, one time12 million tokens at 0.02 dollars per million0.24 dollars
Contextual pass, one time12 million tokens at 1.02 dollars per million12.24 dollars
Storage, monthlyAbout 144 MB at 0.33 dollars per GB0.05 dollars
Reads, monthly100,000 queries at 0.3 read units, at 16 dollars per million0.48 dollars
Metered monthly totalStorage plus reads0.53 dollars
Bill on the Standard plan50 dollar monthly minimum applies50 dollars

The lesson is in the last two rows. The metered cost is 0.53 dollars a month, but the Pinecone Standard plan bills a 50 dollar minimum, so 50 dollars is what you pay. At this size the free Starter tier covers the same load at zero, up to 2 GB of storage and 1 million reads a month.

Generation is billed apart from this table, per the model provider price page, and it dwarfs the retrieval bill at volume. Price the 100,000 query month with 2,000 tokens of context per reply first. Check the price on the day you buy.

If the numbers above look small enough to try, let us discuss your project. Write to sales@denebly.com or call +1 (214) 896-2906.

Measuring quality with RAGAS scores

Measure on real questions with known good answers. Four scores cover the system. Faithfulness checks the answer against the retrieved text. Context precision checks whether the retrieved chunks were relevant. Context recall checks whether all needed facts were retrieved. Answer relevancy checks whether the reply addressed the question.

MetricTargetWhat it measures
FaithfulnessAbove 0.90The answer stays inside the retrieved text
Context precisionAbove 0.80Retrieved chunks are relevant
Context recallAbove 0.75All needed facts were retrieved
Answer relevancyAbove 0.85The reply addresses the question

Build the evaluation set before you tune anything. Collect 50 to 100 real questions with known good answers and the documents that hold them. Run the set on every change, a new chunk size, a new embedding model, a new corpus version. A drop in faithfulness before launch is cheaper than a drop found by users.

When a bad answer lands, the trace tells you which half failed. Log the retrieval scores, the reranker output, the token counts and the latency per stage for every query. If the right chunk never reached the prompt, fix retrieval. If the chunk was there and the answer still went wrong, fix the prompt or the model.

RAGAS, DeepEval and TruLens all track these four scores. Pick one and stay with it, because scores only compare across releases when the tool and the question set stay fixed.

The build plan, from first document to first live answer

A working setup takes 1 to 2 weeks for a prototype and 6 to 10 weeks for a production system with hybrid retrieval, reranking, evaluation and observability, per the Datarmatics guide. The steps below are in order.

  1. Audit the sources and pick the first 500 documents. Output – a source list with a named owner per source.
  2. Parse and clean the text, keeping headings, tables and metadata. Output – 10 documents read by a person, end to end.
  3. Chunk at 512 tokens with 10 to 20 percent overlap and embed the chunks. Output – 23,438 chunks for the worked corpus, each with its source label.
  4. Store the vectors and build the keyword index on the same chunks. Output – a search that answers a pasted order number.
  5. Wire the retrieval with LangChain, hybrid search fused with RRF at constant 60, rerank top 50 to top 5. Output – one merged ranking for a test question.
  6. Write the system prompt with the refusal rule and citation labels. Output – a reply that cites its sources or refuses.
  7. Freeze the evaluation set, 50 labelled questions with known good answers, and record the four RAGAS scores as the launch baseline. Output – a one-page table with the four numbers.

LangChain is the wiring used in step 5, not the only choice. LlamaIndex fits teams whose work starts from documents and indexing, and Haystack fits teams that want an explicit pipeline of named nodes. The seven steps stay the same whichever framework holds them.

Go live only when the checklist is all true. Sources audited, 10 documents read by a person, chunks sized to the model limit, filters that block drafts and private data, RAGAS scores recorded, a reranker decision written down, and a rollback copy of the previous index kept.

If you want the build and the first month of tuning handled for you, let us discuss your project. Write to sales@denebly.com or call +1 (214) 896-2906.

Mistakes that break answer quality

Most failed builds share the same mistakes. Stale indexes, bad chunks, two models, missing filters, trusted retrieved text, no measurement, and an untested retrieval window.

  1. A stale index. Prices and policies change and the old chunk still answers. Fix – incremental refresh on every source change, deletes included.
  2. Chunks cut in the wrong place. A procedure split in half answers neither half. Fix – keep headings with text and procedures whole.
  3. Two embedding models. Documents embedded with one model and queries with another never meet. Fix – one model on both sides, checked in the deploy script.
  4. No filters. Relevance ranking cannot express permission or publication state. Fix – typed metadata fields and hard filters before fusion.
  5. Retrieved text treated as safe. Anyone who can write into an indexed document can write instructions aimed at the model. Fix – treat untrusted retrieved text as data, never as instructions, and strip instruction-like lines at ingestion.
  6. Never measuring. Teams ship the merge, feel good about it, and never learn it made things worse. Fix – one score table per release, kept beside the deploy log, faithfulness first, so a drop shows in the week it happens.
  7. A default top-k left untested. The library default window was never chosen for your corpus. Too narrow and the right chunk ranks just outside it, too wide and the prompt fills with near-duplicates. Fix – test top-k at 20, 50 and 100 on the evaluation set and keep the window with the best context precision.

Who should build one, and who should skip it

It fits teams whose answers live in documents that change. Support teams, internal help desks, sales teams answering product questions, and any firm whose policy pages move faster than model training.

The shape that pays is a corpus of at least a few hundred documents. A RAG system earns its keep when the same questions arrive daily and the answers sit in files no one person holds in memory.

Skip it when the questions have no documents behind them. General knowledge, opinion, and creative writing need no retrieval. Skip it too when the corpus is tiny or frozen. A 40-page handbook that never changes is better served by pasting it into the prompt. A frozen corpus does not need a vector database behind it, and a pure tone problem does not need retrieval at all, it needs fine tuning.

How Denebly builds it

Denebly builds retrieval as one connected system. The work starts with your documents and your questions.

The deliverables are fixed before work starts. The audited source list, the chunking rules, the embedding model choice, the fusion and reranker configuration, the system prompt with its refusal rule, and the 30-day numbers, the four RAGAS scores on your own 50 questions, before and after.

The rule to work by

Count the documents, chunk one of them by hand, and test the prototype on your hardest real questions before you buy anything.

If you would rather hand the build and the first month of tuning to a team, write to sales@denebly.com or call +1 (214) 896-2906 and ask for a retrieval build. We start with your documents and your questions.

Frequently asked questions

What is a rag pipeline

It is a system that pairs a search step with a language model. The search step pulls passages from your documents, and the model writes the answer from those passages. It exists for questions whose answers live in your files and change after the model was trained.

How is it different from fine tuning

Fine tuning retrains the model weights on your data, which suits stable behaviour such as tone and format. Retrieval leaves the weights alone and supplies facts at query time, which suits facts that change. Most production systems use both, one for behaviour and one for knowledge.

What chunk size should I start with

Start at 512 tokens with 10 to 20 percent overlap. Move to 256 tokens for technical reference material and to 1,024 tokens for policies and reports. Test each size on your own 50 questions and keep the size with the best faithfulness score.

Do I need a vector database

For a prototype under 10,000 documents, no, an in-memory search works. For production you need one, for persistence, concurrent access, metadata filters and incremental updates. The operational cost of running a custom search at scale is usually higher than a managed store.

How much does it cost to run each month

On the worked month in this article, the metered retrieval cost is 0.53 dollars a month, but the Pinecone Standard plan bills a 50 dollar monthly minimum, so 50 dollars is the bill. Generation is billed apart and is the larger line at volume.

How do I know if the answers are getting better

Run the same 50 labelled questions after every change and watch faithfulness first, with a target above 0.90. If faithfulness rises and context recall holds above 0.75, the change helped. If faithfulness falls, roll the change back.

Sources

  • Anthropic, Introducing Contextual Retrieval, September 2024, read 28 November 2026.
  • Lewis and colleagues, Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks, NeurIPS 2020, arXiv 2005.11401, read 28 November 2026.
  • OpenAI embedding rates, verified 28 November 2026 through four independent pricing reports checked against each other.
  • Pinecone serverless rates and plan minimums, from the Pinecone pricing page as reported by EmbeddingCost and BudgetForge, read 27 November 2026.
Arslan Mushtaq, Founder of Denebly

WRITTEN BY

Arslan Mushtaq

Founder, Denebly

Arslan founded Denebly in 2018 and leads its AI development work for startups and mid-size businesses, across AI chatbots, agentic workflows, RAG systems, machine learning and automation. Denebly has delivered 100+ projects from Dallas, Texas.

Connect on LinkedIn More about Arslan

Ready to Solve Your Business Problems With AI?

Tell us what you are trying to build, automate or fix. You will get an honest assessment within one business day, not a sales pitch.

Custom AI development for startups and growing businesses. Chatbots, agents, machine learning and automation that deliver measurable results.

sales@denebly.com
Dallas, Texas, USA

Get Started Free Consultation AI Readiness Audit Pricing Response within 24 hours You own the code & data