QA Interview Hub · Knowledge base · Quizzes · Українська

AI › LLM basics: tokens, context, model

LLM, token and context window

An LLM is trained to predict the next token, and a token is a word fragment, a word or punctuation. The context window is the maximum number of tokens the model sees in one request: system prompt, history, documents, tool results and room for the answer. The model has no state, so a dialogue's «memory» is the client resending the history. When a bot «forgot», check the exact request first.

AI for QA · Basics

A chat bot asks for the order number again, although the user gave it at the start. A bug or by design?

In a support chat the user gives an order number in the first message, and on the thirtieth turn the bot asks for it again. The tester files a "bot forgot" bug, and the developer replies that the model remembers nothing. Both are right. To tell a defect from a property of the technology, you need to know what a token is, what the context window is and why the "memory" of a dialogue does not live in the model. This lesson covers the basic concepts that every other AI lesson builds on.

How it works and why. An LLM (large language model) is trained on a large body of text to predict the next token. At each step it produces a probability distribution over tokens, one is chosen, and the process repeats with that token added to the input. The model does not look a fact up in a database and does not run code. That is both its strength (flexible understanding of text) and its weakness: a plausible but wrong answer (a hallucination) is a consequence of the mechanism itself, not of broken code.

A token is the unit the model reads and writes: part of a word, a word or a punctuation mark. Splitting is done by the tokenizer of a particular model, so the same sentence gives a different token count for different models. For English, roughly a few characters make one token, while Ukrainian and code usually split into more tokens, so they cost more and fill the window faster. The model works with tokens, not letters, so it is bad at counting letters in a word or doing exact arithmetic without a tool.

The context window is the maximum number of tokens the model sees in one request. It holds the system prompt, the dialogue history, attached documents, tool definitions and results, and room for the answer itself. Whatever did not fit does not exist for the model. The model also has no state: it keeps nothing between requests, and the "memory" of a dialogue is the client sending the whole history again every time.

What the context window consists of

System promptrules and role, sent every timeDialogue historygrows with every turnDocuments and tool resultsRAG chunks, API responsesRoom for the answerinput + answer ≤ model window
Figure 1. All parts share one token budget. As the history grows, something has to be dropped or compressed.

This answers the order number story. If the client cuts the history, the first turn falls out of the window and the model really does not know the number. That is a defect in the code that builds the context, not in the model. If everything fits and the model still asks, look at the prompt and at long context: in a large volume of text the model uses facts "in the middle" worse than those at the start or the end (the effect is described as lost in the middle), so a window that formally holds everything does not guarantee that the model takes everything into account.

Example: from a lost system prompt to correct trimming. A typical naive implementation limits the history to the last twenty messages:

// cut the history by message count, not by tokens
const sent = history.slice(-20);
// the system prompt was at the start and fell out with the old turns

This code breaks twice. The first time when twenty messages do not fit the window (long pasted logs) and the request fails with a limit error. The second, quieter: the system prompt with the rules falls out together with the old turns, and the bot suddenly changes tone, ignores restrictions and format. There is no error, the behaviour changed. The fix counts tokens, not messages, and always keeps the system prompt:

type Msg = { role: 'system' | 'user' | 'assistant'; content: string };

function fit(history: Msg[], limit: number, count: (m: Msg) => number) {
  const [system, ...rest] = history;
  let used = count(system); // the system prompt always stays
  const kept: Msg[] = [];
  for (const m of rest.reverse()) {  // newest first
    if (used + count(m) > limit) break;
    used += count(m);
    kept.unshift(m);
  }
  return [system, ...kept];
}

limit is the model window minus room for the answer, and count is the vendor's tokenizer (or its token-counting endpoint), not "string length divided by four". For this function the test is deterministic and needs no model:

test('fit keeps system prompt, last turn and the budget', () => {
  const out = fit(longChat, 1000, countTokens);
  expect(out[0].role).toBe('system');
  expect(out.at(-1)).toEqual(longChat.at(-1));
  expect(sum(out.map(countTokens))).toBeLessThanOrEqual(1000);
});

An ordinary function without an LLM and an ordinary unit test. This is a typical example of how a large part of the logic around a model is tested the classic way. Trimming is not the only option: the old part of the dialogue can be compressed into a short summary by another request to the model, but a summary may lose a detail (like the order number), so it is checked too.

Limits and alternatives. A long window is not free: the request is more expensive, slower, and quality on a long input is uneven. So the idea "put the whole knowledge base into the context" loses to RAG, where only the relevant chunks that were found reach the context. A special case: input and output share the window, so a very large input leaves little room for the answer and it gets cut off. A model can get "long-term memory" only at the application level: the system stores facts about the user in its own storage and adds them to the context. That is again code, tested as code.

Common mistakes.

  • Treating the model as a database: checking facts against the model itself with no source. Consequence: a confident invention passes as truth.
  • Counting tokens by characters or words. Consequence: a mismatch with the real limit, especially for Ukrainian and code.
  • Cutting the history from the start and losing the system prompt. Consequence: silently changed behaviour with no error at all.
  • Forgetting room for the answer. Consequence: the answer is cut off mid-sentence.
  • Testing a long dialogue only with short examples. Consequence: trimming defects and "lost in the middle" stay invisible until a user finds them.

Check yourself

At the start of a dialogue the user gave a travel date, and at turn 40 the bot offers tickets for another date. What two different causes can this defect have and how do you tell them apart?

Answer

The first: the code that builds the request dropped the first turn, so the date is not in the context. It is visible if you capture the exact request sent to the model and do not find the date there. The second: the date is in the request, but the model did not take it into account (long context, a vague prompt). It is visible when the date is present in the request and the answer is wrong. The first is fixed in the context-building code, the second with the prompt, the context structure or a summary.

Why does a call that works fine with 10 turns suddenly fail after a big log is pasted, although the log "fits" the window on its own?

Answer

All parts of the request share the window: system prompt, history, the log and room for the answer. The log may fit alone, but the sum with the rest exceeded the limit. So the limit is checked for the total and room for the answer is kept.

Can you write a deterministic test for the history trimming logic? What needs to be mocked?

Answer

Yes: the trimming function does not call the model, so it is a normal unit test. Nothing needs to be mocked, just pass a long history and a token counter (real or a fixed stub). The invariants are checked: the system prompt is in place, the last turn is kept, the token sum is within the limit.

In an interview. Junior: An LLM predicts the next token, a token is a piece of a word, and the context window is how many tokens the model sees in one request. The model itself has no state: the client sends the dialogue history every time. Middle/Senior: The window is shared by the system prompt, history, documents, tool results and the answer, so I count trimming in tokens and never lose the system prompt. On a long input the position of the information affects real quality, not just whether it fit. For "the bot forgot" bugs I first look at the exact request that went to the model: that separates a context-building error from an error of the model itself.

More articles in this chapter