Build a Mini Agent Loop

medium
Unit 18 · Agents0/3 to milestone

An agent is a loop: the model either calls a tool or gives a final answer, tool results are fed back, and the loop repeats until it's done.

Implement run_agent(model, tools, question, max_steps=5):

  • model(messages) returns a dict: either {"tool": name, "args": {...}} or {"answer": text}.
  • messages starts as [{"role": "user", "content": question}].
  • For a tool call, append {"role": "assistant", "tool": name, "args": args}, then run tools[name](**args) and append {"role": "tool", "name": name, "content": str(result)}.
    • Unknown tool → append a tool message with content "error: unknown tool <name>" instead.
    • If the tool raises, append "error: <ExceptionType>: <message>". Don't crash. The model can recover.
  • On an answer, append {"role": "assistant", "content": text} and return {"answer": text, "steps": n, "messages": messages}, where n is the number of model calls.
  • After max_steps model calls without an answer, return {"answer": None, "steps": max_steps, "messages": messages}.
#agents#tool-use#llm2 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Build a Mini Agent Loop · TechGradify