An interactive field guide to large language models

Every answer is written one token at a time.

ChatGPT, Claude, Gemini, DeepSeek and Perplexity all run the same loop: read the text so far, score every possible next token, pick one, append it, repeat. Press Next token and watch each stage of that loop on a tiny model that lives in this page.

This page's model is a trigram counter trained on ~800 words. A real LLM swaps the counting step for a transformer with billions of learned weights. Steps ①, ④ and ⑤ work the same way in both.

Step 1 · Tokenize

Text becomes a list of numbers

A model cannot read letters. A tokenizer chops text into pieces from a fixed vocabulary and replaces each piece with its ID number. Most LLMs use byte-pair encoding (BPE): start with single characters, find the pair that appears most often in the training text, glue it into a new token, and repeat tens of thousands of times.

Common words end up as one token. Rare words get split into chunks. That is why models sometimes fumble spelling questions like "how many r's in strawberry": they see str·aw·berry, not ten letters.

Drag the slider to replay the merges this page learned from its own training text.

120
The merge list, in the order it was learned

Step 2 · Embed

Each token becomes a point in meaning-space

Every token ID indexes one row of a big table called the embedding matrix. That row is a list of numbers, a vector. During training these numbers drift until tokens that are used in similar ways sit close together.

Because meaning becomes geometry, you can do arithmetic on it. The classic example from word2vec (2013): king − man + woman lands next to queen.

The vectors here have 10 named dimensions so you can read them. Real models use thousands of dimensions that nobody named; researchers dig concepts out of them with interpretability tools (see Research frontier).

Vector arithmetic

− +

The vector, dimension by dimension

The map is a flattened 2D shadow of the 10 dimensions, with labels nudged apart so they stay readable. Click any word on the map to inspect its vector. Try prince − boy + girl or puppy − dog + cat.

Step 3 · Attend

Tokens look at each other

Self-attention is the core idea of the 2017 paper "Attention Is All You Need". Each token makes three vectors:

  • Query: what am I looking for?
  • Key: what do I contain?
  • Value: what do I pass on if picked?

Score = query · key ÷ √d. A causal mask hides future tokens (grey cells), softmax turns each row of scores into weights that sum to 1, and each token's new vector is the weighted mix of the values it attended to.

A model runs dozens of these heads in parallel, each learning its own kind of lookup, in every one of dozens of layers. Between attention steps a feed-forward network processes each token on its own; that is where much of the model's stored knowledge appears to live.

Step 4 · Predict & sample

A score for every word, then a dice roll

After the last layer, the vector at the final position is multiplied against every token in the vocabulary. The result is one raw score per token, called the logits. Softmax turns logits into probabilities that add up to 100%.

Then the model samples. The settings you see in AI APIs live here:

  • Temperature sharpens (below 1) or flattens (above 1) the distribution.
  • Top-k keeps only the k most likely tokens.
  • Top-p keeps the smallest set of tokens whose probability adds up to p.

Temperature 0 always picks the top token (greedy). That is why the same prompt can give different answers each time: the model's output is a distribution, and the app rolls dice on it.

Step 5 · Pretrain

Learning is just nudging numbers to lower the surprise

Where do the weights come from? Pretraining. Show the model text, ask it to predict each next token, and measure how surprised it was with cross-entropy loss: minus the log of the probability it gave the right answer.

Gradient descent then nudges every weight a little in the direction that would have lowered that loss. Repeat trillions of times and grammar, facts and some reasoning patterns emerge, because they all help predict the next token.

This lab trains a real (tiny) neural network live in your browser: a 26×26 weight matrix (one row per character) that predicts the next character from the current one. Watch the loss fall from "random guessing" toward the best this model shape can do, and watch its writing go from noise to word-ish text.

Loss (lower is better)

What it predicts row = current char, column = next char

The model writes (sampled from current weights)


        

Step 6 · Align

From text-continuer to assistant

A pretrained base model only continues text. Ask it a question and it may write three more questions, because that is what follows a question on many web pages. Turning it into ChatGPT or Claude takes further training stages. Pick a stage to see how the same prompt is handled.

Be the human labeler

In RLHF (reinforcement learning from human feedback), people compare two answers and pick the better one. A reward model learns to predict their choices, and the language model is then trained to score high on that reward.

Pick your preferred answer in each pair. A small reward model (logistic regression over five answer traits) fits your choices live. Its learned weights show what you taught it to value.

Try preferring the longest answer every time and watch the "long" weight grow. That is reward hacking in miniature: the model learns what raters reward, which is not always what is good.

What the reward model learned

Best-of-4 using your reward model

Step 7 · Reason

Thinking is more tokens, used well

A model does a fixed amount of computation per token. If an answer needs more steps than one forward pass can hold, the model can write the steps out and read its own notes. That is chain-of-thought: the scratch work becomes part of the context.

Reasoning models (OpenAI o1 in 2024, DeepSeek-R1 in January 2025, Claude's extended thinking) are trained with reinforcement learning to think well before answering. Rewards come from answers that can be checked: math results, passing unit tests.

Spending more tokens at answer time is called test-time compute. One simple form is self-consistency: sample many reasoning paths and take a majority vote. Move the slider and run it.

Question A bat and a ball cost $1.10 in total. The bat costs $1.00 more than the ball. How much does the ball cost?

7

Accuracy vs. number of paths (10,000 simulated runs per point, 55% of single paths correct)

How R1-style training rewards good thinking (GRPO)

DeepSeek-R1 was trained with GRPO (Group Relative Policy Optimization). For each problem the model writes a group of answers, here 8. Each gets a reward: 1 if correct, 0 if not. Every answer's advantage is its reward minus the group average, divided by the group's spread.

Positive advantage: make that chain of thought more likely. Negative: less likely. No separate critic network is needed, which made it cheaper than earlier methods. Click answers to flip them right or wrong.

Step 8 · Build

What a chatbot actually sends

A chat model has no memory between messages. Every turn, the app re-sends a single long prompt: instructions, the whole conversation, any retrieved documents, and the tools it may call. Everything must fit inside the context window. Products differ mostly in what they put into that prompt and what they do with the reply.

1 · Retrieval (RAG): how Perplexity-style answers get sources

2 · The prompt that is actually sent


        

3 · The agent loop: tool use, step by step

    
                

    Your first real chatbot

    This is a complete, working terminal chatbot using the Anthropic Python SDK. Note how it keeps the history list itself and sends it every turn. That is the "memory".

    Run it with pip install anthropic, set ANTHROPIC_API_KEY, then python chat.py. This repo has a fuller version in examples/chat.py (it also handles declined requests), plus the full tool-use loop from step 3 in examples/agent.py.

    chat.py
    import anthropic
    
    client = anthropic.Anthropic()   # reads ANTHROPIC_API_KEY
    history = []                     # the model's only "memory"
    
    while True:
        user = input("you › ")
        history.append({"role": "user", "content": user})
    
        reply = client.messages.create(
            model="claude-opus-5-5",
            max_tokens=2048,
            system="You are a patient tutor who explains AI concepts simply.",
            messages=history,        # the WHOLE conversation, every turn
        )
        text = "".join(b.text for b in reply.content if b.type == "text")
        history.append({"role": "assistant", "content": reply.content})
        print("claude ›", text)
        print(f"[{reply.usage.input_tokens} tokens in, {reply.usage.output_tokens} out]")

    Context · 1950 to now

    How we got here

    Filter by thread. Each entry says what changed and why it mattered for the models you use today.

      Context · open questions

      The research frontier

      Where researchers are pushing in 2025–2026. Each card names the open question and links to a primary source to start with.

      Context · go deeper

      Read, watch, build next