GOAT EngineerPreparing your learning space…

AI Engineering · Concept Library · Free article

How LLMs Actually Work

An LLM reads a sequence of tokens and outputs a probability for every possible next token, then picks one, appends it and repeats. That single loop is the whole machine, and fluency, code, reasoning and hallucination are all consequences of it rather than separate features somebody built.

Under the hood, a large language model does something almost embarrassingly simple: it guesses the next token, adds it to the text, and guesses again. The fluency, the “reasoning” and the confident wrong answers all fall out of that one loop plus the scale it runs at. You do not need the training math to build on it. You need the loop, because once you can see it you can predict the behaviour: why outputs vary, why it invents facts, why “be concise” is a latency setting, and why RAG, tools and memory exist at all.

A customer writes in: “I was charged twice this month.” Your assistant, Wrenlet, drafts a warm, articulate reply citing “section 7.4 of our refund policy”, a section that does not exist. The tone is perfect. The fact is invented. And nothing in the code threw an error.

You cannot debug that with print statements. To know why a model does this, and to predict the next surprise before it ships, you need a mental model of what the thing actually is. Not the training math. Just the one loop it runs, and the handful of consequences that pour out of it.

How does an LLM actually work?

It predicts the next token, and that is the whole job. Give the model some text and it does not “think of an answer.” It computes a probability distribution over its entire vocabulary, a hundred thousand or more possible next tokens, and hands you the odds. “refunded” at 34%, “checked” at 24%, “escalated” at 16%, and a long tail of less likely continuations. A sampler then draws one token from that distribution.

That is why the same prompt can give different answers: you are drawing from a distribution, not reading a fixed reply. Drag the temperature below and watch the odds reshape, and watch what happens to the draw.

The interactive version of this example is available when JavaScript loads.

The knob is temperature. Low temperature sharpens the distribution until the top token towers over the rest: the model becomes predictable and a little boring, which is exactly what you want for pulling a field out of a document or deciding which tool to call. High temperature flattens it until even unlikely tokens get a turn: more variety, more surprises, more drift. “More creative” and “less reliable” are the same setting turned the same direction.

One token at a time, feeding on its own output

The model never writes a whole sentence at once. It emits one token, appends it to the input, and runs the exact same prediction on the now-longer text: again and again until it predicts a special “stop” token. This is autoregression, and it explains three things you see every day.

The text it runs on has a ceiling, called the context window. That window is the model's entire world for one request: the instructions, the conversation so far, anything you retrieved, and the reply it is writing all share the same budget, measured in tokens. Nothing outside it exists to the model, and going over it is an error rather than a graceful forgetting.

The interactive version of this example is available when JavaScript loads.

Three consequences of the one-at-a-time loop

  1. Replies stream. Words appear as they are generated because they are, literally, produced in order. The model has the first word long before it has the last.
  2. It cannot plan ahead. There is no outline it is filling in. Each token is chosen from a shortlist given only the tokens before it, so it is committing to a sentence it has not finished thinking.
  3. Early mistakes compound. Because every new token is conditioned on the ones already written, a wrong turn near the start bends everything after it to stay consistent. This is why a bad opening line often drags a whole answer off course.

What is attention, without the math?

So where does “refunded: 34%” actually come from? Two ideas carry all the intuition you need.

First, every token is turned into a list of numbers, an embedding, that places its meaning as a point in space. Tokens that mean similar things land near each other, so “refund”, “chargeback”, and “reimburse” cluster together while “refund” and “giraffe” sit far apart. Meaning becomes geometry. (The classic textbook demo of this is the word-vector arithmetic where subtracting and adding embeddings lands you on a related word: a neat party trick, but the useful part is just: nearby means related.)

Second, the model reads with attention, the mechanism the 2017 transformer paper is named for: as it processes each token, it looks back over the earlier tokens and pulls in the ones that matter for what comes next. Reading “I was charged twice so please issue a refund”, a model sitting on “refund” and working out what follows leans hard on “charged” and “twice”, and barely at all on “please.” The meaning of a word is shaped by the company it keeps, and attention is the mechanism that lets a token gather that context. Pick a token below and watch which earlier ones it leans on:

The interactive version of this example is available when JavaScript loads.

Here is the intuition with no matrices. As it processes a token, the model forms a little request, what kind of earlier token would help me predict what comes next?, and every earlier token advertises what it is about. Where a request and an advertisement match well, that earlier token's content gets pulled in strongly; where they don't, it is mostly ignored. (The three roles have names, the request is a query, the advertisement a key, the content a value, and the match-and-pull is a weighted average, but the plain version is all you need to reason about behavior.)

Two properties of that look-back matter in production. First, during generation a token can only attend backward. It literally cannot see tokens that do not exist yet. That one restriction is what forces text out strictly left to right, one token at a time; it is the same fact the autoregression section showed from the outside, now seen from the inside. Second, the model does not run one look-back but many in parallel: separate passes that can each specialize (one tracks who-did-what-to-whom, another tracks a reference made far earlier) and are then merged. Stack all of that dozens of layers deep and the final layer produces the odds over the next token.

How does an LLM learn anything at all?

In three stages, and each one explains a different part of its personality: pretraining gives it knowledge and fluency, instruction tuning turns a text-completer into an assistant, and preference tuning gives it its manners, including the reflex to sound confident.

The training pipeline: what each stage actually changes
StageWhat happensWhat it changes about behavior
PretrainingPredict the next token across a huge slice of the internet and books.Knowledge and fluency. The “base model” can complete text but does not reliably answer questions or follow instructions.
Instruction tuningFine-tune on examples of instructions paired with good responses.It learns the shape of “a helpful answer to a request.” This is where a text-completer becomes an assistant.
Preference tuning (RLHF)Reward responses humans prefer; penalize the rest.Helpfulness, tone, refusals, and the habits it drills in, like sounding confident and agreeable even when it should hedge.

Two things fall straight out of this. The friendly “assistant” you talk to is a persona layered on a raw text-completer by the last two stages, not a different kind of program. And the reflex to sound assertive and agreeable (sometimes to the point of telling you what you want to hear) is a learned behavior from preference tuning, not a bug. Once the training run ends, the weights freeze: the model stops learning. It does not remember your last conversation, and its knowledge stops at a cutoff date: unless you hand it fresh information at request time.

The difference between the stages is easiest to feel by watching one prompt run through all three. Step it:

The interactive version of this example is available when JavaScript loads.

The base model is the surprising one: ask it a question and it may answer with more questions, because to a pure text-completer a question is just a document to continue, and questions are often followed by more questions. Instruction tuning is the step that reframes the prompt as a request to fulfill. Preference tuning then polishes the delivery, and bakes in the confident, agreeable habits.

But how does instruction tuning actually teach that? Not with a rule: nobody writes “when you see a question, answer it.” You fine-tune on examples: pairs of an instruction and a good response. Show the model enough of them and it learns the shape of a helpful answer and applies it to instructions it has never seen. Play the engineer below: add a few example pairs (none of them about refunds) and watch the model's answer to an unseen refund question snap into place:

The interactive version of this example is available when JavaScript loads.

That is the crux, and it is worth stating plainly: the model did not memorize your examples. It generalized the pattern from them to a new question. This is why instruction tuning works at all, and why the examples' quality and consistency matter so much: a few thousand well-chosen (instruction → good answer) pairs teach the behavior; sloppy or contradictory ones teach sloppiness. Now the model answers. The last stage decides how it answers.

And how does preference tuning work? You show the model two candidate answers and mark which is better, over and over, and it shifts toward the kind people prefer. There are two recipes for turning those rankings into training. Be the judge below, then flip between them:

The interactive version of this example is available when JavaScript loads.

The knobs you actually turn

You rarely retrain a model; you configure how it samples. Three settings do most of the work, and they cut in different places. Temperature reshapes the whole distribution first, low sharpens it toward the top token, high flattens it, without removing anything. Then a cutoff trims the tail. Top-k is the blunt cutoff: keep the k highest tokens, drop the rest, no matter how confident the model is. Top-p (nucleus) is the smart one: keep the smallest set of top tokens whose probabilities add up to p, say 0.9, and drop the tail. The difference is that top-p adapts: when the model is sure, the nucleus is one or two tokens; when it is torn, the nucleus widens to let more in. Watch the nucleus move, then draw a batch and see the diversity:

The interactive version of this example is available when JavaScript loads.

The order matters: temperature reshapes, then the cutoff trims, then a token is drawn. A useful rule from the providers is to tune temperature or top-p, not both at once, so you are moving one thing you understand. And greedy decoding, always take the single top token, is just this with the randomness turned all the way off; it is repeatable but prone to getting stuck in loops (“I can help, I can help, I can help”), which is why a separate repetition penalty exists to nudge the model off tokens it has already used.

Pick the setting from the task, not by feel
TaskSettingWhy
Extraction, classification, tool/function callsTemperature ~0You want the single most likely, repeatable answer. Variety is a liability here.
Drafting a support reply, summarizingLow to moderate (~0.3 to 0.7)A little variation reads as natural without going off-script.
Brainstorming names, alternate phrasingsHigher (~0.8 to 1.2)You are deliberately buying diversity and can throw away the misses.
Anything inside an agent loopLowEvery step feeds the next; randomness compounds into runaway trajectories.

What is a reasoning model?

A model trained to generate a long stretch of private working before the visible reply, and to be judged on the answer that follows it. So far the model produces its answer immediately, one token after another. A reasoning model does something different first: before the visible reply, it generates a long stretch of private working, a scratchpad where it tries an approach, checks it, backs up, tries another, and only then writes the answer. That working is made of tokens too, usually hidden from the user, and the model was specifically trained to produce it, rather than merely asked to “show its work” in the prompt. The result is a real jump in accuracy on genuinely hard problems: multi-step math, tricky code, planning, anything where the first plausible guess is often wrong.

This is a new lever, and it is not free. Those hidden thinking tokens are generated serially, so they cost money and, because decode is serial, they cost time: a reasoning answer can take seconds longer and run a few times the token bill of a direct answer. That is a great trade on a hard problem and a terrible one on an easy lookup. Slide a thinking budget on a hard task and an easy one and watch when it pays:

The interactive version of this example is available when JavaScript loads.

Does a bigger model always work better?

Scale is real: more parameters and more training generally buy more capability. But bigger is not free, and it is not always the right buy. A model has a rough compute-optimal balance between its size and how much data it is trained on (the Chinchilla result landed around 20 training tokens per parameter), and the industry has since learned to deliberately over-train smaller models on far more data, because a smaller model that hits the quality bar is dramatically cheaper and faster to serve for the millions of calls that follow.

So the senior move is rarely “reach for the biggest model.” It is: can a smaller, cheaper model plus good context, a sharp prompt, the right retrieved facts, beat a bigger model working blind? Very often, yes. You will make that trade constantly, and it is a cost-and-latency decision as much as a quality one.

There is one scale trick worth knowing because it explains why some enormous models are cheap to run. A plain (dense) model runs every parameter for every token. A mixture-of-experts model instead holds many specialized sub-networks and, for each token, a small router picks a small handful of them to run, often somewhere between two and eight, so a model with hundreds of billions of parameters in total might fire only tens of billions per token. It buys the knowledge capacity of a huge model at the running cost of a much smaller one, which is why most recent open-weight frontier models are built this way, and the closed ones are widely believed to be. Treat that last part as belief rather than fact: the labs that ship the closed models have not published their architectures. You do not configure it, but it is why “huge parameter count” no longer means “huge cost per token.”

The landscape you actually choose from

As an engineer you are not training these. You are picking one. Two axes organize the whole market. The first is who controls it: proprietary models you reach only through an API (the frontier labs) versus open-weight models you can download and run on your own hardware (private, free at inference, no vendor lock, but you operate the servers). The gap between them has narrowed to the point that a good open-weight model often clears the bar for everyday work. The second axis is size tier, and the right move is to match the tier to the job, not to reach for prestige.

Pick the tier from the job (names reshuffle: reason about the tier)
TierWhat it is forThe tradeoff
Frontier / largeThe hardest reasoning, the trickiest code, the ambiguous judgment calls.Top capability, highest cost and latency. Overkill for routine work.
Mid / workhorseThe bulk of production traffic: drafting, extraction, classification, routing.Strong enough for most tasks at a fraction of frontier cost. The default you reach for.
Small / on-deviceHigh-volume simple calls, or private/offline work on a laptop or phone.Cheapest and fastest, runs anywhere, but limited: pair it with good context.

One more shift you will feel: modern flagship models are natively multimodal, the same model takes text, images, and often audio in one stream, treating a picture as just more tokens alongside the words. Reading a receipt screenshot or a diagram is no longer a separate service bolted on; it is the same next-token machine with a wider idea of what a token can be. As with everything here, treat the specific names as a snapshot: the tiers are stable, the leaderboard is not.

What it is brilliant at, and what it cannot do

You can read a model's strengths and weaknesses straight off the mechanism, which is far more useful than a list of warnings. It is a next-token predictor trained on oceans of text, so anything that is a text-pattern task plays to its core: writing and rewriting, summarizing, translating, drafting a support reply, scaffolding code, fuzzy recall of common knowledge. Where it struggles, the cause is almost always one of two things you have already met.

The weak spots, and why

  • Counting characters and exact arithmetic. Ask it how many times the letter “r” appears in a product name and it often miscounts, because it never sees letters. It sees tokens, whole chunks, so the individual characters inside a token are invisible to it. Multi-digit math fails for the same reason: numbers split into inconsistent chunks, so it pattern-matches arithmetic instead of computing it. The fix is not a better prompt. It is a calculator tool.
  • Anything after its training cutoff. Its knowledge is frozen at the moment training ended, so it cannot know yesterday's news, this quarter's numbers, or a policy you changed last week: unless you put that information in the prompt.
  • Your private data. Your docs, your customer's order history, your internal wiki were never in its training set, so it simply does not have them. It will happily sound like it does, which is worse than admitting it doesn't.

Read the mechanism, predict the behavior

Here is where the mental model earns its keep. Because the model completes the most plausible continuation, not the most true one, and with no lookup and no memory, you can predict its failure modes before they bite:

The loop explains the surprises
You observeBecause the mechanism is…
Confident, fluent, wrong factsIt optimizes plausibility, not truth, and has no ground truth to check against. See the hallucination page.
Rewording the prompt changes the answerDifferent input tokens → a different distribution. The model is sensitive to phrasing because phrasing is the input.
It agrees with your framing / flatters youPreference tuning rewarded agreeable, confident responses. Sycophancy is trained in.
It “forgot” what you said earlierFrozen weights + a finite context window: only what is in the window right now exists to the model.
A wrong first sentence poisons the restAutoregression conditions every later token on the earlier ones, mistakes included.

Cost and latency are baked into the loop

Generation happens in two phases. First prefill: the model reads your whole prompt in one parallel pass to build up its internal state. Then decode: it generates the reply one token at a time, serially, each step waits on the last. That split has direct consequences for your bill and your latency. A long prompt costs money and prefill time on every call, so a bloated system prompt is a tax you pay forever. And because decode is serial, a long reply is a long wait: “be concise” is not a style note, it is a latency lever. You pay for tokens twice: once on the invoice, once on the clock. The tokenization page turns this into the arithmetic you will actually use.

Where does each idea show up in your API call?

Every idea on this page surfaces as a handful of knobs on a single call. You send the conversation and get back a completion; the parameters are exactly the levers you have been reading about.

The call, annotated

  • model, which model and version. Pin an exact version (not a floating “latest” alias) so an upstream update can't silently change your app's behavior.
  • messages: the whole context you assembled: a system instruction plus the conversation turns. The model is stateless, so this is re-sent every call; it is the model's entire world for this request.
  • temperature / top_p: the sampling knobs. Near 0 for extraction, classification, and tool calls; higher for drafting and brainstorming. Tune one, not both.
  • max_tokens: a hard cap on the reply length. This is your direct latency-and-cost lever, since decode is serial and paid per token.
  • stop: sequences that end generation early (a closing tag, a delimiter), so you don't pay for tokens past the part you need.
  • stream: true, receive tokens as they are decoded instead of waiting for the whole reply. Because generation is left-to-right, the first words are ready long before the last.

What to unlearn, and what to do instead

The section above explains why the model behaves the way it does. This one is what to do about it. Each belief below is what people arrive with, and each habit is what the loop actually licenses once you stop believing it.

The six that cost real money
Drop this beliefBuild this habit
“It looks things up.”Put the order history, the current policy, the retrieved passage into the context yourself, and gate anything the model should not invent.
“It remembers our chats.”Treat the context as the whole of its memory, and decide deliberately what you re-send on every turn rather than letting it grow.
“It understands, and it knows when it is right.”Check the properties you need, a valid shape, the right field, a passing rubric, rather than trusting the tone.
“Same prompt, same output, so I can cache exact strings.”Design for a distribution and never assert on exact output text. Pick the sampling setting from the task: near-zero for extraction, classification and tool calls, a little warmth for drafting.
“Bigger is always better.”Start mid-tier and move up only if the quality bar demands it. Route hard multi-step problems to a reasoning model, and keep routine, high-volume calls on a fast one.
“The model I called last month is the model I am calling now.”Pin the model version, and log usage and the stop reason. They are your bill and your truncation alarm in real time.

Interview cheat-sheet: intern to principal

In one sentence, what does an LLM do?
It reads a sequence of tokens and predicts a probability distribution over the next token; a sampler picks one, it is appended, and the process repeats. Everything else is a consequence of that loop at scale.
Why does the same prompt give different answers?
Because the next token is sampled from a distribution, not chosen deterministically. Temperature and top-p control how much of the tail is in play. Even at temperature 0, GPU batching and floating-point non-associativity can cause run-to-run variation, so don’t rely on exact reproducibility.
Explain attention without math.
As the model processes each token, it looks back over earlier tokens and weights how much each one matters for what comes next, mixing that context into the token’s representation. A word’s meaning is shaped by the words around it; stacking this operation across many layers produces the final next-token odds.
What do pretraining, instruction tuning, and RLHF each contribute?
Pretraining builds knowledge and fluency (a raw text-completer). Instruction tuning teaches it to follow requests (base model → assistant). RLHF shapes helpfulness, tone, and refusals, and drills in habits like sounding confident and agreeable. The assistant persona is those last two stages layered on the completer.
Given how it works, when would you NOT reach for the biggest model?
Almost always as the first move. A smaller, cheaper, faster model plus good context (a tight prompt, retrieved facts) frequently beats a bigger model working blind, and at the scale of production traffic the cost and latency savings are enormous. Choose by cost-per-correct-answer, not by parameter count.
Why do RAG, memory, and agents exist at all?
Because the model is frozen, stateless, and cutoff-limited with no access to your data. RAG supplies facts it never trained on, memory re-supplies context across turns, and tools/agents let it act in the world. They are all workarounds for the same fixed constraints of a next-token predictor.
Top-k vs top-p: what's the difference, and which do you prefer?
Both trim the tail before sampling, but differently. Top-k keeps a fixed number of top tokens regardless of the model's confidence. Top-p (nucleus) keeps the smallest set whose probabilities sum to p, so it adapts: a tiny nucleus when the model is sure, a wider one when it's torn. Top-p is usually preferred for that adaptivity. Temperature is applied first (it reshapes the whole distribution); the cutoff trims what's left. Tune one, not both.
Why did attention-based models beat the earlier sequential ones?
Older models passed a single running summary from token to token, so long-range dependencies had to survive a long relay and faded. Attention gives every token a direct connection to every other token, so distant links stay sharp, and unlike the sequential relay, it parallelizes across the sequence, which is what let it scale. The cost is that attention grows with the square of the context length, which is why long context is expensive.
What is a reasoning model, and when would you NOT use one?
A model trained to generate a long private chain of thinking tokens before its answer, which buys real accuracy on hard, multi-step problems (math, code, planning) at the cost of more tokens and higher latency. You would not use one for simple, high-volume, or lookup-style tasks: it over-thinks, multiplying the token bill for little gain and sometimes talking itself out of a right answer. Route hard problems to it and keep routine ones on a fast direct model.
How can a model have hundreds of billions of parameters but still be cheap per token?
Mixture-of-experts. Instead of running every parameter for every token (a dense model), it holds many expert sub-networks and a router activates only a couple per token, so the per-token compute reflects a small active fraction, not the huge total. It decouples total capacity from per-token cost, which is why most recent frontier models are built this way.
Why is an LLM bad at counting letters or doing exact arithmetic?
Because it never sees letters or digits. It sees tokens, whole chunks of text. The individual characters inside a token are invisible, so counting the r's in a word is guesswork; and numbers split into inconsistent chunks, so it pattern-matches arithmetic rather than computing place value. The fix is a tool (a real counter or calculator), not a cleverer prompt: the limitation is baked into tokenization.

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.