AI Engineering Interview Questions: Agents & Agent Systems
Reviewed by Mark Dickie · Last updated
AI agents are software systems that use large language models to plan, select tools, take actions, and iterate toward a goal with limited human oversight. For an AI agent interview, expect questions on agent architectures (ReAct, Plan-and-Execute), tool calling and function schemas, memory management, and evaluation of agentic loops. You should be able to explain how an agent decides when to call a tool versus respond directly, how to structure multi-step plans, and the failure modes that come up most: infinite loops, hallucinated tool calls, and context window overflow.
| Area | What it covers | Typical interview question |
|---|---|---|
| ReAct | Reason-then-act loop: think, act, observe, repeat | Walk through a single ReAct cycle |
| Plan-and-Execute | Decompose a goal into steps, execute, then replan | When should the agent replan vs. continue? |
| Tool calling | LLM selects a function and arguments from a schema | How do you validate tool arguments before execution? |
| Memory | Short-term context window, long-term vector retrieval | How does an agent decide what to keep vs. discard? |
| Multi-agent | Multiple agents with roles, shared or isolated state | How do you prevent infinite handoffs between agents? |
What does an AI agent interview test?
- Agent loop design: can you write the control flow from prompt to LLM to tool call to observation and back?
- Tool and schema design: can you write tool descriptions and argument schemas that an LLM will reliably pick?
- Failure handling: what happens when a tool errors out, the LLM loops, or the context window fills?
- Evaluation: how do you measure whether an agent solved the task or gave up partway?
- Framework trade-offs: where do LangGraph, CrewAI, or AutoGen help, and what do they hide from you?
How do you manage context and memory in an agent?
Agent memory splits into two layers: the working context (the current conversation held in the LLM's context window) and long-term storage (typically a vector database for retrieval). The hard part in interviews is explaining when you retrieve, how you summarize past interactions to fit the window, and how you avoid loading irrelevant history. Expect questions on whether to use a fixed buffer, a summarization step, or retrieval-augmented memory, and the trade-offs of each approach.
Key facts
- Tarmac has 207 AI Engineering interview questions on this topic, 25 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 31 August 2026.
At a glance
| Questions | 25 shown · 207 in the bank |
|---|---|
| Difficulty | 1–5 of 5 |
| Formats | Ordering, Multiple choice, Multiple answer, True / false, Fill in the blank, Short answer, Flashcard, Code output, Find the bug, Design exercise |
What you'll review
- agent loops
- agent memory
- agents
- tool calling
- mcp
Practice questions
Try one before you open the answer. Pick an option and press Check; it's marked on the spot.
AI Engineering/agents/agent-loops
Arrange the steps of a standard LLM agent loop in the correct execution order, starting from the beginning of one iteration.#
Put these in order
Show answer
In a standard LLM agent loop, the correct execution order is: (1) the LLM reasons over the current context and selects an action, (2) that action or tool call is executed, (3) the agent receives the observation or tool result, (4) a stopping condition is checked to see if the task is complete, and (5) if not done, the observation is appended to context and the next iteration begins. This repeating think-act-observe cycle is the core pattern behind frameworks like ReAct.
An agent loop (also called a ReAct loop or think-act loop) follows a repeated cycle: the agent observes the current state/context, reasons or thinks about what to do, takes an action (e.g., calls a tool), receives an observation back, and repeats until a stopping condition is met. This is the fundamental pattern behind virtually all LLM-based agent frameworks.
AI Engineering/agents/agent-loops
In a typical LLM-based agent loop, which component is responsible for actually executing a tool call (e.g., running a web search or calling an API)?#
Options
Show answer
The agent runtime (or orchestrator) that wraps the LLM is responsible for actually executing tool calls like web searches or API requests. The LLM itself only reasons about which action to take and what arguments to pass — it cannot run code or call external services directly. The runtime performs the action, then feeds the result back to the LLM as an observation to continue the loop.
In an agent loop the LLM does NOT execute code or call APIs directly — that is the job of the surrounding runtime/executor. The LLM's role is limited to reasoning and deciding which action to take and what arguments to pass. The runtime then actually performs the action and returns the result (observation) to the LLM.
AI Engineering/agents/agent-loops
Which of the following are valid stopping conditions that can terminate an LLM agent loop? Select all that apply.#
Options
Pick every one that applies.
Show answer
Valid stopping conditions for an LLM agent loop include the LLM emitting a designated "Final Answer" signal, a cap on the maximum number of steps or iterations being reached, and a programmatic check detecting that the task objective is satisfied. Any of these terminates the loop, which would otherwise run indefinitely. Reaching a minimum token count, by contrast, is not a practical or meaningful stopping criterion.
Without a stopping condition an agent loop would run forever. Common termination criteria are: the LLM emits a special 'Final Answer' token/signal, a maximum number of steps/iterations is reached, or the task objective is detected as satisfied. Reaching a minimum token count is not a meaningful stopping condition and is not used in practice.
AI Engineering/agents/agent-memory
A vector database used as an agent's external long-term memory can store and retrieve information from previous conversation sessions, not just the current one.#
Options
Show answer
True. A vector database used as an agent's external memory persists embeddings of past interactions to disk. This means the agent can retrieve relevant information from previous conversation sessions — not just the current one — effectively providing long-term memory that survives context window resets.
Vector databases (e.g., Pinecone, Chroma, Weaviate) persist embeddings of past interactions or knowledge on disk. An AI agent can query this store at the start of or during a new session to retrieve relevant memories from prior sessions, effectively giving it long-term memory that survives context resets.
AI Engineering/agents/agent-loops
To prevent an agent loop from running indefinitely, developers should set a _____ limit on the number of iterations, and the loop should also exit when the agent emits a _____ action (e.g., finish or final_answer).#
Show answer
To prevent an agent loop from running indefinitely, developers should set a maximum-step limit on the number of iterations, and the loop should also exit when the agent emits a terminal action (e.g., finish or final_answer).
A maximum-step (or max-iterations) guard is essential to prevent an agent loop from running forever when the LLM never produces a terminal action or gets stuck in a tool-call cycle. Without it, the loop can consume unbounded tokens and API calls. The other options — temperature, embedding size, and chunk size — do not control loop termination.
AI Engineering/agents
Your assistant calls a single get_weather tool once per user message, returns the result, and stops — it never decides to call a second tool or re-plan based on what it learned. A teammate calls this 'an agent.' What is the more precise distinction between a tool-using assistant and an agent?#
Options
Show answer
An agent runs an iterative loop: it plans a next step, acts (often via a tool call), observes the result, and decides what to do next toward a goal, rather than making one call and stopping. A workflow orchestrates LLMs and tools through a predefined code path; an agent is a system where the model dynamically directs its own process based on what it just observed. A single tool call followed by returning the result, with no model-decided branching, is a workflow of depth one, not an agent. Using multiple LLM providers or streaming tokens are unrelated implementation details.
The architectural line is control flow, not vocabulary: a workflow orchestrates LLMs and tools through a predefined code path, while an agent is a system where the model dynamically directs its own process — deciding, based on what it just observed, whether to call another tool, revise its plan, or stop. A single tool call followed by returning the result, with no branching decided by the model, is a workflow of depth one, not an agent loop; the defining property is the model-controlled plan → act → observe cycle repeating until the model judges the task done. Provider count (c) and streaming (d) are unrelated implementation details.
AI Engineering/agents/tool-calling
Explain how LLM tool calling (function calling) works end to end. Who actually executes the tool?#
Show answer
You give the model a set of tool definitions with names, descriptions, and JSON-schema parameters. When the model decides a tool is needed it doesn't run anything — it returns a structured tool-call request with arguments matching the schema. Your application code executes the function, then sends the result back to the model as a tool-result message, and the model continues, optionally calling more tools, until it produces a final answer. The model only chooses and fills in arguments; your code is the one that actually executes the side effect.
Tool calling is a structured-output contract: the model emits a request (tool name plus schema-validated arguments) rather than running code itself. The host application executes the function, returns the result as a tool message, and the loop repeats. This separation is the whole security model — the model never has direct execution authority, so you can validate arguments, enforce permissions, and sandbox effects before acting. It is also the foundation of agent loops and MCP.
AI Engineering/agents/mcp
What problem does the Model Context Protocol (MCP) solve, and what does it standardize?#
Show answer
MCP is an open protocol that standardizes how LLM applications connect to external tools, data sources, and prompts through a uniform client/server interface. Instead of writing a bespoke integration for every tool and every model host, you build an MCP server that exposes capabilities — tools (callable functions), resources (readable data/context), and prompts (reusable templates) — and any MCP-compatible client (host app) can discover and use them. It decouples integrations from any single vendor: write the server once, reuse it across hosts.
MCP is essentially "USB-C for tools": a common wire format so the M×N problem of wiring M apps to N tools collapses to M+N. It standardizes capability discovery and invocation (tools/resources/prompts), keeping integrations portable across model hosts.
AI Engineering/agents
A support-ticket feature always performs the same three steps for every ticket, in the same order: classify the category, look up the matching KB article, and draft a templated reply. No step's outcome ever changes which step runs next. Which architecture fits best, and why?#
Options
Show answer
A fixed pipeline of three deterministic steps — a workflow — fits best, because the control flow never actually depends on the model's own judgment about what to do next. When a task's steps are fixed and predictable ahead of time, a deterministic pipeline gives the same result with lower cost, lower latency, and fully reproducible behavior; an agent's autonomy buys nothing when there's no real decision to make, and adds a new failure surface instead. A multi-agent supervisor adds coordination overhead for no benefit here, and letting a single prompt decide whether to skip steps just reintroduces the same non-determinism.
Find the simplest solution possible and only add complexity when it demonstrably improves outcomes. When the sequence of steps is fixed and predictable ahead of time, a deterministic pipeline gives the same result with lower cost, lower latency, and fully reproducible behavior — an agent's autonomy buys nothing when there is no real decision for the model to make, and it adds a new failure surface (the model could mis-route, loop, or call tools unnecessarily). Reserve agents for tasks whose path genuinely can't be predetermined. A multi-agent supervisor (c) adds coordination overhead for three steps that need no specialist parallel work. Letting one prompt 'decide' whether to skip steps (d) just reintroduces the same non-determinism through the back door.
AI Engineering/agents
An agent got stuck overnight: it kept calling the same search tool with slightly reworded queries, never satisfied it had 'enough' information, until it hit the model's context-window limit and errored out after running up a large bill. Which guardrail most directly prevents this failure mode from recurring?#
Options
Show answer
Enforce a hard cap on iterations or tool calls, and/or a token or dollar budget, per task, forcing the agent to stop and return its best partial answer once the cap is hit. Maximum iteration limits are a core agent safeguard because agent errors can compound and autonomy needs a hard external ceiling, not a hope that the model self-regulates. Lowering temperature makes output deterministic but doesn't bound iteration count — a deterministic 'not sufficient yet' judgment will loop forever without an external stop. A bigger context window only delays the crash, and removing the tool disables legitimate functionality instead of bounding misuse.
Maximum iteration limits (and/or token or cost budgets) are a core agent safeguard precisely because agent errors can compound and autonomy needs a hard external ceiling, not a hope that the model self-regulates (b). Temperature 0 (a) doesn't bound iteration count — it makes the model's output deterministic, but a deterministic 'not sufficient yet' judgment will deterministically loop forever without an external stop condition. A bigger context window (c) only delays the crash and raises the cost ceiling before anything actually stops it. Removing the tool (d) disables legitimate functionality instead of bounding misuse of it — the next tool the agent leans on unboundedly would cause the same failure.
AI Engineering/agents
Giving an agent a hard iteration/token budget guarantees it will produce a correct final answer within that budget, as long as the budget is large enough.#
Options
Show answer
False. A hard iteration or token budget bounds cost and runtime — it forces the agent to stop — but it does not make the agent's reasoning or tool use correct. An agent can exhaust its entire budget on a flawed plan or a misread tool result and still be wrong when the cap hits, and enlarging the budget only lets more unproductive work happen before the forced stop rather than fixing why the agent went wrong. Budgets protect cost and latency; correctness needs its own guardrails, like sufficiency checks and evaluation.
A budget bounds cost and runtime — it forces the agent to stop — it does not make the agent's reasoning or tool use correct. An agent can exhaust its entire budget on a flawed plan, misinterpret a tool's result, or oscillate between two unproductive strategies and still be wrong (or return a low-confidence partial answer) when the cap hits. Enlarging the budget only lets more of that unproductive work happen before the forced stop; it doesn't address why the agent went wrong in the first place. Budgets and correctness are separate concerns — the budget protects cost and latency, while quality needs its own guardrails, such as sufficiency checks, verification steps, and evaluation.
AI Engineering/agents
Splitting a task across more specialized agents always improves output quality compared to a single well-scoped agent handling the whole task.#
Options
Show answer
False. More agents means more inter-agent hand-offs, more tokens spent on coordination, and more opportunities for one agent's error or stale context to propagate downstream — documented failure modes that can make a multi-agent system worse than a single agent, especially on tasks that are fundamentally sequential rather than genuinely parallelizable. Multi-agent decomposition pays off when sub-tasks are large, independent, and benefit from focused per-agent context and tools; it is not an automatic quality win for every task.
More agents means more inter-agent hand-offs, more tokens spent on coordination, and more opportunities for one agent's error or stale context to be passed downstream and treated as trusted input by the next agent — documented failure modes (coordination overhead, error compounding, context pollution) that can make a multi-agent system worse than a single agent, especially on tasks that are fundamentally sequential rather than genuinely parallelizable. Multi-agent decomposition pays off when sub-tasks are large, independent, and benefit from focused per-agent context and tools — it is not an automatic quality win for every task.
AI Engineering/agents
An engineer builds an agent that plans all N tool calls upfront in one shot, executes them, and only afterward looks at any of the results. Why does this break the point of an agent loop, and what should happen instead?#
Show answer
Planning every step upfront without looking at results defeats the reason to use an agent at all — it collapses back into a fixed pipeline of predetermined steps decided before any evidence exists, so it can't adapt when a tool returns something unexpected: an empty search result, an error, or a value that changes what the next question even should be. The point of the plan-act-observe loop is that each observation feeds back into the model's context before the next planning step, so the agent can revise its plan, retry with different arguments, ask a follow-up, or decide it already has enough information and stop early. Batch-planning N calls upfront only works when the calls are genuinely independent and none of them could change what the others need to look like; the moment step 2 might depend on what step 1 returned, planning both before observing either throws away the model's ability to react — which is exactly what separates an agent from a scripted workflow.
The plan-act-observe loop's whole value is that each observation updates the model's context before the next decision, letting the agent react to what it just learned. Planning every step in a single upfront batch — without an observe step between them — throws that adaptability away and turns the 'agent' into a fixed sequence of predetermined calls, which is fine only when the calls are truly independent, and a liability the moment one step's result should change the next step's plan.
AI Engineering/agents
What's the practical difference between 'an LLM that can call tools' and 'an agent,' and why does the distinction matter when you're deciding how to architect a feature?#
Show answer
Tool-calling is a capability — the model can emit a structured request for your code to execute. An agent is an architecture built on top of that capability: the model runs an iterative loop where it plans a next step, observes the result of acting on it, and decides on its own what to do next, potentially many times, until it judges the task done. A single tool call followed by one response is much closer to a scripted workflow than an agent — the control flow is still effectively fixed. The distinction matters architecturally because agents trade predictability for flexibility: more LLM calls, more latency, non-deterministic behavior, and a need for guardrails (iteration caps, budgets, human checkpoints) a single call or fixed pipeline doesn't need. Reach for an agent only when the task's path genuinely can't be predetermined; otherwise a workflow of one or more scripted tool calls is simpler, cheaper, and more predictable.
The line between 'tool calling' and 'agent' is architectural, not a marketing label: the loop the model runs and the decisions it's allowed to make on its own is what separates them, and that difference is exactly what should drive the build-vs-simplify call on a new feature.
AI Engineering/agents/agent-loops
This models an agent loop that re-sends its whole transcript each iteration. sent accumulates the input tokens billed across the run. What does it print?#
context = 1000 # system prompt + goal
sent = 0
for step in range(4):
sent += context # the whole transcript is re-sent
context += 500 # this step's tool call + result
print(sent, context)Options
Show answer
The loop prints 7000 3000, billing 1000, 1500, 2000 and 2500 input tokens across its four iterations, summing to 7000, while the transcript itself only reaches 3000 tokens. The gap is the whole point: every earlier token is paid for again on every later step, so the run costs more than twice the final context size. Counting only the tokens each step adds gives 4000 — the single-call intuition that makes agent bills surprising. At 10 steps the sum reaches 32,500 against a 6000-token transcript.
Trace the four iterations: the loop bills 1000, then 1500, then 2000, then 2500, summing to 7000, while context ends at 1000 + 4·500 = 3000. The point is the gap between those two numbers. The transcript grew to 3000 tokens, but the run was billed for 7000 — more than twice the final size — because every earlier token is paid for again on every later step. Option (b) is what you get by counting only the tokens each step adds, which is the intuition most people carry over from single-call pricing and the reason agent bills surprise teams. Option (c) mistakes the final context size for the amount billed. Extend the loop to 10 steps and the sum reaches 32,500 against a 6000-token transcript: the growth is quadratic, which is why trimming what you carry forward is the strongest cost lever in an agent loop.
AI Engineering/agents
You're building a research assistant that must pull together legal, financial, and technical analysis for one report, and you don't know ahead of time how many sub-questions each domain will need. Which multi-agent pattern directly addresses the problem of one generalist agent trying to hold all three domains' context and tools at once?#
Options
Show answer
The orchestrator-workers pattern fits: a lead agent decomposes the task into sub-tasks, delegates each to a worker agent scoped to one domain's tools and context, then synthesizes the workers' results into the final report. This suits tasks whose subtasks can't be predicted in advance, letting each worker hold a focused, uncluttered context. Loading every tool into one generalist agent causes tool-selection confusion and context overload; running parallel copies of a generalist doesn't decompose the task by domain; and chaining domains as sequential turns in one conversation is still a single agent with no real specialization.
The orchestrator-workers pattern fits exactly this shape: a central LLM dynamically breaks the task down, delegates focused sub-tasks to worker agents each scoped to one domain's tools and context, then synthesizes their results — a good fit whenever subtasks can't be predicted in advance and each worker benefits from a focused, uncluttered context (a). Loading every tool into one generalist agent (b) causes tool-selection confusion and context overload — the more tools a model holds, the harder it is to pick correctly. Three parallel copies of a generalist (c) never decomposes the task by domain, and averaging free-form report text isn't a meaningful synthesis operation. Chaining domains as sequential turns in one conversation (d) is still a single agent with no real specialization or context isolation.
AI Engineering/agents
You're productionizing an autonomous agent that can take many turns to complete a task. Which of the following are genuine guardrails against it running away — looping indefinitely, burning budget, or taking an unsafe action? Select all that apply.#
Options
Pick every one that applies.
Show answer
Genuine guardrails against a runaway agent are a hard cap on iterations or tool calls (and/or a token or dollar budget) with a forced stop, a human-in-the-loop checkpoint before irreversible or high-stakes actions, an overall wall-clock timeout independent of iteration count, and least-privilege scoping of the agent's tools and permissions so a runaway loop can only touch what it's allowed to. Running at temperature 0 is a trap: determinism only means the same input reliably produces the same output, not that the process converges — a deterministic 'not sufficient yet' judgment will loop forever without an external cap.
Genuine safeguards are a hard iteration/budget cap with a forced stop (a), a human checkpoint before consequential actions (b), an overall wall-clock timeout independent of iteration count — a slow-but-under-cap loop could still run forever in real time without one (c), and least-privilege tool/permission scoping, which bounds the blast radius even when a loop does run away (e). Temperature 0 (d) is the trap: determinism only means the same input reliably produces the same output, not that the process converges — a model whose sufficiency check deterministically says 'not yet' every time will deterministically loop forever without an external cap. Determinism and termination are different properties.
AI Engineering/agents
You split a task across a supervisor agent and several worker agents that pass results back and forth. Compared to a single well-scoped agent, which of these are genuine failure modes that multi-agent systems introduce? Select all that apply.#
Options
Pick every one that applies.
Show answer
Genuine multi-agent failure modes are coordination overhead — extra tokens and rounds spent on hand-off can outweigh any parallelization gain, especially on sequential work — error compounding, where a downstream agent trusts an upstream agent's wrong result without re-verifying it, and context pollution, where shared or forwarded history carries one agent's mistaken assumptions into another agent's context. Splitting a task across more agents does not guarantee higher accuracy — it can just as easily amplify errors — and multi-agent chains do not implicitly validate each other's output; assuming the next agent will catch a mistake is exactly how errors compound silently.
Real, documented multi-agent failure modes are coordination overhead — extra tokens and rounds spent on hand-off can outweigh any parallelization gain, especially on tasks that are fundamentally sequential rather than genuinely parallelizable (a); error compounding — a downstream agent trusts an upstream agent's wrong or hallucinated result without re-verifying it, so mistakes propagate and can amplify rather than cancel out (b); and context pollution — shared or forwarded history carries one agent's mistaken assumptions or stale state into another agent's context (c). (d) is false: more agents does not guarantee higher accuracy — it can just as easily amplify errors, and reliably improving quality requires explicit structure like verification steps, not headcount. (e) is false and dangerous: assuming 'the next agent will implicitly catch it' is precisely the assumption behind the error-compounding failure mode in (b) — an implicit downstream glance is not an actual validation step, so chaining agents with no explicit check is exactly how bad results silently propagate.
AI Engineering/agents
After a runaway-loop incident — an agent looped on a search tool overnight until it blew through its context window and ran up a large bill — you're asked to design the guardrails so it can't happen again. What would you put in place, and why does the model's own 'I'm not confident yet, let me check once more' judgment need a backstop rather than being trusted alone?#
Show answer
Layer several independent guardrails rather than relying on the model to self-regulate: a hard cap on iterations/tool calls per task; a token or dollar budget that forces a stop when exceeded; an overall wall-clock timeout independent of iteration count, since a slow loop could still run forever in real time without one; and a human-in-the-loop checkpoint before any irreversible or high-stakes action. When any cap is hit, the agent should return its best partial answer rather than erroring out or silently continuing. The model's own 'not confident yet, let me check once more' judgment can't be the only backstop because it's exactly the mechanism that failed here: if the model's internal sufficiency check never concludes 'yes, I have enough,' it will keep looping indefinitely by its own logic, no matter how reasonable that logic looked on the first few iterations. The guardrail has to be an external, deterministic circuit-breaker the agent cannot reason its way around — not another judgment call made by the same model that just got stuck.
The concrete guardrails — an iteration/tool-call cap, a token or dollar budget, a wall-clock timeout, and a human checkpoint before high-stakes actions — matter less individually than the underlying insight: the failure mode here is the model's own sufficiency judgment being wrong, so the fix cannot be 'ask the model to judge better.' It has to be an external, deterministic stop the agent's own reasoning cannot talk its way past, with a defined graceful-degradation path (return the best partial answer) once a cap is hit.
AI Engineering/agents
Name two common multi-agent orchestration patterns and the kind of task each one fits.#
Show answer
Orchestrator-workers: a lead/supervisor agent decomposes a task into sub-tasks it couldn't fully predict in advance, delegates each to a worker agent scoped to focused context and tools, then synthesizes the workers' results — fits open-ended tasks like multi-domain research or multi-file code changes, where the shape of the work depends on what earlier steps discover. Sequential handoff (a pipeline of specialist agents): each agent completes its stage and passes a structured result to the next, with no shared free-for-all context — fits tasks with a genuinely fixed stage order (e.g. draft → fact-check → format), where each stage's specialist only needs its input, not the others' full history. Both trade single-agent simplicity for parallelism or specialization, at the cost of coordination overhead and the risk that one agent's error or stale context propagates to the next.
Orchestrator-workers suits genuinely unpredictable decomposition; sequential handoff suits a fixed stage order where each specialist only needs a narrow slice of context. Picking the wrong pattern — e.g. a shared free-for-all context for what's really a fixed pipeline — is what invites coordination overhead and error propagation for no benefit.
AI Engineering/agents
An orchestrator agent coordinates two specialist worker agents to answer a multi-domain research question ('compare the legal and financial risk of this deal'). Order the steps of one orchestration pass.#
Put these in order
Show answer
An orchestrator-workers pass with a supervisor and specialist workers runs in this order:
- Orchestrator receives the task and decomposes it into domain-scoped sub-tasks (legal risk, financial risk)
- Orchestrator delegates each sub-task to the worker agent scoped to that domain's context and tools
- Each worker agent runs its own plan/act/observe loop independently and returns a structured result
- Orchestrator collects the workers' results and checks them for consistency and completeness
- Orchestrator synthesizes the results into a single combined answer for the user
The orchestrator-workers pattern only pays off if decomposition happens first (a) — sub-tasks are unpredictable until the specific task is decomposed — so workers are scoped narrowly (b) rather than loaded with the whole problem. Each worker then runs its own independent loop (c), since folding its execution into the orchestrator's own context would recreate the tool/context overload the pattern exists to avoid. The orchestrator checks the returned results before using them (d) — trusting worker output without verification is exactly how error compounding happens across agents — and only then synthesizes a final answer (e); synthesizing before checking risks baking an unverified worker error into the response the user sees.
AI Engineering/agents/agent-loops
The following Python snippet implements one iteration of an OpenAI function-calling agent loop. There is exactly one bug that will cause the agent loop to silently malfunction (wrong role/message structure fed back to the model). Identify the buggy line number.#
import json, openai
def run_agent_step(messages, tools, tool_registry):
response = openai.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto",
)
msg = response.choices[0].message
messages.append(msg)
if msg.tool_calls:
for tc in msg.tool_calls:
fn_name = tc.function.name
fn_args = json.loads(tc.function.arguments)
result = tool_registry[fn_name](**fn_args)
messages.append({"role": "assistant", "content": str(result)})
return messagesShow answer
The bug is on line 17.
The bug is on line 17. The code appends the tool result to messages as a dict with role assistant, but tool/function call results must be appended with role tool and must reference the tool_call_id from the assistant's message (e.g., {"role": "tool", "tool_call_id": tc.id, "content": str(result)}). Appending the result as an assistant message (a) loses the tool_call_id linkage and (b) causes the model to treat the observation as its own prior utterance rather than an external tool response, breaking the agent loop. All other lines are structurally correct for a minimal function-calling agent loop.
AI Engineering/agents
Your team evaluates single LLM calls with a golden set: fixed inputs, an expected output, and roughly deterministic scoring. Even with an equivalent golden set of tasks for a multi-step agent, why does that same approach fail to fully evaluate it?#
Options
Show answer
An agent's trajectory — which tools it calls, in what order, with what intermediate reasoning — can differ run to run and still land on a correct final answer, so scoring only the final output can't tell a sound path from a lucky or risky one, and a single bad step early on can silently corrupt every step after it. Each step is its own LLM sample, so stochasticity compounds, and several different valid tool-call sequences can reach the same correct answer, leaving no single 'expected trajectory' to grade against. This is why agent evals score the trajectory itself alongside outcome correctness. Agents are not guaranteed more accurate than single calls, and they do produce a final answer worth grading in addition to the trajectory.
Each step in an agent's run is its own LLM sample, so stochasticity compounds across many steps: the same task can produce qualitatively different trajectories on different runs, and a wrong or risky choice early on — misreading a tool result, calling an unnecessary or destructive tool — can cascade into failures several steps later even when the final text happens to look correct. Conversely, an agent can reach the right final answer via an inefficient or unsafe path that a final-answer-only score would never catch, and several different tool-call sequences can all be equally valid routes to the same correct answer, so there's no single 'expected trajectory' to grade against (b). This is why agent evals add trajectory-level signals — which tools were called, in what order, whether each step was sound — on top of outcome correctness. Agents are not guaranteed more accurate than single calls (c): more steps means more chances to compound errors, not fewer. They do produce a final answer to grade, in addition to the trajectory (d is false).
AI Engineering/agents
Why is evaluating a multi-step agent fundamentally harder than evaluating a single LLM call, even when you have a good golden dataset for both? Name the specific problems, not just 'agents are more complex.'#
Show answer
Three compounding problems, not just general complexity. First, non-determinism compounds across steps: every tool call and re-plan is its own LLM sample, so the same task can take a different path on different runs, and a small divergence early on can snowball into a completely different trajectory by the end — a single pass/fail run tells you little about the distribution of outcomes. Second, there's no single ground-truth trajectory: several different sequences of tool calls can all reach the same correct final answer, so scoring against one 'expected path' penalizes valid alternatives, while scoring only the final answer misses whether the path taken was efficient, safe, or just lucky. Third, failures are spread across many components and can be silent: a bad intermediate step, like a misread tool result or an unnecessary call, can still end in a textually correct final answer, hiding a real problem a final-answer-only eval would never catch. The practical fix is to evaluate the trajectory itself — which tools were called, in what order, whether intermediate steps were sound — in addition to final-answer correctness, and to run each task multiple times rather than once given the non-determinism.
Agent evaluation is harder for three specific, named reasons, not vague complexity: trajectory non-determinism (each step is its own sample, so runs diverge and small early differences cascade), no single ground-truth trajectory (multiple valid tool-call sequences can reach the same correct answer, so a fixed 'expected path' over-penalizes), and silent compounding failures (a bad intermediate step can still yield a correct-looking final answer, hiding the real defect from an outcome-only score). The fix is scoring the trajectory alongside the outcome, and sampling multiple runs per task rather than treating one pass/fail run as representative.
AI Engineering/agents/agent-loops
Design the agent loop behind a support assistant that answers billing questions. It can read invoices, read the customer's plan, and issue refunds up to a limit. Runs take anywhere from 2 to 40 iterations. Cover how the loop terminates, what happens when a tool fails, how context is kept under the window, how refunds are controlled, and how you would debug a bad run a week later. State your assumptions.#
Show answer
Assume a few thousand runs a day, a refund ceiling of $200, and 30-day trace retention. Most tickets follow a handful of shapes, so I would route: a classifier sends the common ones down fixed workflows and only the tail reaches the agent, which cuts cost and shrinks the surface where things can go wrong.
The loop terminates on four conditions, not one: the model returns a final answer that passes a goal check; a cumulative token budget for the run is exhausted; a step cap fires as a backstop; or a repeated-call detector sees the same (tool, arguments) hash twice with nothing new in context. Budget is the primary control because steps are a poor proxy for cost — each iteration re-sends the transcript, so late steps cost far more than early ones. On any stop without an answer the agent hands the ticket to a human with its partial findings attached, rather than replying with something it is not sure of.
Tool failures go back into the context as tool results flagged as errors, so the model can adapt — try a different lookup, or tell the user. Retry policy is per-tool, not global: reads retry with exponential backoff, and the refund call never retries blindly, because a 5xx there is ambiguous rather than failed. Refunds carry an idempotency key so a duplicate collapses server-side.
For a 40-iteration run I pin the system prompt, tool schemas and goal, summarise older turns into a running recap once the transcript passes a threshold, clear stale tool results while keeping the calls that produced them, and keep large invoice payloads in storage behind a reference the agent re-reads on demand.
Refunds are gated in code. The loop intercepts the call before execution, verifies the amount against the invoice server-side, and requires human approval above a threshold — the model's authority is whatever the loop grants it, and the system prompt is a hint, not a control. Invoice text is untrusted: it reaches the context as data, and instructions inside it have no privilege, which is exactly why enforcement cannot live in the prompt.
Every run writes a trace keyed by run id and ticket id, one span per iteration, capturing the rendered prompt, the tool calls and arguments, results, token counts, and the stop reason. A week later I can open the ticket, find the run, and see which iteration went wrong and what the model was looking at when it did.
The main tradeoff is autonomy against friction: a lower approval threshold means fewer bad refunds and more human load. I would start conservative, measure the approval queue, and raise the threshold only against evidence.
This exercise separates people who have run an agent in production from people who have read about them. The tells are consistent. A weak answer treats max_steps as termination, wraps every tool in one retry, plans to 'use a bigger context window', and puts the refund limit in the system prompt. A strong answer knows that a step cap does not bound cost, that retry policy is a property of the tool rather than of the loop, that trimming has to pin the instructions it must never drop, and above all that a prompt instruction is not an authorization boundary — the loop executes tools, so the loop is the only place a refund limit can be enforced. The prompt-injection probe is the sharpest discriminator: any design where the model's instructions are the sole control fails it, because the invoice is attacker-influenced text arriving in the same context. The debuggability criterion is what makes the whole thing operable — without per-iteration traces tied to a run id, nobody can answer 'why did it do that' a week later, and every incident becomes a guess.
Related interview questions
Job market
See ai-engineering salaries and hiring demand from live job postings.
The other 182 questions
This page shows 25 and marks what you pick. That's as far as a page can go. A free account opens the other 182 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