AI agent interview questions and answers
Questions on designing and running agents: tools, the agent loop, permissions, context, multi-agent systems, security and evaluation.
Live output, stopping safely, and saving and resuming transcripts.
When is a streamed tool request complete enough to run?
Treat stream fragments as partial data until the API reports a complete tool block. An append-only event record gives recovery code a way to distinguish a complete request from an interrupted one.
Stream delivers pieces of the tool arguments
Harness assembles and validates the complete block
Only the completed request is eligible for execution
Stream delivers pieces of the tool arguments
Harness assembles and validates the complete block
Only the completed request is eligible for execution
Given Stream delivers pieces of the tool arguments and Only the completed request is eligible for execution, write down the missing step that connects them.
Harness assembles and validates the complete block
Now take Harness assembles and validates the complete block and the result above. Write an input and an implementation that could produce this trace.
Stream delivers pieces of the tool arguments. Check that your implementation produces the result shown above.
A connection drops after half of the tool's JSON arguments arrive. Can a resumed run execute that request?
The incomplete block must stay unexecuted. Resume from a stable event and let the next valid turn produce a complete request.
A note is visible after a crash but the event log ends at pending. Which identifiers should a recovery test keep fixed across both processes?
Keep the operation ID, caller scope, and intended payload stable. Assert that recovery finds the committed note, records the result, and leaves the note count unchanged.
Check this when debugging. Parsing each tool input piece as it arrives.
A harness is software people use, not a batch job. They want to see the reply as it's written, stop the agent when it heads the wrong way, close the laptop and carry on tomorrow. Each needs care: streamed tool inputs arrive as half-finished JSON, a stop in the middle of a turn can break the transcript, and a session file that's only written at the end is lost in a crash.
Interrupt it, keeping the work done so far
A good harness streams events as they happen, so the user can stop it mid-step and redirect it, and it saves the session so it can be resumed or forked later.
Recall: Streaming responses showed text arriving in pieces, and The core loop, built properly appended each finished message. Here the pieces are tool inputs and thinking too.
content_block_delta events of the text_delta kind, and the stop reason arrives in message_delta, near the end. What does this print?events = [
{"type": "message_start"},
{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hel"}},
{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "lo"}},
{"type": "message_delta", "delta": {"stop_reason": "end_turn"}},
]
text = "".join(e["delta"]["text"] for e in events
if e["type"] == "content_block_delta"
and e["delta"]["type"] == "text_delta")
stop = [e["delta"]["stop_reason"] for e in events if e["type"] == "message_delta"][0]
print(text, stop)Hello end_turn
The two text pieces are joined in the order they arrived, and the stop reason is read from the event near the end. A harness has to assemble every stream this way. Tool input arrives in pieces too, as fragments of JSON. This lesson builds that, and what to do when someone presses Stop halfway through.
Think of a news ticker, or a parcel tracker that updates as things happen. With "stream": true, the Messages API sends server-sent events as the reply is generated:
| event | carries |
|---|---|
message_start | the message shell, with starting usage |
content_block_start | a new block at an index: text, tool_use (name and id), or thinking |
content_block_delta | a piece of that block: text_delta, input_json_delta, thinking_delta or signature_delta |
content_block_stop | that block is complete |
message_delta | the stop_reason, and final output usage |
message_stop | the end |
There are also ping events to ignore, and error events to handle.
Text pieces can be shown at once: that's the live typing effect. Tool inputs are more like flat-pack furniture arriving in several boxes. They come as fragments of a JSON string ({"pa, th": "src/, app.py"}), and you can't build anything until the last box arrives. Join them, and parse only at content_block_stop. Parsing early fails, or worse, gives a partial input.
Thinking pieces (thinking_delta) join into the block's thinking text, and its signature arrives in a signature_delta before the block stops. Send it back exactly as it came, signature included, or the API rejects it. The text may be empty; the signature still comes.
The SDKs do this assembly for you (client.messages.stream(...) with get_final_message()). Knowing how it works helps when you show partial output or debug a stream that broke halfway.
Eleven events, one message. The thinking block keeps both its text and its signature.
parts = ['{"sku"', ': "TENT', '-2"}'] import json print(json.loads("".join(parts))["sku"])
TENT-2
join puts the pieces back together as {"sku": "TENT-2"}, and ["sku"] reads TENT-2. Tool input arrives as pieces of JSON. Only the joined whole can be parsed.
At that block's content_block_stop, after joining all the pieces
Pieces are fragments of one JSON string. Only the joined whole is valid.
Write a sentence or two, then compare it with a good answer in the lesson.
Each piece alone is broken JSON. Together they parse.
import json pieces = ['{"pa', 'th": "src/', 'app.py", "li', 'mit": 50}'] for p in pieces: try: json.loads(p) print("parsed alone:", p) except json.JSONDecodeError: print("not JSON alone:", repr(p)) print(json.loads("".join(pieces)))
This is why a harness keeps a buffer per block index and parses at the block's stop event.
Don't parse tool input until it's finished. Tool input arrives as pieces of JSON text, and each piece on its own is usually invalid.
import json pieces = ['{"path": "sr', 'c/app.py", ', '"limit": 10}'] try: json.loads(pieces[0]) except ValueError as err: print("too soon:", err.msg) print(json.loads("".join(pieces)))
Collect the pieces by the block's index, and parse once at content_block_stop. If you want to show progress before then, display the raw text.
If you only save the transcript when a session ends, then a crash loses everything, including what the agent did to your files. So append each message when it happens. Disk writes cost almost nothing next to a model call.
A person might come back to a session hours or days later. In that time, files can change, branches can move, and a test that was failing may have been fixed. The transcript still describes the old world, and the model will trust it. So when resuming, tell the model that time has passed, and what's changed if you can tell. For example, add a note: "This session resumed after 3 days. Files may have changed, so read them again before editing." It's a small message, and it prevents the agent from confidently editing code that's no longer there.
That time has passed, and what has changed since the transcript ended
The transcript describes the world as it was, and the model will trust it. Files, branches and test results may have moved, so say that time has passed and what is different now.
A factory line has a stop cord, and everyone knows what happens when it's pulled. When the person presses Stop, the harness must:
tool_use blocks without results, add a user message of tool_result blocks saying they were interrupted, with is_error: true. Or drop that unfinished assistant message entirely.Skip step 3, and the next request fails: every tool_use needs a tool_result. The interruption note also tells the model why its plan stopped, so it doesn't assume the tool ran.
If someone presses Stop during a tool call, the last message has a tool_use with no result, and the next API call would fail. Repair it before saving.
def repair(messages): last = messages[-1] if last["role"] != "assistant": return messages open_calls = [b["id"] for b in last["content"] if b["type"] == "tool_use"] if open_calls: messages.append({"role": "user", "content": [ {"type": "tool_result", "tool_use_id": i, "content": "Interrupted by the user.", "is_error": True} for i in open_calls]}) return messages messages = [ {"role": "user", "content": [{"type": "text", "text": "Run the tests"}]}, {"role": "assistant", "content": [{"type": "tool_use", "id": "t1", "name": "bash"}]}, ] repair(messages) print(messages[-1])
Now the transcript is valid and it's honest about what happened. When the session resumes, the model knows the tests didn't finish, so it won't assume they passed.
The emergency stop on a machine doesn't wait for the current cycle to finish. When a person presses Stop, they may have spotted the agent doing something wrong. So stopping must take effect at once: close the stream, kill running commands, and don't start anything new. A Stop that waits for the current tool to finish isn't really a Stop. Test it on purpose, with a long-running command, since this is the kind of path that nobody exercises until the day it matters, and then it really has to work.
content_block_start
The block starts with its type, name and id. The input then arrives in input_json_delta pieces.
Save each session as an append-only log, like a ship's log written one line at a time: one JSON object per line (JSONL), written as each message is added. A crash loses at most the line being written. Resuming means reading the lines back into a message list.
The world moves on. After a vacation, you'd check what changed before picking up old work. Between sessions, files change and branches move. On resume, tell the model: "Session resumed. Files may have changed since; read them again before editing." The stale-edit check from the file tools lesson is your safety net.
One JSON object per line means each message is saved as it happens. If the power goes mid-write, only the last line is damaged, and you can skip it.
import json lines = [ json.dumps({"role": "user", "content": "Fix the bug"}), json.dumps({"role": "assistant", "content": "On it"}), '{"role": "user", "cont', # the crash happened here ] def load(lines): messages = [] for n, line in enumerate(lines): try: messages.append(json.loads(line)) except ValueError: if n != len(lines) - 1: raise # damage in the middle isn't a crash: stop and look return messages print(load(lines))
Everything before the crash is safe. Note that only a bad last line is forgiven. A bad line in the middle means something else is wrong, and quietly skipping it would hide lost messages.
Sessions are saved one JSON record per line, so a crash can leave a half-written last line. Write load(text): parse each non-blank line with json.loads; if the last line is broken, drop it; if any earlier line is broken, raise ValueError (that's real corruption, not a crash mid-write).
import json def load(text): return [json.loads(line) for line in text.splitlines()] text = '{"role": "user", "content": "hi"}\n{"role": "assistant", "content": "hel' print(load(text))
Copies the first part of a session into a new one, to try another approach from that point
The original stays untouched, so you can compare approaches from the same starting point.
Forking starts a new session from an earlier point, leaving the original untouched. Write fork(messages, upto): return a deep copy (copy.deepcopy) of the first upto messages, so changes to the fork, even inside nested content blocks, can't reach the original.
import copy def fork(messages, upto): return messages[:upto] ask = [{"type": "text", "text": "Plan the migration."}] original = [{"role": "user", "content": ask}, {"role": "assistant", "content": "Step 1..."}] branch = fork(original, 1) branch[0]["content"][0]["text"] = "Plan it differently." print(original[0]["content"][0]["text"])
That time has passed and files may have changed
The transcript describes the world as it was. Without a note, the model will trust it and may edit code that is no longer there.
Write a sentence or two, then compare it with a good answer in the lesson.
A real harness gets all of this from the SDK. What stays yours is the stop button, the session log and where the run lives, which is often not a browser tab.
A long run should not hold a connection open. Put the harness in a worker, put each message in the session log, and let callers read a status endpoint or get a webhook. Caches, queues and background jobs builds the queue and the worker; the loop inside is the one you wrote.
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.
Which stream event carries the stop_reason?
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