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.
Start here
What if the model proposes two tool calls in one reply?
Does your reply shape allow it?
Extend the reply to a list of calls, validate each, run independent reads in order or in parallel, and append each result with its call id so the model can match them.
Carry it forwardResults must be paired with call ids.
Weak answerRunning only the first and silently dropping the rest.
Constraint changes
What if the model keeps sending the same invalid arguments?
How many chances?
Count consecutive invalid calls per tool; after two, stop with an exit reason such as 'repeated invalid calls', rather than burning the budget.
Carry it forwardRepeated identical failures end early.
Weak answerLetting the budget be the only stop.
Constraint changes
What if a tool returns a huge result?
What enters the context?
Truncate or summarise it in the dispatcher with a note on how to get more (pagination), so one result cannot fill the context.
Carry it forwardThe dispatcher shapes what the model sees.
Weak answerAppending the raw result.
Now defend it
One-line summary of the build?
A registry with schemas, a loop that validates, executes and turns every failure into a structured observation, a step budget with named exits, and scripted-model tests for each path.
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.