TaskHandler manages a submitted Task through an LLMAgent’s processing loop. It is an inner class of LLMAgent and an asyncio.Future that resolves to a TaskResult. LLMAgent.run() creates the handler, schedules the loop as a background asyncio.Task, and returns the handler so the caller can await it or check its status. section 4.2.1 section 4.5
The handler coordinates each sub-step and retains execution state:
- get_next_step(previous_step_result) returns the initial TaskStep from the task instruction, or decides whether to produce another TaskStep or the final TaskResult. section 4.2.3
- run_step(step) increments step_counter and executes the sub-step using the agent’s LLM and available tools. Tool-call requests are executed during this method. section 4.2.3 section 10.2.3
- rollout starts empty and accumulates formatted sub-step chat histories. It provides context for later steps and a record for inspection and evaluation. section 4.2.3 section 4.5
- The loop alternates between routing and execution until it obtains a TaskResult or encounters a stopping condition, such as an irrecoverable error or the maximum step count. section 4.2.3
Run a sequence task
Create a Task asking for the Hailstone sequence starting at 4, then call handler = llm_agent.run(task, max_steps=5). Await the handler, or check handler.done() before retrieving handler.result(). The demonstrated result is 4 → 2 → 1; handler.rollout exposes the steps and tool responses. section 4.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_handlerInspect how run() creates the handler and schedules its processing loop. section 4.2.3
The handler also provides integration points for task-level capabilities. Skill discovery runs at construction, producing a fresh registry for each run; by default, project-scoped skills take precedence over user-scoped skills with the same name. For episodic memory, load_memories() recalls from configured backends and supplies formatted memories to step system messages, while record_memory() writes an episode containing the task, rollout, and result or error. section 6.3.3 section 7.5.2
Optional result approval sends a proposed TaskResult to a human operator. Approval completes the task; rejection turns feedback into a new TaskStep and re-enters the loop. The approval prompt runs in a thread and auto-approves on EOF in a headless environment. section 8.3.1
For delegation, run_step() can expose catalogs and tools for local subagents or remote A2A agents. Subagents are fixed in the agent’s registry at construction, unlike skills discovered for each task run. Remote A2A dispatch occurs through a tool call within run_step(). section 9.2.3 section 10.2.3
