PROMETHEUS OS
NATIVE AI OPERATING SYSTEM
[INIT] Prometheus OS loading...
[CORE] Neural interface initializing...
[AI] LLM router connecting...
[MEM] Memory graph loading...
[AGT] Agent chains on standby...
[SEC] Security protocols active...
[NET] Provider mesh established...
[UI] Workspace rendering...
[DONE] All systems nominal.
Welcome to PROMETHEUS OS.
READY · OFFLINE · SECURE · PRIVATE
🎨 THEME ENGINE
PROMETHEUS OS · 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

Context Windows and Memory

Beginner 13 min· 4 exercises

What a context window is, how it is measured in tokens, what chat-app "memory" really is, and why answers can get worse deep into long conversations or documents.

By the end of this lesson you will be able to
  • Estimate the token count of a text and plan a token budget across system prompt, history, documents and output.
  • Explain why longer contexts cost more time and memory, including the quadratic growth of attention scores and linear growth of the KV cache.
  • Calculate a model's KV-cache memory from its layer count, KV heads, head dimension and precision.
  • Distinguish advertised context length from effective context length and describe how it is measured.
  • Implement a simple history-trimming strategy that keeps a conversation within its budget.

Before this: Prompting Fundamentals, How Large Language Models Work

Every AI chat has a limit on how much text the model can consider at once. Knowing that limit, and what really happens when a chat app "remembers" you, explains a lot of odd behaviour, from forgotten instructions to answers that get worse in very long conversations.

What a context window is

The context window is the maximum amount of text a model can take in and work with in a single request. It includes everything: the app's hidden instructions, your messages, the model's earlier replies, any documents you attached, and the answer the model is writing now.

An analogy: the context window is the model's desk. Whatever is on the desk, it can look at. Anything that does not fit on the desk simply is not there, no matter how important it was earlier. The model does not have a filing cabinet behind it that it can rummage through on its own.

Measured in tokens

Context windows are measured in tokens, the small chunks of text a model actually reads. A token is often a whole short word, part of a longer word, or a punctuation mark. As a rough rule of thumb for English, one token is about three-quarters of a word, so 1,000 tokens is roughly 750 words. Other languages, code and unusual words often use more tokens per word, so treat this as an estimate.

Worked example. A 300-page novel has roughly 100,000 words. At about 0.75 words per token, that is around 133,000 tokens. A model with a 128,000-token window could not hold the entire book plus your question; a model with a 1-million-token window could, with plenty of room left.

As of November 2026, leading hosted models commonly advertise context windows from a few hundred thousand tokens up to around a million. For example, Google lists a 1-million-token window for Gemini 4 Argon, and Anthropic lists a 1-million-token window for Claude Opus 5.5. Smaller models, and models run on your own computer, often work with much less. These figures change frequently, so check the current documentation for the model you use.

What "memory" in a chat app actually is

The model itself does not remember anything between requests. Each time you send a message, the app sends the model a fresh bundle of text. What feels like memory is built from a few tricks:

  • Re-sent history. Within one conversation, the app re-sends earlier messages along with your new one. That is why the model "remembers" what you said ten messages ago: it is reading it again.
  • Summaries. When a conversation gets too long to fit, some apps quietly compress older parts into a summary, or drop them entirely. Details can be lost in that compression.
  • Saved memories and personalisation. If your app has a memory or personalisation feature, it typically stores short notes about you (for example, "prefers metric units") and inserts them into the context of new chats. The model has not learned these facts permanently; they are just added text.
  • Custom instructions. Standing instructions you set in settings are added to every conversation in the same way.

So a model can "forget" an instruction from early in a long chat because it was summarised away, dropped, or simply given less weight among a lot of other text.

Long documents

Large context windows let you paste in long reports, contracts or transcripts and ask questions about them. That is genuinely useful, but there are trade-offs:

  • Cost and speed. Every token in the window has to be processed. Longer inputs mean slower responses and, on paid services that charge per token, higher bills. Part of the reason is that the model keeps a working record of everything it has read, called the KV cache, which grows with the length of the context and takes up memory. (The lesson on KV cache and context cost covers this in detail.)
  • Usage limits. Many consumer plans cap how much you can use in a period, and long contexts use that allowance up faster.
  • Not always necessary. If you only need one section, paste only that section.

Why quality can drop deep into long contexts

A model accepting a million tokens does not mean it pays equal attention to every one of them. Research has repeatedly found that reliability falls as inputs get longer:

  • A 2023 study, "Lost in the Middle", found that models answered questions best when the relevant information was near the start or the end of a long input, and noticeably worse when it was buried in the middle.
  • A 2025 technical report from the company Chroma tested 18 models and found that performance declined as input length grew, even on simple tasks such as finding and repeating a piece of text.

Newer models have improved, but the general lesson still holds: more context is not free, and the most important material can get diluted by everything around it.

Going deeper

Where tokens come from

Most modern models split text with a subword method descended from byte-pair encoding (BPE), adapted for language models by Sennrich, Haddow and Birch (2015). The idea: start from single characters (or bytes), then repeatedly merge the most frequent adjacent pair into a new token until the vocabulary reaches a target size. Common words end up as single tokens; rare words are built from several pieces. That is why "the" is one token, an unusual surname may be four, and languages or code that were less common in the tokenizer's training text need more tokens per word. The 0.75-words-per-token rule is an average for English prose; for precise counts, run the model's own tokenizer.

Budgeting the window

Everything shares one window of WW tokens:

Tsystem+Thistory+Tdocuments+Toutput≤WT_{\text{system}} + T_{\text{history}} + T_{\text{documents}} + T_{\text{output}} \le W

The output counts too, so you must reserve room for the answer before filling the rest.

Worked example. A model has W=128,000W = 128{,}000. The app's system prompt uses 2,000 tokens, the conversation so far 30,000, and you reserve 8,000 for the reply. The room left for documents is 128,000−2,000−30,000−8,000=88,000128{,}000 - 2{,}000 - 30{,}000 - 8{,}000 = 88{,}000 tokens, about 88,000×0.75=66,00088{,}000 \times 0.75 = 66{,}000 words. A 100,000-word document will not fit; you would trim it, summarise parts, or start a fresh chat to free the 30,000 tokens of history.

Why long contexts cost more

In a transformer, each new token is compared against every earlier token by the attention mechanism. Reading a prompt of nn tokens therefore involves roughly n2/2n^2/2 pairwise comparisons per attention layer. Doubling nn roughly quadruples that work, which is one reason very long prompts are slow to start answering. (Real systems use many optimisations, and other parts of the model grow only linearly with nn, so total cost grows somewhat less than fourfold; the direction of the effect is the point.)

The model also stores, for every token it has read, a key and a value vector in every layer so it does not recompute them: the KV cache. Its size grows linearly with context length:

KV bytes per token=2×L×Hkv×dhead×b\text{KV bytes per token} = 2 \times L \times H_{kv} \times d_{\text{head}} \times b

where LL is the number of layers, HkvH_{kv} the number of key/value heads, dheadd_{\text{head}} the size of each head, bb the bytes per stored number, and the 2 counts keys and values.

Worked example. A configuration typical of 8-billion-parameter models has L=32L = 32, Hkv=8H_{kv} = 8, dhead=128d_{\text{head}} = 128, stored at 16-bit precision (b=2b = 2):

2×32×8×128×2=131,072 bytes=128 KiB per token.2 \times 32 \times 8 \times 128 \times 2 = 131{,}072 \text{ bytes} = 128 \text{ KiB per token.}

At 100,000 tokens that is 131,072×100,000≈13.1131{,}072 \times 100{,}000 \approx 13.1 GB, more than the model's own weights at 4-bit precision. This is why local tools often default to short contexts, and why hosted providers price long inputs carefully.

Advertised versus effective context

A model accepting a million tokens tells you what it can read, not what it can use well. Researchers measure this with tests such as "needle in a haystack" (hide one fact at different depths of a long filler text and ask for it) and harder suites such as RULER (Hsieh et al., 2024), which adds multi-step tracing and aggregation tasks. RULER's authors found that almost all models aced the simple needle test, yet performance dropped substantially on the harder tasks as length grew, and only about half of the models that claimed windows of 32,000 tokens or more held up satisfactorily at 32,000. The useful idea is effective context length: the longest input at which a model still performs your kind of task reliably. It is often well below the advertised figure, and you can measure it for your own task.

Trimming history in code

Chat applications must decide what to drop when a conversation outgrows its budget. The simplest policy keeps the most recent messages that fit:

def est_tokens(text):
    # Rough English estimate (~0.75 words per token).
    # For real counts, use the model's own tokenizer.
    return round(len(text.split()) / 0.75)

def fit_history(system, messages, window=128_000, reserve_out=8_000):
    budget = window - reserve_out - est_tokens(system)
    kept = []
    for msg in reversed(messages):        # walk from newest to oldest
        cost = est_tokens(msg)
        if cost > budget:
            break
        kept.append(msg)
        budget -= cost
    return list(reversed(kept)), budget   # restore chronological order

msgs = ["word " * 3000, "word " * 59000, "word " * 1500]   # three old-to-new messages
kept, left = fit_history("You are helpful.", msgs, window=90_000)
print(len(kept), "messages kept;", left, "tokens left for documents")

With a 90,000-token window, the newest two messages (about 2,000 and 78,700 estimated tokens) fit and the oldest (about 4,000) is dropped. Notice the weakness: if the oldest message held the original task statement, it is now gone, which is exactly the "forgotten instruction" behaviour described above. Production systems therefore pin important messages, summarise old ones, or retrieve relevant pieces on demand (the idea behind retrieval-augmented generation).

Common pitfalls

  • Treating the advertised window as usable capacity. Test your task at the lengths you actually need.
  • Forgetting to reserve space for the answer. A prompt that fills the window leaves the model no room to reply, or causes the reply to be cut off.
  • Assuming the 0.75 rule holds everywhere. Code, tables, non-English text and unusual names can need far more tokens.
  • Believing memory means learning. Saved memories are inserted text; delete them if they are wrong, or they will keep steering answers.
  • Pasting everything to save effort. Long inputs cost money and time and can dilute the part that matters.
  • Dropping the oldest messages blindly in your own apps; pin the task statement and key constraints.

In practice

  • Start fresh for new topics. A new chat gives the model a clean desk with no leftover clutter from earlier tasks.
  • Restate key instructions in long conversations, or put them in custom instructions so they are included every time.
  • Put the important part where it is easy to find. Place your question and key instructions at the end, after a long document, and say which section matters most.
  • Trim what you paste. Remove boilerplate, unrelated sections and duplicate copies.
  • Ask for a summary, then continue from it. For very long projects, ask the model to summarise decisions so far, then start a new chat with that summary.
  • Check what your app remembers. Look in settings for memory or personalisation features, see what is stored, and delete anything you do not want carried into future chats.

Key takeaways

  • The context window is the most text a model can consider in one request, including instructions, history, documents and its reply.
  • Context is measured in tokens; in English one token is roughly three-quarters of a word.
  • Models do not remember between requests; chat apps simulate memory by re-sending history, summarising it, or inserting saved notes.
  • A large window does not mean equal attention: reliability tends to drop as inputs get longer, especially for material in the middle.
  • Fresh chats, trimmed inputs and restated key instructions usually give better results than ever-longer conversations.

Terms in this lesson

Context window
The maximum amount of text, measured in tokens, that a model can take into account in a single request.
Token
A small chunk of text, often a short word or part of a word, that a model reads and writes.
Saved memory
Short notes a chat app stores about you and adds to the context of new conversations.
KV cache
The model's working record of text it has already read, which grows with context length and uses memory.
Byte-pair encoding (BPE)
A tokenization method that builds a vocabulary by repeatedly merging the most frequent adjacent pairs of symbols, so common words become single tokens and rare words split into pieces.
Effective context length
The longest input at which a model still performs a given task reliably, often shorter than its advertised context window.

Check your understanding

  1. 1.

    A chat app seems to remember your preferences in a brand-new conversation. What is most likely happening?

  2. 2.

    Roughly how many tokens is a 3,000-word English report?

  3. 3.

    You pasted a long contract and the model missed a clause in the middle. Which change is most likely to help?

  4. 4.

    A model has a 128,000-token window. The system prompt uses 4,000 tokens, the chat history 20,000, and you reserve 8,000 for the answer. How many tokens are left for a pasted document?

  5. 5.

    With standard attention, what happens when a prompt grows from 50,000 to 100,000 tokens?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    A model has a 200,000-token window. The system prompt is 3,000 tokens, the conversation history 12,000, and you want to reserve 16,000 for the answer. Roughly how many English words of documents can you add?

    Show solution

    Room for documents: 200,000−3,000−12,000−16,000=169,000200{,}000 - 3{,}000 - 12{,}000 - 16{,}000 = 169{,}000 tokens.

    At about 0.75 words per token: 169,000×0.75≈126,750169{,}000 \times 0.75 \approx 126{,}750 words. Treat this as an estimate; if the documents contain tables, code or other languages, leave a margin.

  2. Exercise 2Core

    A model has 40 layers, 8 key/value heads and a head dimension of 128, and stores its KV cache at 16-bit precision (2 bytes). How much KV-cache memory does a 32,000-token context need? How much with an 8-bit cache?

    Show solution

    Per token: 2×40×8×128×2=163,8402 \times 40 \times 8 \times 128 \times 2 = 163{,}840 bytes (160 KiB).

    For 32,000 tokens: 163,840×32,000=5,242,880,000163{,}840 \times 32{,}000 = 5{,}242{,}880{,}000 bytes, about 5.24 GB.

    At 8 bits (b=1b = 1) every figure halves: about 2.62 GB. Cache quantization is a common way local runtimes fit longer contexts, at some risk to quality.

  3. Exercise 3Core

    Modify fit_history so the first message (the original task statement) is always kept, even when older messages are dropped. Return messages in chronological order.

    Show solution
    def fit_history_pinned(system, messages, window=128_000, reserve_out=8_000):
        if not messages:
            return [], window - reserve_out - est_tokens(system)
        first, rest = messages[0], messages[1:]
        budget = window - reserve_out - est_tokens(system) - est_tokens(first)
        if budget < 0:
            raise ValueError("task statement alone exceeds the budget")
        kept = []
        for msg in reversed(rest):
            cost = est_tokens(msg)
            if cost > budget:
                break
            kept.append(msg)
            budget -= cost
        return [first] + list(reversed(kept)), budget
    

    The pinned message is paid for first, then the newest remaining messages fill what is left. Real apps often replace the dropped middle with a short summary message.

  4. Exercise 4Challenge

    Design a small experiment to measure the effective context length of a model for your own task (for example, finding a clause in contracts). Describe the variables, how you would score it, and sketch Python that builds the test inputs.

    Show solution

    Design. Vary two things: total length (for example 2k, 8k, 32k, 64k, 128k tokens) and the depth at which the key fact sits (0%, 25%, 50%, 75%, 100% of the way through). Use realistic filler (other contracts, not repeated text) and a fact the model cannot guess, such as a specific penalty amount. For each length-depth cell, run 5 to 10 different facts and score exact-match correctness. Effective context length is the largest length at which accuracy stays above your threshold (say 95%) at every depth. Keep temperature low and the question identical across cells.

    import random
    
    def build_case(filler_docs, fact, total_words, depth):
        random.shuffle(filler_docs)
        words = " ".join(filler_docs).split()[:total_words]
        pos = int(depth * len(words))
        words[pos:pos] = fact.split()          # insert the fact at the chosen depth
        return " ".join(words)
    
    # for each total_words in [1500, 6000, 24000, 48000, 96000]
    #   for each depth in [0, .25, .5, .75, 1.0]
    #     prompt = build_case(...) + "\n\nQuestion: What is the late-payment penalty?"
    #     record whether the answer contains the right figure
    

    Plot accuracy by depth for each length. A dip in the middle depths at long lengths is the "lost in the middle" pattern.

Further reading

Go further

Sources

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OS™ · Native AI OS · Built for the future © 2025 - 2026