Sub topic 1
How a language model turns a prompt into text
Prerequisites
This chapter assumes you can read basic Python, know what JSON is, and have used a chatbot or AI assistant. You do not need any machine learning background. Later chapters build on the working model described here.
The core idea: predict the next token
A large language model (LLM) is a program that, given some text, produces a probability for every possible next piece of text. It then picks one piece, appends it, and repeats. Everything an LLM does, including answering questions, writing code, and filling in JSON, comes from this loop.
The pieces are called tokens. A token is a chunk of text, often a whole common word, part of a rarer word, a punctuation mark, or a space plus a few letters. The model never sees raw characters. A tokenizer converts your text into a list of integer IDs, and the model returns scores over a fixed vocabulary of tens of thousands of such tokens.
Token counts matter in practice. English text averages roughly three-quarters of a word per token, so 1,000 words is about 1,300 tokens. Code, numbers, and non-English text often split into more tokens per word. You pay for tokens, and the model's memory is measured in tokens.
From prompt to output: the generation loop
The steps for a single request are:
- The tokenizer converts the prompt into token IDs.
- The model reads all the tokens and produces a score for each vocabulary token as the next one.
- The scores become probabilities.
- A sampling rule picks one token.
- That token is appended to the sequence and the process repeats from step 2.
- Generation stops when the model emits a special end-of-sequence token or reaches a maximum length you set.
Because each token depends on all the tokens before it, the model produces output one token at a time. This is why responses can stream to the screen as they are generated, and why longer outputs take longer.
What happens inside the model
Inside, the model is a neural network, a large set of numeric parameters (often billions) arranged in layers. Most modern LLMs use the transformer architecture. Two parts are worth knowing.
- Embeddings. Each token ID is first mapped to a vector, a list of numbers. Tokens used in similar ways end up with similar vectors. The embeddings chapter returns to this idea.
- Attention. In each layer, every token position can look at earlier positions and weigh how relevant each one is. This lets the model connect a pronoun to the noun it refers to, or an instruction at the top of the prompt to a question at the bottom.
The parameters are fixed once training ends. When you send a prompt, the model does not learn from it. It only uses the prompt as input to a fixed function.
How the model was trained
Training happens in stages, and each stage shapes behavior you will see later.
| Stage | What it does | Effect you observe |
|---|---|---|
| Pretraining | Predicts the next token across a very large text collection | Broad knowledge of language, facts, and code, with a knowledge cutoff date |
| Instruction tuning | Trains on examples of instructions paired with good responses | The model follows requests instead of just continuing text |
| Preference tuning | Adjusts the model toward responses that people rated higher | More helpful tone, refusals on some requests, a tendency to sound confident |
A pretrained-only model asked "What is the capital of France?" might continue with more quiz questions. An instruction-tuned model answers. Most APIs expose instruction-tuned models.
Sampling: why outputs vary
The model produces probabilities, not a single answer. The sampling rule decides how to choose from them. The common settings are:
- Temperature. Scales how sharply the probabilities favor the top choice. Low values (near 0) almost always pick the most likely token. Higher values give less likely tokens more chance, so output is more varied.
- Top-p (nucleus sampling). Restricts the choice to the smallest set of tokens whose probabilities add up to p, such as 0.9.
- Max tokens. An upper limit on output length. If the model hits it, the output stops mid-sentence.
The sketch below shows what temperature does to a small set of scores. It is a simplified model of the real process, using only the standard library.
import math
import random
def sample(scores: dict, temperature: float) -> str:
if temperature == 0:
return max(scores, key=scores.get)
scaled = {tok: s / temperature for tok, s in scores.items()}
biggest = max(scaled.values())
weights = {tok: math.exp(v - biggest) for tok, v in scaled.items()}
total = sum(weights.values())
r = random.random() * total
running = 0.0
for tok, w in weights.items():
running += w
if r <= running:
return tok
return tok
scores = {"Paris": 5.0, "Lyon": 3.0, "banana": 0.5}
random.seed(0)
print([sample(scores, 0) for _ in range(5)])
print([sample(scores, 2.0) for _ in range(8)])At temperature 0 the output is always Paris. At 2.0 you will see Lyon and occasionally banana. The same prompt can therefore produce different outputs on different runs.
The context window
The context window is the maximum number of tokens the model can handle in one request, counting the prompt and the output together. Windows range from a few thousand tokens to hundreds of thousands or more, depending on the model.
Three consequences follow:
- The model has no memory between requests. A chat application works by resending earlier messages with each new request.
- If the input plus the output budget exceeds the window, the request fails or the oldest content must be cut.
- Longer prompts cost more and take longer, and models can use information in the middle of a very long prompt less reliably than information at the start or end.
Why this shapes what models do well and badly
The next-token view explains both strengths and failures.
Strengths. Predicting text well across huge amounts of data forces the model to pick up grammar, style, common facts, and patterns of reasoning. That is why it handles summarizing, rewriting, translating, and classifying with only an instruction.
Weaknesses that follow directly:
- Fluent but wrong output. The model is trained to produce plausible text, not verified text. When it lacks a fact, a plausible-sounding guess is still a likely continuation. This is often called hallucination.
- No access to current or private data. The parameters reflect training data up to a cutoff. Anything newer, or anything in your own documents, must be put into the prompt.
- Weak exact computation. Arithmetic, counting characters, and precise lookups are done by pattern, not by an algorithm. Use code for these.
- Sensitivity to wording. The prompt is the only input, so small changes to it can change the output.
Seeing the loop in code
Most APIs hide the loop, but the shape of a request is similar across providers. The function below is a stand-in that mimics the interface you will pass around in later chapters. It takes a prompt and returns text.
def fake_complete(prompt: str, max_tokens: int = 20) -> str:
# Stand-in for a real model API. A real call would send the prompt,
# run the generation loop on the provider's servers, and return text.
canned = "Paris is the capital of France."
words = canned.split()
return " ".join(words[:max_tokens])
def rough_token_estimate(text: str) -> int:
# About 4 characters per token for English prose. A rough guide only.
return max(1, len(text) // 4)
prompt = "What is the capital of France?"
reply = fake_complete(prompt)
print(reply)
print("approx prompt tokens:", rough_token_estimate(prompt))
print("approx reply tokens:", rough_token_estimate(reply))Real APIs return exact token counts in the response, and you should use those for budgeting instead of an estimate.
Common errors when starting out
- Treating the model as a database. It stores patterns, not records. Retrieve facts from a real source and pass them in.
- Expecting memory. If a second request needs the first request's content, you must include it.
- Ignoring the output limit. A truncated answer looks like a complete one unless you check why generation stopped. Most APIs report a stop reason.
- Raising temperature for "better" answers. Higher temperature adds variety, not accuracy. For classification and extraction, use low values.
- Trusting confidence. Fluent wording is not evidence of correctness.
Exercise
A teammate sends a prompt with temperature 0 twice and gets slightly different answers. They conclude the API is broken. Give two reasons this can happen, and say what a team should do in code to handle it.
Show answer
Hosted serving can produce tiny numeric differences (batching, floating-point order), so a near-tied token can flip, and the provider may update or route to different model versions. This is not a bug. In code, avoid exact string comparison of free-form output: constrain the output (for example to an allowed label list or validated JSON), check results against that constraint, and test with several runs.
Exercise
A request has a context window of 8,000 tokens. The prompt is 7,500 tokens and you set max tokens to 1,000. What is the problem, and what are two ways to fix it?
Show answer
The prompt plus the output budget is 8,500 tokens, which exceeds the 8,000 window, so the request may fail or the output will be cut off. Fix it by shortening the prompt (trim or summarize older content, include only relevant documents) or by lowering max tokens to 500 or less. Choosing a model with a larger window is a third option.