# RAG pipelines

Build retrieval-augmented generation in AgenticMind, from basic retrieval to cited answers, hybrid search, reranking, query rewriting, compression and parent-child chunks.

Source: https://glamorous-boar.cloudvent.net/rag/

---

**Retrieval-augmented generation (RAG)** answers questions from your own documents: find the passages most relevant to the question, put them in the prompt, and ask the model to answer from them, citing its sources. The theory is in the handbook chapters [Retrieval-augmented generation](/learn/rag/) and [Advanced retrieval](/learn/advanced-retrieval/); this page is the how-to.

## The two flows

A RAG project has an **ingestion flow** and a **query flow** that share two handles:

<Diagram caption="Both flows use the same Embedding Model and Vector Store nodes, so vectors are always comparable.">

```
flowchart TB
  subgraph Ingest[Ingestion: Run → Index report]
    L[Document Loader] --> C[Document Cleaner] --> K[Chunker] --> I[Index Documents] --> R1[Output]
  end
  subgraph Query[Query: Chat / Run → Answer]
    Q[Manual Input: question] --> RT[Retriever / Hybrid Search] --> CB[Context Builder] --> M[LLM] --> CI[Citation Builder] --> R2[Output: answer]
  end
  E[Embedding Model] -.-> I
  V[Vector Store] -.-> I
  E -.-> RT
  V -.-> RT
```

</Diagram>

Run ingestion with **Run → Index report** whenever documents change; ask questions in **Chat**.

## Recipe 1: Basic cited answers

Template *RAG answers with citations*.

| Step | Node | Key settings |
|---|---|---|
| 1 | **Document Loader** | `files` (upload); `split_pdf_pages` on for page citations |
| 2 | **Document Cleaner** | defaults (Unicode normalisation, de-hyphenation, whitespace) |
| 3 | **Chunker** | `strategy: recursive`, `chunk_size: 300` tokens, `chunk_overlap: 50` |
| 4 | **Embedding Model** | `fastembed`, `BAAI/bge-small-en-v1.5` (local, no key) |
| 5 | **Vector Store** | `qdrant` embedded, `collection: documents`, `namespace_by_project` on |
| 6 | **Index Documents** | `skip_unchanged` on, `keyword_index` on |
| 7 | **Retriever** | `top_k: 5`, optional `score_threshold`, `filters` |
| 8 | **Context Builder** | `token_budget: 3000`, `order: relevance`, `deduplicate` on, prompt with `{{context}}` and `{{question}}` |
| 9 | **LLM** | your model; low `temperature` |
| 10 | **Citation Builder** | `remove_invalid` on; `require_citations` to fail uncited answers |

The answer output is `{answer, citations, validation}`. Chat renders citation numbers as links to the source chunk (file, page, section, exact offsets).

<Alert variant="tip" title="Say I don't know" text="The default Context Builder prompt tells the model to answer only from the numbered sources and to say it doesn't know otherwise. Keep that instruction: it is the main defence against hallucinated answers."/>

## Recipe 2: Advanced RAG

Template *Advanced RAG (hybrid search + reranking)*. The query flow becomes:

`question` → **Query Rewriter** → **Hybrid Search** → **Reranker** → **Context Compressor** → Context Builder → LLM → Citation Builder.

| Node | What it adds | Settings to know |
|---|---|---|
| **Query Rewriter** | Turns follow-ups (*and for managers?*) into standalone questions using chat `history`, and generates `variants` alternative phrasings. Falls back to the original query on failure. | `variants: 3`, `temperature: 0.3` |
| **Hybrid Search** | Vector search (meaning) + BM25 keyword search (exact terms: codes, names), over every query variant, fused with **reciprocal rank fusion**. | `top_k: 8`, `candidates: 20`, `fusion: rrf` or `weighted` (`vector_weight`), `rrf_k: 60` |
| **Reranker** | A **cross-encoder** reads each (question, passage) pair and rescores it. Much more accurate than embedding similarity, too slow for a whole corpus, ideal for the top 20. | `provider: fastembed` (`Xenova/ms-marco-MiniLM-L-6-v2`, ~80 MB, local), `llm` or `overlap`; `candidates: 20`, `top_k: 5`, `score_threshold` |
| **Context Compressor** | Keeps only the sentences relevant to the question, so the prompt is shorter and more focused. `llm` mode may keep only sentences that literally occur in the source, so compression cannot introduce text. | `method: extractive` or `llm`, `max_sentences: 4`, `neighbors: 1` |

If the keyword index is missing (for collections indexed before it existed), Hybrid Search degrades to vector results and emits `keyword_index_missing`; re-run ingestion to build it.

## Recipe 3: Parent-child chunks

Template *RAG with parent-child chunks*. Small chunks match a question precisely, but give the model too little context. Parent-child chunking gets both:

1. **Document Loader** with `pdf_layout` on (larger-font lines become headings).
2. **Chunker** with `strategy: parent_child`, `parent_chunk_size: 1200`, `chunk_size: 300`. Each child carries its parent's ID, text and offsets.
3. Index the children as usual.
4. After the **Retriever**, add **Parent Expander** (`max_parents: 5`): it swaps children for their parents, de-duplicated in rank order, keeping the best child score.

## Choosing a chunking strategy

| Strategy | Use when |
|---|---|
| `recursive` (default) | General text. Splits on paragraphs → lines → sentences → words with overlap. |
| `fixed` | You need uniform windows (sliding window). |
| `sentence` | Q&A over prose; chunks are whole sentences with whole-sentence overlap. |
| `markdown` | Markdown or converted DOCX; split by heading sections, then recursively. |
| `layout` | Structured documents: a new chunk at each heading, headings stay with their content, tables, lists and code blocks are never cut unless one alone is too big. |
| `semantic` | Long documents that drift between topics: breaks where neighbouring sentence windows are least similar (`semantic_threshold` percentile). Uses a connected Embedding Model, or offline TF-IDF. |
| `document` | Short documents: one chunk each, split only if too long. |
| `parent_child` | Precise matching plus full context (Recipe 3). |

Every strategy yields **exact slices** of the source text, so offsets, citations and retrieval evaluation stay valid. Sizes are in approximate tokens (words and punctuation) or characters.

## Filtering

Retriever, Keyword Search and Hybrid Search accept exact-match `filters`, for example `{"filename": "handbook.pdf", "page": 3, "metadata.lang": "en"}`. Every vector store stores the same flat filter fields: `filename`, `artifact_id`, `page`, `section`, `parent_id` and `meta_<key>`.

## Safety nets

- **Re-indexing skips unchanged chunks** (content hash + embedding model identity).
- **Dimension mismatch** fails at index time (`EMBEDDING_DIMENSION_MISMATCH`): set `recreate` on Index Documents after switching to a model with different dimensions.
- **Model mismatch** fails at query time (`EMBEDDING_MODEL_MISMATCH`): ingestion and query must use the same Embedding Model node.
- **Project isolation**: with `namespace_by_project` on, collections are prefixed with the project ID; embedded collections are deleted with the project.

## RAG with an agent

Instead of a fixed pipeline, give an Agent a **Knowledge Search Tool** (connected to the same Embedding Model and Vector Store). The agent decides when and how often to search, and can combine search with other tools. Template *Agent with tools*. See [Agents and tools](/agents/).

## Measure it

Change one thing at a time and compare in the [Evaluation Lab](/evaluation/): recall@K, MRR and NDCG tell you whether retrieval improved; required facts, citation validity and the correctness judge tell you whether answers improved.

## Known limits

- Deleting a source document does not yet remove its chunks from either index; use `recreate`.
- The keyword index is a local SQLite FTS5 file even for remote vector backends.
- Citation validation checks that cited sources exist, not that they support the claim (use the groundedness judge in the Evaluation Lab).
