fabricatio_capabilities.models.generic

This module defines generic classes for models in the Fabricatio library, providing a foundation for various model functionalities.

Classes

ModelHash

Class that provides a hash value for the object.

UpdateFrom

Class that provides a method to update the object from another object.

ProposedUpdateAble

Make the obj can be updated from the proposed obj in place.

FinalizedDumpAble

Class that provides a method to finalize the dump of the object.

Patch

A generic patch class that allows field-based updates to target objects.

SequencePatch

Base class for patches.

PersistentAble

Class providing file persistence capabilities.

AsPrompt

Class that provides a method to generate a prompt from the model.

WordCount

Class that includes a word count attribute.

Module Contents

class fabricatio_capabilities.models.generic.ModelHash(/, **data: Any)

Bases: fabricatio_core.models.generic.Base, abc.ABC

Class that provides a hash value for the object.

This class includes a method to calculate a hash value for the object based on its JSON representation.

__hash__() int

Calculates a hash value for the object based on its model_dump_json representation.

Returns:

The hash value of the object.

Return type:

int

class fabricatio_capabilities.models.generic.UpdateFrom

Bases: abc.ABC

Class that provides a method to update the object from another object.

This class includes methods to update the current object with the attributes of another object.

update_pre_check(other: Self) Self

Pre-check for updating the object from another object.

Parameters:

other (Self) – The other object to update from.

Returns:

The current instance after pre-check.

Return type:

Self

Raises:

TypeError – If the other object is not of the same type.

abstractmethod update_from_inner(other: Self) Self

Updates the current instance with the attributes of another instance.

This method should be implemented by subclasses to provide the specific update logic.

Parameters:

other (Self) – The other instance to update from.

Returns:

The current instance with updated attributes.

Return type:

Self

update_from(other: Self) Self

Updates the current instance with the attributes of another instance.

Parameters:

other (Self) – The other instance to update from.

Returns:

The current instance with updated attributes.

Return type:

Self

class fabricatio_capabilities.models.generic.ProposedUpdateAble(/, **data: Any)

Bases: fabricatio_core.models.generic.SketchedAble, UpdateFrom, abc.ABC

Make the obj can be updated from the proposed obj in place.

This class provides the ability to update an object in place from a proposed object.

class fabricatio_capabilities.models.generic.FinalizedDumpAble(/, **data: Any)

Bases: fabricatio_core.models.generic.Base, abc.ABC

Class that provides a method to finalize the dump of the object.

This class includes methods to finalize the JSON representation of the object and dump it to a file.

finalized_dump() str

Finalize the dump of the object.

Returns:

The finalized dump of the object.

Return type:

str

finalized_dump_to(path: str | pathlib.Path) Self

Finalize the dump of the object to a file.

Parameters:

path (str | Path) – The path to save the finalized dump.

Returns:

The current instance of the object.

Return type:

Self

class fabricatio_capabilities.models.generic.Patch[T](/, **data: Any)

Bases: fabricatio_core.models.generic.ProposedAble, abc.ABC

A generic patch class that allows field-based updates to target objects.

This class provides functionality to:

  1. Apply patches to update object fields

  2. Generate dictionary representations of patches

  3. Handle JSON schema generation with reference class integration

The patch system works by comparing fields between the patch and target object, ensuring type safety while enabling flexible data transformations.

Type Parameters:

T: The type of object this patch can be applied to (typically a Pydantic model)

Example

>>> from pydantic import BaseModel
>>> class MyModel(BaseModel):
...     name: str
...     value: int
...
>>> class MyPatch(Patch[MyModel], BaseModel):
...     name: str
...
>>> target = MyModel(name="old", value=42)
>>> patch = MyPatch(name="new")
>>> updated = patch.apply(target)
>>> assert updated.name == "new" and updated.value == 42
apply(other: T) T

Apply the patch to another instance.

This method copies all fields from the patch to the target object, ensuring that only existing fields are modified.

Parameters:

other (T) – The instance to apply the patch to.

Returns:

The instance with the patch applied.

Return type:

T

Raises:

ValueError – If a field in the patch is not found in the target instance.

Example

>>> class User(BaseModel):
...     name: str
...     age: int
...
>>> class UserPatch(Patch[User], BaseModel):
...     name: Optional[str] = None
...
>>> user = User(name="Alice", age=30)
>>> patch = UserPatch(name="Bob")
>>> updated_user = patch.apply(user)
>>> assert updated_user.name == "Bob" and updated_user.age == 30
as_kwargs() Dict[str, Any]

Get the kwargs of the patch.

Converts the patch into a dictionary suitable for use with kwargs syntax.

Returns:

A dictionary representation of the patch.

Return type:

Dict[str, Any]

Example

>>> class ConfigPatch(Patch[MyModel], BaseModel):
...     timeout: int
...     retries: int
...
>>> patch = ConfigPatch(timeout=30, retries=3)
>>> kwargs = patch.as_kwargs()
>>> print(kwargs)  # {'timeout': 30, 'retries': 3}
static ref_cls() Type[pydantic.BaseModel] | None

Get the reference class of the model.

This can be overridden in subclasses to provide a reference model for schema documentation.

Returns:

The reference class if available, None otherwise.

Return type:

Optional[Type[BaseModel]]

static excluded_fields() Set[str]

Get a list of fields to exclude from the patch.

This can be overridden in subclasses to provide a list of fields that should be excluded from the patch.

Returns:

A list of fields to exclude from the patch.

Return type:

Set[str]

classmethod formated_json_schema() str

Get the JSON schema of the model in a formatted string.

Generates a JSON schema with optional documentation inherited from a reference class. This is particularly useful for API documentation and validation systems.

Returns:

The JSON schema of the model in a formatted string.

Return type:

str

Example

>>> class MyBaseModel(BaseModel):
...     id: int
...     name: str
...
>>> class MyPatch(Patch[MyBaseModel], BaseModel):
...     @staticmethod
...     def ref_cls():
...         return MyBaseModel
...
>>> print(MyPatch.formated_json_schema())
{
  "title": "MyBaseModel",
  "type": "object",
  "properties": {
    "id": {
      "type": "integer",
      "description": "..."
    },
    "name": {
      "type": "string",
      "description": "..."
    }
  },
  "required": ["id", "name"]
}
class fabricatio_capabilities.models.generic.SequencePatch[T](/, **data: Any)

Bases: ProposedUpdateAble, abc.ABC

Base class for patches.

This class provides a base implementation for patches that can be applied to sequences of objects.

tweaked: List[T]

Tweaked content list

update_from_inner(other: Self) Self

Updates the current instance with the attributes of another instance.

Parameters:

other (Self) – The other instance to update from.

Returns:

The current instance with updated attributes.

Return type:

Self

classmethod default() Self

Defaults to empty list.

Returns:

A new instance with an empty list of tweaks.

Return type:

Self

class fabricatio_capabilities.models.generic.PersistentAble(/, **data: Any)

Bases: fabricatio_core.models.generic.Base, abc.ABC

Class providing file persistence capabilities.

Enables saving model instances to disk with timestamped filenames and loading from persisted files. Implements basic versioning through filename hashing and timestamping.

persist(path: str | pathlib.Path) Self

Save model instance to disk with versioned filename.

Parameters:

path (str | Path) – Target directory or file path. If directory, filename is auto-generated.

Returns:

Current instance for method chaining

Return type:

Self

Notes

  • Filename format: ClassName_YYYYMMDD_HHMMSS_6-char_hash.json

  • Hash generated from JSON content ensures uniqueness

classmethod from_latest_persistent(dir_path: str | pathlib.Path) Self | None

Load most recent persisted instance from directory.

Parameters:

dir_path (str | Path) – Directory containing persisted files

Returns:

Most recently modified instance

Return type:

Self

Raises:
classmethod from_persistent(path: str | pathlib.Path) Self

Load an instance from a specific persisted file.

Parameters:

path (str | Path) – Path to the JSON file.

Returns:

The loaded instance from the file.

Return type:

Self

Raises:
class fabricatio_capabilities.models.generic.AsPrompt

Bases: abc.ABC

Class that provides a method to generate a prompt from the model.

This class includes a method to generate a prompt based on the model’s attributes.

rendering_template: ClassVar[str]
as_prompt() str

Generate a prompt from the model.

Returns:

The generated prompt.

Return type:

str

class fabricatio_capabilities.models.generic.WordCount(/, **data: Any)

Bases: fabricatio_core.models.generic.Base, abc.ABC

Class that includes a word count attribute.

expected_word_count: int

Expected word count of this research component.

property exact_word_count: int
Abstractmethod:

Get the exact word count of this research component.