AI Engineering interview questions: LLM tokens & context windows
Reviewed by Mark Dickie · Last updated
LLM tokens are the atomic units that large language models use to represent text: every input string is split into subword pieces, each mapped to an integer ID, and those IDs are what the model actually processes. Context window size is the maximum number of tokens a model can attend to in a single forward pass, covering both the prompt you send and the response it generates. For an AI engineering interview, you should know how tokenizers like BPE and SentencePiece chunk text, why different models produce different token counts for the same input, and what happens when a conversation exceeds the context limit. You should also be comfortable with cost calculations, since API providers charge per token and context length directly affects both latency and price.
What does an AI engineering interview test about tokens and context?
Interviewers focus on practical reasoning: can you estimate token counts, pick the right context window for a task, and handle the failure modes that arise at the boundaries. The table below maps the core areas to what you are likely to be asked.
| Topic | What the question targets |
|---|---|
| Tokenization | How BPE and SentencePiece split text; why whitespace and Unicode matter |
| Context window limits | What breaks when you exceed the max context length (truncation, errors, silent drops) |
| Token budgeting | Splitting a fixed window across system prompt, conversation history, and completion |
| Cost and latency | How input/output token pricing works and why longer prompts slow inference |
| Chunking strategies | How to split long documents for retrieval without losing semantic meaning |
How should you approach a token or context-window interview question?
- Identify the constraint: the model's context length and how the prompt is structured.
- Count or estimate tokens for each section, including system instructions, tool definitions, and any retrieved context.
- Decide what to keep and what to compress: truncate oldest turns, summarize history, or reduce the number of retrieved chunks.
- Verify the output token budget remains positive after subtracting the input from the context window.
- State the tradeoff: a larger context window costs more and adds latency, so only use it when the task genuinely needs it.
What pitfalls come up with tokens and context windows in production?
The most common production failure is silent truncation. When a prompt exceeds the context limit, some APIs drop the oldest messages without warning, which means the model loses instructions or earlier conversation turns and starts producing answers that ignore context. A second pitfall is tokenizer mismatch: if you count tokens with one tokenizer (say, a generic word splitter) but the API uses another, your budget estimates can be off by 20% or more. Always count with the tokenizer that matches the model you are calling, and build in a safety margin below the advertised context length so room remains for the completion.
Key facts
- Tarmac has 26 AI Engineering interview questions on this topic, 10 of them on this page, at difficulty 1–5 of 5.
- Tarmac tracked 4,175 job postings asking for AI Engineering in August 2026.
- Roles asking for AI Engineering advertise a median base salary of US$182,450, across 806 job postings as of August 2026.
- Tarmac last reviewed these AI Engineering interview questions on 14 September 2026.
At a glance
| Questions | 10 shown · 26 in the bank |
|---|---|
| Difficulty | 1–5 of 5 |
| Formats | Ordering, True / false, Code output, Fill in the blank, Multiple choice, Multiple answer, Find the bug, Short answer, Flashcard |
What you'll review
- tokens context
- agent loops
- agent memory
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
AI Engineering/llm-foundations/tokens-context
When a piece of raw text is fed into a standard decoder-only LLM (e.g., GPT-style), the text goes through several stages before being processed by the transformer. Arrange the following stages in the order they actually occur, from first to last.#
Put these in order
Show answer
The correct order is: (1) tokenize raw text into tokens, (2) map each token to a token ID via the vocabulary, (3) look up an embedding vector for each token ID, (4) add positional encodings to the embeddings, (5) pass the vectors through the transformer layers. This is the fixed pipeline every standard decoder-only LLM follows — IDs are needed before embeddings, and embeddings must exist before positional information can be added.
In a standard decoder-only LLM pipeline, raw text is first tokenized into subword pieces, then each token is converted to a numerical token ID via the vocabulary lookup, then each ID is mapped to a dense embedding vector, then positional encodings are added so the model can use order information, and finally the resulting vectors are fed into the transformer layers. This order is fixed: you cannot look up embeddings without IDs, and you cannot add positional encodings before embeddings exist.
AI Engineering/llm-foundations/tokens-context
A model's context window is shared between the input (prompt) tokens and the generated output tokens — they draw from the same budget.#
Options
Show answer
True. The context window bounds the total tokens the model attends to — system prompt, retrieved context, conversation history, and the tokens it generates all draw from the same budget. If you stuff the input close to the limit, you starve the output and risk truncated completions. Budget explicitly: reserve headroom for max_tokens of output, since long outputs cost both latency and window space.
The context window bounds the total tokens the model attends to: system prompt + retrieved context + conversation history + the tokens it generates. If you stuff the input close to the limit, you starve the output and risk truncated completions. Budget explicitly — reserve headroom for max_tokens of output, and remember that long outputs cost both latency and window space.
AI Engineering/llm-foundations/tokens-context
A common back-of-the-envelope rule for English text is roughly 4 characters per token. This estimates the token count of a string using that heuristic. What does it print?#
import math
text = "The quick brown fox jumps over the lazy dog today"
estimate = math.ceil(len(text) / 4)
print(estimate)Show answer
13
The string is 49 characters; ceil(49 / 4) = ceil(12.25) = 13. The ~4 chars/token rule is a quick estimate for budgeting context windows and cost, not an exact count — real tokenizers (BPE) split on sub-word units, so whitespace, punctuation, code, and non-English text all change the ratio. For anything that must be exact (e.g. enforcing a hard context limit) you should call the model's real tokenizer rather than rely on this heuristic.
AI Engineering/llm-foundations/tokens-context
The maximum number of tokens a model can attend to at once — covering both the input and the generated output — is called the _____ window.#
Show answer
The maximum number of tokens a model can attend to at once — covering both the input and the generated output — is called the context window.
The context window is the hard token budget for a single request, shared between the prompt (system + history + retrieved context + user message) and the completion. Overflowing it forces truncation or summarization of history, and because attention cost grows with sequence length, packing the window with marginal context also raises latency and price — so context is a resource to budget, not just fill.
AI Engineering/agents/agent-loops
Your agent appends every tool result to one growing message list and re-sends the whole list on each iteration. Short runs work. A task that needs about 40 iterations fails partway through with the provider rejecting the request. What is the most likely cause?#
Options
Show answer
The accumulated messages grew past the model's context window, so the request was rejected before the model ran. An append-only transcript grows on every iteration and the whole thing is re-sent each time, so a long run eventually exceeds the limit — which is why the failure is iteration-dependent rather than input-dependent. System prompts do not expire, old tool results are not garbage-collected for you, and there is no per-conversation tool-call ceiling beyond the one you impose.
An append-only transcript grows monotonically, and every iteration re-sends all of it, so a long run walks straight into the context-window limit — the request is rejected on validation, before any generation happens. That is why the failure looks sudden and iteration-dependent rather than input-dependent: nothing about iteration 26 is special except the cumulative size. The fixes are all about what you carry forward — summarise or compact older turns, clear old tool results, or keep detail out of the loop and retrieve it on demand. The distractors are the three things engineers commonly assume the provider is doing for them: system prompts do not expire (b), old tool results stay valid and are not garbage-collected for you (c), and there is no per-conversation tool-call ceiling — your own max_steps is the only one (d). Believing any of them leads to the same production bug: an agent that works in testing and dies on the long tasks that matter.
AI Engineering/llm-foundations/tokens-context
Transformer-based LLMs convert raw text into tokens and process them within a fixed context window. Which of the following statements about tokens and context windows are correct?#
Options
Pick every one that applies.
Show answer
The correct statements are: tokenization is a preprocessing step that splits text into subword units mapped to vocabulary IDs; the context window bounds the maximum number of input tokens per request; and each vocabulary token maps to one fixed-dimensional embedding vector. The incorrect ones claim self-attention scales linearly (it is O(n²)) and that tokens equal whitespace-delimited words (they are subword units).
Statements (a), (b), and (d) are correct. Tokenization (e.g., BPE, WordPiece) runs as a preprocessing step that splits text into subword units and maps each to a vocabulary ID (a). The context window is the upper bound on how many input tokens the model can accept in one request (b). The input embedding layer is a lookup table where each vocabulary ID corresponds to exactly one fixed-size vector (d). Statement (c) is wrong because standard transformer self-attention has O(n²) complexity in sequence length, not linear—doubling the context more than doubles attention cost. Statement (e) is wrong because tokens are subword units, not whole words; a single word may span multiple tokens and a single token may encode partial words, punctuation, or whitespace.
AI Engineering/llm-foundations/tokens-context
A junior engineer wrote this helper to truncate a chat conversation so that the total token count of all retained messages stays within max_tokens. The system prompt (messages[0]) must always be kept; beyond that, the most recent messages should be retained and the oldest non-system messages dropped first. The code is correct when the system prompt alone already exceeds max_tokens, but it silently returns an over-budget result in the common case where the system prompt fits yet the remaining conversation does not. Each line below is numbered with a trailing comment # Ln so you can identify the buggy line by its number.#
def truncate_to_context(messages, max_tokens, count_tokens): # L1
""" # L2
Keep the system prompt (messages[0]) and as many of the # L3
most recent messages as fit within max_tokens tokens. # L4
Drop the oldest non-system messages first. # L5
count_tokens(text) returns the token count for a string. # L6
""" # L7
total = sum(count_tokens(m['content']) for m in messages) # L8
if total <= max_tokens: # L9
return messages # L10
# L11
system = messages[0] # L12
budget = max_tokens - count_tokens(system['content']) # L13
remaining = list(messages[1:]) # L14
# L15
# Remove oldest messages until the remaining fit the budget # L16
while remaining and budget <= 0: # L17
remaining.pop(0) # L18
# L19
return [system] + remaining # L20Show answer
The bug is on line 17.
Line 17 (while remaining and budget <= 0:) is the sole bug. The variable budget (line 13) is max_tokens - count_tokens(system['content']) — the token capacity available for non-system messages. The condition budget <= 0 is true only when the system prompt alone already exceeds max_tokens, so the loop body runs only in that edge case. In the common scenario the system prompt fits (budget > 0) but the remaining conversation still overflows the budget; the loop never executes, so the function returns the full conversation without dropping anything, violating the token limit. The condition should instead check whether the total token count of all remaining messages exceeds the available budget: while remaining and sum(count_tokens(m['content']) for m in remaining) > budget:. Line 18 (remaining.pop(0)) is correct: it removes the oldest non-system message (the first element of remaining), which is exactly the required behavior, and needs no change.
AI Engineering/agents/agent-memory
An autonomous agent has been working a task for 200+ turns and its conversation is approaching the model's context-window limit. Which approach best lets it keep going without losing the thread of the task?#
Options
Show answer
Compact older turns into a running summary (and move details to an external store the agent can retrieve on demand), keeping the most recent turns verbatim. Managing what occupies the window is what keeps long sessions alive. Dropping the system prompt and tool definitions deletes the agent's instructions and capabilities; overflow is not gracefully ignored — it either errors or silently truncates the oldest tokens, often the goal; and temperature does nothing about capacity.
Long sessions are kept alive by managing what occupies the window: summarize/compact older turns into a compact running state while keeping the latest turns verbatim, and offload detail to an external memory the agent can retrieve when relevant (a). Dropping the system prompt and tool definitions (c) deletes the agent's instructions and capabilities — it will lose its task and its tools. Overflow is not gracefully ignored (d): exceeding the window either errors outright (most provider APIs reject the request) or, in some client/framework helpers, silently truncates the oldest tokens (often the goal/system prompt) — which is the failure you're trying to avoid. Temperature (b) does nothing about capacity.
AI Engineering/agents/agent-memory
An agent runs for hundreds of turns and its transcript no longer fits in the model's window. How do you keep it working without losing the information it needs? Name the main techniques.#
Show answer
Stop sending the full raw transcript and instead manage what occupies the window. The common techniques: summarize/compact older turns into a running summary while keeping the most recent turns verbatim; offload the full history to an external store (a vector database or scratchpad) and retrieve only the passages relevant to the current step; prune or evict low-value turns (tool spew, stale intermediate results); and keep the durable facts (the goal, key decisions) pinned in a compact memory block. The point is to compress and select, not to assume a bigger window will save you.
Long-running agents survive by managing the window rather than enlarging it. Two complementary moves dominate: (1) compaction — replace older turns with a running summary, keeping recent turns verbatim; (2) externalize + retrieve — persist the full history to an outside store and pull back only what's relevant to the current step (RAG over your own transcript). Supporting tactics: prune/evict low-signal turns, and pin durable facts (goal, decisions, constraints) in a small always-present block. Simply 'use a model with a bigger context window' defers the problem and raises cost/latency; the win is compressing and selecting what the model actually needs to see.
AI Engineering/llm-foundations/tokens-context
Why can ALiBi-based Transformer models extrapolate to sequence lengths well beyond their training context window, while models using learned absolute positional embeddings cannot?#
Show answer
ALiBi (Attention with Linear Biases) never encodes an absolute position index. Instead it adds a fixed, unlearned negative penalty to attention scores that scales linearly with the relative distance between query and key positions. At inference time, longer sequences simply apply the same relative-distance penalties the model already saw during training, so no new representation is needed. Learned absolute positional embeddings, by contrast, assign a dedicated trainable vector to each integer position 0…N−1. At any position ≥ N (the training context length) there is no learned embedding vector, so the model has no representation for that position and degrades immediately. This is why absolute-embedding models hit a hard ceiling while ALiBi extrapolates gracefully.
This tests a staff-level understanding of how positional encoding strategy determines context-length behavior. ALiBi's relative-distance bias is position-agnostic by construction, enabling extrapolation; absolute embeddings are table-lookups with a fixed vocabulary of positions, creating a hard upper bound. RoPE sits between these two extremes — it is relative but periodic, which is why it requires position interpolation or NTK-aware scaling to extend beyond the pre-training length.
Related interview questions
Job market
See ai-engineering salaries and hiring demand from live job postings.
The other 16 questions
This page shows 10 and marks what you pick. That's as far as a page can go. A free account opens the other 16 and keeps every answer. What you miss comes back until it's right: after a day, then at longer gaps.
Free · the whole bank · 100 marked answers per 30 days · written feedback on the paid plan