Article · RAG · Embeddings & vector databases
RAG: answers grounded in your own documents
Retrieval-Augmented Generation from basics to production – chunking, hybrid search with BM25 and RRF, reranking, cited answers with Claude, evaluation and the cases where RAG is unnecessary.
A language model does not know Halina's Pierogi menu, the opening hours of the new restaurant or yesterday's change to the delivery terms. RAG (Retrieval-Augmented Generation) is a pattern in which, before generating an answer, the application retrieves matching fragments of your own documents and adds them to the prompt. The model then answers from the facts supplied, not from its training memory – and can point to where it got them.
- 2020
- the year of the paper that named RAG – Lewis et al., Facebook AI Research
- k = 60
- the constant in Reciprocal Rank Fusion – score = Σ 1 / (k + rank)
- 67%
- fewer failed retrievals – Contextual Retrieval + reranking (Anthropic's measurement, 2024)
The problem: 40 restaurants, 40 menus and terms that change every month
Halina's Pierogi has grown to 40 restaurants. Each has its own menu, opening hours, delivery zones and promotions; on top of that there are FAQs, terms of service, an allergen policy and thousands of customer reviews. The assistant on the website has to answer questions like "does the Kazimierz restaurant deliver on Sundays?" or "do the spinach pierogi contain nuts?".
Three approaches that do not work well:
- Relying on the model's knowledge – it does not have it, so it will make things up (see LLM fundamentals).
- Fine-tuning – it teaches style and format but memorizes facts poorly, and every menu change would mean retraining.
- Pasting everything into the prompt – with several million tokens that is expensive, slow and hurts accuracy.
RAG solves it the way a person would: first find the right pages in the binder, then answer.
Do you really need RAG?
An honest question before the first line of code. The menu, FAQ and terms of one restaurant are maybe 30,000 tokens. With a context window of around a million tokens and prompt caching, the simplest solution is to send all of it in a stable prompt prefix – no vector database, no chunking, no retrieval errors.
Without RAG: the whole small corpus in the cache
import anthropic
from pathlib import Path
client = anthropic.Anthropic()
# Menu + FAQ + terms of one restaurant: ~30k tokens. Small enough to send whole - no retrieval needed.
corpus = "\n\n".join(p.read_text(encoding="utf-8") for p in sorted(Path("knowledge").glob("*.md")))
def ask(question: str) -> str:
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system=[
{"type": "text", "text": "Answer only from the knowledge base below. If it is not there, say so."},
# Stable prefix -> cached: later calls pay a fraction of the price for these tokens.
{"type": "text", "text": corpus, "cache_control": {"type": "ephemeral"}},
],
messages=[{"role": "user", "content": question}], # the variable part goes after the cache breakpoint
)
u = response.usage
print(f"cache read={u.cache_read_input_tokens} written={u.cache_creation_input_tokens} fresh={u.input_tokens}")
return next(b.text for b in response.content if b.type == "text")
print(ask("Do you deliver on Sundays?"))import Anthropic from "@anthropic-ai/sdk";
import { readFileSync, readdirSync } from "node:fs";
const client = new Anthropic();
// Menu + FAQ + terms of one restaurant: ~30k tokens. Small enough to send whole.
const corpus = readdirSync("knowledge")
.filter((f) => f.endsWith(".md"))
.sort()
.map((f) => readFileSync(`knowledge/${f}`, "utf8"))
.join("\n\n");
export async function ask(question: string): Promise<string> {
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
system: [
{ type: "text", text: "Answer only from the knowledge base below. If it is not there, say so." },
// Stable prefix -> cached; keep timestamps and user data out of it.
{ type: "text", text: corpus, cache_control: { type: "ephemeral" } },
],
messages: [{ role: "user", content: question }],
});
const u = response.usage;
console.log(`cache read=${u.cache_read_input_tokens} written=${u.cache_creation_input_tokens}`);
return response.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
}| Situation | Better choice |
|---|---|
| corpus up to ~a few hundred thousand tokens, rarely changes | everything in the prompt + prompt caching |
| large corpus (millions of tokens) or growing | RAG |
| different permissions per document (restaurants, roles, customers) | RAG with permission filtering |
| data changes every minute (order status, availability) | tools – tool use – instead of an index |
Our chain of 40 restaurants with reviews and a history of terms is a classic case for RAG.
Architecture: two paths
The indexing path runs in the background (a job, a queue, a webhook from the CMS). The query path has to fit the latency budget of a conversation – typically tens of milliseconds for search, up to a few hundred for reranking, and the rest for generation.
Indexing: garbage in, hallucinations out
Most RAG problems start before the embeddings. Strip navigation, footers and cookie banners from HTML, keep tables (opening hours in a PDF are a common headache), remove duplicates and attach metadata: restaurant, language, document type, validity date, permissions. Metadata is used for filtering ("restaurant 7 only", "current version of the terms only") and for showing the source in the answer.
Chunking
A chunk is the unit of retrieval and citation. Too big and it "blurs" the meaning and wastes context space; too small and it loses sense ("Delivery takes 45 minutes" – but at which restaurant?).
| Strategy | How | When |
|---|---|---|
| Fixed size + overlap | windows of e.g. 300–500 tokens, 10–20% overlap | a starting point, unstructured text |
| Recursive by structure | headings/paragraphs first, then size | documentation, terms, FAQs – the most common choice |
| Semantic | cut where the topic changes (similarity of neighbouring sentences) | long narrative texts |
| One record = one chunk | a menu item, a review, an FAQ entry | data already split by nature |
Good practice: prepend the heading path ("Terms > Delivery > Zones") and the restaurant name to each chunk – then the chunk makes sense on its own. Anthropic described an extension of this idea as Contextual Retrieval: a model writes a short context from the whole document for each chunk before embedding; in their measurements, combined with BM25 it cut the rate of failed retrievals by 49%, and with reranking by 67%.
Chunking: structure first, then size
import re
from dataclasses import dataclass
MAX_CHARS = 1200 # ~250-350 tokens of English, fewer for Polish - measure with your tokenizer
OVERLAP = 200 # repeated tail so a sentence cut at the border is still findable
@dataclass
class Chunk:
doc_id: str
heading_path: str # e.g. "Terms > Delivery > Zones" - keeps the chunk self-explanatory
text: str
def split_by_headings(markdown: str) -> list[tuple[str, str]]:
"""Structure first: one section per Markdown heading, with the full heading path."""
sections, path, buf = [], [], []
for line in markdown.splitlines():
m = re.match(r"^(#{1,4})\s+(.*)", line)
if m:
if buf:
sections.append((" > ".join(path), "\n".join(buf).strip()))
buf = []
level = len(m.group(1))
path = path[: level - 1] + [m.group(2).strip()]
else:
buf.append(line)
if buf:
sections.append((" > ".join(path), "\n".join(buf).strip()))
return [(p, t) for p, t in sections if t]
def window(text: str) -> list[str]:
"""Size second: long sections become overlapping windows, cut at paragraph or sentence ends."""
out, start = [], 0
while start < len(text):
end = min(start + MAX_CHARS, len(text))
if end < len(text):
cut = max(text.rfind("\n\n", start, end), text.rfind(". ", start, end))
end = cut + 1 if cut > start + MAX_CHARS // 2 else end
out.append(text[start:end].strip())
if end >= len(text):
break
start = max(end - OVERLAP, start + 1)
return out
def chunk_document(doc_id: str, markdown: str) -> list[Chunk]:
return [
Chunk(doc_id, path, f"{path}\n\n{piece}") # the heading path is embedded together with the text
for path, body in split_by_headings(markdown)
for piece in window(body)
]export interface Chunk {
docId: string;
headingPath: string; // e.g. "Terms > Delivery > Zones"
text: string;
}
const MAX_CHARS = 1200; // measure in tokens for your model and language
const OVERLAP = 200;
function splitByHeadings(markdown: string): Array<[path: string, body: string]> {
const sections: Array<[string, string]> = [];
let path: string[] = [];
let buf: string[] = [];
const flush = () => {
const body = buf.join("\n").trim();
if (body) sections.push([path.join(" > "), body]);
buf = [];
};
for (const line of markdown.split("\n")) {
const m = /^(#{1,4})\s+(.*)/.exec(line);
if (m) {
flush();
path = [...path.slice(0, m[1].length - 1), m[2].trim()];
} else buf.push(line);
}
flush();
return sections;
}
function windows(text: string): string[] {
const out: string[] = [];
let start = 0;
while (start < text.length) {
let end = Math.min(start + MAX_CHARS, text.length);
if (end < text.length) {
const cut = Math.max(text.lastIndexOf("\n\n", end), text.lastIndexOf(". ", end));
if (cut > start + MAX_CHARS / 2) end = cut + 1;
}
out.push(text.slice(start, end).trim());
if (end >= text.length) break;
start = Math.max(end - OVERLAP, start + 1);
}
return out;
}
export function chunkDocument(docId: string, markdown: string): Chunk[] {
return splitByHeadings(markdown).flatMap(([headingPath, body]) =>
windows(body).map((piece) => ({ docId, headingPath, text: `${headingPath}\n\n${piece}` })),
);
}using System.Text.RegularExpressions;
var terms = """
# Terms
## Delivery
We deliver within 5 km of each restaurant. Orders above 80 PLN are delivered for free.
## Allergens
Every dish lists the 14 EU allergens. The walnut sauce contains nuts.
""";
foreach (var c in Chunker.Chunk("terms-v3", terms))
Console.WriteLine($"[{c.HeadingPath}] {c.Text.Length} chars");
public sealed record Chunk(string DocId, string HeadingPath, string Text);
public static partial class Chunker
{
const int MaxChars = 1200, Overlap = 200;
[GeneratedRegex(@"^(#{1,4})\s+(.*)$")]
private static partial Regex Heading();
public static IEnumerable<Chunk> Chunk(string docId, string markdown)
{
var path = new List<string>();
var buf = new List<string>();
foreach (var line in markdown.Split('\n').Append("# ")) // sentinel flushes the last section
{
var m = Heading().Match(line);
if (!m.Success) { buf.Add(line); continue; }
var body = string.Join('\n', buf).Trim();
var headingPath = string.Join(" > ", path);
foreach (var piece in Windows(body))
yield return new Chunk(docId, headingPath, $"{headingPath}\n\n{piece}");
buf.Clear();
int level = m.Groups[1].Length;
path = [.. path.Take(level - 1), m.Groups[2].Value.Trim()];
}
}
static IEnumerable<string> Windows(string text)
{
for (int start = 0; start < text.Length;)
{
int end = Math.Min(start + MaxChars, text.Length);
if (end < text.Length)
{
int cut = Math.Max(text.LastIndexOf("\n\n", end - 1), text.LastIndexOf(". ", end - 1));
if (cut > start + MaxChars / 2) end = cut + 1;
}
yield return text[start..end].Trim();
if (end >= text.Length) yield break;
start = Math.Max(end - Overlap, start + 1);
}
}
}The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Hybrid search: words and meaning
- Reranking: wide first, then precise
- Generation: an answer with citations
- Evaluation: measure retrieval and generation separately
- Advanced techniques
- When RAG, and when something else
- Pre-production checklist
- Test yourself
- What's next