# How do LLMs work? Explained for software engineers

> An LLM is a function that turns tokens into next-token probabilities, called in a loop. Tokens, attention, sampling and context, with runnable TypeScript.

Source: https://devaiper.com/blog/how-do-llms-work
Published: 2026-10-25
Topics: LLM, Fundamentals, Tokens, TypeScript

**Short answer:** A large language model is a function: give it a list of tokens and it returns a probability for every possible next token. Generating text is a loop that picks one token, appends it and calls the function again. Everything else (tokenizers, attention, temperature, context windows, hallucinations) follows from that one idea.

You use LLMs every day. You may even ship features on top of them. But if someone asked "so how does it actually work?", would the answer be more than "it predicts the next word"? That answer is right, and it is also the start of every important engineering decision you will make with these models.

This post explains it the way you would explain any system to a colleague: inputs, outputs, and the loop in between. No math beyond "add these up". And because reading about it only goes so far, you will run a real (small, old) language model on your laptop and look at its probabilities yourself.

## The one-sentence answer

**An LLM is a function from tokens to next-token probabilities, called in a loop.**

> **Diagram:** How an LLM generates text. The text is split into tokens. The model returns a probability for every possible next token. One token is picked, appended to the text, and the loop repeats until the answer is done.
> Tokenize the text (word pieces -> ids) → ... → Model: f(tokens) (a probability per token) → ... → Pick one, append it (sampling + temperature)
> A paragraph of output is hundreds of trips around this loop.

If you have written a lexer, a pure function and a `while` loop, you already know the shape. Let's open each box.

## 1. Tokens: the model reads pieces, not words

A **tokenizer** splits text into pieces from a fixed vocabulary and turns each piece into a number. Think of it as the model's lexer. Here is what the GPT-2 tokenizer does to a few inputs (real output from the code below):

| Text | Tokens |
|---|---|
| `The capital of France is` | `The` · ` capital` · ` of` · ` France` · ` is` |
| ` unbelievably` | ` unbelievably` |
| `unbelievably` | `un` · `bel` · `iev` · `ably` |
| ` TypeScript` | ` Type` · `Script` |
| ` strawberry` | ` strawberry` |
| `strawberry` | `st` · `raw` · `berry` |

Three things fall out of this table:

- **Spaces matter.** The leading space is part of the token, so the same word can be one token or four.
- **The model never sees letters.** Ask it how many r's are in "strawberry" and it is looking at `st`, `raw`, `berry`, not at characters. That is why letter-counting questions trip models up.
- **Tokens are the unit of everything else:** price, speed, and the context limit are all counted in tokens, not words. Every model family has its own tokenizer, so the exact splits differ, but the idea is the same.

## 2. The model: a function that returns probabilities

Feed the token ids into the model and you get back one score for **every token in the vocabulary**. GPT-2's vocabulary has 50,257 tokens, so one call returns 50,257 numbers. Turn the scores into probabilities (that is `softmax`, below) and they add up to 1.

Here is GPT-2's actual answer to "The capital of France is":

| Next token | Probability |
|---|---|
| ` the` | 8.5% |
| ` now` | 4.8% |
| ` a` | 4.6% |
| ` France` | 3.2% |
| ` Paris` | 3.2% |

Not Paris. ` the`. Which makes sense once you stop thinking of it as a database: "The capital of France is **the** city of..." is a perfectly likely sentence. The model learned what text tends to look like, and facts come along only to the extent that they shaped the text it was trained on. **That one table is the best explanation of hallucinations I know.** A model produces plausible text. Sometimes plausible and true are the same thing.

(GPT-2 is a small 2019 model with 124 million parameters. Modern models are far larger and far better at facts, but they work the same way: probabilities over tokens.)

## 3. Inside the function: attention, in one paragraph

How does the model turn tokens into those probabilities? The architecture behind nearly every modern LLM is the **transformer**, from the 2017 paper [Attention Is All You Need](https://arxiv.org/abs/1706.03762). Its key mechanism, **attention**, lets each token look at every earlier token and decide which ones matter for predicting what comes next. In "The trophy did not fit in the suitcase because **it** was too big", attention is how the model links "it" to "trophy". Stack dozens of these layers, each holding millions of learned numbers (the **parameters**, or weights), and you get the function.

You do not need more detail than that to build with LLMs. The analogy that helped me: the weights are a compiled program. Nobody wrote it by hand, and you cannot read it, but you can call it.

## 4. Where the weights come from: training

Training is a giant optimization loop:

1. **Pretraining.** Show the model a huge amount of text. At every position, it predicts the next token, gets told the real one, and its weights are nudged to make the right answer a bit more likely. Repeat for a very, very long time. The result is a model that continues text, like GPT-2 above.
2. **Post-training.** Further training on examples of helpful conversations and on human (and AI) feedback about which answers are better. This turns a text continuer into an assistant that follows instructions, says "I don't know" more often and refuses harmful requests.

Training happens once, at the vendor, at enormous cost. Using a model (inference) is just calling the function. Nothing you type changes the weights.

## 5. Generation: a loop with a dice roll

To write an answer, the app calls the function, **picks** a token from the probabilities, appends it, and calls again. Picking the single most likely token every time sounds sensible but tends to produce dull, repetitive text, so apps usually **sample**: roll a weighted die over the probabilities.

**Temperature** reshapes the probabilities before the roll. Same model, same prompt:

| Next token | Temperature 1 | Temperature 0.2 | Temperature 2 |
|---|---|---|---|
| ` the` | 8.5% | **88.2%** | 0.5% |
| ` now` | 4.8% | 5.2% | 0.4% |
| ` Paris` | 3.2% | 0.7% | 0.3% |

Low temperature makes the favorite a near-certainty: predictable output. High temperature flattens everything: the top token drops to 0.5% because thousands of unlikely tokens gain probability, which is where "creative" (and unhinged) output comes from. With a fixed random seed, GPT-2 at temperature 0.8 continued our prompt as "The capital of France is a last ditch effort to stop". Fluent, confident, and nonsense.

One practical note: some current models no longer let you set temperature at all (Claude Opus 5.5, for example, rejects it); the provider tunes sampling for you. The concept still explains why the same prompt gives different answers.

## 6. The context window: the only memory there is

The model sees exactly one thing: the tokens in the current request. There is no hidden memory of yesterday's chat. When a chat app "remembers" your earlier messages, it is **resending the whole conversation** every time ([your first API call](https://devaiper.com/blog/claude-api-first-call-typescript) shows this in code).

The **context window** is the maximum number of tokens one call can take: your instructions, the history, any documents and the answer. Current Claude models accept up to a million tokens. That is a lot, but it is a buffer, not a brain: everything outside it does not exist for the model, and filling it costs money and attention. Deciding what goes into it is a whole discipline, [context engineering](https://devaiper.com/blog/what-is-context-engineering), and making agents remember across sessions is a design problem of its own ([AI agent memory](https://devaiper.com/blog/ai-agent-memory)).

## Run it yourself

All of the numbers above come from this code. It runs GPT-2 locally with [transformers.js](https://github.com/huggingface/transformers.js): no API key, no GPU. The first run downloads the model files from Hugging Face and caches them.

```bash
npm install @huggingface/transformers
```

The two helpers that turn scores into a choice:

```ts
/** Raw scores to probabilities. Lower temperature = pickier. */
export function softmax(logits: number[], temperature = 1): number[] {
  const scaled = logits.map((x) => x / temperature);
  const max = Math.max(...scaled); // subtract max: no overflow
  const exps = scaled.map((x) => Math.exp(x - max));
  const sum = exps.reduce((a, b) => a + b, 0);
  return exps.map((e) => e / sum);
}

/** Pick an index at random, weighted by its probability. */
export function sample(probs: number[], rand = Math.random): number {
  let r = rand();
  for (let i = 0; i < probs.length; i++) {
    r -= probs[i];
    if (r <= 0) return i;
  }
  return probs.length - 1;
}
```

And the model, the tokenizer and the generation loop:

```ts
import {
  AutoModelForCausalLM,
  AutoTokenizer,
} from "@huggingface/transformers";
import { sample, softmax } from "./sampling.ts";

const MODEL = "Xenova/gpt2"; // small (124M), old, runs on a laptop
const tokenizer = await AutoTokenizer.from_pretrained(MODEL);
const model = await AutoModelForCausalLM.from_pretrained(MODEL);

/** How the model sees your text: a list of token pieces. */
export function tokens(text: string): string[] {
  return tokenizer.encode(text).map((id) => tokenizer.decode([id]));
}

/** One forward pass: a probability for every token in the vocab. */
export async function nextTokenProbs(text: string, temp = 1) {
  const { logits } = await model(tokenizer(text));
  const [, len, vocab] = logits.dims as number[];
  const last = logits.data.slice((len - 1) * vocab, len * vocab);
  return softmax(Array.from(last as Float32Array), temp);
}

export async function topNext(text: string, temp = 1, k = 5) {
  const probs = await nextTokenProbs(text, temp);
  return probs
    .map((p, id) => ({ token: tokenizer.decode([id]), p }))
    .sort((a, b) => b.p - a.p)
    .slice(0, k);
}

/** Generation is a loop: predict, pick, append, repeat. */
export async function generate(
  text: string,
  steps: number,
  temp = 1,
  rand = Math.random,
): Promise<string> {
  for (let i = 0; i < steps; i++) {
    const id = sample(await nextTokenProbs(text, temp), rand);
    text += tokenizer.decode([id]);
  }
  return text;
}
```

Try `await topNext("function add(a, b) {")` and watch a 2019 model guess at JavaScript: ` return` at 39.7%, a newline at 10.8%, then ` if`, ` var` and ` //`. The model's output for the last position is `logits`: one row of 50,257 scores per input token, and we only need the last row. Real apps also reuse work between steps instead of re-reading the whole text each time, but the loop is the same.

How I tested this: it ran under Node 24 with `@huggingface/transformers` 4.3.1. The tests check that the probabilities cover all 50,257 tokens and sum to 1, that lower temperature sharpens them, that sampling follows the weights, that the token splits in the table above are exact, and that generation repeats with the same seed.

## What confused me

Two things, when I first looked at this properly:

- **The model does not "know" it is answering a question.** It continues text. Assistants feel like they answer because post-training taught them that the likely continuation of a question is a helpful answer.
- **"It predicts the next word" undersells it.** To predict the next token of a function body well, you have to track variables, types and intent. The objective is simple. What it takes to be good at it is not.

## What this means for your code

| Fact | So in practice |
|---|---|
| Output is sampled | Same prompt, different answers: test with several runs, and use [structured output](https://devaiper.com/blog/how-to-get-json-from-an-llm) when you parse it |
| Plausible is not true | Put the facts in the context ([RAG](https://devaiper.com/blog/what-is-rag)) and [verify AI-written code](https://devaiper.com/blog/how-to-catch-ai-hallucinations-in-code) |
| Stateless, limited context | You decide what the model sees, every call |
| Everything is tokens | Cost, speed and limits are counted in tokens, so [cache what repeats](https://devaiper.com/blog/prompt-caching-explained) |

Next step on the roadmap: [your first LLM API call in TypeScript](https://devaiper.com/blog/claude-api-first-call-typescript).

Sources: [Attention Is All You Need (2017)](https://arxiv.org/abs/1706.03762), [GPT-2 model card](https://huggingface.co/openai-community/gpt2), [transformers.js](https://github.com/huggingface/transformers.js).

## FAQ

### How do LLMs work in simple terms?

An LLM reads your text as tokens (word pieces), then predicts a probability for every possible next token. It picks one, appends it, and repeats. A chat answer is thousands of these small predictions in a row.

### What is a token in an LLM?

A token is the unit the model reads: often a whole word with its leading space, sometimes a word piece, a punctuation mark or a byte. With the GPT-2 tokenizer, ' strawberry' is one token but 'strawberry' without the space is three: 'st', 'raw' and 'berry'.

### Why do LLMs hallucinate?

Because they are trained to predict likely text, not to look facts up. A fluent, plausible continuation can be wrong. Give the model the facts in its context, ask it to cite them, and verify anything that matters.

### What does temperature do?

It reshapes the probabilities before a token is picked. Low temperature makes the most likely token even more likely, so answers get more predictable. High temperature flattens the distribution, so rarer tokens get picked more often.

### Does an LLM remember my previous messages?

Not by itself. The model is stateless. Chat apps resend the conversation with every request, and anything outside the context window is invisible to the model.

