Article · LLM fundamentals · Prompt engineering
LLM fundamentals: tokens, context windows and next-token prediction
How a large language model really works – from tokenization and the transformer, through context windows and sampling, to costs, hallucinations and a first API call in five languages.
A large language model (LLM) is not a knowledge base or a search engine. It is a function that, given a piece of text, returns a probability distribution over the next token – and it does this so well that translation, coding and reasoning emerge from that single skill. Once you understand the mechanics, you know why the model "forgets", where hallucinations come from and what exactly you are paying for on the invoice.
- 1M
- tokens of context window – Claude Opus 5.5, Sonnet 5.5 and Haiku 5.5 (as of November 2026)
- 5×
- how much more an output token costs than an input token – a typical price ratio
- 0
- memory between calls – the API is stateless – you send the history
The problem: an assistant that invents allergens
Halina's Pierogi launches a chat on its ordering site. A developer wires up a model, pastes the prompt "You are the assistant of a pierogi restaurant, answer customer questions" and has a working demo within an hour. A week later three tickets arrive:
- A customer asked whether the spinach pierogi contain nuts. The model confidently said "no" – even though the menu says nothing about it and the sauce contains walnuts.
- In a long conversation the assistant "forgot" the delivery address the customer gave at the start.
- The API bill is three times the estimate, because every message carries the whole menu and the whole conversation so far.
Each of these problems follows directly from how an LLM works. Let's start with the mechanics.
Intuition: autocomplete that has read the internet
Your phone keyboard suggests the next word based on the previous two or three. An LLM does the same, except that it looks at the entire text so far (even hundreds of thousands of tokens), and its "statistics" are billions of parameters learned from a huge corpus of text and code. To predict how "Ruskie pierogi are filled with…" continues, the model has to capture grammar, cooking and the context of the conversation – and that very pressure is what makes knowledge about the world get encoded in the parameters.
The answer is not produced all at once. The model generates one token, appends it to the input and computes the next one – until it emits an end token or hits the max_tokens limit.
Tokens: the currency of language models
The model sees neither letters nor words, only tokens – numbers from a fixed vocabulary (typically tens to hundreds of thousands of entries). The vocabulary is built with an algorithm such as BPE (Byte Pair Encoding): it starts from single bytes and repeatedly merges the most frequent pairs into new tokens. Common English words become a single token; rarer ones break into pieces.
| Text | Example split (illustrative) | Why |
|---|---|---|
the order | the · order | common words = single tokens, the space often belongs to the token |
pierogarnia | pier · og · arnia | a rare non-English word is assembled from pieces |
zamówień | zam · ów · ień | Polish diacritics and inflection multiply tokens |
2026-11-26 | 202 · 6 · - · 11 · - · 26 | numbers split unintuitively – hence the trouble with arithmetic |
The exact split depends on a given model's tokenizer – the table shows the phenomenon, not an exact result. Three consequences matter to developers:
- Cost and limits are measured in tokens, not characters. The same text in Polish usually costs noticeably more tokens than in English – measure instead of guessing.
- Tokenizers differ between vendors, and even between model generations of the same vendor. The
tiktokenlibrary counts tokens for OpenAI models and gives wrong numbers for Claude; for Claude use thecount_tokensendpoint. - Model quirks (counting letters in a word, reversing strings, arithmetic on long numbers) often come from the fact that the model never saw individual characters.
Counting tokens and estimating cost
import anthropic
client = anthropic.Anthropic()
# List prices in USD per 1M tokens (check the pricing page before relying on them).
PRICES = {
"claude-opus-5-5": (4.00, 20.00),
"claude-sonnet-5-5": (2.00, 10.00),
"claude-haiku-5-5": (0.10, 0.50),
}
def estimate(model: str, system: str, question: str, expected_output: int) -> float:
# count_tokens uses the real tokenizer of the given model - never tiktoken.
counted = client.messages.count_tokens(
model=model,
system=system,
messages=[{"role": "user", "content": question}],
)
price_in, price_out = PRICES[model]
return (counted.input_tokens * price_in + expected_output * price_out) / 1_000_000
menu = open("menu.md", encoding="utf-8").read() # ~ the whole menu as context
for model in PRICES:
cost = estimate(model, menu, "Which pierogi are vegan?", expected_output=300)
print(f"{model:20} ${cost:.5f} per question")import Anthropic from "@anthropic-ai/sdk";
import { readFileSync } from "node:fs";
const client = new Anthropic();
// List prices in USD per 1M tokens (check the pricing page before relying on them).
const PRICES = {
"claude-opus-5-5": [4.0, 20.0],
"claude-sonnet-5-5": [2.0, 10.0],
"claude-haiku-5-5": [0.1, 0.5],
} as const;
type ModelId = keyof typeof PRICES;
async function estimate(model: ModelId, system: string, question: string, expectedOutput: number) {
// countTokens uses the real tokenizer of the given model - never a GPT tokenizer.
const counted = await client.messages.countTokens({
model,
system,
messages: [{ role: "user", content: question }],
});
const [priceIn, priceOut] = PRICES[model];
return (counted.input_tokens * priceIn + expectedOutput * priceOut) / 1_000_000;
}
const menu = readFileSync("menu.md", "utf8");
for (const model of Object.keys(PRICES) as ModelId[]) {
const cost = await estimate(model, menu, "Which pierogi are vegan?", 300);
console.log(`${model.padEnd(20)} $${cost.toFixed(5)} per question`);
}using Anthropic;
using Anthropic.Models.Messages;
AnthropicClient client = new();
// List prices in USD per 1M tokens (check the pricing page before relying on them).
var prices = new Dictionary<string, (decimal In, decimal Out)>
{
["claude-opus-5-5"] = (4.00m, 20.00m),
["claude-sonnet-5-5"] = (2.00m, 10.00m),
["claude-haiku-5-5"] = (0.10m, 0.50m),
};
string menu = await File.ReadAllTextAsync("menu.md");
foreach (var (model, price) in prices)
{
// CountTokens uses the real tokenizer of the given model.
MessageTokensCount counted = await client.Messages.CountTokens(new MessageCountTokensParams
{
Model = model,
System = menu,
Messages = [new UserMessageParam { Content = "Which pierogi are vegan?" }],
});
const int expectedOutput = 300;
decimal cost = (counted.InputTokens * price.In + expectedOutput * price.Out) / 1_000_000m;
Console.WriteLine($"{model,-20} ${cost:F5} per question");
}The context window: everything the model sees at once
The context window is the maximum number of tokens a model processes in a single call – input and output together. It holds the system prompt, tool definitions, attached documents, the whole conversation history, the current question and the generated answer.
The most important fact beginners forget: the API is stateless. The model does not remember the previous call. A chat's "memory" is an illusion created by the application, which sends the entire history every time.
This explains two of the pierogi tickets. The assistant "forgot" the address because the application trimmed the history to the last five messages. And the bill grew because on every turn the whole menu and the whole conversation were counted again as input tokens:
| System prompt (menu) | Tool definitions | Conversation history | |
|---|---|---|---|
| turn 1 | 1800 tokens | 1200 tokens | 150 tokens |
| turn 2 | 1800 tokens | 1200 tokens | 1250 tokens |
| turn 3 | 1800 tokens | 1200 tokens | 2350 tokens |
| turn 4 | 1800 tokens | 1200 tokens | 3450 tokens |
| turn 5 | 1800 tokens | 1200 tokens | 4550 tokens |
| turn 6 | 1800 tokens | 1200 tokens | 5650 tokens |
| turn 7 | 1800 tokens | 1200 tokens | 6750 tokens |
| turn 8 | 1800 tokens | 1200 tokens | 7850 tokens |
A large window (a million tokens) does not mean it is worth filling. Every token costs money and adds latency, and models make worse use of information "buried" in the middle of a very long context (a phenomenon known as lost in the middle). Good practice is to send what is needed: the relevant document fragments instead of the whole knowledge base – which is exactly the idea behind RAG – and to summarize or compact the older part of the conversation.
What happens inside: the transformer in five sentences
Almost all modern LLMs are decoder-only transformers, descended from the 2017 paper Attention Is All You Need.
- Each token is turned into an embedding – a vector of a few thousand numbers – enriched with information about its position in the text.
- The vectors pass through dozens of transformer blocks. In each, the self-attention mechanism lets a token "look at" all earlier tokens and pull relevant information from them (for example, who "he" refers to), and an MLP layer processes the result.
- A causal mask makes each token see only the past – the model learns to predict the future without peeking at it.
- The last vector is projected onto logits – one number per vocabulary token – and the softmax function turns them into probabilities.
- The next token is chosen from that distribution.
This also explains the price list. The model processes input tokens in parallel (the prefill phase), but has to generate output tokens one after another, each requiring a separate pass through the network (the decode phase, sped up by the KV cache). That is why an output token costs several times more, and why answer length has the biggest impact on waiting time.
Sampling: why the same request gives different answers
The model returns a distribution, not a single answer. The strategy for picking a token from it is called sampling. The classic knobs are:
- temperature – divides the logits before the softmax: a low value sharpens the distribution (the favourite almost always wins), a high one flattens it (more variety and more risk),
- top-p (nucleus sampling) – samples only from the most probable tokens whose cumulative probability reaches p,
- top-k – samples from the k best candidates.
The chart shows a real softmax computed for made-up logits of candidates completing the sentence "Ruskie pierogi are filled with…":
| T = 0.5 | T = 1.0 | T = 1.5 | |
|---|---|---|---|
| potatoes | 78.6 % | 54.2 % | 42.2 % |
| cheese | 15.9 % | 24.4 % | 24.7 % |
| quark | 4.8 % | 13.4 % | 16.6 % |
| onion | 0.5 % | 4.5 % | 8 % |
| meat | 0.1 % | 2.2 % | 5 % |
| cabbage | 0 % | 1.3 % | 3.6 % |
Even at zero temperature, do not count on bit-for-bit reproducible answers – floating-point arithmetic on GPUs and batching on the provider's side introduce small differences. Tests for LLM applications are therefore written as evaluations with criteria, not string comparisons.
Your first API call
The hottest new programming language is English.
Enough theory – time to send a request. All official Anthropic SDKs look similar: the client reads the key from ANTHROPIC_API_KEY, the call takes a model, an output token limit, a system prompt and a list of messages, and the response contains content blocks, a stop reason (stop_reason) and token usage (usage).
First Messages API call
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
SYSTEM = (
"You are the support assistant of Halina's Pierogi. "
"Answer briefly. If you are not sure, say so instead of guessing."
)
response = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system=SYSTEM,
messages=[{"role": "user", "content": "Do you deliver on Sundays?"}],
)
# The model may stop for different reasons - always check before trusting the text.
if response.stop_reason == "max_tokens":
print("Answer was cut off - raise max_tokens or ask for a shorter reply.")
elif response.stop_reason == "refusal":
print("Request declined.")
for block in response.content:
if block.type == "text":
print(block.text)
# Every response reports what you pay for.
usage = response.usage
print(f"input={usage.input_tokens} output={usage.output_tokens}")import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment
const SYSTEM =
"You are the support assistant of Halina's Pierogi. " +
"Answer briefly. If you are not sure, say so instead of guessing.";
const response = await client.messages.create({
model: "claude-opus-5-5",
max_tokens: 1024,
system: SYSTEM,
messages: [{ role: "user", content: "Do you deliver on Sundays?" }],
});
// The model may stop for different reasons - always check before trusting the text.
if (response.stop_reason === "max_tokens") {
console.warn("Answer was cut off - raise max_tokens or ask for a shorter reply.");
} else if (response.stop_reason === "refusal") {
console.warn("Request declined.");
}
for (const block of response.content) {
if (block.type === "text") console.log(block.text);
}
// Every response reports what you pay for.
const { input_tokens, output_tokens } = response.usage;
console.log(`input=${input_tokens} output=${output_tokens}`);using Anthropic;
using Anthropic.Models.Messages;
AnthropicClient client = new(); // reads ANTHROPIC_API_KEY from the environment
const string SystemPrompt =
"You are the support assistant of Halina's Pierogi. " +
"Answer briefly. If you are not sure, say so instead of guessing.";
var response = await client.Messages.Create(new MessageCreateParams
{
Model = "claude-opus-5-5",
MaxTokens = 1024,
System = SystemPrompt,
Messages = [new UserMessageParam { Content = "Do you deliver on Sundays?" }],
});
// The model may stop for different reasons - always check before trusting the text.
if (response.StopReason == "max_tokens")
Console.WriteLine("Answer was cut off - raise MaxTokens or ask for a shorter reply.");
foreach (var text in response.Content.Select(b => b.Value).OfType<TextBlock>())
Console.WriteLine(text.Text);
// Every response reports what you pay for.
Console.WriteLine($"input={response.Usage.InputTokens} output={response.Usage.OutputTokens}");import com.anthropic.client.AnthropicClient;
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
import com.anthropic.models.messages.Message;
import com.anthropic.models.messages.MessageCreateParams;
public class FirstCall {
public static void main(String[] args) {
// Reads ANTHROPIC_API_KEY from the environment.
AnthropicClient client = AnthropicOkHttpClient.fromEnv();
MessageCreateParams params = MessageCreateParams.builder()
.model("claude-opus-5-5")
.maxTokens(1024L)
.system("You are the support assistant of Halina's Pierogi. "
+ "Answer briefly. If you are not sure, say so instead of guessing.")
.addUserMessage("Do you deliver on Sundays?")
.build();
Message response = client.messages().create(params);
response.content().stream()
.flatMap(block -> block.text().stream())
.forEach(text -> System.out.println(text.text()));
// Every response reports what you pay for.
System.out.printf("input=%d output=%d%n",
response.usage().inputTokens(), response.usage().outputTokens());
}
}package main
import (
"context"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go/v2"
)
func main() {
client := anthropic.NewClient() // reads ANTHROPIC_API_KEY from the environment
resp, err := client.Messages.New(context.Background(), anthropic.MessageNewParams{
Model: "claude-opus-5-5",
MaxTokens: 1024,
System: []anthropic.TextBlockParam{{
Text: "You are the support assistant of Halina's Pierogi. " +
"Answer briefly. If you are not sure, say so instead of guessing.",
}},
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Do you deliver on Sundays?")),
},
})
if err != nil {
log.Fatal(err)
}
for _, block := range resp.Content {
if text, ok := block.AsAny().(anthropic.TextBlock); ok {
fmt.Println(text.Text)
}
}
// Every response reports what you pay for.
fmt.Printf("input=%d output=%d\n", resp.Usage.InputTokens, resp.Usage.OutputTokens)
}Note three details:
max_tokensis a hard output limit, not a wish. When the model reaches it, the answer is cut off mid-sentence andstop_reasonismax_tokens– always check it.contentis a list of blocks, not a single string. Besides text it can contain thinking blocks or tool calls – filter by type.usagetells you what you will pay. Log it from day one; without it you cannot optimize costs.
Streaming: the answer before it is complete
Generating a long answer takes seconds. Instead of making the user wait, display tokens as they are produced (streaming, technically Server-Sent Events). The key UX metric then becomes time to first token (TTFT), not the time of the whole answer.
Streaming the response
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=64000,
output_config={"effort": "low"}, # simple FAQ answer: little reasoning needed
messages=[{"role": "user", "content": "Explain in 3 sentences how you cook pierogi."}],
) as stream:
for text in stream.text_stream: # tokens arrive as they are generated
print(text, end="", flush=True)
final = stream.get_final_message()
print(f"\n[{final.stop_reason}] output tokens: {final.usage.output_tokens}")import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const stream = client.messages.stream({
model: "claude-opus-5-5",
max_tokens: 64000,
output_config: { effort: "low" }, // simple FAQ answer: little reasoning needed
messages: [{ role: "user", content: "Explain in 3 sentences how you cook pierogi." }],
});
// Tokens arrive as they are generated - render them immediately.
stream.on("text", (delta) => process.stdout.write(delta));
const final = await stream.finalMessage();
console.log(`\n[${final.stop_reason}] output tokens: ${final.usage.output_tokens}`);package main
import (
"context"
"fmt"
"log"
"github.com/anthropics/anthropic-sdk-go/v2"
)
func main() {
client := anthropic.NewClient()
stream := client.Messages.NewStreaming(context.Background(), anthropic.MessageNewParams{
Model: "claude-opus-5-5",
MaxTokens: 64000,
Messages: []anthropic.MessageParam{
anthropic.NewUserMessage(anthropic.NewTextBlock("Explain in 3 sentences how you cook pierogi.")),
},
})
// Tokens arrive as server-sent events - print each text delta immediately.
for stream.Next() {
event := stream.Current()
if delta, ok := event.AsAny().(anthropic.ContentBlockDeltaEvent); ok {
if text, ok := delta.Delta.AsAny().(anthropic.TextDelta); ok {
fmt.Print(text.Text)
}
}
}
if err := stream.Err(); err != nil {
log.Fatal(err)
}
}using Anthropic;
using Anthropic.Models.Messages;
AnthropicClient client = new();
var parameters = new MessageCreateParams
{
Model = "claude-opus-5-5",
MaxTokens = 64000,
Messages = [new UserMessageParam { Content = "Explain in 3 sentences how you cook pierogi." }],
};
// Tokens arrive as server-sent events - print each text delta immediately.
await foreach (RawMessageStreamEvent ev in client.Messages.CreateStreaming(parameters))
{
if (ev.TryPickContentBlockDelta(out var delta) && delta.Delta.TryPickText(out var text))
Console.Write(text.Text);
}Where the model "knows" anything from: training stages
1. Pretraining. The model learns to predict the next token on trillions of tokens of text and code. The result is a "base model" that completes text brilliantly but does not answer questions like an assistant.
2. Instruction tuning (SFT). On carefully prepared dialogue examples, the model learns the "question → helpful answer" format.
3. Reinforcement learning. RLHF (human ratings), RLAIF and Constitutional AI (ratings by another model following written principles) teach preferred behaviour: helpfulness, honesty, declining harmful requests. Training on verifiable tasks (maths, code) develops step-by-step reasoning.
4. Knowledge cutoff. Anything that happened after the training data was collected is unknown to the model – you have to supply current facts in the context.
- 2017 Attention Is All You Need – Vaswani et al. (Google) introduce the transformer architecture.
- 2018 GPT and BERT – OpenAI shows generative pretraining, Google the bidirectional BERT.
- 2019 GPT-2 – 1.5B parameters and a debate about whether to release the weights.
- 2020 GPT-3 – 175B parameters; learning "from a few examples in the prompt" (few-shot).
- 2022 InstructGPT and ChatGPT – RLHF turns a base model into an assistant; ChatGPT launches at the end of the year.
- 2023 GPT-4, Claude, Llama – a race between commercial and open-weight models.
- 2024 Reasoning models and MCP – models that "think before answering"; Anthropic publishes the Model Context Protocol.
- 2025 Agents – models in a loop with tools become part of developers' daily work.
Hallucinations: confident but untrue text
A hallucination is a fluent, convincing but false answer. It is not a bug in the model's code but a natural consequence of its training objective: the model generates probable text, and "sounds credible" does not mean "true". When the training data lacked the information (Halina's menu), the model will still produce something that fits stylistically.
How to deal with it:
- Grounding – attach the source of truth to the context (menu, terms) and instruct the model to answer only from it. For large document sets, RAG does this.
- Permission to say "I don't know" – state explicitly in the prompt what the model should do when data is missing. Without it, it will try to help at any cost.
- Citations and verification – ask for the supporting source fragment, and in critical places (allergens!) check the answer with a rule or a second call.
- Tools instead of memory – fetch the order status from your API through tool use instead of hoping the model will "guess" it.
- Measurement – a set of test questions with expected answers (evals) tells you whether a prompt change reduced the hallucination rate.
Costs: simple maths, big numbers
Call cost = input tokens × input price + output tokens × output price (+ any cache reads and writes). Prices are quoted per million tokens.
| Model | Context window | Max output | Input / output per 1M tokens |
|---|---|---|---|
claude-opus-5-5 | 1M | 128K | USD 4 / USD 20 |
claude-sonnet-5-5 | 1M | 128K | USD 2 / USD 10 |
claude-haiku-5-5 | 1M | 128K | USD 0.10 / USD 0.50 (prompts up to 100K tokens) |
Anthropic API list prices as of November 2026 – check the current price list before budgeting.
Let's price the pierogi chat: 50,000 conversations a month, 4 turns each, on average 6,000 input and 400 output tokens per turn. That is 1.2 billion input tokens and 80 million output tokens a month:
| Input tokens | Output tokens | |
|---|---|---|
| Opus 5.5 | 4800 USD | 1600 USD |
| Sonnet 5.5 | 2400 USD | 800 USD |
| Haiku 5.5 | 120 USD | 40 USD |
The takeaway: in conversational applications the input cost dominates, because history and context are sent over and over. The cheapest optimizations are a shorter context, prefix caching and matching the model to the task – simple ticket classification does not need the largest model.
When an LLM, and when plain code
Strengths
- understanding and generating natural language, including unstructured text
- summarizing, classifying and extracting data from text without writing rules
- generating and explaining code, translation, changing style
- one model handles hundreds of tasks – you only change the prompt
Weaknesses
- no guarantee of correctness: hallucinations and factual errors
- non-determinism makes classic unit tests hard
- cost and latency grow with context and answer length
- knowledge frozen at the training cutoff
- vulnerable to prompt injection when processing untrusted text
Pre-production checklist
- ☐ The system prompt says what to do when data is missing ("I don't know" instead of guessing)
- ☐ Facts (menu, prices, allergens) come from the context or tools, not from the model's memory
- ☐ Every response checks
stop_reason(max_tokens,refusal) - ☐
usageis logged per request and per application feature; you have a cost alert - ☐ Conversation history has a trimming or summarizing strategy – deliberate, not accidental
- ☐ The stable prompt prefix is cached and contains no variable data (dates, IDs)
- ☐ Answers are streamed in the user interface
- ☐ An evaluation set runs on every prompt or model change
Test yourself
Question: An application sends the model only the user's latest message. What happens on the third turn of the conversation?
- The model remembers the previous turns because the API keeps a session
- The model does not know the earlier turns and answers without their context
- The model reads the history from the previous call's context window
Question: Why does an output token cost several times more than an input token?
- Because output tokens are longer
- Because output is generated sequentially, token by token, while input is processed in parallel
- Because the provider adds the cost of moderating answers
Interview question: how does the context window differ from training knowledge?
Training knowledge is stored in the model's parameters – "frozen" at the cutoff date, imprecise and impossible to change without retraining or fine-tuning. The context window is the data supplied in a specific call: the model uses it literally and up to date, but only in that single request and only up to the token limit. That is why current and company-specific facts are passed in the context (prompt, RAG, tools) rather than relying on the model's memory.
What's next
You know the mechanics – now learn to steer them. The next steps on the "AI for developers" path:
Prompt engineering – How to write instructions, examples and output formats so the model does what you want
Embeddings and vector databases – Turning text into meaning vectors and searching by similarity
RAG – Answers grounded in your own documents instead of the model's memory
Evaluation (evals) – How to measure whether a prompt or model change really improved anything