Skip to content

Class swarmauri_standard.programs.Program.Program

swarmauri_standard.programs.Program.Program

Program(id=None, version=None, metadata=None, content=None)

Bases: ProgramBase

Concrete implementation of ProgramBase providing an immutable program object.

This class implements the abstract methods defined in ProgramBase and provides functionality for serialization, diffing, and validation of program objects.

ATTRIBUTE DESCRIPTION
type

The literal type identifier for this program class

TYPE: Literal['Program']

id

Unique identifier for the program instance

version

Version information for the program

metadata

Additional metadata associated with the program

content

The actual program content

Initialize a new Program instance.

PARAMETER DESCRIPTION
id

Unique identifier for the program, auto-generated if not provided

TYPE: Optional[str] DEFAULT: None

version

Version information, defaults to "1.0.0" if not provided

TYPE: Optional[str] DEFAULT: None

metadata

Additional metadata for the program

TYPE: Optional[Dict[str, Any]] DEFAULT: None

content

The actual program content

TYPE: Optional[Dict[str, Any]] DEFAULT: None

Source code in swarmauri_standard/programs/Program.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def __init__(
    self,
    id: Optional[str] = None,
    version: Optional[str] = None,
    metadata: Optional[Dict[str, Any]] = None,
    content: Optional[Dict[str, Any]] = None,
):
    """
    Initialize a new Program instance.

    Args:
        id: Unique identifier for the program, auto-generated if not provided
        version: Version information, defaults to "1.0.0" if not provided
        metadata: Additional metadata for the program
        content: The actual program content
    """
    super().__init__()
    self.id = id if id else str(uuid.uuid4())
    self.version = version if version else "1.0.0"
    self.metadata = metadata if metadata else {}
    self.content = content if content else {}

    # Ensure program ID and version are included in metadata
    if "program_id" not in self.metadata:
        self.metadata["program_id"] = self.id
    if "program_version" not in self.metadata:
        self.metadata["program_version"] = self.version
    if "created_at" not in self.metadata:
        self.metadata["created_at"] = datetime.utcnow().isoformat()

type class-attribute instance-attribute

type = 'Program'

model_config class-attribute instance-attribute

model_config = {}

id instance-attribute

id = id if id else str(uuid4())

version instance-attribute

version = version if version else '1.0.0'

metadata instance-attribute

metadata = metadata if metadata else {}

content instance-attribute

content = content if content else {}

members class-attribute instance-attribute

members = None

owners class-attribute instance-attribute

owners = None

host class-attribute instance-attribute

host = None

default_logger class-attribute

default_logger = None

logger class-attribute instance-attribute

logger = None

name class-attribute instance-attribute

name = None

resource class-attribute instance-attribute

resource = PROGRAM.value

diff

diff(other)

Calculate the difference between this program and another.

PARAMETER DESCRIPTION
other

Another program to compare against

TYPE: IProgram

RETURNS DESCRIPTION
DiffType

A structured representation of the differences between programs

RAISES DESCRIPTION
TypeError

If the other program is not compatible for diffing

Source code in swarmauri_standard/programs/Program.py
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 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
def diff(self, other: IProgram) -> DiffType:
    """
    Calculate the difference between this program and another.

    Args:
        other: Another program to compare against

    Returns:
        A structured representation of the differences between programs

    Raises:
        TypeError: If the other program is not compatible for diffing
    """
    if not isinstance(other, IProgram):
        raise TypeError(f"Expected IProgram instance, got {type(other)}")

    logger.info(f"Computing diff between {self._program_type} programs")

    diff = {}

    # Compare content fields
    if hasattr(self, "content") and hasattr(other, "content"):
        content_diff = {}
        other_content = getattr(other, "content", {})

        # Find modified and removed keys
        for key, value in self.content.items():
            if key not in other_content:
                content_diff[key] = {"old": value, "new": None}
            elif other_content[key] != value:
                content_diff[key] = {"old": value, "new": other_content[key]}

        # Find added keys
        for key, value in other_content.items():
            if key not in self.content:
                content_diff[key] = {"old": None, "new": value}

        if content_diff:
            diff["content"] = content_diff

    return diff

apply_diff

apply_diff(diff)

Apply a diff to this program to create a new modified program.

PARAMETER DESCRIPTION
diff

The diff structure to apply to this program

TYPE: DiffType

RETURNS DESCRIPTION
Program

A new program instance with the diff applied

RAISES DESCRIPTION
ValueError

If the diff cannot be applied to this program

TypeError

If the diff is not in the expected format

Source code in swarmauri_standard/programs/Program.py
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
def apply_diff(self, diff: DiffType) -> "Program":
    """
    Apply a diff to this program to create a new modified program.

    Args:
        diff: The diff structure to apply to this program

    Returns:
        A new program instance with the diff applied

    Raises:
        ValueError: If the diff cannot be applied to this program
        TypeError: If the diff is not in the expected format
    """
    if not isinstance(diff, dict):
        raise TypeError(f"Expected dict for diff, got {type(diff)}")

    logger.info(f"Applying diff to {self._program_type} program")

    # Create a new program by cloning the current one
    new_program = Program(
        id=self.id,
        version=self.version,
        metadata=copy.deepcopy(self.metadata),
        content=copy.deepcopy(self.content),
    )

    # Apply changes to content
    if "content" in diff and hasattr(new_program, "content"):
        content_diff = diff["content"]
        new_content = dict(new_program.content)

        for key, change in content_diff.items():
            if not isinstance(change, dict) or "new" not in change:
                raise ValueError(f"Invalid diff format for key {key}")

            # Add or modify
            if change.get("new") is not None:
                new_content[key] = change["new"]
            # Remove
            elif key in new_content:
                del new_content[key]

        new_program.content = new_content

    # Update the version number to indicate a change
    version_parts = new_program.version.split(".")
    if len(version_parts) >= 3:
        version_parts[-1] = str(int(version_parts[-1]) + 1)
        new_program.version = ".".join(version_parts)
        new_program.metadata["program_version"] = new_program.version
        new_program.metadata["updated_at"] = datetime.utcnow().isoformat()

    return new_program

validate

validate()

Validate that this program is well-formed and executable.

This implementation performs basic validation checks on the program structure.

RETURNS DESCRIPTION
bool

True if the program is valid, False otherwise

Source code in swarmauri_standard/programs/Program.py
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
def validate(self) -> bool:
    """
    Validate that this program is well-formed and executable.

    This implementation performs basic validation checks on the program structure.

    Returns:
        True if the program is valid, False otherwise
    """
    logger.info(f"Validating {self._program_type} program with ID {self.id}")

    # Check for required metadata
    if "program_id" not in self.metadata or self.metadata["program_id"] != self.id:
        logger.error("Program ID mismatch or missing in metadata")
        return False

    if (
        "program_version" not in self.metadata
        or self.metadata["program_version"] != self.version
    ):
        logger.error("Program version mismatch or missing in metadata")
        return False

    # Additional validation could be implemented here based on specific requirements
    # For example, validating the structure of the content, checking for required fields, etc.

    logger.info(f"Program {self.id} validation successful")
    return True

from_workspace classmethod

from_workspace(root)

Create a program from all source files in root.

PARAMETER DESCRIPTION
root

Workspace directory containing source files.

TYPE: Path

RETURNS DESCRIPTION
Program

Instance populated with file contents.

TYPE: Program

Source code in swarmauri_standard/programs/Program.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
@classmethod
def from_workspace(cls, root: Path) -> "Program":
    """Create a program from all source files in *root*.

    Args:
        root (Path): Workspace directory containing source files.

    Returns:
        Program: Instance populated with file contents.
    """
    root = root.resolve()
    content: Dict[str, str] = {}
    for path in root.rglob("*"):
        if path.is_file() and path.suffix in {".py", ".txt", ".md"}:
            rel = path.relative_to(root)
            content[str(rel)] = path.read_text(encoding="utf-8")

    return cls(content=content)

get_source_files

get_source_files()

Return program source files keyed by relative path.

Source code in swarmauri_standard/programs/Program.py
209
210
211
def get_source_files(self) -> Dict[str, str]:
    """Return program source files keyed by relative path."""
    return self.content

register_model classmethod

register_model()

Decorator to register a base model in the unified registry.

RETURNS DESCRIPTION
Callable

A decorator function that registers the model class.

TYPE: Callable[[Type[BaseModel]], Type[BaseModel]]

Source code in swarmauri_base/DynamicBase.py
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
@classmethod
def register_model(cls) -> Callable[[Type[BaseModel]], Type[BaseModel]]:
    """
    Decorator to register a base model in the unified registry.

    Returns:
        Callable: A decorator function that registers the model class.
    """

    def decorator(model_cls: Type[BaseModel]):
        """Register ``model_cls`` as a base model."""
        model_name = model_cls.__name__
        if model_name in cls._registry:
            glogger.warning(
                "Model '%s' is already registered; skipping duplicate.", model_name
            )
            return model_cls

        cls._registry[model_name] = {"model_cls": model_cls, "subtypes": {}}
        glogger.debug("Registered base model '%s'.", model_name)
        DynamicBase._recreate_models()
        return model_cls

    return decorator

register_type classmethod

register_type(resource_type=None, type_name=None)

Decorator to register a subtype under one or more base models in the unified registry.

PARAMETER DESCRIPTION
resource_type

The base model(s) under which to register the subtype. If None, all direct base classes (except DynamicBase) are used.

TYPE: Optional[Union[Type[T], List[Type[T]]]] DEFAULT: None

type_name

An optional custom type name for the subtype.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Callable

A decorator function that registers the subtype.

TYPE: Callable[[Type[DynamicBase]], Type[DynamicBase]]

Source code in swarmauri_base/DynamicBase.py
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
@classmethod
def register_type(
    cls,
    resource_type: Optional[Union[Type[T], List[Type[T]]]] = None,
    type_name: Optional[str] = None,
) -> Callable[[Type["DynamicBase"]], Type["DynamicBase"]]:
    """
    Decorator to register a subtype under one or more base models in the unified registry.

    Parameters:
        resource_type (Optional[Union[Type[T], List[Type[T]]]]):
            The base model(s) under which to register the subtype. If None, all direct base classes (except DynamicBase)
            are used.
        type_name (Optional[str]): An optional custom type name for the subtype.

    Returns:
        Callable: A decorator function that registers the subtype.
    """

    def decorator(subclass: Type["DynamicBase"]):
        """Register ``subclass`` as a subtype."""
        if resource_type is None:
            resource_types = [
                base for base in subclass.__bases__ if base is not cls
            ]
        elif not isinstance(resource_type, list):
            resource_types = [resource_type]
        else:
            resource_types = resource_type

        for rt in resource_types:
            if not issubclass(subclass, rt):
                raise TypeError(
                    f"'{subclass.__name__}' must be a subclass of '{rt.__name__}'."
                )
            final_type_name = type_name or getattr(
                subclass, "_type", subclass.__name__
            )
            base_model_name = rt.__name__

            if base_model_name not in cls._registry:
                cls._registry[base_model_name] = {"model_cls": rt, "subtypes": {}}
                glogger.debug(
                    "Created new registry entry for base model '%s'.",
                    base_model_name,
                )

            subtypes_dict = cls._registry[base_model_name]["subtypes"]
            if final_type_name in subtypes_dict:
                glogger.warning(
                    "Type '%s' already exists under '%s'; skipping duplicate.",
                    final_type_name,
                    base_model_name,
                )
                continue

            subtypes_dict[final_type_name] = subclass
            glogger.debug(
                "Registered '%s' as '%s' under '%s'.",
                subclass.__name__,
                final_type_name,
                base_model_name,
            )

        DynamicBase._recreate_models()
        return subclass

    return decorator

model_validate_toml classmethod

model_validate_toml(toml_data)

Validate a model from a TOML string.

Source code in swarmauri_base/TomlMixin.py
12
13
14
15
16
17
18
19
20
21
22
23
24
@classmethod
def model_validate_toml(cls, toml_data: str):
    """Validate a model from a TOML string."""
    try:
        # Parse TOML into a Python dictionary
        toml_content = tomllib.loads(toml_data)

        # Convert the dictionary to JSON and validate using Pydantic
        return cls.model_validate_json(json.dumps(toml_content))
    except tomllib.TOMLDecodeError as e:
        raise ValueError(f"Invalid TOML data: {e}")
    except ValidationError as e:
        raise ValueError(f"Validation failed: {e}")

model_dump_toml

model_dump_toml(
    fields_to_exclude=None, api_key_placeholder=None
)

Return a TOML representation of the model.

Source code in swarmauri_base/TomlMixin.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def model_dump_toml(self, fields_to_exclude=None, api_key_placeholder=None):
    """Return a TOML representation of the model."""
    if fields_to_exclude is None:
        fields_to_exclude = []

    # Load the JSON string into a Python dictionary
    json_data = json.loads(self.model_dump_json())

    # Function to recursively remove specific keys and handle api_key placeholders
    def process_fields(data, fields_to_exclude):
        """Recursively filter fields and apply placeholders."""
        if isinstance(data, dict):
            return {
                key: (
                    api_key_placeholder
                    if key == "api_key" and api_key_placeholder is not None
                    else process_fields(value, fields_to_exclude)
                )
                for key, value in data.items()
                if key not in fields_to_exclude
            }
        elif isinstance(data, list):
            return [process_fields(item, fields_to_exclude) for item in data]
        else:
            return data

    # Filter the JSON data
    filtered_data = process_fields(json_data, fields_to_exclude)

    # Convert the filtered data into TOML
    return toml.dumps(filtered_data)

model_validate_yaml classmethod

model_validate_yaml(yaml_data)

Validate a model from a YAML string.

Source code in swarmauri_base/YamlMixin.py
11
12
13
14
15
16
17
18
19
20
21
22
23
@classmethod
def model_validate_yaml(cls, yaml_data: str):
    """Validate a model from a YAML string."""
    try:
        # Parse YAML into a Python dictionary
        yaml_content = yaml.safe_load(yaml_data)

        # Convert the dictionary to JSON and validate using Pydantic
        return cls.model_validate_json(json.dumps(yaml_content))
    except yaml.YAMLError as e:
        raise ValueError(f"Invalid YAML data: {e}")
    except ValidationError as e:
        raise ValueError(f"Validation failed: {e}")

model_dump_yaml

model_dump_yaml(
    fields_to_exclude=None, api_key_placeholder=None
)

Return a YAML representation of the model.

Source code in swarmauri_base/YamlMixin.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def model_dump_yaml(self, fields_to_exclude=None, api_key_placeholder=None):
    """Return a YAML representation of the model."""
    if fields_to_exclude is None:
        fields_to_exclude = []

    # Load the JSON string into a Python dictionary
    json_data = json.loads(self.model_dump_json())

    # Function to recursively remove specific keys and handle api_key placeholders
    def process_fields(data, fields_to_exclude):
        """Recursively filter fields and apply placeholders."""
        if isinstance(data, dict):
            return {
                key: (
                    api_key_placeholder
                    if key == "api_key" and api_key_placeholder is not None
                    else process_fields(value, fields_to_exclude)
                )
                for key, value in data.items()
                if key not in fields_to_exclude
            }
        elif isinstance(data, list):
            return [process_fields(item, fields_to_exclude) for item in data]
        else:
            return data

    # Filter the JSON data
    filtered_data = process_fields(json_data, fields_to_exclude)

    # Convert the filtered data into YAML using safe mode
    return yaml.safe_dump(filtered_data, default_flow_style=False)

model_post_init

model_post_init(logger=None)

Assign a logger instance after model initialization.

Source code in swarmauri_base/LoggerMixin.py
23
24
25
26
27
28
def model_post_init(self, logger: Optional[FullUnion[LoggerBase]] = None) -> None:
    """Assign a logger instance after model initialization."""

    # Directly assign the provided FullUnion[LoggerBase] or fallback to the
    # class-level default.
    self.logger = self.logger or logger or self.default_logger

clone

clone()

Create a deep copy of this program.

RETURNS DESCRIPTION
IProgram

A new program instance with the same state

Source code in swarmauri_base/programs/ProgramBase.py
28
29
30
31
32
33
34
35
def clone(self) -> "IProgram":
    """
    Create a deep copy of this program.

    Returns:
        A new program instance with the same state
    """
    return copy.deepcopy(self)