Implement a Minimal Agent Loop with Tool Calls

Free with account Updated Nov 16, 2026 · 6 min read
On this page

    Problem statement

    Implement a minimal agent loop. You get a function model(messages) that returns either a final text answer or a list of tool calls (each with an id, a tool name and JSON arguments), and a dictionary of Python tools. Keep calling the model, run the tools it asks for, feed the results back, and return the final answer. The loop must not run forever and must not crash when a tool fails.

    Example

    The model decides what to do next; the loop only runs tools, records results and enforces the step limit.
    The model decides what to do next; the loop only runs tools, records results and enforces the step limit.
    user:      Where is order A17?
    assistant: tool_calls: get_order(order_id="A17")   id=c1
    tool c1:   {"ok": {"status": "shipped", "carrier": "UPS"}}
    assistant: tool_calls: get_eta(carrier="UPS")      id=c2
    tool c2:   {"ok": "2 days"}
    assistant: Order A17 shipped with UPS and should arrive in 2 days.

    Constraints (assumed)

    • The model is a black box with the reply shape above (the same shape the big chat APIs use, simplified).
    • Tools are synchronous Python functions; arguments arrive as a dict.
    • One reply may contain several tool calls (parallel tool calls).
    • A step means one model call; max_steps defaults to 8.

    What this question tests

    • Whether you understand that an "agent" is just a loop: the model chooses, your code executes.
    • Message bookkeeping: roles, call ids, and sending the full history every turn.
    • Failure handling: tool errors, unknown tools, a model that never stops.
    • Production instincts: budgets, repeated-call detection, logging.

    Questions to ask first

    • What does the model return, and can one reply hold several tool calls?
    • Should tool errors stop the run or go back to the model?
    • What is the stop budget: steps, time, tokens or cost?
    • Do any tools have side effects (sending email, paying) that need a human approval step?