Skip to content

Interview question · Build-an-Agent Coding Rounds

Implement a tool-calling loop with validation, a step budget and error results in 45 minutes.

The interviewer is checking four things: the loop terminates, bad calls become useful observations instead of crashes, the budget holds, and you can prove all of it with a scripted model.

mediumEssentialNewUpdated Nov 2026

TL;DR: Define a tool registry where each tool has a schema; run a loop that asks the model for the next step, validates the proposed call against the schema, executes it, and appends either the result or a structured error the model can act on; stop on a final answer or when the step budget is spent, returning a named exit reason. Test it with a scripted model: a happy path, an unknown tool, invalid arguments, a tool exception and budget exhaustion.

How to approach it

Spend two minutes on interfaces (model reply shape, tool definition, result shape), get the happy path running with a test, then add validation, errors and budget, each with its own test. Narrate the choices.

A strong answer

import json

class Tool:
    def __init__(self, fn, schema):
        self.fn, self.schema = fn, schema            # schema: {arg: type}

def validate(schema, args):
    missing = [k for k in schema if k not in args]
    extra = [k for k in args if k not in schema]
    wrong = [k for k, t in schema.items()
             if k in args and not isinstance(args[k], t)]
    return ([f"missing {k}" for k in missing] + [f"unexpected {k}" for k in extra]
            + [f"{k} must be {schema[k].__name__}" for k in wrong])

def run(model, tools, task, max_steps=8):
    messages = [{"role": "user", "content": task}]
    for step in range(1, max_steps + 1):
        reply = model(messages)
        if reply["type"] == "final":
            return {"exit": "final", "answer": reply["text"], "steps": step}
        name, args = reply.get("tool"), reply.get("args", {})
        if name not in tools:
            result = {"error": "unknown_tool", "message": f"no tool {name!r}",
                      "available": sorted(tools), "retryable": False}
        elif problems := validate(tools[name].schema, args):
            result = {"error": "invalid_arguments", "problems": problems,
                      "retryable": True}
        else:
            try:
                result = {"ok": tools[name].fn(**args)}
            except Exception as e:                    # tool bug: observation, not crash
                result = {"error": "tool_failed", "message": type(e).__name__,
                          "retryable": False}
        messages.append({"role": "tool", "name": name, "content": json.dumps(result)})
    return {"exit": "budget", "answer": None, "steps": max_steps}

def scripted(*replies):
    it = iter(replies)
    return lambda messages: next(it)

tools = {"weather": Tool(lambda city: {"temp_c": 19}, {"city": str})}

happy = run(scripted({"type": "tool", "tool": "weather", "args": {"city": "Pune"}},
                     {"type": "final", "text": "19°C"}), tools, "Pune?")
print(happy["exit"], happy["steps"])  # => final 2

seen = []
def recording(messages):
    seen.append(messages[-1])
    return {"type": "tool", "tool": "weather", "args": {"town": "Pune"}} \
        if len(seen) == 1 else {"type": "final", "text": "sorry"}
run(recording, tools, "Pune?")
problems = json.loads(seen[-1]["content"])["problems"]
print(problems)  # => ['missing city', 'unexpected town']

looping = run(lambda m: {"type": "tool", "tool": "nope", "args": {}}, tools, "x", 3)
print(looping["exit"])  # => budget

The checks the interviewer will look for are all there: unknown tools return the list of available tools, invalid arguments return specific problems the model can fix, a tool exception becomes an observation instead of crashing the loop, and the budget ends the run with a named exit.

What to say while building.

  • "Errors go back to the model as observations with retryable, so it can correct arguments but will not retry a tool that does not exist."
  • "The exception handler is broad on purpose, at the boundary, to keep the loop alive; it records the type, not the message, to avoid leaking internals."
  • "With more time: per-tool timeouts, a repeated-call detector, and session-derived arguments that the model may not supply."

What interviewers probe next

"How would you add a timeout per tool?" Run the tool in a worker with a deadline (a thread or async task), and on timeout return {"error": "timeout", "retryable": true}.

"Why return available tools on unknown_tool?" It gives the model what it needs to recover in one step.

"Where would identity checks go?" In the dispatcher, before execution: arguments like customer_id come from the session, and the schema excludes them.

What if?

What if · interview follow-ups

Hold your answer as the constraints change

Your 45-minute loop validates arguments, returns error observations and enforces a step budget.

  1. Start here

    What if the model proposes two tool calls in one reply?

How it's scored

Weak: A loop that crashes on bad arguments or never stops.

Hire: Validation, error results and a budget, with a happy-path test.

Strong Hire: Clean interfaces, specific and actionable error observations with retryable, exceptions contained at the boundary, named exits, scripted tests for every failure path, and clear narration of what would come next.

Common mistakes

  • Raising exceptions out of the loop on model mistakes.
  • Error messages the model cannot act on ("invalid input").
  • No exit reason when the budget ends.
  • Testing only with a real model, or only the happy path.
You just read a free answer. Every topic opens its first 5 answers to anyone. Sign in and the count per topic goes to 6, and the site remembers where you stopped in each one.Google sign-in · free · no payment details
HOW DID IT GO?
0
READING SIGNED OUT

Signing in raises your free answers from 5 to 6 per topic, adds an applied lesson in every topic and easy practice tests, and the site starts remembering you: mastery per topic, bookmarks, and a next-focus recommendation. Free, no card.

Sign in free
UP NEXT ON YOUR JOURNEY
DISCUSSION · 0

Nobody has commented. Post a correction or another way to answer.