Dify RAG Recipes: Production RAG Pipelines with Chunking, Hybrid Search, Reranking, Citations and Evaluation
Production-minded RAG (retrieval-augmented generation) recipes for engineers who have a demo working and now need it to be accurate, cheap and debuggable. Covers document chunking strategies, hybrid search (BM25 + vector), reciprocal rank fusion, reranking, grounded answers with citations, and RAG evaluation, with small dependency-free Python reference code (ragkit/) and SQL you can paste into Postgres + pgvector.
It is framework-neutral: the ideas apply whether you build in Dify (see Applying the recipes in Dify), LlamaIndex, LangChain, Haystack, a managed vector database or hand-rolled code. This is an independent guide, not Dify documentation.
Last reviewed: December 2026. Model names, prices and library APIs change quickly; this guide describes techniques and points to official docs for the specifics.
Table of Contents
- Quick start
- The pipeline at a glance
- Recipe 0: Build an evaluation set first
- Recipe 1: Parsing and cleaning documents
- Recipe 2: Chunking strategies
- Recipe 3: Metadata and contextual chunk headers
- Recipe 4: Embeddings and vector indexes
- Recipe 5: Hybrid search with BM25 and vectors
- Recipe 6: Hybrid search in Postgres with pgvector
- Recipe 7: Query transformation
- Recipe 8: Reranking
- Recipe 9: Diversity with MMR
- Recipe 10: Context assembly and prompt
- Recipe 11: Citations you can verify
- Recipe 12: Evaluating retrieval
- Recipe 13: Evaluating answers
- Recipe 14: Freshness, updates and deletes
- Recipe 15: Access control
- Recipe 16: Latency and cost
- Applying the recipes in Dify
- Debugging checklist
- Best picks by situation
- Common anti-patterns
- FAQ
- Where to go next
- Tools and further reading
- Repository layout
- Contributing
- License
- More free resources
Quick start
No installs needed; Python 3.9+ standard library only.
git clone https://github.com/Ralpberry-Labs/dify-rag-recipes.git
cd dify-rag-recipes
python3 -m unittest discover -s tests -t .
python3 examples/hybrid_demo.py "how do I combine keyword and vector search"
from ragkit import BM25, markdown_chunks, reciprocal_rank_fusion, build_context, check_citations
chunks = markdown_chunks(open("handbook.md").read(), max_len=2000, source="handbook.md")
bm25 = BM25([c.text for c in chunks])
keyword_ids = [i for i, _ in bm25.search("refund policy for annual plans", k=20)]
vector_ids = my_vector_search("refund policy for annual plans", k=20) # your vector DB
top = [i for i, _ in reciprocal_rank_fusion([keyword_ids, vector_ids])][:8]
ragkit is a teaching and testing reference. It is intentionally small and readable; for large corpora use a search engine or database for BM25 and vectors and keep the same logic around it.
The pipeline at a glance
INGEST (offline) QUERY (online)
----------------- -----------------------------
sources ─► parse ─► clean ─► chunk ─► enrich question
│ │
▼ ▼
embed + index (vector) rewrite / expand (optional)
index (keyword / BM25) │
│ ┌──────┴───────┐
└──────────►│ keyword vec │ retrieve top 20-100 each
└──────┬───────┘
▼
fuse (RRF) ─► filter (ACL, date)
▼
rerank ─► top 5-10 ─► MMR (optional)
▼
assemble context with source ids
▼
generate answer with citations
▼
verify citations ─► respond / abstain
Where quality is usually lost, in rough order of how often we see it:
- Bad parsing (tables flattened, headers and footers repeated, text missing from scans).
- Chunks that separate a fact from what it refers to (“It costs $40” with no product name).
- Pure vector search missing exact terms (SKU, error code, person’s name).
- Too few candidates before reranking, or no reranking.
- Prompt that lets the model answer from its own memory.
- No evaluation set, so changes are judged by vibes.
Recipe 0: Build an evaluation set first
Before tuning anything, collect 50 to 200 real questions with the passages that answer them. Without this, every change below is guesswork.
How to build it in a day:
- Pull real questions from support tickets, chat logs or search logs. Real phrasing matters; synthetic questions are too clean.
- For each, record the document and section that answers it (
relevantids) and a short reference answer. - Include hard cases on purpose:
- questions needing an exact identifier (error codes, plan names);
- questions whose answer spans two sections;
- questions with no answer in the corpus (the correct behavior is to abstain);
- questions with outdated answers in old docs.
- Store it as JSONL:
{"id": "q017", "question": "Can I get a refund on an annual plan after 30 days?", "relevant": ["billing.md#refunds"], "answer": "No, annual plans are refundable within 30 days only.", "tags": ["billing", "exact-term"]}
{"id": "q018", "question": "Do you support SAML login on the starter plan?", "relevant": [], "answer": null, "tags": ["unanswerable"]}
Synthetic expansion is fine after you have real questions: ask an LLM to write questions for random chunks, then hand-check a sample. Keep synthetic and real questions tagged separately and report both.
Recipe 1: Parsing and cleaning documents
Garbage in, garbage retrieved. Spend real time here.
| Source | Common problem | Fix |
|---|---|---|
| HTML pages | Navigation, cookie banners, footers repeated in every chunk | Extract main content (readability-style extraction), drop nav, footer, aside |
| PDFs (digital) | Columns merged, headers and page numbers inside sentences | Layout-aware parser; strip repeated header/footer lines by frequency |
| PDFs (scanned) | No text layer | OCR, or a vision-capable model to transcribe pages |
| Tables | Flattened into meaningless number soup | Convert to Markdown tables or one row per line with column names repeated |
| Slides | Fragments without context | Keep slide title with each slide’s text; include speaker notes |
| Spreadsheets | Rows without headers | Serialize each row as column: value pairs |
| Code | Split mid-function | Split on function or class boundaries |
Cleaning rules that pay off:
- Normalize whitespace and Unicode (NFKC), fix hyphenation at line breaks (
infor-\nmation). - Remove boilerplate that appears in more than, say, 30% of pages of the same site.
- Keep structure as Markdown (headings, lists, tables). Markdown chunking (Recipe 2) relies on it.
- Store the cleaned text and a content hash; you will re-chunk many times without re-parsing.
Spot-check: print 20 random cleaned documents and read them. Ten minutes of reading catches problems that no metric will.
Recipe 2: Chunking strategies
A chunk is the unit you retrieve. It should be small enough to be specific and large enough to be self-contained.
| Strategy | How | Good for | Watch out for |
|---|---|---|---|
| Fixed size with overlap | Windows of N tokens, overlap 10 to 20% | Uniform prose, quick baseline | Cuts across sections and tables |
| Recursive | Split on paragraphs, then lines, then sentences, then words; merge up to N | General documents | Still ignores headings |
| Structure-aware (Markdown/HTML headings) | Split by section, sub-split long sections | Docs, wikis, manuals | Very short sections; merge them |
| Sentence window | Index single sentences, return neighbors at query time | Precise fact lookup | More vectors, more storage |
| Parent-child (small-to-big) | Retrieve small chunks, return their parent section | Precision of small + context of big | Two-level bookkeeping |
| Semantic | Split where embedding similarity between sentences drops | Long unstructured text | Extra embedding cost; gains vary |
| Per-record | One chunk per FAQ entry, ticket, product, row | Structured data | Very small records may need grouping |
Reference implementations in ragkit/chunking.py:
from ragkit import fixed_size_chunks, recursive_chunks, markdown_chunks
fixed_size_chunks(text, size=2000, overlap=200) # character windows, word-safe
recursive_chunks(text, max_len=2000) # paragraphs > lines > sentences > words
markdown_chunks(md, max_len=2000, source="faq.md") # heading path kept in metadata
Starting points (then tune with your evaluation set):
- Chunk size: 200 to 800 tokens for most prose. Smaller for FAQs and reference tables, larger for narrative text where meaning builds up.
- Overlap: 10 to 15% for fixed windows; usually unnecessary with structure-aware splitting.
- Tune by measuring recall@k (Recipe 12) for 3 or 4 sizes. Do not choose by intuition.
Anti-patterns:
- One chunk per PDF page. Page breaks are layout, not meaning.
- Chunks of 2,000+ tokens “so nothing is lost”. Retrieval gets vague, and you pay for irrelevant tokens on every query.
- Stripping headings. The heading is often the most informative line.
Recipe 3: Metadata and contextual chunk headers
A chunk saying “The limit is 10 per minute” is useless without knowing which limit. Fix it by prepending context before embedding and indexing:
Document: API Reference > Rate limits > Free plan
Updated: 2026-10-02
The limit is 10 requests per minute per API key...
Options, cheapest first:
- Heading path (free):
markdown_chunksstores it inmetadata["heading"]. - Document title and summary line (cheap): one LLM call per document, reused for all its chunks.
- Per-chunk contextual summary (more expensive): an LLM writes one or two sentences situating each chunk within its document, then that text is prepended before embedding and BM25 indexing. Anthropic described this approach as Contextual Retrieval and reported large reductions in retrieval failures when combined with BM25 and reranking. Prompt caching makes it much cheaper because the full document is reused across its chunks.
Also store filterable metadata on every chunk: source, url, doc_id, section, updated_at, language, product, version, access_label. Filters (Recipe 15) and freshness (Recipe 14) depend on it.
Recipe 4: Embeddings and vector indexes
Choosing an embedding model:
- Check the MTEB leaderboard for candidates, then test the top few on your own evaluation set. Leaderboard rank does not transfer perfectly to your domain.
- Match language coverage to your corpus (multilingual models for mixed-language docs).
- Consider dimension and storage: 1 million chunks × 1,024 dimensions × 4 bytes is about 4 GB of raw float32 vectors before index overhead.
- Some models expect different prefixes or task types for queries and documents. Read the model card and use them; it matters.
- Embed queries and documents with the same model and version. Changing models means re-embedding everything.
Index types:
| Index | Idea | Trade-off |
|---|---|---|
| Flat (exact) | Compare against every vector | Perfect recall, slow beyond ~1M vectors |
| HNSW | Navigable graph of neighbors | Fast and accurate, memory heavy; tune ef_search |
| IVF | Cluster vectors, search nearest clusters | Less memory, tune number of probes |
| Quantized (PQ, binary, int8) | Compress vectors | Much smaller, some recall loss; rescore with full vectors |
Normalize vectors if you use inner product as a cosine substitute. Pick the distance the model was trained for (usually cosine).
Recipe 5: Hybrid search with BM25 and vectors
Vector search understands paraphrase; keyword search nails exact terms. Run both and fuse. In most evaluations we have seen, hybrid retrieval beats either alone, and it is especially strong on queries with names, codes and numbers.
from ragkit import BM25, reciprocal_rank_fusion
bm25 = BM25(chunk_texts) # or your search engine's BM25
kw = [i for i, _ in bm25.search(q, k=50)]
vec = vector_db.search(embed(q), k=50) # ids, best first
fused = reciprocal_rank_fusion([kw, vec], k=60)[:20]
Reciprocal Rank Fusion (RRF), from Cormack, Clarke and Buettcher (SIGIR 2009):
score(d) = Σ_retrievers w_r / (k + rank_r(d)) k ≈ 60, ranks start at 1
Why RRF is the default:
- Uses ranks only, so BM25 scores (unbounded) and cosine similarities (bounded) never need calibrating.
- One parameter,
k, that rarely needs tuning. - Weights let you favor a retriever, for example
weights=[1.0, 1.5]to lean on vectors.
Alternative: weighted score fusion (ragkit.weighted_score_fusion) min-max normalizes each retriever’s scores and sums them with weights. It can beat RRF when scores are well behaved, but it is sensitive to outliers and to how many results you normalize over.
Practical settings:
- Retrieve 20 to 100 candidates per retriever, fuse, then rerank down to 5 to 10.
- Use the same text (including contextual headers) for both indexes.
- For BM25, a language-appropriate analyzer (stemming, stopwords) matters more than
k1andb.
Recipe 6: Hybrid search in Postgres with pgvector
One database, both retrievers, fused in SQL. Requires the pgvector extension and PostgreSQL 12+ (for generated columns).
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
doc_id text NOT NULL,
heading text,
content text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now(),
access_label text NOT NULL DEFAULT 'public',
embedding vector(1024), -- match your model's dimension
tsv tsvector GENERATED ALWAYS AS
(to_tsvector('english', coalesce(heading, '') || ' ' || content)) STORED
);
CREATE INDEX chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX chunks_tsv_gin ON chunks USING gin (tsv);
CREATE INDEX chunks_doc ON chunks (doc_id);
Hybrid query with RRF ($1 = query embedding, $2 = query text, $3 = allowed access labels):
WITH vector_hits AS (
SELECT id, row_number() OVER (ORDER BY embedding <=> $1) AS rank
FROM chunks
WHERE access_label = ANY($3)
ORDER BY embedding <=> $1
LIMIT 50
),
keyword_hits AS (
SELECT id, row_number() OVER (ORDER BY ts_rank_cd(tsv, query) DESC) AS rank
FROM chunks, websearch_to_tsquery('english', $2) AS query
WHERE tsv @@ query AND access_label = ANY($3)
ORDER BY ts_rank_cd(tsv, query) DESC
LIMIT 50
),
fused AS (
SELECT id, sum(1.0 / (60 + rank)) AS rrf
FROM (SELECT * FROM vector_hits UNION ALL SELECT * FROM keyword_hits) h
GROUP BY id
)
SELECT c.id, c.doc_id, c.heading, c.content, f.rrf
FROM fused f JOIN chunks c USING (id)
ORDER BY f.rrf DESC
LIMIT 20;
Notes:
<=>is cosine distance in pgvector (<->is L2,<#>is negative inner product). Use the operator class matching your index (vector_cosine_opshere).- Raise recall of the HNSW index per session with
SET hnsw.ef_search = 100;(the default is lower). Filtering withWHEREcan reduce how many rows the approximate search returns; check the pgvector README section on filtering and iterative scans for your version. ts_rank_cdis not BM25, but it is a reasonable lexical signal. If you need true BM25 inside Postgres, look at extensions that provide it, or use a search engine alongside.websearch_to_tsqueryaccepts user-style input ("exact phrase" -excluded or) without syntax errors.
Recipe 7: Query transformation
The user’s words are often not the document’s words. Transform the query, then retrieve.
| Technique | What it does | Use when |
|---|---|---|
| Rewrite | LLM turns a chatty question into a search query, resolving pronouns from chat history | Multi-turn chat (“what about the other plan?”) |
| Multi-query | Generate 3 to 5 paraphrases, retrieve for each, fuse with RRF | Vague or short questions |
| Decomposition | Split a compound question into sub-questions | “Compare X and Y on price and limits” |
| HyDE | Generate a hypothetical answer and embed that (Gao et al., 2022) | Short queries against long technical passages |
| Step-back | Ask a more general question first to fetch background | Reasoning-heavy domains |
| Filters from query | Extract product, version, date range into metadata filters |
Versioned docs, catalogs |
Rewrite prompt for chat:
Given the conversation and the latest user message, write one standalone search query
that contains every entity needed to find the answer (product names, plan names, versions).
Do not answer the question. Output the query only.
Keep the original query as one of the retrievals. Transformations sometimes drift; fusing original plus transformed is a safe default.
Recipe 8: Reranking
Retrievers are tuned for recall over millions of chunks. A reranker looks at the query and each candidate together and scores relevance much more precisely. It is usually the single biggest quality jump after hybrid search.
| Reranker type | Examples | Notes |
|---|---|---|
| Cross-encoder (open weights) | BAAI/bge-reranker-v2-m3, cross-encoder/ms-marco-MiniLM-L-6-v2 |
Run locally; small ones are fast on CPU for 20 to 50 candidates |
| Hosted rerank APIs | Offered by several providers (Cohere, Voyage AI, Jina AI and others) | Simple HTTP call; check data handling terms |
| Late interaction | ColBERT-style models (paper) | Token-level matching; can serve as retriever or reranker |
| LLM as reranker | Ask a model to score or order candidates | Flexible and slow; good for small candidate sets or offline labeling |
Example with a local cross-encoder (requires pip install sentence-transformers, not executed in this repo’s tests):
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
pairs = [(query, chunk_texts[i]) for i in candidate_ids]
scores = reranker.predict(pairs)
reranked = [i for _, i in sorted(zip(scores, candidate_ids), reverse=True)][:8]
Guidelines:
- Rerank 20 to 100 candidates. Fewer and the reranker cannot fix recall misses; more and latency climbs.
- Use the reranker score for a relevance threshold: if the best candidate scores below a tuned cut-off, abstain instead of answering from weak context.
- Rerank on the same enriched text you indexed (with headings).
Recipe 9: Diversity with MMR
When your corpus has near-duplicates (versions of the same page, copied FAQ answers), the top results can be five copies of one passage. Maximal Marginal Relevance picks results that are relevant and different from what is already picked:
MMR = argmax_d [ λ · sim(q, d) − (1 − λ) · max_{s ∈ selected} sim(d, s) ]
from ragkit import mmr
picked = mmr(query_vec, [vecs[i] for i in reranked], k=5, lambda_=0.7)
λ = 1is pure relevance;λ = 0.5to0.8is typical.- De-duplicate at ingest time too (exact hash and near-duplicate detection). MMR is a safety net, not a substitute.
Recipe 10: Context assembly and prompt
How you lay out the context changes answer quality.
- Order: put the most relevant chunks first. Research such as “Lost in the Middle” found models use information at the start and end of long contexts better than the middle. With 5 to 10 well-reranked chunks this matters less.
- Group by document and keep headings, so the model sees structure.
- Number every source so citations are checkable (Recipe 11).
- Budget tokens: stop adding chunks at a limit (
build_context(..., max_chars=...)). - Include dates and versions in the source header if answers can go stale.
from ragkit import build_context
context = build_context([
{"title": "Billing > Refunds", "url": "https://docs.example.com/billing#refunds", "text": "..."},
{"title": "Plans > Annual", "url": "https://docs.example.com/plans#annual", "text": "..."},
], max_chars=12000)
Grounded answer prompt:
You answer questions using only the numbered sources below.
Rules:
- Every sentence that states a fact must end with a citation like [1] or [2, 3].
- If the sources do not contain the answer, reply exactly: "I don't know based on the available documents."
- If sources disagree, say so and cite both. Prefer the most recently updated source.
- Do not use outside knowledge. Do not invent URLs.
Sources:
{context}
Question: {question}
Recipe 11: Citations you can verify
Citations are only useful if they are checked.
from ragkit import check_citations
report = check_citations(answer, num_sources=len(sources))
# {'cited': [1, 3], 'invalid': [], 'uncited_sentences': [...], 'unused_sources': [2], 'ok': False}
Policy options when the check fails:
| Failure | Action |
|---|---|
| Citation number out of range | Regenerate once; if still bad, strip the citation and flag |
| Sentences without citations | Regenerate with a reminder, or show the answer with a “partially sourced” badge |
| Answer cites nothing | Treat as ungrounded: abstain or fall back to showing the top sources |
Stronger verification (more cost): for each cited sentence, ask a small model “Does source [n] support this sentence? yes/no”. Use it in evaluation always, and in production for high-stakes domains.
Render citations as links to the exact section (url#anchor) and, where possible, highlight the quoted span. Users trust what they can click.
Recipe 12: Evaluating retrieval
Retrieval is measurable without any LLM. Do it first; answer quality cannot exceed retrieval quality.
| Metric | Question it answers | ragkit |
|---|---|---|
| Recall@k | Did the right chunks make it into the top k at all? | recall_at_k |
| Hit rate@k | Did at least one right chunk make it? | hit_rate |
| Precision@k | How much of the top k is relevant? | precision_at_k |
| MRR | How high is the first relevant result? | mrr |
| nDCG@k | Are the most relevant results ranked highest (graded relevance)? | ndcg_at_k |
Minimal evaluation loop:
import json
from statistics import mean
from ragkit import recall_at_k, mrr, ndcg_at_k
rows = [json.loads(l) for l in open("eval.jsonl")]
answerable = [r for r in rows if r["relevant"]]
results = {"recall@5": [], "recall@20": [], "mrr": [], "ndcg@10": []}
for r in answerable:
ids = retrieve(r["question"], k=20) # your pipeline: chunk ids, best first
rel = set(r["relevant"])
results["recall@5"].append(recall_at_k(ids, rel, 5))
results["recall@20"].append(recall_at_k(ids, rel, 20))
results["mrr"].append(mrr(ids, rel))
results["ndcg@10"].append(ndcg_at_k(ids, rel, 10))
print({k: round(mean(v), 3) for k, v in results.items()})
How to read the numbers:
- Recall@20 low → retrieval problem: parsing, chunking, embeddings, missing keyword search.
- Recall@20 high but Recall@5 low → ranking problem: add or improve reranking.
- Recall@5 high but answers wrong → generation problem: prompt, context layout, model.
Label relevance at the section or document level (for example billing.md#refunds) and map chunk ids to it, so re-chunking does not invalidate your labels.
Public benchmarks such as BEIR are useful for comparing methods in general; your own set decides for your data.
Recipe 13: Evaluating answers
Measure several properties separately:
| Property | Question | How to measure |
|---|---|---|
| Correctness | Does it match the reference answer? | LLM judge with the reference, or exact match for short facts |
| Faithfulness / groundedness | Is every claim supported by the retrieved context? | Claim extraction + support check per claim |
| Answer relevance | Does it address the question asked? | LLM judge |
| Citation accuracy | Do cited sources support their sentences? | Per-citation support check (Recipe 11) |
| Abstention | Does it say “I don’t know” for unanswerable questions, and only then? | Precision and recall of abstention on tagged questions |
LLM-as-judge tips:
- Give the judge a rubric with examples and ask for a short reason plus a label. Labels like
correct / partially_correct / incorrectare more stable than 1 to 10 scores. - Use a different or stronger model than the one generating, where practical.
- Calibrate: hand-label 50 answers, compare with the judge, and only trust the judge if agreement is high.
- Track metrics per tag (exact-term, multi-hop, unanswerable). Averages hide regressions.
Tooling (open source): Ragas (paper), DeepEval, promptfoo, TruLens. All can work with your own pipeline; check their docs for current metric names.
Run the evaluation in CI or before every release, and keep a results log so you can see trends over time.
Recipe 14: Freshness, updates and deletes
A RAG system that serves deleted or outdated content is worse than none.
- Stable ids:
chunk_id = hash(doc_id, chunk_index, content_hash). Re-ingesting unchanged content is then a no-op. - Document-level replace: when a document changes, delete all of its chunks and insert the new ones in one transaction (or with a version flag flip).
- Deletes propagate: listen for delete events or reconcile nightly (ids in source vs ids in index).
- Store
updated_atand show it in the source header; optionally boost recent documents or filter out superseded versions. - Re-embedding plan: when you change embedding models, build a new index in parallel, evaluate it, then switch reads. Never mix vectors from two models in one index.
Recipe 15: Access control
If not every user may see every document, enforce permissions in retrieval, not in the prompt.
- Store an
access_label(or a list of group ids) on every chunk at ingest. - At query time, resolve the user’s groups and filter the search (
WHERE access_label = ANY($groups)in Recipe 6, or the vector database’s metadata filter). - Filter before reranking and generation, so restricted text never reaches the model.
- Re-sync permissions when they change in the source system; stale ACLs leak data.
- Log which chunk ids were shown to which user for audits.
Prompt instructions like “do not reveal confidential documents” are not access control.
Recipe 16: Latency and cost
Typical budget for an interactive answer (varies widely by stack):
| Stage | Typical latency | Levers |
|---|---|---|
| Query rewrite | 0.2 to 1 s | Skip for single-turn queries; use a small model |
| Embedding the query | tens of ms | Cache embeddings of frequent queries |
| Keyword + vector search | tens of ms | Indexes, filters, fewer candidates |
| Reranking 50 candidates | 50 ms to 1 s | Smaller reranker, fewer candidates, GPU |
| Generation | 1 to 10 s | Stream tokens; fewer, better chunks; smaller model for easy questions |
Cost levers:
- Fewer, better chunks in the prompt is the biggest saving. Five reranked chunks often beat fifteen unreranked ones on both cost and quality.
- Prompt caching for stable system prompts and instructions.
- Semantic answer cache for very frequent questions, keyed by normalized query, invalidated when sources change.
- Route easy, short questions to a smaller model; measure on your evaluation set before and after.
Applying the recipes in Dify
Dify exposes many of these choices as knowledge base settings. A mapping, based on the Dify knowledge docs at the time of review (labels may move between versions):
| Recipe | Where it lives in Dify |
|---|---|
| Chunking (Recipe 2) | Knowledge > chunk settings: General mode (one chunk size, custom delimiter, overlap) or Parent-child mode (search small child chunks, return the parent). The chunk mode cannot be changed after the knowledge base is created, so test on a copy first |
| Cleaning (Recipe 1) | Text pre-processing rules in the same step (whitespace, URLs and emails); do heavier cleaning before upload |
| Embeddings (Recipe 4) | High Quality index method with an embedding model you configure. The Economical method uses only a keyword inverted index |
| Hybrid search (Recipes 5 and 6) | Retrieval setting Hybrid Search with Weight Settings to balance semantic and keyword results |
| Reranking (Recipe 8) | Rerank Model toggle in retrieval settings (needs a configured rerank provider) |
| Final candidate count and abstain threshold | TopK and Score Threshold |
| Citations (Recipe 11) | Enable citations and attributions in the app’s features, and keep the “cite your sources” rule in the prompt |
| Evaluation (Recipes 12 and 13) | Use the knowledge base’s retrieval testing page for spot checks, and run your JSONL evaluation set against the app’s API for real numbers |
Practical order in Dify: start with Parent-child chunking plus Hybrid Search, measure recall on your evaluation set through the API, then add a Rerank Model and tune TopK and Score Threshold.
Debugging checklist
When an answer is wrong, walk the pipeline in order and look at the actual data:
- Is the answer in the corpus? Search the raw documents by hand.
- Was it parsed correctly? Look at the cleaned text.
- Is it in one chunk with enough context? Print the chunk.
- Is that chunk in the top 50 from keyword search? From vector search?
- Did it survive fusion and reranking into the final context?
- Did the prompt allow outside knowledge, or bury the chunk in the middle of a long context?
- Did the model cite it? Did the citation check pass?
Log the intermediate ids at every stage for every query; this checklist becomes a single lookup.
Best picks by situation
| Situation | Pick | Why |
|---|---|---|
| Already run PostgreSQL, under ~10M chunks | pgvector + full-text search (Recipe 6) | One database, transactions, joins and ACL filters in SQL |
| Need managed, scalable vector search with filters | A managed vector database (Qdrant Cloud, Weaviate Cloud, Pinecone and others) | Operations handled; strong metadata filtering |
| Need true BM25 plus vectors in one engine | OpenSearch, Elasticsearch, Vespa, Weaviate or Qdrant hybrid modes | Native hybrid queries |
| Prototype on a laptop | Chroma or LanceDB, or ragkit + an in-memory index |
Zero infrastructure |
| Visual pipeline builder with knowledge bases | Dify | Chunking, hybrid search and reranking as settings (mapping) |
| Best quality per query, cost secondary | Hybrid + cross-encoder reranker + contextual chunk headers | The three biggest quality levers combined |
| Cheapest acceptable quality | BM25 + small embedding model + RRF, no reranker | Fast, cheap, surprisingly strong baseline |
| Many PDFs with tables | A layout-aware parser (Docling, Unstructured, Marker) before chunking | Parsing errors cannot be fixed downstream |
Common anti-patterns
| Anti-pattern | Why it hurts | Do instead |
|---|---|---|
| Tuning prompts before measuring retrieval | Generation cannot fix missing context | Measure Recall@k first (Recipe 12) |
| Top-k = 20 straight into the prompt | Cost, distraction, “lost in the middle” | Retrieve 50, rerank, keep 5 to 8 |
| One giant chunk size for all content | FAQs and manuals need different sizes | Per-source chunking settings |
| Vector-only search for product codes and names | Embeddings blur exact identifiers | Hybrid search |
| No metadata on chunks | No filters, no freshness, no citations | Store source, url, section, updated_at, access label |
| Re-embedding everything nightly | Wasted cost and index churn | Content hashes; re-embed only changed docs |
| Trusting an LLM judge blindly | Judges have biases and drift | Calibrate against human labels |
| Answering when retrieval is weak | Confident wrong answers | Reranker score threshold and an explicit abstain path |
| ACL rules in the prompt | Prompts are not security | Filter at query time (Recipe 15) |
FAQ
What is a RAG pipeline? Retrieval-augmented generation: for each question, search your documents for relevant passages, put them in the prompt, and have the model answer from them with citations. The pipeline covers ingestion (parse, chunk, embed, index) and query time (retrieve, rerank, assemble, generate, verify).
What chunk size should I use for RAG? Start around 300 to 800 tokens for prose and smaller for FAQs or reference tables, split on headings, then compare 3 or 4 sizes by Recall@k on your evaluation set. There is no universal best size.
Is hybrid search always better than vector search? Usually, especially for queries with names, codes and numbers. On purely conversational queries over well-written prose the gain can be small. Measure both; hybrid rarely hurts.
What is reciprocal rank fusion (RRF)?
A way to merge ranked lists from different retrievers using only ranks: each document scores the sum of 1 / (k + rank) across lists, with k around 60. It avoids calibrating incompatible scores.
Do I need a reranker? If quality matters, yes. A cross-encoder reranker over 20 to 100 candidates is typically the largest single improvement after hybrid search. Skip it only when latency or cost rules it out.
How do I evaluate a RAG system without labels? You can bootstrap with LLM-generated questions per chunk and an LLM judge for faithfulness, but calibrate against a small set of human-labeled questions before trusting the numbers.
How do I stop the model from making things up? Retrieve well, instruct it to answer only from sources and to say “I don’t know”, require citations, verify them in code, and abstain when the reranker’s top score is low.
Long context models are huge now; do I still need RAG? For small, static corpora you can sometimes put everything in context. RAG still wins on cost, latency, freshness, access control and citations for anything large or changing, and the two combine well (retrieve more, rerank less aggressively).
Which embedding model is best? Shortlist from the MTEB leaderboard by language, size and license, then test the top three on your own evaluation set. Use the same model for queries and documents.
pgvector or a dedicated vector database? pgvector is excellent when you already run Postgres and want joins, transactions and SQL filters. Dedicated engines offer more indexing options, native hybrid search and easier horizontal scaling. Both are valid; choose by operations, not hype.
Where to go next
- Run
python3 -m unittest discover -s testsand readragkit/end to end; it is about 400 lines. - Build your 50-question evaluation set (Recipe 0) before touching anything else.
- Try Recipe 6 on your own data and compare Recall@20 with and without the keyword half.
- Add a reranker and measure Recall@5 again.
- Read the Contextual Retrieval write-up and the RAGAS paper for evaluation ideas.
Tools and further reading
Frameworks and platforms
- LlamaIndex: data framework for indexing and retrieval pipelines.
- LangChain: components for chains, retrievers and agents.
- Haystack: pipeline framework for search and RAG.
- Dify: open-source LLM app platform with visual RAG pipelines.
Vector and hybrid search engines
- pgvector (PostgreSQL extension)
- Qdrant
- Weaviate
- Milvus
- Chroma
- LanceDB
- OpenSearch and Elasticsearch (BM25 plus vector search)
- Vespa
Document parsing
- Docling: layout-aware conversion of PDFs and Office files to Markdown or JSON.
- Unstructured: partitions many document types into typed elements.
- Marker: PDF to Markdown with table and equation handling.
- MarkItDown: lightweight conversion of many formats to Markdown.
Embeddings and rerankers (libraries)
- sentence-transformers: embedding and cross-encoder models in Python.
- FlagEmbedding: the BGE embedding and reranker families.
End-to-end RAG engines
- RAGFlow: open-source RAG engine with deep document understanding.
- GraphRAG: knowledge-graph-based retrieval for questions across a whole corpus.
Papers and articles
- Lewis et al., 2020. Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks.
- Cormack, Clarke and Buettcher, 2009. Reciprocal Rank Fusion outperforms Condorcet and individual rank learning methods. SIGIR.
- Gao et al., 2022. Precise Zero-Shot Dense Retrieval without Relevance Labels (HyDE).
- Khattab and Zaharia, 2020. ColBERT.
- Liu et al., 2023. Lost in the Middle.
- Thakur et al., 2021. BEIR benchmark.
- Es et al., 2023. RAGAS.
- Anthropic, 2024. Introducing Contextual Retrieval.
- Carbonell and Goldstein, 1998. The use of MMR, diversity-based reranking for reordering documents and producing summaries. SIGIR.
Benchmarks
- MTEB leaderboard for embedding models.
Repository layout
dify-rag-recipes/
├── ragkit/
│ ├── chunking.py # fixed, recursive and Markdown-aware chunking
│ ├── bm25.py # Okapi BM25 keyword scoring
│ ├── fusion.py # reciprocal rank fusion, weighted score fusion
│ ├── rerank.py # cosine similarity, maximal marginal relevance
│ ├── citations.py # numbered context, citation extraction and checks
│ └── evaluate.py # recall@k, precision@k, hit rate, MRR, nDCG@k
├── examples/
│ └── hybrid_demo.py # offline end-to-end toy pipeline
└── tests/
└── test_ragkit.py # unittest suite, standard library only
Run the tests:
python3 -m unittest discover -s tests -t .
Contributing
PRs are welcome: new recipes, better defaults backed by measurements, bug fixes in ragkit, and ports of the SQL to other databases. Please keep entries accurate, link only to real and primary sources, keep ragkit standard-library only, and add a test for any code change.
License
Code and content are released under the MIT License.
If this helped you, a star helps others find it.
More free resources
Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.