1. LLM fundamentals
What a large language model is and how it behaves. Tokens, next-token prediction, context windows, sampling and temperature, chat formats, reasoning models, multimodality, cost and latency.
What a large language model is
A large language model (LLM) is a neural network trained to predict the next piece of text. Given “The capital of France is”, it assigns a probability to every possible next token and Paris gets most of it. Generation is just this step repeated: pick a token, append it, predict again. This is called autoregressive generation.
Modern LLMs are transformers (Vaswani et al., 2017, Attention Is All You Need). The key mechanism, attention, lets every token look at every earlier token and decide which ones matter, which is how a model connects a pronoun to its noun three paragraphs back.
Training happens in stages:
- Pre-training on trillions of tokens of text and code: the model learns language, facts and patterns by predicting the next token.
- Instruction tuning (supervised fine-tuning) on examples of instructions and good answers: the model learns to follow requests.
- Preference tuning (RLHF, reinforcement learning from human feedback, or related methods): the model learns which answers people prefer, and to refuse harmful requests.
- For reasoning models, additional reinforcement learning rewards correct multi-step reasoning on checkable problems such as maths and code.
As an AI engineer you almost never train. You use models through APIs, so what matters is how they behave.
Tokens
Models do not read characters or words; they read tokens: chunks of text from a fixed vocabulary, typically 50,000–200,000 entries. Common words are one token; rare words split into several (unbelievable might be un, believ, able). A rough rule for English: 1 token ≈ 4 characters ≈ ¾ of a word. Other languages and code often use more tokens per word.
Tokens matter because everything is measured in them:
- Price: providers charge per million input tokens and per million output tokens (output is usually several times more expensive).
- Limits: the context window and
max_tokensare in tokens. - Latency: output is generated token by token, so long answers take longer.
The context window
The context window is the maximum number of tokens the model can consider at once: system prompt + conversation + retrieved documents + tool results + the answer being generated. Modern models offer from 128k to over a million tokens.
Bigger is not free:
- Every input token costs money and adds latency on every call.
- Models use the middle of a long context less reliably than the start and end (Liu et al., 2023, Lost in the Middle).
- Irrelevant context distracts the model and can lower answer quality.
So the core skill of AI engineering is context engineering: putting the right information in the window, not all of it. Retrieval (chapters 5–6), compression, summarisation and memory are all context engineering.
Sampling: temperature and friends
At each step the model produces a probability distribution over tokens. Sampling picks one:
| Parameter | Effect |
|---|---|
| Temperature | Rescales the distribution. 0 = almost always the most likely token (near-deterministic). 0.7–1.0 = more varied. High values = creative but error-prone. |
| Top-p (nucleus) | Sample only from the smallest set of tokens whose probabilities add up to p (e.g. 0.9). |
| Top-k | Sample only from the k most likely tokens. |
| Max tokens | Hard cap on output length. |
| Stop sequences | Stop when a given string appears. |
Rules of thumb: use low temperature (0–0.3) for extraction, classification, SQL and factual answers; higher (0.7+) when you want diversity, for example sampling several candidate answers for self-consistency or proposing alternatives in tree-of-thought search.
Even at temperature 0, outputs are not perfectly deterministic across calls, because of batching and floating-point effects on the provider’s side. Design for variation.
Chat format and roles
APIs expose models as chat: a list of messages with roles:
- system: instructions and persona that frame everything (You are a support assistant. Answer only from the sources.);
- user: the request;
- assistant: the model’s previous replies;
- tool: results of tool calls the model requested (chapter 3).
The model is stateless: each request must contain the whole conversation you want it to consider. “Memory” in a chat app is the application re-sending history (chapter 10).
Reasoning models
Reasoning models (for example Gemini 3.x thinking models, Claude with extended/adaptive thinking, OpenAI’s o-series and GPT-5-class reasoning models, DeepSeek-R1) generate hidden reasoning tokens before the visible answer. They are much better at multi-step problems (maths, code, planning) at the cost of latency and tokens.
Practical consequences:
- Thinking consumes
max_tokens. A cap of 16 or 200 tokens may be entirely spent thinking, leaving an empty answer. Give reasoning models room (1,000–4,000+). - Reasoning effort controls how long they think. Lower effort is faster and cheaper, higher effort is more accurate on hard problems. Providers expose it differently (OpenAI
reasoning_effort, Anthropic effort, Gemini thinking level, OpenRouterreasoning.effort). - Hand-crafted step-by-step prompting matters less with these models, since they already reason internally.
Multimodality
Many models accept images (and some audio, video or PDFs) alongside text. Vision models can describe images, read charts and screenshots, and answer questions about them. OCR (optical character recognition) is a separate, cheaper technique that only extracts text from images and runs locally.
Hallucination
LLMs generate plausible text; plausibility is not truth. A hallucination is a fluent, confident statement that is false or unsupported: an invented citation, a wrong number, a nonexistent API. It happens because the model’s training objective rewards likely-sounding text, and because its knowledge is frozen at a training cut-off and has gaps.
Mitigations, in rough order of power:
- Grounding: put the facts in the context (RAG) and instruct the model to answer only from them and say I don’t know otherwise.
- Tools: let the model compute (calculator, code), look up (search, SQL) or check the date instead of guessing.
- Citations that the system verifies.
- Verification: guards, critics, judges and evaluation.
- Lower temperature for factual tasks.
Cost and latency
| Driver | Lever |
|---|---|
| Input tokens | Retrieve less but better; compress context; cache stable prompt prefixes (prompt caching) |
| Output tokens | Ask for concise answers; cap max_tokens sensibly |
| Model choice | Route easy requests to small, cheap models (model routing) |
| Number of calls | Prefer fixed pipelines to agents when the path is known; bound agent turns |
| Reasoning | Lower reasoning effort where depth is not needed |
| Perceived latency | Stream tokens so users see progress immediately |
Time to first token (TTFT) and tokens per second are the two latency numbers that matter; reasoning models have a long TTFT because they think first.
Choosing a model
- Capability vs cost: frontier models for hard reasoning and agents, small fast models for classification, routing, extraction and summarisation.
- Tool calling quality matters for agents.
- Context window and multimodality if you need them.
- Data and hosting constraints: a provider’s own API (data processing agreements, regions), or local open-weight models (Llama, Qwen, Mistral, Gemma) via Ollama when data must stay on your machine.
- Measure on your task. Public benchmarks are a starting point; your evaluation set decides (chapter 12).
Try it in AgenticMind
- LLM node: set
provider,model,temperature,max_tokens,reasoning_effortand asystem_prompt. See Models and providers. - Model Router: route each request to a cheap or a strong model automatically.
- Watch tokens and cost per answer in Chat, and per node in the Trace.
- Template LLM assistant (mock provider) runs with no key; switch the provider to compare models.
Key takeaways
An LLM predicts the next token. Everything is measured in tokens: price, limits and latency. The context window is precious, so put the right information in it. Temperature controls randomness. Reasoning models think before answering and need room in max_tokens. Hallucination is the default failure mode; grounding, tools and verification are the cure.

