← All posts

AI basics › How LLMs work

What is a context window? How much an LLM can see at once

A context window is the most tokens an LLM can handle at once. What fills it, what happens when it overflows, and why longer inputs cost more.

News about a new AI model almost always mentions a number like a “1 million token” context window. And if you’ve had a long conversation with ChatGPT or Claude, perhaps you’ve felt that the model forgot something you told it at the very start. Both stories rest on the same idea. But because it goes by several names, such as context length or simply context, it’s easy to stay a little unsure about what the number actually counts.

A context window is the largest number of tokens a model can see and work with at once. When the model writes an answer, it can only see what’s inside this window, and Anthropic’s context windows page describes it as the model’s “working memory,” something separate from the data it was trained on. You hear the term often lately because windows have grown by a factor of several hundred in just a few years, so the size has become one of the ways people choose a model. And as more people paste whole documents into a chat or run AI agents that work for hours, actually hitting the limit has become common too.

What shares the window

More goes into the window than you might expect. According to the Anthropic page above, everything in the request counts: the system prompt, every message exchanged so far, the documents and images attached to them, the results of tool calls, and even the tool definitions. On top of that, the answer the model writes on this turn lives in the same window. The model writes its answer one token at a time, and every token it has already written has to be read again when it picks the next one. And the window is measured in tokens, the small pieces of text a model reads and writes, not in characters or words.

From 512 tokens to a million

The window has grown remarkably in a few years. The 2019 GPT-2 paper says it increased the context size from the 512 tokens of the earlier GPT to 1,024 tokens, and a year later, all the models in the GPT-3 paper used a 2,048-token window. Qwen2.5-0.5B-Instruct, the model I’ll use in the example below, has only 0.49 billion parameters, yet its model card lists a context length of 32,768 tokens.

Model Context window Where I checked
GPT (2018) 512 tokens GPT-2 paper
GPT-2 (2019) 1,024 tokens GPT-2 paper, model config file
GPT-3 (2020) 2,048 tokens GPT-3 paper
Qwen2.5-0.5B-Instruct (2024) 32,768 tokens Model card, model config file
Claude Opus 5.5 (2026) 1M tokens Anthropic docs

When I checked Anthropic’s docs on October 28, 2026, Claude Opus 5.5 and several other models were listed with a 1M-token window. Google’s Gemini long context page also says many Gemini models come with windows of 1 million tokens or more.

What happens when the window overflows

When the input grows longer than the window, one of three things usually happens. According to the Anthropic page, if the input alone exceeds the window, the Claude API returns a 400 error saying “prompt is too long,” on every model. Chat interfaces such as claude.ai may also manage the window on a rolling “first in, first out” basis. And the server-side compaction that the same page recommends summarizes earlier parts of the conversation automatically, so the conversation can keep going past the window’s limit.

Let’s reproduce the case where the beginning gets cut, using a small model. I put one made-up fact at the very top of a warehouse log, “The back door code for Warehouse 7 is 4071,” then add one uneventful line per day, and finally ask for the code. I compare two runs: one with the window set to the model’s real size of 32,768 tokens, and one that pretends the window is only 512 tokens and drops the oldest tokens first. Even when cutting, the system prompt and the question stay, and 10 tokens are kept free for the answer.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

name = "Qwen/Qwen2.5-0.5B-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, dtype=torch.float32)
print("max_position_embeddings:", model.config.max_position_embeddings)

fact = "The back door code for Warehouse 7 is 4071."  # made up, placed first
question = "What is the back door code for Warehouse 7? Reply with the number only."
chat = [{"role": "user", "content": "@@\n\n" + question}]
head, tail = tok.apply_chat_template(chat, add_generation_prompt=True, tokenize=False).split("@@")
head, tail = tok(head).input_ids, tok(tail).input_ids  # system prompt, question

def ask(window, days, room=10):  # room: tokens kept free for the answer
    notes = [fact] + [f"Day {d}: we restocked shelf {d % 9 + 1} and swept the loading bay."
                      for d in range(1, days + 1)]
    body = tok("\n".join(notes)).input_ids
    body = body[-(window - room - len(head) - len(tail)):]  # drop the oldest tokens
    ids = torch.tensor([head + body + tail])
    out = model.generate(ids, attention_mask=torch.ones_like(ids), max_new_tokens=room,
                         do_sample=False, repetition_penalty=1.0)  # greedy decoding
    answer = tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True)
    print(f"window {window:>6,}, {days} days: prompt {ids.shape[1]:>5,} tokens, "
          f"fact kept: {'4071' in tok.decode(body)}, answer: {answer!r}")

ask(32_768, 60)
ask(512, 60)
ask(32_768, 80)

This model turns on sampling and a repetition penalty by default, and do_sample=False with repetition_penalty=1.0 switches both off. What remains is greedy decoding, which always takes the most likely next token, so the answer is the same however many times you run it.

max_position_embeddings: 32768
window 32,768, 60 days: prompt 1,073 tokens, fact kept: True, answer: '4071'
window    512, 60 days: prompt   502 tokens, fact kept: False, answer: '7'
window 32,768, 80 days: prompt 1,413 tokens, fact kept: True, answer: '4'

The 32,768 on the first line is the maximum number of positions in the config file, and it matches the context length on the model card. With sixty days of notes, the prompt came to 1,073 tokens, which fit easily in the 32,768-token window, and the model answered 4071 correctly. When I shrank the window to 512 tokens, though, the system prompt that the chat template adds on its own plus the question took 47 tokens, the answer’s space took 10, and only 455 tokens were left for the notes. The line with the code at the very top was cut off, and instead of saying it didn’t know, the model answered 7. Perhaps it borrowed the number from “Warehouse 7” in the question. To the model, a line that was cut is the same as a line that never existed. That’s why, if a chatbot seems to forget what you said early in a long conversation, it’s worth first suspecting that those words have already been pushed out of the window.

Information missed even inside the window

Being inside the window doesn’t mean the model will always use it well, though. The last line of the output above is an example. With 80 days of notes, the prompt came to 1,413 tokens, less than 5% of the window, and the code wasn’t cut. Yet the model wrote only 4 and stopped. When I added days a few at a time, it still answered 4071 at 65 days (1,158 tokens) and stopped at 4 from 70 days (1,243 tokens) on. So for this small model, a length under 4% of its window was already too much.

Larger models aren’t free of this either. In their 2023 paper Lost in the Middle, Nelson F. Liu and colleagues asked models questions over 20 documents (about 4K tokens), moving the document that held the answer to different positions. Performance traced a U shape: it was highest when the answer sat at the very beginning or the very end, and dropped sharply when it sat in the middle. In the worst case, GPT-3.5-Turbo scored lower than it did with no documents at all (56.1%). And GPT-3.5-Turbo with its window extended to 16K performed almost exactly like the original wherever the input fit in both. In 2025, NoLiMa also found that 11 of 13 models claiming support for at least 128K tokens fell below half their short-input scores at 32K. The size of the window tells you how much fits, and how well the model uses what’s inside is something you have to check separately.

Compute and memory grow with length

Using a big window also costs more. Attention in a transformer compares every token with every token before it, so, as the comparison table in Attention Is All You Need shows, the compute per layer grows with the square of the length. On the memory side, the KV cache grows. The KV cache stores the key and value vectors already computed for every token the model has read. As Hugging Face’s cache guide explains, it exists so the model doesn’t repeat the same work each time it generates a token. The catch is that every token adds keys and values for every layer, so the longer the conversation, the larger this store becomes. Let’s work out its size from the example model’s config.

from transformers import AutoConfig

cfg = AutoConfig.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
head_dim = cfg.hidden_size // cfg.num_attention_heads
print(f"{cfg.num_hidden_layers} layers, {cfg.num_attention_heads} query heads, "
      f"{cfg.num_key_value_heads} KV heads, head size {head_dim}")

# a key and a value for every layer and KV head, 2 bytes per number (bfloat16)
per_token = 2 * cfg.num_hidden_layers * cfg.num_key_value_heads * head_dim * 2
print(f"KV cache: {per_token:,} bytes per token")
for n in [512, 4_096, 32_768]:
    print(f"{n:>6,} tokens: {n * per_token / 2**20:5,.0f} MiB")
24 layers, 14 query heads, 2 KV heads, head size 64
KV cache: 12,288 bytes per token
   512 tokens:     6 MiB
 4,096 tokens:    48 MiB
32,768 tokens:   384 MiB

A full window of 32,768 tokens comes to 384 MiB. For a model whose weight file is about 988 MB, one conversation’s cache takes roughly 40% of that, and ten long conversations at once take ten times as much. To check the arithmetic, I fed the model 1,000 real tokens, and the cache came out to exactly 12,288,000 bytes. That’s already the smaller version, too. This model uses grouped-query attention (GQA), where 14 query heads share 2 KV heads, so its cache is one seventh the size it would be with a separate KV head for every query head.

Because compute and memory grow together, a long input shows up in both waiting time and price. Anthropic’s models overview notes that actual latency depends on prompt length and output length, and since API prices are set per million tokens, the more tokens you send, the more you pay.

How it differs from output limits, training data, and long-term memory

A number people often confuse with the context window is the maximum output tokens. The maximum output is the cap on how many new tokens the model can write in one request, while the window is the cap on input and output together. In the same models overview, which I read on October 28, 2026, Claude Opus 5.5 had a 1M-token window and a maximum output of 128K tokens. And according to the context windows page, generation stops where it reaches the window’s limit. So if you send 950K tokens, the model can really only write about the 50K tokens left, even with a 128K output limit.

The window is also different from training data. If you think of a desk, what the model learned in training is what’s in its head, meaning its parameters, and the window is the papers spread out on the desk for this conversation. When the conversation ends, the desk is cleared, but the parameters stay as they were.

Features called long-term memory still pass through the window in the end. For example, Claude Code’s memory docs explain that each session begins with a fresh context window, and that the CLAUDE.md files you write and the auto memory Claude writes for itself are loaded at the start of every session. So the memory lives in files outside the window, and the window reads it back in each session.

When a big window fits and when to save space

A big window fits well when the whole thing has to be seen at once, like a long contract or code spread across several files. If you split such material up, the model can’t see how one piece relates to another. On the other hand, if only part of a long source matters, putting all of it in adds time and cost, and it may even make the answer worse.

So it helps to know a few ways to save space. First, put important instructions and the question at the beginning or the end, where they won’t get buried in the middle. Anthropic’s prompting guide recommends putting long material of 20k tokens or more near the top and the question at the end, and says that in tests, putting the question at the end improved response quality by up to 30%. The Gemini page also recommends placing the question at the very end. Then summarize old conversation into something shorter, and from long sources, find and include only the pieces that relate to the question. The work of choosing what goes into the window at each step is often discussed separately under the name context engineering.

If you’re trying it for the first time

If you’re new to this, I’d suggest changing days and window in the first example and watching when the answer changes. The model, about 1 GB, downloads automatically on the first run. You could also move the code line into the middle of the log. If there’s a model you use regularly, look up its window size and maximum output together in its docs, and check whether the output counts toward the window. I ran these examples on October 28, 2026, on a Mac CPU with Python 3.13.12, PyTorch 2.14.1, Transformers 5.20.2, and Qwen2.5-0.5B-Instruct.

AI tools helped with the research for this post.