LESSON 8 · UNDERSTANDING LLMs

How LLMs Work

An LLM turns text into tokens, maps those tokens into numerical representations, processes them through many neural-network layers, and repeatedly predicts the next token to generate an answer.

20 min readBeginnerGenerative AI

By the end of this lesson, you will be able to:

  • Trace the main path from text input to generated output.
  • Explain why tokenization and embeddings are needed.
  • Understand the high-level role of Transformer layers and attention.
  • Describe next-token prediction and autoregressive generation.
  • Use Python to call an LLM and reason about what happens around the API call.
1

The big picture

When you send a prompt to an LLM, the model does not receive your sentence as raw English characters. The system converts the text into tokens, turns those tokens into numerical representations, processes them through the model, and produces probabilities for what should come next.

1Text“Explain APIs simply”
2Tokenstext fragments / IDs
3Representationsvectors the network can process
4Transformerattention + neural layers
5Next tokenone token is selected
Think of it as a pipeline: text → tokens → numerical representations → neural-network processing → next-token probabilities → generated text.
2

Step 1: text becomes tokens

LLMs work with tokens rather than directly with words. A tokenizer splits input text into pieces and maps those pieces to token IDs.

INPUT“AI makes coding faster.”
TOKEN SEQUENCE
AI makes coding faster .

The exact split depends on the tokenizer and model. A token may represent a whole word, part of a word, punctuation, or another frequently occurring text fragment.

Example A“playing” might be represented as one token or several pieces.
Example B“Hello, world!” includes text plus punctuation that the tokenizer represents as tokens.
3

Step 2: tokens become vectors

A token ID is just an identifier. The neural network needs useful numerical representations, so tokens are mapped into vectors called embeddings.

TOKEN
“cat”
VECTOR
[0.21, -0.47, 0.83, 0.16, …]

These numbers do not mean “cat = these five properties.” Real embeddings have many dimensions, and their useful structure emerges from training. Tokens with related usage can develop representations that help the network model relationships in language.

Mental model: tokenization gives the model discrete pieces; embeddings give the network continuous numerical representations it can transform through its layers.
4

Step 3: the Transformer processes the sequence

Modern LLMs are commonly based on the Transformer architecture. At a high level, Transformer layers repeatedly transform the representations of the input sequence.

Token representationsvectors + position information
Attentioncompare relationships between positions
Feed-forward networknon-linear transformation
Repeat across many layersincreasingly rich representations

For this lesson, you do not need every matrix operation. The important idea is that the network repeatedly mixes information and transforms representations so that later predictions can use relationships across the sequence.

5

Step 4: attention helps connect relevant context

Attention gives the model a mechanism for relating one position in a sequence to other positions. This helps the network decide which parts of the available context are useful when building a representation.

The developer fixed the bug because it was blocking checkout.
“it”attention relationship“bug”

This is a simplified illustration—not a claim that the model uses a single human-readable rule. Real attention uses learned numerical computations across many heads and layers.

Why it matters

Language meaning often depends on words that are separated in the sequence.

What it does not mean

Attention is not a human-style thought process. It is a learned mathematical operation inside the network.

6

Step 5: the model produces next-token probabilities

After processing the current sequence, the model produces scores that can be converted into probabilities over possible next tokens.

“ Paris”0.82
“ London”0.09
“ Rome”0.05
other tokens0.04
Important: these numbers are a teaching illustration, not the output of a specific model run. Real vocabularies contain many thousands of possible tokens.
7

Step 6: generation repeats the process

The model does not normally generate an entire answer in one magical step. In autoregressive generation, a token is selected, added to the sequence, and the model predicts the next token again.

PromptThe capital of France is
PredictParis
Add token… is Paris
Predict again… and continue
RoundCurrent textNext token
1The capital of France isParis
2The capital of France is Paris.
3The capital of France is Paris.It

Real generation also involves decoding choices, stopping rules, token limits, and other settings. You will study those ideas in later lessons.

8

What happens when your Python app calls an LLM?

The API hides the internal neural-network calculations, but the application-level flow is still useful to understand.

Your Python codecreates the request
APIaccepts input + options
LLMprocesses tokens + generates
Responseyour app receives output
</> Python
from openai import OpenAI

client = OpenAI(api_key=input("Enter your API key: "))

response = client.responses.create(
    model="gpt-5.6-luna",
    input="Explain attention in one simple paragraph."
)

print(response.output_text)
Connect the dots: your application supplies text → the service tokenizes and processes it with the model → generation predicts tokens repeatedly → the API returns the generated result.
9

A tiny Python model to understand the idea

You can demonstrate the shape of next-token prediction without pretending that a few lines of Python are an LLM. Here, a tiny frequency table chooses the most common next word from a small dataset.

</> Python
from collections import Counter, defaultdict

sentences = [
    "the cat sleeps",
    "the cat eats",
    "the dog sleeps",
]

next_words = defaultdict(Counter)

for sentence in sentences:
    words = sentence.split()
    for current_word, next_word in zip(words, words[1:]):
        next_words[current_word][next_word] += 1

print(next_words["the"].most_common())
Example output[('cat', 2), ('dog', 1)]

This toy program captures one narrow idea: use previous context to estimate what comes next. Real LLMs replace this tiny lookup table with a huge learned neural network operating over token sequences.

10

Experiment: change the context

One of the most useful ways to understand LLM behavior is to change the input and observe how the generated continuation changes.

INPUT A“The customer is angry because the delivery”likely continuation: “was late…”
INPUT B“The customer is happy because the delivery”the context changes what continuation is useful
Break it

Give the model a vague or contradictory prompt and inspect how the answer changes.

Fix it

Add clear instructions, relevant context, and an explicit output format.

11

What you should remember

1. TokensText is converted into model-specific token pieces.
2. EmbeddingsToken IDs become numerical representations.
3. TransformerLayers transform representations using mechanisms such as attention.
4. PredictionThe model produces probabilities for possible next tokens.
5. GenerationSelected tokens are added and prediction repeats.
6. ApplicationYour software wraps the model with prompts, data, tools, validation, and UI.
PRACTICE

Check your understanding

Answer first, then reveal the explanation.

1Why does an LLM tokenize text before processing it?Tokenization converts raw text into discrete pieces that the model can map to token IDs and process numerically.
2What is the high-level purpose of an embedding?It represents a token as a numerical vector that can be transformed by the neural network.
3What does attention help a Transformer do?It provides a learned mechanism for relating positions in the sequence so useful contextual information can be combined.
4Why is generation called autoregressive?Because newly generated tokens become part of the sequence used to predict subsequent tokens.
QUICK QUIZ

Which sequence best describes the high-level generation process?

30-second recap

  • LLMs first convert input text into tokens.
  • Token IDs are mapped into numerical representations called embeddings.
  • Transformer layers process those representations using mechanisms such as attention.
  • The model produces probabilities for possible next tokens.
  • Generation repeats: select a token, add it to the context, and predict again.
  • An API hides the internal calculations, but your application still controls the input, options, and surrounding system.