AAI Agentic Handbook
Volume I

LLM Foundations

What a language model is, how it is trained, and what actually happens when it answers.

Sections

Interview questions answered at staff level

01

How LLMs work

Tokens, transformers, prompting and why models make things up.

10 questions
02

Training, tuning & inference

Pretraining, fine-tuning, RLHF, and the economics of serving a model.

10 questions

Read first

Blog posts for this volume, easiest first

What happens when you ask an AI a question

From pressing enter to the last word: tokens, the desk the model reads from, one-token-at-a-time writing, thinking, web search, and where your words go.

The three dials: tokens, temperature and context

Two bugs show up in nearly every first LLM integration. Both trace back to the same three settings, and both are fixable in a few lines of code.

Prompt, retrieve or fine-tune? A decision guide

Diagnose the failure first, then pick the technique. A worked claims-triage case shows where fine-tuning pays in 2026: cost, not knowledge.

The real cost of an LLM feature: latency, tokens and the bill

Five terms make up the bill and two make up the wait. Reasoning tokens, cache writes, batch discounts and the self-host break-even, worked with stated assumptions.

Thinking models, explained without the hype

What a reasoning model does with its extra time, why the same question can cost ten times more and take forty seconds longer, and a simple rule for when that is worth it.

Structured outputs that don't break

Getting JSON out of a model is easy; getting JSON your code can trust on every call is a system. Schemas, provider structured-output modes versus prompting, validation with targeted retries, and rendering partial JSON while it streams.

Self-host or API? A break-even memo with the maths shown

A decision memo for serving Open-weights vs closed models models yourself versus paying per token, with every price, throughput and headcount stated as an assumption, a cost-versus-volume curve, and a calculator you can rerun with your own numbers.

Key terms

44 pages with diagrams and quizzes

Large Language Model (LLM)Budding

A transformer trained to predict the next token over trillions of tokens, then tuned to follow instructions: the engine under chat, agents and RAG.

TokenBudding

The unit an LLM reads and writes: a word or word fragment. Context limits, latency and price are all metered in tokens, not characters.

Context windowBudding

The maximum number of tokens, prompt plus output, a model can handle in one call. Anything outside it does not exist for the model.

Prompt & system promptBudding

The full input sent to an LLM: instructions, examples, retrieved context and the user's message. The main lever for controlling behaviour.

Parametric knowledgeMid

Facts an LLM absorbed into its weights during training: broad but frozen at the cutoff, unattributable, and impossible to update or delete one at a time.

HallucinationBudding

When an LLM states something fluent and confident that is false or not supported by its sources.

Fine-tuningMid

Continuing to train a pretrained model on your own examples to change its behaviour, format or style. Not a reliable way to add facts.

Retrieval-Augmented Generation (RAG)Budding

Retrieval-augmented generation: fetch relevant documents for a question, put them in the prompt, and have the LLM answer from them with citations.

CorpusBudding

The full collection of documents a retrieval system can search: the source of truth that RAG answers are built from.

AttentionMid

The transformer mechanism that lets each token weigh every earlier token in the context when building its representation.

Prompt cachingMid

Reusing the model's computed state for an identical prompt prefix across requests: cheaper, faster input for repeated context, minus a cache-write premium.

Structured output / decodingSenior

Constraining generation so output always matches a schema or grammar (e.g. valid JSON) by masking tokens that would break it.

Model distillationSenior

Training a smaller, cheaper student model to imitate a larger teacher model's outputs on your task.

Multimodal & vision modelsMid

Models or pipelines that handle more than text, such as images, scanned PDFs, audio or video, in the same input or index.

Text-to-SQLSenior

Having an LLM translate a natural-language question into a SQL query, run it under a restricted role, and answer from the result.

Agentic RAGSenior

RAG where the LLM decides what to retrieve, from which source, and when to search again, in a bounded loop instead of one fixed retrieval step.

LLM-as-judgeSenior

Using an LLM with a rubric to grade outputs (faithfulness, relevance, correctness) so evaluation scales beyond human review.

Neural networkBudding

A function built from layers of weighted sums and non-linearities whose weights are learned from examples by gradient descent; the machinery under every LLM.

Parameters & weightsBudding

The learned numbers (weights and biases) inside a model. '70B' means 70 billion of them; they set memory and compute cost, not quality on their own.

TransformerBudding

The architecture behind nearly all modern LLMs: stacked attention and feed-forward blocks that process every token of a sequence in parallel.

PretrainingBudding

The first and most expensive training phase: a model learns language and world knowledge by predicting the next token across trillions of tokens.

Next-token predictionBudding

The single task an LLM is trained on and runs at inference: given the text so far, assign a probability to every possible next token.

Training dataBudding

The text, code and examples a model learns from; mix, quality, recency and licensing decide what it knows and how it behaves.

Scaling lawsMid

Empirical power laws: loss falls predictably as parameters, data and compute grow, with diminishing returns per extra 10× of compute.

Instruction tuningMid

Supervised fine-tuning on (instruction, good response) pairs that turns a base model that continues text into an assistant that follows requests.

RLHF (reinforcement learning from human feedback)Mid

Reinforcement learning from human feedback: train a reward model on human preference comparisons, then optimise the LLM to score highly on it.

Preference optimization (DPO)Senior

Methods like DPO that train directly on chosen-vs-rejected answer pairs, getting RLHF-like alignment without a reward model or RL loop.

LoRA & parameter-efficient fine-tuningMid

Low-Rank Adaptation: fine-tune by training small add-on matrices while the original weights stay frozen; cheap, fast, swappable per task or tenant.

In-context learningBudding

A model adapting to a task purely from instructions and examples in its prompt, with no change to its weights.

Few-shot promptingBudding

Including a handful of worked input-output examples in the prompt so the model copies the format, labels and style you want.

Chain-of-thoughtMid

Having a model write intermediate reasoning steps before its final answer, which improves accuracy on multi-step problems at a token cost.

Reasoning models & extended thinkingMid

Models trained with RL to think at length before answering, trading latency and output tokens for accuracy on maths, code and multi-step work.

Temperature & samplingBudding

A sampling setting that sharpens (low) or flattens (high) next-token probabilities, trading consistency for variety; it does not change what the model knows.

Top-p (nucleus) samplingMid

Nucleus sampling: sample only from the smallest set of tokens whose probabilities add up to p (e.g. 0.9), cutting off the unlikely tail.

Logits & probabilitiesMid

The raw scores a model outputs for every token in its vocabulary; softmax turns them into next-token probabilities.

InferenceBudding

Running a trained model to produce output. For LLMs: a compute-bound prefill over the prompt, then a memory-bound decode loop, one token per step.

KV cacheMid

Stored attention keys and values for past tokens, so each new token skips recomputing the sequence; at long context it fills GPU memory.

Model quantizationMid

Storing weights (and sometimes activations or KV) in 8 or 4 bits instead of 16 to cut memory and speed up inference, at a quality cost you must measure.

Time to first token (TTFT)Mid

Latency from sending a request until the first output token arrives; the main driver of how responsive a streaming LLM app feels.

Batching & throughputSenior

Running many requests through the GPU together so one weight read serves many tokens: throughput and cost per token improve, per-stream speed falls.

Speculative decodingSenior

A cheap draft proposes several tokens and the big model verifies them in one pass: same output distribution, fewer sequential big-model steps.

Mixture of experts (MoE)Senior

An architecture where each token is routed to a few of many expert sub-networks, so a huge model computes like a much smaller one per token.

Open-weights vs closed modelsMid

Open-weights models publish their parameters for self-hosting; closed models are API-only. The choice trades control and residency for convenience.

Knowledge cutoffBudding

The date after which a model's training data ends; it knows nothing newer unless you supply it in the prompt or through tools.