// 72 cards · 10 categories

Cheatsheets.

Every formula, metric and rule from the course on one page, grouped by category. Filter to what you're revising, or print it.

Core concepts

The big ideas, each in a sentence or two.

What an LLM does

Predicts a probability for each possible next token; the app samples one, appends it and repeats.
1.1 What an LLM Actually Does →

Roles

System: developer rules and format (stable). User: the request and documents. Assistant: earlier model replies.
1.2 Prompts, Roles and Structured Output →

Knowledge or behaviour?

Missing facts → RAG. Wrong behaviour → better prompt, then fine-tuning only if prompting is not enough.
1.4 Prompting, RAG or Fine-tuning? →

Why RAG

Fresh, private, verifiable (citations) and controllable (permissions), with no retraining.
3.1 The RAG Pipeline →

MCP

Model Context Protocol: an open standard so one server's tools and data work with any compatible LLM app.
4.1 Tool Calling →

EU AI Act for assistants

Most business assistants: transparency (users know it is AI). Hiring, credit, essential services: possibly high-risk.
6.3 Security, Privacy and Compliance →

Formulas and numbers

Cost, similarity, chunking, fusion and metric formulas.

Tokens and words

English: 1 token ≈ ¾ word, so 1,000 words ≈ 1,300 tokens. Code and other languages use more.
1.1 What an LLM Actually Does →

Cost of a call

, prices per million tokens.
1.3 Tokens, Cost and Latency →

Latency

Latency ≈ TTFT + output tokens ÷ tokens per second. Streaming cuts perceived wait, not total time.
1.3 Tokens, Cost and Latency →

Cosine similarity

. For unit-length vectors it equals the dot product.
2.1 Embeddings: Meaning as Vectors →

Number of chunks

for tokens, chunk size , overlap .
2.2 Chunking Documents →

Vector storage

Raw bytes = vectors × dimensions × 4 (float32). Add 1.5–2× for an HNSW index.
2.3 Vector Indexes and Nearest-neighbour Search →

Reciprocal rank fusion

, with . Uses ranks only, so scales don't matter.
2.4 Hybrid Search and Reranking →

Noise in a small eval

Standard error ≈ . At , : ±8 points (2 SE). Small gains may be chance.
5.1 Why Evals Come First →

Recall@k and precision@k

Recall@k = relevant in top k ÷ all relevant. Precision@k = relevant in top k ÷ k.
5.2 Retrieval Metrics: Recall@k, MRR and nDCG →

MRR

Average over queries of 1 / rank of the first relevant result (0 if missing).
5.2 Retrieval Metrics: Recall@k, MRR and nDCG →

nDCG

DCG@k ; nDCG = DCG ÷ ideal DCG, between 0 and 1.
5.2 Retrieval Metrics: Recall@k, MRR and nDCG →

Routing cost

Blended cost for a share routed to the small model.
6.2 Controlling Cost: Caching, Routing and Budgets →

Prompting

Prompts, roles and structured output that hold up in production.

Structured output recipe

Schema in the request → validate in code → retry once with the error → fall back to a human or safe default.
1.2 Prompts, Roles and Structured Output →

Embeddings, chunking, vector indexes and ranking.

Chunking defaults

Start at 300–800 tokens, 10–20% overlap, split on headings and paragraphs, then tune with evals.
2.2 Chunking Documents →

Chunk metadata

Source, URL, heading, page, date/version, permissions. Needed to cite, filter, re-index and control access.
2.2 Chunking Documents →

HNSW in one line

A layered neighbour graph searched greedily from coarse to fine. Fast, in-memory, ~95–99% recall.
2.3 Vector Indexes and Nearest-neighbour Search →

Two-stage retrieval

Hybrid search for 30–100 candidates (recall) → rerank → top 3–8 to the LLM (precision).
2.4 Hybrid Search and Reranking →

RAG

Pipelines, prompts, debugging and upgrades.

Indexing pipeline (offline)

Load and parse → chunk → embed → store vector, text and metadata.
3.1 The RAG Pipeline →

Query pipeline (online)

Embed query → retrieve (hybrid + filters) → rerank → assemble prompt → generate with citations → log.
3.1 The RAG Pipeline →

RAG prompt rules

Use only sources; cite [n] per claim; say "couldn't find it" when absent; prefer the newest on conflict; be concise.
3.2 Building the Prompt: Context, Citations and Refusals →

Context layout

3–8 reranked chunks, best first, numbered with recognisable labels, question after the sources, no duplicates.
3.2 Building the Prompt: Context, Citations and Refusals →

The first debugging question

Was the answer in the retrieved context? No → retrieval failure. Yes → generation failure.
3.3 Why RAG Fails: A Debugging Guide →

Query rewriting

Turn follow-ups into standalone questions with a small LLM before retrieval. Big win for chat.
3.4 Beyond Basic RAG: Query Rewriting, Filters and Freshness →

Tools and agents

Tool calling, workflows, agent loops and safety.

The tool-calling loop

Send tools → model requests a call → your code validates and runs it → send result → model answers or calls again.
4.1 Tool Calling →

Good tool design

Few non-overlapping tools; descriptions say what, when and returns; compact outputs; helpful errors; validate arguments.
4.1 Tool Calling →

Workflow patterns

Chaining, routing, parallel, orchestrator–workers, evaluator loop.
4.2 Workflows versus Agents →

Agent checklist

Steps unknowable in advance? Valuable enough? Mistakes reversible? Success measurable? Otherwise use a workflow.
4.2 Workflows versus Agents →

Stopping conditions

Step limit, cost budget, timeout, and a graceful hand-off to a human with a summary when any is hit.
4.3 Designing the Agent Loop: Stopping, Memory and Errors →

Context management

Compact tool outputs, summarise or drop used results, keep notes outside the context.
4.3 Designing the Agent Loop: Stopping, Memory and Errors →

Prompt injection

Text the model reads can act as instructions. Indirect injection hides in emails, pages and files.
4.4 Agent Safety: Prompt Injection and Permissions →

The lethal combination

Private data + untrusted content + a way to send data out. Remove one leg by design.
4.4 Agent Safety: Prompt Injection and Permissions →

Evals

Eval sets, retrieval metrics, judges and production evaluation.

Error analysis

Label 30–50 failures by root cause, count, fix the biggest bucket, add the cases to the eval set.
3.3 Why RAG Fails: A Debugging Guide →

What an eval is

A fixed set of test inputs with expected answers or criteria, scored automatically after every change.
5.1 Why Evals Come First →

Eval set recipe

Real client inputs; common, edge and should-refuse cases; tags; start with 50–100, grow with every bug.
5.1 Why Evals Come First →

Judge prompt rules

One criterion; pass/fail or a defined 1–3 scale; reasoning then verdict; structured output; give it the sources.
5.3 LLM-as-a-Judge →

Judge biases

Position, length, self-preference, leniency. Swap orders, reward concision, use another model, require evidence.
5.3 LLM-as-a-Judge →

RAG metrics

Context recall, faithfulness, answer relevance, correctness, refusal accuracy, citation accuracy.
5.4 Evaluating RAG and Agents in Production →

Agent metrics

Task success on end state, steps, cost, latency, tool-call accuracy, safety violations. Run tasks several times.
5.4 Evaluating RAG and Agents in Production →

Production

Architecture, cost, compliance, observability and handover.

Where RAG money goes

In RAG most of the bill is input tokens (context). Trim retrieved text before shortening answers.
1.3 Tokens, Cost and Latency →

Failure handling

Timeouts, retries with exponential backoff + jitter on transient errors, a tested fallback model, graceful degradation.
6.1 Production Architecture →

Keys stay on the server

Never call the LLM from the browser. The backend holds keys, authenticates users and enforces limits.
6.1 Production Architecture →

Prompt caching

Stable prefix first (system prompt, tools, fixed docs), changing content last. Cached tokens are billed at a steep discount.
6.2 Controlling Cost: Caching, Routing and Budgets →

Client data questions

Where does data go? Used for training? How long kept? Who can see it? Have written answers.
6.3 Security, Privacy and Compliance →

GDPR checklist

DPA with provider, lawful transfers (EU region helps), minimise and redact, retention schedule, deletion on request.
6.3 Security, Privacy and Compliance →

What a trace records

Message, rewritten query, chunk IDs and scores, prompt version, model and parameters, tool calls, answer, tokens, latency, cost.
6.4 Observability and Handover →

Safe changes

Versioned prompts, pinned models, evals in CI, canary rollout, one-step rollback.
6.4 Observability and Handover →

Handover pack

Architecture doc, eval report, runbook, operating procedures, service levels, training and a first-months plan.
6.4 Observability and Handover →

Comparisons

Side-by-side differences between ideas that are easy to mix up.

Prompting vs RAG vs fine-tuning

Prompting changes instructions; RAG changes the facts per request; fine-tuning changes the weights.
1.4 Prompting, RAG or Fine-tuning? →

Keyword vs semantic search

Keyword: exact terms, codes, names. Semantic: meaning, paraphrases, synonyms. Combine them for production.
2.1 Embeddings: Meaning as Vectors →

pgvector vs vector database

pgvector: already on Postgres, up to millions of chunks, one system. Dedicated DB: tens of millions, high QPS.
2.3 Vector Indexes and Nearest-neighbour Search →

Bi-encoder vs cross-encoder

Bi-encoder: embeds query and chunk separately, fast, for retrieval. Cross-encoder: reads both together, accurate, for reranking.
2.4 Hybrid Search and Reranking →

Multi-query vs HyDE

Multi-query: several phrasings, fused with RRF. HyDE: search with the embedding of a hypothetical answer.
3.4 Beyond Basic RAG: Query Rewriting, Filters and Freshness →

Workflow vs agent

Workflow: code fixes the steps (predictable, cheap). Agent: the model picks steps in a loop (flexible, costly).
4.2 Workflows versus Agents →

Faithful vs correct

Faithful: supported by the retrieved sources. Correct: matches the truth. An outdated source gives faithful but wrong.
5.4 Evaluating RAG and Agents in Production →

Request vs queue

Interactive chat: stream in the request. Long or bulk work: queue + workers, resumable, notify when done.
6.1 Production Architecture →

Common traps

Mistakes that cost clients money or trust, and the correct approach.

The model has no memory

Each API call is stateless. Chat history exists only because the app resends it inside the context window.
1.1 What an LLM Actually Does →

Schema ≠ truth

A JSON schema guarantees shape, not correct values. Check values against your data and with evals.
1.2 Prompts, Roles and Structured Output →

"Train it on our docs"

Usually means RAG: grounded answers with sources. Fine-tuning is a poor way to store changing facts.
1.4 Prompting, RAG or Fine-tuning? →

One space per model

Query and documents must use the same embedding model. Changing models means re-embedding everything.
2.1 Embeddings: Meaning as Vectors →

Fake citations

Check every cited [n] exists among the sources you sent. Catch it in code, not in production.
3.2 Building the Prompt: Context, Citations and Refusals →

Prompt-tweaking retrieval bugs

If the evidence was never retrieved, no prompt or model change can fix the answer.
3.3 Why RAG Fails: A Debugging Guide →

Prompt is not access control

Filter by user permissions in the search itself, so forbidden chunks are never retrieved.
3.4 Beyond Basic RAG: Query Rewriting, Filters and Freshness →

Uncaught tool errors

Return errors to the model as tool results it can act on; an exception kills the run.
4.3 Designing the Agent Loop: Stopping, Memory and Errors →

Prompts are not security

Enforce limits in code and permissions: least privilege, approval for actions, allow-listed outputs.
4.4 Agent Safety: Prompt Injection and Permissions →

Agreement is not enough

With mostly passing answers, "always pass" agrees highly. Check how many real failures the judge catches.
5.3 LLM-as-a-Judge →

Semantic cache collisions

Similar questions can need different answers. Strict thresholds, scoped caches, expiry on document change.
6.2 Controlling Cost: Caching, Routing and Budgets →