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.

Model, version and generation parameters

A model is a set of trained weights with a name and a version, so its identifier is pinned in configuration. An alias without a version can change behaviour without a commit. Temperature sets how random token choice is, max_tokens limits answer length. Even zero temperature does not guarantee identical text, so a test checks properties (schema, fields), not byte-for-byte equality.

AI for QA · Basics

The same test with temperature 0 passed yesterday and fails today. Nobody touched the code. What changed?

A test checks that the bot answers a cancellation request with "Order cancelled.". Green yesterday, red today, the answer is "Your order has been cancelled". There was no commit between the runs, and temperature is zero. This story has three possible causes: the model version changed, non-determinism even at zero, or a check that is too strict. The lesson explains what a model is as an artefact, what the generation parameters do and why a test must not assume byte-for-byte equal output.

How it works and why. A model is a specific set of trained weights with a name and a version. A larger model usually copes better with hard tasks but is slower and more expensive, a small one is fast and cheap for simple ones (classification, field extraction). So choosing a model is a trade-off between quality, speed and cost, and it is made by measurements on an eval set, not by the name. For QA the main point is different: the model version is part of the configuration. If the code uses an alias without a version, the vendor can move it to a new model and the product changes with no commit. So production and tests pin a specific identifier.

Where the generation parameters act

Model: token probabilitiesa score for every possible tokentemperatureflattens or sharpens the distributiontop_pkeeps the most probable headToken choicerandom among those that remainstop / max_tokensstopping, finish_reason
Figure 1. The model only scores tokens. The parameters decide how the next token is chosen from those scores and when generation stops.

The main parameters (names depend on the vendor, check the documentation):

  • temperature: how random the choice is. Near zero the most probable token is almost always taken, higher gives more varied answers;
  • top_p (nucleus sampling): choose only from the smallest group of tokens whose total probability reaches p. The usual advice is to change one of the two parameters, not both;
  • max_tokens (now max_completion_tokens in OpenAI): the limit on answer length. When it is reached the answer is cut mid-sentence, and the stop reason (finish_reason: length in OpenAI, stop_reason: max_tokens in Anthropic) says it was the limit, not a completion;
  • stop: strings on which generation stops;
  • seed: not every vendor has it, and it only raises reproducibility but does not guarantee it.

Why zero does not give determinism. Even with temperature: 0 two requests can produce different text. The causes: parallel floating-point computation (the order of operations affects the last digits, and a gap between two nearly equal tokens flips the choice), request batching on the server and silent updates behind an alias. Some models do not accept an arbitrary temperature at all and reject a non-default value, and some vendors have removed sampling parameters (temperature, top_p) from newer API versions entirely: a request that sets them gets a 400. The conclusion for a test: do not rely on byte-for-byte equal output.

Example: from a brittle check to a stable one. The initial test:

const res = await llm.generate({ model: 'big-latest', temperature: 0, messages });
expect(res.text).toBe('Order cancelled.');

It is brittle for three reasons: the alias big-latest can change, exact text in a free-form answer is guaranteed by nothing, and when it fails you cannot see what happened (a different phrase or a truncated answer). The fix removes all three:

An alias or a pinned version

Alias

A name without a version

The vendor can move an alias to a new version. Product behaviour changes with no commit, and the difference between runs cannot be explained.

Pinned

A specific identifier

The identifier lives in config. A model upgrade becomes a separate change with an eval run and a decision, not a surprise.

Figure 2. Two ways to name a model. The second makes an update a visible, controlled change.
const res = await llm.generate({
  model: config.modelId, // a pinned identifier from config
  temperature: 0,
  max_tokens: 300,
  messages,
});
// the answer was not cut off by the length limit
expect(res.finishReason).not.toBe('length');
// check properties, not the exact text
const data = orderSchema.parse(JSON.parse(res.text));
expect(data.status).toBe('cancelled');

Here the identifier comes from config, so a model update is visible in the diff. The answer is requested as JSON by a schema and the fields are checked, not the phrase. The stop reason is checked separately: length means the answer is truncated and the JSON most likely will not parse. For free text with no structure, semantic checks and judge scoring remain: see the lessons “Why an LLM is not tested like regular code” and “Eval set, metrics and LLM-as-judge”.

Limits and alternatives. Pinning an identifier is not forever: vendors retire old versions on a schedule, so the plan includes a model upgrade as a separate event with an eval run. Model size is chosen by measuring: if a small model gives the required success rate on your set, the more expensive one is not needed. For continuous quality it helps to store the model identifier, prompt version and parameters in the run results, otherwise two runs cannot be compared.

Common mistakes.

  • An alias without a version in production or CI. Consequence: behaviour drifts with no commit, and a regression cannot be explained.
  • Expecting identical text from temperature: 0. Consequence: unstable tests that get "treated" with reruns.
  • Not checking finish_reason. Consequence: truncated JSON is read as a model error, not as a too small max_tokens.
  • Setting max_tokens by eye. Consequence: either cut-offs or paying for headroom that is not needed.
  • Relying on seed as a guarantee. Consequence: the run passes locally and fails in another environment.

Check yourself

A test with temperature 0 and an exact text comparison fails once in twenty runs. The model, prompt and data did not change. Why and what to do?

Answer

Zero does not make output deterministic: different request batching on the server and floating-point operations can flip the choice between two close tokens. Rewrite the check on properties (JSON fields, the required status, absence of forbidden words), and where that is not possible, add a tolerance and measure the success rate over several runs.

A bot answer is always cut off at the same place. Which response field do you look at and how is it fixed?

Answer

finish_reason (or stop_reason). The value length (max_tokens in stop_reason) means max_tokens was reached: raise the limit or ask for a shorter answer. If it says stop, the answer is complete and the cause is in the prompt.

Production suddenly changed the tone of answers although no commit touched the prompts. What do you check first?

Answer

Whether the model behind the alias changed. Look at the model identifier in request logs and in config. If it has no version, pin a specific one and run the eval set on the old and new versions to see the real difference.

In an interview. Junior: Temperature sets how random the token choice is, max_tokens limits the answer length, and the model version is pinned because it changes behaviour. Middle/Senior: The model identifier is part of the configuration, so an upgrade goes through as a change with an eval run. Zero temperature does not guarantee identical text, so tests check properties: schema, fields, finish_reason. I record run results together with the model, prompt version and parameters, otherwise two runs cannot be compared.

Credits, price and limits

Model APIs bill by tokens, input and output separately. Because the model is stateless, every call carries the whole history, so cost grows faster than one request's price suggests. An agent needs limits on steps and cost. A rate limit (429) is retried with a pause, while an exhausted quota is not retried and a clear message is shown. Prompt caching works when the start of the request is identical.

AI for QA · Basics

Ten requests a day cost pennies, yet a night run with an agent burned the monthly balance. Where did the money go?

A nightly agent eval run failed in the third hour: the credits ran out. A single request is cheap, so it seemed the budget would last weeks. Three things explain the gap: token-based billing, the history being resent on every step and an agent with no step limit. The lesson covers what a request price consists of, which limits exist and what QA tests among them.

How it works and why. Model APIs bill by tokens, separately for input (everything you sent) and output (what the model generated). Vendors usually quote a price per million tokens, and output tokens typically cost more. The cost of a call is input × input price + output × output price. Actual rates change, so they are taken from the vendor page and kept in code as configuration.

The key feature: the model has no state, so every call in a dialogue or an agent loop carries the whole history. An illustration with made-up numbers: a system prompt of 1,000 tokens, each turn adds 500 tokens to the history (the question and the answer).

The input of one call grows with the turn

turn 11 000turn 21 500turn 32 000turn 105 500
Figure 1. Made-up numbers: at turn 10 a single call carries 5,500 input tokens, although only 500 of them are new text.
What is countedTokens
Unique text over 10 turns6,000
Input actually billed over 10 turns32,500

So over ten turns you pay for about five and a half times more input than there is unique text, and the gap grows with the dialogue length. An agent that calls tools dozens of times in a loop multiplies the effect. So an agent needs a budget and a step limit (see the lessons “Tool calling, agent and MCP” and “Testing an agent: tools, trajectory, outcome”).

Credits. This is an abstract unit of payment: a prepaid balance or subscription "points" into which the service converts tokens, requests or agent minutes. When credits run out, the service rejects the request or turns the feature off. For QA this is a separate class of scenarios: what the user sees at a zero balance, whether credits are charged for a failed request, whether the counter matches actual spending, whether the limit can be bypassed with parallel requests.

What else affects cost and speed:

  • Prompt caching. A repeating start of the request (system prompt, long documents) can be cached, and re-reading it is cheaper and faster. The cache works only when the start of the request is identical, so variable parts (time, user name) go to the end;
  • Rate limits. Limits on requests and tokens per minute. A 429 response usually means "try again later", and the Retry-After header says when;
  • Latency. Time to first token (TTFT) and total time are measured separately. Streaming shows the answer as it is generated, so the user does not wait for all of it;
  • Model choice. A smaller model for simple steps lowers cost, but quality is checked on an eval set.

Example: telling a rate limit from an empty balance. Both situations often arrive with code 429, but the reaction is opposite. A temporary rate limit is retried with exponential backoff, while a missing quota is pointless to retry, and a retry loop would only burn time and load the service:

async function withRetry<T>(call: () => Promise<T>, tries = 4): Promise<T> {
  for (let i = 0; ; i++) {
    try {
      return await call();
    } catch (e) {
      const err = e as ApiError;
      // quota exhausted: a retry is pointless, the balance will not return
      if (err.code === 'insufficient_quota') throw err;
      const retriable = err.status === 429 || err.status >= 500;
      if (!retriable || i >= tries) throw err;
      // Retry-After if present, else exponential backoff with jitter
      const ms = err.retryAfterSec ? err.retryAfterSec * 1000 : 2 ** i * 500 + Math.random() * 250;
      await new Promise((r) => setTimeout(r, ms));
    }
  }
}

The quota error code and the response fields depend on the vendor, so a test substitutes a stub that imitates both cases. The test checks that on a rate limit the client retries with a pause (preferably with a controlled clock, with no real waiting), and on a quota it stops at once and the user sees a clear message, not an endless spinner.

Limits and alternatives. Caching and a smaller model lower the cost but do not remove the main cause of growth: the stretching history. What helps here is trimming or summarising the history, RAG instead of "everything into the context" and hard step and token limits in the agent. For eval runs in CI a cost limit is set as a separate check, and the full run goes at night, not on every commit.

Common mistakes.

  • Counting the budget by the price of one request. Consequence: a dialogue or an agent costs several times more than the estimate.
  • Retrying 429 without understanding the cause. Consequence: endless retries with an exhausted quota.
  • Retrying without a pause and jitter. Consequence: all clients hit the limit at once and amplify the overload.
  • No step and cost limit in an agent. Consequence: a looping agent burns the budget overnight.
  • Putting variable data at the start of the request. Consequence: the cache misses and the full price is paid.

Check yourself

A 10-turn dialogue: a 1,000-token system prompt, each turn adds 500. How many input tokens does the dialogue pay for in total and why not 6,000?

Answer

The input of call n is 1,000 + 500 × (n − 1), because the history is sent every time. The sum over ten turns: 10 × 1,000 + 500 × (0 + 1 + … + 9) = 10,000 + 22,500 = 32,500 tokens. Unique text is only 6,000, the rest is the history being resent.

A user with a zero balance sees an endless loading state. What is probably wrong in the client and what do you check?

Answer

The client most likely retries the quota error as a temporary one. Check that no retries happen on an out-of-credits error and that the interface shows a balance message. Also check whether credits were charged for the failed request.

Why is putting the time or the user name at the start of the system prompt a poor choice for cost?

Answer

Prompt caching works when the start of the request is identical. A variable string at the start makes the prefix unique every time, the cache misses and the whole long prefix is paid for in full. Variable parts go to the end.

In an interview. Junior: The API bills by tokens, input and output separately, and request limits return 429, so the client retries with a pause. Middle/Senior: Cost grows faster than linearly because the history is resent every time, and in an agent it also multiplies by steps, so I want a budget, step and token limits and prompt caching with a stable prefix. I test a zero balance separately: it is not the same as a rate limit and must not be retried. Cost and tokens per case are part of the eval run metrics.