The basic shape
public AgentResponse runLoop(String task, int maxIterations) {
String current = task;
for (int i = 0; i < maxIterations; i++) {
AgentResponse resp = agent.invoke(current);
if (isDone(resp)) {
return resp;
}
current = resp.text();
}
throw new LoopExhaustedException(maxIterations);
}Advertisement
Deciding &#x27;done&#x27;
The stopping condition can be model-driven ('does the agent say STOP?') or external ('does the output pass validation?'). External is more reliable — models forget to say STOP.
Advertisement
Always cap iterations
Never write an unbounded while(true) agent loop. Cap at 5-10 for most cases. Log when the cap is hit — that's diagnostic gold.