A stopping criterion determines when an agent’s iterative task execution ends. The loop continues through sub-steps until the task is complete or a limit—such as a maximum number of steps—is reached. Irrecoverable errors can also stop execution. section 1.3 section 4.2.3
In an LLMAgent, TaskHandler alternates between choosing the next step and running it. The run() method accepts max_steps; reaching that limit raises MaxStepsReachedError. section 4.2.3
Croissant search task
An agent searches for bakeries, analyzes prices and ratings, then concludes when it has enough information. A maximum-step limit provides another endpoint if execution continues. section 1.3
Listing 4.13 Implementing LLMAgent: run()
# llm_agents_from_scratch/agent/llm_agent.py
… #A
from llm_agents_from_scratch.errors import (
MaxStepsReachedError,
)
class LLMAgent:
… #B
def run(
self,
task: Task,
max_steps: int | None = None,
) -> TaskHandler:
"""Agent's processing loop for executing tasks."""
task_handler = self.TaskHandler( #C
llm_agent=self, task=task,
)
async def _process_loop() -> None: #D
"""The processing loop for task execution."""
step_result = None
while not task_handler.done():
try:
if task_handler.step_counter == max_steps: #E
raise MaxStepsReachedError("Max steps reached.")
# planning
next_step = (await
task_handler.get_next_step(step_result) #F
)
match next_step:
case TaskStep():
step_result = await task_handler.run_step( #G
next_step,
)
case TaskResult():
task_handler.set_result(next_step) #H
except Exception as e:
task_handler.set_exception(e) #I
task_handler.background_task = (
asyncio.create_task(_process_loop()) #J
)
return task_handlerSee the run() implementation’s maximum-step guard. section 4.2.3













