The new building blocks
| Block | What it does | Think of it as |
|---|---|---|
| LLM | Generates text (or code, or tool calls) from a prompt | A very capable, slow, expensive, occasionally wrong function |
| Embedding model | Turns text, images or items into vectors of meaning | A coordinate system where similar things sit close together |
| Vector index | Finds the nearest vectors to a query, approximately | A search engine for meaning |
| Prompt / context builder | Assembles instructions, retrieved facts and history | The briefing you hand to the model |
| Tools / function calls | Let the model call your APIs (search orders, book a slot) | Giving the assistant hands, carefully |
| Guardrails | Filter inputs and outputs for safety, policy and format | A bouncer and an editor |
| Evaluator | Measures answer quality on test sets and live traffic | Unit tests for fuzzy behaviour |
An LLM is a brilliant new hire with no access to your company wiki and a tendency to bluff when unsure. RAG hands them the right pages before each question. Tools let them look things up in your systems. Guardrails are the compliance review. Evaluation is the performance review that tells you whether any of it is working.
Embeddings and vector search, quickly
An embedding is a list of numbers (often 384–3,072 of them) representing meaning. "How do I reset my password?" and "forgot login credentials" land close together even though they share no words. Similarity is usually cosine similarity or dot product.
Comparing a query with every stored vector is exact but slow beyond a few million. Approximate nearest neighbour (ANN) indexes trade a little recall for big speedups:
| Index | Idea | Strengths | Costs |
|---|---|---|---|
| HNSW | Layered "small world" graph; greedy walk toward the query | Excellent recall and latency | Memory-hungry; slower inserts |
| IVF | Cluster vectors; search only the closest clusters | Less memory; tunable | Recall depends on clusters probed |
| PQ / quantisation | Compress vectors into short codes | 4–30× less memory | Lower precision; re-rank needed |
| DiskANN-style | Graph index mostly on SSD | Billions of vectors on one machine | More engineering |
Memory maths: 100 million vectors × 768 dimensions × 4 bytes ≈ 307 GB raw, before index overhead. Quantising to 1 byte per dimension cuts it to ~77 GB. This is why vector search at scale is often a memory and sharding problem.
Hybrid retrieval
Pure vector search misses exact matches (order IDs, error codes, product SKUs); pure keyword search misses paraphrases. Production systems run both (BM25 keyword + vector), merge the results (for example with reciprocal rank fusion), then apply a re-ranker: a slower, more accurate model that re-scores the top 50–100 candidates.
RAG end to end
Retrieval-augmented generation (RAG) answers questions from your data: retrieve relevant passages, put them in the prompt, and ask the model to answer only from them, citing sources.
Ingestion (offline)
- Connectors pull documents from sources, ideally via change events so the index stays fresh (Stream Processing and Change Data Capture (CDC) Explained).
- Parse and clean: extract text from PDFs and HTML, drop boilerplate, keep headings.
- Chunk: split into passages of a few hundred tokens with some overlap, respecting section boundaries. Chunks too small lose context; too large dilute relevance and waste prompt space.
- Embed each chunk; store the vector with metadata: source, URL, timestamps, tenant, and access-control lists.
- Re-index when the embedding model changes: every vector must come from the same model as the query embedding, so model upgrades mean a full re-embed (plan it like a migration).
Query (online)
- Optionally rewrite the question (resolve "it" from chat history, expand acronyms).
- Retrieve with hybrid search, filtered by the user's permissions inside the query.
- Re-rank and keep the best few chunks within the token budget.
- Generate with instructions such as "answer only from the sources; say you don't know otherwise; cite sources".
- Post-process: check citations, apply output guardrails, stream to the user.
Filtering permissions after retrieval or, worse, trusting the model to "not mention" restricted documents. If a chunk reaches the prompt, assume it can reach the user. Enforce access control as a filter in the index query, exactly like a tenant_id filter in SQL.
Serving LLMs: tokens are the unit of everything
Models read and write tokens (roughly ¾ of an English word). Cost, latency and limits are all measured in tokens.
- Time to first token (TTFT): how long until the answer starts appearing. Dominated by processing the prompt ("prefill").
- Tokens per second (TPS): how fast the rest streams ("decode"). A 500-token answer at 50 TPS takes 10 seconds.
- Context window: the maximum tokens of prompt plus output. Long prompts are slower and costlier.
That's why chat products stream responses (SSE or WebSockets, Long Polling vs WebSockets vs Server-Sent Events): the user sees progress after the TTFT instead of waiting for the full answer.
Self-hosting vs API
| Hosted API | Self-hosted open model | |
|---|---|---|
| Time to launch | Hours | Weeks |
| Quality ceiling | Highest-end models | Good and improving; smaller models |
| Cost model | Per token | Per GPU-hour, whether busy or not |
| Data control | Provider terms | Full |
| Ops burden | Low | High: GPUs, scaling, upgrades |
If you self-host, the serving tricks that matter:
- Continuous batching: GPU throughput comes from processing many requests together; modern servers (vLLM, TGI, TensorRT-LLM) add and remove requests from the batch at every step.
- KV cache: the model's memory of the processed prompt. It's large (often gigabytes per long conversation), and managing it (paging, reuse across requests with the same prefix) is the core of serving efficiency.
- Quantisation: 8-bit or 4-bit weights fit bigger models on fewer GPUs with modest quality loss.
- Autoscaling on queue depth and tokens in flight, not CPU. GPUs take minutes to start and load weights, so keep warm capacity for peaks.