swarmauri-core 0.6.0.dev104__tar.gz → 0.6.0.dev106__tar.gz

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.
Files changed (115) hide show
  1. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/PKG-INFO +1 -1
  2. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/pyproject.toml +1 -1
  3. swarmauri_core-0.6.0.dev106/swarmauri_core/ComponentBase.py +440 -0
  4. swarmauri_core-0.6.0.dev104/swarmauri_core/ComponentBase.py +0 -243
  5. swarmauri_core-0.6.0.dev104/swarmauri_core/typing.py +0 -50
  6. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/README.md +0 -0
  7. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/README.md +0 -0
  8. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/__init__.py +0 -0
  9. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agent_apis/IAgentCommands.py +0 -0
  10. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agent_apis/IAgentRouterCRUD.py +0 -0
  11. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agent_apis/__init__.py +0 -0
  12. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agent_factories/IExportConf.py +0 -0
  13. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agent_factories/__init__.py +0 -0
  14. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agents/IAgent.py +0 -0
  15. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agents/IAgentConversation.py +0 -0
  16. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agents/IAgentParser.py +0 -0
  17. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agents/IAgentRetrieve.py +0 -0
  18. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agents/IAgentSystemContext.py +0 -0
  19. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agents/IAgentToolkit.py +0 -0
  20. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agents/IAgentVectorStore.py +0 -0
  21. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/agents/__init__.py +0 -0
  22. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chains/ICallableChain.py +0 -0
  23. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chains/IChain.py +0 -0
  24. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chains/IChainContext.py +0 -0
  25. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chains/IChainContextLoader.py +0 -0
  26. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chains/IChainDependencyResolver.py +0 -0
  27. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chains/IChainFactory.py +0 -0
  28. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chains/IChainStep.py +0 -0
  29. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chains/__init__.py +0 -0
  30. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chunkers/IChunker.py +0 -0
  31. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/chunkers/__init__.py +0 -0
  32. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/control_panels/IControlPanel.py +0 -0
  33. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/control_panels/__init__.py +0 -0
  34. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/conversations/IConversation.py +0 -0
  35. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/conversations/IMaxSize.py +0 -0
  36. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/conversations/ISystemContext.py +0 -0
  37. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/conversations/__init__.py +0 -0
  38. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/dataconnectors/IDataConnector.py +0 -0
  39. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/dataconnectors/__init__.py +0 -0
  40. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/distances/IDistanceSimilarity.py +0 -0
  41. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/distances/__init__.py +0 -0
  42. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/document_stores/IDocumentRetrieve.py +0 -0
  43. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/document_stores/IDocumentStore.py +0 -0
  44. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/document_stores/__init__.py +0 -0
  45. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/documents/IDocument.py +0 -0
  46. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/documents/IExperimentDocument.py +0 -0
  47. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/documents/__init__.py +0 -0
  48. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/embeddings/IFeature.py +0 -0
  49. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/embeddings/ISaveModel.py +0 -0
  50. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/embeddings/IVectorize.py +0 -0
  51. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/embeddings/__init__.py +0 -0
  52. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/experiment_stores/IExperimentStore.py +0 -0
  53. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/experiment_stores/__init__.py +0 -0
  54. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/factories/IFactory.py +0 -0
  55. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/factories/__init__.py +0 -0
  56. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/image_gens/IGenImage.py +0 -0
  57. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/image_gens/__init__.py +0 -0
  58. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/llms/IFit.py +0 -0
  59. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/llms/IPredict.py +0 -0
  60. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/llms/__init__.py +0 -0
  61. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/measurements/IMeasurement.py +0 -0
  62. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/measurements/IMeasurementAggregate.py +0 -0
  63. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/measurements/IMeasurementCalculate.py +0 -0
  64. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/measurements/IThreshold.py +0 -0
  65. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/measurements/__init__.py +0 -0
  66. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/messages/IMessage.py +0 -0
  67. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/messages/__init__.py +0 -0
  68. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/parsers/IParser.py +0 -0
  69. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/parsers/__init__.py +0 -0
  70. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/pipelines/IPipeline.py +0 -0
  71. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/pipelines/__init__.py +0 -0
  72. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/prompts/IPrompt.py +0 -0
  73. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/prompts/IPromptMatrix.py +0 -0
  74. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/prompts/ITemplate.py +0 -0
  75. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/prompts/__init__.py +0 -0
  76. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/schema_converters/ISchemaConvert.py +0 -0
  77. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/schema_converters/__init__.py +0 -0
  78. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/service_registries/IServiceRegistry.py +0 -0
  79. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/service_registries/__init__.py +0 -0
  80. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/state/IState.py +0 -0
  81. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/swarm_apis/IAgentRegistrationAPI.py +0 -0
  82. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/swarm_apis/ISwarmAPI.py +0 -0
  83. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/swarm_apis/__init__.py +0 -0
  84. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/swarms/ISwarm.py +0 -0
  85. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/swarms/__init__.py +0 -0
  86. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/task_mgmt_strategies/ITaskMgmtStrategy.py +0 -0
  87. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/task_mgmt_strategies/__init__.py +0 -0
  88. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/toolkits/IToolkit.py +0 -0
  89. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/toolkits/__init__.py +0 -0
  90. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/tools/IParameter.py +0 -0
  91. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/tools/ITool.py +0 -0
  92. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/tools/__init__.py +0 -0
  93. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/tracing/IChainTracer.py +0 -0
  94. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/tracing/ITraceContext.py +0 -0
  95. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/tracing/ITracer.py +0 -0
  96. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/tracing/__init__.py +0 -0
  97. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/transports/ITransport.py +0 -0
  98. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/transports/__init__.py +0 -0
  99. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/utils/ITransactional.py +0 -0
  100. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/utils/__init__.py +0 -0
  101. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vcms/IPredictVision.py +0 -0
  102. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vcms/__init__.py +0 -0
  103. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vector_stores/ICloudVectorStore.py +0 -0
  104. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vector_stores/IPersistentVectorStore.py +0 -0
  105. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vector_stores/ISimilarity.py +0 -0
  106. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vector_stores/IVectorNorm.py +0 -0
  107. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vector_stores/IVectorStore.py +0 -0
  108. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vector_stores/IVectorStoreRetrieve.py +0 -0
  109. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vector_stores/IVectorStoreSaveLoad.py +0 -0
  110. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vector_stores/__init__.py +0 -0
  111. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vectors/IVector.py +0 -0
  112. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vectors/IVectorMeta.py +0 -0
  113. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vectors/IVectorProduct.py +0 -0
  114. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vectors/IVectorTransform.py +0 -0
  115. {swarmauri_core-0.6.0.dev104 → swarmauri_core-0.6.0.dev106}/swarmauri_core/vectors/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: swarmauri-core
3
- Version: 0.6.0.dev104
3
+ Version: 0.6.0.dev106
4
4
  Summary: This repository includes core interfaces for the Swarmauri framework.
5
5
  Home-page: http://github.com/swarmauri/swarmauri-sdk
6
6
  License: Apache-2.0
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "swarmauri-core"
3
- version = "0.6.0.dev104"
3
+ version = "0.6.0.dev106"
4
4
  description = "This repository includes core interfaces for the Swarmauri framework."
5
5
  authors = ["Jacob Stewart <jacob@swarmauri.com>"]
6
6
  license = "Apache-2.0"
@@ -0,0 +1,440 @@
1
+ # swarmauri_core/ComponentBase.py
2
+
3
+ import hashlib
4
+ import inspect
5
+ import json
6
+ import logging
7
+ from enum import Enum
8
+ from threading import Lock
9
+ from uuid import uuid4
10
+ from pydantic import BaseModel, Field, ValidationError, field_validator
11
+ from typing import (
12
+ Annotated,
13
+ Any,
14
+ ClassVar,
15
+ Dict,
16
+ Generic,
17
+ List,
18
+ Literal,
19
+ Optional,
20
+ Set,
21
+ Type,
22
+ TypeVar,
23
+ Union,
24
+ get_args,
25
+ get_origin,
26
+ )
27
+
28
+
29
+ T = TypeVar("T", bound="ComponentBase")
30
+
31
+ class SubclassUnion(Generic[T], type):
32
+ """
33
+ A generic class to create discriminated unions based on resource types.
34
+ """
35
+ def __class_getitem__(cls, resource_type: Type[T]) -> type:
36
+ """
37
+ Allows usage of SubclassUnion[ResourceType] to get the corresponding discriminated Union.
38
+
39
+ Parameters:
40
+ - resource_type: The base class of the resource (e.g., Shape, Kind).
41
+
42
+ Returns:
43
+ - An Annotated Union of all subclasses registered under the resource_type, with 'type' as the discriminator.
44
+ """
45
+ registered_classes = list(ComponentBase.TYPE_REGISTRY.get(resource_type, {}).values())
46
+ if not registered_classes:
47
+ raise ValueError(f"No subclasses registered for resource type '{resource_type.__name__}'")
48
+ union_type = Union[tuple(registered_classes)]
49
+ return Annotated[union_type, Field(serialization_alias=f"SubclassUnion[{resource_type.__name__}]", discriminator='type')]
50
+
51
+ class ResourceTypes(Enum):
52
+ UNIVERSAL_BASE = "ComponentBase"
53
+ AGENT = "Agent"
54
+ AGENT_FACTORY = "AgentFactory"
55
+ CHAIN = "Chain"
56
+ CHAIN_METHOD = "ChainMethod"
57
+ CHUNKER = "Chunker"
58
+ CONVERSATION = "Conversation"
59
+ DISTANCE = "Distance"
60
+ DOCUMENT_STORE = "DocumentStore"
61
+ DOCUMENT = "Document"
62
+ EMBEDDING = "Embedding"
63
+ EXCEPTION = "Exception"
64
+ IMAGE_GEN = "ImageGen"
65
+ LLM = "LLM"
66
+ MESSAGE = "Message"
67
+ MEASUREMENT = "Measurement"
68
+ PARSER = "Parser"
69
+ PROMPT = "Prompt"
70
+ STATE = "State"
71
+ CHAINSTEP = "ChainStep"
72
+ SCHEMA_CONVERTER = "SchemaConverter"
73
+ SWARM = "Swarm"
74
+ TOOLKIT = "Toolkit"
75
+ TOOL = "Tool"
76
+ PARAMETER = "Parameter"
77
+ TRACE = "Trace"
78
+ UTIL = "Util"
79
+ VECTOR_STORE = "VectorStore"
80
+ VECTOR = "Vector"
81
+ VCM = "VCM"
82
+ DATA_CONNECTOR = "DataConnector"
83
+ TRANSPORT = "Transport"
84
+ FACTORY = "Factory"
85
+ PIPELINE = "Pipeline"
86
+ SERVICE_REGISTRY = "ServiceRegistry"
87
+ CONTROL_PANEL = "ControlPanel"
88
+ TASK_MGMT_STRATEGY = "TaskMgmtStrategy"
89
+
90
+ def generate_id() -> str:
91
+ return str(uuid4())
92
+
93
+ class ComponentBase(BaseModel):
94
+ """
95
+ Base class for all components.
96
+ """
97
+ # Class-level registry mapping resource types to their type mappings
98
+ TYPE_REGISTRY: ClassVar[Dict[Type['ComponentBase'], Dict[str, Type['ComponentBase']]]] = {}
99
+ # Model registry mapping models to their resource types
100
+ MODEL_REGISTRY: ClassVar[Dict[Type[BaseModel], Type['ComponentBase']]] = {}
101
+ _lock: ClassVar[Lock] = Lock()
102
+
103
+ name: Optional[str] = None
104
+ id: str = Field(default_factory=generate_id)
105
+ members: List[str] = Field(default_factory=list)
106
+ owner: Optional[str] = None
107
+ host: Optional[str] = None
108
+ resource: str = Field(default="ComponentBase")
109
+ version: str = "0.1.0"
110
+ type: Literal["ComponentBase"] = "ComponentBase"
111
+
112
+ @field_validator("type")
113
+ def set_type(cls, v, values):
114
+ if v == "ComponentBase" and cls.__name__ != "ComponentBase":
115
+ return cls.__name__
116
+ return v
117
+
118
+
119
+ # Normative Class Methods
120
+ def __swm_class_hash__(self):
121
+ sig_hash = hashlib.sha256()
122
+ for attr_name in dir(self):
123
+ attr_value = getattr(self, attr_name)
124
+ if callable(attr_value) and not attr_name.startswith("_"):
125
+ sig = inspect.signature(attr_value)
126
+ sig_hash.update(str(sig).encode())
127
+ return sig_hash.hexdigest()
128
+
129
+ @classmethod
130
+ def swm_public_interfaces(cls):
131
+ methods = []
132
+ for attr_name in dir(cls):
133
+ attr_value = getattr(cls, attr_name)
134
+ if (callable(attr_value) and not attr_name.startswith("_")) or isinstance(
135
+ attr_value, property
136
+ ):
137
+ methods.append(attr_name)
138
+ return methods
139
+
140
+ @classmethod
141
+ def swm_ismethod_registered(cls, method_name: str):
142
+ return method_name in cls.public_interfaces()
143
+
144
+ @classmethod
145
+ def swm_method_signature(cls, input_signature):
146
+ for method_name in cls.public_interfaces():
147
+ method = getattr(cls, method_name)
148
+ if callable(method):
149
+ sig = str(inspect.signature(method))
150
+ if sig == input_signature:
151
+ return True
152
+ return False
153
+
154
+ # Experimental properties in support of
155
+
156
+ @property
157
+ def swm_path(self):
158
+ if self.host and self.owner:
159
+ return f"{self.host}/{self.owner}/{self.resource}/{self.name}/{self.id}"
160
+ if self.resource and self.name:
161
+ return f"/{self.resource}/{self.name}/{self.id}"
162
+ return f"/{self.resource}/{self.id}"
163
+
164
+ @property
165
+ def swm_isremote(self):
166
+ return bool(self.host)
167
+
168
+ # Functional Class Methods
169
+
170
+ @classmethod
171
+ def register_type(cls, resource_type: Type[T], type_name: str):
172
+ """
173
+ Decorator to register a component class with a specific type name under a resource type.
174
+ """
175
+ def decorator(subclass: Type['ComponentBase']):
176
+ if not issubclass(subclass, resource_type):
177
+ raise TypeError(f"Registered class '{subclass.__name__}' must be a subclass of {resource_type.__name__}")
178
+ if resource_type not in cls.TYPE_REGISTRY:
179
+ cls.TYPE_REGISTRY[resource_type] = {}
180
+ cls.TYPE_REGISTRY[resource_type][type_name] = subclass
181
+ # Automatically recreate models after registering a new type
182
+ cls.recreate_models_for_resource(resource_type)
183
+ logger.info(f"Registered type '{type_name}' for resource '{resource_type.__name__}' with subclass '{subclass.__name__}'")
184
+ return subclass
185
+ return decorator
186
+
187
+ @classmethod
188
+ def register_model(cls):
189
+ """
190
+ Decorator to register a Pydantic model by automatically detecting resource types
191
+ from fields that use SubclassUnion.
192
+ """
193
+ def decorator(model_cls: Type[BaseModel]):
194
+ # Initialize list if not present
195
+ if model_cls not in cls.MODEL_REGISTRY:
196
+ cls.MODEL_REGISTRY[model_cls] = []
197
+
198
+ # Inspect all fields to find SubclassUnion annotations
199
+ for field_name, field in model_cls.__fields__.items():
200
+ field_annotation = model_cls.__annotations__.get(field_name)
201
+ if not field_annotation:
202
+ continue
203
+
204
+ # Check if field uses SubclassUnion
205
+ if cls.field_contains_subclass_union(field_annotation):
206
+ # Extract resource types from SubclassUnion
207
+ resource_types = cls.extract_resource_types_from_field(field_annotation)
208
+ for resource_type in resource_types:
209
+ if resource_type not in cls.MODEL_REGISTRY[model_cls]:
210
+ cls.MODEL_REGISTRY[model_cls].append(resource_type)
211
+ logger.info(f"Registered model '{model_cls.__name__}' for resource '{resource_type.__name__}'")
212
+
213
+ # Recreate models for all associated resource types
214
+ for resource_type in cls.MODEL_REGISTRY[model_cls]:
215
+ cls.recreate_models_for_resource(resource_type)
216
+
217
+ return model_cls
218
+ return decorator
219
+
220
+ @classmethod
221
+ def get_class_by_type(cls, resource_type: Type[T], type_name: str) -> Type['ComponentBase']:
222
+ """
223
+ Retrieve a component class based on its resource type and type name.
224
+
225
+ Parameters:
226
+ - resource_type: The base class of the resource.
227
+ - type_name: The string identifier for the component type.
228
+
229
+ Returns:
230
+ - The corresponding component class.
231
+ """
232
+ return cls.TYPE_REGISTRY.get(resource_type, {}).get(type_name)
233
+
234
+ @classmethod
235
+ def field_contains_subclass_union(cls, field_annotation) -> bool:
236
+ """
237
+ Check if the field annotation contains a SubclassUnion.
238
+
239
+ Parameters:
240
+ - field_annotation: The type annotation of the field.
241
+
242
+ Returns:
243
+ - True if SubclassUnion is present, False otherwise.
244
+ """
245
+ if isinstance(field_annotation, type(SubclassUnion)):
246
+ return True
247
+ origin = get_origin(field_annotation)
248
+ if origin is Annotated:
249
+ args = get_args(field_annotation)
250
+ return cls.field_contains_subclass_union(args[0])
251
+ elif origin in {list, List, dict, Dict, Union}:
252
+ args = get_args(field_annotation)
253
+ return any(cls.field_contains_subclass_union(arg) for arg in args)
254
+ return False
255
+
256
+ @classmethod
257
+ def extract_resource_types_from_field(cls, field_annotation) -> List[Type['BaseResource']]:
258
+ """
259
+ Extracts all resource types from a field annotation that uses SubclassUnion.
260
+
261
+ Parameters:
262
+ - field_annotation: The type annotation of the field.
263
+
264
+ Returns:
265
+ - A list of resource type classes.
266
+ """
267
+ resource_types = []
268
+
269
+ origin = get_origin(field_annotation)
270
+ args = get_args(field_annotation)
271
+
272
+ if origin is Annotated:
273
+ # Extract the actual type from Annotated
274
+ field_annotation = args[0]
275
+ origin = get_origin(field_annotation)
276
+ args = get_args(field_annotation)
277
+
278
+ if origin is Union:
279
+ for arg in args:
280
+ if cls.field_contains_subclass_union(arg):
281
+ resource_types.extend(cls.extract_resource_types_from_field(arg))
282
+ elif isinstance(field_annotation, type) and issubclass(field_annotation, SubclassUnion):
283
+ # Assuming SubclassUnion is generic and parameterized
284
+ subclass_args = get_args(field_annotation)
285
+ if subclass_args:
286
+ resource_type = subclass_args[0]
287
+ resource_types.append(resource_type)
288
+ elif origin is list or origin is List:
289
+ # Handle List[SubclassUnion[ResourceType]]
290
+ item_type = args[0]
291
+ resource_types.extend(cls.extract_resource_types_from_field(item_type))
292
+ elif origin is dict or origin is Dict:
293
+ # Handle Dict[key_type, SubclassUnion[ResourceType]]
294
+ value_type = args[1]
295
+ resource_types.extend(cls.extract_resource_types_from_field(value_type))
296
+
297
+ return resource_types
298
+
299
+ @classmethod
300
+ def determine_new_type(cls, field_annotation, resource_type):
301
+ """
302
+ Determine the new type for a field based on its annotation and resource type.
303
+
304
+ Parameters:
305
+ - field_annotation: The original type annotation.
306
+ - resource_type: The resource type associated with the field.
307
+
308
+ Returns:
309
+ - The updated type annotation incorporating SubclassUnion.
310
+ """
311
+ origin = get_origin(field_annotation)
312
+ args = get_args(field_annotation)
313
+
314
+ is_optional = False
315
+
316
+ if origin is Union and type(None) in args:
317
+ # Handle Optional and Union types
318
+ non_none_args = [arg for arg in args if arg is not type(None)]
319
+ if len(non_none_args) == 1:
320
+ field_annotation = non_none_args[0]
321
+ origin = get_origin(field_annotation)
322
+ args = get_args(field_annotation)
323
+ is_optional = True
324
+ else:
325
+ field_annotation = Union[tuple(non_none_args)]
326
+ origin = get_origin(field_annotation)
327
+ args = get_args(field_annotation)
328
+ is_optional = True
329
+
330
+ # Handle Annotated types by extracting the underlying type
331
+ if origin is Annotated:
332
+ # Extract the actual type from Annotated
333
+ field_annotation = args[0]
334
+ origin = get_origin(field_annotation)
335
+ args = get_args(field_annotation)
336
+
337
+ if origin in {list, List}:
338
+ # Handle List[SubclassUnion[ResourceType]]
339
+ new_type = List[SubclassUnion[resource_type]]
340
+ elif origin in {dict, Dict}:
341
+ # Handle Dict[key_type, SubclassUnion[ResourceType]]
342
+ key_type, value_type = args
343
+ new_type = Dict[key_type, SubclassUnion[resource_type]]
344
+ elif origin is Union:
345
+ # Handle Union types
346
+ union_types = []
347
+ for arg in args:
348
+ if cls.field_contains_subclass_union(arg):
349
+ union_types.append(SubclassUnion[resource_type])
350
+ else:
351
+ union_types.append(arg)
352
+ new_type = Union[tuple(union_types)]
353
+ else:
354
+ # Handle non-generic types
355
+ new_type = SubclassUnion[resource_type]
356
+
357
+ if is_optional:
358
+ # Include None in the Union and maintain the discriminator
359
+ registered_classes = list(cls.TYPE_REGISTRY.get(resource_type, {}).values())
360
+ union_with_none = Union[tuple(registered_classes + [type(None)])]
361
+ new_type = Annotated[union_with_none, Field(discriminator="type")]
362
+
363
+ return new_type
364
+
365
+ @classmethod
366
+ def generate_models_with_fields(cls) -> Dict[Type[BaseModel], Dict[str, Any]]:
367
+ """
368
+ Automatically generate the models_with_fields dictionary based on registered models.
369
+
370
+ Returns:
371
+ - A dictionary mapping model classes to their fields and corresponding resource types.
372
+ """
373
+ models_with_fields = {}
374
+ for model_cls, resource_types in cls.MODEL_REGISTRY.items():
375
+ models_with_fields[model_cls] = {}
376
+ for field_name, field in model_cls.__fields__.items():
377
+ field_annotation = model_cls.__annotations__.get(field_name)
378
+ if not field_annotation:
379
+ continue
380
+
381
+ # Check if SubclassUnion is used in the field type
382
+ if not cls.field_contains_subclass_union(field_annotation):
383
+ continue # Only process fields that use SubclassUnion
384
+
385
+ # Extract all resource types from the field
386
+ field_resource_types = cls.extract_resource_types_from_field(field_annotation)
387
+ for resource_type in field_resource_types:
388
+ new_type = cls.determine_new_type(field_annotation, resource_type)
389
+ models_with_fields[model_cls][field_name] = new_type
390
+
391
+ return models_with_fields
392
+
393
+ @classmethod
394
+ def recreate_models(cls):
395
+ """
396
+ Recreate all models based on the dynamically generated models_with_fields.
397
+ """
398
+ with cls._lock:
399
+ models_with_fields = cls.generate_models_with_fields()
400
+ for model_class, fields in models_with_fields.items():
401
+ for field_name, new_type in fields.items():
402
+ if field_name in model_class.model_fields:
403
+ model_class.model_fields[field_name].annotation = new_type
404
+ else:
405
+ raise ValueError(f"Field '{field_name}' does not exist in model '{model_class.__name__}'")
406
+ model_class.model_rebuild(force=True)
407
+ logger.info("All models have been successfully recreated.")
408
+
409
+ @classmethod
410
+ def recreate_models_for_resource(cls, resource_type: Type[T]):
411
+ """
412
+ Recreate only the models associated with the given resource type.
413
+ """
414
+ with cls._lock:
415
+ models_with_fields = {}
416
+ for model_cls, res_types in cls.MODEL_REGISTRY.items():
417
+ if resource_type in res_types:
418
+ models_with_fields[model_cls] = {}
419
+ for field_name, field in model_cls.__fields__.items():
420
+ field_annotation = model_cls.__annotations__.get(field_name)
421
+ if not field_annotation:
422
+ continue
423
+
424
+ # Check if SubclassUnion is used in the field type
425
+ if not cls.field_contains_subclass_union(field_annotation):
426
+ continue # Only process fields that use SubclassUnion
427
+
428
+ # Determine the new type based on the annotation and resource_type
429
+ new_type = cls.determine_new_type(field_annotation, resource_type)
430
+
431
+ models_with_fields[model_cls][field_name] = new_type
432
+
433
+ for model_class, fields in models_with_fields.items():
434
+ for field_name, new_type in fields.items():
435
+ if field_name in model_class.model_fields:
436
+ model_class.model_fields[field_name].annotation = new_type
437
+ else:
438
+ raise ValueError(f"Field '{field_name}' does not exist in model '{model_class.__name__}'")
439
+ model_class.model_rebuild(force=True)
440
+ logger.info(f"Models associated with resource '{resource_type.__name__}' have been successfully recreated.")
@@ -1,243 +0,0 @@
1
- import json
2
- from typing import (
3
- Any,
4
- Dict,
5
- Optional,
6
- List,
7
- Literal,
8
- TypeVar,
9
- Type,
10
- Union,
11
- ClassVar,
12
- Set,
13
- get_args,
14
- )
15
-
16
- from uuid import uuid4
17
- from enum import Enum
18
- import inspect
19
- import hashlib
20
- from pydantic import BaseModel, Field, ValidationError, field_validator
21
- import logging
22
- from swarmauri_core.typing import SubclassUnion
23
-
24
-
25
- T = TypeVar("T", bound="ComponentBase")
26
-
27
-
28
- class ResourceTypes(Enum):
29
- UNIVERSAL_BASE = "ComponentBase"
30
- AGENT = "Agent"
31
- AGENT_FACTORY = "AgentFactory"
32
- CHAIN = "Chain"
33
- CHAIN_METHOD = "ChainMethod"
34
- CHUNKER = "Chunker"
35
- CONVERSATION = "Conversation"
36
- DISTANCE = "Distance"
37
- DOCUMENT_STORE = "DocumentStore"
38
- DOCUMENT = "Document"
39
- EMBEDDING = "Embedding"
40
- EXCEPTION = "Exception"
41
- IMAGE_GEN = "ImageGen"
42
- LLM = "LLM"
43
- MESSAGE = "Message"
44
- MEASUREMENT = "Measurement"
45
- PARSER = "Parser"
46
- PROMPT = "Prompt"
47
- STATE = "State"
48
- CHAINSTEP = "ChainStep"
49
- SCHEMA_CONVERTER = "SchemaConverter"
50
- SWARM = "Swarm"
51
- TOOLKIT = "Toolkit"
52
- TOOL = "Tool"
53
- PARAMETER = "Parameter"
54
- TRACE = "Trace"
55
- UTIL = "Util"
56
- VECTOR_STORE = "VectorStore"
57
- VECTOR = "Vector"
58
- VCM = "VCM"
59
- DATA_CONNECTOR = "DataConnector"
60
- TRANSPORT = "Transport"
61
- FACTORY = "Factory"
62
- PIPELINE = "Pipeline"
63
- SERVICE_REGISTRY = "ServiceRegistry"
64
- CONTROL_PANEL = "ControlPanel"
65
- TASK_MGMT_STRATEGY = "TaskMgmtStrategy"
66
-
67
- def generate_id() -> str:
68
- return str(uuid4())
69
-
70
- class ComponentBase(BaseModel):
71
- name: Optional[str] = None
72
- id: str = Field(default_factory=generate_id)
73
- members: List[str] = Field(default_factory=list)
74
- owner: Optional[str] = None
75
- host: Optional[str] = None
76
- resource: str = Field(default="ComponentBase")
77
- version: str = "0.1.0"
78
- __swm_subclasses__: ClassVar[Set[Type["ComponentBase"]]] = set()
79
- type: Literal["ComponentBase"] = "ComponentBase"
80
-
81
- def __init_subclass__(cls, **kwargs):
82
- super().__init_subclass__(**kwargs)
83
- ComponentBase.__swm_register_subclass__(cls)
84
-
85
- @classmethod
86
- def __swm_register_subclass__(cls, subclass) -> None:
87
- logging.debug("__swm_register_subclass__ executed\n")
88
-
89
- if "type" in subclass.__annotations__:
90
- sub_type = subclass.__annotations__["type"]
91
- if sub_type not in [
92
- subclass.__annotations__["type"] for subclass in cls.__swm_subclasses__
93
- ]:
94
- cls.__swm_subclasses__.add(subclass)
95
- else:
96
- logging.warning(
97
- f"Subclass {subclass.__name__} does not have a type annotation"
98
- )
99
-
100
- @classmethod
101
- def __swm_reset_class__(cls):
102
- logging.debug("__swm_reset_class__ executed\n")
103
- for each in cls.__fields__:
104
- logging.debug(each, cls.__fields__[each].discriminator)
105
- if cls.__fields__[each].discriminator and each in cls.__annotations__:
106
- if len(get_args(cls.__fields__[each].annotation)) > 0:
107
- for x in range(0, len(get_args(cls.__fields__[each].annotation))):
108
- if hasattr(
109
- get_args(cls.__fields__[each].annotation)[x], "__base__"
110
- ):
111
- if (
112
- hasattr(
113
- get_args(cls.__fields__[each].annotation)[
114
- x
115
- ].__base__,
116
- "__swm_subclasses__",
117
- )
118
- and not get_args(cls.__fields__[each].annotation)[
119
- x
120
- ].__base__.__name__
121
- == "ComponentBase"
122
- ):
123
- baseclass = get_args(cls.__fields__[each].annotation)[
124
- x
125
- ].__base__
126
-
127
- sc = SubclassUnion[baseclass]
128
-
129
- cls.__annotations__[each] = sc
130
- cls.__fields__[each].annotation = sc
131
-
132
- cls.model_rebuild(force=True)
133
-
134
- @field_validator("type")
135
- def set_type(cls, v, values):
136
- if v == "ComponentBase" and cls.__name__ != "ComponentBase":
137
- return cls.__name__
138
- return v
139
-
140
- def __swm_class_hash__(self):
141
- sig_hash = hashlib.sha256()
142
- for attr_name in dir(self):
143
- attr_value = getattr(self, attr_name)
144
- if callable(attr_value) and not attr_name.startswith("_"):
145
- sig = inspect.signature(attr_value)
146
- sig_hash.update(str(sig).encode())
147
- return sig_hash.hexdigest()
148
-
149
- @classmethod
150
- def swm_public_interfaces(cls):
151
- methods = []
152
- for attr_name in dir(cls):
153
- attr_value = getattr(cls, attr_name)
154
- if (callable(attr_value) and not attr_name.startswith("_")) or isinstance(
155
- attr_value, property
156
- ):
157
- methods.append(attr_name)
158
- return methods
159
-
160
- @classmethod
161
- def swm_ismethod_registered(cls, method_name: str):
162
- return method_name in cls.public_interfaces()
163
-
164
- @classmethod
165
- def swm_method_signature(cls, input_signature):
166
- for method_name in cls.public_interfaces():
167
- method = getattr(cls, method_name)
168
- if callable(method):
169
- sig = str(inspect.signature(method))
170
- if sig == input_signature:
171
- return True
172
- return False
173
-
174
- @property
175
- def swm_path(self):
176
- if self.host and self.owner:
177
- return f"{self.host}/{self.owner}/{self.resource}/{self.name}/{self.id}"
178
- if self.resource and self.name:
179
- return f"/{self.resource}/{self.name}/{self.id}"
180
- return f"/{self.resource}/{self.id}"
181
-
182
- @property
183
- def swm_isremote(self):
184
- return bool(self.host)
185
-
186
- @classmethod
187
- def model_validate_json(
188
- cls: Type[T], json_payload: Union[str, Dict[str, Any]], strict: bool = False
189
- ) -> T:
190
- # Ensure we're working with a dictionary
191
- if isinstance(json_payload, str):
192
- try:
193
- payload_dict = json.loads(json_payload)
194
- except json.JSONDecodeError:
195
- raise ValueError("Invalid JSON payload")
196
- else:
197
- payload_dict = json_payload
198
-
199
- # Try to determine the specific component type
200
- component_type = payload_dict.get("type", "ComponentBase")
201
-
202
- # Attempt to find the correct subclass
203
- target_cls = cls.get_subclass_by_type(component_type)
204
-
205
- # Fallback logic
206
- if target_cls is None:
207
- if strict:
208
- raise ValueError(f"Cannot resolve component type: {component_type}")
209
- target_cls = cls
210
- logging.warning(
211
- f"Falling back to base ComponentBase for type: {component_type}"
212
- )
213
-
214
- # Validate using the determined class
215
- try:
216
- return target_cls.model_validate(payload_dict)
217
- except ValidationError as e:
218
- logging.error(f"Validation failed for {component_type}: {e}")
219
- raise
220
-
221
- @classmethod
222
- def get_subclass_by_type(cls, type_name: str) -> Optional[Type["ComponentBase"]]:
223
- # First, check for exact match in registered subclasses
224
- for subclass in cls.__swm_subclasses__:
225
- if (
226
- subclass.__name__ == type_name
227
- or getattr(subclass, "type", None) == type_name
228
- ):
229
- return subclass
230
-
231
- # If no exact match, try case-insensitive search
232
- for subclass in cls.__swm_subclasses__:
233
- if (
234
- subclass.__name__.lower() == type_name.lower()
235
- or str(getattr(subclass, "type", "")).lower() == type_name.lower()
236
- ):
237
- return subclass
238
-
239
- return None
240
-
241
- @classmethod
242
- def from_dict(cls, data: Dict[str, Any]) -> "ComponentBase":
243
- return cls.model_validate(data)
@@ -1,50 +0,0 @@
1
- import logging
2
- from pydantic import BaseModel, Field
3
- from typing import TypeVar, Generic, Union, Annotated, Type
4
-
5
-
6
- class SubclassUnion:
7
- _registry = {}
8
-
9
- @classmethod
10
- def __class_getitem__(cls, baseclass):
11
- subclasses = cls.__swm__get_subclasses__(baseclass)
12
- return Union[tuple(subclasses)]
13
-
14
- @classmethod
15
- def __swm__get_subclasses__(cls, baseclass) -> set:
16
- logging.debug("__swm__get_subclasses__ executed\n")
17
-
18
- def is_excluded_module(module_name: str) -> bool:
19
- return module_name == "builtins" or module_name == "types"
20
-
21
- subclasses_dict = {baseclass.__name__: baseclass}
22
- for subclass in baseclass.__subclasses__():
23
- if not is_excluded_module(subclass.__module__):
24
- subclasses_dict.update(
25
- {
26
- _s.__name__: _s
27
- for _s in cls.__swm__get_subclasses__(subclass)
28
- if not is_excluded_module(_s.__module__)
29
- }
30
- )
31
-
32
- return set(subclasses_dict.values())
33
-
34
- @classmethod
35
- def update(cls, baseclass, type_name: str, obj):
36
- """
37
- Registers a class with the SubclassUnion.
38
- """
39
- if baseclass not in cls._registry:
40
- cls._registry[baseclass] = {}
41
-
42
- cls._registry[baseclass][type_name] = obj
43
- logging.debug(f"Registered {type_name} under {baseclass.__name__}")
44
-
45
- @classmethod
46
- def get_registry(cls, baseclass):
47
- """
48
- Retrieves the registry of subclasses for a given base class.
49
- """
50
- return cls._registry.get(baseclass, {})