Every developer who has used Claude, ChatGPT or Grok has had the same moment. You type a vague question, and the model answers with a clear, well-structured explanation, sometimes better than a colleague would. Then, five minutes later, it confidently invents a function that does not exist in the library you are using.
Both behaviours come from the same machinery. If you understand that machinery, even at a high level, you will write better prompts, design better systems and stop being surprised by the failures. This article walks through what actually happens between the moment you press Enter and the moment text appears on your screen.
The one-sentence version
A large language model (LLM) is a neural network trained to predict the next piece of text, given all the text before it. Everything else, including answering questions, writing code and following instructions, is built on top of that single skill.
That sounds too simple to explain what modern models can do. The surprise of the last few years is that when you train a very large network on a very large amount of text, "predict the next token" turns out to require learning grammar, facts, reasoning patterns, coding conventions and much more.
Step 1, text becomes tokens
Models do not read characters or words. They read tokens, which are chunks of text produced by a tokeniser.
- Common English words are often a single token.
- Rare words are split into several pieces. A long technical term might become three or four tokens.
- Spaces and punctuation are usually attached to tokens.
- Code, Hindi and other non-English text often use more tokens per word than English.
A rough rule of thumb for English is that one token is about three quarters of a word, so 1,000 tokens is roughly 750 words. This matters for two practical reasons:
1. Cost: AI APIs charge per token, for both input and output.
2. Limits: every model has a maximum number of tokens it can consider at once, called the context window.
When you send a prompt, the tokeniser converts it into a list of integer IDs. The model never sees your text directly; it sees numbers.
Step 2, tokens become vectors
Each token ID is mapped to an embedding, a list of numbers (a vector) with hundreds or thousands of dimensions. You can think of an embedding as coordinates in a very high-dimensional space where tokens with related meanings sit closer together.
The model also adds information about position, so that "dog bites man" and "man bites dog" are not treated the same way. Modern models use various positional schemes, but the idea is the same: the network needs to know the order of tokens.
Step 3, the transformer layers
The core of almost every modern LLM is the transformer architecture, introduced in a 2017 research paper titled "Attention Is All You Need".
A transformer is a stack of identical layers. A large model may have dozens or even more than a hundred of them. Each layer has two main parts:
Self-attention
Attention lets every token look at every earlier token and decide which ones matter for understanding it.
Consider the sentence: "The server crashed because it ran out of memory." To understand "it", the model needs to connect it to "server". Attention is the mechanism that learns such connections.
Technically, each token produces three vectors called query, key and value. The model compares each token's query with every earlier token's key to compute attention scores, then uses those scores to mix the value vectors. A layer has many attention heads running in parallel, and different heads learn to track different kinds of relationships, such as syntax, references or code structure.
In a language model that generates text, attention is causal: a token can only look at tokens that came before it, never at future tokens. That is what makes next-token prediction possible.
Feed-forward network
After attention, each token's vector passes through a feed-forward network, a set of learned transformations. Researchers believe much of a model's stored knowledge lives in these layers.
Between these parts there are normalisation steps and residual connections, which help very deep networks train stably.
Why depth matters
Each layer refines the representation of every token. Early layers tend to capture surface patterns such as spelling and grammar. Later layers capture more abstract information such as meaning, intent and relationships across long passages. By the final layer, the vector for the last token contains a rich summary of everything the model has read.
Step 4, from vectors to a probability distribution
At the end of the stack, the model converts the final vector into a score for every token in its vocabulary, often tens of thousands of possible tokens or more. These scores are turned into probabilities.
So the output of a single forward pass is not a word. It is a probability distribution, for example:
- "function" 31%
- "method" 22%
- "class" 9%
- thousands of other tokens with smaller probabilities
Step 5, sampling, one token at a time
The system then samples one token from that distribution, appends it to the input and runs the model again. This loop repeats until the model produces a stop token or reaches the maximum output length you set.
That is why responses appear word by word when you use streaming. The model genuinely generates them one token after another.
Several settings control the sampling:
- Temperature: lower values make the model pick high-probability tokens more often, giving more predictable output. Higher values add variety.
- Top-p and top-k: these limit sampling to the most likely tokens, cutting off the long tail of unlikely options.
- Max tokens: the upper limit on output length.
For code generation and data extraction, low temperature is usually better. For brainstorming, a higher setting can help. Some newer models and API settings manage parts of this for you, so always check the provider's documentation.
How models are trained
Training happens in stages.
Pre-training
The model is trained on a huge dataset of text and code. For each position in each document, it predicts the next token, compares the prediction with the real token and adjusts its billions of internal parameters slightly to do better next time. This process, called gradient descent, runs on thousands of specialised chips for weeks or months.
At the end, you have a base model: very good at continuing text, but not necessarily good at following instructions or being helpful.
Instruction tuning
Next, the model is trained on examples of instructions and good responses. This teaches it the format of a conversation: a user asks, an assistant answers.
Learning from feedback
Finally, developers use techniques such as reinforcement learning from human feedback (RLHF) and related methods. People, and sometimes other AI systems guided by written principles, compare responses and indicate which are better. The model is then adjusted to produce more of the preferred kind of response.
Anthropic, for example, has published research on Constitutional AI, where a written set of principles guides how the model is trained to be helpful, honest and harmless.
Reasoning training
Recent models are also trained to work through problems step by step before answering, sometimes called thinking or reasoning modes. Instead of answering immediately, the model generates intermediate reasoning, which improves performance on maths, coding and complex analysis, at the cost of more tokens and time.
Why LLMs hallucinate
Now we can explain the frustrating behaviour from the introduction.
The model's job is to produce plausible text. When it knows the answer well, plausible and correct are the same. When it does not, it still produces plausible text, because that is what it was trained to do. A made-up function name that follows the library's naming pattern is extremely plausible.
Other causes include:
- Knowledge cutoff: the model only knows what was in its training data, which ends at a certain date.
- Ambiguous prompts: if your question can be read several ways, the model may pick the wrong one.
- Long contexts: important details buried in a very long prompt may receive less attention.
We cover practical defences in detail in our article on reducing AI hallucinations in production. The short version: give the model the facts it needs (for example through retrieval), ask it to say when it is unsure, and verify critical outputs with code or tests.
The context window is the model's working memory
An LLM has no memory between API calls. Each request is independent. When a chat app appears to remember your earlier messages, it is because the app sends the whole conversation, or a summary of it, with every new request.
The context window is the maximum amount of text, measured in tokens, that the model can consider in one request, including your prompt and its answer. Context windows have grown enormously, from a few thousand tokens in early models to hundreds of thousands, and in some current models up to around a million tokens.
Bigger is useful, but it is not free. Longer prompts cost more, take longer and can make it harder for the model to focus. Our article on context windows explains how to design around these limits.
Inference in production
When you call an API such as Claude's Messages API, a lot of engineering happens behind the scenes:
- requests are batched together on specialised hardware
- the work done on your prompt is cached internally while the answer is generated, so each new token does not reprocess everything from scratch
- some providers let you cache stable parts of your prompt across requests for lower cost and latency, a feature called prompt caching
Two numbers matter for user experience:
- Time to first token: how long until the first word appears.
- Output speed: how many tokens per second arrive after that.
Streaming improves perceived speed dramatically because users see progress immediately.
What this means for you as a developer
Understanding the mechanics leads to practical rules:
1. Be specific. The model predicts what comes next based on your prompt. Clear, detailed instructions narrow the space of plausible answers.
2. Provide facts, do not assume them. If accuracy matters, put the source material in the prompt.
3. Ask for structure. If you need JSON, use the provider's structured output features rather than hoping.
4. Keep prompts focused. More context is not always better.
5. Verify. Treat model output like code from a talented but unreliable new colleague: review it, test it and never deploy it blindly.
6. Watch tokens. They drive both cost and latency.
A quick mental model
If you remember only one picture, remember this: an LLM is a very large function that takes a sequence of tokens and returns probabilities for the next token. Training shaped that function on enormous amounts of human writing and feedback. Your prompt is the only steering wheel you have at inference time.
Once you see it this way, prompt engineering stops feeling like magic and starts feeling like engineering.
Related articles on MindStick
- Context Windows Explained and Why They Limit What AI Can Do
- Embeddings and Vector Search for Developers
- Understanding AI Hallucinations and How to Reduce Them in Production
- Tokens, Cost and Latency, Budgeting an AI Application
This article explains general concepts. Specific model behaviour, limits and settings vary by provider and change over time, so always check the official documentation for the model you use.
Leave a Comment