Sub topic 1
How a language model turns a prompt into a response
Prerequisites
This chapter assumes you have the following:
- You have used a chat-based AI assistant and typed requests into it.
- You can read short Python snippets. You do not need to write them.
- You know what JSON is, at the level of keys and values.
You do not need any machine learning background. The chapter builds a working model of what happens between pressing Enter and seeing a reply. Later chapters rely on this model.
What a language model does
A large language model (LLM) is a program that predicts text. Given some text, it estimates which piece of text is likely to come next. It then adds that piece and repeats the process. A reply is the result of many of these small predictions in a row.
Three facts follow from this, and they explain most prompting advice:
- The prompt is the only input. The model does not see your intentions, your project, or your previous work unless that information appears in the text it receives.
- The model continues text in a plausible way. It is not looking up answers in a database. It produces text that fits the pattern of what came before.
- Wording changes the result. A different prompt is a different starting text, so the likely continuations change.
From text to tokens
A model does not read letters or whole words. It reads tokens. A token is a chunk of text, such as a short word, part of a longer word, a number fragment, or a punctuation mark. A tokenizer is the component that splits text into tokens and maps each one to an integer ID.
For example, a tokenizer might split Prompting is fun. into pieces like Prompt, ing, is, fun, and .. The exact split depends on the model, so you cannot predict it perfectly by eye. As a rough guide, one token is about four characters of English text, or three quarters of a word.
Tokens matter for practical reasons:
- Limits are counted in tokens. The model has a maximum number of tokens it can handle at once.
- Cost and speed usually scale with tokens.
- Character-level tasks are harder than they look. Counting the letters in a word or reversing a string is awkward because the model sees chunks, not individual letters.
The context window
The context window is the maximum number of tokens the model can consider in one request. It covers everything: your instructions, any pasted documents, earlier conversation turns, and the reply the model is writing.
This has two consequences.
First, a long prompt leaves less room for the answer. If the window is 8,000 tokens and your prompt uses 7,500, the reply can be at most about 500 tokens.
Second, the model has no memory between requests. A chat application creates the feeling of memory by resending the earlier conversation each time. If something falls out of the window, the model cannot use it.
Predicting the next token
At each step, the model reads all the tokens so far and produces a score for every token in its vocabulary. These scores are converted into probabilities that add up to 1. The model then picks one token, appends it to the text, and runs again.
Here is a simplified example. The prompt is The capital of France is. The model might assign these probabilities to the next token:
| Candidate next token | Probability |
|---|---|
| ` Paris` | 0.92 |
| ` a` | 0.03 |
| ` located` | 0.02 |
| ` the` | 0.01 |
| Everything else | 0.02 |
The numbers are illustrative, not measured from a real model. The point is the shape: a strong favorite and a long tail of unlikely options.
The loop looks like this.
The stop condition is one of two things. The model may emit a special end-of-reply token, or the output may reach a maximum length that you or the service set. If the maximum length cuts the reply off, you get a truncated answer that stops mid-sentence.
How selection works
The step labeled "Select one token" has a choice in it. The simplest rule is to always take the highest-probability token. This is called greedy selection. It is repeatable but can produce dull or repetitive text.
Most systems instead sample: they pick a token at random, weighted by its probability. A token with 0.92 is chosen about 92 times in 100, and a token with 0.02 is occasionally chosen. This is why asking the same question twice can give different wording, and sometimes different content.
Settings such as temperature control how sharp or flat the sampling is. A later chapter covers them in detail. For this chapter, remember one point: the same prompt does not guarantee the same output.
Why wording changes the output
Because the model continues the text it is given, every word in the prompt shifts the probabilities. Compare these two prompts:
Tell me about Python.You are helping a beginner who has never programmed. In two short paragraphs, explain what the Python programming language is used for.The first prompt is ambiguous. It could mean the snake or the language, and it gives no length, audience, or purpose. The model has to guess, and the guess may not match what you wanted. The second prompt narrows the possible continuations. It states the audience, the topic, and the size.
The model is not being obedient or disobedient. It is producing text consistent with the whole prompt. Precise prompts leave fewer plausible continuations, and a larger share of those continuations are ones you would accept.
Seeing the process in code
You can model the idea in a few lines of Python. The function below chooses a token from a probability table, once greedily and once by sampling. It is a toy, not a real language model, but it shows why sampling gives varied answers.
import random
# Illustrative probabilities for the token after "The capital of France is"
next_token_probs = {
" Paris": 0.92,
" a": 0.03,
" located": 0.02,
" the": 0.01,
" famous": 0.02,
}
def greedy(probs):
return max(probs, key=probs.get)
def sample(probs):
tokens = list(probs.keys())
weights = list(probs.values())
return random.choices(tokens, weights=weights, k=1)[0]
print("Greedy:", repr(greedy(next_token_probs)))
random.seed(0)
picks = [sample(next_token_probs) for _ in range(1000)]
for token in next_token_probs:
print(repr(token), picks.count(token))Run it and you will see that greedy selection always returns the same token. Sampling returns Paris most of the time, but the other tokens appear a few times in 1,000 draws. In a real model this happens at every step of a reply, so small differences can compound into noticeably different answers.
What the model does not do
Understanding the loop also tells you what to expect from the model, and what not to.
- It does not verify facts. It produces likely text. A fluent, confident sentence can still be wrong. The final chapter returns to this as hallucination.
- It does not remember you. Anything it needs must be in the current window.
- It does not know your private context. Your company's naming rules, your audience, and the meaning of internal terms must be written into the prompt.
- It does not plan the whole reply first. It writes one token at a time, with each token conditioned on the ones before it. This is one reason asking for step-by-step reasoning can help, as a later chapter explains.
- It does not treat instructions and data differently by default. Everything in the window is text. This matters for safety, because text pasted into a prompt can look like an instruction.
Common mistakes at this stage
| Mistake | Why it happens | Better approach |
|---|---|---|
| Assuming the model remembers an earlier chat | Chat apps hide the resending of history | Include needed facts in the current prompt |
| Expecting identical output every run | Selection is usually random | Test several runs before judging a prompt |
| Pasting a huge document with no instruction | Long text can crowd out the task and the reply space | State the task clearly and send only what is relevant |
| Treating a confident answer as a checked answer | Fluency is not accuracy | Verify important claims against a trusted source |
| Judging a prompt from one result | One sample may be lucky or unlucky | Compare several outputs, as the evaluation chapter shows |
A mental model to carry forward
Think of the prompt as the opening of a document that the model must continue. Your job is to write an opening that makes the continuation you want the most likely one. Clear instructions, supplied context, examples, and format requests are all ways of shaping that opening.
The remaining chapters build on this idea. Each technique either narrows the set of plausible continuations, supplies information the model lacks, or gives you a way to check the result.
Exercise
A colleague says, "I told the assistant our product name in yesterday's chat, so I don't need to repeat it in today's new chat." Explain, using what you learned about the prompt and the context window, why this may fail. Then write one sentence they could add to the prompt to fix it.
Show answer
The model's only input is the text in the current context window. A new chat does not resend yesterday's conversation, so the product name is not in the window and the model cannot use it. The colleague should state it again, for example: "Our product is called Northwind Reports, a tool for generating weekly sales summaries."
Exercise
Run the Python example twice, once as written and once after changing random.seed(0) to random.seed(1). What changes and what stays the same? What does this suggest about running the same prompt on a real model several times?
Show answer
The greedy result stays the same, because it always picks the highest-probability token (" Paris"). The sampled counts change slightly between seeds, because random draws differ, although " Paris" stays dominant. This suggests that a real model can give different outputs for the same prompt, so you should run a prompt several times before deciding whether it works.
Exercise
A request has a context window of 4,000 tokens. Your prompt, including a pasted article, uses 3,900 tokens. What problem can you expect, and what two changes could help?
Show answer
Only about 100 tokens remain for the reply, so the answer may be cut off mid-sentence or be too short to be useful. You could shorten the pasted article to the relevant parts, and you could tighten the instructions. Using a model with a larger context window is another option.