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