InterviewTreedInterviewTreed

InterviewTreed Question Bank

AI Agents & Tool Use Interview Questions and Answers

Explore AI agents, tool calling, agent workflows, planning, memory, orchestration, multi-agent systems, and reliable production agent architectures.

Total Questions

100

Beginner

15

Intermediate

40

Advanced

45

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Agent fundamentals

What is an AI agent?

Define an AI agent and explain how it differs from a basic LLM chatbot.

Answer

An AI agent is a software system that uses a model to interpret a goal, decide on actions, and interact with tools or external systems to make progress. It may observe results and repeat the process until it reaches a stopping condition.

A basic chatbot usually returns a response directly. An agent can use a search API, query a database, call a business service, or delegate a bounded task before composing its response. The amount of autonomy depends on the design and permissions granted.

Example

A support agent can classify a request, look up an order through an approved API, check the result, and draft a response. A refund should still require the configured authorization or confirmation step.

Key Points

  • An agent combines model reasoning with application logic and tools.
  • Tool access does not automatically make a system safe or autonomous.
  • Use explicit goals, permissions, and stop conditions.
Q2Agent fundamentals

How does an AI agent differ from a chatbot?

Compare direct response generation with action-oriented workflows.

Answer

A chatbot commonly maps a user message to a response, possibly using conversation history or retrieval. An agent can select and invoke tools, observe tool results, and make subsequent decisions within a controlled loop.

The distinction is architectural rather than absolute: chatbots can use tools, and agents can be designed as simple single-step workflows. The important questions are whether the system selects actions, uses feedback, and operates within defined limits.

Key Points

  • Chatbot and agent capabilities can overlap.
  • Agents often include tool selection and an execution loop.
  • Evaluate behavior and controls, not just the product label.
Q3Agent fundamentals

What are the main components of an AI agent?

Identify the model, instructions, tools, state, orchestration, and safeguards.

Answer

A typical agent includes a model, system instructions, a set of tool definitions, an orchestrator, state or context, and policies that validate actions. The orchestrator sends model requests, validates tool calls, executes permitted operations, returns results, and decides whether to continue.

Production systems also need observability, timeouts, retries, error handling, identity and authorization, and a way to stop or hand off work.

Key Points

  • The model proposes actions; application code executes them.
  • Tools need schemas and permission checks.
  • Logging, limits, and recovery are production requirements.
Q4Tool calling

What is tool calling in an LLM application?

Explain how a model requests an external function and receives its result.

Answer

Tool calling lets a model emit a structured request naming a tool and supplying arguments that match a declared schema. The application validates the request, runs the function if allowed, and sends the result back to the model so it can continue or answer.

The model normally does not execute the code itself. The application owns execution, validation, authorization, and error handling.

Syntax

{
  "name": "get_order_status",
  "arguments": { "orderId": "ORD-1042" }
}

Example

The application validates that orderId is a string, checks whether the current user may access that order, calls the order service, and returns a minimized status result.

Key Points

  • Tool calls are structured requests.
  • Validate arguments even when the model provides a schema-shaped payload.
  • Authorize every operation before execution.
Q5Tool calling

What is the difference between function calling and tool calling?

Clarify common API terminology for model-invoked application functions.

Answer

Function calling is often used for model requests to invoke developer-defined functions. Tool calling is a broader term that can include functions, retrieval, code execution, or other integrations, depending on the provider and framework.

Exact terminology and supported tool types vary by model API. In all cases, application code should treat the output as an untrusted request that must be validated and authorized.

Key Points

  • Terminology varies by provider.
  • Both patterns connect model decisions to application capabilities.
  • The application remains responsible for executing and securing tools.
Q6Tool calling

Why should a tool have a clear schema?

Explain how typed arguments reduce ambiguity and validation errors.

Answer

A tool schema describes its name, purpose, input fields, types, required properties, and allowed values. It helps the model construct usable requests and gives the application a contract to validate before execution.

A schema is not a security boundary by itself. The server must still enforce business rules, permissions, value limits, and any constraints that cannot be expressed in the schema.

Syntax

{
  "name": "search_products",
  "description": "Search products by keyword",
  "parameters": {
    "type": "object",
    "properties": {
      "query": { "type": "string" },
      "limit": { "type": "integer" }
    },
    "required": ["query"]
  }
}

Key Points

  • Use descriptive names and field descriptions.
  • Validate types, ranges, and required values server-side.
  • Keep tool inputs as narrow as possible.
Q7Agent fundamentals

What is an agent execution loop?

Describe the repeated model, tool execution, and observation cycle.

Answer

A common loop sends the current goal and context to the model, receives either a final answer or a tool request, validates and executes an approved tool, appends the observation, and calls the model again. It stops when the task is complete, a limit is reached, or a failure requires a handoff.

A robust loop has maximum iterations, elapsed-time and token budgets, per-tool timeouts, cancellation, and clear handling for invalid tool requests.

Syntax

while (!done && steps < maxSteps) {
  const decision = await model.next(context);
  if (decision.type === "final") {
    done = true;
  } else {
    const result = await executeValidatedTool(decision.call);
    context = addObservation(context, result);
  }
}

Key Points

  • Every iteration should have a defined state transition.
  • Set limits to prevent infinite loops and runaway costs.
  • Treat tool results as observations, not trusted instructions.
Q8Agent fundamentals

When should you avoid using an AI agent?

Choose simpler workflows when tasks are predictable or high-risk.

Answer

Avoid an agent when a deterministic function, ordinary workflow, or direct model call can solve the problem more reliably and cheaply. Agents add latency, cost, non-determinism, and new failure modes because they choose actions at runtime.

For irreversible or regulated operations, prefer explicit workflow steps, narrow permissions, human approval, and deterministic validation rather than giving a model broad authority.

Key Points

  • Use the simplest architecture that meets the requirement.
  • Deterministic workflows are easier to test and audit.
  • Keep high-impact actions behind stronger controls.
Q9Prompt design

What should an agent system prompt contain?

Cover role, goal, tool-use policy, boundaries, and stopping rules.

Answer

A system prompt should state the agent's role, objective, available capabilities, when tools may be used, expected output format, uncertainty handling, and conditions for stopping or asking for clarification. It should clearly forbid actions outside the agent's scope.

Do not rely on the prompt as the only safeguard. Enforce permissions, data access, transaction limits, and approvals in application code.

Example

A read-only order assistant may be instructed to use the order lookup tool for current status, never invent a status, and ask for clarification when an order identifier is missing. The backend must independently enforce customer ownership.

Key Points

  • Be specific about allowed and disallowed actions.
  • Specify when to ask, stop, or escalate.
  • Enforce security outside the prompt.
Q10Tool calling

Why are structured outputs useful for agents?

Explain machine-readable responses and schema validation.

Answer

Structured outputs constrain a model response to a machine-readable shape, such as a JSON object with known fields. This is useful for routing, extracting parameters, producing typed decisions, and integrating with application code.

The application should still validate the result and handle refusals, incomplete outputs, schema mismatches, and semantic errors. Valid JSON does not guarantee a correct or safe decision.

Syntax

type AgentDecision =
  | { action: "search"; query: string }
  | { action: "answer"; text: string };

Key Points

  • Structured output reduces parsing ambiguity.
  • Validate both schema and business meaning.
  • Handle malformed or incomplete model output.
Q51Agent fundamentals

What is the difference between an agent and a deterministic workflow?

A deterministic workflow follows predefined transitions and rules, while an agent can use a model to choose among permitted…

Answer

A deterministic workflow follows predefined transitions and rules, while an agent can use a model to choose among permitted actions based on the current goal and observations. Many robust systems combine both: the workflow controls important boundaries and the model handles flexible interpretation or planning.

Syntax

User request → deterministic policy/workflow → model decision for flexible step → validated action → result

Example

Example: a support workflow always checks identity before an agent interprets the issue and selects an approved read-only tool.

Key Points

  • Use deterministic rules for hard constraints.
  • Use agent flexibility where inputs vary.
  • Combine both when reliability matters.
Q52Agent fundamentals

What is an agent's environment?

The environment is the system the agent observes and affects through tools, such as APIs, databases, files, browsers, or…

Answer

The environment is the system the agent observes and affects through tools, such as APIs, databases, files, browsers, or business services. The agent's observations may be incomplete or stale, so it should verify important state before acting.

Syntax

observe → decide → act through tool → observe updated environment

Example

Example: a booking agent reads current seat availability, requests a reservation, then checks the reservation result.

Key Points

  • Tools define how the agent interacts with its environment.
  • Observations can be incomplete or stale.
  • Verify important state changes.
Q53Agent fundamentals

What is an observation in an agent loop?

An observation is the result returned after an action, such as search results, a database response, or an error. The…

Answer

An observation is the result returned after an action, such as search results, a database response, or an error. The orchestrator adds this result to the task state so the next decision can use evidence about what actually happened.

Syntax

action → tool result/observation → update state → next decision

Example

Example: after a search tool returns zero matches, the agent can refine the query rather than claim it found a result.

Key Points

  • Record tool outcomes in state.
  • Distinguish empty results from failures.
  • Do not assume an action succeeded without evidence.
Q54Tool calling

What makes a good tool description?

A good description states the tool's purpose, when to use it, required inputs, what it returns, and important limitations.…

Answer

A good description states the tool's purpose, when to use it, required inputs, what it returns, and important limitations. Clear, non-overlapping descriptions help the model select the correct capability and reduce invalid calls.

Syntax

name + purpose + when-to-use + input contract + constraints + output contract

Example

Example: describe `get_order_status` as a read-only lookup for an order the authenticated customer is allowed to access.

Key Points

  • Use specific names and descriptions.
  • State constraints and side effects.
  • Avoid overlapping tool responsibilities.
Q60Workflows and orchestration

What is an agent workflow?

An agent workflow defines how model decisions, tools, state transitions, and control rules work together to complete a task.…

Answer

An agent workflow defines how model decisions, tools, state transitions, and control rules work together to complete a task. It can include fixed steps, conditional branches, retries, approval gates, and agent-selected actions.

Syntax

START → classify → retrieve context → choose permitted action → validate → respond

Example

Example: a document assistant always checks file access before using an agent to summarize the file.

Key Points

  • Make transitions explicit.
  • Keep hard policy checks deterministic.
  • Represent failures and approvals as states.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q11Tool calling

How does an agent choose which tool to call?

Explain tool descriptions, model context, and orchestration policies.

Answer

The model uses the user goal, conversation context, and tool descriptions and schemas to propose a suitable tool call. The orchestrator can constrain the available tools, require a particular workflow, or reject a call that violates policy.

Good tool descriptions explain when to use a tool, what it returns, and what it must not be used for. Overlapping tools with vague descriptions make selection less reliable.

Key Points

  • Keep tool names and descriptions distinct.
  • Expose only tools relevant to the current task.
  • Validate proposed actions before execution.
Q12Tool calling

When can an agent call tools in parallel?

Compare independent read operations with dependent or mutating operations.

Answer

Parallel calls are useful when operations are independent, such as retrieving weather and a public calendar. They reduce total latency because the calls can run concurrently.

Do not parallelize calls whose inputs depend on earlier results or whose concurrent execution could cause conflicting side effects. Consider rate limits, cancellation, partial failures, and per-tool permissions.

Syntax

const [profile, orders] = await Promise.all([
  getProfile(userId),
  getRecentOrders(userId),
]);

Example

A travel assistant may fetch flight options and hotel options concurrently. It should not book both before the user confirms the itinerary and the system validates availability and price.

Key Points

  • Parallelize only independent work.
  • Use bounded concurrency and timeouts.
  • Treat partial failure explicitly.
Q13Reliability

How should an agent handle tool errors?

Discuss typed errors, retries, fallbacks, and user-facing messages.

Answer

Return a structured error that distinguishes validation failure, authorization denial, rate limiting, timeout, unavailable dependency, and unexpected failure. The orchestrator can retry transient errors, ask for missing information, choose an approved fallback, or stop and explain the limitation.

Retries should be bounded and use backoff. A mutation should not be blindly retried unless the operation is idempotent or protected by an idempotency key.

Syntax

{
  "ok": false,
  "code": "RATE_LIMITED",
  "retryable": true,
  "message": "Please retry shortly."
}

Key Points

  • Classify errors rather than returning raw stack traces.
  • Retry only transient failures and cap attempts.
  • Never expose secrets or internal diagnostics to users.
Q14Reliability

Why do agents need timeouts and cancellation?

Prevent stuck tools and long-running agent loops.

Answer

A tool may hang because of a network issue or a slow downstream service. Timeouts bound how long the agent waits, while cancellation lets the system stop work when a user disconnects, a deadline passes, or the task is no longer needed.

Cancellation should propagate to supported downstream operations. A timeout does not prove that a remote side effect did not happen, so mutation workflows need status reconciliation or idempotency.

Key Points

  • Set per-tool and end-to-end deadlines.
  • Propagate cancellation where possible.
  • Reconcile uncertain mutation outcomes.
Q15Reliability

What is idempotency, and why does it matter for agent tools?

Explain safe retries when an operation may have succeeded despite a timeout.

Answer

An operation is idempotent when repeating the same request has the same intended effect as performing it once. This matters because a model or orchestrator may retry after a timeout even though the remote system completed the original request.

For operations such as creating a payment or booking, use a stable idempotency key, persist the operation state, and check the result before issuing a new mutation.

Syntax

await paymentClient.createPayment({
  amount,
  idempotencyKey: requestId,
});

Key Points

  • Retries can duplicate side effects.
  • Use stable request identifiers for mutations.
  • Persist and reconcile operation status.
Q16Reliability

How should an application validate tool output?

Validate shape, size, semantics, and provenance before returning data to the model.

Answer

Validate the returned payload against a schema, enforce size limits, normalize expected values, and distinguish empty results from errors. Check that identifiers and values are consistent with the requested operation.

Tool output may contain untrusted external text. Treat it as data rather than instructions, redact sensitive fields, and avoid sending unnecessary records to the model.

Syntax

const parsed = OrderStatusSchema.safeParse(raw);
if (!parsed.success) {
  throw new Error("Invalid order-service response");
}
return minimizeOrderData(parsed.data);

Key Points

  • Validate data from dependencies, not only model input.
  • Limit output size and remove unnecessary sensitive fields.
  • Keep external content separate from trusted instructions.
Q17State and memory

What is the difference between agent state and memory?

Distinguish current workflow state from information retained across tasks.

Answer

State represents the current execution context, such as the goal, completed steps, pending approvals, and tool results. Memory usually means information retained for later turns or sessions, such as user preferences or summaries.

State should be explicit and recoverable for reliable workflows. Persistent memory needs retention rules, access controls, correction and deletion mechanisms, and care to avoid storing sensitive data without a valid reason.

Key Points

  • State supports the current run; memory can persist across runs.
  • Store only useful information with an appropriate lifetime.
  • Protect and govern persistent memory.
Q18State and memory

How can an agent manage short-term memory?

Use conversation context, summaries, and explicit workflow state.

Answer

Short-term memory can include recent messages, a compact summary of earlier conversation, relevant tool observations, and a structured task state. When context grows, summarize what matters and preserve decisions, constraints, unresolved questions, and source references.

Do not blindly truncate the oldest messages: an early user constraint may still be important. Store durable workflow facts outside the prompt when they must survive retries or process restarts.

Key Points

  • Keep context relevant to the current objective.
  • Summaries should preserve constraints and unresolved work.
  • Persist critical workflow state outside model context.
Q19Safety and control

When should an agent request human approval?

Identify high-impact, irreversible, costly, or sensitive actions.

Answer

Human approval is appropriate before consequential actions such as sending external messages, issuing refunds, making purchases, changing access, deleting data, or committing a financial transaction. Approval can also be required when confidence is low or policy demands a second reviewer.

The approval should summarize the exact action, target, amount or scope, and relevant consequences. The server should revalidate permissions and state after approval because conditions may have changed.

Example

The agent drafts a refund request with order ID and amount. A user with refund permission approves it, and the backend checks the order and limit again before issuing the refund.

Key Points

  • Use approval gates for consequential actions.
  • Show the user exactly what will happen.
  • Revalidate authorization and current state after approval.
Q20Reliability

How should you define an agent's stopping condition?

Prevent endless loops and ensure tasks end in a useful state.

Answer

Stop when the task is completed, the model returns a valid final response, a required approval is pending, an unrecoverable error occurs, or a resource limit is reached. A stop condition should also cover repeated identical tool calls and lack of progress.

Return a clear status such as completed, needs-input, awaiting-approval, failed, or timed-out. Do not claim success when a required tool failed or the result was not verified.

Key Points

  • Define terminal states explicitly.
  • Limit iterations, time, and cost.
  • Report incomplete work honestly.
Q21Planning and reasoning

How does planning improve agent performance?

Explain breaking a goal into steps and checking dependencies.

Answer

Planning decomposes a goal into smaller actions, identifies prerequisites, and establishes an order of operations. The agent can then execute one step, inspect the result, and revise the plan when the environment differs from expectations.

Plans should remain proportional to task complexity. Long plans can become stale, so important steps should be checked against actual tool results rather than assumed to have succeeded.

Key Points

  • Break complex goals into verifiable steps.
  • Check dependencies and results.
  • Revise plans when observations change.
Q22Planning and reasoning

What is the ReAct pattern?

Describe interleaving reasoning-oriented decisions, actions, and observations.

Answer

ReAct is a pattern that interleaves a model's reasoning-oriented step with an action, then uses the observation from that action to decide what to do next. In an application, the useful operational idea is the feedback loop: decide, call an approved tool, inspect its result, and continue.

Implementations should not expose private internal reasoning. Log concise decisions, tool inputs and outputs subject to redaction, and the outcome needed for debugging and audit.

Key Points

  • Actions are grounded by tool observations.
  • Use concise decision traces rather than exposing private reasoning.
  • Bound the loop and validate each action.
Q23Planning and reasoning

What is the plan-and-execute agent pattern?

Compare a separate planning stage with step-by-step reactive execution.

Answer

A plan-and-execute design first creates a sequence of tasks, then an executor performs them and checks results. It can be useful for long tasks with clear dependencies, while a reactive loop can be simpler when the next action depends heavily on new observations.

Plans must be checked for feasibility, permissions, and dependencies. The executor should not blindly follow a stale plan when results or user requirements change.

Key Points

  • Planning provides a high-level structure.
  • Execution validates each step against reality.
  • Replan when assumptions fail.
Q24Multi-agent systems

When would you use a multi-agent architecture?

Weigh specialized agents against coordination overhead.

Answer

Multiple agents can help when tasks are separable and benefit from different tools, context, or specialized instructions. A coordinator may assign research, analysis, and review to separate workers and combine their results.

Multi-agent systems add communication overhead, latency, cost, inconsistent assumptions, and more complex security boundaries. Start with one agent unless measurable benefits justify the extra architecture.

Key Points

  • Use multiple agents for genuinely separable work.
  • Define each agent's scope and tool permissions.
  • Compare quality and cost with a single-agent baseline.
Q25Multi-agent systems

What is an agent handoff?

Explain transferring a task with context to another agent or human.

Answer

A handoff transfers responsibility for a task to another agent, service, or human. A useful handoff includes the objective, relevant findings, completed steps, outstanding questions, constraints, and the reason for escalation.

Avoid sending the entire conversation when a concise, structured summary is sufficient. Validate the receiving agent's permissions independently; a handoff should not silently grant new authority.

Key Points

  • Include task state and unresolved work.
  • Define ownership after the handoff.
  • Recheck permissions at the receiving boundary.
Q26Evaluation and observability

What should you log to debug an agent?

Capture trace IDs, tool calls, timing, outcomes, and safe diagnostic metadata.

Answer

Useful telemetry includes a trace or request ID, model and prompt version, tool name, validated arguments or redacted summaries, execution duration, retry count, outcome, token usage, and final task status. This makes it possible to locate slow or failed steps.

Logs should avoid secrets, access tokens, full sensitive records, and unnecessary personal data. Apply access controls, retention limits, and redaction before telemetry is stored.

Key Points

  • Trace a complete run across model and tool calls.
  • Measure latency, errors, retries, and cost.
  • Redact sensitive data and control log access.
Q27Evaluation and observability

How do you evaluate an AI agent?

Measure task success, tool correctness, safety, latency, and cost.

Answer

Build a representative evaluation set containing normal requests, ambiguous requests, tool failures, adversarial inputs, and edge cases. Score task completion, correctness of tool selection and arguments, final answer quality, policy compliance, latency, and cost.

Use deterministic assertions where possible and human review for subjective outcomes. Test changes against a fixed regression set and examine failures by category instead of relying on a single aggregate score.

Key Points

  • Evaluate the full workflow, not just final text.
  • Include failure and adversarial cases.
  • Track quality, safety, latency, and cost together.
Q28Performance and cost

How can you reduce an agent's cost?

Reduce unnecessary model calls, tool payloads, and repeated work.

Answer

Use a smaller or cheaper model for routine routing, limit the number of iterations, summarize context, retrieve only relevant data, and avoid repeating expensive tool calls. Cache safe, stable results when freshness and user isolation permit it.

Track cost per successful task, not just cost per model call. An apparently cheaper model can increase total cost if it causes more retries or incorrect actions.

Key Points

  • Measure cost per completed task.
  • Reduce redundant calls and oversized context.
  • Cache only when freshness and privacy requirements allow.
Q29Performance and cost

How do you reduce agent latency?

Use parallel independent calls, streaming, bounded context, and faster dependencies.

Answer

Identify whether latency comes from model generation, serial tool calls, network time, or slow dependencies. Parallelize independent reads, stream safe partial responses when appropriate, reduce unnecessary steps, and set efficient timeouts.

Do not trade away validation or authorization to make the system faster. Measure end-to-end percentiles and failure rates because aggressive timeouts can increase retries and worsen overall performance.

Key Points

  • Profile the whole workflow.
  • Parallelize only independent operations.
  • Optimize p95/p99 latency without weakening controls.
Q30Reliability

An agent repeats the same tool call. How would you debug it?

Detect repeated actions, unhelpful observations, and missing progress signals.

Answer

Inspect the trace to see whether the tool result is empty, ambiguous, ignored, or failing to update the context. Check whether the prompt describes how to interpret the result and whether the orchestrator records the call as completed.

Add repeated-call detection, a maximum step count, and explicit progress or terminal-state checks. If a tool repeatedly fails, return a bounded error or escalate rather than continuing indefinitely.

Key Points

  • Inspect model and tool traces.
  • Ensure observations are appended and interpreted.
  • Stop repeated calls when no progress is made.
Q55Tool calling

What is the difference between a tool call and a tool result?

A tool call is the model's structured proposal to invoke a capability with arguments. A tool result is the output produced…

Answer

A tool call is the model's structured proposal to invoke a capability with arguments. A tool result is the output produced by the application after validating and executing that request. Keeping them distinct makes it easier to audit proposed actions versus actual side effects.

Syntax

model tool_call → validation/authorization → execution → tool_result

Example

Example: a model proposes a refund, but the backend rejects it because the order is outside the refund window.

Key Points

  • A proposal is not proof of execution.
  • Record the actual tool outcome.
  • Validate and authorize before running tools.
Q56Tool calling

How should an agent handle missing tool arguments?

The orchestrator should validate required arguments before execution. If a required value is missing or ambiguous, the agent…

Answer

The orchestrator should validate required arguments before execution. If a required value is missing or ambiguous, the agent should ask a focused clarification question or use an approved read-only tool to resolve it; it should not invent identifiers or silently guess high-impact values.

Syntax

tool proposal → schema validation → missing/ambiguous field → clarify or safe lookup

Example

Example: ask which order the user means if multiple orders match the same description.

Key Points

  • Validate required fields.
  • Clarify ambiguity before consequential actions.
  • Never fabricate IDs or transaction details.
Q57Tool calling

How do you prevent an agent from selecting a dangerous tool unnecessarily?

Expose only tools relevant to the current task, separate read-only tools from mutation tools, and apply server-side policy…

Answer

Expose only tools relevant to the current task, separate read-only tools from mutation tools, and apply server-side policy checks to every proposed call. Tool availability can be restricted by user role, task stage, or approval state.

Syntax

task classification → permitted tool set → model proposal → policy validation → execution

Example

Example: a read-only support conversation does not receive the refund-execution tool until eligibility and approval conditions are met.

Key Points

  • Limit the available capability set.
  • Separate reads from writes.
  • Enforce policy outside the model.
Q58Tool calling

How should tool arguments be validated in TypeScript?

Validate model-proposed arguments at runtime with a schema library or equivalent checks, because TypeScript types disappear…

Answer

Validate model-proposed arguments at runtime with a schema library or equivalent checks, because TypeScript types disappear at runtime. Apply semantic rules as well, such as allowed ranges, resource ownership, and limits on free-text length.

Syntax

unknown JSON → runtime schema parse → business validation → authorized execution

Example

TypeScript example: const parsed = CreateTicketSchema.safeParse(args); if (!parsed.success) throw new Error("Invalid tool arguments"); return ticketService.create(parsed.data);

Key Points

  • Use runtime validation, not TypeScript types alone.
  • Validate business rules and ownership.
  • Reject unknown or excessive input.
Q61Workflows and orchestration

When should you use a state machine for an agent?

A state machine is useful when a task has important stages and legal transitions, such as draft, awaiting approval,…

Answer

A state machine is useful when a task has important stages and legal transitions, such as draft, awaiting approval, executing, completed, or failed. It prevents the model from skipping required checks and makes recovery and audit easier.

Syntax

DRAFT → AWAITING_APPROVAL → EXECUTING → COMPLETED; invalid transitions are rejected

Example

Example: a purchase agent cannot transition directly from a product search to purchase execution without a confirmed quote.

Key Points

  • Define valid states and transitions.
  • Persist state for long-running tasks.
  • Reject illegal transitions in application code.
Q62Workflows and orchestration

How should a long-running agent task be persisted?

Persist the task ID, current state, plan or pending step, completed actions, approvals, tool results needed for recovery,…

Answer

Persist the task ID, current state, plan or pending step, completed actions, approvals, tool results needed for recovery, and timestamps in durable storage. On restart, reload the state and reconcile uncertain side effects before continuing.

Syntax

request → durable task record → step execution/checkpoint → resume from last safe state

Example

Example: a research job can resume after a worker restart without repeating completed downloads unnecessarily.

Key Points

  • Persist checkpoints outside model context.
  • Use idempotent steps where possible.
  • Reconcile uncertain mutations before retrying.
Q65Planning and reasoning

How should an agent break a complex goal into subtasks?

Decompose the goal into small, observable tasks with clear completion criteria and dependencies. Each subtask should have a…

Answer

Decompose the goal into small, observable tasks with clear completion criteria and dependencies. Each subtask should have a bounded scope, authorized tools, and a way to verify its result before downstream work relies on it.

Syntax

goal → subtasks/dependencies → execute one step → verify → update plan

Example

Example: a travel planner first gathers dates and constraints, then searches options, compares costs, and asks for approval before booking.

Key Points

  • Define success criteria per subtask.
  • Respect dependencies and user constraints.
  • Verify results before moving forward.
Q66Planning and reasoning

What is plan revision, and when is it needed?

Plan revision updates the next steps when observations invalidate an assumption, a tool fails, or the user changes the goal.…

Answer

Plan revision updates the next steps when observations invalidate an assumption, a tool fails, or the user changes the goal. A robust agent should revise only the affected parts where possible and retain constraints that remain valid.

Syntax

initial plan → observation contradicts assumption → revise affected steps → continue

Example

Example: if a hotel becomes unavailable, the agent searches alternatives while preserving the user's dates and budget.

Key Points

  • Use observations to revise plans.
  • Preserve still-valid constraints.
  • Avoid restarting all work unnecessarily.
Q69State and memory

What should an agent store in persistent memory?

Store only information that improves future tasks and has a legitimate purpose, such as explicit preferences or stable…

Answer

Store only information that improves future tasks and has a legitimate purpose, such as explicit preferences or stable project context. Avoid unnecessary sensitive information, define retention and correction rules, and keep workflow state separate from long-term memory.

Syntax

candidate fact → usefulness/privacy check → consent/policy check → scoped memory with TTL

Example

Example: store a user's preferred report format rather than full private documents from prior sessions.

Key Points

  • Minimize stored information.
  • Define retention and deletion behavior.
  • Separate preferences from task execution state.
Q70State and memory

How can memory become stale or incorrect?

Memory can become stale when preferences change, facts expire, or an earlier model inference was wrong. Store provenance and…

Answer

Memory can become stale when preferences change, facts expire, or an earlier model inference was wrong. Store provenance and timestamps where appropriate, let explicit current instructions override old preferences, and provide ways to correct or remove stored information.

Syntax

memory item + timestamp/source → freshness check → confirm, update, or ignore

Example

Example: a newly stated budget overrides an older budget preference for the current task.

Key Points

  • Track provenance and freshness.
  • Prefer current explicit instructions.
  • Provide correction and deletion paths.
Q72Reliability

How should an agent respond when a tool returns an empty result?

Treat an empty result as a valid observation rather than automatically as a failure. The agent may clarify the query,…

Answer

Treat an empty result as a valid observation rather than automatically as a failure. The agent may clarify the query, broaden search within permitted scope, explain that no matching record was found, or stop if the task cannot proceed.

Syntax

empty result → inspect query and scope → refine safely or report no match

Example

Example: if an order lookup returns no matching order, ask the user to verify the order number instead of inventing a status.

Key Points

  • Distinguish empty results from errors.
  • Do not widen access scope unsafely.
  • Report missing data honestly.
Q73Reliability

What is exponential backoff with jitter?

Exponential backoff increases the delay between retries, while jitter adds randomness to avoid many clients retrying at the…

Answer

Exponential backoff increases the delay between retries, while jitter adds randomness to avoid many clients retrying at the same time. Use it for retryable transient failures and cap both the delay and number of attempts.

Syntax

delay = min(maxDelay, baseDelay × 2^attempt) + random jitter

Example

Example: retry a rate-limited read call after a bounded delay, respecting provider retry guidance when available.

Key Points

  • Retry only transient failures.
  • Cap attempts and total elapsed time.
  • Use jitter to reduce retry storms.
Q77Security

Why is a tool allowlist important?

An allowlist restricts the orchestrator to known, reviewed capabilities rather than letting the model invoke arbitrary…

Answer

An allowlist restricts the orchestrator to known, reviewed capabilities rather than letting the model invoke arbitrary functions or endpoints. It reduces the attack surface and supports consistent validation, authorization, monitoring, and change control.

Syntax

model proposes tool → allowlist check → schema/policy validation → execution

Example

Example: a web research agent can call approved search and fetch tools but cannot invoke a shell command.

Key Points

  • Expose only reviewed tools.
  • Reject unknown tool names.
  • Version and audit tool permissions.
Q81Safety and control

What is the difference between approval and confirmation?

Confirmation usually asks the user to acknowledge a specific action or choice, while approval may represent an authorization…

Answer

Confirmation usually asks the user to acknowledge a specific action or choice, while approval may represent an authorization decision by a person with the required role. A system may require both, especially when an action is high impact.

Syntax

prepare action summary → confirm intent → check authorized approver → execute after revalidation

Example

Example: a requester confirms a refund request, but a manager with refund privileges approves it.

Key Points

  • Define who can confirm versus authorize.
  • Show exact action details.
  • Revalidate before execution.
Q83Evaluation

How do you evaluate tool-selection accuracy?

Create labeled tasks with the appropriate tool or valid tool set, then measure whether the agent selects a suitable…

Answer

Create labeled tasks with the appropriate tool or valid tool set, then measure whether the agent selects a suitable capability and supplies valid arguments. Include cases where no tool should be called and where clarification is required.

Syntax

task set + expected tool behavior → run agent → compare calls/arguments → error analysis

Example

Example: test that a simple definition request does not trigger a privileged database mutation tool.

Key Points

  • Include no-tool and clarification cases.
  • Measure argument validity as well as tool choice.
  • Review false-positive tool use.
Q86Performance and cost

When should an agent use a smaller model for a subtask?

A smaller model can handle simple classification, routing, or extraction when evaluation shows adequate accuracy. Keep more…

Answer

A smaller model can handle simple classification, routing, or extraction when evaluation shows adequate accuracy. Keep more demanding planning or synthesis tasks on a stronger model when the quality improvement justifies its cost and latency.

Syntax

router/classifier → small model for routine task; escalation → stronger model for complex task

Example

Example: use a small model to classify ticket category and a stronger model only for ambiguous escalations.

Key Points

  • Route based on measured task complexity.
  • Evaluate escalation and misclassification rates.
  • Measure cost per successful workflow.
Q88Multi-agent systems

How should a coordinator delegate tasks to worker agents?

The coordinator should assign bounded subtasks with explicit outputs, constraints, deadlines, and permitted tools. It should…

Answer

The coordinator should assign bounded subtasks with explicit outputs, constraints, deadlines, and permitted tools. It should validate worker results, resolve conflicts, and preserve provenance rather than treating another agent's response as automatically correct.

Syntax

coordinator → scoped task contracts → workers → validated results → synthesis

Example

Example: one worker gathers sources and another checks claims, while the coordinator ensures both use approved sources.

Key Points

  • Give each worker a clear contract.
  • Validate outputs and provenance.
  • Limit delegation depth and budget.
Q90Tool protocols and integration

What should you consider before connecting an MCP server?

Review the server's provenance, capabilities, authentication, data access, transport, deployment, update process, and…

Answer

Review the server's provenance, capabilities, authentication, data access, transport, deployment, update process, and security posture. Expose only needed tools and resources, and treat outputs as untrusted even when the protocol is standardized.

Syntax

server review → capability allowlist → credential scope → test environment → monitored rollout

Example

Example: approve a read-only knowledge-base server before enabling a separate server that can update tickets.

Key Points

  • Vet server identity and code provenance.
  • Limit capabilities and credentials.
  • Monitor and review updates.
Q98Coding

Write a simple TypeScript type for a tool definition.

A tool definition should specify a stable name, a description, and an input contract. A generic TypeScript type can document…

Answer

A tool definition should specify a stable name, a description, and an input contract. A generic TypeScript type can document the application interface, but runtime schema validation is still necessary because model responses arrive as untrusted data.

Syntax

type ToolDefinition<TArgs, TResult> = { name: string; description: string; execute(args: TArgs): Promise<TResult> }

Example

TypeScript example: type ToolDefinition<TArgs, TResult> = { name: string; description: string; execute: (args: TArgs, context: AuthContext) => Promise<TResult>; };

Key Points

  • Use typed contracts for maintainability.
  • Pass trusted auth context separately from model arguments.
  • Validate external input at runtime.
Q99Coding

How would you implement a bounded agent loop in TypeScript?

A bounded loop should stop on a final answer, a step limit, a deadline, cancellation, or an unrecoverable error. Every tool…

Answer

A bounded loop should stop on a final answer, a step limit, a deadline, cancellation, or an unrecoverable error. Every tool call must pass validation and authorization before execution, and tool results should be added to explicit state.

Syntax

while steps < maxSteps and before deadline: decide → validate → execute → observe

Example

TypeScript-style pseudocode: for (let step = 0; step < maxSteps; step++) { if (signal.aborted) throw new Error("Cancelled"); const decision = await model.next(state); if (decision.type === "final") return decision.text; const call = validateToolCall(decision.call, authContext); const result = await executeTool(call, { signal, authContext }); state = appendObservation(state, result); } throw new Error("Agent step limit reached");

Key Points

  • Set step and time limits.
  • Validate and authorize each call.
  • Return explicit incomplete status when limits are reached.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q31Security

How can a tool result cause prompt injection?

Explain malicious instructions embedded in retrieved pages, emails, or documents.

Answer

A tool can return untrusted content that contains instructions such as ignoring prior rules, revealing data, or calling another tool. If the agent treats that content as authoritative instructions, it may misuse its capabilities.

Separate trusted system policy from external data, label retrieved content as untrusted, constrain tools and permissions, and require confirmation for sensitive actions. Prompt wording helps but cannot replace application-level controls.

Key Points

  • External content is data, not policy.
  • Use least-privilege tools and explicit authorization.
  • Test indirect prompt-injection scenarios.
Q32Security

How do you apply least privilege to agent tools?

Design narrow capabilities and enforce user-level authorization.

Answer

Give each tool only the permissions needed for its task. Prefer read-only tools when possible, scope queries to the authenticated user's records, and separate privileged actions into dedicated tools with explicit checks and approval requirements.

Do not trust a user ID or account ID supplied by the model. Derive identity from the authenticated request and enforce authorization in the service layer on every call.

Key Points

  • Use narrow, purpose-built tools.
  • Derive identity from trusted authentication context.
  • Authorize every request at the backend.
Q33Security

How should secrets be managed in an agent system?

Protect API keys, credentials, and tokens used by tools.

Answer

Store credentials in a secret manager or protected server-side configuration, rotate them, and grant each service only the scopes it needs. Never place secrets in prompts, tool descriptions, browser code, logs, or model-visible results.

Use short-lived credentials where possible and ensure tools do not let the model choose arbitrary URLs or access internal metadata services. Audit secret access and revoke compromised credentials promptly.

Key Points

  • Keep secrets out of model context and client bundles.
  • Use scoped credentials and rotation.
  • Restrict destinations and audit access.
Q34Security

Where should authorization be enforced for agent actions?

Explain why authorization belongs in trusted application services.

Answer

Authorization must be enforced by the backend or trusted service immediately before an operation executes. A model's decision, prompt instruction, UI visibility, or tool schema is not proof that the user has permission.

Check the authenticated principal, resource ownership, role, tenant, requested action, and current business state. Recheck authorization for delayed approvals because roles or resource state may change.

Key Points

  • Enforce authorization at the execution boundary.
  • Never accept model-supplied identity as authority.
  • Recheck permission after approvals and before mutations.
Q35Security

How would you design a safe tool layer for an enterprise agent?

Describe schemas, policy checks, identity, audit, and controlled execution.

Answer

Put a tool gateway between the model and business services. It should validate schemas, map calls to an allowlist, derive identity from the authenticated session, enforce authorization and business rules, apply rate and resource limits, and record an audit event.

Separate read and write capabilities, require approvals for high-impact actions, redact outputs, and use idempotency for mutations. The gateway should return typed errors and avoid exposing raw internal exceptions.

Key Points

  • Use an allowlisted tool gateway.
  • Enforce identity, authorization, validation, and quotas.
  • Audit actions and add approval gates for high impact.
Q36Security

What should an audit trail record for an agent action?

Capture who requested an action, what was authorized, and the outcome.

Answer

Record a correlation ID, authenticated actor, action and target, timestamp, policy decision, approval reference if applicable, tool version, outcome, and relevant before-and-after identifiers. Store enough evidence to reconstruct the event without copying excessive sensitive content.

Protect audit records against unauthorized modification and apply retention policies. Distinguish model-proposed actions from actions actually executed by the application.

Key Points

  • Separate proposed actions from executed actions.
  • Record actor, authorization, outcome, and correlation IDs.
  • Protect logs and minimize sensitive payloads.
Q37Tool protocols and integration

What is the Model Context Protocol (MCP)?

Explain the purpose of a standard interface for tools and context.

Answer

MCP is a protocol for connecting AI applications to external capabilities and context through standardized server-provided primitives such as tools and resources. It can reduce the need for each client to implement a completely different integration for every service.

Using MCP does not automatically make a server trusted. Clients still need to vet servers, manage credentials, restrict capabilities, validate inputs and outputs, and obtain approval for sensitive operations.

Key Points

  • MCP standardizes integration patterns.
  • MCP does not replace authorization or security review.
  • Expose only approved servers and capabilities.
Q38Tool protocols and integration

When would you choose MCP over custom tool integrations?

Compare interoperability with direct, application-specific integrations.

Answer

MCP is useful when several AI clients need a consistent way to access a service or when the ecosystem already provides a suitable server. A custom integration may be simpler when one application needs a small, tightly controlled set of operations.

Compare operational maturity, authentication, authorization, deployment, latency, observability, versioning, and the trustworthiness of the server. A protocol choice does not remove the need to validate capabilities.

Key Points

  • Choose based on reuse and operational needs.
  • Assess authentication and permission boundaries.
  • Keep integration scope narrow either way.
Q39Tool protocols and integration

How do you version tools without breaking an agent?

Use stable schemas, compatibility rules, and staged rollout.

Answer

Treat tool schemas as APIs. Prefer additive optional fields, preserve existing behavior, version breaking changes, and maintain contract tests for model-generated arguments and tool responses.

Roll out changes gradually, monitor validation failures and task success, and keep a rollback path. Update tool descriptions and model instructions alongside schema changes.

Key Points

  • Maintain backward compatibility where possible.
  • Test both input and output contracts.
  • Use staged rollout and rollback.
Q40Reliability

How would you rate-limit agent tool calls?

Apply per-user, per-tool, and global limits to control abuse and cost.

Answer

Apply limits at multiple levels: per user or tenant, per tool, per time window, and global service capacity. Combine request quotas with concurrency limits, token or cost budgets, and limits on repeated actions.

Return a typed rate-limit response with retry guidance when appropriate. A model should not be allowed to bypass a quota by repeatedly changing arguments or delegating to another agent.

Key Points

  • Use layered limits and concurrency controls.
  • Budget model calls and tool calls separately.
  • Make retry behavior bounded and observable.
Q41Evaluation and observability

What metrics would you monitor for an agent in production?

Track quality, tool reliability, safety, latency, and cost.

Answer

Monitor task completion and user correction rates, tool-call success and validation failures, policy denials, approval rates, repeated-call loops, latency percentiles, token usage, cost per successful task, and downstream dependency health.

Segment metrics by agent version, tool, task type, and tenant where appropriate. Avoid optimizing only for completion rate because an agent that takes unsafe shortcuts can appear successful.

Key Points

  • Combine outcome, reliability, safety, and cost metrics.
  • Segment by version and tool.
  • Alert on regressions and abnormal action patterns.
Q42Evaluation and observability

How would you regression-test an agent?

Create repeatable test cases for tool selection, arguments, and final outcomes.

Answer

Build a test suite of representative tasks with mocked tool responses and expected properties: correct tool selection, valid arguments, correct handling of errors, adherence to policy, and an acceptable final result. Include adversarial and edge cases.

Model outputs can vary, so avoid brittle exact-string assertions when semantic checks are more appropriate. Use fixed seeds or deterministic settings when supported, and add production failures to the test set after removing sensitive data.

Syntax

expect(result.status).toBe("completed");
expect(toolCalls).toContainEqual(
  expect.objectContaining({ name: "get_order_status" })
);
expect(unauthorizedMutationCount).toBe(0);

Key Points

  • Test decisions and side effects, not only wording.
  • Mock external systems for repeatability.
  • Add regression cases from real failures.
Q43Reliability

What should an agent do when its primary tool is unavailable?

Choose between retrying, approved fallback, partial completion, and escalation.

Answer

Classify the failure first. A transient timeout may justify a bounded retry; a permanent authorization error should not. An approved fallback can be used only if it has equivalent permission and data-quality guarantees.

If the task cannot be completed reliably, report what was and was not completed and offer a safe next step. Do not invent missing data or silently use an untrusted source.

Key Points

  • Classify errors before choosing a fallback.
  • Do not bypass permissions to recover availability.
  • Report partial completion accurately.
Q44Security

How do you minimize sensitive data sent to an LLM?

Limit tool results, redact personal data, and send only task-relevant fields.

Answer

Design tools to return the smallest set of fields needed for the task, filter records by authenticated user and purpose, redact or tokenize sensitive values, and avoid placing secrets in conversation history. Keep raw records in trusted services whenever possible.

Define retention and logging rules for prompts and outputs. Apply tenant isolation and verify that cached results cannot leak data between users.

Key Points

  • Minimize data at the source.
  • Redact before model calls and logs.
  • Protect tenant boundaries and cache keys.
Q45Security

How do you secure an agent that can fetch URLs?

Prevent SSRF, access to internal services, and unsafe redirects.

Answer

Do not let a model send arbitrary URLs directly to a privileged network client. Apply an allowlist where feasible, restrict schemes and ports, resolve and validate destination addresses, block private and link-local ranges, and revalidate each redirect.

Run fetchers in a restricted network environment with egress controls, response-size and timeout limits, and content-type checks. Defend against DNS rebinding and avoid exposing cloud metadata or internal administration endpoints.

Key Points

  • Use network-level egress restrictions as well as URL validation.
  • Block internal and metadata destinations.
  • Limit redirects, response size, and execution time.
Q46Safety and control

How would you design an agent that can make purchases?

Use quote, confirmation, authorization, idempotency, and reconciliation steps.

Answer

Separate product search and quote generation from the purchase operation. Present the exact item, quantity, total price, fees, shipping, and terms to the user, then require an explicit confirmation bound to that quote.

Before purchase, revalidate price and availability, authenticate and authorize the actor, apply spending limits, and use an idempotency key. Persist the transaction state and reconcile uncertain outcomes rather than blindly retrying.

Key Points

  • Require confirmation of exact transaction details.
  • Revalidate quote and permissions at execution time.
  • Use idempotency and reconciliation for uncertain results.
Q47Security

How do you ensure tenant isolation in an enterprise agent?

Prevent one customer's context, tools, or retrieved data from leaking to another.

Answer

Derive tenant identity from authenticated server-side context and pass it through every retrieval and tool call. Enforce tenant filters in the data layer, namespace caches and memory, and avoid letting the model choose or override tenant identifiers.

Test cross-tenant access explicitly, including indirect paths such as summaries, logs, shared caches, delegated agents, and background jobs.

Key Points

  • Derive tenant context from trusted authentication.
  • Enforce isolation in storage and service layers.
  • Test cross-tenant leakage paths.
Q48Evaluation and observability

How would you safely roll out a new agent version?

Use offline evaluation, canary traffic, monitoring, and rollback.

Answer

Run the new version against a regression suite and safety evaluations, then deploy it to a small canary segment. Compare task outcomes, tool errors, policy violations, latency, and cost with the current version.

Expand traffic only when metrics meet defined thresholds. Keep model, prompt, tool schema, and application versions traceable, and maintain a fast rollback path.

Key Points

  • Evaluate offline before production.
  • Use canaries and explicit promotion thresholds.
  • Keep version metadata and rollback capability.
Q49System design

Design an AI customer-support agent that can look up orders and issue refunds.

Propose a safe architecture for read and write actions.

Answer

Use an authenticated API layer, an orchestrator, an LLM, and narrow tools such as search knowledge base, get order status, and request refund. Read tools enforce customer ownership; the refund tool checks eligibility, amount limits, and role permissions.

Require explicit approval for the refund, revalidate order state at execution time, use idempotency, and record an audit trail. Add retrieval grounding, prompt-injection defenses, monitoring, rate limits, and a human escalation path.

Key Points

  • Separate read tools from privileged write tools.
  • Authorize and validate at the backend.
  • Add approval, idempotency, audit, and escalation.
Q50System design

Design a research agent that gathers sources and writes a report.

Cover planning, retrieval, source provenance, synthesis, and verification.

Answer

Define the research question and output schema, then use approved search and retrieval tools to collect sources. Store source identifiers, URLs, timestamps, and relevant excerpts; deduplicate results and keep evidence linked to each claim.

The agent should distinguish sourced facts from inference, flag gaps, and verify important claims against reliable sources. Apply URL-fetching safeguards, content-size limits, source-quality checks, and a final review step before publishing.

Key Points

  • Preserve provenance for claims.
  • Treat web content as untrusted input.
  • Verify key claims and disclose evidence gaps.
Q59Tool calling

How do you make tool execution auditable?

Assign a correlation ID to the agent run and record each proposed call, validation decision, authorization result, executed…

Answer

Assign a correlation ID to the agent run and record each proposed call, validation decision, authorization result, executed operation, outcome, and timing. Redact sensitive payloads and protect audit records from unauthorized modification.

Syntax

run_id → proposed call → policy decision → executed operation → outcome record

Example

Example: distinguish a model's proposed `delete_file` call from a deletion that actually passed authorization and completed.

Key Points

  • Record proposals and executions separately.
  • Use correlation IDs across services.
  • Minimize sensitive payloads in logs.
Q63Workflows and orchestration

How do you make agent workflows resumable?

Use durable checkpoints, explicit task states, idempotent actions, and a recovery policy for each step. Store enough…

Answer

Use durable checkpoints, explicit task states, idempotent actions, and a recovery policy for each step. Store enough structured information to resume without replaying every prior model call, and revalidate data that may have changed while the task was paused.

Syntax

checkpoint → worker interruption → load state → verify external state → continue

Example

Example: before retrying a booking after a timeout, query the booking service to determine whether the first attempt succeeded.

Key Points

  • Checkpoint after meaningful transitions.
  • Make side effects idempotent or reconcilable.
  • Revalidate stale assumptions.
Q64Workflows and orchestration

What is the saga pattern and how can it help agent workflows?

A saga coordinates a sequence of distributed operations using local transactions and compensating actions when a later step…

Answer

A saga coordinates a sequence of distributed operations using local transactions and compensating actions when a later step fails. It can help with workflows that span services, but compensation is not always a perfect reversal and must be explicitly designed.

Syntax

reserve inventory → charge payment → schedule shipment; on failure run defined compensations

Example

Example: if shipment scheduling fails after payment, a controlled compensation may void or refund the payment according to business policy.

Key Points

  • Use explicit step and compensation records.
  • Compensation is not always a true rollback.
  • Require reconciliation and audit for partial completion.
Q67Planning and reasoning

How can you detect whether an agent is making progress?

Track explicit milestones, completed subtasks, changed state, repeated tool-call signatures, and whether new observations…

Answer

Track explicit milestones, completed subtasks, changed state, repeated tool-call signatures, and whether new observations reduce uncertainty. If the same action repeats without new information, stop, change strategy, ask for input, or escalate.

Syntax

step signature + state delta + milestone status → progress check → continue or stop

Example

Example: three identical searches with the same empty result trigger a bounded fallback rather than another identical call.

Key Points

  • Define measurable progress signals.
  • Detect repeated calls and unchanged state.
  • Stop or escalate when progress stalls.
Q68Planning and reasoning

How do you balance agent autonomy with predictability?

Grant autonomy for reversible, low-risk tasks while using deterministic gates for sensitive, costly, or irreversible…

Answer

Grant autonomy for reversible, low-risk tasks while using deterministic gates for sensitive, costly, or irreversible operations. Set clear scopes, step budgets, approval requirements, and observable completion criteria so the agent can adapt without receiving unrestricted authority.

Syntax

risk classification → autonomy level → bounded plan → approvals for high-impact steps

Example

Example: allow an agent to summarize documents automatically but require confirmation before sharing them externally.

Key Points

  • Match autonomy to action risk.
  • Use approval and policy gates.
  • Make actions observable and reversible where possible.
Q71State and memory

How would you isolate memory between users and tenants?

Namespace memory by authenticated identity and tenant, enforce access in the storage layer, and include the same scope in…

Answer

Namespace memory by authenticated identity and tenant, enforce access in the storage layer, and include the same scope in cache keys and retrieval filters. Never let the model choose another user's memory namespace or infer permission from remembered text.

Syntax

authenticated principal → server-derived namespace → scoped read/write → access audit

Example

Example: a shared agent service never retrieves one customer's conversation summary for another customer.

Key Points

  • Derive scope from trusted identity.
  • Apply isolation to caches and background jobs.
  • Test cross-user and cross-tenant access.
Q74Reliability

How do you avoid duplicate side effects when an agent retries after a timeout?

A timeout leaves the remote outcome uncertain. Use an idempotency key and durable operation record, then query the…

Answer

A timeout leaves the remote outcome uncertain. Use an idempotency key and durable operation record, then query the downstream system or reconcile by request ID before issuing a new mutation.

Syntax

submit with idempotency key → timeout → query operation status → retry only if safe

Example

Example: a payment tool uses one stable key per intended payment so retrying does not create a second charge.

Key Points

  • A timeout does not prove failure.
  • Use idempotency and operation status checks.
  • Persist intent and final outcome.
Q75Reliability

What is a circuit breaker and when would an agent need one?

A circuit breaker temporarily stops calls to a failing dependency after a threshold of failures, allowing the dependency to…

Answer

A circuit breaker temporarily stops calls to a failing dependency after a threshold of failures, allowing the dependency to recover and preventing cascading load. It can transition through closed, open, and half-open states while probes test recovery.

Syntax

CLOSED → failures exceed threshold → OPEN → wait → HALF_OPEN probe → CLOSED or OPEN

Example

Example: stop repeatedly calling an unavailable CRM API and return a controlled unavailable result until a probe succeeds.

Key Points

  • Prevent cascading failures.
  • Use thresholds and recovery probes.
  • Expose circuit state in monitoring.
Q76Reliability

How should an agent handle partial success across multiple tools?

Track the outcome of each step and distinguish completed, failed, and unknown operations. Decide whether to continue,…

Answer

Track the outcome of each step and distinguish completed, failed, and unknown operations. Decide whether to continue, compensate, request approval, or report partial completion based on business rules rather than presenting the overall task as fully successful.

Syntax

step A completed + step B failed + step C not run → recovery policy → explicit status

Example

Example: report that a report was generated but email delivery failed, and offer a safe retry for delivery.

Key Points

  • Persist per-step status.
  • Define compensation or recovery rules.
  • Communicate partial completion accurately.
Q78Security

How do you defend against indirect prompt injection in agent workflows?

Indirect prompt injection arrives through content the agent reads, such as webpages, emails, documents, or tool output.…

Answer

Indirect prompt injection arrives through content the agent reads, such as webpages, emails, documents, or tool output. Treat such content as untrusted, isolate it from trusted instructions, restrict tools, validate outputs, and require authorization and approval for sensitive actions.

Syntax

external content → untrusted-data boundary → constrained model decision → policy enforcement

Example

Example: a webpage asks the agent to email confidential files; the email tool still requires explicit user authorization and recipient validation.

Key Points

  • Test malicious external content.
  • Do not let retrieved text alter authorization.
  • Use least privilege and approval gates.
Q79Security

How should browser automation tools be secured for an agent?

Run browser automation with isolated sessions and least-privilege accounts, restrict navigation and downloads, validate…

Answer

Run browser automation with isolated sessions and least-privilege accounts, restrict navigation and downloads, validate destinations, and require confirmation for purchases, submissions, or destructive actions. Protect cookies and session tokens from prompts and logs.

Syntax

user-scoped browser session → destination policy → action validation → confirmation → execution

Example

Example: an agent may draft a form but must show the user the final submission details before sending it.

Key Points

  • Isolate sessions and credentials.
  • Restrict destinations and downloads.
  • Confirm consequential browser actions.
Q80Security

How should an agent handle untrusted code execution requests?

Do not run model-provided code in the application process with broad privileges. If code execution is necessary, use a…

Answer

Do not run model-provided code in the application process with broad privileges. If code execution is necessary, use a sandbox with strict CPU, memory, time, filesystem, and network limits, and treat outputs as untrusted data.

Syntax

code proposal → policy gate → isolated sandbox → resource limits → validated output

Example

Example: a data-analysis agent runs a generated script in a disposable container without access to production credentials.

Key Points

  • Sandbox execution separately.
  • Disable unnecessary network and filesystem access.
  • Validate output and enforce resource limits.
Q82Safety and control

How should an agent handle a user changing their mind mid-task?

Record cancellation or updated intent as a state transition, stop cancellable work, and check whether any side effects have…

Answer

Record cancellation or updated intent as a state transition, stop cancellable work, and check whether any side effects have already occurred. If an action is in flight or irreversible, report its status and follow a defined compensation or reconciliation path.

Syntax

new user instruction → update task state → cancel pending work → reconcile completed actions

Example

Example: cancel a draft email immediately, but if it was already sent, explain that it cannot be unsent and offer a follow-up.

Key Points

  • Propagate cancellation where possible.
  • Distinguish pending from completed actions.
  • Reconcile irreversible side effects.
Q84Evaluation

What is the difference between offline and online agent evaluation?

Offline evaluation runs a fixed dataset or simulation before deployment and supports repeatable comparisons. Online…

Answer

Offline evaluation runs a fixed dataset or simulation before deployment and supports repeatable comparisons. Online evaluation measures behavior in real usage, subject to privacy, safety, and experimentation constraints; it can reveal distribution shifts that offline sets miss.

Syntax

offline regression suite → canary deployment → privacy-safe online metrics → review

Example

Example: validate a new planner offline, then compare canary task success and policy denials before expanding traffic.

Key Points

  • Use offline tests before rollout.
  • Monitor online drift and regressions.
  • Protect users during experiments.
Q85Evaluation

How do you evaluate an agent's safety separately from task success?

Task success measures whether the goal was achieved, while safety evaluation measures whether the agent stayed within…

Answer

Task success measures whether the goal was achieved, while safety evaluation measures whether the agent stayed within policy, respected permissions, avoided data leaks, and handled risky requests correctly. Evaluate them separately because an unsafe shortcut can still produce a successful outcome.

Syntax

task outcome metrics + policy-violation tests + access-control tests + adversarial suite

Example

Example: an agent that retrieves another tenant's record fails safety even if it answers the user's question correctly.

Key Points

  • Safety is not implied by success.
  • Test unauthorized and adversarial cases.
  • Track severity as well as frequency.
Q87Performance and cost

How do you cache agent tool results safely?

Cache only results whose freshness and authorization semantics are understood. Include relevant tenant, user scope, query…

Answer

Cache only results whose freshness and authorization semantics are understood. Include relevant tenant, user scope, query parameters, and data version in the cache key; set a suitable TTL and invalidate entries after mutations or source changes.

Syntax

authorized request → scoped cache key → fresh hit or tool call → TTL/invalidation

Example

Example: cache public documentation search separately from customer-specific order lookups, which require strict user-scoped keys.

Key Points

  • Include authorization scope in cache keys.
  • Set TTL based on data freshness.
  • Invalidate after relevant changes.
Q89Multi-agent systems

How do you prevent multi-agent systems from multiplying costs uncontrollably?

Set global budgets for model calls, tool calls, elapsed time, delegation depth, and parallel workers. Require a clear reason…

Answer

Set global budgets for model calls, tool calls, elapsed time, delegation depth, and parallel workers. Require a clear reason for spawning workers, stop redundant tasks, and track cost and quality per completed user goal.

Syntax

global run budget → worker allocation → per-worker limits → aggregate budget enforcement

Example

Example: cap a research run at three parallel workers and stop further delegation when the evidence threshold is met.

Key Points

  • Use global and per-worker budgets.
  • Limit recursion and parallelism.
  • Measure incremental value of each worker.
Q91Tool protocols and integration

How should an agent handle tool schema changes during a running task?

Pin or record the tool contract version for a run where practical, validate calls against the active schema, and return a…

Answer

Pin or record the tool contract version for a run where practical, validate calls against the active schema, and return a controlled incompatibility error if a tool changes unexpectedly. Deploy compatible changes gradually and ensure long-running jobs can resume safely.

Syntax

run uses schema version N → tool deployment → compatibility check → continue or controlled restart

Example

Example: a removed required field causes a typed failure and safe replanning rather than a malformed mutation.

Key Points

  • Version tool contracts.
  • Keep changes backward-compatible when possible.
  • Handle in-flight task incompatibility explicitly.
Q92System design

Design an AI operations agent that can inspect services and restart a deployment.

Use authenticated read-only observability tools for health checks and logs, plus a separate restart tool with strict service…

Answer

Use authenticated read-only observability tools for health checks and logs, plus a separate restart tool with strict service allowlists, role checks, change-window rules, approval, and audit. The agent should diagnose first, present evidence and impact, then execute only the approved action.

Syntax

authenticate → inspect health/logs → diagnosis + evidence → approval → policy-checked restart → verify health

Example

Example: the agent can recommend a restart but cannot restart a production service without an authorized approval and a post-action health check.

Key Points

  • Separate diagnostics from mutations.
  • Use allowlists, approvals, and audit.
  • Verify service health after the action.
Q93System design

Design an agent for processing invoices with human review.

Use document extraction and validation tools to produce structured invoice fields, compare them with purchase orders and…

Answer

Use document extraction and validation tools to produce structured invoice fields, compare them with purchase orders and business rules, and flag mismatches. The agent can prepare a recommendation, but payment or posting requires the configured approval and finance-system authorization.

Syntax

invoice → extraction → validation/matching → exception queue or approval → authorized posting

Example

Example: route an invoice with a mismatched amount to a reviewer rather than letting the model silently approve it.

Key Points

  • Validate extracted fields against trusted records.
  • Route exceptions to humans.
  • Separate recommendation from payment execution.
Q94System design

How would you design a safe agent for managing email?

Provide scoped tools for searching, drafting, and sending messages, with send permission separated from draft permission.…

Answer

Provide scoped tools for searching, drafting, and sending messages, with send permission separated from draft permission. Validate recipients and attachments, prevent exfiltration of sensitive data, and require confirmation before external sends or bulk actions.

Syntax

search/read → draft → recipient/content checks → user confirmation → send tool → audit

Example

Example: the agent drafts a reply to a selected thread, shows recipients and attachments, then sends only after confirmation.

Key Points

  • Separate draft and send capabilities.
  • Validate recipients and attachment scope.
  • Confirm bulk or external sends.
Q95System design

How would you design an agent that edits files in a repository?

Use a version-controlled workspace and tools for reading files, proposing patches, running tests, and creating a reviewable…

Answer

Use a version-controlled workspace and tools for reading files, proposing patches, running tests, and creating a reviewable change. Restrict paths and commands, avoid exposing secrets, and require human review before merging or deploying changes.

Syntax

read-only inspection → patch proposal → sandbox tests → diff review → authorized commit/merge

Example

Example: an agent can open a pull request with test results but cannot directly deploy to production.

Key Points

  • Restrict filesystem paths and commands.
  • Test changes in an isolated environment.
  • Keep human review before merge/deploy.
Q96System design

How would you design an agent for customer data exports?

Treat export as a sensitive operation. Verify identity and purpose, scope the requested records, apply role and tenant…

Answer

Treat export as a sensitive operation. Verify identity and purpose, scope the requested records, apply role and tenant policies, show the export fields and destination, require approval where policy demands, and audit the final export and delivery.

Syntax

request → authenticate/authorize → scope and minimize → approval → generate securely → audit delivery

Example

Example: reject an export request that tries to include records outside the authenticated tenant.

Key Points

  • Apply data minimization and access controls.
  • Validate destination and approval.
  • Securely expire temporary export files.
Q97System design

How would you design a research-and-action agent with a review step?

Separate information gathering, recommendation, and execution into distinct stages. Store source evidence and proposed…

Answer

Separate information gathering, recommendation, and execution into distinct stages. Store source evidence and proposed action details, present a reviewable summary, then revalidate current conditions and permissions before executing any approved mutation.

Syntax

research → evidence-linked recommendation → human review → revalidation → action → verification

Example

Example: the agent researches a vendor and drafts a purchase recommendation, but procurement approval is required before placing an order.

Key Points

  • Separate research from execution.
  • Preserve evidence and proposed action details.
  • Revalidate after review and verify outcomes.
Q100Coding

How do you test a tool without calling a real external service?

Inject the dependency into the tool implementation and replace it with a mock or fake in unit tests. Verify argument…

Answer

Inject the dependency into the tool implementation and replace it with a mock or fake in unit tests. Verify argument mapping, error handling, authorization behavior, and output normalization; use separate integration tests for the real service contract.

Syntax

tool → injected dependency interface → mock in unit tests; real dependency in integration tests

Example

Example: mock the order client to return a known status and assert the tool maps it into a minimized response.

Key Points

  • Use dependency injection.
  • Test failures and unauthorized requests.
  • Keep integration tests for service contracts.

Share this question bank

Send this page to someone preparing for an interview.