Blog/Learn Agentic AI Development/Reference Implementation: The Python Modules

Chapter 13 / 20 min read

Reference Implementation: The Python Modules

Consolidated code listings for enums, Pydantic schemas, tool registry, tool definitions, executor, step execution and dependency checks.

Reference implementation: the important Python modules

This appendix collects the central code contracts from the project in one place. It consolidates the implementation patterns and identifies corrections where an earlier version contained a known issue. The complete end-to-end orchestrator is not yet finished.

1. Status enums — models/enums.py

Code
from enum import Enum

class ExecutionStatus(Enum):
    PENDING = "PENDING"
    RUNNING = "RUNNING"
    SUCCESS = "SUCCESS"
    FAILED = "FAILED"
    SKIPPED = "SKIPPED"


class TaskStatus(Enum):
    PENDING = "PENDING"
    RUNNING = "RUNNING"
    COMPLETED = "COMPLETED"
    INCOMPLETE = "INCOMPLETE"
    FAILED = "FAILED"
    PAUSED = "PAUSED"
    CANCELLED = "CANCELLED"
    LIMIT_REACHED = "LIMIT_REACHED"


class BusinessOutcomeStatus(Enum):
    PENDING = "PENDING"
    SUCCESS = "SUCCESS"
    PARTIAL_SUCCESS = "PARTIAL_SUCCESS"
    FAILED = "FAILED"
    NOT_APPLICABLE = "NOT_APPLICABLE"


class LLMResponseStatus(Enum):
    IN_PROGRESS = "IN_PROGRESS"
    COMPLETED = "COMPLETED"
    ERROR = "ERROR"


class StepStatus(Enum):
    PENDING = "PENDING"
    RUNNING = "RUNNING"
    COMPLETED = "COMPLETED"
    FAILED = "FAILED"
    BLOCKED = "BLOCKED"

The implementation uses StepStatus.PENDING, RUNNING, COMPLETED, FAILED and BLOCKED to represent the lifecycle of a step. Centralizing these values in an enum is safer than manually typing status strings throughout the application.

2. Pydantic models — models/schemas.py

The following section brings the project's schemas together:

Code
from pydantic import BaseModel, ConfigDict, Field
from models.enums import StepStatus


class StrictInput(BaseModel):
    model_config = ConfigDict(
        extra="forbid",
        strict=True,
    )


class SearchInput(StrictInput):
    query: str = Field(
        min_length=3,
        max_length=300,
        description="The search query string.",
    )
    max_results: int = Field(
        default=5,
        ge=1,
        le=10,
    )


class SaveReportInput(StrictInput):
    filename: str = Field(
        min_length=1,
        max_length=100,
    )
    report_markdown: str = Field(
        min_length=50,
        max_length=20000,
    )


class MultiplyInput(StrictInput):
    a: float = Field(description="The first number to multiply.")
    b: float = Field(description="The second number to multiply.")


class AdditionInput(StrictInput):
    a: float = Field(description="The first number to add.")
    b: float = Field(description="The second number to add.")


class DivideInput(StrictInput):
    a: float = Field(description="The numerator.")
    b: float = Field(description="The denominator.")


class TaskStep(StrictInput):
    step_id: int = Field(
        description="The unique identifier for the step."
    )
    tool_name: str = Field(
        description="The name of the tool to be executed for this step."
    )
    arguments: dict[str, object] = Field(
        description="The arguments required for the tool execution."
    )
    depends_on: list[int] = Field(
        default_factory=list,
        description="Step IDs that must complete before this step.",
    )
    status: StepStatus = Field(
        default=StepStatus.PENDING
    )

The arguments field uses a dictionary, which can hold any number of named values. The more explicit dict[str, object] annotation communicates that keys are strings and values may be different Python data types.

The original draft used default=[] for depends_on. This reference uses default_factory=list, avoiding a shared mutable default.

3. Tool registry — tool_registry.py

Code
from tools.calculator import (
    calculate_addition,
    multiply_numbers,
    divide_numbers,
)

TOOL_REGISTRY = {
    "calculate_addition": calculate_addition,
    "multiply_numbers": multiply_numbers,
    "divide_numbers": divide_numbers,
}

4. Tool definitions — tool_definitions.py

Code
from models.schemas import (
    AdditionInput,
    DivideInput,
    MultiplyInput,
)

MULTIPLY_NUMBERS_TOOL = {
    "name": "multiply_numbers",
    "description": "Multiplies two numbers and returns the result.",
    "parameters": MultiplyInput.model_json_schema(),
}

ADDITION_TOOL = {
    "name": "calculate_addition",
    "description": "Adds two numbers and returns the result.",
    "parameters": AdditionInput.model_json_schema(),
}

DIVIDE_NUMBERS_TOOL = {
    "name": "divide_numbers",
    "description": "Divides two numbers and returns the result.",
    "parameters": DivideInput.model_json_schema(),
}

TOOL_DEFINITIONS = [
    MULTIPLY_NUMBERS_TOOL,
    ADDITION_TOOL,
    DIVIDE_NUMBERS_TOOL,
]

5. Tool execution — tool_executor.py

The executor acts as a validation-and-execution boundary rather than merely looking up a function in the registry. Its essential sequence is shown below:

Code
from pydantic import ValidationError
from models.schemas import (
    AdditionInput,
    DivideInput,
    MultiplyInput,
)
from tool_registry import TOOL_REGISTRY

TOOL_SCHEMAS = {
    "calculate_addition": AdditionInput,
    "multiply_numbers": MultiplyInput,
    "divide_numbers": DivideInput,
}


def execute_tool(
    tool_name: str,
    tool_arguments: dict,
) -> dict:
    tool = TOOL_REGISTRY.get(tool_name)
    schema = TOOL_SCHEMAS.get(tool_name)

    if tool is None or schema is None:
        return {
            "success": False,
            "error": f"Tool '{tool_name}' is not registered.",
        }

    try:
        validated = schema.model_validate(tool_arguments)
        arguments = validated.model_dump()
        return tool(**arguments)
    except ValidationError as exc:
        return {
            "success": False,
            "error": "Tool arguments failed validation.",
            "details": exc.errors(),
        }
    except Exception as exc:
        return {
            "success": False,
            "error": str(exc),
        }

This is a consolidated, hardened example of the architecture developed in the project. It brings together the tool registry, Pydantic validation and executor boundary. The complete listing is an explanatory consolidation, not a claim that this exact version was tested as one final file.

6. Step execution — orchestration/step_executor.py

The step-execution implementation follows this pattern:

Code
from models.enums import StepStatus
from models.schemas import TaskStep
from tool_executor import execute_tool


def execute_step(step: TaskStep) -> dict:
    """
    Executes a given task step and returns the result.

    Args:
        step: The TaskStep instance to be executed.

    Returns:
        A dictionary keyed by step ID containing the execution result.
    """
    step_tool_name = step.tool_name
    step_arguments = step.arguments

    step.status = StepStatus.RUNNING

    try:
        execution_result = execute_tool(
            tool_name=step_tool_name,
            tool_arguments=step_arguments,
        )

        if execution_result.get("success"):
            step.status = StepStatus.COMPLETED
        else:
            step.status = StepStatus.FAILED

    except Exception as exc:
        step.status = StepStatus.FAILED
        execution_result = {
            "success": False,
            "error": str(exc),
        }

    return {step.step_id: execution_result}

During debugging, the status initially remained PENDING because the code updated a different variable or assigned a value inconsistently. Once the same TaskStep instance was updated inside execute_step, the observed statuses became:

Code
Successful addition:
Execution result: {1: {'success': True, ... 'result': 30.0}}
Final status: StepStatus.COMPLETED

Division by zero:
Execution result: {1: {'success': False, ...}}
Final status: StepStatus.FAILED

7. Dependency check — orchestration/dependency_resolver.py

The step-execution implementation:

Code
from models.enums import StepStatus
from models.schemas import TaskStep


def are_dependencies_satisfied(
    current_step: TaskStep,
    task_steps: list[TaskStep],
) -> bool:
    """
    Checks if all dependencies for the current step are satisfied.

    A dependency is considered satisfied if the corresponding
    step has a status of COMPLETED.

    Raises:
        ValueError: If any dependency step is missing.
    """
    dependency_ids = current_step.depends_on

    dependency_steps = [
        step
        for step in task_steps
        if step.step_id in dependency_ids
    ]

    available_step_ids = {
        step.step_id
        for step in task_steps
    }

    missing_ids = [
        dep_id
        for dep_id in dependency_ids
        if dep_id not in available_step_ids
    ]

    if missing_ids:
        raise ValueError(
            f"Missing dependencies for step "
            f"{current_step.step_id}: {missing_ids}"
        )

    return all(
        dependency.status == StepStatus.COMPLETED
        for dependency in dependency_steps
    )

Six dependency tests were used, including a case with a missing dependency ID 99. The function raised a ValueError for that case instead of treating the missing dependency as satisfied.

8. What is still not one complete program?

These listings show the key building blocks, but the final orchestration integration remains unfinished. In particular, resolve_arguments() has been implemented but is not yet called by a complete loop that plans, resolves, validates, executes and stores each step.

That is the honest boundary of the project at the end of the recorded work.