AI agent interview questions and answers
Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.
See what an agent did, cap what it spends, and stop it when it loops.
What goes wrong if the harness checks its budget only after a paid tool finishes?
A useful budget is an execution rule at the boundary, supported by per-call traces and cumulative usage. Check allowance before starting work and reconcile the actual use after it completes.
Harness estimates the next call's cost
Budget gate compares it with the remaining allowance
Trace records the admitted call or the reason for stopping
Harness estimates the next call's cost
Budget gate compares it with the remaining allowance
Trace records the admitted call or the reason for stopping
Given Harness estimates the next call's cost and Trace records the admitted call or the reason for stopping, write down the missing step that connects them.
Budget gate compares it with the remaining allowance
Now take Budget gate compares it with the remaining allowance and the result above. Write an input and an implementation that could produce this trace.
Harness estimates the next call's cost. Check that your implementation produces the result shown above.
A run has one unit left and the next call requires two. What should an operator see?
The harness should stop before the call and record a budget event with the needed and remaining amounts. That makes the missing result explainable without overspending.
Check this when debugging. Relying on the turn budget alone to stop loops.
In production an agent runs thousands of times a day with no one watching. When a user reports "it did something weird", you need to see exactly what happened. When a bug makes it loop, you need it to stop before it spends a fortune. Tracing, budgets and guardrails turn a clever demo into a service a team can run and trust.
A trace of that run: each model call, tool call and result
A trace records every step of a run, like a flight recorder, so you can replay what the agent saw and did. Budgets and guardrails stop runs before they go too far; traces explain them afterward.
Recall: Logging and monitoring logged each call, and The core loop, built properly counted turns. In production you also need the tree of what happened, a spending limit and a guard against loops.
After a plane has trouble, investigators read the flight recorder to see exactly what happened and when. A trace is that record for one agent run. It's made of spans: timed steps, each with a parent.
run "fix failing test" 41.2 s $0.183 ├── model call 1 3.1 s in 4,210 out 312 ├── tool read_file src/cart.py 0.01 s ├── model call 2 2.8 s in 5,060 out 158 ├── tool bash "pytest -x" 6.4 s exit 1 └── ...
Each span records its name, start and end time, its parent, and attributes: tokens, stop reason, tool name, exit code, error. Standards such as OpenTelemetry, with its conventions for generative AI, let you send these to common observability tools. Many LLM tracing products accept the same data. Tracing a run end to end follows one trace across several programs.
What to record, and what not to:
latencies = sorted([1.2, 0.9, 1.1, 1.0, 8.5, 1.3, 0.8, 1.0, 1.1, 0.9]) mean = sum(latencies) / len(latencies) p95 = latencies[int(0.95 * len(latencies))] print(round(mean, 2), p95)
1.78 8.5
Nine runs took about a second, and one took 8.5. The mean of 1.78 describes none of them. The p95 points straight at the slow one. A trace, in this lesson, is how you find out where that run spent its time: which model call, which tool, which retry.
Step through the spans. The tool call holds most of the time, and an install holds most of the tool call.
A prepaid phone card can't run up a surprise bill. Every run needs limits that stop it cleanly in the same way:
| budget | stops |
|---|---|
| turns | loops that never converge |
| tokens or dollars | expensive runs, such as huge files read again and again |
| wall-clock time | runs stuck waiting on slow tools |
| tool calls of one kind | for example, at most 3 deploys |
Work out cost from usage on each response. Cache reads cost much less than normal input, and cache writes a little more, so count them separately. Prices change; keep them in config, not code.
Write a sentence or two, then compare it with a good answer in the lesson.
A trace is a tree of timed steps. Draw one as a waterfall and the slow part stands out at once.
import matplotlib.pyplot as plt from agentlab import spans_plot PRICE_IN, PRICE_OUT = 4, 20 # dollars per million tokens, Opus 5.5 SPANS = [ {"id": 1, "name": "agent turn", "start_ms": 0, "end_ms": 8200}, {"id": 2, "parent": 1, "name": "model call", "service": "model", "start_ms": 0, "end_ms": 1100, "tokens_in": 4210, "tokens_out": 312}, {"id": 3, "parent": 1, "name": "tool: run_tests", "service": "tools", "start_ms": 1100, "end_ms": 7800}, {"id": 4, "parent": 3, "name": "install packages", "service": "tools", "start_ms": 1100, "end_ms": 7000}, {"id": 5, "parent": 3, "name": "pytest", "service": "tools", "start_ms": 7000, "end_ms": 7780}, {"id": 6, "parent": 1, "name": "model call", "service": "model", "start_ms": 7800, "end_ms": 8200, "tokens_in": 5060, "tokens_out": 158}, ] spans_plot(SPANS, unit="ms", highlight=[3, 4]) cost = sum(s.get("tokens_in", 0) * PRICE_IN + s.get("tokens_out", 0) * PRICE_OUT for s in SPANS) / 1_000_000 print(f"model cost of the turn: ${cost:.4f}") plt.show()
Without a trace you might blame the model. Here most of the turn goes to installing packages, inside one tool, and that's what you'd cache. Two model calls cost $0.0465 together: 4,210 + 5,060 input tokens and 312 + 158 output tokens at $4 and $20 per million.
Write time_by_name(spans): each span has name, start_ms and end_ms. Return a list of (name, total_ms) tuples, adding up spans with the same name, longest total first.
SPANS = [
{"name": "model_call", "start_ms": 0, "end_ms": 2400},
{"name": "tool:read_file", "start_ms": 2400, "end_ms": 2450},
{"name": "model_call", "start_ms": 2450, "end_ms": 5100},
{"name": "tool:run_tests", "start_ms": 5100, "end_ms": 9300},
]
def time_by_name(spans):
return []
print(time_by_name(SPANS))
Count each kind of input token at its own rate. These prices are made up for the example.
# dollars per million tokens PRICES = {"input": 5.00, "output": 25.00, "cache_read": 0.50, "cache_write": 6.25} def cost(usage): return (usage["input_tokens"] * PRICES["input"] + usage["output_tokens"] * PRICES["output"] + usage.get("cache_read_input_tokens", 0) * PRICES["cache_read"] + usage.get("cache_creation_input_tokens", 0) * PRICES["cache_write"] ) / 1_000_000 first = {"input_tokens": 300, "output_tokens": 400, "cache_creation_input_tokens": 20_000} later = {"input_tokens": 300, "output_tokens": 400, "cache_read_input_tokens": 20_000} print(f"first call ${cost(first):.4f}") print(f"later calls ${cost(later):.4f}")
Once the prefix is cached, later calls cost far less. That's why a stable prefix matters so much for agents.
prices = {"input": 3.0, "output": 15.0}
usage = {"input_tokens": 2000, "output_tokens": 1000}
cost = (usage["input_tokens"] * prices["input"]
+ usage["output_tokens"] * prices["output"]) / 1_000_000
print(round(cost, 3))0.021
2,000 × $3 plus 1,000 × $15 is $21 per million tokens of each, so $0.021 for this call.
Write outliers(costs, multiple=5): return the positions of runs whose cost is more than multiple times the median of all the costs (use statistics.median).
import statistics def outliers(costs, multiple=5): return [] print(outliers([0.12, 0.09, 0.15, 4.80, 0.11, 0.10]))
A budget stops a stuck agent eventually. A guard notices after a few calls. It fingerprints each call as the tool name plus its input as sorted JSON, and counts the last ten.
calls = [("read", "app.py"), ("run", "pytest"), ("run", "pytest"), ("run", "pytest")] def stuck(history, repeats=3): return len(history) >= repeats and len(set(history[-repeats:])) == 1 print([stuck(calls[:n]) for n in range(1, 5)])
[False, False, False, True]
After the fourth call, the last three are identical, and the detector fires. It took 4 calls. A turn budget of 50 would have let the agent hit the same window 46 more times first. When it fires, a good harness tells the model what it noticed, so the next step can be something different.
Here's the fingerprint idea from this section. The call is the same if the tool and its input match, whatever order the input's keys came in.
import json from collections import Counter def fingerprint(tool, args): return tool + ":" + json.dumps(args, sort_keys=True) def watch(calls, window=10, limit=3): recent = [] for n, (tool, args) in enumerate(calls, 1): recent = (recent + [fingerprint(tool, args)])[-window:] if Counter(recent)[recent[-1]] >= limit: return f"step in at call {n}: {tool} repeated {limit} times" return "no loop" calls = [("read", {"path": "a.py", "limit": 10}), ("edit", {"path": "a.py"}), ("read", {"limit": 10, "path": "a.py"}), ("run", {"cmd": "test"}), ("read", {"path": "a.py", "limit": 10})] print(watch(calls)) print(watch(calls[:4]))
The third read has its keys in a different order and still counts, because the JSON is sorted first. This catches a stuck agent after a few calls, not after your turn budget and a large bill.
read_file with the same input three times in its window. What should the harness do first?Tell the model in the tool result that it's repeating itself; stop the run if it carries on
A nudge often breaks the loop cheaply. A firm stop comes next if it doesn't.
Write a sentence or two, then compare it with a good answer in the lesson.
A restaurant tries a new dish on a few tables before it goes on the menu. Ship agents with the same care:
A building has smoke alarms and sprinklers as well as fire doors. A budget will stop a stuck agent eventually, but "eventually" might be $20 and 100 turns later. Loop detection catches it after three identical calls, and a cost limit stops expensive runs whatever they're doing. Use all of them, in layers.
Agent logs are unusually sensitive. Full prompts contain whatever the agent read: customer records, private code, or keys it found in a config file. So decide on redaction and a retention limit before you start logging, not after. Store the sensitive parts separately, with stricter access, and delete them on a schedule. Metadata such as token counts, tool names and timings can usually be kept for longer.
Metadata: token counts, tool names and timings
Metadata says how the agent behaved without holding what it read. The sensitive parts are stored apart and deleted on a schedule.
Prices change, and new models arrive. If they're hard-coded across your harness, your cost reports silently drift from reality. Keep one table in config, and record the model id on each span, so that you can recalculate old runs if you need to.
A one-line change to a system prompt can change an agent's behavior more than a thousand lines of code. Yet people often edit prompts directly in production, with no review and no test. So keep prompts in version control. Run your eval suite on every change, and roll out in stages, just as you would with code. Include the prompt version on every trace, so that when behavior shifts, you can tell which change caused it.
When a shipped agent starts misbehaving, ask first what changed: the prompt, the tools, the model, or the data it reads. Those four cover almost every regression you'll see, and your traces should be able to answer it.
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.
What is a span in a trace?
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