sinapsis_core 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sinapsis_core/__init__.py +0 -0
- sinapsis_core/agent/__init__.py +5 -0
- sinapsis_core/agent/agent.py +362 -0
- sinapsis_core/agent/agent_helpers.py +112 -0
- sinapsis_core/agent/base_models.py +361 -0
- sinapsis_core/agent/builder.py +112 -0
- sinapsis_core/agent/profiler_agent.py +117 -0
- sinapsis_core/cli/__init__.py +0 -0
- sinapsis_core/cli/arg_parser.py +29 -0
- sinapsis_core/cli/display_template_info.py +202 -0
- sinapsis_core/cli/run_agent_from_config.py +40 -0
- sinapsis_core/context_managers/__init__.py +0 -0
- sinapsis_core/context_managers/env_var_override_context_manager.py +39 -0
- sinapsis_core/context_managers/working_dir_context_manager.py +57 -0
- sinapsis_core/data_containers/__init__.py +0 -0
- sinapsis_core/data_containers/annotations.py +152 -0
- sinapsis_core/data_containers/data_packet.py +364 -0
- sinapsis_core/data_containers/model_types/__init__.py +38 -0
- sinapsis_core/data_containers/model_types/_asr_base_models.py +39 -0
- sinapsis_core/data_containers/model_types/llm_types.py +189 -0
- sinapsis_core/exceptions/agent_exceptions.py +2 -0
- sinapsis_core/hooks/__init__.py +15 -0
- sinapsis_core/hooks/pre_init_hook_registry.py +225 -0
- sinapsis_core/template_base/__init__.py +10 -0
- sinapsis_core/template_base/base_models.py +59 -0
- sinapsis_core/template_base/copy_data_container.py +46 -0
- sinapsis_core/template_base/dynamic_template.py +169 -0
- sinapsis_core/template_base/dynamic_template_factory.py +454 -0
- sinapsis_core/template_base/dynamic_template_helpers/__init__.py +0 -0
- sinapsis_core/template_base/dynamic_template_helpers/builder_methods.py +92 -0
- sinapsis_core/template_base/dynamic_template_helpers/signature_parser.py +625 -0
- sinapsis_core/template_base/empty_data_container.py +23 -0
- sinapsis_core/template_base/input_template.py +8 -0
- sinapsis_core/template_base/merge_data_flow.py +33 -0
- sinapsis_core/template_base/multi_execute_template.py +65 -0
- sinapsis_core/template_base/output_template.py +8 -0
- sinapsis_core/template_base/split_data_flow.py +50 -0
- sinapsis_core/template_base/template.py +292 -0
- sinapsis_core/template_base/transfer_data_container.py +13 -0
- sinapsis_core/utils/__init__.py +0 -0
- sinapsis_core/utils/base_model_updater.py +148 -0
- sinapsis_core/utils/doc_string_generator.py +20 -0
- sinapsis_core/utils/env_var_keys.py +249 -0
- sinapsis_core/utils/env_var_utils.py +6 -0
- sinapsis_core/utils/logging_utils.py +53 -0
- sinapsis_core-1.0.0.dist-info/METADATA +239 -0
- sinapsis_core-1.0.0.dist-info/RECORD +50 -0
- sinapsis_core-1.0.0.dist-info/WHEEL +4 -0
- sinapsis_core-1.0.0.dist-info/licenses/LICENSE-APACHE +202 -0
- sinapsis_core-1.0.0.dist-info/licenses/LICENSE-MIT +21 -0
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
from importlib import import_module, metadata
|
|
3
|
+
from typing import Callable, Literal, Type
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
from sinapsis_core.utils.env_var_keys import SinapsisEnvVarDefaults
|
|
8
|
+
from sinapsis_core.utils.logging_utils import sinapsis_logger
|
|
9
|
+
|
|
10
|
+
# Mapping hook types to their respective configurations
|
|
11
|
+
hook_config = {
|
|
12
|
+
"pre_init": {
|
|
13
|
+
"exclude_dirs": ["sinapsis_core"], # + SinapsisEnvVarDefaults.EXCLUDE_PRE_INIT_HOOKS.value,
|
|
14
|
+
"hook_list_name": "PRE_INIT_HOOKS",
|
|
15
|
+
"hook_dir": "hooks",
|
|
16
|
+
"hooks_enabled": SinapsisEnvVarDefaults.ENABLED_PRE_INIT_HOOKS.value,
|
|
17
|
+
},
|
|
18
|
+
"decorator": {
|
|
19
|
+
"exclude_dirs": ["sinapsis_core"], # + SinapsisEnvVarDefaults.EXCLUDE_AGENT_DECORATORS.value,
|
|
20
|
+
"hook_list_name": "AGENT_DECORATORS",
|
|
21
|
+
"hook_dir": "decorators",
|
|
22
|
+
"hooks_enabled": SinapsisEnvVarDefaults.ENABLED_AGENT_DECORATORS.value,
|
|
23
|
+
},
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _deprecated_smart_hook_search(hook_type: Literal["pre_init", "decorator"] = "pre_init"):
|
|
28
|
+
"""
|
|
29
|
+
Search for hooks in installed Sinapsis packages based on hook type.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
hook_type: Type of hook to search for, either "pre_init" or "decorator".
|
|
33
|
+
Defaults to "pre_init".
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
Dictionary mapping package names to their hooks.
|
|
37
|
+
|
|
38
|
+
Raises:
|
|
39
|
+
ValueError: If hook_type is not "pre_init" or "decorator".
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
# Validate hook_type
|
|
43
|
+
if hook_type not in hook_config:
|
|
44
|
+
raise ValueError(f"{hook_type} is not a valid hook type")
|
|
45
|
+
|
|
46
|
+
config = hook_config[hook_type]
|
|
47
|
+
available_hooks: dict[str, list[str]] = {}
|
|
48
|
+
exclude_dirs = config["exclude_dirs"]
|
|
49
|
+
hook_list_name = config["hook_list_name"]
|
|
50
|
+
hooks_dir = config["hook_dir"]
|
|
51
|
+
|
|
52
|
+
for available_dist in metadata.distributions():
|
|
53
|
+
package_name = available_dist._normalized_name # type:ignore[attr-defined]
|
|
54
|
+
if package_name.startswith("sinapsis_") and package_name not in exclude_dirs:
|
|
55
|
+
if (available_dist._path.parent / package_name / hooks_dir).exists(): # type:ignore[attr-defined]
|
|
56
|
+
package_module = import_module(f"{package_name}.{hooks_dir}")
|
|
57
|
+
hooks = getattr(package_module, hook_list_name, [])
|
|
58
|
+
if hooks:
|
|
59
|
+
available_hooks[package_name] = hooks
|
|
60
|
+
sinapsis_logger.debug(f"{package_name} hooks found: {hooks}")
|
|
61
|
+
|
|
62
|
+
return available_hooks
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def smart_hook_search(hook_type: Literal["pre_init", "decorator"] = "pre_init"):
|
|
66
|
+
sinapsis_logger.info("Auto discovering sinapsis packages in the current environment.")
|
|
67
|
+
config = hook_config[hook_type]
|
|
68
|
+
available_hooks: dict[str, list[str]] = {}
|
|
69
|
+
hook_list_name = config["hook_list_name"]
|
|
70
|
+
hooks_dir = config["hook_dir"]
|
|
71
|
+
for module_name in config["hooks_enabled"]:
|
|
72
|
+
module_name = module_name.strip().replace("-", "_")
|
|
73
|
+
if not module_name.startswith("sinapsis_"):
|
|
74
|
+
continue # Hard ignore anything else
|
|
75
|
+
hook_submodule_name = f"{module_name}.{hooks_dir}"
|
|
76
|
+
try:
|
|
77
|
+
# 3. Dynamic import of the subfolder/submodule (e.g., 'sinapsis_rmq.hooks')
|
|
78
|
+
package_module = import_module(hook_submodule_name)
|
|
79
|
+
hooks = getattr(package_module, hook_list_name, [])
|
|
80
|
+
if hooks:
|
|
81
|
+
available_hooks[module_name] = hooks
|
|
82
|
+
sinapsis_logger.debug(f"{module_name} hooks found: {hooks}")
|
|
83
|
+
else:
|
|
84
|
+
sinapsis_logger.debug(f"{module_name} hooks empty, skipping.")
|
|
85
|
+
except ModuleNotFoundError as e:
|
|
86
|
+
# If the hooks directory/module itself doesn't exist, skip it cleanly
|
|
87
|
+
if e.name == hook_submodule_name:
|
|
88
|
+
sinapsis_logger.debug(f"Module '{module_name}' has no '{hooks_dir}' directory.")
|
|
89
|
+
else:
|
|
90
|
+
# The directory exists but crashed internally while loading
|
|
91
|
+
sinapsis_logger.error(f"Error inside '{module_name}' hooks: {e}")
|
|
92
|
+
except Exception as e:
|
|
93
|
+
sinapsis_logger.error(f"Unexpected error in {module_name}: {e}")
|
|
94
|
+
return available_hooks
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class _AgentPreInitHooks:
|
|
98
|
+
_hooks: dict[str, list[Callable]] = {}
|
|
99
|
+
|
|
100
|
+
@classmethod
|
|
101
|
+
def do_smart_search(cls):
|
|
102
|
+
cls._hooks = smart_hook_search()
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def register_hook(cls, package_name: str, hook_func: Callable) -> None:
|
|
106
|
+
if package_name not in cls._hooks:
|
|
107
|
+
cls._hooks[package_name] = [hook_func]
|
|
108
|
+
else:
|
|
109
|
+
cls._hooks[package_name].append(hook_func)
|
|
110
|
+
|
|
111
|
+
@classmethod
|
|
112
|
+
def apply_single_hook(cls, hook_func: Callable, agent_class: Type):
|
|
113
|
+
hook_func(agent_class)
|
|
114
|
+
|
|
115
|
+
@classmethod
|
|
116
|
+
def apply_hooks(cls, agent_class: Type, update_hooks: bool = False) -> None:
|
|
117
|
+
if update_hooks:
|
|
118
|
+
cls._hooks = smart_hook_search()
|
|
119
|
+
for package_name, hook_funcs in cls._hooks.items():
|
|
120
|
+
_ = [cls.apply_single_hook(hook, agent_class) for hook in hook_funcs]
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class CallbackEntry(BaseModel):
|
|
124
|
+
callback_func: Callable
|
|
125
|
+
callback_kwargs: dict
|
|
126
|
+
include_self: bool = False
|
|
127
|
+
include_data_container_if_available: bool = False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class _AgentCallBackRegistry:
|
|
131
|
+
_callback_registry: dict[str, list[CallbackEntry]] = {}
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def __contains__(cls, callback_name: str):
|
|
135
|
+
return callback_name in cls._callback_registry
|
|
136
|
+
|
|
137
|
+
@classmethod
|
|
138
|
+
def register_callback(
|
|
139
|
+
cls, callback_type, callback: Callable, callback_kwargs: dict, include_self: bool = False
|
|
140
|
+
) -> None:
|
|
141
|
+
"""Register a callback for a specific class or method."""
|
|
142
|
+
if callback_type not in cls._callback_registry:
|
|
143
|
+
cls._callback_registry[callback_type] = []
|
|
144
|
+
|
|
145
|
+
cls._callback_registry[callback_type].append(
|
|
146
|
+
CallbackEntry(callback_func=callback, callback_kwargs=callback_kwargs, include_self=include_self)
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
@classmethod
|
|
150
|
+
def make_args(cls, callback_entry: CallbackEntry, agent_cls) -> dict:
|
|
151
|
+
callback_kwargs = callback_entry.callback_kwargs
|
|
152
|
+
if callback_entry.include_self:
|
|
153
|
+
callback_kwargs["self"] = agent_cls
|
|
154
|
+
return callback_kwargs
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def add_callback_support(cls, agent_class):
|
|
158
|
+
# Wrap the execute method to trigger callbacks
|
|
159
|
+
for callback_type, callback_entries in cls._callback_registry.items():
|
|
160
|
+
if hasattr(agent_class, callback_type):
|
|
161
|
+
original_method = getattr(agent_class, callback_type)
|
|
162
|
+
|
|
163
|
+
def wrapped_async_method(self, *args, **kwargs):
|
|
164
|
+
result = original_method(self, *args, **kwargs)
|
|
165
|
+
for callback_entry in callback_entries:
|
|
166
|
+
callback_kwargs = cls.make_args(callback_entry, self)
|
|
167
|
+
callback_entry.callback_func(**callback_kwargs)
|
|
168
|
+
return result
|
|
169
|
+
|
|
170
|
+
# Ensure we don't override an existing wrapped method
|
|
171
|
+
if not hasattr(agent_class, f"{callback_type}_wrapped"):
|
|
172
|
+
setattr(agent_class, callback_type, wrapped_async_method)
|
|
173
|
+
setattr(agent_class, f"{callback_type}_wrapped", True)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class AgentClassDecoratorRegistry:
|
|
177
|
+
_decorator_registry: list[Callable] = []
|
|
178
|
+
|
|
179
|
+
@classmethod
|
|
180
|
+
def do_smart_search(cls):
|
|
181
|
+
decorators = smart_hook_search(hook_type="decorator")
|
|
182
|
+
if decorators:
|
|
183
|
+
decorators = list(decorators.values())[0]
|
|
184
|
+
cls._decorator_registry.extend(decorators)
|
|
185
|
+
|
|
186
|
+
@classmethod
|
|
187
|
+
def register_decorator(cls, decorator: Callable) -> None:
|
|
188
|
+
"""Register a decorator to be applied to agent classes."""
|
|
189
|
+
cls._decorator_registry.append(decorator)
|
|
190
|
+
|
|
191
|
+
@classmethod
|
|
192
|
+
def apply_decorators(cls, agent_class):
|
|
193
|
+
for decorator in cls._decorator_registry:
|
|
194
|
+
agent_class = decorator(agent_class)
|
|
195
|
+
return agent_class
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
AgentPreInitHooks = _AgentPreInitHooks()
|
|
199
|
+
AgentPreInitHooks.do_smart_search()
|
|
200
|
+
|
|
201
|
+
AgentCallBackRegistry = _AgentCallBackRegistry()
|
|
202
|
+
AgentClassDecoratorRegistry.do_smart_search()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class PreInitMetaclass(type):
|
|
206
|
+
def __new__(cls, name, bases, namespace):
|
|
207
|
+
new_class = super().__new__(cls, name, bases, namespace)
|
|
208
|
+
|
|
209
|
+
# decorators are applied to the entire agent class and normally
|
|
210
|
+
# would be class decorators, meaning they'd inherit from cls
|
|
211
|
+
# [Agent or subclass] to add additional functionality
|
|
212
|
+
if not hasattr(new_class, "_decorated"):
|
|
213
|
+
new_class._decorated = True # Mark as decorated to prevent re-decoration
|
|
214
|
+
new_class = AgentClassDecoratorRegistry.apply_decorators(new_class)
|
|
215
|
+
|
|
216
|
+
return new_class
|
|
217
|
+
|
|
218
|
+
def __call__(cls, *args, **kwargs):
|
|
219
|
+
AgentPreInitHooks.apply_hooks(cls, update_hooks=False)
|
|
220
|
+
|
|
221
|
+
# callbacks are meant to be executed after an agent's method
|
|
222
|
+
AgentCallBackRegistry.add_callback_support(cls)
|
|
223
|
+
|
|
224
|
+
agent_instance = super().__call__(*args, **kwargs)
|
|
225
|
+
return agent_instance
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
from sinapsis_core.template_base.base_models import (
|
|
4
|
+
TemplateAttributes,
|
|
5
|
+
TemplateAttributeType,
|
|
6
|
+
TemplateMetadata,
|
|
7
|
+
)
|
|
8
|
+
from sinapsis_core.template_base.template import Template
|
|
9
|
+
|
|
10
|
+
__all__ = ["Template", "TemplateAttributeType", "TemplateAttributes", "TemplateMetadata"]
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
|
|
3
|
+
from enum import Enum
|
|
4
|
+
from typing import Annotated, Any, Literal
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, StringConstraints
|
|
7
|
+
from pydantic.dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
CATEGORY_TYPE = Annotated[str, StringConstraints(strip_whitespace=True, strict=True)]
|
|
10
|
+
TIER_TYPE = Literal["free", "pro", "enterprise"]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class OutputTypes(Enum):
|
|
14
|
+
MULTIMODAL = "multimodal"
|
|
15
|
+
IMAGE = "image"
|
|
16
|
+
VIDEO = "video"
|
|
17
|
+
TEXT = "text"
|
|
18
|
+
TIMESERIES = "timeseries"
|
|
19
|
+
AUDIO = "audio"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class TemplateMetadata:
|
|
24
|
+
"""
|
|
25
|
+
Dataclass to contain the Template metadata.
|
|
26
|
+
|
|
27
|
+
template_instance_name (str): The name of the template specified in Agent definition.
|
|
28
|
+
agent_name (str): The name of the agent containing the template instance.
|
|
29
|
+
|
|
30
|
+
When agents are used through the API then we require user_id and agent_id.
|
|
31
|
+
"""
|
|
32
|
+
|
|
33
|
+
template_instance_name: str
|
|
34
|
+
agent_name: str
|
|
35
|
+
user_id: str | None = None
|
|
36
|
+
agent_id: str | None = None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class UIPropertiesMetadata:
|
|
41
|
+
tags: list[str] | None = None
|
|
42
|
+
tier: TIER_TYPE = "free"
|
|
43
|
+
category: CATEGORY_TYPE = "community"
|
|
44
|
+
output_type: OutputTypes = OutputTypes.MULTIMODAL
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class TemplateAttributes(BaseModel):
|
|
48
|
+
"""
|
|
49
|
+
Base pydantic class for Template Attributes.
|
|
50
|
+
|
|
51
|
+
metadata (TemplateMetadata | None): Field used to set the template instance name and agent name. Defaults to None.
|
|
52
|
+
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
metadata: TemplateMetadata | None = None
|
|
56
|
+
model_config = ConfigDict(revalidate_instances="always", validate_assignment=True)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
TemplateAttributeType = Annotated[dict[str, Any] | TemplateAttributes, TemplateAttributes]
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
from copy import copy, deepcopy
|
|
3
|
+
from typing import Literal
|
|
4
|
+
|
|
5
|
+
from sinapsis_core.data_containers.data_packet import DataContainer
|
|
6
|
+
from sinapsis_core.template_base.base_models import TemplateAttributes
|
|
7
|
+
from sinapsis_core.template_base.transfer_data_container import TransferDataContainer
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class CopyDataContainer(TransferDataContainer):
|
|
11
|
+
"""
|
|
12
|
+
Utility template used to propagate a copy of
|
|
13
|
+
the received DataContainer.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
class AttributesBaseModel(TemplateAttributes):
|
|
17
|
+
"""
|
|
18
|
+
copy_type (Literal["deepcopy","shallow"]): select the type of copy operation to
|
|
19
|
+
be performed.
|
|
20
|
+
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
copy_type: Literal["deepcopy", "shallow"] = "deepcopy"
|
|
24
|
+
|
|
25
|
+
def get_data_container_copy(self, container: DataContainer) -> DataContainer:
|
|
26
|
+
"""
|
|
27
|
+
Return the type of selected DataContainer copy.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
container (DataContainer): received container.
|
|
31
|
+
|
|
32
|
+
Returns:
|
|
33
|
+
DataContainer: a copy of received container
|
|
34
|
+
|
|
35
|
+
if self.attributes.copy_type == "deepcopy":
|
|
36
|
+
return deepcopy(container)
|
|
37
|
+
return copy(container)
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
if self.attributes.copy_type == "deepcopy":
|
|
41
|
+
return deepcopy(container)
|
|
42
|
+
# Return shallow copy of container
|
|
43
|
+
return copy(container)
|
|
44
|
+
|
|
45
|
+
def execute(self, container: DataContainer) -> DataContainer:
|
|
46
|
+
return self.get_data_container_copy(container)
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import inspect
|
|
5
|
+
from abc import ABC
|
|
6
|
+
from functools import cached_property
|
|
7
|
+
from types import ModuleType
|
|
8
|
+
from typing import Any, Callable, cast
|
|
9
|
+
|
|
10
|
+
from pydantic import BaseModel, ConfigDict, Field, computed_field, model_validator
|
|
11
|
+
|
|
12
|
+
from sinapsis_core.template_base.base_models import TemplateAttributeType
|
|
13
|
+
from sinapsis_core.template_base.template import Template
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class WrapperEntryConfig(BaseModel):
|
|
17
|
+
"""
|
|
18
|
+
Configuration model for dynamic template wrapper generation. Controls how objects are wrapped
|
|
19
|
+
and how their signatures are analyzed for template creation.
|
|
20
|
+
|
|
21
|
+
Attributes:
|
|
22
|
+
wrapped_object (Callable | ModuleType): Object to be wrapped by the template
|
|
23
|
+
template_name_suffix (str): Suffix to append to generated template names
|
|
24
|
+
exclude_module_atts (list[str]): Module methods/classes to exclude from wrapping
|
|
25
|
+
exclude_method_attributes (list[str]): exclude attributes from a method.
|
|
26
|
+
method_names_to_inspect (list[str]): Methods to analyze when wrapping a class
|
|
27
|
+
additional_callables_to_inspect (list[WrapperEntryConfig]): Additional objects to wrap
|
|
28
|
+
signature_from_doc_string (bool): Whether to extract type information from docstrings
|
|
29
|
+
parse_entire_mro (bool): Whether to analyze full method resolution order
|
|
30
|
+
force_init_as_method (bool): Whether to parse __init__ signature instead of class signature
|
|
31
|
+
allow_arbitrary_kwargs (bool): Whether to allow additional keyword arguments in models
|
|
32
|
+
Notes:
|
|
33
|
+
- force_init_as_method helps to parse the __init__ signature instead of getting the signature for
|
|
34
|
+
the class, which may return cls attributes instead.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
wrapped_object: Callable | ModuleType
|
|
38
|
+
template_name_suffix: str = "Wrapper"
|
|
39
|
+
exclude_module_atts: list[str] = Field(default_factory=list)
|
|
40
|
+
exclude_method_attributes: list[str] = Field(default_factory=list)
|
|
41
|
+
method_names_to_inspect: list[str] = Field(default_factory=list)
|
|
42
|
+
additional_callables_to_inspect: list[WrapperEntryConfig] = Field(default_factory=list)
|
|
43
|
+
signature_from_doc_string: bool = False
|
|
44
|
+
parse_entire_mro: bool = False
|
|
45
|
+
force_init_as_method: bool = True
|
|
46
|
+
allow_arbitrary_kwargs: bool = True
|
|
47
|
+
model_config = ConfigDict(arbitrary_types_allowed=True)
|
|
48
|
+
|
|
49
|
+
@model_validator(mode="before")
|
|
50
|
+
def update_wrapper_module(cls, values: dict[str, Any]) -> dict[str, Any]:
|
|
51
|
+
"""
|
|
52
|
+
Updates the wrapped module's __all__ attribute by filtering out excluded attributes.
|
|
53
|
+
This validation occurs before model creation to ensure proper module attribute handling.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
values (dict[str, Any]): Dictionary of configuration values being validated
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
dict[str, Any]: Returns the validated configuration values with updated module
|
|
60
|
+
attributes filtered according to `exclude_module_atts`
|
|
61
|
+
"""
|
|
62
|
+
wrapped_object = values.get("wrapped_object")
|
|
63
|
+
exclude_module_atts = values.get("exclude_module_atts", [])
|
|
64
|
+
if inspect.ismodule(wrapped_object) and exclude_module_atts:
|
|
65
|
+
cast(Any, wrapped_object).__all__ = [n for n in wrapped_object.__all__ if n not in exclude_module_atts]
|
|
66
|
+
return values
|
|
67
|
+
|
|
68
|
+
@model_validator(mode="after")
|
|
69
|
+
def no_methods_if_function(self) -> WrapperEntryConfig:
|
|
70
|
+
"""
|
|
71
|
+
Validates that method inspection is only configured for appropriate object types.
|
|
72
|
+
Ensures method_names_to_inspect is empty when wrapping functions.
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
WrapperEntryConfig: Returns the validated configuration instance
|
|
76
|
+
|
|
77
|
+
Raises:
|
|
78
|
+
ValueError: If method_names_to_inspect is set for a function wrapper
|
|
79
|
+
"""
|
|
80
|
+
if not inspect.isfunction(self.wrapped_object) and self.method_names_to_inspect:
|
|
81
|
+
raise ValueError("method_names_to_inspect cannot be set if the wrapped object is a class or module")
|
|
82
|
+
return self
|
|
83
|
+
|
|
84
|
+
@computed_field
|
|
85
|
+
@cached_property
|
|
86
|
+
def module_att_names(self) -> list[str]:
|
|
87
|
+
"""
|
|
88
|
+
Generates the list of template names for wrapped module attributes.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
list[str]: Returns a list of template names generated by combining module
|
|
92
|
+
attributes with the configured template name suffix
|
|
93
|
+
"""
|
|
94
|
+
if inspect.ismodule(self.wrapped_object):
|
|
95
|
+
all_atts = getattr(self.wrapped_object, "__all__", [])
|
|
96
|
+
att_names_with_suffix = [f"{att}{self.template_name_suffix}" for att in all_atts]
|
|
97
|
+
else:
|
|
98
|
+
att_names_with_suffix = [f"{self.wrapped_object.__name__}{self.template_name_suffix}"]
|
|
99
|
+
return att_names_with_suffix
|
|
100
|
+
|
|
101
|
+
def strip_suffix(self, template_name: str) -> str:
|
|
102
|
+
"""
|
|
103
|
+
Removes the template suffix from a template name to get the original object name.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
template_name (str): Name of the template including suffix
|
|
107
|
+
|
|
108
|
+
Returns:
|
|
109
|
+
str: Returns the original object name without the template suffix
|
|
110
|
+
"""
|
|
111
|
+
return template_name.split(self.template_name_suffix)[0]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
class BaseDynamicWrapperTemplate(Template, ABC):
|
|
115
|
+
"""
|
|
116
|
+
Base class for dynamically generated template wrappers. Provides core functionality for
|
|
117
|
+
wrapping Python objects (functions, classes, modules) into templates.
|
|
118
|
+
|
|
119
|
+
Attributes:
|
|
120
|
+
WrapperEntry (WrapperEntryConfig): Configuration for how objects should be wrapped
|
|
121
|
+
CALLABLE_ATT_NAME (str): Name of attribute storing the wrapped callable
|
|
122
|
+
"""
|
|
123
|
+
|
|
124
|
+
WrapperEntry: WrapperEntryConfig
|
|
125
|
+
CALLABLE_ATT_NAME: str = "callable_object"
|
|
126
|
+
|
|
127
|
+
def __init__(self, attributes: TemplateAttributeType) -> None:
|
|
128
|
+
super().__init__(attributes)
|
|
129
|
+
self.wrapped_callable = self._make_wrapper_object()
|
|
130
|
+
|
|
131
|
+
def _make_wrapper_object(self) -> Callable:
|
|
132
|
+
"""
|
|
133
|
+
Gets the class object or method that is being wrapped dynamically. If a class object,
|
|
134
|
+
then it gets instantiated. It is expected that the required attributes to instantiate
|
|
135
|
+
the class, or to call the function or method, are present in self.attributes[name_of_class_or_method].
|
|
136
|
+
Returns:
|
|
137
|
+
Callable: Returns either an instantiated class object or the original callable,
|
|
138
|
+
configured according to the template's attributes
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
template_wrapped_callable = getattr(self, self.CALLABLE_ATT_NAME)
|
|
142
|
+
if inspect.isclass(template_wrapped_callable):
|
|
143
|
+
template_wrapped_callable = template_wrapped_callable(
|
|
144
|
+
**self.get_callable_attributes(f"{template_wrapped_callable.__name__.lower()}_init", as_dict=True)
|
|
145
|
+
)
|
|
146
|
+
return template_wrapped_callable
|
|
147
|
+
|
|
148
|
+
def get_callable_attributes(self, method_name: str, as_dict: bool = False) -> dict[str, Any] | BaseModel:
|
|
149
|
+
"""
|
|
150
|
+
Retrieves attributes for a specific callable (method or function) from the template's
|
|
151
|
+
attribute configuration.
|
|
152
|
+
|
|
153
|
+
Args:
|
|
154
|
+
method_name (str): Name of the method or function to get attributes for
|
|
155
|
+
as_dict (bool): Whether to return attributes as a dictionary
|
|
156
|
+
|
|
157
|
+
Returns:
|
|
158
|
+
dict[str, Any] | BaseModel: Returns either a dictionary of attributes or
|
|
159
|
+
a Pydantic BaseModel containing the attributes, depending on the as_dict parameter
|
|
160
|
+
"""
|
|
161
|
+
atts_base_model = getattr(self.attributes, method_name, {})
|
|
162
|
+
if as_dict and atts_base_model and isinstance(atts_base_model, BaseModel):
|
|
163
|
+
if type(atts_base_model) is BaseModel:
|
|
164
|
+
self.logger.warning(f"`{method_name}` is a raw BaseModel instance; skipping dump of model.")
|
|
165
|
+
return {}
|
|
166
|
+
return atts_base_model.model_dump()
|
|
167
|
+
if not atts_base_model:
|
|
168
|
+
self.logger.debug(f"No `{method_name}` defined in attributes. Will return empty dict.")
|
|
169
|
+
return atts_base_model
|