A teammate built an appointment-scheduling agent for a dental practice. The agentic loop terminates when the assistant's text contains the word "scheduled" or "done". It works most of the time. But occasionally the agent says "I'll need to verify if this date is done being held by another patient" mid-process — and the loop exits before the appointment is actually booked.
What is the correct fix?
Why did you pick that answer? Two or three sentences. The act of articulating it is what builds the judgment — not the click that follows.
The agentic loop has a documented control signal: stop_reason. When the model still wants to act, it returns "tool_use"; when it considers the turn complete, it returns "end_turn". Parsing the assistant's natural-language text to decide whether to continue the loop is one of the most common anti-patterns in agentic systems — language is ambiguous, and the model isn't talking to your loop controller, it's talking to the user. Use the structured signal that exists for this purpose.
This is the genuinely tempting answer because it engages with the actual failure — the regex is matching too eagerly, and a tighter pattern would fix this specific case. But it leaves the architecture wrong: you're still inferring loop control from natural language, just with more brittle rules. The next failure mode ("the appointment was scheduled, but we still need to verify…") will require another regex round, and the round after that. Use the structured signal the platform provides instead of building an arms race against the model's prose.
A max_iterations cap is a safety net against runaway loops, not a primary stopping mechanism. Using it as the main control means every successful run hits the cap or terminates somewhere arbitrary. The stop_reason field exists precisely so you don't have to guess.
Reinventing a control signal that already exists adds fragility (the model has to remember to emit your special token; what if it forgets?) without adding any reliability over stop_reason. Use the documented mechanism.