Skip to content

API Reference

OpenSymbolicAI Core Runtime.

CheckpointStatus

Bases: str, Enum

Status of an execution checkpoint.

Source code in src/opensymbolicai/checkpoint.py
class CheckpointStatus(str, Enum):
    """Status of an execution checkpoint."""

    PENDING = "pending"  # Not yet started
    RUNNING = "running"  # Currently executing
    PAUSED = "paused"  # Manually paused
    AWAITING_APPROVAL = "awaiting_approval"  # Waiting for mutation approval
    COMPLETED = "completed"  # Successfully finished
    FAILED = "failed"  # Execution failed

CheckpointStore

Bases: Protocol

Protocol for checkpoint storage backends.

Implement this protocol to store checkpoints in your preferred backend (PostgreSQL, Redis, MongoDB, filesystem, etc.).

Example

class RedisCheckpointStore: def init(self, redis_client): self.redis = redis_client

def save(self, checkpoint: ExecutionCheckpoint) -> None:
    self.redis.set(
        f"checkpoint:{checkpoint.checkpoint_id}",
        checkpoint.model_dump_json()
    )

def load(self, checkpoint_id: str) -> ExecutionCheckpoint | None:
    data = self.redis.get(f"checkpoint:{checkpoint_id}")
    if data:
        return ExecutionCheckpoint.model_validate_json(data)
    return None

def delete(self, checkpoint_id: str) -> None:
    self.redis.delete(f"checkpoint:{checkpoint_id}")

def list_by_status(self, status: CheckpointStatus) -> list[str]:
    # Implementation depends on your indexing strategy
    ...
Source code in src/opensymbolicai/checkpoint.py
@runtime_checkable
class CheckpointStore(Protocol):
    """Protocol for checkpoint storage backends.

    Implement this protocol to store checkpoints in your preferred backend
    (PostgreSQL, Redis, MongoDB, filesystem, etc.).

    Example:
        class RedisCheckpointStore:
            def __init__(self, redis_client):
                self.redis = redis_client

            def save(self, checkpoint: ExecutionCheckpoint) -> None:
                self.redis.set(
                    f"checkpoint:{checkpoint.checkpoint_id}",
                    checkpoint.model_dump_json()
                )

            def load(self, checkpoint_id: str) -> ExecutionCheckpoint | None:
                data = self.redis.get(f"checkpoint:{checkpoint_id}")
                if data:
                    return ExecutionCheckpoint.model_validate_json(data)
                return None

            def delete(self, checkpoint_id: str) -> None:
                self.redis.delete(f"checkpoint:{checkpoint_id}")

            def list_by_status(self, status: CheckpointStatus) -> list[str]:
                # Implementation depends on your indexing strategy
                ...
    """

    def save(self, checkpoint: ExecutionCheckpoint) -> None:
        """Save a checkpoint to storage."""
        ...

    def load(self, checkpoint_id: str) -> ExecutionCheckpoint | None:
        """Load a checkpoint from storage. Returns None if not found."""
        ...

    def delete(self, checkpoint_id: str) -> None:
        """Delete a checkpoint from storage."""
        ...

    def list_by_status(self, status: CheckpointStatus) -> list[str]:
        """List checkpoint IDs with the given status."""
        ...

delete(checkpoint_id)

Delete a checkpoint from storage.

Source code in src/opensymbolicai/checkpoint.py
def delete(self, checkpoint_id: str) -> None:
    """Delete a checkpoint from storage."""
    ...

list_by_status(status)

List checkpoint IDs with the given status.

Source code in src/opensymbolicai/checkpoint.py
def list_by_status(self, status: CheckpointStatus) -> list[str]:
    """List checkpoint IDs with the given status."""
    ...

load(checkpoint_id)

Load a checkpoint from storage. Returns None if not found.

Source code in src/opensymbolicai/checkpoint.py
def load(self, checkpoint_id: str) -> ExecutionCheckpoint | None:
    """Load a checkpoint from storage. Returns None if not found."""
    ...

save(checkpoint)

Save a checkpoint to storage.

Source code in src/opensymbolicai/checkpoint.py
def save(self, checkpoint: ExecutionCheckpoint) -> None:
    """Save a checkpoint to storage."""
    ...

ExecutionCheckpoint

Bases: BaseModel

Serializable execution state for pause/resume across distributed workers.

Source code in src/opensymbolicai/checkpoint.py
class ExecutionCheckpoint(BaseModel):
    """Serializable execution state for pause/resume across distributed workers."""

    # Identity
    checkpoint_id: str = Field(
        default_factory=lambda: str(uuid.uuid4()),
        description="Unique checkpoint identifier",
    )
    task: str = Field(..., description="The original task description")
    plan: str = Field(..., description="The Python plan being executed")

    # Plan generation context (LLM history)
    plan_context: PlanContext | None = Field(
        default=None,
        description="Full context of how the plan was generated, including LLM interactions",
    )

    # Execution progress
    current_step: int = Field(default=0, description="Next step to execute (0-indexed)")
    total_steps: int = Field(..., description="Total number of steps in the plan")
    status: CheckpointStatus = Field(
        default=CheckpointStatus.PENDING, description="Current execution status"
    )

    # State
    namespace_snapshot: dict[str, SerializedValue] = Field(
        default_factory=dict,
        description="Serialized namespace variables",
    )
    completed_steps: list[ExecutionStep] = Field(
        default_factory=list, description="Steps that have been executed"
    )

    # Mutation approval
    pending_mutation: PendingMutation | None = Field(
        default=None,
        description="Mutation awaiting approval (if status is awaiting_approval)",
    )

    # Error tracking
    error: str | None = Field(
        default=None, description="Error message if status is failed"
    )

    # Metadata
    created_at: datetime = Field(
        default_factory=lambda: datetime.now(UTC),
        description="When the checkpoint was created",
    )
    updated_at: datetime = Field(
        default_factory=lambda: datetime.now(UTC),
        description="When the checkpoint was last updated",
    )
    worker_id: str | None = Field(
        default=None, description="ID of the worker that created/last updated this"
    )

    # Result (when completed)
    result_value: SerializedValue | None = Field(
        default=None, description="The final result value (when status is completed)"
    )
    result_variable: str = Field(
        default="", description="Name of the variable containing the result"
    )

    def touch(self, worker_id: str | None = None) -> None:
        """Update the updated_at timestamp and optionally worker_id."""
        self.updated_at = datetime.now(UTC)
        if worker_id is not None:
            self.worker_id = worker_id

    @property
    def is_resumable(self) -> bool:
        """Check if this checkpoint can be resumed."""
        return self.status in (
            CheckpointStatus.PENDING,
            CheckpointStatus.RUNNING,
            CheckpointStatus.PAUSED,
            CheckpointStatus.AWAITING_APPROVAL,
        )

    @property
    def is_terminal(self) -> bool:
        """Check if this checkpoint is in a terminal state."""
        return self.status in (CheckpointStatus.COMPLETED, CheckpointStatus.FAILED)

    @property
    def progress_fraction(self) -> float:
        """Get execution progress as a fraction (0.0 to 1.0)."""
        if self.total_steps == 0:
            return 0.0
        return self.current_step / self.total_steps

    model_config = {"arbitrary_types_allowed": True}

is_resumable property

Check if this checkpoint can be resumed.

is_terminal property

Check if this checkpoint is in a terminal state.

progress_fraction property

Get execution progress as a fraction (0.0 to 1.0).

touch(worker_id=None)

Update the updated_at timestamp and optionally worker_id.

Source code in src/opensymbolicai/checkpoint.py
def touch(self, worker_id: str | None = None) -> None:
    """Update the updated_at timestamp and optionally worker_id."""
    self.updated_at = datetime.now(UTC)
    if worker_id is not None:
        self.worker_id = worker_id

ExecutionError

Bases: Exception

Base exception for all primitive execution errors.

This is the root of the exception hierarchy. All custom exceptions should inherit from this class. When raised in a primitive, execution will stop and the error details will be captured in the execution trace.

Attributes:

Name Type Description
message

Human-readable error message.

code

Optional error code for programmatic handling.

details

Optional dictionary with additional context.

halt_execution

Whether this exception should stop plan execution.

Source code in src/opensymbolicai/exceptions.py
class ExecutionError(Exception):
    """Base exception for all primitive execution errors.

    This is the root of the exception hierarchy. All custom exceptions
    should inherit from this class. When raised in a primitive, execution
    will stop and the error details will be captured in the execution trace.

    Attributes:
        message: Human-readable error message.
        code: Optional error code for programmatic handling.
        details: Optional dictionary with additional context.
        halt_execution: Whether this exception should stop plan execution.
    """

    def __init__(
        self,
        message: str,
        *,
        code: str | None = None,
        details: dict[str, Any] | None = None,
        halt_execution: bool = True,
    ) -> None:
        """Initialize the exception.

        Args:
            message: Human-readable error message.
            code: Optional error code for programmatic handling (e.g., "INVALID_INPUT").
            details: Optional dictionary with additional context about the error.
            halt_execution: Whether this exception should stop plan execution.
                           Defaults to True.
        """
        super().__init__(message)
        self.message = message
        self.code = code
        self.details = details or {}
        self.halt_execution = halt_execution

    def __str__(self) -> str:
        """Return string representation of the exception."""
        parts = [self.message]
        if self.code:
            parts.insert(0, f"[{self.code}]")
        return " ".join(parts)

    def __repr__(self) -> str:
        """Return detailed representation of the exception."""
        return (
            f"{self.__class__.__name__}("
            f"message={self.message!r}, "
            f"code={self.code!r}, "
            f"details={self.details!r}, "
            f"halt_execution={self.halt_execution!r})"
        )

    def to_dict(self) -> dict[str, Any]:
        """Convert exception to a dictionary for serialization.

        Returns:
            Dictionary containing all exception attributes.
        """
        return {
            "type": self.__class__.__name__,
            "message": self.message,
            "code": self.code,
            "details": self.details,
            "halt_execution": self.halt_execution,
        }

__init__(message, *, code=None, details=None, halt_execution=True)

Initialize the exception.

Parameters:

Name Type Description Default
message str

Human-readable error message.

required
code str | None

Optional error code for programmatic handling (e.g., "INVALID_INPUT").

None
details dict[str, Any] | None

Optional dictionary with additional context about the error.

None
halt_execution bool

Whether this exception should stop plan execution. Defaults to True.

True
Source code in src/opensymbolicai/exceptions.py
def __init__(
    self,
    message: str,
    *,
    code: str | None = None,
    details: dict[str, Any] | None = None,
    halt_execution: bool = True,
) -> None:
    """Initialize the exception.

    Args:
        message: Human-readable error message.
        code: Optional error code for programmatic handling (e.g., "INVALID_INPUT").
        details: Optional dictionary with additional context about the error.
        halt_execution: Whether this exception should stop plan execution.
                       Defaults to True.
    """
    super().__init__(message)
    self.message = message
    self.code = code
    self.details = details or {}
    self.halt_execution = halt_execution

__repr__()

Return detailed representation of the exception.

Source code in src/opensymbolicai/exceptions.py
def __repr__(self) -> str:
    """Return detailed representation of the exception."""
    return (
        f"{self.__class__.__name__}("
        f"message={self.message!r}, "
        f"code={self.code!r}, "
        f"details={self.details!r}, "
        f"halt_execution={self.halt_execution!r})"
    )

__str__()

Return string representation of the exception.

Source code in src/opensymbolicai/exceptions.py
def __str__(self) -> str:
    """Return string representation of the exception."""
    parts = [self.message]
    if self.code:
        parts.insert(0, f"[{self.code}]")
    return " ".join(parts)

to_dict()

Convert exception to a dictionary for serialization.

Returns:

Type Description
dict[str, Any]

Dictionary containing all exception attributes.

Source code in src/opensymbolicai/exceptions.py
def to_dict(self) -> dict[str, Any]:
    """Convert exception to a dictionary for serialization.

    Returns:
        Dictionary containing all exception attributes.
    """
    return {
        "type": self.__class__.__name__,
        "message": self.message,
        "code": self.code,
        "details": self.details,
        "halt_execution": self.halt_execution,
    }

ExecutionMetrics

Bases: BaseModel

Metrics from a complete orchestration run.

Source code in src/opensymbolicai/models.py
class ExecutionMetrics(BaseModel):
    """Metrics from a complete orchestration run."""

    plan_tokens: TokenUsage = Field(
        default_factory=TokenUsage, description="Tokens used for planning"
    )
    plan_time_seconds: float = Field(default=0.0, description="Time for planning")
    execute_time_seconds: float = Field(default=0.0, description="Time for execution")
    steps_executed: int = Field(default=0, description="Number of steps executed")
    provider: str = Field(default="", description="LLM provider used")
    model: str = Field(default="", description="Model used")

    @property
    def total_time_seconds(self) -> float:
        """Total time for planning and execution."""
        return self.plan_time_seconds + self.execute_time_seconds

total_time_seconds property

Total time for planning and execution.

ExecutionResult

Bases: BaseModel

Result from executing a plan.

Source code in src/opensymbolicai/models.py
class ExecutionResult(BaseModel):
    """Result from executing a plan."""

    value_type: str = Field(..., description="Python type name of the result")
    value_name: str = Field(default="", description="Variable name of the result")
    value_json: str = Field(default="null", description="JSON-serialized value")
    trace: ExecutionTrace = Field(
        default_factory=ExecutionTrace, description="Step-by-step execution trace"
    )

    def get_value(self) -> Any:
        """Deserialize and return the actual value."""
        return json.loads(self.value_json)

get_value()

Deserialize and return the actual value.

Source code in src/opensymbolicai/models.py
def get_value(self) -> Any:
    """Deserialize and return the actual value."""
    return json.loads(self.value_json)

ExecutionStep

Bases: BaseModel

A single step in plan execution.

Source code in src/opensymbolicai/models.py
class ExecutionStep(BaseModel):
    """A single step in plan execution."""

    step_number: int = Field(..., description="1-based step number")
    statement: str = Field(..., description="The Python statement executed")
    variable_name: str = Field(default="", description="Variable being assigned")
    primitive_called: str | None = Field(
        default=None, description="Name of primitive method called"
    )
    args: dict[str, ArgumentValue] = Field(
        default_factory=dict,
        description="Arguments passed to the primitive with both expression and resolved value",
    )
    namespace_before: dict[str, Any] = Field(
        default_factory=dict, description="Namespace snapshot before execution"
    )
    namespace_after: dict[str, Any] = Field(
        default_factory=dict, description="Namespace snapshot after execution"
    )
    result_type: str = Field(default="", description="Type of the result")
    result_value: Any = Field(default=None, description="The computed value")
    result_json: str = Field(default="null", description="JSON-serialized result")
    time_seconds: float = Field(default=0.0, description="Time taken for this step")
    success: bool = Field(default=True, description="Whether the step succeeded")
    error: str | None = Field(default=None, description="Error message if failed")

    model_config = {"arbitrary_types_allowed": True}

ExecutionTrace

Bases: BaseModel

Complete trace of plan execution.

Source code in src/opensymbolicai/models.py
class ExecutionTrace(BaseModel):
    """Complete trace of plan execution."""

    steps: list[ExecutionStep] = Field(
        default_factory=list, description="All executed steps"
    )
    total_time_seconds: float = Field(default=0.0, description="Total execution time")

    @property
    def step_count(self) -> int:
        """Number of steps executed."""
        return len(self.steps)

    @property
    def successful_steps(self) -> list[ExecutionStep]:
        """Get all successful steps."""
        return [s for s in self.steps if s.success]

    @property
    def failed_steps(self) -> list[ExecutionStep]:
        """Get all failed steps."""
        return [s for s in self.steps if not s.success]

    @property
    def all_succeeded(self) -> bool:
        """Check if all steps succeeded."""
        return all(s.success for s in self.steps)

    @property
    def last_step(self) -> ExecutionStep | None:
        """Get the last executed step."""
        return self.steps[-1] if self.steps else None

    @property
    def primitives_called(self) -> list[str]:
        """Get list of all primitives called."""
        return [s.primitive_called for s in self.steps if s.primitive_called]

all_succeeded property

Check if all steps succeeded.

failed_steps property

Get all failed steps.

last_step property

Get the last executed step.

primitives_called property

Get list of all primitives called.

step_count property

Number of steps executed.

successful_steps property

Get all successful steps.

FileCheckpointStore

File-based checkpoint store for simple persistence.

Source code in src/opensymbolicai/checkpoint.py
class FileCheckpointStore:
    """File-based checkpoint store for simple persistence."""

    def __init__(self, directory: str) -> None:
        """Initialize with a directory path for storing checkpoints.

        Args:
            directory: Path to directory where checkpoint JSON files are stored.
        """
        import os

        self.directory = directory
        os.makedirs(directory, exist_ok=True)

    def _path(self, checkpoint_id: str) -> str:
        import os

        # Sanitize checkpoint_id to prevent path traversal
        safe_id = "".join(c for c in checkpoint_id if c.isalnum() or c in "-_")
        return os.path.join(self.directory, f"{safe_id}.json")

    def save(self, checkpoint: ExecutionCheckpoint) -> None:
        """Save a checkpoint to a JSON file."""
        checkpoint.touch()
        with open(self._path(checkpoint.checkpoint_id), "w") as f:
            f.write(checkpoint.model_dump_json(indent=2))

    def load(self, checkpoint_id: str) -> ExecutionCheckpoint | None:
        """Load a checkpoint from a JSON file."""
        import os

        path = self._path(checkpoint_id)
        if not os.path.exists(path):
            return None
        with open(path) as f:
            return ExecutionCheckpoint.model_validate_json(f.read())

    def delete(self, checkpoint_id: str) -> None:
        """Delete a checkpoint file."""
        import os

        path = self._path(checkpoint_id)
        if os.path.exists(path):
            os.remove(path)

    def list_by_status(self, status: CheckpointStatus) -> list[str]:
        """List checkpoint IDs with the given status."""
        import os

        result = []
        for filename in os.listdir(self.directory):
            if filename.endswith(".json"):
                checkpoint_id = filename[:-5]
                checkpoint = self.load(checkpoint_id)
                if checkpoint and checkpoint.status == status:
                    result.append(checkpoint_id)
        return result

    def list_all(self) -> list[str]:
        """List all checkpoint IDs."""
        import os

        return [f[:-5] for f in os.listdir(self.directory) if f.endswith(".json")]

__init__(directory)

Initialize with a directory path for storing checkpoints.

Parameters:

Name Type Description Default
directory str

Path to directory where checkpoint JSON files are stored.

required
Source code in src/opensymbolicai/checkpoint.py
def __init__(self, directory: str) -> None:
    """Initialize with a directory path for storing checkpoints.

    Args:
        directory: Path to directory where checkpoint JSON files are stored.
    """
    import os

    self.directory = directory
    os.makedirs(directory, exist_ok=True)

delete(checkpoint_id)

Delete a checkpoint file.

Source code in src/opensymbolicai/checkpoint.py
def delete(self, checkpoint_id: str) -> None:
    """Delete a checkpoint file."""
    import os

    path = self._path(checkpoint_id)
    if os.path.exists(path):
        os.remove(path)

list_all()

List all checkpoint IDs.

Source code in src/opensymbolicai/checkpoint.py
def list_all(self) -> list[str]:
    """List all checkpoint IDs."""
    import os

    return [f[:-5] for f in os.listdir(self.directory) if f.endswith(".json")]

list_by_status(status)

List checkpoint IDs with the given status.

Source code in src/opensymbolicai/checkpoint.py
def list_by_status(self, status: CheckpointStatus) -> list[str]:
    """List checkpoint IDs with the given status."""
    import os

    result = []
    for filename in os.listdir(self.directory):
        if filename.endswith(".json"):
            checkpoint_id = filename[:-5]
            checkpoint = self.load(checkpoint_id)
            if checkpoint and checkpoint.status == status:
                result.append(checkpoint_id)
    return result

load(checkpoint_id)

Load a checkpoint from a JSON file.

Source code in src/opensymbolicai/checkpoint.py
def load(self, checkpoint_id: str) -> ExecutionCheckpoint | None:
    """Load a checkpoint from a JSON file."""
    import os

    path = self._path(checkpoint_id)
    if not os.path.exists(path):
        return None
    with open(path) as f:
        return ExecutionCheckpoint.model_validate_json(f.read())

save(checkpoint)

Save a checkpoint to a JSON file.

Source code in src/opensymbolicai/checkpoint.py
def save(self, checkpoint: ExecutionCheckpoint) -> None:
    """Save a checkpoint to a JSON file."""
    checkpoint.touch()
    with open(self._path(checkpoint.checkpoint_id), "w") as f:
        f.write(checkpoint.model_dump_json(indent=2))

InMemoryCheckpointStore

In-memory checkpoint store for testing and development.

Source code in src/opensymbolicai/checkpoint.py
class InMemoryCheckpointStore:
    """In-memory checkpoint store for testing and development."""

    def __init__(self) -> None:
        self._checkpoints: dict[str, ExecutionCheckpoint] = {}

    def save(self, checkpoint: ExecutionCheckpoint) -> None:
        """Save a checkpoint to memory."""
        checkpoint.touch()
        # Store a copy to prevent mutation issues
        self._checkpoints[checkpoint.checkpoint_id] = checkpoint.model_copy(deep=True)

    def load(self, checkpoint_id: str) -> ExecutionCheckpoint | None:
        """Load a checkpoint from memory."""
        cp = self._checkpoints.get(checkpoint_id)
        if cp:
            return cp.model_copy(deep=True)
        return None

    def delete(self, checkpoint_id: str) -> None:
        """Delete a checkpoint from memory."""
        self._checkpoints.pop(checkpoint_id, None)

    def list_by_status(self, status: CheckpointStatus) -> list[str]:
        """List checkpoint IDs with the given status."""
        return [
            cp.checkpoint_id for cp in self._checkpoints.values() if cp.status == status
        ]

    def list_all(self) -> list[str]:
        """List all checkpoint IDs."""
        return list(self._checkpoints.keys())

    def clear(self) -> None:
        """Clear all checkpoints."""
        self._checkpoints.clear()

clear()

Clear all checkpoints.

Source code in src/opensymbolicai/checkpoint.py
def clear(self) -> None:
    """Clear all checkpoints."""
    self._checkpoints.clear()

delete(checkpoint_id)

Delete a checkpoint from memory.

Source code in src/opensymbolicai/checkpoint.py
def delete(self, checkpoint_id: str) -> None:
    """Delete a checkpoint from memory."""
    self._checkpoints.pop(checkpoint_id, None)

list_all()

List all checkpoint IDs.

Source code in src/opensymbolicai/checkpoint.py
def list_all(self) -> list[str]:
    """List all checkpoint IDs."""
    return list(self._checkpoints.keys())

list_by_status(status)

List checkpoint IDs with the given status.

Source code in src/opensymbolicai/checkpoint.py
def list_by_status(self, status: CheckpointStatus) -> list[str]:
    """List checkpoint IDs with the given status."""
    return [
        cp.checkpoint_id for cp in self._checkpoints.values() if cp.status == status
    ]

load(checkpoint_id)

Load a checkpoint from memory.

Source code in src/opensymbolicai/checkpoint.py
def load(self, checkpoint_id: str) -> ExecutionCheckpoint | None:
    """Load a checkpoint from memory."""
    cp = self._checkpoints.get(checkpoint_id)
    if cp:
        return cp.model_copy(deep=True)
    return None

save(checkpoint)

Save a checkpoint to memory.

Source code in src/opensymbolicai/checkpoint.py
def save(self, checkpoint: ExecutionCheckpoint) -> None:
    """Save a checkpoint to memory."""
    checkpoint.touch()
    # Store a copy to prevent mutation issues
    self._checkpoints[checkpoint.checkpoint_id] = checkpoint.model_copy(deep=True)

MethodType

Bases: Enum

Classification of agent methods.

Source code in src/opensymbolicai/core.py
class MethodType(Enum):
    """Classification of agent methods."""

    PRIMITIVE = "primitive"
    DECOMPOSITION = "decomposition"

MutationHookContext

Bases: BaseModel

Context passed to mutation hooks when a non-read-only primitive is called.

Source code in src/opensymbolicai/models.py
class MutationHookContext(BaseModel):
    """Context passed to mutation hooks when a non-read-only primitive is called."""

    method_name: str = Field(..., description="Name of the primitive method called")
    args: dict[str, Any] = Field(
        default_factory=dict, description="Arguments passed to the method"
    )
    result: Any = Field(default=None, description="Result returned by the method")
    step: ExecutionStep | None = Field(
        default=None, description="The execution step containing full details"
    )

    model_config = {"arbitrary_types_allowed": True}

OperationError

Bases: ExecutionError

Exception raised when an operation fails during execution.

Use this for runtime errors that occur during the actual operation, not input validation.

Example

raise OperationError( "File write failed", code="WRITE_FAILED", details={"path": "/tmp/output.txt", "reason": "disk full"} )

Source code in src/opensymbolicai/exceptions.py
class OperationError(ExecutionError):
    """Exception raised when an operation fails during execution.

    Use this for runtime errors that occur during the actual operation,
    not input validation.

    Example:
        raise OperationError(
            "File write failed",
            code="WRITE_FAILED",
            details={"path": "/tmp/output.txt", "reason": "disk full"}
        )
    """

    def __init__(
        self,
        message: str,
        *,
        code: str | None = "OPERATION_ERROR",
        details: dict[str, Any] | None = None,
        operation: str | None = None,
    ) -> None:
        """Initialize operation error.

        Args:
            message: Human-readable error message.
            code: Error code, defaults to "OPERATION_ERROR".
            details: Additional context about the error.
            operation: Optional name of the operation that failed.
        """
        if operation:
            details = details or {}
            details["operation"] = operation
        super().__init__(message, code=code, details=details)
        self.operation = operation

__init__(message, *, code='OPERATION_ERROR', details=None, operation=None)

Initialize operation error.

Parameters:

Name Type Description Default
message str

Human-readable error message.

required
code str | None

Error code, defaults to "OPERATION_ERROR".

'OPERATION_ERROR'
details dict[str, Any] | None

Additional context about the error.

None
operation str | None

Optional name of the operation that failed.

None
Source code in src/opensymbolicai/exceptions.py
def __init__(
    self,
    message: str,
    *,
    code: str | None = "OPERATION_ERROR",
    details: dict[str, Any] | None = None,
    operation: str | None = None,
) -> None:
    """Initialize operation error.

    Args:
        message: Human-readable error message.
        code: Error code, defaults to "OPERATION_ERROR".
        details: Additional context about the error.
        operation: Optional name of the operation that failed.
    """
    if operation:
        details = details or {}
        details["operation"] = operation
    super().__init__(message, code=code, details=details)
    self.operation = operation

OrchestrationResult

Bases: BaseModel

Result from a complete plan-and-execute run.

Source code in src/opensymbolicai/models.py
class OrchestrationResult(BaseModel):
    """Result from a complete plan-and-execute run."""

    success: bool = Field(..., description="Whether the orchestration succeeded")
    result: Any = Field(default=None, description="The computed result")
    error: str | None = Field(default=None, description="Error message if failed")
    metrics: ExecutionMetrics | None = Field(
        default=None, description="Execution metrics"
    )
    plan: str | None = Field(default=None, description="The generated plan")
    trace: ExecutionTrace | None = Field(
        default=None, description="Step-by-step execution trace"
    )
    plan_attempts: list[PlanAttempt] = Field(
        default_factory=list,
        description="All plan generation attempts including retries",
    )
    task: str = Field(default="", description="The original task description")

PendingMutation

Bases: BaseModel

Information about a mutation awaiting approval.

Source code in src/opensymbolicai/checkpoint.py
class PendingMutation(BaseModel):
    """Information about a mutation awaiting approval."""

    method_name: str = Field(..., description="Name of the mutating primitive")
    args: dict[str, Any] = Field(
        default_factory=dict, description="Arguments to the mutation"
    )
    statement: str = Field(..., description="The full statement to execute")
    step_number: int = Field(..., description="Which step this mutation is")
    variable_name: str = Field(
        default="", description="Variable being assigned the result"
    )

PlanAnalysis

Bases: BaseModel

Analysis of a plan's structure.

Source code in src/opensymbolicai/models.py
class PlanAnalysis(BaseModel):
    """Analysis of a plan's structure."""

    calls: list[PrimitiveCall] = Field(
        default_factory=list, description="All primitive calls in the plan"
    )

    @property
    def has_mutations(self) -> bool:
        """Check if any calls are not read-only."""
        return any(not call.read_only for call in self.calls)

    @property
    def method_names(self) -> list[str]:
        """Get list of all method names called."""
        return [call.method_name for call in self.calls]

has_mutations property

Check if any calls are not read-only.

method_names property

Get list of all method names called.

PlanContext

Bases: BaseModel

Context about how the plan was generated.

Source code in src/opensymbolicai/checkpoint.py
class PlanContext(BaseModel):
    """Context about how the plan was generated."""

    plan_attempts: list[PlanAttempt] = Field(
        default_factory=list,
        description="All plan generation attempts including retries",
    )
    final_plan: str = Field(default="", description="The final validated plan")
    generation_time_seconds: float = Field(
        default=0.0, description="Total time spent generating the plan"
    )

    @property
    def attempt_count(self) -> int:
        """Number of plan generation attempts."""
        return len(self.plan_attempts)

    @property
    def had_retries(self) -> bool:
        """Whether the plan required retries."""
        return len(self.plan_attempts) > 1

    @property
    def all_llm_interactions(self) -> list[LLMInteraction]:
        """Get all LLM interactions from all attempts."""
        return [
            attempt.plan_generation.llm_interaction for attempt in self.plan_attempts
        ]

all_llm_interactions property

Get all LLM interactions from all attempts.

attempt_count property

Number of plan generation attempts.

had_retries property

Whether the plan required retries.

PlanExecute

Bases: Planner

Agent that generates and executes Python plans using LLMs.

PlanExecute orchestrators use an LLM to generate Python code that calls primitive methods, then execute that code step-by-step with full tracing.

Subclasses should: 1. Define primitive methods using the @primitive decorator 2. Optionally define decomposition examples using @decomposition

Example

class Calculator(PlanExecute): @primitive(read_only=True) def add(self, a: float, b: float) -> float: return a + b

@decomposition(intent="What is 2 + 3?")
def _example_add(self) -> float:
    result = self.add(2, 3)
    return result
Source code in src/opensymbolicai/blueprints/plan_execute.py
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
class PlanExecute(Planner):
    """Agent that generates and executes Python plans using LLMs.

    PlanExecute orchestrators use an LLM to generate Python code that calls
    primitive methods, then execute that code step-by-step with full tracing.

    Subclasses should:
    1. Define primitive methods using the @primitive decorator
    2. Optionally define decomposition examples using @decomposition

    Example:
        class Calculator(PlanExecute):
            @primitive(read_only=True)
            def add(self, a: float, b: float) -> float:
                return a + b

            @decomposition(intent="What is 2 + 3?")
            def _example_add(self) -> float:
                result = self.add(2, 3)
                return result
    """

    def __init__(
        self,
        llm: LLM | LLMConfig,
        name: str = "",
        description: str = "",
        config: PlanExecuteConfig | None = None,
    ) -> None:
        """Initialize the PlanExecute agent.

        Args:
            llm: LLM instance or config for plan generation.
            name: Agent name for prompts.
            description: Agent description for prompts.
            config: Extended configuration options.
        """
        if isinstance(llm, LLMConfig):
            self._llm = create_llm(llm)
        else:
            self._llm = llm

        self.name = name or self.__class__.__name__
        self.description = description or self.__class__.__doc__ or ""
        self.config = config or PlanExecuteConfig()
        self.allowed_builtins = (
            self.config.allowed_builtins
            if self.config.allowed_builtins is not None
            else DEFAULT_ALLOWED_BUILTINS.copy()
        )

        # Multi-turn state
        self._history: list[ConversationTurn] = []
        self._persisted_namespace: dict[str, Any] = {}

    @property
    def history(self) -> list[ConversationTurn]:
        """Get the conversation history (multi-turn mode only)."""
        return self._history

    @property
    def persisted_variables(self) -> dict[str, Any]:
        """Get the persisted variables from previous turns (multi-turn mode only)."""
        return self._persisted_namespace.copy()

    # -------------------------------------------------------------------------
    # Introspection: Extract primitives and decompositions
    # -------------------------------------------------------------------------

    def _get_primitive_methods(self) -> list[tuple[str, Callable[..., Any]]]:
        """Get all methods decorated with @primitive."""
        primitives = []
        for name in dir(self):
            if name.startswith("_"):
                continue
            method = getattr(self, name, None)
            if (
                callable(method)
                and hasattr(method, "__method_type__")
                and method.__method_type__ == MethodType.PRIMITIVE
            ):
                primitives.append((name, method))
        return primitives

    def _get_decomposition_methods(
        self,
    ) -> list[tuple[str, Callable[..., Any], str, str]]:
        """Get all methods decorated with @decomposition.

        Returns:
            List of (name, method, intent, expanded_intent) tuples.
        """
        decompositions = []
        for name in dir(self):
            method = getattr(self, name, None)
            if (
                callable(method)
                and hasattr(method, "__method_type__")
                and method.__method_type__ == MethodType.DECOMPOSITION
            ):
                intent = getattr(method, "__decomposition_intent__", "")
                expanded = getattr(method, "__decomposition_expanded_intent__", "")
                decompositions.append((name, method, intent, expanded))
        return decompositions

    def _get_primitive_names(self) -> set[str]:
        """Get the names of all primitive methods."""
        return {name for name, _ in self._get_primitive_methods()}

    def _get_primitive_read_only_map(self) -> dict[str, bool]:
        """Get a mapping of primitive names to their read_only status."""
        return {
            name: getattr(method, "__primitive_read_only__", False)
            for name, method in self._get_primitive_methods()
        }

    def _format_primitive_signature(self, name: str, method: Callable[..., Any]) -> str:
        """Format a primitive method's signature and docstring for the prompt."""
        sig = inspect.signature(method)
        params = []
        for param_name, param in sig.parameters.items():
            if param_name == "self":
                continue
            annotation = (
                param.annotation.__name__
                if hasattr(param.annotation, "__name__")
                else str(param.annotation)
            )
            if param.annotation == inspect.Parameter.empty:
                annotation = "Any"
            if param.default != inspect.Parameter.empty:
                params.append(f"{param_name}: {annotation} = {param.default!r}")
            else:
                params.append(f"{param_name}: {annotation}")

        return_annotation = sig.return_annotation
        if return_annotation == inspect.Signature.empty:
            return_type = "Any"
        elif hasattr(return_annotation, "__name__"):
            return_type = return_annotation.__name__
        else:
            return_type = str(return_annotation)

        signature_str = f"{name}({', '.join(params)}) -> {return_type}"
        docstring = inspect.getdoc(method) or ""
        return f'{signature_str}\n    """{docstring}"""'

    def _get_decomposition_source(self, method: Callable[..., Any]) -> str:
        """Extract the source code body of a decomposition method."""
        try:
            source = inspect.getsource(method)
            # Dedent to remove class-level indentation before parsing
            source = textwrap.dedent(source)
            # Parse and extract just the function body (skip decorator and def line)
            tree = ast.parse(source)
            if tree.body and isinstance(tree.body[0], ast.FunctionDef):
                func_def = tree.body[0]
                # Get the body statements as source
                body_lines = []
                for stmt in func_def.body:
                    # Skip docstrings
                    if isinstance(stmt, ast.Expr) and isinstance(
                        stmt.value, ast.Constant
                    ):
                        continue
                    body_lines.append(ast.unparse(stmt))
                return "\n".join(body_lines)
        except (OSError, TypeError):
            pass
        return ""

    # -------------------------------------------------------------------------
    # Prompt Building
    # -------------------------------------------------------------------------

    def _format_history_for_prompt(self) -> str:
        """Format conversation history for inclusion in the prompt."""
        if not self._history:
            return ""

        sections = []
        for i, turn in enumerate(self._history, 1):
            section = f"### Turn {i}\n"
            section += f"Task: {turn.task}\n"
            section += f"Plan:\n```python\n{turn.plan}\n```\n"
            if turn.success:
                section += f"Result: {turn.result!r}"
            else:
                section += f"Error: {turn.error}"
            sections.append(section)

        return "\n\n".join(sections)

    def build_plan_prompt(self, task: str, feedback: str | None = None) -> str:
        """Build the prompt for the LLM to generate a plan.

        Override this method in subclasses to customize the prompt sent to the LLM.

        Args:
            task: The task description to plan for.
            feedback: Optional error feedback from a previous failed plan attempt.

        Returns:
            The complete prompt string to send to the LLM.
        """
        primitives = self._get_primitive_methods()
        decompositions = self._get_decomposition_methods()

        # Build primitive documentation
        primitive_docs = [
            self._format_primitive_signature(name, method)
            for name, method in primitives
        ]

        # Build decomposition examples
        examples = []
        for _name, method, intent, expanded in decompositions:
            source = self._get_decomposition_source(method)
            if source:
                example = f"Intent: {intent}"
                if expanded:
                    example += f"\nApproach: {expanded}"
                example += f"\nPython:\n{source}"
                examples.append(example)

        # Build conversation history section if in multi-turn mode
        history_section = ""
        if self.config.multi_turn and self._history:
            history_section = f"""
## Conversation History

Previous turns in this conversation. You can reference variables from previous turns.

{self._format_history_for_prompt()}

"""

        # Build feedback section if retrying after a failed plan
        feedback_section = ""
        if feedback:
            feedback_section = f"""
## Previous Attempt Failed

Your previous plan was invalid. Please fix the following error and regenerate:

{feedback}

"""

        prompt = f"""You are {self.name}, an AI agent that generates Python code plans.

{self.description}

## Available Primitive Methods

You can ONLY call these methods:

```python
{chr(10).join(primitive_docs)}
```

## Example Decompositions

Here are examples of how to compose primitives:

{chr(10).join(f"### Example {i + 1}{chr(10)}{ex}" for i, ex in enumerate(examples)) if examples else "No examples available."}
{history_section}{feedback_section}## Task

Generate Python code to accomplish this task: {task}

## Rules

1. Output ONLY Python assignment statements
2. Each statement must assign a result to a variable
3. You can ONLY call the primitive methods listed above
4. Do NOT use imports, loops, conditionals, or function definitions
5. Do NOT use any dangerous operations (exec, eval, open, etc.)
6. The last assigned variable will be the final result

## Output

```python
"""
        return prompt

    def _extract_code_block(self, response_text: str) -> str:
        """Extract code from markdown code blocks in an LLM response.

        Args:
            response_text: The raw text response from the LLM.

        Returns:
            The extracted code string.
        """
        text = response_text.strip()
        code = text
        if "```python" in text:
            # Extract code between ```python and ```
            start = text.find("```python") + len("```python")
            end = text.find("```", start)
            if end > start:
                code = text[start:end]
        elif "```" in text:
            # Generic code block
            start = text.find("```") + 3
            end = text.find("```", start)
            if end > start:
                code = text[start:end]

        # Normalize indentation - some models (especially smaller local ones)
        # may return code with unexpected leading indentation
        code = textwrap.dedent(code).strip()

        # Strip trailing markdown code block delimiters that weren't properly matched
        # This handles cases where the LLM adds a closing ``` without proper opening
        if code.endswith("```"):
            code = code[:-3].rstrip()

        return code

    def on_code_extracted(self, raw_response: str, extracted_code: str) -> str:
        """Hook called after code is extracted from the LLM response.

        Override this method in subclasses to observe and/or modify the
        extracted code before it is used for planning.

        Args:
            raw_response: The original raw text response from the LLM.
            extracted_code: The code extracted by _extract_code_block.

        Returns:
            The final code to use (can be modified from extracted_code).
        """
        return extracted_code

    # -------------------------------------------------------------------------
    # Plan Generation
    # -------------------------------------------------------------------------

    def plan(self, task: str, feedback: str | None = None) -> PlanResult:
        """Generate a plan (Python statements) for a task.

        Args:
            task: The task description to plan for.
            feedback: Optional error feedback from a previous failed plan attempt.

        Returns:
            PlanResult containing the generated plan and metrics.
        """
        prompt = self.build_plan_prompt(task, feedback=feedback)
        start_time = time.perf_counter()
        response = self._llm.generate(prompt)
        elapsed = time.perf_counter() - start_time

        # Extract code from response (handle markdown code blocks)
        raw_response = response.text
        extracted_code = self._extract_code_block(raw_response)
        plan_text = self.on_code_extracted(raw_response, extracted_code)

        # Build full LLM interaction details
        llm_interaction = LLMInteraction(
            prompt=prompt,
            response=raw_response,
            input_tokens=response.usage.input_tokens,
            output_tokens=response.usage.output_tokens,
            time_seconds=elapsed,
            provider=response.provider,
            model=response.model,
        )
        plan_generation = PlanGeneration(
            llm_interaction=llm_interaction,
            extracted_code=extracted_code,
        )

        return PlanResult(
            plan=plan_text,
            usage=ModelTokenUsage(
                input_tokens=response.usage.input_tokens,
                output_tokens=response.usage.output_tokens,
            ),
            time_seconds=elapsed,
            provider=response.provider,
            model=response.model,
            plan_generation=plan_generation,
        )

    # -------------------------------------------------------------------------
    # Plan Analysis and Validation
    # -------------------------------------------------------------------------

    def analyze_plan(self, plan: str) -> PlanAnalysis:
        """Analyze a plan to extract primitive calls.

        Args:
            plan: The Python statements to analyze.

        Returns:
            PlanAnalysis containing all primitive calls found.

        Raises:
            ValueError: If the plan has invalid syntax.
        """
        try:
            tree = ast.parse(plan)
        except SyntaxError as e:
            raise ValueError(f"Invalid Python syntax: {e}") from e

        primitive_names = self._get_primitive_names()
        read_only_map = self._get_primitive_read_only_map()
        calls: list[PrimitiveCall] = []

        for node in ast.walk(tree):
            if not isinstance(node, ast.Call):
                continue

            method_name: str | None = None

            # Direct call: method_name(...)
            if isinstance(node.func, ast.Name) and node.func.id in primitive_names:
                method_name = node.func.id

            # Method call on self: self.method_name(...)
            elif (
                isinstance(node.func, ast.Attribute)
                and isinstance(node.func.value, ast.Name)
                and node.func.value.id == "self"
                and node.func.attr in primitive_names
            ):
                method_name = node.func.attr

            if method_name is not None:
                args: dict[str, Any] = {}
                for kw in node.keywords:
                    if kw.arg is not None:
                        try:
                            args[kw.arg] = ast.literal_eval(kw.value)
                        except (ValueError, TypeError):
                            args[kw.arg] = ast.unparse(kw.value)

                for i, arg in enumerate(node.args):
                    try:
                        args[f"arg{i}"] = ast.literal_eval(arg)
                    except (ValueError, TypeError):
                        args[f"arg{i}"] = ast.unparse(arg)

                calls.append(
                    PrimitiveCall(
                        method_name=method_name,
                        read_only=read_only_map.get(method_name, False),
                        args=args,
                    )
                )

        return PlanAnalysis(calls=calls)

    def validate_plan(self, plan: str) -> None:
        """Validate that a plan only uses allowed operations.

        Args:
            plan: The Python statements to validate.

        Raises:
            ValueError: If the plan contains disallowed operations.
        """
        try:
            tree = ast.parse(plan)
        except SyntaxError as e:
            raise ValueError(f"Invalid Python syntax: {e}") from e

        primitive_names = self._get_primitive_names()
        dangerous_builtins = {
            "exec",
            "eval",
            "compile",
            "open",
            "__import__",
            "globals",
            "locals",
            "vars",
            "dir",
            "getattr",
            "setattr",
            "delattr",
            "hasattr",
            "type",
            "isinstance",
            "issubclass",
            "callable",
            "breakpoint",
            "input",
            "memoryview",
            "object",
        }

        disallowed_statements: tuple[type, ...] = (
            ast.If,
            ast.For,
            ast.While,
            ast.Try,
            ast.With,
            ast.FunctionDef,
            ast.AsyncFunctionDef,
            ast.ClassDef,
            ast.Import,
            ast.ImportFrom,
            ast.Global,
            ast.Nonlocal,
            ast.Raise,
            ast.Assert,
            ast.Delete,
        )
        if hasattr(ast, "Match"):
            disallowed_statements = (*disallowed_statements, ast.Match)

        for node in ast.walk(tree):
            if isinstance(node, disallowed_statements):
                node_type = type(node).__name__
                raise ValueError(f"{node_type} statements are not allowed in plans")

        # Every top-level statement must be an assignment
        for stmt in tree.body:
            if not isinstance(stmt, (ast.Assign, ast.AnnAssign)):
                stmt_type = type(stmt).__name__
                raise ValueError(
                    f"Every statement must be an assignment. Found: {stmt_type}"
                )

        for node in ast.walk(tree):
            # Disallow private/dunder attributes
            if isinstance(node, ast.Attribute) and node.attr.startswith("_"):
                raise ValueError(
                    f"Accessing private/dunder attributes not allowed: {node.attr}"
                )

            # Validate function calls
            if isinstance(node, ast.Call):
                if isinstance(node.func, ast.Name):
                    func_name = node.func.id
                    if func_name in dangerous_builtins:
                        raise ValueError(f"Calling '{func_name}' is not allowed")
                    allowed_names = primitive_names | set(self.allowed_builtins.keys())
                    if func_name not in allowed_names:
                        raise ValueError(
                            f"Function '{func_name}' is not allowed. "
                            f"Only primitive methods and allowed builtins can be called."
                        )

                if (
                    isinstance(node.func, ast.Attribute)
                    and isinstance(node.func.value, ast.Name)
                    and node.func.value.id == "self"
                    and node.func.attr not in primitive_names
                ):
                    raise ValueError(f"Method '{node.func.attr}' is not a primitive.")

    # -------------------------------------------------------------------------
    # Step-by-Step Execution
    # -------------------------------------------------------------------------

    def _snapshot_namespace(
        self, namespace: dict[str, Any], reserved_names: set[str]
    ) -> dict[str, Any]:
        """Create a JSON-serializable snapshot of user-defined variables in the namespace."""
        snapshot: dict[str, Any] = {}
        for key, value in namespace.items():
            if key in reserved_names:
                continue
            try:
                # Try to JSON serialize to ensure it's capturable
                json.dumps(value, default=str)
                snapshot[key] = value
            except (TypeError, ValueError):
                snapshot[key] = f"<{type(value).__name__}>"
        return snapshot

    def _resolve_arg_value(
        self, node: ast.expr, namespace: dict[str, Any]
    ) -> ArgumentValue:
        """Resolve an argument AST node to an ArgumentValue with expression and resolved value."""
        expression = ast.unparse(node)
        variable_reference: str | None = None
        resolved_value: Any = None

        # Check if it's a simple variable reference
        if isinstance(node, ast.Name):
            variable_reference = node.id
            resolved_value = namespace.get(node.id)
        else:
            # Try to evaluate the expression in the namespace
            try:
                resolved_value = ast.literal_eval(node)
            except (ValueError, TypeError):
                # Try to eval in the namespace for more complex expressions
                try:
                    resolved_value = eval(  # noqa: S307
                        expression, {"__builtins__": {}}, namespace
                    )
                except Exception:
                    resolved_value = None

        return ArgumentValue(
            expression=expression,
            resolved_value=resolved_value,
            variable_reference=variable_reference,
        )

    def _execute_statement(
        self,
        stmt: ast.stmt,
        namespace: dict[str, Any],
        step_number: int,
        read_only_map: dict[str, bool] | None = None,
        reserved_names: set[str] | None = None,
    ) -> ExecutionStep:
        """Execute a single statement and return the step result."""
        statement_str = ast.unparse(stmt)
        start_time = time.perf_counter()

        if reserved_names is None:
            reserved_names = set()

        # Capture namespace before execution
        namespace_before = self._snapshot_namespace(namespace, reserved_names)

        # Determine variable name and extract call info
        variable_name = ""
        primitive_called = None
        args: dict[str, ArgumentValue] = {}

        if isinstance(stmt, ast.Assign):
            if stmt.targets and isinstance(stmt.targets[0], ast.Name):
                variable_name = stmt.targets[0].id
            # Check if value is a Call
            if isinstance(stmt.value, ast.Call):
                call = stmt.value
                if isinstance(call.func, ast.Name):
                    primitive_called = call.func.id
                elif isinstance(call.func, ast.Attribute):
                    primitive_called = call.func.attr

                # Extract positional args
                for i, arg in enumerate(call.args):
                    args[f"arg{i}"] = self._resolve_arg_value(arg, namespace)

                # Extract keyword args
                for kw in call.keywords:
                    if kw.arg is not None:
                        args[kw.arg] = self._resolve_arg_value(kw.value, namespace)

        elif isinstance(stmt, ast.AnnAssign):
            if isinstance(stmt.target, ast.Name):
                variable_name = stmt.target.id
            # Check if value is a Call (annotated assignments can also have calls)
            if stmt.value is not None and isinstance(stmt.value, ast.Call):
                call = stmt.value
                if isinstance(call.func, ast.Name):
                    primitive_called = call.func.id
                elif isinstance(call.func, ast.Attribute):
                    primitive_called = call.func.attr

                # Extract positional args
                for i, arg in enumerate(call.args):
                    args[f"arg{i}"] = self._resolve_arg_value(arg, namespace)

                # Extract keyword args
                for kw in call.keywords:
                    if kw.arg is not None:
                        args[kw.arg] = self._resolve_arg_value(kw.value, namespace)

        # Check mutation hook BEFORE execution for non-read-only primitives
        is_mutation = (
            primitive_called is not None
            and read_only_map is not None
            and not read_only_map.get(primitive_called, True)
        )

        if is_mutation and self.config.on_mutation is not None:
            assert primitive_called is not None  # Guaranteed by is_mutation check
            # Convert ArgumentValue dict to plain dict for hook context
            plain_args = {k: v.resolved_value for k, v in args.items()}
            hook_context = MutationHookContext(
                method_name=primitive_called,
                args=plain_args,
                result=None,  # Not yet executed
                step=None,  # Not yet created
            )
            rejection_reason = self.config.on_mutation(hook_context)

            if rejection_reason is not None:
                # Hook rejected the mutation - fail without executing
                elapsed = time.perf_counter() - start_time
                return ExecutionStep(
                    step_number=step_number,
                    statement=statement_str,
                    variable_name=variable_name,
                    primitive_called=primitive_called,
                    args=args,
                    namespace_before=namespace_before,
                    namespace_after=namespace_before,  # No change since rejected
                    result_type="",
                    result_value=None,
                    result_json="null",
                    time_seconds=elapsed,
                    success=False,
                    error=f"Mutation rejected: {rejection_reason}",
                )

        try:
            # Execute the single statement
            exec(  # noqa: S102
                compile(ast.Module(body=[stmt], type_ignores=[]), "<plan>", "exec"),
                {"__builtins__": {}},
                namespace,
            )
            elapsed = time.perf_counter() - start_time

            # Capture namespace after execution
            namespace_after = self._snapshot_namespace(namespace, reserved_names)

            # Get the result value
            result_value = namespace.get(variable_name) if variable_name else None

            result_json = (
                "null"
                if self.config.skip_result_serialization
                else json.dumps(result_value, default=str)
            )

            step = ExecutionStep(
                step_number=step_number,
                statement=statement_str,
                variable_name=variable_name,
                primitive_called=primitive_called,
                args=args,
                namespace_before=namespace_before,
                namespace_after=namespace_after,
                result_type=type(result_value).__name__
                if result_value is not None
                else "NoneType",
                result_value=result_value,
                result_json=result_json,
                time_seconds=elapsed,
                success=True,
            )

            return step

        except Exception as e:
            elapsed = time.perf_counter() - start_time
            # Capture namespace after failed execution (may have partial changes)
            namespace_after = self._snapshot_namespace(namespace, reserved_names)
            return ExecutionStep(
                step_number=step_number,
                statement=statement_str,
                variable_name=variable_name,
                primitive_called=primitive_called,
                args=args,
                namespace_before=namespace_before,
                namespace_after=namespace_after,
                result_type="",
                result_value=None,
                result_json="null",
                time_seconds=elapsed,
                success=False,
                error=str(e),
            )

    def execute(self, plan: str) -> ExecutionResult:
        """Execute a plan step-by-step with full tracing.

        Args:
            plan: The Python statements to execute.

        Returns:
            ExecutionResult containing the final value and execution trace.

        Raises:
            ValueError: If the plan contains disallowed operations.
        """
        self.validate_plan(plan)

        tree = ast.parse(plan)
        steps: list[ExecutionStep] = []
        total_start = time.perf_counter()

        # Build execution namespace
        namespace: dict[str, Any] = {"self": self}
        for name, method in self._get_primitive_methods():
            namespace[name] = method
        namespace.update(self.allowed_builtins)

        # Include persisted variables from previous turns in multi-turn mode
        if self.config.multi_turn:
            namespace.update(self._persisted_namespace)

        # Get read_only map for mutation hook
        read_only_map = self._get_primitive_read_only_map()

        # Calculate reserved names for namespace snapshots
        reserved_names = (
            {"self"}
            | set(self.allowed_builtins.keys())
            | {name for name, _ in self._get_primitive_methods()}
        )

        # Execute statement by statement
        for i, stmt in enumerate(tree.body, 1):
            step = self._execute_statement(
                stmt, namespace, i, read_only_map, reserved_names
            )
            steps.append(step)

            # Stop on first error
            if not step.success:
                break

        # Persist user-defined variables for multi-turn mode
        if self.config.multi_turn:
            for key, value in namespace.items():
                if key not in reserved_names:
                    self._persisted_namespace[key] = value

        total_elapsed = time.perf_counter() - total_start

        trace = ExecutionTrace(
            steps=steps,
            total_time_seconds=total_elapsed,
        )

        # Determine final result
        if steps and steps[-1].success:
            last = steps[-1]
            return ExecutionResult(
                value_type=last.result_type,
                value_name=last.variable_name,
                value_json=last.result_json,
                trace=trace,
            )
        else:
            return ExecutionResult(
                value_type="NoneType",
                value_name="",
                value_json="null",
                trace=trace,
            )

    # -------------------------------------------------------------------------
    # Checkpoint-based Execution (Distributed/Interruptible)
    # -------------------------------------------------------------------------

    def execute_stepwise(
        self,
        task: str,
        plan_context: PlanContext | None = None,
        serializer: SerializerRegistry | None = None,
        checkpoint_id: str | None = None,
    ) -> Iterator[ExecutionCheckpoint]:
        """Execute a plan step-by-step, yielding checkpoints for persistence.

        This method enables distributed execution by yielding a checkpoint after
        each step. The checkpoint can be persisted to a database and resumed on
        any worker.

        When `require_mutation_approval` is True (default), execution pauses
        before mutations and yields a checkpoint with status `awaiting_approval`.
        Call `resume_from_checkpoint()` with `approve_mutation=True` to continue.

        Args:
            task: The task description to accomplish.
            plan_context: Optional pre-computed plan context (from a previous
                planning phase). If None, will generate a new plan.
            serializer: Custom serializer registry. Defaults to the global registry.
            checkpoint_id: Optional ID for the checkpoint. Auto-generated if None.

        Yields:
            ExecutionCheckpoint after each step, allowing for persistence and
            distributed resume.

        Example:
            # Simple usage - collect all checkpoints
            for checkpoint in agent.execute_stepwise("do something"):
                store.save(checkpoint)
                if checkpoint.status == CheckpointStatus.AWAITING_APPROVAL:
                    # Handle approval externally
                    break

            # Resume after approval
            checkpoint = store.load(checkpoint_id)
            for checkpoint in agent.resume_from_checkpoint(checkpoint, approve_mutation=True):
                store.save(checkpoint)
        """
        serializer = serializer or default_serializer_registry

        # Generate plan if not provided
        if plan_context is None:
            plan_result = self.plan(task)
            plan_context = PlanContext(
                plan_attempts=[
                    PlanAttempt(
                        attempt_number=1,
                        plan_generation=plan_result.plan_generation
                        or PlanGeneration(
                            llm_interaction=LLMInteraction(
                                prompt="",
                                response="",
                                input_tokens=plan_result.usage.input_tokens,
                                output_tokens=plan_result.usage.output_tokens,
                                time_seconds=plan_result.time_seconds,
                                provider=plan_result.provider,
                                model=plan_result.model,
                            ),
                            extracted_code=plan_result.plan,
                        ),
                        success=True,
                    )
                ],
                final_plan=plan_result.plan,
                generation_time_seconds=plan_result.time_seconds,
            )

        plan = plan_context.final_plan

        # Validate plan
        try:
            self.validate_plan(plan)
        except ValueError as e:
            checkpoint = ExecutionCheckpoint(
                task=task,
                plan=plan,
                plan_context=plan_context,
                current_step=0,
                total_steps=0,
                status=CheckpointStatus.FAILED,
                error=str(e),
                worker_id=self.config.worker_id,
            )
            if checkpoint_id is not None:
                checkpoint.checkpoint_id = checkpoint_id
            yield checkpoint
            return

        tree = ast.parse(plan)
        total_steps = len(tree.body)

        # Build execution namespace
        namespace: dict[str, Any] = {"self": self}
        for name, method in self._get_primitive_methods():
            namespace[name] = method
        namespace.update(self.allowed_builtins)

        if self.config.multi_turn:
            namespace.update(self._persisted_namespace)

        read_only_map = self._get_primitive_read_only_map()
        reserved_names = (
            {"self"}
            | set(self.allowed_builtins.keys())
            | {name for name, _ in self._get_primitive_methods()}
        )

        steps: list[ExecutionStep] = []

        # Create initial checkpoint
        checkpoint = ExecutionCheckpoint(
            task=task,
            plan=plan,
            plan_context=plan_context,
            current_step=0,
            total_steps=total_steps,
            status=CheckpointStatus.RUNNING,
            namespace_snapshot=serializer.serialize_namespace(
                namespace, reserved_names
            ),
            completed_steps=[],
            worker_id=self.config.worker_id,
        )
        if checkpoint_id is not None:
            checkpoint.checkpoint_id = checkpoint_id

        # Execute statement by statement
        for i, stmt in enumerate(tree.body):
            step_number = i + 1
            statement_str = ast.unparse(stmt)

            # Check if this is a mutation requiring approval
            is_mutation = False
            method_name: str | None = None
            variable_name = ""
            args_for_pending: dict[str, Any] = {}

            if isinstance(stmt, ast.Assign):
                if stmt.targets and isinstance(stmt.targets[0], ast.Name):
                    variable_name = stmt.targets[0].id
                if isinstance(stmt.value, ast.Call):
                    call = stmt.value
                    if isinstance(call.func, ast.Name):
                        method_name = call.func.id
                    elif isinstance(call.func, ast.Attribute):
                        method_name = call.func.attr

                    if method_name and not read_only_map.get(method_name, True):
                        is_mutation = True
                        # Extract args for pending mutation info
                        for idx, arg in enumerate(call.args):
                            try:
                                args_for_pending[f"arg{idx}"] = ast.literal_eval(arg)
                            except (ValueError, TypeError):
                                args_for_pending[f"arg{idx}"] = ast.unparse(arg)
                        for kw in call.keywords:
                            if kw.arg:
                                try:
                                    args_for_pending[kw.arg] = ast.literal_eval(
                                        kw.value
                                    )
                                except (ValueError, TypeError):
                                    args_for_pending[kw.arg] = ast.unparse(kw.value)

            # If mutation requires approval, pause and yield
            if is_mutation and self.config.require_mutation_approval:
                checkpoint.current_step = i
                checkpoint.status = CheckpointStatus.AWAITING_APPROVAL
                checkpoint.pending_mutation = PendingMutation(
                    method_name=method_name or "",
                    args=args_for_pending,
                    statement=statement_str,
                    step_number=step_number,
                    variable_name=variable_name,
                )
                checkpoint.namespace_snapshot = serializer.serialize_namespace(
                    namespace, reserved_names
                )
                checkpoint.completed_steps = steps.copy()
                checkpoint.touch(self.config.worker_id)
                yield checkpoint
                return  # Caller must resume with approve_mutation=True

            # Execute the step
            step = self._execute_statement(
                stmt, namespace, step_number, read_only_map, reserved_names
            )
            steps.append(step)

            # Update checkpoint
            checkpoint.current_step = step_number
            checkpoint.completed_steps = steps.copy()
            checkpoint.namespace_snapshot = serializer.serialize_namespace(
                namespace, reserved_names
            )

            if not step.success:
                checkpoint.status = CheckpointStatus.FAILED
                checkpoint.error = step.error
                checkpoint.touch(self.config.worker_id)
                yield checkpoint
                return

            # Yield progress checkpoint
            checkpoint.status = CheckpointStatus.RUNNING
            checkpoint.touch(self.config.worker_id)
            yield checkpoint

        # Execution completed successfully
        checkpoint.status = CheckpointStatus.COMPLETED
        if steps:
            last_step = steps[-1]
            checkpoint.result_variable = last_step.variable_name
            result_value = namespace.get(last_step.variable_name)
            checkpoint.result_value = serializer.serialize(result_value)

        # Persist for multi-turn
        if self.config.multi_turn:
            for key, value in namespace.items():
                if key not in reserved_names:
                    self._persisted_namespace[key] = value

        checkpoint.touch(self.config.worker_id)
        yield checkpoint

    def resume_from_checkpoint(
        self,
        checkpoint: ExecutionCheckpoint,
        approve_mutation: bool = False,
        serializer: SerializerRegistry | None = None,
    ) -> Iterator[ExecutionCheckpoint]:
        """Resume execution from a persisted checkpoint.

        This method reconstructs execution state from a checkpoint and continues
        execution from where it left off.

        Args:
            checkpoint: The checkpoint to resume from.
            approve_mutation: If True and checkpoint is awaiting approval,
                execute the pending mutation and continue.
            serializer: Custom serializer registry. Must match the one used
                when creating the checkpoint.

        Yields:
            ExecutionCheckpoint after each step.

        Raises:
            ValueError: If checkpoint is in a terminal state or approval is
                required but not provided.

        Example:
            # Load and resume
            checkpoint = store.load(checkpoint_id)
            if checkpoint.status == CheckpointStatus.AWAITING_APPROVAL:
                # Get user approval somehow
                if user_approved:
                    for cp in agent.resume_from_checkpoint(checkpoint, approve_mutation=True):
                        store.save(cp)
        """
        serializer = serializer or default_serializer_registry

        if checkpoint.is_terminal:
            raise ValueError(
                f"Cannot resume from terminal checkpoint (status: {checkpoint.status})"
            )

        if (
            checkpoint.status == CheckpointStatus.AWAITING_APPROVAL
            and not approve_mutation
        ):
            raise ValueError(
                "Checkpoint is awaiting mutation approval. "
                "Set approve_mutation=True to continue."
            )

        # Parse the plan
        tree = ast.parse(checkpoint.plan)
        total_steps = len(tree.body)

        # Rebuild namespace
        namespace: dict[str, Any] = {"self": self}
        for name, method in self._get_primitive_methods():
            namespace[name] = method
        namespace.update(self.allowed_builtins)

        if self.config.multi_turn:
            namespace.update(self._persisted_namespace)

        # Restore serialized variables (skip undeserializable values)
        import contextlib

        for var_name, serialized_val in checkpoint.namespace_snapshot.items():
            with contextlib.suppress(ValueError):
                namespace[var_name] = serializer.deserialize(serialized_val)

        read_only_map = self._get_primitive_read_only_map()
        reserved_names = (
            {"self"}
            | set(self.allowed_builtins.keys())
            | {name for name, _ in self._get_primitive_methods()}
        )

        # Copy completed steps
        steps = list(checkpoint.completed_steps)

        # Determine starting point
        start_step = checkpoint.current_step

        # If resuming from awaiting_approval, execute the pending mutation first
        if (
            checkpoint.status == CheckpointStatus.AWAITING_APPROVAL
            and approve_mutation
            and checkpoint.pending_mutation
        ):
            stmt = tree.body[start_step]
            step_number = start_step + 1

            step = self._execute_statement(
                stmt, namespace, step_number, read_only_map, reserved_names
            )
            steps.append(step)

            checkpoint.completed_steps = steps.copy()
            checkpoint.pending_mutation = None

            if not step.success:
                checkpoint.status = CheckpointStatus.FAILED
                checkpoint.error = step.error
                checkpoint.current_step = step_number
                checkpoint.namespace_snapshot = serializer.serialize_namespace(
                    namespace, reserved_names
                )
                checkpoint.touch(self.config.worker_id)
                yield checkpoint
                return

            checkpoint.current_step = step_number
            checkpoint.namespace_snapshot = serializer.serialize_namespace(
                namespace, reserved_names
            )
            checkpoint.status = CheckpointStatus.RUNNING
            checkpoint.touch(self.config.worker_id)
            yield checkpoint

            start_step += 1

        # Continue with remaining steps
        for i in range(start_step, total_steps):
            stmt = tree.body[i]
            step_number = i + 1
            statement_str = ast.unparse(stmt)

            # Check for mutations
            is_mutation = False
            method_name: str | None = None
            variable_name = ""
            args_for_pending: dict[str, Any] = {}

            if isinstance(stmt, ast.Assign):
                if stmt.targets and isinstance(stmt.targets[0], ast.Name):
                    variable_name = stmt.targets[0].id
                if isinstance(stmt.value, ast.Call):
                    call = stmt.value
                    if isinstance(call.func, ast.Name):
                        method_name = call.func.id
                    elif isinstance(call.func, ast.Attribute):
                        method_name = call.func.attr

                    if method_name and not read_only_map.get(method_name, True):
                        is_mutation = True
                        for idx, arg in enumerate(call.args):
                            try:
                                args_for_pending[f"arg{idx}"] = ast.literal_eval(arg)
                            except (ValueError, TypeError):
                                args_for_pending[f"arg{idx}"] = ast.unparse(arg)
                        for kw in call.keywords:
                            if kw.arg:
                                try:
                                    args_for_pending[kw.arg] = ast.literal_eval(
                                        kw.value
                                    )
                                except (ValueError, TypeError):
                                    args_for_pending[kw.arg] = ast.unparse(kw.value)

            # Pause for mutation approval if required
            if is_mutation and self.config.require_mutation_approval:
                checkpoint.current_step = i
                checkpoint.status = CheckpointStatus.AWAITING_APPROVAL
                checkpoint.pending_mutation = PendingMutation(
                    method_name=method_name or "",
                    args=args_for_pending,
                    statement=statement_str,
                    step_number=step_number,
                    variable_name=variable_name,
                )
                checkpoint.namespace_snapshot = serializer.serialize_namespace(
                    namespace, reserved_names
                )
                checkpoint.completed_steps = steps.copy()
                checkpoint.touch(self.config.worker_id)
                yield checkpoint
                return

            # Execute step
            step = self._execute_statement(
                stmt, namespace, step_number, read_only_map, reserved_names
            )
            steps.append(step)

            checkpoint.current_step = step_number
            checkpoint.completed_steps = steps.copy()
            checkpoint.namespace_snapshot = serializer.serialize_namespace(
                namespace, reserved_names
            )

            if not step.success:
                checkpoint.status = CheckpointStatus.FAILED
                checkpoint.error = step.error
                checkpoint.touch(self.config.worker_id)
                yield checkpoint
                return

            checkpoint.status = CheckpointStatus.RUNNING
            checkpoint.touch(self.config.worker_id)
            yield checkpoint

        # Completed
        checkpoint.status = CheckpointStatus.COMPLETED
        if steps:
            last_step = steps[-1]
            checkpoint.result_variable = last_step.variable_name
            result_value = namespace.get(last_step.variable_name)
            checkpoint.result_value = serializer.serialize(result_value)

        if self.config.multi_turn:
            for key, value in namespace.items():
                if key not in reserved_names:
                    self._persisted_namespace[key] = value

        checkpoint.touch(self.config.worker_id)
        yield checkpoint

    def run_with_checkpoints(
        self,
        task: str,
        store: CheckpointStore,
        serializer: SerializerRegistry | None = None,
        auto_approve: bool = False,
    ) -> ExecutionCheckpoint:
        """Run execution with automatic checkpoint persistence.

        Convenience method that handles checkpoint saving automatically.

        Args:
            task: The task to execute.
            store: Checkpoint store for persistence.
            serializer: Custom serializer registry.
            auto_approve: If True, automatically approve all mutations.

        Returns:
            The final checkpoint (completed or failed).
        """
        checkpoint: ExecutionCheckpoint | None = None

        for checkpoint in self.execute_stepwise(task, serializer=serializer):
            store.save(checkpoint)

            if checkpoint.status == CheckpointStatus.AWAITING_APPROVAL:
                if auto_approve:
                    # Resume with approval - consume all checkpoints from resume
                    current_cp = checkpoint
                    while current_cp.status == CheckpointStatus.AWAITING_APPROVAL:
                        for next_cp in self.resume_from_checkpoint(
                            current_cp, approve_mutation=True, serializer=serializer
                        ):
                            store.save(next_cp)
                            current_cp = next_cp
                    checkpoint = current_cp
                else:
                    # Return checkpoint for external approval
                    return checkpoint

        if checkpoint is None:
            raise RuntimeError("No checkpoint was generated")

        return checkpoint

    # -------------------------------------------------------------------------
    # Main Orchestration
    # -------------------------------------------------------------------------

    def run(self, task: str) -> OrchestrationResult:
        """Run the complete plan-and-execute cycle.

        Args:
            task: The task description to accomplish.

        Returns:
            OrchestrationResult containing the outcome and metrics.
        """
        plan_result = None
        feedback: str | None = None
        max_attempts = 1 + self.config.max_plan_retries
        plan_attempts: list[PlanAttempt] = []

        for attempt in range(max_attempts):
            try:
                # Generate plan (with feedback if retrying)
                plan_result = self.plan(task, feedback=feedback)

                # Record the plan attempt
                plan_attempt = PlanAttempt(
                    attempt_number=attempt + 1,
                    plan_generation=plan_result.plan_generation
                    or PlanGeneration(
                        llm_interaction=LLMInteraction(
                            prompt="",
                            response="",
                            input_tokens=plan_result.usage.input_tokens,
                            output_tokens=plan_result.usage.output_tokens,
                            time_seconds=plan_result.time_seconds,
                            provider=plan_result.provider,
                            model=plan_result.model,
                        ),
                        extracted_code=plan_result.plan,
                    ),
                    feedback=feedback,
                    validation_error=None,
                    success=True,
                )

                # Validate plan before execution (to catch validation errors for retry)
                try:
                    self.validate_plan(plan_result.plan)
                except ValueError as validation_error:
                    plan_attempt.validation_error = str(validation_error)
                    plan_attempt.success = False
                    plan_attempts.append(plan_attempt)
                    raise

                plan_attempts.append(plan_attempt)

                # Execute plan
                exec_start = time.perf_counter()
                exec_result = self.execute(plan_result.plan)
                exec_time = time.perf_counter() - exec_start

                metrics = ExecutionMetrics(
                    plan_tokens=plan_result.usage,
                    plan_time_seconds=plan_result.time_seconds,
                    execute_time_seconds=exec_time,
                    steps_executed=exec_result.trace.step_count,
                    provider=plan_result.provider,
                    model=plan_result.model,
                )

                # Check if execution succeeded
                if exec_result.trace.all_succeeded:
                    result_value = exec_result.get_value()

                    # Track history in multi-turn mode
                    if self.config.multi_turn:
                        self._history.append(
                            ConversationTurn(
                                task=task,
                                plan=plan_result.plan,
                                result=result_value,
                                success=True,
                            )
                        )

                    return OrchestrationResult(
                        success=True,
                        result=result_value,
                        metrics=metrics,
                        plan=plan_result.plan,
                        trace=exec_result.trace,
                        plan_attempts=plan_attempts,
                        task=task,
                    )
                else:
                    # Get error from failed step
                    failed = (
                        exec_result.trace.failed_steps[0]
                        if exec_result.trace.failed_steps
                        else None
                    )
                    error_msg = failed.error if failed else "Unknown execution error"

                    # Track history in multi-turn mode (even for failures)
                    if self.config.multi_turn:
                        self._history.append(
                            ConversationTurn(
                                task=task,
                                plan=plan_result.plan,
                                success=False,
                                error=error_msg,
                            )
                        )

                    return OrchestrationResult(
                        success=False,
                        error=error_msg,
                        metrics=metrics,
                        plan=plan_result.plan,
                        trace=exec_result.trace,
                        plan_attempts=plan_attempts,
                        task=task,
                    )

            except ValueError as e:
                # Validation error - retry if attempts remaining
                error_msg = str(e)
                if attempt < max_attempts - 1:
                    feedback = error_msg
                    continue

                # No more retries - return failure
                if self.config.multi_turn and plan_result is not None:
                    self._history.append(
                        ConversationTurn(
                            task=task,
                            plan=plan_result.plan,
                            success=False,
                            error=error_msg,
                        )
                    )

                return OrchestrationResult(
                    success=False,
                    error=error_msg,
                    plan=plan_result.plan if plan_result else None,
                    plan_attempts=plan_attempts,
                    task=task,
                )

            except Exception as e:
                error_msg = str(e)

                # Track history in multi-turn mode (even for validation/other failures)
                if self.config.multi_turn and plan_result is not None:
                    self._history.append(
                        ConversationTurn(
                            task=task,
                            plan=plan_result.plan,
                            success=False,
                            error=error_msg,
                        )
                    )

                return OrchestrationResult(
                    success=False,
                    error=error_msg,
                    plan=plan_result.plan if plan_result else None,
                    plan_attempts=plan_attempts,
                    task=task,
                )

        # Should not reach here, but satisfy type checker
        return OrchestrationResult(
            success=False,
            error="Unexpected: exhausted all plan retry attempts",
            plan=plan_result.plan if plan_result else None,
            plan_attempts=plan_attempts,
            task=task,
        )

history property

Get the conversation history (multi-turn mode only).

persisted_variables property

Get the persisted variables from previous turns (multi-turn mode only).

__init__(llm, name='', description='', config=None)

Initialize the PlanExecute agent.

Parameters:

Name Type Description Default
llm LLM | LLMConfig

LLM instance or config for plan generation.

required
name str

Agent name for prompts.

''
description str

Agent description for prompts.

''
config PlanExecuteConfig | None

Extended configuration options.

None
Source code in src/opensymbolicai/blueprints/plan_execute.py
def __init__(
    self,
    llm: LLM | LLMConfig,
    name: str = "",
    description: str = "",
    config: PlanExecuteConfig | None = None,
) -> None:
    """Initialize the PlanExecute agent.

    Args:
        llm: LLM instance or config for plan generation.
        name: Agent name for prompts.
        description: Agent description for prompts.
        config: Extended configuration options.
    """
    if isinstance(llm, LLMConfig):
        self._llm = create_llm(llm)
    else:
        self._llm = llm

    self.name = name or self.__class__.__name__
    self.description = description or self.__class__.__doc__ or ""
    self.config = config or PlanExecuteConfig()
    self.allowed_builtins = (
        self.config.allowed_builtins
        if self.config.allowed_builtins is not None
        else DEFAULT_ALLOWED_BUILTINS.copy()
    )

    # Multi-turn state
    self._history: list[ConversationTurn] = []
    self._persisted_namespace: dict[str, Any] = {}

analyze_plan(plan)

Analyze a plan to extract primitive calls.

Parameters:

Name Type Description Default
plan str

The Python statements to analyze.

required

Returns:

Type Description
PlanAnalysis

PlanAnalysis containing all primitive calls found.

Raises:

Type Description
ValueError

If the plan has invalid syntax.

Source code in src/opensymbolicai/blueprints/plan_execute.py
def analyze_plan(self, plan: str) -> PlanAnalysis:
    """Analyze a plan to extract primitive calls.

    Args:
        plan: The Python statements to analyze.

    Returns:
        PlanAnalysis containing all primitive calls found.

    Raises:
        ValueError: If the plan has invalid syntax.
    """
    try:
        tree = ast.parse(plan)
    except SyntaxError as e:
        raise ValueError(f"Invalid Python syntax: {e}") from e

    primitive_names = self._get_primitive_names()
    read_only_map = self._get_primitive_read_only_map()
    calls: list[PrimitiveCall] = []

    for node in ast.walk(tree):
        if not isinstance(node, ast.Call):
            continue

        method_name: str | None = None

        # Direct call: method_name(...)
        if isinstance(node.func, ast.Name) and node.func.id in primitive_names:
            method_name = node.func.id

        # Method call on self: self.method_name(...)
        elif (
            isinstance(node.func, ast.Attribute)
            and isinstance(node.func.value, ast.Name)
            and node.func.value.id == "self"
            and node.func.attr in primitive_names
        ):
            method_name = node.func.attr

        if method_name is not None:
            args: dict[str, Any] = {}
            for kw in node.keywords:
                if kw.arg is not None:
                    try:
                        args[kw.arg] = ast.literal_eval(kw.value)
                    except (ValueError, TypeError):
                        args[kw.arg] = ast.unparse(kw.value)

            for i, arg in enumerate(node.args):
                try:
                    args[f"arg{i}"] = ast.literal_eval(arg)
                except (ValueError, TypeError):
                    args[f"arg{i}"] = ast.unparse(arg)

            calls.append(
                PrimitiveCall(
                    method_name=method_name,
                    read_only=read_only_map.get(method_name, False),
                    args=args,
                )
            )

    return PlanAnalysis(calls=calls)

build_plan_prompt(task, feedback=None)

Build the prompt for the LLM to generate a plan.

Override this method in subclasses to customize the prompt sent to the LLM.

Parameters:

Name Type Description Default
task str

The task description to plan for.

required
feedback str | None

Optional error feedback from a previous failed plan attempt.

None

Returns:

Type Description
str

The complete prompt string to send to the LLM.

Source code in src/opensymbolicai/blueprints/plan_execute.py
    def build_plan_prompt(self, task: str, feedback: str | None = None) -> str:
        """Build the prompt for the LLM to generate a plan.

        Override this method in subclasses to customize the prompt sent to the LLM.

        Args:
            task: The task description to plan for.
            feedback: Optional error feedback from a previous failed plan attempt.

        Returns:
            The complete prompt string to send to the LLM.
        """
        primitives = self._get_primitive_methods()
        decompositions = self._get_decomposition_methods()

        # Build primitive documentation
        primitive_docs = [
            self._format_primitive_signature(name, method)
            for name, method in primitives
        ]

        # Build decomposition examples
        examples = []
        for _name, method, intent, expanded in decompositions:
            source = self._get_decomposition_source(method)
            if source:
                example = f"Intent: {intent}"
                if expanded:
                    example += f"\nApproach: {expanded}"
                example += f"\nPython:\n{source}"
                examples.append(example)

        # Build conversation history section if in multi-turn mode
        history_section = ""
        if self.config.multi_turn and self._history:
            history_section = f"""
## Conversation History

Previous turns in this conversation. You can reference variables from previous turns.

{self._format_history_for_prompt()}

"""

        # Build feedback section if retrying after a failed plan
        feedback_section = ""
        if feedback:
            feedback_section = f"""
## Previous Attempt Failed

Your previous plan was invalid. Please fix the following error and regenerate:

{feedback}

"""

        prompt = f"""You are {self.name}, an AI agent that generates Python code plans.

{self.description}

## Available Primitive Methods

You can ONLY call these methods:

```python
{chr(10).join(primitive_docs)}
```

## Example Decompositions

Here are examples of how to compose primitives:

{chr(10).join(f"### Example {i + 1}{chr(10)}{ex}" for i, ex in enumerate(examples)) if examples else "No examples available."}
{history_section}{feedback_section}## Task

Generate Python code to accomplish this task: {task}

## Rules

1. Output ONLY Python assignment statements
2. Each statement must assign a result to a variable
3. You can ONLY call the primitive methods listed above
4. Do NOT use imports, loops, conditionals, or function definitions
5. Do NOT use any dangerous operations (exec, eval, open, etc.)
6. The last assigned variable will be the final result

## Output

```python
"""
        return prompt

execute(plan)

Execute a plan step-by-step with full tracing.

Parameters:

Name Type Description Default
plan str

The Python statements to execute.

required

Returns:

Type Description
ExecutionResult

ExecutionResult containing the final value and execution trace.

Raises:

Type Description
ValueError

If the plan contains disallowed operations.

Source code in src/opensymbolicai/blueprints/plan_execute.py
def execute(self, plan: str) -> ExecutionResult:
    """Execute a plan step-by-step with full tracing.

    Args:
        plan: The Python statements to execute.

    Returns:
        ExecutionResult containing the final value and execution trace.

    Raises:
        ValueError: If the plan contains disallowed operations.
    """
    self.validate_plan(plan)

    tree = ast.parse(plan)
    steps: list[ExecutionStep] = []
    total_start = time.perf_counter()

    # Build execution namespace
    namespace: dict[str, Any] = {"self": self}
    for name, method in self._get_primitive_methods():
        namespace[name] = method
    namespace.update(self.allowed_builtins)

    # Include persisted variables from previous turns in multi-turn mode
    if self.config.multi_turn:
        namespace.update(self._persisted_namespace)

    # Get read_only map for mutation hook
    read_only_map = self._get_primitive_read_only_map()

    # Calculate reserved names for namespace snapshots
    reserved_names = (
        {"self"}
        | set(self.allowed_builtins.keys())
        | {name for name, _ in self._get_primitive_methods()}
    )

    # Execute statement by statement
    for i, stmt in enumerate(tree.body, 1):
        step = self._execute_statement(
            stmt, namespace, i, read_only_map, reserved_names
        )
        steps.append(step)

        # Stop on first error
        if not step.success:
            break

    # Persist user-defined variables for multi-turn mode
    if self.config.multi_turn:
        for key, value in namespace.items():
            if key not in reserved_names:
                self._persisted_namespace[key] = value

    total_elapsed = time.perf_counter() - total_start

    trace = ExecutionTrace(
        steps=steps,
        total_time_seconds=total_elapsed,
    )

    # Determine final result
    if steps and steps[-1].success:
        last = steps[-1]
        return ExecutionResult(
            value_type=last.result_type,
            value_name=last.variable_name,
            value_json=last.result_json,
            trace=trace,
        )
    else:
        return ExecutionResult(
            value_type="NoneType",
            value_name="",
            value_json="null",
            trace=trace,
        )

execute_stepwise(task, plan_context=None, serializer=None, checkpoint_id=None)

Execute a plan step-by-step, yielding checkpoints for persistence.

This method enables distributed execution by yielding a checkpoint after each step. The checkpoint can be persisted to a database and resumed on any worker.

When require_mutation_approval is True (default), execution pauses before mutations and yields a checkpoint with status awaiting_approval. Call resume_from_checkpoint() with approve_mutation=True to continue.

Parameters:

Name Type Description Default
task str

The task description to accomplish.

required
plan_context PlanContext | None

Optional pre-computed plan context (from a previous planning phase). If None, will generate a new plan.

None
serializer SerializerRegistry | None

Custom serializer registry. Defaults to the global registry.

None
checkpoint_id str | None

Optional ID for the checkpoint. Auto-generated if None.

None

Yields:

Type Description
ExecutionCheckpoint

ExecutionCheckpoint after each step, allowing for persistence and

ExecutionCheckpoint

distributed resume.

Example

Simple usage - collect all checkpoints

for checkpoint in agent.execute_stepwise("do something"): store.save(checkpoint) if checkpoint.status == CheckpointStatus.AWAITING_APPROVAL: # Handle approval externally break

Resume after approval

checkpoint = store.load(checkpoint_id) for checkpoint in agent.resume_from_checkpoint(checkpoint, approve_mutation=True): store.save(checkpoint)

Source code in src/opensymbolicai/blueprints/plan_execute.py
def execute_stepwise(
    self,
    task: str,
    plan_context: PlanContext | None = None,
    serializer: SerializerRegistry | None = None,
    checkpoint_id: str | None = None,
) -> Iterator[ExecutionCheckpoint]:
    """Execute a plan step-by-step, yielding checkpoints for persistence.

    This method enables distributed execution by yielding a checkpoint after
    each step. The checkpoint can be persisted to a database and resumed on
    any worker.

    When `require_mutation_approval` is True (default), execution pauses
    before mutations and yields a checkpoint with status `awaiting_approval`.
    Call `resume_from_checkpoint()` with `approve_mutation=True` to continue.

    Args:
        task: The task description to accomplish.
        plan_context: Optional pre-computed plan context (from a previous
            planning phase). If None, will generate a new plan.
        serializer: Custom serializer registry. Defaults to the global registry.
        checkpoint_id: Optional ID for the checkpoint. Auto-generated if None.

    Yields:
        ExecutionCheckpoint after each step, allowing for persistence and
        distributed resume.

    Example:
        # Simple usage - collect all checkpoints
        for checkpoint in agent.execute_stepwise("do something"):
            store.save(checkpoint)
            if checkpoint.status == CheckpointStatus.AWAITING_APPROVAL:
                # Handle approval externally
                break

        # Resume after approval
        checkpoint = store.load(checkpoint_id)
        for checkpoint in agent.resume_from_checkpoint(checkpoint, approve_mutation=True):
            store.save(checkpoint)
    """
    serializer = serializer or default_serializer_registry

    # Generate plan if not provided
    if plan_context is None:
        plan_result = self.plan(task)
        plan_context = PlanContext(
            plan_attempts=[
                PlanAttempt(
                    attempt_number=1,
                    plan_generation=plan_result.plan_generation
                    or PlanGeneration(
                        llm_interaction=LLMInteraction(
                            prompt="",
                            response="",
                            input_tokens=plan_result.usage.input_tokens,
                            output_tokens=plan_result.usage.output_tokens,
                            time_seconds=plan_result.time_seconds,
                            provider=plan_result.provider,
                            model=plan_result.model,
                        ),
                        extracted_code=plan_result.plan,
                    ),
                    success=True,
                )
            ],
            final_plan=plan_result.plan,
            generation_time_seconds=plan_result.time_seconds,
        )

    plan = plan_context.final_plan

    # Validate plan
    try:
        self.validate_plan(plan)
    except ValueError as e:
        checkpoint = ExecutionCheckpoint(
            task=task,
            plan=plan,
            plan_context=plan_context,
            current_step=0,
            total_steps=0,
            status=CheckpointStatus.FAILED,
            error=str(e),
            worker_id=self.config.worker_id,
        )
        if checkpoint_id is not None:
            checkpoint.checkpoint_id = checkpoint_id
        yield checkpoint
        return

    tree = ast.parse(plan)
    total_steps = len(tree.body)

    # Build execution namespace
    namespace: dict[str, Any] = {"self": self}
    for name, method in self._get_primitive_methods():
        namespace[name] = method
    namespace.update(self.allowed_builtins)

    if self.config.multi_turn:
        namespace.update(self._persisted_namespace)

    read_only_map = self._get_primitive_read_only_map()
    reserved_names = (
        {"self"}
        | set(self.allowed_builtins.keys())
        | {name for name, _ in self._get_primitive_methods()}
    )

    steps: list[ExecutionStep] = []

    # Create initial checkpoint
    checkpoint = ExecutionCheckpoint(
        task=task,
        plan=plan,
        plan_context=plan_context,
        current_step=0,
        total_steps=total_steps,
        status=CheckpointStatus.RUNNING,
        namespace_snapshot=serializer.serialize_namespace(
            namespace, reserved_names
        ),
        completed_steps=[],
        worker_id=self.config.worker_id,
    )
    if checkpoint_id is not None:
        checkpoint.checkpoint_id = checkpoint_id

    # Execute statement by statement
    for i, stmt in enumerate(tree.body):
        step_number = i + 1
        statement_str = ast.unparse(stmt)

        # Check if this is a mutation requiring approval
        is_mutation = False
        method_name: str | None = None
        variable_name = ""
        args_for_pending: dict[str, Any] = {}

        if isinstance(stmt, ast.Assign):
            if stmt.targets and isinstance(stmt.targets[0], ast.Name):
                variable_name = stmt.targets[0].id
            if isinstance(stmt.value, ast.Call):
                call = stmt.value
                if isinstance(call.func, ast.Name):
                    method_name = call.func.id
                elif isinstance(call.func, ast.Attribute):
                    method_name = call.func.attr

                if method_name and not read_only_map.get(method_name, True):
                    is_mutation = True
                    # Extract args for pending mutation info
                    for idx, arg in enumerate(call.args):
                        try:
                            args_for_pending[f"arg{idx}"] = ast.literal_eval(arg)
                        except (ValueError, TypeError):
                            args_for_pending[f"arg{idx}"] = ast.unparse(arg)
                    for kw in call.keywords:
                        if kw.arg:
                            try:
                                args_for_pending[kw.arg] = ast.literal_eval(
                                    kw.value
                                )
                            except (ValueError, TypeError):
                                args_for_pending[kw.arg] = ast.unparse(kw.value)

        # If mutation requires approval, pause and yield
        if is_mutation and self.config.require_mutation_approval:
            checkpoint.current_step = i
            checkpoint.status = CheckpointStatus.AWAITING_APPROVAL
            checkpoint.pending_mutation = PendingMutation(
                method_name=method_name or "",
                args=args_for_pending,
                statement=statement_str,
                step_number=step_number,
                variable_name=variable_name,
            )
            checkpoint.namespace_snapshot = serializer.serialize_namespace(
                namespace, reserved_names
            )
            checkpoint.completed_steps = steps.copy()
            checkpoint.touch(self.config.worker_id)
            yield checkpoint
            return  # Caller must resume with approve_mutation=True

        # Execute the step
        step = self._execute_statement(
            stmt, namespace, step_number, read_only_map, reserved_names
        )
        steps.append(step)

        # Update checkpoint
        checkpoint.current_step = step_number
        checkpoint.completed_steps = steps.copy()
        checkpoint.namespace_snapshot = serializer.serialize_namespace(
            namespace, reserved_names
        )

        if not step.success:
            checkpoint.status = CheckpointStatus.FAILED
            checkpoint.error = step.error
            checkpoint.touch(self.config.worker_id)
            yield checkpoint
            return

        # Yield progress checkpoint
        checkpoint.status = CheckpointStatus.RUNNING
        checkpoint.touch(self.config.worker_id)
        yield checkpoint

    # Execution completed successfully
    checkpoint.status = CheckpointStatus.COMPLETED
    if steps:
        last_step = steps[-1]
        checkpoint.result_variable = last_step.variable_name
        result_value = namespace.get(last_step.variable_name)
        checkpoint.result_value = serializer.serialize(result_value)

    # Persist for multi-turn
    if self.config.multi_turn:
        for key, value in namespace.items():
            if key not in reserved_names:
                self._persisted_namespace[key] = value

    checkpoint.touch(self.config.worker_id)
    yield checkpoint

on_code_extracted(raw_response, extracted_code)

Hook called after code is extracted from the LLM response.

Override this method in subclasses to observe and/or modify the extracted code before it is used for planning.

Parameters:

Name Type Description Default
raw_response str

The original raw text response from the LLM.

required
extracted_code str

The code extracted by _extract_code_block.

required

Returns:

Type Description
str

The final code to use (can be modified from extracted_code).

Source code in src/opensymbolicai/blueprints/plan_execute.py
def on_code_extracted(self, raw_response: str, extracted_code: str) -> str:
    """Hook called after code is extracted from the LLM response.

    Override this method in subclasses to observe and/or modify the
    extracted code before it is used for planning.

    Args:
        raw_response: The original raw text response from the LLM.
        extracted_code: The code extracted by _extract_code_block.

    Returns:
        The final code to use (can be modified from extracted_code).
    """
    return extracted_code

plan(task, feedback=None)

Generate a plan (Python statements) for a task.

Parameters:

Name Type Description Default
task str

The task description to plan for.

required
feedback str | None

Optional error feedback from a previous failed plan attempt.

None

Returns:

Type Description
PlanResult

PlanResult containing the generated plan and metrics.

Source code in src/opensymbolicai/blueprints/plan_execute.py
def plan(self, task: str, feedback: str | None = None) -> PlanResult:
    """Generate a plan (Python statements) for a task.

    Args:
        task: The task description to plan for.
        feedback: Optional error feedback from a previous failed plan attempt.

    Returns:
        PlanResult containing the generated plan and metrics.
    """
    prompt = self.build_plan_prompt(task, feedback=feedback)
    start_time = time.perf_counter()
    response = self._llm.generate(prompt)
    elapsed = time.perf_counter() - start_time

    # Extract code from response (handle markdown code blocks)
    raw_response = response.text
    extracted_code = self._extract_code_block(raw_response)
    plan_text = self.on_code_extracted(raw_response, extracted_code)

    # Build full LLM interaction details
    llm_interaction = LLMInteraction(
        prompt=prompt,
        response=raw_response,
        input_tokens=response.usage.input_tokens,
        output_tokens=response.usage.output_tokens,
        time_seconds=elapsed,
        provider=response.provider,
        model=response.model,
    )
    plan_generation = PlanGeneration(
        llm_interaction=llm_interaction,
        extracted_code=extracted_code,
    )

    return PlanResult(
        plan=plan_text,
        usage=ModelTokenUsage(
            input_tokens=response.usage.input_tokens,
            output_tokens=response.usage.output_tokens,
        ),
        time_seconds=elapsed,
        provider=response.provider,
        model=response.model,
        plan_generation=plan_generation,
    )

resume_from_checkpoint(checkpoint, approve_mutation=False, serializer=None)

Resume execution from a persisted checkpoint.

This method reconstructs execution state from a checkpoint and continues execution from where it left off.

Parameters:

Name Type Description Default
checkpoint ExecutionCheckpoint

The checkpoint to resume from.

required
approve_mutation bool

If True and checkpoint is awaiting approval, execute the pending mutation and continue.

False
serializer SerializerRegistry | None

Custom serializer registry. Must match the one used when creating the checkpoint.

None

Yields:

Type Description
ExecutionCheckpoint

ExecutionCheckpoint after each step.

Raises:

Type Description
ValueError

If checkpoint is in a terminal state or approval is required but not provided.

Example

Load and resume

checkpoint = store.load(checkpoint_id) if checkpoint.status == CheckpointStatus.AWAITING_APPROVAL: # Get user approval somehow if user_approved: for cp in agent.resume_from_checkpoint(checkpoint, approve_mutation=True): store.save(cp)

Source code in src/opensymbolicai/blueprints/plan_execute.py
def resume_from_checkpoint(
    self,
    checkpoint: ExecutionCheckpoint,
    approve_mutation: bool = False,
    serializer: SerializerRegistry | None = None,
) -> Iterator[ExecutionCheckpoint]:
    """Resume execution from a persisted checkpoint.

    This method reconstructs execution state from a checkpoint and continues
    execution from where it left off.

    Args:
        checkpoint: The checkpoint to resume from.
        approve_mutation: If True and checkpoint is awaiting approval,
            execute the pending mutation and continue.
        serializer: Custom serializer registry. Must match the one used
            when creating the checkpoint.

    Yields:
        ExecutionCheckpoint after each step.

    Raises:
        ValueError: If checkpoint is in a terminal state or approval is
            required but not provided.

    Example:
        # Load and resume
        checkpoint = store.load(checkpoint_id)
        if checkpoint.status == CheckpointStatus.AWAITING_APPROVAL:
            # Get user approval somehow
            if user_approved:
                for cp in agent.resume_from_checkpoint(checkpoint, approve_mutation=True):
                    store.save(cp)
    """
    serializer = serializer or default_serializer_registry

    if checkpoint.is_terminal:
        raise ValueError(
            f"Cannot resume from terminal checkpoint (status: {checkpoint.status})"
        )

    if (
        checkpoint.status == CheckpointStatus.AWAITING_APPROVAL
        and not approve_mutation
    ):
        raise ValueError(
            "Checkpoint is awaiting mutation approval. "
            "Set approve_mutation=True to continue."
        )

    # Parse the plan
    tree = ast.parse(checkpoint.plan)
    total_steps = len(tree.body)

    # Rebuild namespace
    namespace: dict[str, Any] = {"self": self}
    for name, method in self._get_primitive_methods():
        namespace[name] = method
    namespace.update(self.allowed_builtins)

    if self.config.multi_turn:
        namespace.update(self._persisted_namespace)

    # Restore serialized variables (skip undeserializable values)
    import contextlib

    for var_name, serialized_val in checkpoint.namespace_snapshot.items():
        with contextlib.suppress(ValueError):
            namespace[var_name] = serializer.deserialize(serialized_val)

    read_only_map = self._get_primitive_read_only_map()
    reserved_names = (
        {"self"}
        | set(self.allowed_builtins.keys())
        | {name for name, _ in self._get_primitive_methods()}
    )

    # Copy completed steps
    steps = list(checkpoint.completed_steps)

    # Determine starting point
    start_step = checkpoint.current_step

    # If resuming from awaiting_approval, execute the pending mutation first
    if (
        checkpoint.status == CheckpointStatus.AWAITING_APPROVAL
        and approve_mutation
        and checkpoint.pending_mutation
    ):
        stmt = tree.body[start_step]
        step_number = start_step + 1

        step = self._execute_statement(
            stmt, namespace, step_number, read_only_map, reserved_names
        )
        steps.append(step)

        checkpoint.completed_steps = steps.copy()
        checkpoint.pending_mutation = None

        if not step.success:
            checkpoint.status = CheckpointStatus.FAILED
            checkpoint.error = step.error
            checkpoint.current_step = step_number
            checkpoint.namespace_snapshot = serializer.serialize_namespace(
                namespace, reserved_names
            )
            checkpoint.touch(self.config.worker_id)
            yield checkpoint
            return

        checkpoint.current_step = step_number
        checkpoint.namespace_snapshot = serializer.serialize_namespace(
            namespace, reserved_names
        )
        checkpoint.status = CheckpointStatus.RUNNING
        checkpoint.touch(self.config.worker_id)
        yield checkpoint

        start_step += 1

    # Continue with remaining steps
    for i in range(start_step, total_steps):
        stmt = tree.body[i]
        step_number = i + 1
        statement_str = ast.unparse(stmt)

        # Check for mutations
        is_mutation = False
        method_name: str | None = None
        variable_name = ""
        args_for_pending: dict[str, Any] = {}

        if isinstance(stmt, ast.Assign):
            if stmt.targets and isinstance(stmt.targets[0], ast.Name):
                variable_name = stmt.targets[0].id
            if isinstance(stmt.value, ast.Call):
                call = stmt.value
                if isinstance(call.func, ast.Name):
                    method_name = call.func.id
                elif isinstance(call.func, ast.Attribute):
                    method_name = call.func.attr

                if method_name and not read_only_map.get(method_name, True):
                    is_mutation = True
                    for idx, arg in enumerate(call.args):
                        try:
                            args_for_pending[f"arg{idx}"] = ast.literal_eval(arg)
                        except (ValueError, TypeError):
                            args_for_pending[f"arg{idx}"] = ast.unparse(arg)
                    for kw in call.keywords:
                        if kw.arg:
                            try:
                                args_for_pending[kw.arg] = ast.literal_eval(
                                    kw.value
                                )
                            except (ValueError, TypeError):
                                args_for_pending[kw.arg] = ast.unparse(kw.value)

        # Pause for mutation approval if required
        if is_mutation and self.config.require_mutation_approval:
            checkpoint.current_step = i
            checkpoint.status = CheckpointStatus.AWAITING_APPROVAL
            checkpoint.pending_mutation = PendingMutation(
                method_name=method_name or "",
                args=args_for_pending,
                statement=statement_str,
                step_number=step_number,
                variable_name=variable_name,
            )
            checkpoint.namespace_snapshot = serializer.serialize_namespace(
                namespace, reserved_names
            )
            checkpoint.completed_steps = steps.copy()
            checkpoint.touch(self.config.worker_id)
            yield checkpoint
            return

        # Execute step
        step = self._execute_statement(
            stmt, namespace, step_number, read_only_map, reserved_names
        )
        steps.append(step)

        checkpoint.current_step = step_number
        checkpoint.completed_steps = steps.copy()
        checkpoint.namespace_snapshot = serializer.serialize_namespace(
            namespace, reserved_names
        )

        if not step.success:
            checkpoint.status = CheckpointStatus.FAILED
            checkpoint.error = step.error
            checkpoint.touch(self.config.worker_id)
            yield checkpoint
            return

        checkpoint.status = CheckpointStatus.RUNNING
        checkpoint.touch(self.config.worker_id)
        yield checkpoint

    # Completed
    checkpoint.status = CheckpointStatus.COMPLETED
    if steps:
        last_step = steps[-1]
        checkpoint.result_variable = last_step.variable_name
        result_value = namespace.get(last_step.variable_name)
        checkpoint.result_value = serializer.serialize(result_value)

    if self.config.multi_turn:
        for key, value in namespace.items():
            if key not in reserved_names:
                self._persisted_namespace[key] = value

    checkpoint.touch(self.config.worker_id)
    yield checkpoint

run(task)

Run the complete plan-and-execute cycle.

Parameters:

Name Type Description Default
task str

The task description to accomplish.

required

Returns:

Type Description
OrchestrationResult

OrchestrationResult containing the outcome and metrics.

Source code in src/opensymbolicai/blueprints/plan_execute.py
def run(self, task: str) -> OrchestrationResult:
    """Run the complete plan-and-execute cycle.

    Args:
        task: The task description to accomplish.

    Returns:
        OrchestrationResult containing the outcome and metrics.
    """
    plan_result = None
    feedback: str | None = None
    max_attempts = 1 + self.config.max_plan_retries
    plan_attempts: list[PlanAttempt] = []

    for attempt in range(max_attempts):
        try:
            # Generate plan (with feedback if retrying)
            plan_result = self.plan(task, feedback=feedback)

            # Record the plan attempt
            plan_attempt = PlanAttempt(
                attempt_number=attempt + 1,
                plan_generation=plan_result.plan_generation
                or PlanGeneration(
                    llm_interaction=LLMInteraction(
                        prompt="",
                        response="",
                        input_tokens=plan_result.usage.input_tokens,
                        output_tokens=plan_result.usage.output_tokens,
                        time_seconds=plan_result.time_seconds,
                        provider=plan_result.provider,
                        model=plan_result.model,
                    ),
                    extracted_code=plan_result.plan,
                ),
                feedback=feedback,
                validation_error=None,
                success=True,
            )

            # Validate plan before execution (to catch validation errors for retry)
            try:
                self.validate_plan(plan_result.plan)
            except ValueError as validation_error:
                plan_attempt.validation_error = str(validation_error)
                plan_attempt.success = False
                plan_attempts.append(plan_attempt)
                raise

            plan_attempts.append(plan_attempt)

            # Execute plan
            exec_start = time.perf_counter()
            exec_result = self.execute(plan_result.plan)
            exec_time = time.perf_counter() - exec_start

            metrics = ExecutionMetrics(
                plan_tokens=plan_result.usage,
                plan_time_seconds=plan_result.time_seconds,
                execute_time_seconds=exec_time,
                steps_executed=exec_result.trace.step_count,
                provider=plan_result.provider,
                model=plan_result.model,
            )

            # Check if execution succeeded
            if exec_result.trace.all_succeeded:
                result_value = exec_result.get_value()

                # Track history in multi-turn mode
                if self.config.multi_turn:
                    self._history.append(
                        ConversationTurn(
                            task=task,
                            plan=plan_result.plan,
                            result=result_value,
                            success=True,
                        )
                    )

                return OrchestrationResult(
                    success=True,
                    result=result_value,
                    metrics=metrics,
                    plan=plan_result.plan,
                    trace=exec_result.trace,
                    plan_attempts=plan_attempts,
                    task=task,
                )
            else:
                # Get error from failed step
                failed = (
                    exec_result.trace.failed_steps[0]
                    if exec_result.trace.failed_steps
                    else None
                )
                error_msg = failed.error if failed else "Unknown execution error"

                # Track history in multi-turn mode (even for failures)
                if self.config.multi_turn:
                    self._history.append(
                        ConversationTurn(
                            task=task,
                            plan=plan_result.plan,
                            success=False,
                            error=error_msg,
                        )
                    )

                return OrchestrationResult(
                    success=False,
                    error=error_msg,
                    metrics=metrics,
                    plan=plan_result.plan,
                    trace=exec_result.trace,
                    plan_attempts=plan_attempts,
                    task=task,
                )

        except ValueError as e:
            # Validation error - retry if attempts remaining
            error_msg = str(e)
            if attempt < max_attempts - 1:
                feedback = error_msg
                continue

            # No more retries - return failure
            if self.config.multi_turn and plan_result is not None:
                self._history.append(
                    ConversationTurn(
                        task=task,
                        plan=plan_result.plan,
                        success=False,
                        error=error_msg,
                    )
                )

            return OrchestrationResult(
                success=False,
                error=error_msg,
                plan=plan_result.plan if plan_result else None,
                plan_attempts=plan_attempts,
                task=task,
            )

        except Exception as e:
            error_msg = str(e)

            # Track history in multi-turn mode (even for validation/other failures)
            if self.config.multi_turn and plan_result is not None:
                self._history.append(
                    ConversationTurn(
                        task=task,
                        plan=plan_result.plan,
                        success=False,
                        error=error_msg,
                    )
                )

            return OrchestrationResult(
                success=False,
                error=error_msg,
                plan=plan_result.plan if plan_result else None,
                plan_attempts=plan_attempts,
                task=task,
            )

    # Should not reach here, but satisfy type checker
    return OrchestrationResult(
        success=False,
        error="Unexpected: exhausted all plan retry attempts",
        plan=plan_result.plan if plan_result else None,
        plan_attempts=plan_attempts,
        task=task,
    )

run_with_checkpoints(task, store, serializer=None, auto_approve=False)

Run execution with automatic checkpoint persistence.

Convenience method that handles checkpoint saving automatically.

Parameters:

Name Type Description Default
task str

The task to execute.

required
store CheckpointStore

Checkpoint store for persistence.

required
serializer SerializerRegistry | None

Custom serializer registry.

None
auto_approve bool

If True, automatically approve all mutations.

False

Returns:

Type Description
ExecutionCheckpoint

The final checkpoint (completed or failed).

Source code in src/opensymbolicai/blueprints/plan_execute.py
def run_with_checkpoints(
    self,
    task: str,
    store: CheckpointStore,
    serializer: SerializerRegistry | None = None,
    auto_approve: bool = False,
) -> ExecutionCheckpoint:
    """Run execution with automatic checkpoint persistence.

    Convenience method that handles checkpoint saving automatically.

    Args:
        task: The task to execute.
        store: Checkpoint store for persistence.
        serializer: Custom serializer registry.
        auto_approve: If True, automatically approve all mutations.

    Returns:
        The final checkpoint (completed or failed).
    """
    checkpoint: ExecutionCheckpoint | None = None

    for checkpoint in self.execute_stepwise(task, serializer=serializer):
        store.save(checkpoint)

        if checkpoint.status == CheckpointStatus.AWAITING_APPROVAL:
            if auto_approve:
                # Resume with approval - consume all checkpoints from resume
                current_cp = checkpoint
                while current_cp.status == CheckpointStatus.AWAITING_APPROVAL:
                    for next_cp in self.resume_from_checkpoint(
                        current_cp, approve_mutation=True, serializer=serializer
                    ):
                        store.save(next_cp)
                        current_cp = next_cp
                checkpoint = current_cp
            else:
                # Return checkpoint for external approval
                return checkpoint

    if checkpoint is None:
        raise RuntimeError("No checkpoint was generated")

    return checkpoint

validate_plan(plan)

Validate that a plan only uses allowed operations.

Parameters:

Name Type Description Default
plan str

The Python statements to validate.

required

Raises:

Type Description
ValueError

If the plan contains disallowed operations.

Source code in src/opensymbolicai/blueprints/plan_execute.py
def validate_plan(self, plan: str) -> None:
    """Validate that a plan only uses allowed operations.

    Args:
        plan: The Python statements to validate.

    Raises:
        ValueError: If the plan contains disallowed operations.
    """
    try:
        tree = ast.parse(plan)
    except SyntaxError as e:
        raise ValueError(f"Invalid Python syntax: {e}") from e

    primitive_names = self._get_primitive_names()
    dangerous_builtins = {
        "exec",
        "eval",
        "compile",
        "open",
        "__import__",
        "globals",
        "locals",
        "vars",
        "dir",
        "getattr",
        "setattr",
        "delattr",
        "hasattr",
        "type",
        "isinstance",
        "issubclass",
        "callable",
        "breakpoint",
        "input",
        "memoryview",
        "object",
    }

    disallowed_statements: tuple[type, ...] = (
        ast.If,
        ast.For,
        ast.While,
        ast.Try,
        ast.With,
        ast.FunctionDef,
        ast.AsyncFunctionDef,
        ast.ClassDef,
        ast.Import,
        ast.ImportFrom,
        ast.Global,
        ast.Nonlocal,
        ast.Raise,
        ast.Assert,
        ast.Delete,
    )
    if hasattr(ast, "Match"):
        disallowed_statements = (*disallowed_statements, ast.Match)

    for node in ast.walk(tree):
        if isinstance(node, disallowed_statements):
            node_type = type(node).__name__
            raise ValueError(f"{node_type} statements are not allowed in plans")

    # Every top-level statement must be an assignment
    for stmt in tree.body:
        if not isinstance(stmt, (ast.Assign, ast.AnnAssign)):
            stmt_type = type(stmt).__name__
            raise ValueError(
                f"Every statement must be an assignment. Found: {stmt_type}"
            )

    for node in ast.walk(tree):
        # Disallow private/dunder attributes
        if isinstance(node, ast.Attribute) and node.attr.startswith("_"):
            raise ValueError(
                f"Accessing private/dunder attributes not allowed: {node.attr}"
            )

        # Validate function calls
        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                func_name = node.func.id
                if func_name in dangerous_builtins:
                    raise ValueError(f"Calling '{func_name}' is not allowed")
                allowed_names = primitive_names | set(self.allowed_builtins.keys())
                if func_name not in allowed_names:
                    raise ValueError(
                        f"Function '{func_name}' is not allowed. "
                        f"Only primitive methods and allowed builtins can be called."
                    )

            if (
                isinstance(node.func, ast.Attribute)
                and isinstance(node.func.value, ast.Name)
                and node.func.value.id == "self"
                and node.func.attr not in primitive_names
            ):
                raise ValueError(f"Method '{node.func.attr}' is not a primitive.")

PlanExecuteConfig

Bases: BaseModel

Extended configuration for PlanExecute agents.

Source code in src/opensymbolicai/models.py
class PlanExecuteConfig(BaseModel):
    """Extended configuration for PlanExecute agents."""

    allowed_builtins: dict[str, Any] | None = Field(
        default=None,
        description="Dict of builtins allowed in execution. None uses defaults.",
    )
    skip_result_serialization: bool = Field(
        default=False,
        description="Skip JSON serialization of results. Useful for large or non-serializable outputs.",
    )
    multi_turn: bool = Field(
        default=False,
        description="Enable multi-turn mode. Persists variables and tracks conversation history.",
    )
    on_mutation: MutationHook | None = Field(
        default=None,
        description="Hook called when a primitive with read_only=False is executed. "
        "Return None to allow, or a string rejection reason to block the mutation.",
    )
    max_plan_retries: int = Field(
        default=0,
        description="Maximum number of times to retry plan generation if validation fails. "
        "The LLM will receive the error message as feedback for regeneration.",
    )

    # Checkpoint/distributed execution settings
    require_mutation_approval: bool = Field(
        default=True,
        description="If True, execution pauses before mutations and yields a checkpoint "
        "for external approval. Use with execute_stepwise() for distributed execution.",
    )
    worker_id: str | None = Field(
        default=None,
        description="Identifier for this worker instance. Used in checkpoints to track "
        "which worker created/updated the checkpoint.",
    )

    model_config = {"arbitrary_types_allowed": True}

PlanResult

Bases: BaseModel

Result from the planning phase.

Source code in src/opensymbolicai/models.py
class PlanResult(BaseModel):
    """Result from the planning phase."""

    plan: str = Field(..., description="Generated Python statements")
    usage: TokenUsage = Field(default_factory=TokenUsage, description="Token usage")
    time_seconds: float = Field(default=0.0, description="Time taken to generate plan")
    provider: str = Field(default="", description="LLM provider used")
    model: str = Field(default="", description="Model used")
    plan_generation: PlanGeneration | None = Field(
        default=None, description="Full LLM interaction details for plan generation"
    )

Planner

Bases: ABC

Abstract base class for agents that plan and execute tasks.

The Planner defines the interface for agents that: 1. Generate plans from natural language tasks 2. Execute those plans step-by-step 3. Return structured results with execution traces

Subclasses must implement: - plan(): Generate a plan for a given task - execute(): Execute a plan and return results - run(): Complete plan-and-execute cycle

Source code in src/opensymbolicai/blueprints/planner.py
class Planner(ABC):
    """Abstract base class for agents that plan and execute tasks.

    The Planner defines the interface for agents that:
    1. Generate plans from natural language tasks
    2. Execute those plans step-by-step
    3. Return structured results with execution traces

    Subclasses must implement:
    - plan(): Generate a plan for a given task
    - execute(): Execute a plan and return results
    - run(): Complete plan-and-execute cycle
    """

    @abstractmethod
    def plan(self, task: str) -> PlanResult:
        """Generate a plan (Python statements) for a task.

        Args:
            task: The task description to plan for.

        Returns:
            PlanResult containing the generated plan and metrics.
        """
        ...

    @abstractmethod
    def execute(self, plan: str) -> ExecutionResult:
        """Execute a plan step-by-step.

        Args:
            plan: The Python statements to execute.

        Returns:
            ExecutionResult containing the final value and execution trace.
        """
        ...

    @abstractmethod
    def run(self, task: str) -> OrchestrationResult:
        """Run the complete plan-and-execute cycle.

        Args:
            task: The task description to accomplish.

        Returns:
            OrchestrationResult containing the outcome and metrics.
        """
        ...

execute(plan) abstractmethod

Execute a plan step-by-step.

Parameters:

Name Type Description Default
plan str

The Python statements to execute.

required

Returns:

Type Description
ExecutionResult

ExecutionResult containing the final value and execution trace.

Source code in src/opensymbolicai/blueprints/planner.py
@abstractmethod
def execute(self, plan: str) -> ExecutionResult:
    """Execute a plan step-by-step.

    Args:
        plan: The Python statements to execute.

    Returns:
        ExecutionResult containing the final value and execution trace.
    """
    ...

plan(task) abstractmethod

Generate a plan (Python statements) for a task.

Parameters:

Name Type Description Default
task str

The task description to plan for.

required

Returns:

Type Description
PlanResult

PlanResult containing the generated plan and metrics.

Source code in src/opensymbolicai/blueprints/planner.py
@abstractmethod
def plan(self, task: str) -> PlanResult:
    """Generate a plan (Python statements) for a task.

    Args:
        task: The task description to plan for.

    Returns:
        PlanResult containing the generated plan and metrics.
    """
    ...

run(task) abstractmethod

Run the complete plan-and-execute cycle.

Parameters:

Name Type Description Default
task str

The task description to accomplish.

required

Returns:

Type Description
OrchestrationResult

OrchestrationResult containing the outcome and metrics.

Source code in src/opensymbolicai/blueprints/planner.py
@abstractmethod
def run(self, task: str) -> OrchestrationResult:
    """Run the complete plan-and-execute cycle.

    Args:
        task: The task description to accomplish.

    Returns:
        OrchestrationResult containing the outcome and metrics.
    """
    ...

PreconditionError

Bases: ExecutionError

Exception raised when a precondition for an operation is not met.

Use this when the operation cannot proceed due to missing prerequisites or invalid state (e.g., division by zero, empty collection).

Example

if divisor == 0: raise PreconditionError( "Cannot divide by zero", code="DIVISION_BY_ZERO", details={"dividend": dividend, "divisor": divisor} )

Source code in src/opensymbolicai/exceptions.py
class PreconditionError(ExecutionError):
    """Exception raised when a precondition for an operation is not met.

    Use this when the operation cannot proceed due to missing prerequisites
    or invalid state (e.g., division by zero, empty collection).

    Example:
        if divisor == 0:
            raise PreconditionError(
                "Cannot divide by zero",
                code="DIVISION_BY_ZERO",
                details={"dividend": dividend, "divisor": divisor}
            )
    """

    def __init__(
        self,
        message: str,
        *,
        code: str | None = "PRECONDITION_FAILED",
        details: dict[str, Any] | None = None,
    ) -> None:
        """Initialize precondition error.

        Args:
            message: Human-readable error message.
            code: Error code, defaults to "PRECONDITION_FAILED".
            details: Additional context about the error.
        """
        super().__init__(message, code=code, details=details)

__init__(message, *, code='PRECONDITION_FAILED', details=None)

Initialize precondition error.

Parameters:

Name Type Description Default
message str

Human-readable error message.

required
code str | None

Error code, defaults to "PRECONDITION_FAILED".

'PRECONDITION_FAILED'
details dict[str, Any] | None

Additional context about the error.

None
Source code in src/opensymbolicai/exceptions.py
def __init__(
    self,
    message: str,
    *,
    code: str | None = "PRECONDITION_FAILED",
    details: dict[str, Any] | None = None,
) -> None:
    """Initialize precondition error.

    Args:
        message: Human-readable error message.
        code: Error code, defaults to "PRECONDITION_FAILED".
        details: Additional context about the error.
    """
    super().__init__(message, code=code, details=details)

PrimitiveCall

Bases: BaseModel

Information about a primitive method call in a plan.

Source code in src/opensymbolicai/models.py
class PrimitiveCall(BaseModel):
    """Information about a primitive method call in a plan."""

    method_name: str = Field(..., description="Name of the primitive method")
    read_only: bool = Field(
        default=False, description="Whether the method is read-only"
    )
    args: dict[str, Any] = Field(default_factory=dict, description="Arguments passed")

ResourceError

Bases: ExecutionError

Exception raised when a required resource is unavailable.

Use this for missing files, network failures, or unavailable external services.

Example

raise ResourceError( "Database connection failed", code="DB_UNAVAILABLE", details={"host": "localhost", "port": 5432} )

Source code in src/opensymbolicai/exceptions.py
class ResourceError(ExecutionError):
    """Exception raised when a required resource is unavailable.

    Use this for missing files, network failures, or unavailable
    external services.

    Example:
        raise ResourceError(
            "Database connection failed",
            code="DB_UNAVAILABLE",
            details={"host": "localhost", "port": 5432}
        )
    """

    def __init__(
        self,
        message: str,
        *,
        code: str | None = "RESOURCE_ERROR",
        details: dict[str, Any] | None = None,
        resource: str | None = None,
    ) -> None:
        """Initialize resource error.

        Args:
            message: Human-readable error message.
            code: Error code, defaults to "RESOURCE_ERROR".
            details: Additional context about the error.
            resource: Optional identifier for the unavailable resource.
        """
        if resource:
            details = details or {}
            details["resource"] = resource
        super().__init__(message, code=code, details=details)
        self.resource = resource

__init__(message, *, code='RESOURCE_ERROR', details=None, resource=None)

Initialize resource error.

Parameters:

Name Type Description Default
message str

Human-readable error message.

required
code str | None

Error code, defaults to "RESOURCE_ERROR".

'RESOURCE_ERROR'
details dict[str, Any] | None

Additional context about the error.

None
resource str | None

Optional identifier for the unavailable resource.

None
Source code in src/opensymbolicai/exceptions.py
def __init__(
    self,
    message: str,
    *,
    code: str | None = "RESOURCE_ERROR",
    details: dict[str, Any] | None = None,
    resource: str | None = None,
) -> None:
    """Initialize resource error.

    Args:
        message: Human-readable error message.
        code: Error code, defaults to "RESOURCE_ERROR".
        details: Additional context about the error.
        resource: Optional identifier for the unavailable resource.
    """
    if resource:
        details = details or {}
        details["resource"] = resource
    super().__init__(message, code=code, details=details)
    self.resource = resource

RetryableError

Bases: ExecutionError

Exception raised for errors that may succeed on retry.

Use this for transient failures like network timeouts or rate limits. By default, this does NOT halt execution to allow potential recovery.

Example

raise RetryableError( "API rate limit exceeded", code="RATE_LIMIT", details={"retry_after_seconds": 60} )

Source code in src/opensymbolicai/exceptions.py
class RetryableError(ExecutionError):
    """Exception raised for errors that may succeed on retry.

    Use this for transient failures like network timeouts or rate limits.
    By default, this does NOT halt execution to allow potential recovery.

    Example:
        raise RetryableError(
            "API rate limit exceeded",
            code="RATE_LIMIT",
            details={"retry_after_seconds": 60}
        )
    """

    def __init__(
        self,
        message: str,
        *,
        code: str | None = "RETRYABLE_ERROR",
        details: dict[str, Any] | None = None,
        retry_after: float | None = None,
    ) -> None:
        """Initialize retryable error.

        Args:
            message: Human-readable error message.
            code: Error code, defaults to "RETRYABLE_ERROR".
            details: Additional context about the error.
            retry_after: Optional seconds to wait before retrying.
        """
        if retry_after is not None:
            details = details or {}
            details["retry_after_seconds"] = retry_after
        super().__init__(message, code=code, details=details, halt_execution=False)
        self.retry_after = retry_after

__init__(message, *, code='RETRYABLE_ERROR', details=None, retry_after=None)

Initialize retryable error.

Parameters:

Name Type Description Default
message str

Human-readable error message.

required
code str | None

Error code, defaults to "RETRYABLE_ERROR".

'RETRYABLE_ERROR'
details dict[str, Any] | None

Additional context about the error.

None
retry_after float | None

Optional seconds to wait before retrying.

None
Source code in src/opensymbolicai/exceptions.py
def __init__(
    self,
    message: str,
    *,
    code: str | None = "RETRYABLE_ERROR",
    details: dict[str, Any] | None = None,
    retry_after: float | None = None,
) -> None:
    """Initialize retryable error.

    Args:
        message: Human-readable error message.
        code: Error code, defaults to "RETRYABLE_ERROR".
        details: Additional context about the error.
        retry_after: Optional seconds to wait before retrying.
    """
    if retry_after is not None:
        details = details or {}
        details["retry_after_seconds"] = retry_after
    super().__init__(message, code=code, details=details, halt_execution=False)
    self.retry_after = retry_after

SerializedValue

Bases: BaseModel

A serialized value with type information for deserialization.

Source code in src/opensymbolicai/checkpoint.py
class SerializedValue(BaseModel):
    """A serialized value with type information for deserialization."""

    type_name: str = Field(..., description="Fully qualified type name")
    data: Any = Field(..., description="Serialized data (JSON-compatible)")
    is_primitive: bool = Field(
        default=True,
        description="Whether this is a JSON primitive (no custom deserializer needed)",
    )

SerializerRegistry

Registry for custom type serializers.

Allows registering serializers/deserializers for types that aren't natively JSON-serializable.

Example

registry = SerializerRegistry()

Register a custom class

registry.register( MyClass, serializer=lambda obj: {"field": obj.field}, deserializer=lambda data: MyClass(field=data["field"]) )

Or use decorators

@registry.register_serializer(MyClass) def serialize_myclass(obj: MyClass) -> dict: return {"field": obj.field}

@registry.register_deserializer("mymodule.MyClass") def deserialize_myclass(data: dict) -> MyClass: return MyClass(field=data["field"])

Source code in src/opensymbolicai/checkpoint.py
class SerializerRegistry:
    """Registry for custom type serializers.

    Allows registering serializers/deserializers for types that aren't
    natively JSON-serializable.

    Example:
        registry = SerializerRegistry()

        # Register a custom class
        registry.register(
            MyClass,
            serializer=lambda obj: {"field": obj.field},
            deserializer=lambda data: MyClass(field=data["field"])
        )

        # Or use decorators
        @registry.register_serializer(MyClass)
        def serialize_myclass(obj: MyClass) -> dict:
            return {"field": obj.field}

        @registry.register_deserializer("mymodule.MyClass")
        def deserialize_myclass(data: dict) -> MyClass:
            return MyClass(field=data["field"])
    """

    def __init__(self) -> None:
        self._serializers: dict[type, Serializer] = {}
        self._deserializers: dict[str, Deserializer] = {}
        self._register_defaults()

    def _register_defaults(self) -> None:
        """Register serializers for common types."""
        import base64

        # datetime
        self._serializers[datetime] = lambda dt: dt.isoformat()
        self._deserializers["datetime.datetime"] = lambda s: datetime.fromisoformat(s)

        # bytes
        self._serializers[bytes] = lambda b: base64.b64encode(b).decode("ascii")
        self._deserializers["builtins.bytes"] = lambda s: base64.b64decode(
            s.encode("ascii")
        )

        # set and frozenset
        self._serializers[set] = lambda s: list(s)
        self._deserializers["builtins.set"] = lambda lst: set(lst)
        self._serializers[frozenset] = lambda s: list(s)
        self._deserializers["builtins.frozenset"] = lambda lst: frozenset(lst)

        # tuple (preserve as tuple, not list)
        self._serializers[tuple] = lambda t: list(t)
        self._deserializers["builtins.tuple"] = lambda lst: tuple(lst)

    def register(
        self, type_: type, serializer: Serializer, deserializer: Deserializer
    ) -> None:
        """Register a serializer/deserializer pair for a type.

        Args:
            type_: The Python type to register.
            serializer: Function that converts instance to JSON-compatible data.
            deserializer: Function that converts JSON data back to instance.
        """
        type_name = f"{type_.__module__}.{type_.__qualname__}"
        self._serializers[type_] = serializer
        self._deserializers[type_name] = deserializer

    def register_serializer(self, type_: type) -> Callable[[Serializer], Serializer]:
        """Decorator to register a serializer for a type.

        Example:
            @registry.register_serializer(MyClass)
            def serialize(obj: MyClass) -> dict:
                return {"field": obj.field}
        """

        def decorator(fn: Serializer) -> Serializer:
            self._serializers[type_] = fn
            return fn

        return decorator

    def register_deserializer(
        self, type_name: str
    ) -> Callable[[Deserializer], Deserializer]:
        """Decorator to register a deserializer for a type name.

        Example:
            @registry.register_deserializer("mymodule.MyClass")
            def deserialize(data: dict) -> MyClass:
                return MyClass(field=data["field"])
        """

        def decorator(fn: Deserializer) -> Deserializer:
            self._deserializers[type_name] = fn
            return fn

        return decorator

    def _get_type_name(self, value_type: type) -> str:
        """Get the fully qualified type name."""
        return f"{value_type.__module__}.{value_type.__qualname__}"

    def serialize(self, value: Any) -> SerializedValue:
        """Serialize a value to a SerializedValue.

        Args:
            value: The value to serialize.

        Returns:
            SerializedValue with type info and serialized data.
        """
        # Handle None
        if value is None:
            return SerializedValue(type_name="NoneType", data=None, is_primitive=True)

        value_type = type(value)
        type_name = self._get_type_name(value_type)

        # Check for JSON primitives
        if isinstance(value, bool):  # Must check bool before int (bool is subclass)
            return SerializedValue(
                type_name="builtins.bool", data=value, is_primitive=True
            )
        if isinstance(value, int):
            return SerializedValue(
                type_name="builtins.int", data=value, is_primitive=True
            )
        if isinstance(value, float):
            return SerializedValue(
                type_name="builtins.float", data=value, is_primitive=True
            )
        if isinstance(value, str):
            return SerializedValue(
                type_name="builtins.str", data=value, is_primitive=True
            )

        # Check for registered serializer (before generic handling)
        if value_type in self._serializers:
            serializer = self._serializers[value_type]
            return SerializedValue(
                type_name=type_name, data=serializer(value), is_primitive=False
            )

        # Check for lists (recursively serialize)
        if isinstance(value, list):
            serialized_items = [self.serialize(item).model_dump() for item in value]
            return SerializedValue(
                type_name="builtins.list",
                data=serialized_items,
                is_primitive=False,
            )

        # Check for dicts (recursively serialize)
        if isinstance(value, dict):
            serialized_dict = {
                k: self.serialize(v).model_dump() for k, v in value.items()
            }
            return SerializedValue(
                type_name="builtins.dict",
                data=serialized_dict,
                is_primitive=False,
            )

        # Check if it's a Pydantic model
        if hasattr(value, "model_dump"):
            return SerializedValue(
                type_name=type_name,
                data={"__pydantic__": True, "data": value.model_dump()},
                is_primitive=False,
            )

        # Fallback: try to convert to string representation
        return SerializedValue(
            type_name=type_name,
            data={"__repr__": repr(value), "__unserializable__": True},
            is_primitive=False,
        )

    def deserialize(self, serialized: SerializedValue) -> Any:
        """Deserialize a SerializedValue back to its original value.

        Args:
            serialized: The SerializedValue to deserialize.

        Returns:
            The deserialized value.

        Raises:
            ValueError: If no deserializer is registered for the type.
        """
        # Handle None
        if serialized.type_name == "NoneType":
            return None

        # Handle primitives
        if serialized.is_primitive:
            return serialized.data

        # Handle lists
        if serialized.type_name == "builtins.list":
            return [
                self.deserialize(SerializedValue(**item)) for item in serialized.data
            ]

        # Handle dicts
        if serialized.type_name == "builtins.dict":
            return {
                k: self.deserialize(SerializedValue(**v))
                for k, v in serialized.data.items()
            }

        # Check for registered deserializer
        if serialized.type_name in self._deserializers:
            deserializer = self._deserializers[serialized.type_name]
            return deserializer(serialized.data)

        # Check for Pydantic model marker
        if isinstance(serialized.data, dict) and serialized.data.get("__pydantic__"):
            raise ValueError(
                f"Cannot deserialize Pydantic model '{serialized.type_name}': "
                f"register a deserializer that can reconstruct the model from: "
                f"{serialized.data['data']}"
            )

        # Check for __repr__ fallback (non-deserializable)
        if isinstance(serialized.data, dict) and serialized.data.get(
            "__unserializable__"
        ):
            raise ValueError(
                f"Cannot deserialize type '{serialized.type_name}': "
                f"no deserializer registered. Original repr: {serialized.data.get('__repr__', 'unknown')}"
            )

        raise ValueError(
            f"No deserializer registered for type '{serialized.type_name}'"
        )

    def can_deserialize(self, type_name: str) -> bool:
        """Check if a type can be deserialized."""
        if type_name in ("NoneType", "builtins.list", "builtins.dict"):
            return True
        # Primitives
        if type_name in (
            "builtins.bool",
            "builtins.int",
            "builtins.float",
            "builtins.str",
        ):
            return True
        return type_name in self._deserializers

    def serialize_namespace(
        self, namespace: dict[str, Any], exclude: set[str] | None = None
    ) -> dict[str, SerializedValue]:
        """Serialize an entire namespace dict.

        Args:
            namespace: The namespace to serialize.
            exclude: Keys to exclude from serialization.

        Returns:
            Dict mapping variable names to SerializedValues.
        """
        exclude = exclude or set()
        result: dict[str, SerializedValue] = {}
        for key, value in namespace.items():
            if key in exclude:
                continue
            result[key] = self.serialize(value)
        return result

    def deserialize_namespace(
        self, serialized: dict[str, SerializedValue]
    ) -> dict[str, Any]:
        """Deserialize a namespace back to regular values.

        Args:
            serialized: Dict of serialized values.

        Returns:
            Dict mapping variable names to deserialized values.
        """
        result: dict[str, Any] = {}
        for key, value in serialized.items():
            result[key] = self.deserialize(value)
        return result

can_deserialize(type_name)

Check if a type can be deserialized.

Source code in src/opensymbolicai/checkpoint.py
def can_deserialize(self, type_name: str) -> bool:
    """Check if a type can be deserialized."""
    if type_name in ("NoneType", "builtins.list", "builtins.dict"):
        return True
    # Primitives
    if type_name in (
        "builtins.bool",
        "builtins.int",
        "builtins.float",
        "builtins.str",
    ):
        return True
    return type_name in self._deserializers

deserialize(serialized)

Deserialize a SerializedValue back to its original value.

Parameters:

Name Type Description Default
serialized SerializedValue

The SerializedValue to deserialize.

required

Returns:

Type Description
Any

The deserialized value.

Raises:

Type Description
ValueError

If no deserializer is registered for the type.

Source code in src/opensymbolicai/checkpoint.py
def deserialize(self, serialized: SerializedValue) -> Any:
    """Deserialize a SerializedValue back to its original value.

    Args:
        serialized: The SerializedValue to deserialize.

    Returns:
        The deserialized value.

    Raises:
        ValueError: If no deserializer is registered for the type.
    """
    # Handle None
    if serialized.type_name == "NoneType":
        return None

    # Handle primitives
    if serialized.is_primitive:
        return serialized.data

    # Handle lists
    if serialized.type_name == "builtins.list":
        return [
            self.deserialize(SerializedValue(**item)) for item in serialized.data
        ]

    # Handle dicts
    if serialized.type_name == "builtins.dict":
        return {
            k: self.deserialize(SerializedValue(**v))
            for k, v in serialized.data.items()
        }

    # Check for registered deserializer
    if serialized.type_name in self._deserializers:
        deserializer = self._deserializers[serialized.type_name]
        return deserializer(serialized.data)

    # Check for Pydantic model marker
    if isinstance(serialized.data, dict) and serialized.data.get("__pydantic__"):
        raise ValueError(
            f"Cannot deserialize Pydantic model '{serialized.type_name}': "
            f"register a deserializer that can reconstruct the model from: "
            f"{serialized.data['data']}"
        )

    # Check for __repr__ fallback (non-deserializable)
    if isinstance(serialized.data, dict) and serialized.data.get(
        "__unserializable__"
    ):
        raise ValueError(
            f"Cannot deserialize type '{serialized.type_name}': "
            f"no deserializer registered. Original repr: {serialized.data.get('__repr__', 'unknown')}"
        )

    raise ValueError(
        f"No deserializer registered for type '{serialized.type_name}'"
    )

deserialize_namespace(serialized)

Deserialize a namespace back to regular values.

Parameters:

Name Type Description Default
serialized dict[str, SerializedValue]

Dict of serialized values.

required

Returns:

Type Description
dict[str, Any]

Dict mapping variable names to deserialized values.

Source code in src/opensymbolicai/checkpoint.py
def deserialize_namespace(
    self, serialized: dict[str, SerializedValue]
) -> dict[str, Any]:
    """Deserialize a namespace back to regular values.

    Args:
        serialized: Dict of serialized values.

    Returns:
        Dict mapping variable names to deserialized values.
    """
    result: dict[str, Any] = {}
    for key, value in serialized.items():
        result[key] = self.deserialize(value)
    return result

register(type_, serializer, deserializer)

Register a serializer/deserializer pair for a type.

Parameters:

Name Type Description Default
type_ type

The Python type to register.

required
serializer Serializer

Function that converts instance to JSON-compatible data.

required
deserializer Deserializer

Function that converts JSON data back to instance.

required
Source code in src/opensymbolicai/checkpoint.py
def register(
    self, type_: type, serializer: Serializer, deserializer: Deserializer
) -> None:
    """Register a serializer/deserializer pair for a type.

    Args:
        type_: The Python type to register.
        serializer: Function that converts instance to JSON-compatible data.
        deserializer: Function that converts JSON data back to instance.
    """
    type_name = f"{type_.__module__}.{type_.__qualname__}"
    self._serializers[type_] = serializer
    self._deserializers[type_name] = deserializer

register_deserializer(type_name)

Decorator to register a deserializer for a type name.

Example

@registry.register_deserializer("mymodule.MyClass") def deserialize(data: dict) -> MyClass: return MyClass(field=data["field"])

Source code in src/opensymbolicai/checkpoint.py
def register_deserializer(
    self, type_name: str
) -> Callable[[Deserializer], Deserializer]:
    """Decorator to register a deserializer for a type name.

    Example:
        @registry.register_deserializer("mymodule.MyClass")
        def deserialize(data: dict) -> MyClass:
            return MyClass(field=data["field"])
    """

    def decorator(fn: Deserializer) -> Deserializer:
        self._deserializers[type_name] = fn
        return fn

    return decorator

register_serializer(type_)

Decorator to register a serializer for a type.

Example

@registry.register_serializer(MyClass) def serialize(obj: MyClass) -> dict: return {"field": obj.field}

Source code in src/opensymbolicai/checkpoint.py
def register_serializer(self, type_: type) -> Callable[[Serializer], Serializer]:
    """Decorator to register a serializer for a type.

    Example:
        @registry.register_serializer(MyClass)
        def serialize(obj: MyClass) -> dict:
            return {"field": obj.field}
    """

    def decorator(fn: Serializer) -> Serializer:
        self._serializers[type_] = fn
        return fn

    return decorator

serialize(value)

Serialize a value to a SerializedValue.

Parameters:

Name Type Description Default
value Any

The value to serialize.

required

Returns:

Type Description
SerializedValue

SerializedValue with type info and serialized data.

Source code in src/opensymbolicai/checkpoint.py
def serialize(self, value: Any) -> SerializedValue:
    """Serialize a value to a SerializedValue.

    Args:
        value: The value to serialize.

    Returns:
        SerializedValue with type info and serialized data.
    """
    # Handle None
    if value is None:
        return SerializedValue(type_name="NoneType", data=None, is_primitive=True)

    value_type = type(value)
    type_name = self._get_type_name(value_type)

    # Check for JSON primitives
    if isinstance(value, bool):  # Must check bool before int (bool is subclass)
        return SerializedValue(
            type_name="builtins.bool", data=value, is_primitive=True
        )
    if isinstance(value, int):
        return SerializedValue(
            type_name="builtins.int", data=value, is_primitive=True
        )
    if isinstance(value, float):
        return SerializedValue(
            type_name="builtins.float", data=value, is_primitive=True
        )
    if isinstance(value, str):
        return SerializedValue(
            type_name="builtins.str", data=value, is_primitive=True
        )

    # Check for registered serializer (before generic handling)
    if value_type in self._serializers:
        serializer = self._serializers[value_type]
        return SerializedValue(
            type_name=type_name, data=serializer(value), is_primitive=False
        )

    # Check for lists (recursively serialize)
    if isinstance(value, list):
        serialized_items = [self.serialize(item).model_dump() for item in value]
        return SerializedValue(
            type_name="builtins.list",
            data=serialized_items,
            is_primitive=False,
        )

    # Check for dicts (recursively serialize)
    if isinstance(value, dict):
        serialized_dict = {
            k: self.serialize(v).model_dump() for k, v in value.items()
        }
        return SerializedValue(
            type_name="builtins.dict",
            data=serialized_dict,
            is_primitive=False,
        )

    # Check if it's a Pydantic model
    if hasattr(value, "model_dump"):
        return SerializedValue(
            type_name=type_name,
            data={"__pydantic__": True, "data": value.model_dump()},
            is_primitive=False,
        )

    # Fallback: try to convert to string representation
    return SerializedValue(
        type_name=type_name,
        data={"__repr__": repr(value), "__unserializable__": True},
        is_primitive=False,
    )

serialize_namespace(namespace, exclude=None)

Serialize an entire namespace dict.

Parameters:

Name Type Description Default
namespace dict[str, Any]

The namespace to serialize.

required
exclude set[str] | None

Keys to exclude from serialization.

None

Returns:

Type Description
dict[str, SerializedValue]

Dict mapping variable names to SerializedValues.

Source code in src/opensymbolicai/checkpoint.py
def serialize_namespace(
    self, namespace: dict[str, Any], exclude: set[str] | None = None
) -> dict[str, SerializedValue]:
    """Serialize an entire namespace dict.

    Args:
        namespace: The namespace to serialize.
        exclude: Keys to exclude from serialization.

    Returns:
        Dict mapping variable names to SerializedValues.
    """
    exclude = exclude or set()
    result: dict[str, SerializedValue] = {}
    for key, value in namespace.items():
        if key in exclude:
            continue
        result[key] = self.serialize(value)
    return result

TokenUsage

Bases: BaseModel

Token usage statistics from LLM generation.

Source code in src/opensymbolicai/models.py
class TokenUsage(BaseModel):
    """Token usage statistics from LLM generation."""

    input_tokens: int = Field(default=0, description="Number of input/prompt tokens")
    output_tokens: int = Field(
        default=0, description="Number of output/completion tokens"
    )

    @property
    def total_tokens(self) -> int:
        """Total tokens used."""
        return self.input_tokens + self.output_tokens

total_tokens property

Total tokens used.

ValidationError

Bases: ExecutionError

Exception raised when input validation fails.

Use this for invalid arguments, out-of-range values, or constraint violations in primitive inputs.

Example

if number <= 0: raise ValidationError( "Logarithm requires positive input", code="INVALID_INPUT", details={"received": number, "expected": "positive number"} )

Source code in src/opensymbolicai/exceptions.py
class ValidationError(ExecutionError):
    """Exception raised when input validation fails.

    Use this for invalid arguments, out-of-range values, or
    constraint violations in primitive inputs.

    Example:
        if number <= 0:
            raise ValidationError(
                "Logarithm requires positive input",
                code="INVALID_INPUT",
                details={"received": number, "expected": "positive number"}
            )
    """

    def __init__(
        self,
        message: str,
        *,
        code: str | None = "VALIDATION_ERROR",
        details: dict[str, Any] | None = None,
        field: str | None = None,
    ) -> None:
        """Initialize validation error.

        Args:
            message: Human-readable error message.
            code: Error code, defaults to "VALIDATION_ERROR".
            details: Additional context about the error.
            field: Optional name of the field that failed validation.
        """
        if field and details is None:
            details = {}
        if field:
            details = details or {}
            details["field"] = field
        super().__init__(message, code=code, details=details)
        self.field = field

__init__(message, *, code='VALIDATION_ERROR', details=None, field=None)

Initialize validation error.

Parameters:

Name Type Description Default
message str

Human-readable error message.

required
code str | None

Error code, defaults to "VALIDATION_ERROR".

'VALIDATION_ERROR'
details dict[str, Any] | None

Additional context about the error.

None
field str | None

Optional name of the field that failed validation.

None
Source code in src/opensymbolicai/exceptions.py
def __init__(
    self,
    message: str,
    *,
    code: str | None = "VALIDATION_ERROR",
    details: dict[str, Any] | None = None,
    field: str | None = None,
) -> None:
    """Initialize validation error.

    Args:
        message: Human-readable error message.
        code: Error code, defaults to "VALIDATION_ERROR".
        details: Additional context about the error.
        field: Optional name of the field that failed validation.
    """
    if field and details is None:
        details = {}
    if field:
        details = details or {}
        details["field"] = field
    super().__init__(message, code=code, details=details)
    self.field = field

decomposition(intent, expanded_intent='')

Mark a method as a decomposition example.

Decompositions demonstrate how to break down high-level intents into sequences of primitive operations. They serve as examples for the LLM to learn the patterns of composition.

Parameters:

Name Type Description Default
intent str

A high-level description of what this decomposition achieves. This is the natural language query that this example answers.

required
expanded_intent str

An optional step-by-step breakdown of the approach. Provides additional context about the reasoning or methodology.

''

Returns:

Type Description
Callable[[F], F]

A decorator that marks the function as a decomposition example.

Example

@decomposition( intent="What is sine of 90 degrees?", expanded_intent="First convert 90 degrees to radians, then calculate sine", ) def _example_sine_90(self) -> float: angle_rad: float = self.convert_degrees_to_radians(angle_in_degrees=90) sin_90: float = self.sine(angle_in_radians=angle_rad) return sin_90

Source code in src/opensymbolicai/core.py
def decomposition(intent: str, expanded_intent: str = "") -> Callable[[F], F]:
    """Mark a method as a decomposition example.

    Decompositions demonstrate how to break down high-level intents into
    sequences of primitive operations. They serve as examples for the LLM
    to learn the patterns of composition.

    Args:
        intent: A high-level description of what this decomposition achieves.
            This is the natural language query that this example answers.
        expanded_intent: An optional step-by-step breakdown of the approach.
            Provides additional context about the reasoning or methodology.

    Returns:
        A decorator that marks the function as a decomposition example.

    Example:
        @decomposition(
            intent="What is sine of 90 degrees?",
            expanded_intent="First convert 90 degrees to radians, then calculate sine",
        )
        def _example_sine_90(self) -> float:
            angle_rad: float = self.convert_degrees_to_radians(angle_in_degrees=90)
            sin_90: float = self.sine(angle_in_radians=angle_rad)
            return sin_90
    """

    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            return func(*args, **kwargs)

        wrapper.__method_type__ = MethodType.DECOMPOSITION  # type: ignore[attr-defined]
        wrapper.__decomposition_intent__ = intent  # type: ignore[attr-defined]
        wrapper.__decomposition_expanded_intent__ = expanded_intent  # type: ignore[attr-defined]
        return cast(F, wrapper)

    return decorator

primitive(read_only=False)

Mark a method as a primitive operation.

Primitives are atomic operations that the agent can directly execute. They serve as the building blocks for more complex behaviors.

Parameters:

Name Type Description Default
read_only bool

If True, indicates this primitive does not modify state.

False

Returns:

Type Description
Callable[[F], F]

A decorator that marks the function as a primitive.

Example

@primitive(read_only=True) def add_numbers(self, a: float, b: float) -> float: return a + b

Source code in src/opensymbolicai/core.py
def primitive(read_only: bool = False) -> Callable[[F], F]:
    """Mark a method as a primitive operation.

    Primitives are atomic operations that the agent can directly execute.
    They serve as the building blocks for more complex behaviors.

    Args:
        read_only: If True, indicates this primitive does not modify state.

    Returns:
        A decorator that marks the function as a primitive.

    Example:
        @primitive(read_only=True)
        def add_numbers(self, a: float, b: float) -> float:
            return a + b
    """

    def decorator(func: F) -> F:
        @wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            return func(*args, **kwargs)

        wrapper.__method_type__ = MethodType.PRIMITIVE  # type: ignore[attr-defined]
        wrapper.__primitive_read_only__ = read_only  # type: ignore[attr-defined]
        return cast(F, wrapper)

    return decorator