Agent loop and tool calling
medium 40 minAn agent is a loop.
See it run
Max wants their Friday train moved to Saturday. Watch the model propose and the harness decide.
Operations
One call, no tools
The model only has the words in front of it. It cannot look up a booking.
Step 1 of 3
The goal
- Sent to the model
- 40 tokens
Messages so far
user: move BK-7 to Saturday
Max writes: move booking BK-7 to Saturday. The harness sends this one message.
Step 1: The goal
reply = model(messages) # no tools offeredprint(reply.text) # sounds sure, may be invented- Model calls
- 1 call
- Tokens
- no facts
- Answer
- a guess
A model call reads text and writes text. Facts it was never given, it can only guess.
In the real world
The same agent loop and tool calling doing real jobs. Pick one and step through it.
The harness dies after the booking API moved the seat, before the result was saved.
Step 1 of 3
The change runs
Noor approved. The booking API moves BK-7 to Saturday, seat 22C.
Step 1: The change runs
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Letting the model run side effects directly
criticalThe model only proposes. If its words reach the payment API with no check in between, one bad sentence moves money.
Wrongexec(reply.text)Rightif c.name in ALLOWED and valid(c) and approved(c): run(c)No step or cost limit
criticalA model that keeps asking for tools keeps spending. Every extra call rereads the whole context.
Wrongwhile True: reply = model(messages)Rightfor step in range(MAX_STEPS): reply = model(messages)Crashing on a tool error
majorOne bad argument ends the run. Returned as text, the model can usually fix it in one step.
Wrongout = run(c) # raisesRighttry: out = run(c)except Exception as e: out = error_text(e)Dropping a result for a parallel call
majorEvery call ID needs a result in the next message, even for calls you skipped. Providers reject the request otherwise.
Wrongresults = [run(calls[0])]Rightresults = [result(c.id, run_or_error(c)) for c in calls]Putting a timestamp at the start of the prompt
minorThe prefix changes on every call, so the cache never hits and every step pays full price.
Wrongsystem = f"{now()} You change bookings..."Rightsystem = "You change bookings..." # time goes last
Interview tips
How to explain it
- The model proposes, the harness disposes.
- Loop: call, run tools, append, repeat.
- Stop on an answer or a budget.
Memory trick
- TOAST: Think, Order, Act, See, Stop.
- The balloon: slips, roll, sandbags, stamp.
- A note is not an order.
Always say
- Validate arguments against the schema.
- Errors go back as text.
- Approval and allowlists in code.
- One span per step, with tokens.
Numbers to know
- Input at call k: S + (k - 1) x d.
- Our example: 8 calls, 40,800 tokens.
- Cached reads: often 0.1x input price.
- OpenAI Agents SDK default: 10 turns.