1818 TaskStepResult ,
1919 ToolCallResult ,
2020)
21- from llm_agents_from_scratch .errors import LLMAgentError , TaskHandlerError
21+ from llm_agents_from_scratch .errors import (
22+ LLMAgentError ,
23+ MaxStepsReachedError ,
24+ TaskHandlerError ,
25+ )
2226from llm_agents_from_scratch .logger import get_logger
2327
2428from .templates import TaskHandlerTemplates , default_task_handler_templates
@@ -344,11 +348,13 @@ async def run_step(self, step: TaskStep) -> TaskStepResult:
344348 content = final_content ,
345349 )
346350
347- def run (self , task : Task ) -> TaskHandler :
351+ def run (self , task : Task , max_steps : int | None = None ) -> TaskHandler :
348352 """Agent's processing loop for executing tasks.
349353
350354 Args:
351355 task (Task): the Task to perform.
356+ max_steps (int | None): Maximum number of steps to run for task.
357+ Defaults to None.
352358
353359 Returns:
354360 TaskHandler: the TaskHandler object responsible for task execution.
@@ -364,8 +370,12 @@ async def _process_loop() -> None:
364370 """
365371 self .logger .info (f"🚀 Starting task: { task .instruction } " )
366372 step_result = None
373+ ix = 0
367374 while not task_handler .done ():
368375 try :
376+ if max_steps and ix == max_steps :
377+ raise MaxStepsReachedError ("Max steps reached." )
378+
369379 next_step = await task_handler .get_next_step (step_result )
370380
371381 match next_step :
@@ -386,6 +396,8 @@ async def _process_loop() -> None:
386396
387397 except Exception as e :
388398 task_handler .set_exception (e )
399+ finally :
400+ ix += 1
389401
390402 task_handler .background_task = asyncio .create_task (_process_loop ())
391403
0 commit comments