AI Agentic Handbook
Cheat sheet

Retrieval-Augmented Generation

One line per term, the default to reach for, and the number to remember. Print it or save it as a PDF.

Embedding

A list of numbers that stands for the meaning of a piece of text, arranged so that similar meanings land close together.

Default: bge-m3 (568M params, 1,024 dims, 8,192-token input) self-hosted, or a hosted embedding model truncated to 1,024 dims; L2-normalise at write; store model@version with every vector; hybrid with BM25; re-embed via a new index behind an Index alias.

Dimensions: 384–4,096 (common production models; 768–1,024 is the default sweet spot)

Vector space

The space embeddings live in, where 'close together' means 'similar in meaning'.

Default: One model per index, version recorded; L2-normalise and use inner product; exact search (FAISS flat or pgvector without an index) below ~1M vectors, HNSW above; thresholds calibrated per model on 300–1,000 labelled pairs; UMAP plots for exploration only.

Random-vector cosine spread: std ≈ 1/√d (≈0.03 at d = 1,024; real models are anisotropic and sit higher)

Encoder

A model that reads text and turns it into meaning-numbers, instead of writing a reply.

Default: bge-m3 for multilingual or long chunks; all-MiniLM-L6-v2 when CPU-only and chunks are short; served with Text Embeddings Inference or Sentence-Transformers, batch 32–128, FP16 on GPU; an ingest assertion that token length ≤ max_seq_length.

Encoder sizes: 22M–7B parameters (production embedding models, Oct 2026)

Bi-encoder

Turns the question and each document into vectors separately, then compares them. Fast enough to search millions.

Default: bge-m3 or a hosted embedding model; documents embedded at ingest, queries at request time with the model's documented prefix; HNSW (M = 16, ef_construction = 200, ef_search tuned to recall ≥ 0.95 vs exact); top 50–100 candidates handed to a reranker.

Query encode: 5–15 ms (100M–600M encoder on a GPU)

Cross-encoder

Reads the question and one document together and scores the match. Much sharper than comparing vectors, far too slow to run over everything.

Default: bge-reranker-v2-m3 (568M, multilingual) self-hosted on one GPU, or a hosted rerank API; rerank the top 50 from hybrid search, keep 5–8; max length 512 tokens per pair; batch all candidates in one call; MiniLM-L6 cross-encoder when CPU-only or under 100 ms total budget.

Rerank latency, small model: 100–300 ms per 100 candidates (MiniLM-L6 (22M) on one A10G, 300-token chunks)

Cosine similarity

A score from −1 to 1 for how closely two embeddings point the same way: the usual way to ask 'are these two texts about the same thing?'

Default: L2-normalise every vector at write time and at query time; index with inner product (pgvector vector_ip_ops, FAISS IndexFlatIP/HNSW-IP); follow the model card if it specifies dot product on raw vectors; calibrate thresholds per model on 500–1,000 labelled pairs.

Unit-vector identity: ‖a − b‖² = 2 − 2cos(a, b) (holds only when both vectors are L2-normalised)

Dot product

Multiply two lists of numbers position by position and add it all up. The cheapest way to ask 'do these two texts mean the same thing?'

Default: L2-normalize every vector at write and query time, assert the norm in the ingestion path, and index with inner product: pgvector vector_ip_ops (the <#> operator returns the negative inner product, so order ascending), FAISS METRIC_INNER_PRODUCT, Qdrant Dot (or Cosine, which normalizes on insert).

Bytes read per 1024-dim candidate: 4 KB float32, 1 KB int8, 128 B binary (uncompressed vector, no index overhead)

Embedding dimensionality

How many numbers are in each embedding — 384, 768, 1024, 3072. Storage, speed and cost grow with it in a straight line. Quality does not.

Default: Start at 1024 dims: bge-m3 self-hosted, or text-embedding-3-large / gemini-embedding-001 truncated to 1024, or voyage-3.5 at its 1024 default.

Raw float32 storage: 4 KB per 1024-dim vector; 4.1 GB per 1M (before index overhead)

Symmetric vs asymmetric embeddings

Symmetric search matches like with like (ticket to ticket). Asymmetric search matches a short question to the long passage that answers it.

Default: For RAG, use an asymmetric model and always pass the role: Cohere input_type, Voyage input_type, E5/Nomic prefixes, or the query instruction for bge and Qwen3-Embedding.

Typical MS MARCO query vs passage length: ~6 words vs ~55 words (MS MARCO passage ranking)

Instruction prefix (query: / passage:)

A tiny label such as 'query: ' or 'passage: ' stuck in front of text before embedding it, telling the model which role this text is playing.

Default: One shared embedding client that owns model id, revision, query prefix and document prefix as a single versioned config; every chunk stores the config hash; ingestion refuses to write if hashes disagree.

Prefix cost: 2–20 tokens per input (fixed role strings vs free-text task instruction)

Matryoshka embeddings

Embeddings trained so the first few hundred numbers work on their own: cut 3072 down to 256 and keep most of the quality.

Default: text-embedding-3-large or gemini-embedding-001 at 1024 dims for the main index; 256-dim prefix plus rescoring when RAM dominates.

Quality at 256 of 3072 dims: 62.0 vs 64.6 MTEB (≈96%) (text-embedding-3-large, OpenAI-reported)

MTEB leaderboard

The big public scoreboard for embedding models. Perfect for picking three to try; your own test set decides the winner.

Default: Shortlist 3–5 models from the MTEB retrieval tab filtered by language and size, always including one API model (voyage-3.5, text-embedding-3-large, gemini-embedding-001 or Cohere embed-v4) and one self-hostable model (bge-m3 or Qwen3-Embedding-0.6B).

Original MTEB scope: 58 datasets, 8 task types, 112 languages (Muennighoff et al., 2022)

Fine-tuning an embedding model

Training an embedding model a bit further on your own question-and-passage pairs, so your field's jargon finally lands near its meaning.

Default: Sentence Transformers v3+ trainer, base model bge-base-en-v1.5 or bge-m3 (or Qwen3-Embedding-0.6B for multilingual), CachedMultipleNegativesRankingLoss, batch 512–1,024, 2 hard negatives per pair from ranks 10–50 filtered by a cross-encoder, lr 2e-5, 1–2 epochs, golden set split by document.

Typical in-domain gain: +5–15 points recall@10 (jargon-heavy domain, 10k–50k pairs, vs same base model)

Chunking

Cutting documents into passages small enough to search and hand to a model. Usually a few hundred tokens, cut where the document itself breaks.

Default: Parse to Markdown first (Docling or Unstructured), then a recursive splitter (LangChain RecursiveCharacterTextSplitter.from_tiktoken_encoder or LlamaIndex SentenceSplitter) at 256–400 tokens of the embedding model's tokenizer, 0 overlap, headings prepended as a breadcrumb, tables and code blocks kept whole up to 800–1,000 tokens.

Recall vs size: 88.1% @200 · 89.5% @400 · 85.4% @800(+400 overlap) (Chroma 2024, text-embedding-3-large, 5 chunks)

Chunk overlap

Repeating the tail of one chunk at the start of the next, so an idea cut in half still appears whole somewhere.

Default: 0 overlap with structure-aware splitting plus read-time expansion (neighbouring chunks or parent section).

Storage multiplier: 1 / (1 − overlap fraction): 1.25× at 20%, 2× at 50% (fixed-length windows)

Structural & semantic chunking

Cutting where the topic changes rather than every N words, spotted by a drop in similarity between neighbouring sentences.

Default: LangChain SemanticChunker or LlamaIndex SemanticSplitterNodeParser with a small fast embedder (bge-small-en-v1.5 or all-MiniLM-L6-v2) for breakpoint detection, buffer of 1 sentence each side, 90–95th percentile threshold, 100-token minimum and 500-token maximum; then embed the final chunks with your main model.

Extra ingest embedding calls: 5–20× chunk count (one call per sentence (window))

Parent-document retrieval

Search small chunks so the match is precise, then hand the model the bigger section around them. Retrieve small, return big.

Default: Children of 150–250 tokens indexed with parent_id; parents = heading sections capped at 2,000 tokens (split larger ones); retrieve 30 children, group, return top 3 parents ordered best-first.

Context per answer: ~1.5k (children) → 4–6k tokens (3 parents) (200-token children, 1.5–2k parents)

Contextual enrichment (breadcrumbs)

Adding a short model-written note to each chunk saying where it came from, before it is stored. Anthropic measured 35–67% fewer retrieval misses.

Default: Step 1, always: prepend title › section path › date to every chunk.

Retrieval failure reduction: 35% (embed) · 49% (+BM25) · 67% (+rerank) (Anthropic benchmark, top-20, Sept 2024)

Layout-aware parsing

Pulling text out of PDFs and scans with reading order, headings, tables and figures intact — so everything downstream has structure to work with.

Default: Docling (open source) to Markdown with page numbers and bounding boxes; tables exported as Markdown or HTML and chunked whole; page headers and footers dropped.

Docling throughput: ~1–2 s/page CPU, sub-second on GPU (text-layer PDFs with table structure on (estimate; measure))

OCR (optical character recognition)

Turning pictures of text — scans, photos, faxes — into text a computer can actually read. Mistakes here spread into everything downstream.

Default: Preprocess (deskew, 300 DPI, binarise), Tesseract 5 or PaddleOCR with word confidences, escalate pages with mean confidence <80 to a managed OCR service, keep bounding boxes and engine version per page, and send identifier fields (policy numbers, MRNs, invoice ids) with confidence <90 to human review.

Tesseract CER: ~1–2% clean 300-DPI print; 5–10%+ on faxes/photos (printed Latin script, no handwriting)

Ingestion pipeline

The machinery that collects your documents, parses, chunks, embeds and indexes them — and keeps the index honest as sources change and vanish.

Default: Event-driven per-document jobs on SQS or Kafka with stateless workers; Docling for parsing; SHA-256 content hash on normalised text; deterministic chunk ids; embedding batches of 64–256; upsert then delete stale chunk ids; registry write last; DLQ after 3 retries with exponential backoff; nightly reconciliation job.

Unchanged-content events skipped by hash: 50–80% (wikis and CMSs where metadata edits dominate)

Document registry

The record book for ingestion: one row per source document — where it came from, its version, its status, who may see it, which chunks it made.

Default: A Postgres table keyed by (tenant_id, doc_id) with the columns above, indexes on status and embed_model, row written after the index upsert (or via a transactional outbox), soft deletes with deleted_at, and raw source snapshots in object storage keyed by content hash so the index can be rebuilt without re-crawling.

Row size: ~1–2 KB (with ~20 chunk ids and ACL list)

Content hashing

A fingerprint of a document's text. Same text, same fingerprint — so you can skip unchanged files, spot duplicates and retry safely.

Default: SHA-256 over normalised extracted text; document hash in the registry; chunk embedding cache keyed by sha256(chunk_text) + embed_model + prefix_version + chunker_version; MinHash LSH (datasketch, 128 permutations, Jaccard 0.8–0.85) for near-duplicate collapse on web or marketplace corpora.

Truly changed share on nightly re-crawl: 1–5% (catalogs and docs sites after normalisation)

Change data capture (CDC)

Change data capture: reading a database's own change log so your search index follows every insert, update and delete within seconds.

Default: Debezium (Postgres pgoutput) to Kafka or a managed equivalent, topic partitioned by primary key, max_slot_wal_keep_size set, Kafka retention ≥ 7 days, consumer applying events only when source LSN/version is newer than the stored one, metadata-only updates skipping re-embed, nightly reconciliation against a table snapshot.

Source-to-searchable latency: seconds (p95 5–30 s) (CDC + streaming consumer, excluding batch embedding waits)

Tombstone

A little note saying 'this was deleted', travelling through the system so every copy and index learns to drop it.

Default: Deletes as events (Kafka tombstones or explicit op: d), registry deleted_at + chunk ids, delete by id (never by fuzzy filter), purge semantic-cache entries by cited doc id, nightly orphan reconciliation, compaction/vacuum on a deleted-ratio threshold, and a restore runbook that replays registry deletions before serving.

Kafka tombstone retention: delete.retention.ms = 24 h default (compacted topics; raise if consumers can lag longer)

Backfill

Rebuilding the whole index the new way — new model, new chunker, new fields — beside the live one, then switching over once it checks out.

Default: Versioned indexes behind an alias (docs → docs_v7); backfill from the registry's cached text, sharded by doc-id hash with per-shard checkpoints; provider Batch API when latency allows; record CDC/stream position at start and replay; gate the switch on count parity (±0.1%), golden-set recall no worse than −0.5 points, and 2–3 days of shadow traffic; keep v1 for 7–14 days.

Duration: tokens ÷ throughput, ×1.5–2 for retries (e.g. 10.6B tokens at 3M tokens/min ≈ 2.5 days)

Chunk metadata

The labels stored next to each chunk — customer, permissions, source, date, page — used for filtering, access control and citations.

Default: Every chunk carries tenant_id, acl, doc_id, chunk_id, source, doc_type, section_path, page, updated_at and embed_model; payload indexes on tenant_id, acl and any field used in filters; tenant and ACL filters injected server-side from the authenticated principal; volatile fields (price, stock, ACL) in metadata only.

Metadata per chunk: ~200 B–1 KB (15–20 fields, short ACL lists)

Sparse retrieval

Good old keyword search: find the documents containing the words you typed. Fast, easy to explain, and still unbeatable for IDs, codes and names.

Default: Elasticsearch or OpenSearch with BM25 (k1=1.2, b=0.75 defaults), a standard analyzer on prose fields and a separate code-aware or keyword sub-field for identifiers.

Query latency, 3-term query: 5–20 ms p50 (10M passages, one 8-vCPU Elasticsearch node, warm page cache)

BM25

The keyword scoring formula behind most search engines: rare words count more, repeats count less and less, long documents don't win by being long.

Default: Engine defaults k1=1.2, b=0.75; per-field similarity only after an offline eval shows a gain.

Lucene defaults: k1 = 1.2, b = 0.75 (Elasticsearch, OpenSearch, Solr)

SPLADE

Keyword search with a brain: a model writes the weighted word list, and adds related words the text never used.

Default: On Elasticsearch: ELSER into a sparse_vector field, fused with BM25 and a dense leg via the rrf retriever.

BEIR zero-shot nDCG@10: ≈0.47–0.50 average (SPLADE v2 / SPLADE++ checkpoints vs ≈0.43 for BM25)

Dense retrieval

Search by meaning: turn the question and every passage into number-lists, and return the passages whose numbers sit closest.

Default: Open-weights bge-m3 (568M, 1024-d, multilingual) or Qwen3-Embedding-0.6B self-hosted on one L4; or an API model (OpenAI text-embedding-3-small, Cohere Embed, Voyage) when you cannot host.

Query embed latency: 5–20 ms self-hosted, 50–200 ms API (single query, ≤64 tokens, 0.5B-class model on L4)

Hybrid search

Run keyword search and meaning search side by side, then merge the two lists — each one covers what the other misses.

Default: BM25 top 100 + dense top 100, RRF with k=60, cross-encoder (bge-reranker-v2-m3, 568M) on the fused top 50, 5–10 chunks to the LLM.

RRF constant: k = 60 (Cormack et al. 2009; Elasticsearch default rank_constant)

Semantic search vs similarity search

Search that goes after what you meant rather than the words you typed. Usually embeddings, plus a reranker to tidy up the top.

Default: Hybrid retrieval (BM25 + bge-m3 or text-embedding-3-small) to 200 candidates, structured filters from a lightweight query parser, bge-reranker-v2-m3 on the top 50, sentence-level highlighting from the reranker's best sentence.

BERT rerank gain over BM25: MRR@10 0.187 → 0.365 (MS MARCO passage dev (Nogueira & Cho 2019))

Approximate nearest neighbour (ANN)

Approximate nearest neighbour search: find vectors close to your query without checking them all. Give up a sliver of accuracy, gain huge speed.

Default: ≤ 100k vectors: exact search.

HNSW query latency: 1–3 ms (10M × 768-d in RAM, ef_search 100, recall@10 ≈ 0.95–0.98)

HNSW

The most common way to index vectors in memory: a layered map of 'who is near whom', walked greedily from the top down.

Default: M=16, ef_construction=64–128, ef_search=100 (≥ 5× k), cosine via normalised vectors + inner product.

Link overhead: ~128–200 B per vector at M=16 (4-byte neighbour ids, 2·M links on layer 0)

IVF (inverted file index)

Sort the vectors into buckets, then only search the buckets nearest your question. Cheap to build, easy to split across machines.

Default: FAISS: nlist ≈ 4√N–16√N (IVF4096,Flat at 1M, IVF65536,PQ64 at 100M+), train on ≥ 30 × nlist random vectors, nprobe swept to hit recall@10 ≥ 0.95 after rescoring.

Distance computations per query: nlist + nprobe·N/nlist (flat lists; minimised near nlist ≈ √N)

Product quantization (PQ)

Squash each vector into a handful of bytes by describing it with 'standard pieces' from a learned catalogue. 3,072 bytes become 64.

Default: FAISS OPQ{m},IVF{nlist},PQ{m} with m = D/8–D/12 (64–96 at 768-d), 8-bit codes, train on ≥ 256 × 256 vectors per subspace sample (~1M vectors is safe), rescore the top 200–1,000 with float16 vectors.

Compression: 48× (3,072 B → 64 B) (768-d float32, PQ64 with 8-bit codes)

Scalar & binary quantization

Storing each number in an embedding with fewer bits — 16-bit, 8-bit, even 1-bit — to cut memory 2–32×, with a re-check pass to win the accuracy back.

Default: float16 storage by default (pgvector halfvec).

Memory reduction: 2× / 4× / 32× (float16 / int8 / binary vs float32)

ANN recall (efSearch, nprobe)

How many of the genuinely closest vectors your fast index actually returned. Measured against slow exact search, not against human opinion.

Default: Nightly job: 1,000–2,000 sampled production queries, exact top-k via brute force, recall@10 reported overall and per segment (tenant size bucket, filter vs no filter, data age).

Typical production target: recall@10 ≥ 0.95 (with a reranker and fusion downstream)

Metadata filtering (pre, post, filtered ANN)

Restricting a search to items whose fields match conditions — this customer, this language, after 2024 — without quietly wrecking recall.

Default: Payload/metadata index on every filtered field (Qdrant create_payload_index, B-tree in Postgres).

Post-filter expected matches: ef_search × selectivity (e.g. 100 × 1% = 1 row for k=10)

Candidate generation & the retrieval funnel

The cheap first pass that cuts millions of items down to a few hundred, so something slower and smarter can order them properly.

Default: Hybrid (BM25 + dense) to 100–200 fused candidates; rerank 50–100 with a cross-encoder; pass 5–10 to the LLM.

Stage-1 recall target: ≥ 0.9 at the handoff N (labelled golden set; below this the reranker is starved)

Top-k (retrieval k vs context k)

How many results a stage returns. Early stages want lots (100+); the few you hand the model want to be few (5–10).

Default: Retrieval k = 100 (each hybrid leg), rerank top 50, reranker score threshold tuned on the golden set (start at 0.2–0.3), cap 8 chunks / ~6k tokens in context, near-duplicate removal before the cap.

Mid-context accuracy drop: 20+ points (answer in the middle of 20 docs vs first position (Liu et al. 2023))

Query rewriting

Turning the user's messy message into a proper search query: resolving 'it', expanding jargon, dropping the small talk.

Default: Standalone-question rewrite for every turn after the first, using a small model with JSON output and a 2-second timeout falling back to the raw query.

Follow-ups needing contextualisation: 20–40% of turns (multi-turn assistant traffic (typical sampled logs))

Query decomposition

Breaking a question that is really three questions into parts, searching for each, then answering from all the evidence together.

Default: Gate on intent (comparison, multi-hop).

Added latency, parallel: 300–800 ms (one small-model planner call + concurrent retrieval)

HyDE (hypothetical document embeddings)

Have the model write a pretend answer first, then search with that instead of the question — because answers look like documents, and questions don't.

Default: Off by default.

Added latency: 300–1,500 ms (one ~120–150-token generation on a small hosted model)

Intent classification & routing

Working out what kind of request just arrived, so it can be sent down the right path: document search, database query, tool call, or a polite 'no'.

Default: Embedding + logistic-regression classifier (200–500 examples/intent) with a confidence threshold of 0.7; LLM (small model, JSON schema) for the low-confidence tail; unknown falls back to hybrid RAG; all routing decisions logged with confidence.

Embedding classifier latency: 2–10 ms (small encoder on CPU + linear head)

Vector database

A store built to search embeddings quickly, with filters, updates, deletes and backups. Often Postgres with pgvector is already enough.

Default: pgvector (0.8+) in the existing Postgres up to ~10M vectors: halfvec, HNSW m=16 / ef_construction=64–128, iterative scans for filters.

pgvector comfortable range: ≲10M vectors per instance (768–1024-d halfvec HNSW, index fits in RAM alongside OLTP working set)

Sharding & partitioning

Splitting an index across machines so each holds a slice. Buys you size and write throughput — not a faster single query.

Default: Elasticsearch/OpenSearch: 10–50 GB per shard, primaries sized for 12–18 months of growth, time- or alias-based indices for rollover.

Shard size: 10–50 GB, < 200M docs (Elasticsearch sizing guidance)

Replication

Keeping copies of each shard on several machines, so you survive a failure and can answer more queries at once.

Default: 1 replica minimum in production (2 copies), across availability zones; 2 replicas for indices that must survive a node loss during maintenance.

Read scaling: ~linear in copies (until coordinator/network saturates)

Reranker

A slower, sharper model that re-scores the top 50–200 candidates, so only the best 5–10 ever reach the model writing the answer.

Default: Hybrid retrieval → top 100 → bge-reranker-v2-m3 (FP16, max length 512, batch 32) on a GPU behind Hugging Face TEI or Infinity → keep top 5–8.

MiniLM-L6 cross-encoder latency: 300–600 ms CPU, 30–60 ms GPU (100 pairs × 256 tokens; 8 vCPU ONNX vs one L4/A10G)

Reciprocal Rank Fusion (RRF)

A merge trick for two result lists: score each document by its position in each list, not by the raw numbers. No calibration needed.

Default: k = 60; fuse the top 50–100 from each retriever; dedupe by document or chunk id before scoring; send the fused top 100 to a Reranker.

Default k: 60 (Cormack et al. 2009; results stable for k ≈ 20–100)

Weighted score fusion

Combining retriever scores rather than ranks: rescale each list to a common range, then blend them with a weight you tune.

Default: Min-max normalise each list per query over its top 100; missing docs take that list's min; α from a 0.0–1.0 sweep in 0.1 steps on the golden set, picked by nDCG@10 with a bootstrap CI.

Labels needed to tune α: 50–200 queries (single global α; per-class α needs ~50 per class)

Context assembly

Turning ranked chunks into an actual prompt: drop duplicates, fit the token budget, order them, label them so they can be cited.

Default: Budget 3–6k tokens of retrieved context for single-hop Q&A, 8–15k for multi-document synthesis.

Retrieved-context budget: 3–6k tokens (single-hop Q&A; 8–15k for multi-document synthesis)

Lost in the middle

Models used to overlook facts buried in the middle of a long prompt. Finding one fact is largely fixed; joining several across a long text still isn't.

Default: Rerank to 5–10 chunks; order best-first, second-best-last; restate the question after the context block; decompose multi-hop questions into single-hop sub-queries.

Middle-position penalty (2023): > 20 accuracy points (GPT-3.5-Turbo, 20 documents, middle vs first position (Liu et al. 2023))

Grounding & groundedness checks

Making the model answer from the sources you handed it rather than from memory — and then checking that it actually did.

Default: System prompt: answer only from tagged sources, cite ids for every factual sentence, say you cannot find it when sources are insufficient.

Verifier cost: 10–20% of generation cost (small judge model checking 3–8 claims per answer)

Attribution & citations

Linking each claim in an answer to the exact passage that backs it — and measuring whether those citations are right and complete.

Default: Native span citations (Anthropic Citations, or the provider equivalent) when available; else XML-tagged chunks with short ids and an instruction to cite after every factual sentence.

Citation recall target: ≥ 0.9 (customer-facing; measured per sentence on a sample)

Abstention & relevance thresholds

Letting the system say 'I don't know' on purpose when the evidence isn't there, instead of guessing beautifully.

Default: Golden set with 10–15% unanswerable items.

Unanswerable share in golden set: 10–15% (enough to measure false-answer rate with ±5-point CI at n ≈ 500)

Semantic cache

Reusing a stored answer when a new question means roughly the same as an old one. Cheap and fast, with a real risk attached.

Default: Provider prompt caching first.

Threshold: 0.92–0.97 cosine (start at 0.95; depends on embedding model)