swarmauri-base 0.6.0.dev4__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.
Files changed (74) hide show
  1. swarmauri_base/agents/AgentBase.py +16 -0
  2. swarmauri_base/agents/AgentConversationMixin.py +8 -0
  3. swarmauri_base/agents/AgentRetrieveMixin.py +10 -0
  4. swarmauri_base/agents/AgentSystemContextMixin.py +15 -0
  5. swarmauri_base/agents/AgentToolMixin.py +9 -0
  6. swarmauri_base/agents/AgentVectorStoreMixin.py +8 -0
  7. swarmauri_base/agents/__init__.py +0 -0
  8. swarmauri_base/chains/ChainBase.py +34 -0
  9. swarmauri_base/chains/ChainContextBase.py +46 -0
  10. swarmauri_base/chains/ChainStepBase.py +18 -0
  11. swarmauri_base/chains/PromptContextChainBase.py +154 -0
  12. swarmauri_base/chains/__init__.py +1 -0
  13. swarmauri_base/chunkers/ChunkerBase.py +19 -0
  14. swarmauri_base/chunkers/__init__.py +0 -0
  15. swarmauri_base/control_panels/ControlPanelBase.py +99 -0
  16. swarmauri_base/control_panels/__init__.py +0 -0
  17. swarmauri_base/conversations/ConversationBase.py +50 -0
  18. swarmauri_base/conversations/ConversationSystemContextMixin.py +8 -0
  19. swarmauri_base/conversations/__init__.py +0 -0
  20. swarmauri_base/data_connectors/DataConnectorBase.py +79 -0
  21. swarmauri_base/data_connectors/__init__.py +0 -0
  22. swarmauri_base/distances/DistanceBase.py +35 -0
  23. swarmauri_base/distances/VisionDistanceBase.py +7 -0
  24. swarmauri_base/distances/__init__.py +0 -0
  25. swarmauri_base/document_stores/DocumentStoreBase.py +88 -0
  26. swarmauri_base/document_stores/DocumentStoreRetrieveBase.py +22 -0
  27. swarmauri_base/document_stores/__init__.py +0 -0
  28. swarmauri_base/documents/DocumentBase.py +14 -0
  29. swarmauri_base/documents/__init__.py +0 -0
  30. swarmauri_base/embeddings/EmbeddingBase.py +11 -0
  31. swarmauri_base/embeddings/VisionEmbeddingBase.py +7 -0
  32. swarmauri_base/embeddings/__init__.py +1 -0
  33. swarmauri_base/factories/FactoryBase.py +31 -0
  34. swarmauri_base/factories/_init__.py +0 -0
  35. swarmauri_base/image_gens/ImageGenBase.py +51 -0
  36. swarmauri_base/image_gens/__init__.py +0 -0
  37. swarmauri_base/llms/LLMBase.py +41 -0
  38. swarmauri_base/llms/__init__.py +0 -0
  39. swarmauri_base/measurements/MeasurementAggregateMixin.py +25 -0
  40. swarmauri_base/measurements/MeasurementBase.py +23 -0
  41. swarmauri_base/measurements/MeasurementCalculateMixin.py +32 -0
  42. swarmauri_base/measurements/MeasurementThresholdMixin.py +8 -0
  43. swarmauri_base/measurements/__init__.py +0 -0
  44. swarmauri_base/messages/MessageBase.py +12 -0
  45. swarmauri_base/messages/__init__.py +0 -0
  46. swarmauri_base/parsers/ParserBase.py +28 -0
  47. swarmauri_base/parsers/__init__.py +0 -0
  48. swarmauri_base/pipelines/PipelineBase.py +105 -0
  49. swarmauri_base/pipelines/__init__.py +0 -0
  50. swarmauri_base/prompts/PromptBase.py +37 -0
  51. swarmauri_base/prompts/PromptGeneratorBase.py +40 -0
  52. swarmauri_base/prompts/PromptMatrixBase.py +37 -0
  53. swarmauri_base/prompts/PromptTemplateBase.py +39 -0
  54. swarmauri_base/prompts/__init__.py +0 -0
  55. swarmauri_base/schema_converters/SchemaConverterBase.py +15 -0
  56. swarmauri_base/schema_converters/__init__.py +0 -0
  57. swarmauri_base/service_registries/ServiceRegistryBase.py +60 -0
  58. swarmauri_base/service_registries/__init__.py +0 -0
  59. swarmauri_base/state/StateBase.py +47 -0
  60. swarmauri_base/state/__init__.py +0 -0
  61. swarmauri_base/swarm/SwarmBase.py +101 -0
  62. swarmauri_base/swarm/__init__.py +0 -0
  63. swarmauri_base/task_mgmt_strategies/TaskMgtStrategyBase.py +63 -0
  64. swarmauri_base/task_mgmt_strategies/__init__.py +0 -0
  65. swarmauri_base/toolkits/ToolkitBase.py +96 -0
  66. swarmauri_base/toolkits/__init__.py +0 -0
  67. swarmauri_base/tools/ParameterBase.py +13 -0
  68. swarmauri_base/tools/ToolBase.py +64 -0
  69. swarmauri_base/tools/__init__.py +0 -0
  70. swarmauri_base/transports/TransportBase.py +50 -0
  71. swarmauri_base/transports/__init__.py +0 -0
  72. swarmauri_base-0.6.0.dev4.dist-info/METADATA +58 -0
  73. swarmauri_base-0.6.0.dev4.dist-info/RECORD +74 -0
  74. swarmauri_base-0.6.0.dev4.dist-info/WHEEL +4 -0
@@ -0,0 +1,16 @@
1
+ from typing import Any, Optional, Dict, Union, Literal
2
+ from pydantic import ConfigDict, Field, field_validator
3
+ from swarmauri_core.typing import SubclassUnion
4
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
5
+ from swarmauri_core.messages.IMessage import IMessage
6
+ from swarmauri_core.agents.IAgent import IAgent
7
+ from swarmauri.llms.base.LLMBase import LLMBase
8
+
9
+ class AgentBase(IAgent, ComponentBase):
10
+ llm: SubclassUnion[LLMBase]
11
+ resource: ResourceTypes = Field(default=ResourceTypes.AGENT.value)
12
+ model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
13
+ type: Literal['AgentBase'] = 'AgentBase'
14
+
15
+ def exec(self, input_str: Optional[Union[str, IMessage]] = "", llm_kwargs: Optional[Dict] = {}) -> Any:
16
+ raise NotImplementedError('The `exec` function has not been implemeneted on this class.')
@@ -0,0 +1,8 @@
1
+ from pydantic import BaseModel, ConfigDict
2
+ from swarmauri_core.typing import SubclassUnion
3
+ from swarmauri_core.agents.IAgentConversation import IAgentConversation
4
+ from swarmauri.conversations.base.ConversationBase import ConversationBase
5
+
6
+ class AgentConversationMixin(IAgentConversation, BaseModel):
7
+ conversation: SubclassUnion[ConversationBase] # 🚧 Placeholder
8
+ model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
@@ -0,0 +1,10 @@
1
+ from abc import ABC
2
+ from typing import List
3
+ from pydantic import BaseModel, ConfigDict, field_validator, Field
4
+ from swarmauri.documents.concrete.Document import Document
5
+ from swarmauri_core.agents.IAgentRetrieve import IAgentRetrieve
6
+
7
+ class AgentRetrieveMixin(IAgentRetrieve, BaseModel):
8
+ last_retrieved: List[Document] = Field(default_factory=list)
9
+ model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
10
+
@@ -0,0 +1,15 @@
1
+ from typing import Union
2
+ from pydantic import BaseModel, field_validator
3
+
4
+ from swarmauri.messages.concrete.SystemMessage import SystemMessage
5
+ from swarmauri_core.agents.IAgentSystemContext import IAgentSystemContext
6
+
7
+
8
+ class AgentSystemContextMixin(IAgentSystemContext, BaseModel):
9
+ system_context: Union[SystemMessage, str]
10
+
11
+ @field_validator('system_context', mode='before')
12
+ def set_system_context(cls, value: Union[str, SystemMessage]) -> SystemMessage:
13
+ if isinstance(value, str):
14
+ return SystemMessage(content=value)
15
+ return value
@@ -0,0 +1,9 @@
1
+ from pydantic import BaseModel, ConfigDict
2
+ from swarmauri_core.typing import SubclassUnion
3
+ from swarmauri.toolkits.base.ToolkitBase import ToolkitBase
4
+ from swarmauri_core.agents.IAgentToolkit import IAgentToolkit
5
+
6
+ class AgentToolMixin(IAgentToolkit, BaseModel):
7
+ toolkit: SubclassUnion[ToolkitBase]
8
+ model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
9
+
@@ -0,0 +1,8 @@
1
+ from pydantic import BaseModel, ConfigDict
2
+ from swarmauri_core.typing import SubclassUnion
3
+ from swarmauri_core.agents.IAgentVectorStore import IAgentVectorStore
4
+ from swarmauri.vector_stores.base.VectorStoreBase import VectorStoreBase
5
+
6
+ class AgentVectorStoreMixin(IAgentVectorStore, BaseModel):
7
+ vector_store: SubclassUnion[VectorStoreBase]
8
+ model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
File without changes
@@ -0,0 +1,34 @@
1
+ from typing import List, Dict, Any, Optional, Literal
2
+ from pydantic import Field, ConfigDict
3
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
4
+ from swarmauri_core.chains.IChain import IChain
5
+ from swarmauri.stanard.chains.concrete.ChainStep import ChainStep
6
+ from swarmauri_core.typing import SubclassUnion
7
+
8
+
9
+ class ChainBase(IChain, ComponentBase):
10
+ """
11
+ A base implementation of the IChain interface.
12
+ """
13
+
14
+ steps: List[ChainStep] = []
15
+ resource: Optional[str] = Field(default=ResourceTypes.CHAIN.value)
16
+ model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
17
+ type: Literal["ChainBase"] = "ChainBase"
18
+
19
+ def add_step(self, step: ChainStep) -> None:
20
+ self.steps.append(step)
21
+
22
+ def remove_step(self, step: ChainStep) -> None:
23
+ """
24
+ Removes an existing step from the chain. This alters the chain's execution sequence
25
+ by excluding the specified step from subsequent executions of the chain.
26
+
27
+ Parameters:
28
+ step (ChainStep): The Callable representing the step to remove from the chain.
29
+ """
30
+
31
+ raise NotImplementedError("This is not yet implemented")
32
+
33
+ def execute(self, *args, **kwargs) -> Dict[str, Any]:
34
+ raise NotImplementedError("This is not yet implemented")
@@ -0,0 +1,46 @@
1
+ from typing import Any, Callable, Dict, List, Optional, Literal
2
+ from pydantic import Field, ConfigDict
3
+ import re
4
+ from swarmauri.chains.concrete.ChainStep import ChainStep
5
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
6
+ from swarmauri_core.chains.IChainContext import IChainContext
7
+
8
+ class ChainContextBase(IChainContext, ComponentBase):
9
+ steps: List[ChainStep] = []
10
+ context: Dict = {}
11
+ resource: Optional[str] = Field(default=ResourceTypes.CHAIN.value)
12
+ model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
13
+ type: Literal['ChainContextBase'] = 'ChainContextBase'
14
+
15
+ def update(self, **kwargs):
16
+ self.context.update(kwargs)
17
+
18
+ def get_value(self, key: str) -> Any:
19
+ return self.context.get(key)
20
+
21
+ def _resolve_fstring(self, template: str) -> str:
22
+ pattern = re.compile(r'{([^}]+)}')
23
+ def replacer(match):
24
+ expression = match.group(1)
25
+ try:
26
+ return str(eval(expression, {}, self.context))
27
+ except Exception as e:
28
+ print(f"Failed to resolve expression: {expression}. Error: {e}")
29
+ return f"{{{expression}}}"
30
+ return pattern.sub(replacer, template)
31
+
32
+ def _resolve_placeholders(self, value: Any) -> Any:
33
+ if isinstance(value, str):
34
+ return self._resolve_fstring(value)
35
+ elif isinstance(value, dict):
36
+ return {k: self._resolve_placeholders(v) for k, v in value.items()}
37
+ elif isinstance(value, list):
38
+ return [self._resolve_placeholders(v) for v in value]
39
+ else:
40
+ return value
41
+
42
+ def _resolve_ref(self, value: Any) -> Any:
43
+ if isinstance(value, str) and value.startswith('$'):
44
+ placeholder = value[1:]
45
+ return placeholder
46
+ return value
@@ -0,0 +1,18 @@
1
+ from typing import Any, Tuple, Dict, Optional, Union, Literal
2
+ from pydantic import Field, ConfigDict
3
+ from swarmauri_core.typing import SubclassUnion
4
+ from swarmauri.tools.base.ToolBase import ToolBase
5
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
6
+ from swarmauri_core.chains.IChainStep import IChainStep
7
+
8
+ class ChainStepBase(IChainStep, ComponentBase):
9
+ """
10
+ Represents a single step within an execution chain.
11
+ """
12
+ key: str
13
+ method: SubclassUnion[ToolBase]
14
+ args: Tuple = Field(default_factory=tuple)
15
+ kwargs: Dict[str, Any] = Field(default_factory=dict)
16
+ ref: Optional[str] = Field(default=None)
17
+ resource: Optional[str] = Field(default=ResourceTypes.CHAINSTEP.value)
18
+ type: Literal['ChainStepBase'] = 'ChainStepBase'
@@ -0,0 +1,154 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import List, Dict, Any, Optional, Literal
3
+ from pydantic import Field
4
+ from collections import defaultdict, deque
5
+ import re
6
+ import numpy as np
7
+
8
+
9
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
10
+ from swarmauri.chains.concrete.ChainStep import ChainStep
11
+ from swarmauri.chains.base.ChainContextBase import ChainContextBase
12
+ from swarmauri.prompts.concrete.PromptMatrix import PromptMatrix
13
+ from swarmauri_core.typing import SubclassUnion
14
+ from swarmauri.agents.base.AgentBase import AgentBase
15
+ from swarmauri_core.prompts.IPromptMatrix import IPromptMatrix
16
+ from swarmauri_core.chains.IChainDependencyResolver import IChainDependencyResolver
17
+
18
+ class PromptContextChainBase(IChainDependencyResolver, ChainContextBase, ComponentBase):
19
+ prompt_matrix: PromptMatrix
20
+ agents: List[SubclassUnion[AgentBase]] = Field(default_factory=list)
21
+ context: Dict[str, Any] = Field(default_factory=dict)
22
+ llm_kwargs: Dict[str, Any] = Field(default_factory=dict)
23
+ response_matrix: Optional[PromptMatrix] = None
24
+ current_step_index: int = 0
25
+ steps: List[Any] = Field(default_factory=list)
26
+ resource: Optional[str] = Field(default=ResourceTypes.CHAIN.value)
27
+ type: Literal['PromptContextChainBase'] = 'PromptContextChainBase'
28
+
29
+ def __init__(self, **data: Any):
30
+ super().__init__(**data)
31
+ # Now that the instance is created, we can safely access `prompt_matrix.shape`
32
+ self.response_matrix = PromptMatrix(matrix=[[None for _ in range(self.prompt_matrix.shape[1])]
33
+ for _ in range(self.prompt_matrix.shape[0])])
34
+
35
+ def execute(self, build_dependencies=True) -> None:
36
+ """
37
+ Execute the chain of prompts based on the state of the prompt matrix.
38
+ Iterates through each sequence in the prompt matrix, resolves dependencies,
39
+ and executes prompts in the resolved order.
40
+ """
41
+ if build_dependencies:
42
+ self.steps = self.build_dependencies()
43
+ self.current_step_index = 0
44
+
45
+ while self.current_step_index < len(self.steps):
46
+ step = self.steps[self.current_step_index]
47
+ method = step.method
48
+ args = step.args
49
+ ref = step.ref
50
+ result = method(*args)
51
+ self.context[ref] = result
52
+ prompt_index = self._extract_step_number(ref)
53
+ self._update_response_matrix(args[0], prompt_index, result)
54
+ self.current_step_index += 1 # Move to the next step
55
+ else:
56
+ print("All steps have been executed.")
57
+
58
+ def execute_next_step(self):
59
+ """
60
+ Execute the next step in the steps list if available.
61
+ """
62
+ if self.current_step_index < len(self.steps):
63
+ step = self.steps[self.current_step_index]
64
+ method = step.method
65
+ args = step.args
66
+ ref = step.ref
67
+ result = method(*args)
68
+ self.context[ref] = result
69
+ prompt_index = self._extract_step_number(ref)
70
+ self._update_response_matrix(args[0], prompt_index, result)
71
+ self.current_step_index += 1 # Move to the next step
72
+ else:
73
+ print("All steps have been executed.")
74
+
75
+ def _execute_prompt(self, agent_index: int, prompt: str, ref: str):
76
+ """
77
+ Executes a given prompt using the specified agent and updates the response.
78
+ """
79
+ formatted_prompt = prompt.format(**self.context) # Using context for f-string formatting
80
+
81
+ agent = self.agents[agent_index]
82
+ # get the unformatted version
83
+ unformatted_system_context = agent.system_context
84
+ # use the formatted version
85
+ agent.system_context = agent.system_context.content.format(**self.context)
86
+ response = agent.exec(formatted_prompt, model_kwargs=self.model_kwargs)
87
+ # reset back to the unformatted version
88
+ agent.system_context = unformatted_system_context
89
+
90
+ self.context[ref] = response
91
+ prompt_index = self._extract_step_number(ref)
92
+ self._update_response_matrix(agent_index, prompt_index, response)
93
+ return response
94
+
95
+ def _update_response_matrix(self, agent_index: int, prompt_index: int, response: Any):
96
+ self.response_matrix.matrix[agent_index][prompt_index] = response
97
+
98
+
99
+ def _extract_agent_number(self, text):
100
+ # Regular expression to match the pattern and capture the agent number
101
+ match = re.search(r'\{Agent_(\d+)_Step_\d+_response\}', text)
102
+ if match:
103
+ # Return the captured group, which is the agent number
104
+ return int(match.group(1))
105
+ else:
106
+ # Return None if no match is found
107
+ return None
108
+
109
+ def _extract_step_number(self, ref):
110
+ # This regex looks for the pattern '_Step_' followed by one or more digits.
111
+ match = re.search(r"_Step_(\d+)_", ref)
112
+ if match:
113
+ return int(match.group(1)) # Convert the extracted digits to an integer
114
+ else:
115
+ return None # If no match is found, return None
116
+
117
+ def build_dependencies(self) -> List[ChainStep]:
118
+ """
119
+ Build the chain steps in the correct order by resolving dependencies first.
120
+ """
121
+ steps = []
122
+
123
+ for i in range(self.prompt_matrix.shape[1]):
124
+ try:
125
+ sequence = np.array(self.prompt_matrix.matrix)[:,i].tolist()
126
+ execution_order = self.resolve_dependencies(sequence=sequence)
127
+ for j in execution_order:
128
+ prompt = sequence[j]
129
+ if prompt:
130
+ ref = f"Agent_{j}_Step_{i}_response" # Using a unique reference string
131
+ step = ChainStep(
132
+ key=f"Agent_{j}_Step_{i}",
133
+ method=self._execute_prompt,
134
+ args=[j, prompt, ref],
135
+ ref=ref
136
+ )
137
+ steps.append(step)
138
+ except Exception as e:
139
+ print(str(e))
140
+ return steps
141
+
142
+ def resolve_dependencies(self, sequence: List[Optional[str]]) -> List[int]:
143
+ """
144
+ Resolve dependencies within a specific sequence of the prompt matrix.
145
+
146
+ Args:
147
+ matrix (List[List[Optional[str]]]): The prompt matrix.
148
+ sequence_index (int): The index of the sequence to resolve dependencies for.
149
+
150
+ Returns:
151
+ List[int]: The execution order of the agents for the given sequence.
152
+ """
153
+
154
+ return [x for x in range(0, len(sequence), 1)]
@@ -0,0 +1 @@
1
+ #
@@ -0,0 +1,19 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Optional, Union, List, Any, Literal
3
+ from pydantic import Field
4
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
5
+
6
+ class ChunkerBase(ComponentBase, ABC):
7
+ """
8
+ Interface for chunking text into smaller pieces.
9
+
10
+ This interface defines abstract methods for chunking texts. Implementing classes
11
+ should provide concrete implementations for these methods tailored to their specific
12
+ chunking algorithms.
13
+ """
14
+ resource: Optional[str] = Field(default=ResourceTypes.CHUNKER.value)
15
+ type: Literal['ChunkerBase'] = 'ChunkerBase'
16
+
17
+ @abstractmethod
18
+ def chunk_text(self, text: Union[str, Any], *args, **kwargs) -> List[Any]:
19
+ pass
File without changes
@@ -0,0 +1,99 @@
1
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
2
+ from swarmauri_core.control_panels.IControlPanel import IControlPlane
3
+ from typing import Any, List, Literal
4
+ from pydantic import Field, ConfigDict
5
+ from swarmauri.service_registries.base.ServiceRegistryBase import ServiceRegistryBase
6
+ from swarmauri.factories.base.FactoryBase import FactoryBase
7
+ from swarmauri.task_mgt_strategies.base.TaskMgtStrategyBase import TaskMgtStrategyBase
8
+ from swarmauri.transports.base.TransportBase import TransportBase
9
+ from swarmauri_core.typing import SubclassUnion
10
+ import logging
11
+
12
+
13
+ class ControlPanelBase(IControlPlane, ComponentBase):
14
+ """
15
+ Implementation of the ControlPlane abstract class.
16
+ This class orchestrates agents, manages tasks, and ensures task distribution
17
+ and transport between agents and services.
18
+ """
19
+
20
+ resource: ResourceTypes = Field(default=ResourceTypes.CONTROL_PANEL.value)
21
+ model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
22
+ type: Literal["ControlPanelBase"] = "ControlPanelBase"
23
+
24
+ agent_factory: SubclassUnion[FactoryBase]
25
+ service_registry: SubclassUnion[ServiceRegistryBase]
26
+ task_mgt_strategy: SubclassUnion[TaskMgtStrategyBase]
27
+ transport: SubclassUnion[TransportBase]
28
+
29
+ # Agent management methods
30
+ def create_agent(self, name: str, role: str) -> Any:
31
+ """
32
+ Create an agent with the given name and role, and register it in the service registry.
33
+ """
34
+ agent = self.agent_factory.create_agent(name, role)
35
+ self.service_registry.register_service(name, {"role": role, "status": "active"})
36
+ logging.info(f"Agent '{name}' with role '{role}' created and registered.")
37
+ return agent
38
+
39
+ def remove_agent(self, name: str) -> None:
40
+ """
41
+ Remove the agent with the specified name and unregister it from the service registry.
42
+ """
43
+ agent = self.agent_factory.get_agent_by_name(name)
44
+ if not agent:
45
+ raise ValueError(f"Agent '{name}' not found.")
46
+ self.service_registry.unregister_service(name)
47
+ self.agent_factory.delete_agent(name)
48
+ logging.info(f"Agent '{name}' removed and unregistered.")
49
+
50
+ def list_active_agents(self) -> List[str]:
51
+ """
52
+ List all active agent names.
53
+ """
54
+ agents = self.agent_factory.get_agents()
55
+ active_agents = [agent.name for agent in agents if agent]
56
+ logging.info(f"Active agents listed: {active_agents}")
57
+ return active_agents
58
+
59
+ # Task management methods
60
+ def submit_tasks(self, tasks: List[Any]) -> None:
61
+ """
62
+ Submit one or more tasks to the task management strategy for processing.
63
+ """
64
+ for task in tasks:
65
+ self.task_mgt_strategy.add_task(task)
66
+ logging.info(
67
+ f"Task '{task.get('task_id', 'unknown')}' submitted to the strategy."
68
+ )
69
+
70
+ def process_tasks(self) -> None:
71
+ """
72
+ Process and assign tasks from the queue, then transport them to their assigned services.
73
+ """
74
+ try:
75
+ self.task_mgt_strategy.process_tasks(
76
+ self.service_registry.get_services, self.transport
77
+ )
78
+ logging.info("Tasks processed and transported successfully.")
79
+ except Exception as e:
80
+ logging.error(f"Error while processing tasks: {e}")
81
+ raise ValueError(f"Error processing tasks: {e}")
82
+
83
+ def distribute_tasks(self, task: Any) -> None:
84
+ """
85
+ Distribute tasks using the task strategy (manual or on-demand assignment).
86
+ """
87
+ self.task_mgt_strategy.assign_task(task, self.service_registry.get_services)
88
+ logging.info(
89
+ f"Task '{task.get('task_id', 'unknown')}' distributed to a service."
90
+ )
91
+
92
+ # Orchestration method
93
+ def orchestrate_agents(self, tasks: List[Any]) -> None:
94
+ """
95
+ Orchestrate agents for task distribution and transportation.
96
+ """
97
+ self.submit_tasks(tasks) # Add task to the strategy
98
+ self.process_tasks() # Process and transport the task
99
+ logging.info("Agents orchestrated successfully.")
File without changes
@@ -0,0 +1,50 @@
1
+ from typing import List, Union, Literal
2
+ from pydantic import Field, PrivateAttr, ConfigDict
3
+ from swarmauri_core.typing import SubclassUnion
4
+ from swarmauri.messages.base.MessageBase import MessageBase
5
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
6
+ from swarmauri_core.conversations.IConversation import IConversation
7
+
8
+
9
+ class ConversationBase(IConversation, ComponentBase):
10
+ """
11
+ Concrete implementation of IConversation, managing conversation history and operations.
12
+ """
13
+
14
+ _history: List[SubclassUnion[MessageBase]] = PrivateAttr(default_factory=list)
15
+ resource: ResourceTypes = Field(default=ResourceTypes.CONVERSATION.value)
16
+ model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
17
+ type: Literal["ConversationBase"] = "ConversationBase"
18
+
19
+ @property
20
+ def history(self) -> List[SubclassUnion[MessageBase]]:
21
+ """
22
+ Provides read-only access to the conversation history.
23
+ """
24
+ return self._history
25
+
26
+ def add_message(self, message: SubclassUnion[MessageBase]):
27
+ self._history.append(message)
28
+
29
+ def remove_message(self, message: SubclassUnion[MessageBase]):
30
+ """
31
+ Remove a message from the history
32
+
33
+ @param message: Message to remove from the history
34
+ @return None
35
+ """
36
+ if self._history and message in self._history:
37
+ self._history.remove(message)
38
+ return None
39
+
40
+ def add_messages(self, messages: List[SubclassUnion[MessageBase]]):
41
+ for message in messages:
42
+ self._history.append(message)
43
+
44
+ def get_last(self) -> Union[SubclassUnion[MessageBase], None]:
45
+ if self._history:
46
+ return self._history[-1]
47
+ return None
48
+
49
+ def clear_history(self):
50
+ self._history.clear()
@@ -0,0 +1,8 @@
1
+ from abc import ABC
2
+ from typing import Optional, Literal
3
+ from pydantic import BaseModel
4
+ from swarmauri_core.conversations.ISystemContext import ISystemContext
5
+ from swarmauri.messages.concrete.SystemMessage import SystemMessage
6
+
7
+ class ConversationSystemContextMixin(ISystemContext, BaseModel):
8
+ system_context: Optional[SystemMessage]
File without changes
@@ -0,0 +1,79 @@
1
+ from swarmauri_core.dataconnectors.IDataConnector import IDataConnector
2
+
3
+
4
+ class DataConnectorBase(IDataConnector):
5
+ """
6
+ Base implementation of IDataConnector that raises NotImplementedError
7
+ for all abstract methods, ensuring explicit implementation in child classes.
8
+ """
9
+
10
+ def authenticate(self, **kwargs):
11
+ """
12
+ Raises NotImplementedError to enforce implementation in child classes.
13
+
14
+ :param kwargs: Authentication parameters
15
+ :raises NotImplementedError: Always raised to require specific implementation
16
+ """
17
+ raise NotImplementedError(
18
+ "Authenticate method must be implemented by child classes."
19
+ )
20
+
21
+ def fetch_data(self, query: str, **kwargs):
22
+ """
23
+ Raises NotImplementedError to enforce implementation in child classes.
24
+
25
+ :param query: Query string or parameters
26
+ :param kwargs: Additional parameters
27
+ :raises NotImplementedError: Always raised to require specific implementation
28
+ """
29
+ raise NotImplementedError(
30
+ "Fetch data method must be implemented by child classes."
31
+ )
32
+
33
+ def insert_data(self, data, **kwargs):
34
+ """
35
+ Raises NotImplementedError to enforce implementation in child classes.
36
+
37
+ :param data: Data to be inserted
38
+ :param kwargs: Additional parameters
39
+ :raises NotImplementedError: Always raised to require specific implementation
40
+ """
41
+ raise NotImplementedError(
42
+ "Insert data method must be implemented by child classes."
43
+ )
44
+
45
+ def update_data(self, identifier, data, **kwargs):
46
+ """
47
+ Raises NotImplementedError to enforce implementation in child classes.
48
+
49
+ :param identifier: Unique identifier of the data to update
50
+ :param data: Updated data
51
+ :param kwargs: Additional parameters
52
+ :raises NotImplementedError: Always raised to require specific implementation
53
+ """
54
+ raise NotImplementedError(
55
+ "Update data method must be implemented by child classes."
56
+ )
57
+
58
+ def delete_data(self, identifier, **kwargs):
59
+ """
60
+ Raises NotImplementedError to enforce implementation in child classes.
61
+
62
+ :param identifier: Unique identifier of the data to delete
63
+ :param kwargs: Additional parameters
64
+ :raises NotImplementedError: Always raised to require specific implementation
65
+ """
66
+ raise NotImplementedError(
67
+ "Delete data method must be implemented by child classes."
68
+ )
69
+
70
+ def test_connection(self, **kwargs):
71
+ """
72
+ Raises NotImplementedError to enforce implementation in child classes.
73
+
74
+ :param kwargs: Connection parameters
75
+ :raises NotImplementedError: Always raised to require specific implementation
76
+ """
77
+ raise NotImplementedError(
78
+ "Test connection method must be implemented by child classes."
79
+ )
File without changes
@@ -0,0 +1,35 @@
1
+ from abc import abstractmethod
2
+ from numpy.linalg import norm
3
+ from typing import List, Optional, Literal
4
+ from pydantic import Field
5
+ from swarmauri_core.distances.IDistanceSimilarity import IDistanceSimilarity
6
+ from swarmauri.vectors.concrete.Vector import Vector
7
+ from swarmauri.vectors.concrete.VectorProductMixin import VectorProductMixin
8
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
9
+
10
+ class DistanceBase(IDistanceSimilarity, VectorProductMixin, ComponentBase):
11
+ """
12
+ Implements cosine distance calculation as an IDistanceSimiliarity interface.
13
+ Cosine distance measures the cosine of the angle between two non-zero vectors
14
+ of an inner product space, capturing the orientation rather than the magnitude
15
+ of these vectors.
16
+ """
17
+ resource: Optional[str] = Field(default=ResourceTypes.DISTANCE.value, frozen=True)
18
+ type: Literal['DistanceBase'] = 'DistanceBase'
19
+ @abstractmethod
20
+ def distance(self, vector_a: Vector, vector_b: Vector) -> float:
21
+ pass
22
+
23
+ @abstractmethod
24
+ def similarity(self, vector_a: Vector, vector_b: Vector) -> float:
25
+ pass
26
+
27
+
28
+ @abstractmethod
29
+ def distances(self, vector_a: Vector, vectors_b: List[Vector]) -> List[float]:
30
+ pass
31
+
32
+ @abstractmethod
33
+ def similarities(self, vector_a: Vector, vectors_b: List[Vector]) -> List[float]:
34
+ pass
35
+
@@ -0,0 +1,7 @@
1
+ from typing import Optional, Literal
2
+ from pydantic import Field
3
+ from swarmauri_core.ComponentBase import ComponentBase, ResourceTypes
4
+
5
+ class VisionDistanceBase(ComponentBase):
6
+ resource: Optional[str] = Field(default=ResourceTypes.DISTANCE.value, frozen=True)
7
+ type: Literal['VisionDistanceBase'] = 'VisionDistanceBase'
File without changes