Solving tips
- An agent is a while-loop: call the model, and either finish or run a tool and feed the result back.
- Always cap the number of steps so a misbehaving model can't loop forever.
- The model call is mocked here — the point is the control flow, which is exactly what interviewers grade.
Implement the core agent loop — the control flow that turns a language model into an agent. The model call is a stub you are given; the exercise is the loop that drives it. This is the first thing interviewers ask you to build in an agent-coding round.
How the loop works
You keep a running list of messages. Each turn you call model(messages) and it returns one of two things:
- a final answer —
{"role": "assistant", "type": "final", "content": "..."}— stop and return the content. - a tool call —
{"role": "assistant", "type": "tool", "name": "search", "args": {"q": "..."}}— look up the tool by name intools, call it withargs, append the assistant’s tool call and the tool’s result tomessages, and loop again.
You must cap the loop at max_steps so a model that never finishes cannot run forever.
Task
Complete run_agent(model, tools, user_msg, max_steps=10):
- Start
messageswith the user message:{"role": "user", "content": user_msg}. - Loop up to
max_stepstimes: call the model, and either return the final content or execute the named tool and append both the assistant message and a tool-result message{"role": "tool", "name": ..., "content": <tool output>}. - If the loop runs out of steps, return a clear message like
"Stopped: reached max steps.".
Example
def model(messages):
# (mock) first turn asks for a tool, second turn answers
if not any(m["role"] == "tool" for m in messages):
return {"role": "assistant", "type": "tool", "name": "add", "args": {"a": 2, "b": 3}}
return {"role": "assistant", "type": "final", "content": "The answer is 5."}
tools = {"add": lambda args: str(args["a"] + args["b"])}
run_agent(model, tools, "what is 2 + 3?") # -> "The answer is 5."
Constraints
- Handle an unknown tool name gracefully (append an error result rather than crashing).
- Do not call any real LLM or network —
modeland the tools are provided.