AI agent interview questions and answers
Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.
Stop reasons, parallel tool calls, errors and turn budgets.
What tells a harness whether to call a tool, retry, or finish a turn?
The model response includes a stop reason. Use it as an explicit transition in a bounded loop, and return correlated tool results together when a model step requested them together.
Model returns a message with an explicit stop reason
Harness follows the matching transition and appends the exchange
Loop continues under its cap or returns the final outcome
Model returns a message with an explicit stop reason
Harness follows the matching transition and appends the exchange
Loop continues under its cap or returns the final outcome
Given Model returns a message with an explicit stop reason and Loop continues under its cap or returns the final outcome, write down the missing step that connects them.
Harness follows the matching transition and appends the exchange
Now take Harness follows the matching transition and appends the exchange and the result above. Write an input and an implementation that could produce this trace.
Model returns a message with an explicit stop reason. Check that your implementation produces the result shown above.
A model response requests three tools at once, and one fails with a valid error result. What goes back into the transcript?
Return a result for each requested ID together, including the failed tool's actionable error. The model can proceed with complete information about that turn.
Check this when debugging. Running a tool call from a reply that stopped at max_tokens.
The Phase 1 loop handled two cases: the model wants a tool, or it's done. Real loops meet more. Replies get cut off by the token limit. Long server-side work pauses. The API is sometimes overloaded. A model may decline. Each needs a different response, and getting one wrong causes the classic agent bugs: running a half-written tool call, retrying forever, or losing the conversation. This lesson builds a loop that handles them all.
Not run the half-written call; ask again with more room
Each stop reason needs its own handling. max_tokens means the reply is incomplete, so a half-written tool call may have broken or missing input, and running it could do the wrong thing.
Recall: What an agent harness is built a loop around a scripted model, and Hosts: connecting servers to a model ran a model's tool calls for real. The loop below handles every way a reply can end.
def run(model, prompt): return model(prompt).upper() calls = [] def scripted(prompt): calls.append(prompt) return "ok" print(run(scripted, "status?"), calls)
OK ['status?']
run doesn't know or care which model it was given. The scripted one returns a fixed reply and records what it was sent, so the test can check both sides of the call. No API was used. The loop in this lesson is tested the same way, one stop reason at a time.
A coworker writing you a note can stop for different reasons. They've finished. They need you to fetch something. They ran out of paper. They'd rather not answer. You'd respond differently to each, and a loop has to as well. Each Messages API response has a stop_reason, and a loop should branch on all of them:
| stop_reason | what happened | what the loop does |
|---|---|---|
end_turn | the model finished its reply | return the answer |
stop_sequence | it wrote one of your stop_sequences | usually treat as finished |
tool_use | it wants one or more tools | run them all, send all results back, loop |
max_tokens | it hit your max_tokens limit mid-reply | don't trust the reply; retry with a bigger limit, or continue |
model_context_window_exceeded | the conversation and the reply filled the model's context window | don't trust the reply; shrink the context, then call again |
pause_turn | a long server-side tool turn was paused | send the assistant content back as-is and call again |
refusal | the model declined, for safety reasons | stop; show the user a clear message |
Three of these deserve care.
stop_reason: "refusal". What should the loop do?Stop, and show the user a clear message
A refusal means the model declined, for safety reasons. Looping on it wastes calls, and passing it off as an answer misleads the user.
max_tokens with a tool call. If the reply was cut off while writing a tool_use block, its input may be incomplete. You wouldn't act on an instruction that stops mid-sentence. So never run it. The safe move is to send the same request again with a higher limit. Nothing was appended, so the transcript is unchanged.
model_context_window_exceeded. This one looks like max_tokens, but a bigger limit won't help: the whole window is full. Append nothing, shrink the context by clearing old tool results or compacting (the context lesson), and call again.
pause_turn. Server tools such as web search run on Anthropic's side. A long one can pause. Append the assistant's content as it is, with no new user message, and call again. The model picks up where it stopped.
One reply can hold several tool_use blocks, for example "read these three files". It's a shopping list, and you bring everything back in one trip. The rule: every tool_use gets a tool_result with the matching tool_use_id, and all of them go in the next user message. Dropping one gets a 400 error. Sending them as separate user messages doesn't fail, because the API merges back-to-back messages from the same role, but it teaches the model to stop asking for parallel calls. The harness may run independent calls at the same time; the results still go back together.
Four messages by the end: user, assistant, user, assistant. Read the body on every arrow.
Write a sentence or two, then compare it with a good answer in the lesson.
Separate from what the model says, the HTTP call can fail. When a phone call fails, a busy signal means try again later, and a wrong number means check the number. Sort failures the same way, by whether retrying could help:
| status | meaning | retry? |
|---|---|---|
| 400 | bad request: your code built something invalid | no: fix the code |
| 401, 403 | bad key, or no permission | no |
| 413 | request too large | no; shrink the context |
| 429 | rate limited | yes, after the retry-after header or a backoff |
| 500, 529 | server error or overloaded | yes, with backoff |
400 Bad Request. What should the harness do?Stop and fix the code: it will fail again
A 400 means your code built something invalid. Retrying sends the same broken request again, burning time and money.
Backoff, jitter and retry budgets are taught in Rate limits, retries and idempotency. Here you only decide which statuses reach that code. The official SDKs already retry 408, 409, 429, 5xx and dropped connections, twice by default, with exponential backoff and jitter. A harness adds a cap on total attempts and logs each retry. Never retry a 400 in a loop: the same bad request fails the same way, and an agent stuck doing that burns time and money.
Treat the message list like a ship's log written in pen. Add each reply and each batch of results to the end, and don't edit or reorder what's already there. That's what append-only means.
There are two reasons. Prompt caching reuses an unchanged prefix, so edits near the start make every later call pay full price. And models that think keep signed reasoning blocks in their replies; changing earlier turns can invalidate them. When the context does need to shrink, use the deliberate tools in the context lesson.
You'd give a contractor a limit on hours, so a small job can't run on forever. A loop with no limit can run forever too: the model keeps calling tools without converging. Count model calls and stop at a budget (often 20 to 100 for coding agents). When the budget runs out, return a clear status, not an exception, so the caller can report it or ask the user to continue.
statuses = [529, 429, 200] delay, waits = 1, [] for s in statuses: if s in (429, 500, 529): waits.append(delay) delay *= 2 print(waits)
[1, 2]
Two temporary errors mean two waits, 1 then 2 seconds. The 200 ends the retries.
A model can ask for several tools at once. The next message must answer every one of them, matched by id, or the API rejects the whole request.
reply = [
{"type": "text", "text": "Let me check both."},
{"type": "tool_use", "id": "t1", "name": "get_stock", "input": {"sku": "TENT-2"}},
{"type": "tool_use", "id": "t2", "name": "get_price", "input": {"sku": "TENT-2"}},
]
TOOLS = {"get_stock": lambda sku: 14, "get_price": lambda sku: 89.0}
results = [{"type": "tool_result", "tool_use_id": b["id"],
"content": str(TOOLS[b["name"]](**b["input"]))}
for b in reply if b["type"] == "tool_use"]
asked = {b["id"] for b in reply if b["type"] == "tool_use"}
answered = {b["tool_use_id"] for b in results}
print(results)
print("every call answered:", asked == answered)All the results go in one user message, and their order doesn't matter since the ids match them up. Forgetting one is a common bug, so check for it when you build the message.
Not run it: the input may be cut off. Resend the same request with a higher max_tokens
A truncated tool input could write half a file. Retrying the unchanged request with more room is safe.
The heart of a production loop is a single function that decides what to do with each reply.
def next_action(reply): reason = reply["stop_reason"] if reason in ("end_turn", "stop_sequence"): return "finish" if reason == "tool_use": return "run_tools" if reason == "pause_turn": return "continue" if reason == "max_tokens": return "retry_bigger" if reason == "model_context_window_exceeded": return "shrink_context" if reason == "refusal": return "refused" return "unknown" REASONS = ["end_turn", "tool_use", "pause_turn", "max_tokens", "model_context_window_exceeded", "refusal", "something_new"] for r in REASONS: print(r, "->", next_action({"stop_reason": r}))
Keep an explicit "unknown" branch. APIs add stop reasons over time; a loop that treats any unknown reason as "done" might silently drop work. Better to stop and log it.
The calls are independent, so run them at the same time with asyncio.gather. It returns outputs in the order the calls were given, so each result still matches its id.
import asyncio async def get_stock(sku): await asyncio.sleep(0.2) return "14" async def get_price(sku): await asyncio.sleep(0.2) return "89.0" CALLS = [("t1", get_stock, "TENT-2"), ("t2", get_price, "TENT-2")] async def run_calls(calls): outputs = await asyncio.gather(*(fn(arg) for _, fn, arg in calls)) return [{"type": "tool_result", "tool_use_id": cid, "content": out} for (cid, _, _), out in zip(calls, outputs)] import time start = time.perf_counter() results = asyncio.run(run_calls(CALLS)) took = round(time.perf_counter() - start, 1) print([r["tool_use_id"] for r in results], took, "seconds")
Stop and return a clear status, such as max_turns, with the transcript intact
A clear status lets the caller report it, or ask the person whether to continue, without losing any work.
A loop should stop for a reason it can report. Write exhausted(turns, max_turns, tokens, max_tokens): return "turns" if the turn budget is used up, "tokens" if the token budget is, "both" if both are, or None if the loop may continue.
def exhausted(turns, max_turns, tokens, max_tokens): return None print(exhausted(40, 40, 120_000, 200_000))
Write results_for(reply, tools): for each tool_use block in reply, return a tool_result dict with the same tool_use_id. The content is str(tools[name](**input)). If the tool raises, the content is "Error: " + str(err) and the dict also has "is_error": True. Keep the order of the calls.
def results_for(reply, tools): return [] reply = [{"type": "tool_use", "id": "t1", "name": "div", "input": {"a": 6, "b": 3}}] print(results_for(reply, {"div": lambda a, b: a / b}))
Write a sentence or two, then compare it with a good answer in the lesson.
Here is the same shape against the real endpoint. Without an API key, the academy's practice server answers, in the real response format. It always uses the first tool, so it shows the loop's shape rather than real reasoning.
import requests TOOLS = [{"name": "get_time", "description": "Current time in a city.", "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}] def call(messages, max_tokens=800): 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": max_tokens, "tools": TOOLS, "messages": messages}, timeout=60) r.raise_for_status() return r.json() messages = [{"role": "user", "content": "What time is it in Lisbon?"}] for turn in range(4): reply = call(messages) messages.append({"role": "assistant", "content": reply["content"]}) print(turn, reply["stop_reason"]) if reply["stop_reason"] != "tool_use": break results = [{"type": "tool_result", "tool_use_id": b["id"], "content": "14:05"} for b in reply["content"] if b["type"] == "tool_use"] messages.append({"role": "user", "content": results}) from agentlab import show show(messages) print([b["text"] for b in reply["content"] if b["type"] == "text"][-1][:120])
In an engineer's week, this loop is where every incident about a stuck or looping agent ends up: a status that was never branched on, a retry with no cap, or a cut-off reply that ran. Read the stop reason first.
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.
A reply contains three tool_use blocks. How should their results go back?
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