Skip to content

Lesson 1 of 40How AI works

How LLMs Work

Understand next-token prediction, training, temperature and hallucination well enough to predict when an AI model will help and when it will fail.

15 min read0/5 questions

A large language model (LLM) like Claude feels like it understands you. Under the hood it does one thing, over and over: it looks at the text so far and predicts what comes next. Everything else, from answering questions to writing code, grows out of that single trick done at enormous scale. Once you see this clearly, a lot of AI behaviour stops being mysterious: why the same question gets different answers, why models invent things with total confidence, and why giving more context so often helps. This lesson gives you that mental model, which every later lesson in this course builds on.

One word at a time

Type "The capital of France is" and ask yourself what comes next. You almost certainly thought "Paris". You did not look it up; you have seen that pattern many times. An LLM does the same thing, except it does it with maths instead of memories.

Given some text, the model outputs a probability for every possible next piece of text. For "The capital of France is", it might give "Paris" 97%, "a" 1%, "the" 0.5%, and tiny amounts to thousands of other options. It then picks one, adds it to the text, and repeats. A 500-word answer is 500-ish rounds of "predict, pick, append".

Strictly, models predict tokens, chunks of text that are often a whole short word or part of a longer one. For this lesson, "word" is close enough. You will see exactly what tokens are, and why they matter for cost, in the Tokens and Context lesson.

How a reply gets written
Your textModelReply so farWhy is the skyblue 92%, grey 4%...Why is the sky blue? 88%, and 6%...

The model reads everything so far: your prompt plus anything it has already written.

1/4

Notice what is missing. There is no step where the model checks a database of facts, and no step where it plans the whole answer and then writes it out. Each token is chosen based on the text before it. That is the root of both the magic and the mistakes.

A toy model you can run

Real models are huge, but the core idea fits in a few lines. This "bigram model" learns by counting which word follows which in a tiny piece of text. Then it predicts the next word using those counts as probabilities. Run it, then change corpus and run it again.

Python
import randomfrom collections import Counter, defaultdict corpus = """the cat sat on the mat . the cat ate the fish .the dog sat on the rug . the dog chased the cat .the cat sat on the sofa . a dog ate the bone .""" # "Training": count which word follows which.words = corpus.split()follows = defaultdict(Counter)for current, nxt in zip(words, words[1:]): follows[current][nxt] += 1 def next_word_probs(word): counts = follows[word] total = sum(counts.values()) return {w: c / total for w, c in counts.most_common()} print("After 'the':")for w, p in next_word_probs("the").items(): print(f" {w:<5} {p:.0%}") def sample(word, temperature): probs = next_word_probs(word) # Temperature reshapes the odds: low sharpens, high flattens. weights = [p ** (1 / temperature) for p in probs.values()] return random.choices(list(probs), weights=weights)[0] def generate(start, temperature, length=8): out = [start] for _ in range(length): nxt = sample(out[-1], temperature) out.append(nxt) if nxt == ".": break return " ".join(out) random.seed(4)for t in (0.1, 1.0, 2.0): print(f"\ntemperature {t}:") for _ in range(3): print(" ", generate("the", t))
Output
Press Run (⌘ Enter) to see what happens.

Three things to notice in the output:

  1. "cat" is the most likely word after "the" because it appeared most often. The model has no idea what a cat is. It only knows patterns in its training text.
  2. At low temperature it gets stuck in a loop ("the cat sat on the cat sat on"). Always taking the top choice is not the same as making sense.
  3. "the cat sat on the bone" is grammatical, plausible, and never appeared in the training text. The model generated something new by stitching patterns together. That is creativity and hallucination from the same source.

A real LLM looks at thousands of previous tokens instead of one word, and instead of a table of counts it uses a neural network with billions of numbers. But the job is the same.

Predict the outputPython

What does this print?

counts = {"cat": 3, "dog": 1}
print(counts["cat"] / sum(counts.values()))
Need a nudge? Hints walk you through it.

Training and inference

There are two very different phases in a model's life.

Training is how the model is built. It happens once (per model version), takes months, and costs a great deal of computing power. Inference is using the finished model: every time you send a message, the model runs inference to produce a reply. Inference does not change the model. Chatting with Claude does not teach that model anything new; it only sees what is in the current conversation.

The thing training produces is a set of parameters, also called weights: a huge list of numbers inside the neural network. In our toy model the "weights" are the counts in follows. In a real model they are billions of numbers that nobody wrote by hand. Training starts them random and nudges each one, trillions of times, so the model gets slightly better at predicting the next token of real text. Knowledge, grammar, coding style and facts all end up encoded, blurrily, in those numbers.

Training itself has two big stages:

  • Pretraining. The model reads a vast amount of text (web pages, books, code) and learns to predict the next token. The result is a powerful autocomplete. Ask it "How do I reverse a list in Python?" and it might continue with three more questions, because on forum pages questions are often followed by more questions.
  • Post-training. The model is then trained further to behave like a helpful assistant. Instruction tuning shows it many examples of a request followed by a good answer. Then feedback training (often called RLHF, reinforcement learning from human feedback) has it produce several answers, has people or other models judge which is better, and nudges the weights towards the preferred style: helpful, honest, safe, and well formatted.

So the assistant you talk to is still a next-token predictor. Post-training just changed which continuations it finds most likely: "a clear answer to the question" now beats "more forum questions".

From raw text to assistant
Text and code: web, books, reposText and codeweb, books, reposPretraining: predict next tokenPretrainingpredict next tokenBase model: clever autocompleteBase modelclever autocompletePost-training: examples, feedbackPost-trainingexamples, feedbackAssistant: what you chat withAssistantwhat you chat withYou: inference: promptsYouinference: promptstrainweightstuned weightsmessage

Pretraining turns a huge pile of text into weights. The result predicts text well but does not follow instructions reliably.

1/3
Quick check
Yesterday you told a chatbot your project uses Postgres. Today, in a brand new conversation with no memory feature, it suggests MySQL. Why?
Need a nudge? A hint rules out a wrong answer.

Temperature and why answers vary

At each step the model has a probability for every candidate token. It still has to choose one. That choice is called sampling, and the main knob controlling it is temperature.

  • Low temperature (near 0) makes the top choice dominate. Output is focused and repetitive, close to "always pick the most likely".
  • Temperature around 1 samples roughly in proportion to the probabilities. Output is varied and natural.
  • High temperature flattens the odds, so unlikely tokens get picked more. Output becomes surprising, then incoherent.

This is why asking the same question twice gives two different answers. Nothing is broken: the model is rolling weighted dice at every token, and one different early token sends the rest of the reply down a different path. For a developer, the lesson is practical: one good answer does not prove a prompt is reliable. Try it several times before you trust it.

Hallucination is a feature of prediction

A hallucination is a fluent, confident answer that is false: a function that does not exist, a fake citation, a wrong date. It is not a bug someone forgot to fix. It is the natural result of the mechanism you just ran.

The model is trained to produce likely-looking text, and "likely-looking" and "true" usually overlap, but not always. Ask for the method that converts a pandas DataFrame to a list of dictionaries and you get df.to_dict("records"), which is real, because that pattern appears constantly in training data. Ask about a small library's API from a version released after training, and the model still produces something shaped like a correct answer, because the shape is what it learned. There is no internal alarm that says "I have not seen this".

Hallucinations are more likely when:

  • the topic is rare or niche, so the model saw few examples,
  • the facts changed after training (new library versions, new prices),
  • you ask for exact details: numbers, quotes, URLs, version-specific flags,
  • the prompt assumes something false ("Why does Python's list.sortBy return None?") and the model goes along with it.

The fix is not to distrust everything. It is to give the model the facts it needs (paste the docs, show the file) and to check anything that matters. The Trust but Verify lesson covers that in depth.

Quick check
Which request is MOST likely to produce a confident hallucination?
Need a nudge? A hint rules out a wrong answer.

What "thinking" adds

Because each token is predicted from the tokens before it, the text the model writes becomes part of its own input. If it writes out intermediate steps first ("the list has 7 items, so the middle index is 3..."), those steps are now in the context and make the final answer more likely to be right. A model asked to blurt out the answer to a multi-step maths problem has to do all the work inside a single prediction.

Modern models are post-trained to do this on purpose. With extended thinking (often called reasoning), the model writes a scratchpad of reasoning before its final answer: exploring approaches, checking its work, backtracking. On current Claude models, thinking is adaptive, meaning the model decides how much to think for each request, and an effort setting lets you dial that up or down. You will tune that dial in the Choosing a Model lesson.

Thinking helps most with maths, multi-step logic, tricky debugging and planning. It adds little to "translate this sentence", and it costs time and tokens either way. It also does not make the model a fact database: careful reasoning built on a hallucinated API is still wrong.

Match the pairs0/5 matched

Match each idea to what it means.

Choose an item, then its match on the other side.
Put it in order4 steps

Put the steps of generating one token in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

How this course is laid out

  • How AI works: tokens, context, prompting and choosing a model, the mental model behind everything else.
  • Learning with AI and AI coding tools: using AI as a tutor, checking its work, then Claude Code, Copilot and context engineering in a real codebase.
  • Agents and Quality loops: building agents, skills and MCP servers, then the build, test and review loop that makes AI code worth merging.
  • AI in production and Building LLM systems: structured output, RAG, evals, security, guardrails and observability for features real users rely on.
  • AI at work: policy, governance, careers and a capstone that builds one feature end to end.

By the end you can build with AI tools and ship AI features on a team. The course closes with a short wrap-up.

Key terms
large language model (LLM)
A neural network trained on huge amounts of text to predict the next token.
next-token prediction
The core task: given text so far, output probabilities for what comes next.
parameters (weights)
The billions of learned numbers inside the model that encode what it learned.
inference
Running a trained model to produce output. It does not change the weights.
post-training
Extra training, with examples and feedback, that turns a base model into an assistant.
temperature
A sampling setting: low is focused and repetitive, high is varied and random.
hallucination
A fluent, confident output that is false, a natural side effect of predicting likely text.