AI agent interview questions and answers
Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.
Budgets, clearing old tool results, compaction and a cacheable prefix.
What can a harness remove from history without breaking a tool exchange?
A model request has a limited context window. Keep unresolved call-and-result pairs intact, then summarize completed material while retaining the facts and references later turns need.
Transcript fills with old messages and tool output
Compactor picks a completed boundary and preserves needed facts
Newest request fits and still has coherent tool pairs
Transcript fills with old messages and tool output
Compactor picks a completed boundary and preserves needed facts
Newest request fits and still has coherent tool pairs
Given Transcript fills with old messages and tool output and Newest request fits and still has coherent tool pairs, write down the missing step that connects them.
Compactor picks a completed boundary and preserves needed facts
Now take Compactor picks a completed boundary and preserves needed facts and the result above. Write an input and an implementation that could produce this trace.
Transcript fills with old messages and tool output. Check that your implementation produces the result shown above.
The oldest item is a tool call whose result remains in the next message. Can you remove just the call?
Keep the pair together, or summarize the completed exchange as a unit when it is safe to do so. Retaining an orphaned result leaves the transcript structurally incomplete.
Check this when debugging. Thinking a bigger context window removes the need to manage context.
Every model call sends the whole conversation. A coding agent that reads twenty files and runs the tests ten times can fill even a large context window within an hour. Then calls get slow and costly, quality drops as old material crowds out what matters, and finally the request is too big to send. Long-running agents depend on managing context well. This is one of the main things that separates a toy harness from a professional one.
Clear out old tool results it no longer needs
Old file contents and test logs take up most of a long session. Trimming them, and compacting the history, keeps the context for what still matters. This lesson budgets the context like a desk of fixed size.
Recall: Hosts: connecting servers to a model kept a host inside its context limits, and Tokens and the context window showed what a window holds. An agent fills its window on its own, one tool result at a time.
Picture a desk of a fixed size. Your tools, your instructions, the papers for the job and the space to write your reply all have to fit on it. A request works the same way. Each one holds: tool definitions, the system prompt, the messages, and room for the reply (max_tokens). They all share one window. The response's usage tells you the real input size, so log it every turn:
used = (u["input_tokens"] + u["cache_read_input_tokens"] + u["cache_creation_input_tokens"])
usage is below. What does this print?u = {"input_tokens": 1200, "cache_read_input_tokens": 48000,
"cache_creation_input_tokens": 3000, "output_tokens": 900}
used = (u["input_tokens"] + u["cache_read_input_tokens"]
+ u["cache_creation_input_tokens"])
print(used)52200
With caching, input_tokens counts only the uncached part. The real input is all three: 1,200 + 48,000 + 3,000 = 52,200 tokens.
Bigger isn't free even when it fits. On a buried desk, the note you need is still there, and you won't find it. Models attend less sharply to details buried in a huge context, sometimes called context rot. So the goal isn't only to fit, but to keep the context full of what matters now.
offset and limit (the tool registry and file tools).tool_use and tool_result blocks, so the pairing stays valid.The Claude API can do 2 and 3 on the server. Context editing (beta) has a clear_tool_uses_20250919 strategy that clears old tool results past a threshold. Compaction (beta compact-2026-01-12) summarizes automatically when the context gets long; your loop appends the whole response.content each turn, compaction block included, and the API handles the rest.
Step through 15 calls. The sawtooth is the whole job of context management.
Write a sentence or two, then compare it with a good answer in the lesson.
Replacing an old tool result frees its tokens while the conversation stays valid, because each tool_use still has its tool_result. The function builds new blocks and leaves the old list as it was.
def call(i): block = {"type": "tool_use", "id": i, "name": "read"} return {"role": "assistant", "content": [block]} def result(i, text): block = {"type": "tool_result", "tool_use_id": i, "content": text} return {"role": "user", "content": [block]} messages = [call("a"), result("a", "x" * 9000), call("b"), result("b", "y" * 4000)] def clear_old(messages, keep_last=1): spots = [(i, j) for i, m in enumerate(messages) for j, b in enumerate(m["content"]) if b["type"] == "tool_result"] old = set(spots[:-keep_last]) note = "[cleared: read again if you need it]" return [{**m, "content": [{**b, "content": note} if (i, j) in old else b for j, b in enumerate(m["content"])]} for i, m in enumerate(messages)] def size(messages): return sum(len(b.get("content", "")) for m in messages for b in m["content"]) cleared = clear_old(messages) print("before:", size(messages), "after:", size(cleared)) print(cleared[1]["content"][0])
The placeholder tells the model that the file is still there and how to get it back. The newest result stays whole, since that's probably what it's working on now. The original list is untouched, so the harness can still log or compare it.
On a model that thinks, such as claude-opus-5-5, replies carry thinking blocks, and each one has a signature tied to everything before it: the tools, the system prompt and every earlier message. Change an earlier turn, by clearing a result or summarizing old turns, and every thinking block after the change no longer matches. Send those blocks back and the API can reject the request with a 400 ("bound to a different conversation"). On claude-opus-5-5 it may let the request through instead, and the model then reasons from notes about text that has changed. Neither is what you want, so build as if the 400 always comes.
So in production, let the server do 2 and 3: its clearing and compaction don't count as edits, because the API checks the conversation as you sent it. When you clear or compact in your own code, as in this lesson, also drop the thinking blocks (thinking and redacted_thinking) from every assistant message after the first one you changed. Keep their text and tool calls. Dropping a run of thinking blocks from the end is allowed; editing in the middle is what breaks them.
roles = ["user", "assistant", "user", "assistant", "user", "assistant"] changed = 2 drop = [i for i, r in enumerate(roles) if r == "assistant" and i > changed] print(drop)
[3, 5]
The thinking in message 1 was written before the change, so it still matches. Messages 3 and 5 came after it, so their thinking blocks no longer match the conversation and must go. Their text and tool calls stay.
Every tool_use must still have a matching tool_result, or the request is invalid
The API checks the pairing. Keep the structure; shrink the content.
The same sawtooth, computed: the harness clears the old results when the total passes 150,000, and keeps the last two.
import matplotlib.pyplot as plt FIXED, RESULT, NOTE = 15_000, 12_000, 50 LIMIT, CLEAR_ABOVE, KEEP = 200_000, 150_000, 2 results, sent = [], [] for call in range(15): if FIXED + sum(results) > CLEAR_ABOVE: results = [NOTE] * (len(results) - KEEP) + results[-KEEP:] sent.append(FIXED + sum(results)) results.append(RESULT) print(sent) plt.plot(sent, marker="o", label="tokens sent") plt.axhline(CLEAR_ABOVE, color="gray", linestyle="--", label="clear above") plt.axhline(LIMIT, color="red", linestyle=":", label="window") plt.xlabel("model call") plt.ylabel("input tokens") plt.title("Context size per call, with clearing") plt.legend() plt.show()
You can't cut anywhere. If you tear pages out of an interview transcript, you mustn't leave an answer without its question. If the recent part starts with a user message of tool_result blocks, their tool_use blocks are in the part you summarized away, and the request is invalid. A safe cut is right before an assistant message: put the summary in a new first user message, then the recent turns from that assistant message on. Roles still alternate, and every result in the recent part has its tool call there too.
The summary prompt matters. Treat it as a handover note at the end of a shift. Ask for the original task, key decisions and their reasons, files touched, errors met and fixed, and the next steps. A summary that loses the task leaves an agent that's lost.
A cut must fall right before an assistant message, or some tool_result loses its tool_use. Here's a function that finds the latest safe cut that keeps enough recent turns.
roles = ["user", "assistant", "user", "assistant", "user", "assistant", "user"] kinds = ["text", "tool_use", "tool_result", "tool_use", "tool_result", "text", "text"] def safe_cut(roles, keep_recent): for i in range(len(roles) - keep_recent, 0, -1): if roles[i] == "assistant": return i return None cut = safe_cut(roles, keep_recent=3) print("cut before message", cut, f"({roles[cut]}, {kinds[cut]})") print("summarized:", kinds[:cut]) print("kept word for word:", kinds[cut:]) cut = safe_cut(roles, keep_recent=2) print("asking to keep 2 keeps:", kinds[cut:])
The search walks backward to an assistant turn, so it may keep a little more than you asked for. That's fine: keeping one extra turn costs little, and an invalid request costs the whole call.
messages = ["task", "a1", "r1", "a2", "r2", "a3", "r3"] roles = ["user", "assistant", "user", "assistant", "user", "assistant", "user"] cut = len(messages) - 3 while cut > 0 and roles[cut] != "assistant": cut -= 1 print(cut, messages[cut:])
3 ['a2', 'r2', 'a3', 'r3']
Index 4 holds tool results, so the cut moves back to the assistant message at 3. Every kept result still has its tool call.
Write budget_report(parts, limit): parts maps names (system, tools, history...) to token counts. Return lines NAME: N tokens (P%), largest first, with P the share of the total rounded to a whole number, then a last line Total: T of LIMIT followed by (over by X) if T is above the limit.
def budget_report(parts, limit): return [f"{k}: {v}" for k, v in parts.items()] PARTS = {"system": 3_000, "tools": 12_000, "history": 170_000, "reserve": 16_000} for line in budget_report(PARTS, 200_000): print(line)
A movie recap never has every scene, and a summary always drops detail. So write important decisions and plans to files, which survive compaction word for word, and read them back whenever you need them again later on in a session.
Write a sentence or two, then compare it with a good answer in the lesson.
If you've already checked the first 50 pages of a contract, you can skip them next time, as long as not one word has changed. Prompt caching does the same thing. It makes a repeated prefix, the unchanged start of a request, cheaper and faster. The order is tools, then system, then messages, so:
claude-opus-5-5 among them, accept system role messages later in the conversation for this. Not every model does, so check before you rely on it.Clearing and compaction do change the prefix, so the next call pays to rebuild the cache, and when your own code does them, the thinking blocks after the change go too. That's why you clear in large batches when crossing a threshold, not a little every turn.
In plain words: keep the start of every request exactly the same, and put whatever changes at the end.
def shared_prefix(a, b): count = 0 for x, y in zip(a, b): if x != y: break count += 1 return count call_1 = ["tools", "system", "msg 1", "msg 2"] call_2 = ["tools", "system", "msg 1", "msg 2", "msg 3"] call_3 = ["tools", "system v2", "msg 1", "msg 2", "msg 3"] print(shared_prefix(call_1, call_2), shared_prefix(call_2, call_3))
4 1
Call 2 only added a message at the end, so all four earlier blocks can be read from the cache. Call 3 changed the system prompt, and everything after the change has to be paid for again, though the messages are word for word the same. That is why this lesson's harness only ever adds to the end.
Sort tool definitions once and never reorder them
Caching reuses an unchanged start of the request. Anything that changes it early makes later calls pay full price.
Anything near the top of a prompt that changes on every request makes the cached prefix useless. Write prefix_breakers(system): return every date like 2026-11-07 and every clock time like 09:14 (or 09:14:05) found in the text, in order, using re.findall with one pattern for each.
import re SYSTEM = ("Today is 2026-11-07 and the time is 09:14:05. " "You help customers of Trailhead Outfitters.") def prefix_breakers(system): return [] print(prefix_breakers(SYSTEM))
The second call sends the same tools and system prompt, so that prefix is read from the cache. (The practice server follows the same rules: it caches prefixes of 512 tokens or more.)
import requests PROMPT = "You are a careful coding agent for the gradient-shop project. " * 60 SYSTEM = [{"type": "text", "text": PROMPT, "cache_control": {"type": "ephemeral"}}] def call(question): r = requests.post("https://api.anthropic.com/v1/messages", headers={"x-api-key": "added-by-the-academy-server", "anthropic-version": "2026-10-21"}, json={"model": "claude-opus-5-5", "max_tokens": 200, "system": SYSTEM, "messages": [{"role": "user", "content": question}]}, timeout=60) r.raise_for_status() return r.json()["usage"] for q in ["List the test files.", "Which tests are slow?"]: u = call(q) print(q, "| new:", u["input_tokens"], "| written to cache:", u["cache_creation_input_tokens"], "| read from cache:", u["cache_read_input_tokens"])
In an engineer's week, the symptom is a bill that climbs every turn, or an agent that forgets its task after a compaction. Check the usage line first, then whether the summary kept the task.
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Where is it safe to cut a conversation when compacting?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.
Learn how to build AI agents by building one: tools, the agent loop, MCP, permissions, context management and evals, ending with a coding agent that stops when its tests pass.
Build a bounded run loop, test it with scripted model responses, and recover interrupted work from an event log.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write