InterviewPrepKit

Home / Coding / Agent Coding / The Agent Loop / The Basic Agent Loop

The Basic Agent Loop

easy 00:00
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 in tools, call it with args, append the assistant’s tool call and the tool’s result to messages, 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):

  1. Start messages with the user message: {"role": "user", "content": user_msg}.
  2. Loop up to max_steps times: 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>}.
  3. 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 — model and the tools are provided.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug