How Generative AI Works
An accurate beginner's mental model of modern AI: LLMs as next-token predictors, the pretraining to instruction tuning to RLHF recipe, multimodal and reasoning models, tool-using agents, and what they still cannot do.
In the last lesson you trained a model with a simple loop: predict, measure loss, adjust, repeat. Remarkably, the systems that write essays, explain code, and analyse images are built on exactly that loop, run at enormous scale with one specific prediction task. This lesson gives you an accurate mental model of modern generative AI: what a large language model (LLM) actually computes, how it is turned into a helpful assistant, what multimodal, reasoning, and agentic models add, and where all of them still break. Everything later in the course, from prompting to fine-tuning to cost optimization, builds on this picture.
Step 1: text becomes tokens
A model cannot read letters directly; it works with numbers. Text is first split into tokens: common words, word pieces, punctuation, and spaces. A frequent word like "the" is usually one token; a rare word may be split into several pieces. Each token has an ID in a fixed vocabulary, typically tens of thousands to a few hundred thousand entries. Try typing into the tokenizer below.
Tokens matter for three practical reasons. Cost and limits are measured in tokens: API prices are per token, and each model has a maximum context window (how many tokens it can consider at once). As a rough rule, English text averages around three quarters of a word per token, but this varies by tokenizer and is often worse for other languages and for code. And quirks: because a model sees "strawberry" as one or two chunks rather than ten letters, character-level tasks like counting letters can trip it up.
Each token ID is then mapped to an embedding, a vector of numbers learned during training, exactly the kind of representation you met in the previous lesson.
Step 2: predict the next token
An LLM is, at heart, a function that takes a sequence of tokens and outputs a score for every token in the vocabulary: how plausible it is as the next token. These raw scores are called logits. A function called softmax turns them into probabilities that sum to 1:
Here is the logit of token , the sum runs over every token in the vocabulary, and is the temperature. Exponentiating (, with ) makes every score positive, and dividing by the total makes them sum to 1. A worked example: suppose after "The cat sat on the" only three candidate tokens matter, with logits 2.0 for "mat", 1.0 for "sofa", and 0.1 for "moon". At :
so the probabilities are about for "mat", for "sofa", and for "moon". At the logits are doubled before exponentiating and "mat" rises to about 0.86; at they are halved and "mat" falls to about 0.50. Then one token is picked, appended to the input, and the whole process repeats. This one-token-at-a-time loop is called autoregressive generation. Play with the temperature slider below.
Low temperature sharpens the distribution toward the most likely token, giving focused, repeatable output. High temperature flattens it, giving more varied, sometimes incoherent output. Temperature 0 (or "greedy" decoding) always takes the top token. This is also why the same question can get different answers: sampling is random by design.
Inside, the model is a transformer: a deep stack of layers in which every token's vector is repeatedly updated by looking at the other tokens in the context (the attention mechanism) and then transforming the result. You will look inside one in Module 07 (Transformers & LLMs). For now, the key insight is that to predict the next token well across all of human writing, a model must implicitly learn grammar, facts, styles, and patterns of reasoning. Prediction at scale forces a great deal of structure into the parameters.
See it in 30 lines
Here is a toy "language model" that predicts the next character from the previous one, by counting. A real LLM replaces counting with a transformer that looks at thousands of previous tokens, but the generation loop is the same.
import numpy as np
text = (
"the cat sat on the mat. the dog sat on the log. "
"the cat saw the dog. the dog saw the cat on the mat. "
) * 20
# 1. "Tokenize": here every character is a token
vocab = sorted(set(text))
idx = {ch: i for i, ch in enumerate(vocab)}
V = len(vocab)
# 2. "Pretrain": count which token follows which (a bigram model)
counts = np.ones((V, V)) # start at 1 so nothing has zero probability
for a, b in zip(text, text[1:]):
counts[idx[a], idx[b]] += 1
logits = np.log(counts) # log-counts play the role of logits
def next_token_probs(ch, temperature=1.0):
z = logits[idx[ch]] / temperature
z = z - z.max() # numerical stability
p = np.exp(z)
return p / p.sum() # softmax
# 3. Inspect the model's prediction after "t"
p = next_token_probs("t")
top = np.argsort(p)[::-1][:3]
print("after 't':", [(vocab[i], round(float(p[i]), 2)) for i in top])
# 4. Generate autoregressively: sample, append, repeat
def generate(start="t", n=60, temperature=1.0, seed=0):
rng = np.random.default_rng(seed)
out = start
for _ in range(n):
p = next_token_probs(out[-1], temperature)
out += vocab[rng.choice(V, p=p)]
return out
for T in (0.2, 1.0, 2.0):
print(f"T={T}: {generate(temperature=T)!r}")
The model predicts "h" after "t" with probability 0.54. At T=0.2 it repeats "the the the" (too greedy); at T=2.0 it produces noise. With only one character of context it cannot do better, which is exactly why real models attend to long contexts.
Putting steps 1 and 2 together, generation is a loop:
The diagram shows autoregressive generation: every new token is fed back in as input for the next prediction, which is why longer answers take longer and cost more, and why an early mistake can steer everything that follows.
Step 3: from raw predictor to helpful assistant
A model trained only to predict web text, called a base model, is knowledgeable but not helpful. Ask it "What is the capital of France?" and it might continue with "What is the capital of Germany?", because lists of quiz questions are common online. Turning it into an assistant takes several training stages.
The diagram shows the modern training recipe as a pipeline: one very expensive pretraining stage builds broad knowledge, then progressively smaller, more targeted stages shape behaviour.
- Pretraining. Next-token prediction over a huge, filtered mix of web pages, books, code, and other data, using cross-entropy loss. This is where nearly all the compute goes and where knowledge and general skills come from.
- Supervised fine-tuning (SFT), also called instruction tuning. The model is trained on curated examples of instructions paired with high-quality responses, written by people or generated and filtered by other models. It learns the format and manner of an assistant.
- Preference tuning. People (or AI systems guided by written principles) compare pairs of responses and pick the better one. In reinforcement learning from human feedback (RLHF), a separate reward model (a second network that scores responses) learns to predict those preferences, and the assistant is then optimized with reinforcement learning to produce responses the reward model scores highly, with a penalty for drifting too far from its starting behaviour. Simpler methods such as Direct Preference Optimization (DPO) learn from the preference pairs directly. This stage is where helpfulness, honesty, tone, and refusing harmful requests are largely shaped.
- Reinforcement learning on verifiable tasks. For maths, code, and tool use, answers can be checked automatically: the proof is valid, the tests pass. Rewarding correct outcomes teaches models to work through problems step by step. This stage is central to reasoning models.
Note: Each stage is an application of the same loop from the previous lesson: predict, score, update. What changes is the data and how the score is defined.
Beyond text: multimodal models
The same machinery works for anything that can be turned into tokens. Images are cut into small patches, each converted into a vector; audio is split into short frames. A multimodal model processes these alongside text tokens in one context, which is how an assistant can read a chart, transcribe a voice note, or answer questions about a photo. Image generation often uses a different family, diffusion models, which learn to turn random noise into an image step by step, though autoregressive image generation is also used. You will meet both later.
Reasoning models: thinking with extra tokens
A plain LLM must produce each answer token after a fixed amount of computation. For hard problems, it helps to write out intermediate steps first, the idea behind "chain-of-thought" prompting. Reasoning models are trained (largely with the reinforcement learning described above) to do this automatically: they generate a long internal chain of reasoning, check and revise partial solutions, and only then answer.
The trade-off is cost and speed: more "thinking" tokens means more computation and latency per answer. This created a second way to scale besides making models bigger, test-time compute: spend more computation at inference for harder questions. Many systems now let you choose a reasoning effort level, or decide automatically.
Tools and agents: models that act
On its own, a model can only produce text. But that text can be a structured request to call a tool: search the web, run Python, query a database, edit a file. The surrounding software executes the tool and feeds the result back into the context, and the model continues. Run that in a loop toward a goal and you have an agent.
The sequence diagram shows one agent task: the model decides which tool to call, the tool runner executes it and returns results, and the model loops until it can answer. The model never touches the database directly; the system controls what tools exist and what they are allowed to do. Coding agents that read a repository, run tests, and propose fixes are the most widely used agents today.
What generative AI still cannot do (reliably)
An accurate mental model includes the limits. These follow directly from how the systems are built.
- Hallucination. The model generates plausible text, not verified facts. When it lacks knowledge, the most "probable-sounding" continuation may be an invented citation or number. Grounding answers in retrieved sources and tools reduces but does not eliminate this.
- Knowledge cutoff. Pretraining data stops at some date. Without a search tool, the model does not know newer events and may not realize it.
- Limited, imperfect context. Models can only consider what fits in the context window, and even within it they may overlook details in long inputs. They have no memory between conversations unless the system provides one.
- Jagged reliability. Excellent at many hard tasks, surprisingly wrong on some easy ones; performance can change with small rewordings. Long, multi-step agent tasks compound small error rates.
- Sycophancy. Preference tuning can reward agreeable answers, so models may tell you what you seem to want to hear. Ask for critique explicitly.
- Prompt injection. Instructions and data share one stream of tokens, so text the model reads (a web page, an email) can try to hijack it. This is a serious security issue for agents.
- No guarantee of faithful explanations. A model's stated reasoning is itself generated text and may not reflect what actually drove its answer.
Tip: The habit that protects you: for anything important, ask "where would this fact come from?" If the answer is "only the model's training", verify it.
Hands-on exercise
- Run the toy bigram model above. Change it to use the previous two characters as context (a trigram: index
countsby the pair). Does the generated text look more like the training text? Explain why in one sentence. - Change
generateto use temperature 0 by always takingnp.argmax(p)instead of sampling. What happens, and why is pure greedy decoding prone to repetition? - In the tokenizer widget, compare the token counts of an English sentence, the same sentence in another language, and a line of code. Which is most expensive?
- Ask a chat assistant a question whose answer changed recently, once with web search off (if possible) and once with it on. Compare the answers and note which parts came from tools.
Expected outcome: you can explain, in your own words, tokens, logits, softmax, temperature, autoregressive generation, the training stages, and at least four limits that follow from them.
Key takeaways
- An LLM turns text into tokens, computes logits for the next token, converts them to probabilities with softmax, samples one, and repeats.
- Pretraining on next-token prediction builds knowledge; SFT teaches the assistant format; preference tuning (RLHF, DPO) shapes helpfulness and safety; RL on checkable tasks builds reasoning.
- Multimodal models tokenize images and audio too; reasoning models trade extra inference compute for accuracy.
- Agents are models in a loop with tools, controlled by surrounding software.
- Limits follow from the design: hallucination, knowledge cutoffs, context limits, jagged reliability, sycophancy, and prompt injection.
Next, we zoom out to the real world: where these systems deliver value today, how they fail in deployment, and how to separate hype from evidence.
Further reading
- Andrej Karpathy, "Intro to Large Language Models" (2023 talk, YouTube) and his video "Deep Dive into LLMs like ChatGPT" (2025): clear, accurate overviews of the training pipeline.
- Ouyang et al., "Training language models to follow instructions with human feedback" (2022): the InstructGPT paper that popularized RLHF for assistants.
- Rafailov et al., "Direct Preference Optimization: Your Language Model is Secretly a Reward Model" (2023).
- DeepSeek-AI, "DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning" (2025): an openly described recipe for training a reasoning model.
Save your progress and earn XP
Create a free account to take the quiz, track progress and unlock badges.