PrepStack › AI › AI Agents & Tool Calling
AI Agents & Tool Calling interview cheat sheet
Agent loop, function calling, ReAct, planning, memory, multi-agent, safety and evals
Agent interviews check whether you can build a reliable loop around an LLM, not just call an API. Expect questions on the tool-calling request/response flow, when to use a fixed workflow instead of an agent, ReAct and planning, memory and state, multi-agent patterns, and, at senior level, guardrails, prompt injection, evaluation and cost control. Every Python demo below is pure standard library with a fake model, so you can see the mechanics; the SDK snippets show the real request shapes. Read the 15-minute list first, then use Quiz mode.
15-minute revision
- An agent = LLM + tools + a loop + memory/state. The model decides the next step; your code runs the tools and feeds results back until a stop condition.
- Workflow vs agent (Anthropic): workflows follow code-defined paths (chaining, routing, parallelisation, orchestrator-workers, evaluator-optimiser); agents choose their own path. Start with the simplest thing that works.
- Tool calling flow: send tools (name, description, JSON Schema) → model returns a tool call with JSON args → you execute → send the result back linked by call id → repeat.
- The model never runs tools. It only emits a structured request. Your app validates and executes it, so validation, auth and limits live in your code.
- OpenAI Responses:
function_callitems withcall_id+arguments(JSON string) → reply withfunction_call_output. Anthropic:tool_useblocks withid+input,stop_reason: "tool_use"→ reply with a usertool_resultcarryingtool_use_id. - Strict / structured tool schemas (
strict: true,additionalProperties: false) make args match the schema. Still validate on your side. - Parallel tool calls: one turn can hold several calls. Run independent ones concurrently and return one result per id. Turn it off when order matters.
- Good tools: few, clearly named and namespaced, detailed descriptions, enums over free text, concise high-signal output, and actionable error messages returned to the model.
- ReAct interleaves Thought → Action → Observation. Plan-and-execute writes the plan first, runs steps (often with cheaper models), and replans on failure.
- Reflection / evaluator-optimiser: generate, critique, revise. Works best when the critic has a grounded signal (tests, validators), not just another opinion.
- Memory: short-term = the context window (trim/summarise); long-term = external store; semantic (facts), episodic (past runs), procedural (instructions/skills).
- Multi-agent patterns: supervisor, hierarchical, handoffs, swarm, agents-as-tools. They add cost and failure points, so use them only when one agent with good tools is not enough.
- MCP connects an agent to tools/data (agent ↔ tool). A2A connects agents to other agents (agent ↔ agent) using Agent Cards and tasks.
- Security: treat every tool output as untrusted input (indirect prompt injection). Least privilege, allowlists, sandboxing and human approval for risky actions (OWASP LLM01, LLM06).
- Control the loop: max steps, token/cost budgets, timeouts, repeated-call detection, retries with backoff, and checkpoints so runs can resume.
- Evaluate outcomes and trajectories (right tools, order, steps, cost), trace every LLM and tool call as spans, and turn production failures into regression tests.
Foundations
What an agent is: LLM + tools + loop + memory
An agent is an LLM running in a loop, choosing tools and reading their results until the goal is met or a limit is hit.
- The augmented LLM is the building block: a model plus retrieval, tools and memory.
- An agent adds a loop: the model looks at the state, picks an action (tool call or final answer), your code runs it, and the result is appended to the context.
- Tools let the model act and fetch fresh data: APIs, DB queries, code execution, search, file edits.
- Memory/state holds the transcript, intermediate results, and facts kept across sessions.
- Stop conditions are part of the design: final answer, max steps, budget, timeout, or a human stop.
- Agents trade predictability for flexibility. They suit open-ended tasks where you cannot hard-code the number or order of steps.
Interview questions
- What is an AI agent?
- How is an agent different from a normal LLM call or RAG pipeline?
- What are the main components you would design for an agent?
Workflows vs agents: the five patterns
Prefer code-defined workflows for predictable tasks; use autonomous agents only when the path cannot be known in advance.
- Prompt chaining: split a task into fixed steps; each LLM call uses the previous output. Add programmatic gates between steps.
- Routing: classify the input, then send it to a specialised prompt, tool set or model (for example a cheap model for easy queries).
- Parallelisation: sectioning (independent subtasks at once) or voting (same task several times, then aggregate).
- Orchestrator-workers: a central LLM breaks the task into subtasks decided at run time, delegates to workers, and merges results.
- Evaluator-optimiser: one LLM generates, another evaluates and gives feedback, in a loop, when clear criteria exist.
- Rule of thumb: start with one well-prompted call, add retrieval and tools, then workflows, and only then agents. Each step adds cost and latency.
Interview questions
- What is the difference between a workflow and an agent?
- When would you NOT use an agent?
- Explain orchestrator-workers vs parallelisation.
- What is the voting variant of parallelisation?
Tool calling
Function / tool calling flow
You describe tools with JSON Schema; the model replies with structured calls; you execute them and return results tagged with the call id.
- Each tool has a name, a description, and a JSON Schema for its parameters (
parametersin OpenAI,input_schemain Anthropic). - Tool definitions are injected into the prompt, so they cost input tokens on every request.
- The response may contain zero, one or many calls. Always loop over all of them.
- Arguments arrive as a JSON string in OpenAI (
arguments) and as a parsed object in Anthropic (input). Parse defensively. - Every result must reference its call (
call_id/tool_call_id/tool_use_id) so the model can match answers to questions. tool_choicecontrols behaviour: let the model decide (auto), force some tool (requiredin OpenAI,anyin Anthropic), force a specific tool, or disable tools (none).
Interview questions
- Walk me through how function calling works.
- How does the model know which tool to call?
- What does
tool_choicedo? - Function calling vs structured outputs?
Tool schemas, strict mode & validation
JSON Schema tells the model what arguments are valid; strict mode enforces it; your registry must still validate before executing.
- Use
type: object,propertieswith descriptions,required,enumfor fixed choices andadditionalProperties: false. - OpenAI strict mode (
strict: true) requires every property listed inrequiredandadditionalProperties: false; model optional fields as nullable ("type": ["string", "null"]). - Even with strict mode, validate semantics yourself: IDs exist, the user owns them, ranges are sane.
- On a validation error, do not crash. Return a clear error as the tool result so the model can fix its call.
- A tool registry maps names to functions, schemas and metadata (risk level, timeout, owner). Generate schemas from type hints (Pydantic,
@function_tool,@tool) to avoid drift. - Never
evalor blindly**kwargsmodel output into sensitive functions; unknown tool names must be rejected.
Interview questions
- Why use JSON Schema for tools?
- If strict mode guarantees the schema, why validate again?
- What should happen when the model sends invalid arguments?
Parallel tool calls
A single model turn can request several independent calls; run them concurrently and return one result per call id.
- Parallel calls cut latency and model round trips: fetching weather for 3 cities is one turn, not three.
- Execute independent calls with
asyncio.gatheror a thread pool; respect rate limits with a semaphore. - Return every result, each tied to its id. Missing results usually cause an API error on the next request.
- If one call fails, return an error result for that id and success results for the rest.
- Disable parallel calls (
parallel_tool_calls: false, or Anthropicdisable_parallel_tool_use) when calls depend on each other or have side effects that must be ordered. - Parallel tool calls (inside one turn) differ from parallel agents or the parallelisation workflow (several LLM calls at once).
Interview questions
- What are parallel tool calls and why do they matter?
- When would you turn off parallel tool calls?
- One of three parallel calls times out. What do you send back?
Tool design best practices
Design tools for an LLM user: few, clearly described, task-shaped, concise outputs and helpful errors.
- Descriptions matter most: what it does, when to use it (and when not), what each parameter means, what it returns, limits. Use the "intern test".
- Build tools around tasks, not raw endpoints:
schedule_eventbeatslist_users+list_events+create_event. Combine calls that always happen together. - Namespace names when you have many (
github_list_prs,slack_send_message) and keep the active set small; use tool search / deferred loading for large catalogs. - Use enums and typed fields to block invalid states; do not ask the model for values your code already knows (user id, auth tokens).
- Return high-signal, concise output: names and stable ids, not blobs and internal UUID soup. Paginate, truncate and offer a
response_format(concise/detailed). - Errors should be actionable: say what went wrong and how to fix it, not just a stack trace.
- Make side-effecting tools idempotent where possible and mark them as risky so the harness can require approval.
Interview questions
- How do you design good tools for an agent?
- Your agent has 80 tools and picks the wrong one often. What do you do?
- Why should tools return concise output?
Reasoning & control patterns
ReAct: reason + act
ReAct interleaves a short Thought, an Action (tool call) and an Observation (tool result), repeating until it can answer.
- From the 2022 ReAct paper (Yao et al.): combining reasoning traces with actions beats either alone on knowledge and decision tasks.
- The thought helps the model plan the next step and react to surprising observations; the action grounds it in real data, reducing hallucination.
- Originally done with text parsing (
Action: search[...]); today native tool calling replaces parsing, and reasoning models think internally. - Strength: adapts after every observation. Weakness: one LLM call per step, so it is slow and costly on long tasks, and can wander or loop.
- Most framework "prebuilt agents" (
create_react_agent,create_agent, Agents SDKRunner) are ReAct-style tool loops.
Interview questions
- What is ReAct?
- ReAct vs chain-of-thought?
- What are the weaknesses of ReAct and how do you mitigate them?
Plan-and-execute & planning
A planner LLM writes the full plan up front; an executor runs the steps; a replanner adjusts when results differ from expectations.
- Planner produces a list or DAG of steps (often as structured JSON); executor runs each step with tools, maybe with a smaller cheaper model.
- Benefits: fewer calls to the big model, a global view of the task, easy to show the plan to a user for approval, and independent steps can run in parallel.
- Replanning: after each step (or on failure), feed results back to the planner to revise remaining steps.
- Variants: ReWOO (plan with variable references like
#E1, execute without re-calling the planner), LLMCompiler (plan as a DAG, run in parallel). - Weakness: a bad initial plan wastes work; plans go stale when the environment changes. Combine with ReAct inside each step for flexibility.
- Coding agents often keep a visible todo list as a lightweight plan they update as they go.
Interview questions
- What is plan-and-execute and why use it?
- How would you handle a step that fails mid-plan?
- How do LLM agents plan for tasks larger than the context window?
Reflection, self-critique & evaluator-optimiser
Let the agent check its own work and revise, ideally against an external signal like tests, schemas or a separate judge.
- Reflection: after an attempt, the model critiques the output and produces an improved version.
- Reflexion (Shinn et al., 2023) stores verbal lessons from failed attempts in memory and uses them in the next try.
- Evaluator-optimiser: separate generator and evaluator prompts (or models) loop until the evaluator passes or a limit is hit.
- Pure self-critique has limits: a model often cannot find its own errors without new information. Grounded feedback (unit tests, compilers, linters, validators, retrieval) works much better.
- Always cap iterations and keep the best-so-far answer; critique loops can oscillate or make things worse.
Interview questions
- What is reflection in agents?
- Does self-critique always improve results?
- How would you build an agent that writes SQL reliably?
Stop conditions, retries & loop control
Bound every agent run with step, token, cost and time limits, detect loops, and retry only transient failures with backoff.
- Stop conditions: final answer,
max_steps/max_turns, token or cost budget, wall-clock timeout, user cancel, or a guardrail trip. - Loop detection: the same tool + same args repeated N times, or no progress in state over several steps. Stop or inject a hint.
- Retries: retry transient errors (timeouts, 429, 5xx) with exponential backoff + jitter; do not retry validation or auth errors, send them to the model instead.
- Model-level retries: invalid JSON or unknown tool → reply with an error message; after K failures, fall back or escalate.
- Fallbacks: a backup model or provider, a cached answer, or a hand-off to a human.
- When stopping early, return a useful partial result and the reason, not a silent failure.
Interview questions
- How do you stop an agent from looping forever?
- Which errors do you retry and which do you return to the model?
- What is a good fallback strategy for an agent in production?
Memory & state
Memory: short-term, long-term, episodic, semantic
Short-term memory is what fits in the context window; long-term memory lives in external stores and is retrieved when relevant.
- Short-term (working) memory: the current conversation/thread in the context window. Managed by trimming, summarising, or dropping old tool outputs.
- Long-term memory: persists across sessions in a database or vector store, retrieved by key or similarity.
- Semantic memory: facts and preferences ("user prefers metric units"). Episodic memory: past experiences and trajectories, used as few-shot examples. Procedural memory: how to act (system prompt, rules, learned skills).
- Summarisation (rolling or hierarchical) compresses older turns; keep recent turns verbatim because they matter most.
- Write paths: in the hot path (agent calls a
save_memorytool) or in the background (a job extracts memories after the conversation). - Memory needs governance: dedupe, update conflicting facts, expire stale data, respect privacy and deletion requests, and guard against memory poisoning.
Interview questions
- What types of memory does an agent have?
- How do you handle a conversation longer than the context window?
- Long-term memory vs RAG?
- What is memory poisoning?
State management, checkpoints & durable execution
Keep agent state explicit and persisted after each step so runs can pause, resume, be inspected and be replayed.
- State = messages plus structured fields (plan, results, flags, counters). Make it explicit (a typed dict / model), not hidden in prompts.
- Checkpointing saves state after every step (LangGraph checkpointers, Agents SDK sessions, workflow engines like Temporal). Key it by a thread/run id.
- Checkpoints enable resume after crash, human-in-the-loop pauses that can last days, time travel (replay from an earlier step) and debugging.
- Side effects need idempotency keys so a resumed step does not charge a card twice.
- Separate thread state (one conversation) from cross-thread store (long-term memory shared across threads).
- Long-running agents should be async jobs with status polling or streaming, not one HTTP request that can time out.
Interview questions
- Why do agents need checkpointing?
- How do you make a resumed agent not repeat side effects?
- How would you run an agent task that takes 20 minutes behind a web API?
Multi-agent & ecosystem
Multi-agent systems: supervisor, hierarchical, handoffs, swarm
Split work across specialised agents when one agent's context or tool set gets too large, but expect more cost and coordination failures.
- Supervisor: a central agent routes each step to a worker agent and decides when the task is done.
- Hierarchical: supervisors of supervisors (team leads), for large domains.
- Handoffs: an agent transfers control (and the conversation) to another agent, which then talks to the user directly. Swarm = peers that hand off to each other with no central boss.
- Agents as tools: a manager calls a sub-agent like a function and gets back a compact result; the manager keeps control.
- Benefits: smaller focused prompts and tool sets, parallel exploration, and fresh context windows per sub-task. Anthropic reported their multi-agent research system used far more tokens than single-agent chat.
- Risks: lost context between agents, duplicated work, conflicting actions, error cascades, much higher token use, and harder debugging. Share state explicitly and define clear contracts.
Interview questions
- When would you use multiple agents instead of one?
- Handoff vs agent-as-tool?
- Supervisor vs swarm?
- What are common failure modes of multi-agent systems?
Agent frameworks overview
Frameworks package the loop, tools, state, multi-agent and tracing; pick by control vs convenience, language and ecosystem.
- LangGraph: low-level graph runtime (nodes, edges, typed state), with checkpointers,
interrupt()for human-in-the-loop, streaming and durable execution. Good when you need fine control. - OpenAI Agents SDK (Python/TS): few primitives —
Agent,Runner, function tools, handoffs, agents-as-tools, guardrails, sessions and built-in tracing; provider-agnostic via adapters. - CrewAI: role-based agents (role, goal, backstory), tasks and crews with sequential or hierarchical processes, plus Flows for event-driven control.
- AutoGen pioneered multi-agent conversations; Microsoft has moved it to maintenance and merged its ideas with Semantic Kernel into Microsoft Agent Framework. AG2 is the community fork of AutoGen.
- Semantic Kernel: Microsoft SDK (C#, Python, Java) with plugins and kernel functions; enterprise-focused, now converging into Agent Framework.
- Google ADK (Agent Development Kit):
LlmAgentplus workflow agents (SequentialAgent,ParallelAgent,LoopAgent), multi-agent hierarchies, built-in eval, and A2A support. - You can always skip frameworks: a raw API loop is ~50 lines and fully transparent.
Interview questions
- Which agent framework would you choose and why?
- What does a framework give you over a raw API loop?
- What happened to AutoGen?
MCP and A2A protocols
MCP standardises how agents reach tools and data; A2A standardises how independent agents talk to each other.
- MCP (Model Context Protocol), from Anthropic (2024), is an open JSON-RPC protocol: a host app runs clients that connect to servers exposing tools, resources and prompts.
- MCP transports: stdio for local servers and Streamable HTTP for remote ones (with OAuth-based auth). It solves the N×M integration problem: write a server once, use it in any MCP host.
- A2A (Agent2Agent), launched by Google in 2025 and now under the Linux Foundation, lets agents built on different frameworks collaborate as peers.
- A2A discovery uses an Agent Card (JSON with identity, endpoint, skills, auth), commonly at
/.well-known/agent-card.json. Work is a task with a lifecycle, exchanging messages with parts and producing artifacts, over HTTP with JSON-RPC and streaming. - They are complementary: an agent uses MCP to call its tools and A2A to delegate to another agent it does not control.
- Both widen the attack surface: untrusted MCP servers can carry tool poisoning (malicious descriptions) and prompt injection; vet, pin and sandbox them.
Interview questions
- What is MCP and what problem does it solve?
- MCP vs A2A?
- What are the security risks of MCP servers?
Computer-use, browser & coding agents
Computer-use agents act on screens via screenshots and mouse/keyboard; coding agents read, edit and run code in a workspace with tests as feedback.
- Computer use: the model gets screenshots and returns actions (click x,y, type, scroll, key). Your harness executes them in a VM/container and returns a new screenshot. Offered by Anthropic (computer use tool) and OpenAI (computer use in the Responses API).
- Browser agents can use screenshots, the accessibility tree/DOM (more reliable and cheaper) or tools like Playwright. DOM-based actions beat pixel clicking when available.
- These agents are slow and fragile (pop-ups, layout shifts) and are high-risk for prompt injection from web pages. Run in an isolated VM, allowlist domains, and require confirmation for logins, purchases and sends.
- Coding agents (Claude Code, Codex, GitHub Copilot coding agent, Cursor, etc.) loop over search/read files → edit → run tests/linters → fix, often with a todo-list plan and sub-agents.
- Coding works well for agents because there is a fast verifiable signal: compilers and tests. Benchmarks like SWE-bench Verified measure fixing real GitHub issues.
- Key design choices for coding agents: good file search tools, diff-based edit tools, sandboxed execution, permission modes, context files like
AGENTS.md, and PR-based human review.
Interview questions
- How does a computer-use agent work?
- Why do coding agents work better than many other agents?
- How would you safely let an agent run shell commands?
Production: safety, evals & operations
Guardrails, human-in-the-loop & approvals
Check inputs, outputs and actions with code and models, and pause for a human before high-impact or irreversible actions.
- Input guardrails: topic/relevance checks, jailbreak and injection classifiers, PII detection. Can run in parallel with the main agent and cancel it if tripped.
- Output guardrails: schema validation, policy/moderation checks, groundedness checks, secret and PII redaction.
- Action guardrails: per-tool risk levels, allowlists, argument limits (max refund amount), rate limits.
- Human-in-the-loop (HITL): approve, edit or reject a tool call; review a plan; or escalate when confidence is low. Requires checkpointed state so the run can pause.
- Make approvals meaningful: show the exact action and arguments in plain language, and avoid approval fatigue by only gating risky actions.
- Guardrails reduce risk; they are not proof against injection. Combine with least privilege and sandboxing.
Interview questions
- What are guardrails in an agent system?
- Which actions should require human approval?
- How do you implement human-in-the-loop technically?
Security: prompt injection, excessive agency & sandboxing
Assume anything the agent reads can contain instructions; limit what the agent can do so that a hijacked agent still cannot cause serious harm.
- Indirect prompt injection: malicious instructions hidden in web pages, emails, files, tool results or MCP tool descriptions. The model cannot reliably tell data from instructions.
- The dangerous combination (Simon Willison's "lethal trifecta"): access to private data + exposure to untrusted content + ability to communicate externally. Remove at least one leg.
- Excessive agency (OWASP LLM06): too much functionality, too many permissions, or too much autonomy. Fix with minimal tools, scoped credentials acting as the user, and approvals.
- Sandboxing: run code and browsers in containers/microVMs (gVisor, Firecracker, e2b-style), no secrets inside, egress allowlists, resource limits, disposable environments.
- Improper output handling (LLM05): never pass model output straight into shells, SQL,
evalor HTML. Parameterise and escape. - Other OWASP LLM 2025 items relevant to agents: sensitive information disclosure, supply chain, system prompt leakage and unbounded consumption (runaway cost).
Interview questions
- What is indirect prompt injection and why is it worse for agents?
- How do you defend an agent against prompt injection?
- What is excessive agency?
- How would you sandbox code execution for an agent?
Evaluating agents: outcomes, trajectories & failure modes
Measure whether the task got done, how (tools, order, steps), and at what cost, on a fixed task set plus real production traces.
- Outcome / task success: did the final state match the goal? Check the environment (DB row exists, tests pass) rather than trusting the agent's text.
- Trajectory evaluation: compare the sequence of tool calls to a reference: exact match, in-order match, any-order match, or an LLM judge reading the trace.
- Step-level metrics: tool-selection accuracy, argument correctness, error/retry rate, number of steps, tokens, latency and cost per task.
- Agents are non-deterministic: run each task several times and report pass@k / pass^k (succeeds in all k runs) for reliability.
- Benchmarks: SWE-bench Verified (coding), τ-bench / τ²-bench (tool + user simulation), WebArena / OSWorld (web/computer), GAIA (general assistants). Use them for model choice, but build your own eval set.
- Common failure modes: wrong tool or args, hallucinated tool results, loops, premature "done", ignoring tool errors, context overflow, injection, and goal drift.
Interview questions
- How do you evaluate an AI agent?
- What is trajectory evaluation?
- What are the most common agent failure modes you have seen?
- How would you use an LLM-as-judge for agents safely?
Observability, tracing, cost & latency
Trace every run as a tree of spans (LLM calls, tool calls, handoffs) with tokens, latency and cost, and tune the loop to cut round trips.
- A trace is one agent run; spans are LLM calls, tool calls, guardrails and handoffs, nested in a tree with timings and attributes.
- Record: prompts and responses (with PII redaction), tool args/results, tokens in/out, cached tokens, latency, model, errors, and the stop reason.
- Tools: built-in tracing (OpenAI Agents SDK), LangSmith, Langfuse, Arize Phoenix, Braintrust, plus OpenTelemetry GenAI semantic conventions for vendor-neutral spans.
- Cost drivers: number of model calls × context size. Long histories are re-sent every turn, so trim context and use prompt caching on stable prefixes.
- Latency levers: parallel tool calls, fewer round trips (bigger task-level tools), smaller/faster models for routing and simple steps, streaming partial output, and caching tool results.
- Set per-run and per-user budgets and alerts; unbounded agent loops are a real billing risk (OWASP LLM10).
Interview questions
- How do you debug an agent that gives a wrong answer?
- How do you reduce cost and latency of an agent?
- What would you put on an agent monitoring dashboard?