swarmauri-standard 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 (211) hide show
  1. swarmauri_standard/README.md +37 -0
  2. swarmauri_standard/__init__.py +37 -0
  3. swarmauri_standard/__version__.py +1 -0
  4. swarmauri_standard/agents/QAAgent.py +19 -0
  5. swarmauri_standard/agents/RagAgent.py +99 -0
  6. swarmauri_standard/agents/SimpleConversationAgent.py +28 -0
  7. swarmauri_standard/agents/ToolAgent.py +47 -0
  8. swarmauri_standard/agents/__init__.py +16 -0
  9. swarmauri_standard/chains/CallableChain.py +29 -0
  10. swarmauri_standard/chains/ChainStep.py +8 -0
  11. swarmauri_standard/chains/ContextChain.py +48 -0
  12. swarmauri_standard/chains/PromptContextChain.py +5 -0
  13. swarmauri_standard/chains/__init__.py +15 -0
  14. swarmauri_standard/chunkers/DelimiterBasedChunker.py +35 -0
  15. swarmauri_standard/chunkers/FixedLengthChunker.py +32 -0
  16. swarmauri_standard/chunkers/MdSnippetChunker.py +44 -0
  17. swarmauri_standard/chunkers/SentenceChunker.py +31 -0
  18. swarmauri_standard/chunkers/SlidingWindowChunker.py +35 -0
  19. swarmauri_standard/chunkers/__init__.py +17 -0
  20. swarmauri_standard/control_panels/ControlPanel.py +10 -0
  21. swarmauri_standard/control_panels/__init__.py +13 -0
  22. swarmauri_standard/conversations/Conversation.py +8 -0
  23. swarmauri_standard/conversations/MaxSizeConversation.py +25 -0
  24. swarmauri_standard/conversations/MaxSystemContextConversation.py +83 -0
  25. swarmauri_standard/conversations/SessionCacheConversation.py +81 -0
  26. swarmauri_standard/conversations/__init__.py +22 -0
  27. swarmauri_standard/dataconnectors/GoogleDriveDataConnector.py +341 -0
  28. swarmauri_standard/dataconnectors/__init__.py +16 -0
  29. swarmauri_standard/distances/CanberraDistance.py +68 -0
  30. swarmauri_standard/distances/ChebyshevDistance.py +48 -0
  31. swarmauri_standard/distances/ChiSquaredDistance.py +39 -0
  32. swarmauri_standard/distances/CosineDistance.py +61 -0
  33. swarmauri_standard/distances/EuclideanDistance.py +50 -0
  34. swarmauri_standard/distances/HaversineDistance.py +50 -0
  35. swarmauri_standard/distances/JaccardIndexDistance.py +73 -0
  36. swarmauri_standard/distances/LevenshteinDistance.py +75 -0
  37. swarmauri_standard/distances/ManhattanDistance.py +49 -0
  38. swarmauri_standard/distances/MinkowskiDistance.py +64 -0
  39. swarmauri_standard/distances/SorensenDiceDistance.py +51 -0
  40. swarmauri_standard/distances/SquaredEuclideanDistance.py +47 -0
  41. swarmauri_standard/distances/__init__.py +27 -0
  42. swarmauri_standard/documents/Document.py +5 -0
  43. swarmauri_standard/documents/__init__.py +11 -0
  44. swarmauri_standard/embeddings/CohereEmbedding.py +207 -0
  45. swarmauri_standard/embeddings/GeminiEmbedding.py +170 -0
  46. swarmauri_standard/embeddings/MistralEmbedding.py +134 -0
  47. swarmauri_standard/embeddings/NmfEmbedding.py +106 -0
  48. swarmauri_standard/embeddings/OpenAIEmbedding.py +141 -0
  49. swarmauri_standard/embeddings/TfidfEmbedding.py +52 -0
  50. swarmauri_standard/embeddings/VoyageEmbedding.py +115 -0
  51. swarmauri_standard/embeddings/__init__.py +19 -0
  52. swarmauri_standard/exceptions/IndexErrorWithContext.py +21 -0
  53. swarmauri_standard/exceptions/__init__.py +13 -0
  54. swarmauri_standard/factories/AgentFactory.py +35 -0
  55. swarmauri_standard/factories/Factory.py +42 -0
  56. swarmauri_standard/factories/__init__.py +14 -0
  57. swarmauri_standard/image_gens/BlackForestImgGenModel.py +259 -0
  58. swarmauri_standard/image_gens/DeepInfraImgGenModel.py +195 -0
  59. swarmauri_standard/image_gens/FalAIImgGenModel.py +322 -0
  60. swarmauri_standard/image_gens/HyperbolicImgGenModel.py +210 -0
  61. swarmauri_standard/image_gens/OpenAIImgGenModel.py +192 -0
  62. swarmauri_standard/image_gens/__init__.py +0 -0
  63. swarmauri_standard/llms/AI21StudioModel.py +411 -0
  64. swarmauri_standard/llms/AnthropicModel.py +426 -0
  65. swarmauri_standard/llms/AnthropicToolModel.py +444 -0
  66. swarmauri_standard/llms/CohereModel.py +440 -0
  67. swarmauri_standard/llms/CohereToolModel.py +601 -0
  68. swarmauri_standard/llms/DeepInfraModel.py +407 -0
  69. swarmauri_standard/llms/DeepSeekModel.py +355 -0
  70. swarmauri_standard/llms/FalAIVisionModel.py +243 -0
  71. swarmauri_standard/llms/GeminiProModel.py +452 -0
  72. swarmauri_standard/llms/GeminiToolModel.py +582 -0
  73. swarmauri_standard/llms/GroqAIAudio.py +200 -0
  74. swarmauri_standard/llms/GroqModel.py +405 -0
  75. swarmauri_standard/llms/GroqToolModel.py +471 -0
  76. swarmauri_standard/llms/GroqVisionModel.py +387 -0
  77. swarmauri_standard/llms/HyperbolicAudioTTS.py +146 -0
  78. swarmauri_standard/llms/HyperbolicModel.py +427 -0
  79. swarmauri_standard/llms/HyperbolicVisionModel.py +381 -0
  80. swarmauri_standard/llms/MistralModel.py +432 -0
  81. swarmauri_standard/llms/MistralToolModel.py +517 -0
  82. swarmauri_standard/llms/OpenAIAudio.py +192 -0
  83. swarmauri_standard/llms/OpenAIAudioTTS.py +224 -0
  84. swarmauri_standard/llms/OpenAIModel.py +468 -0
  85. swarmauri_standard/llms/OpenAIToolModel.py +444 -0
  86. swarmauri_standard/llms/PerplexityModel.py +492 -0
  87. swarmauri_standard/llms/PlayHTModel.py +352 -0
  88. swarmauri_standard/llms/WhisperLargeModel.py +217 -0
  89. swarmauri_standard/llms/__init__.py +43 -0
  90. swarmauri_standard/measurements/CompletenessMeasurement.py +79 -0
  91. swarmauri_standard/measurements/DistinctivenessMeasurement.py +98 -0
  92. swarmauri_standard/measurements/FirstImpressionMeasurement.py +16 -0
  93. swarmauri_standard/measurements/MeanMeasurement.py +42 -0
  94. swarmauri_standard/measurements/MiscMeasurement.py +176 -0
  95. swarmauri_standard/measurements/MissingnessMeasurement.py +120 -0
  96. swarmauri_standard/measurements/PatternMatchingMeasurement.py +31 -0
  97. swarmauri_standard/measurements/RatioOfSumsMeasurement.py +35 -0
  98. swarmauri_standard/measurements/StaticMeasurement.py +17 -0
  99. swarmauri_standard/measurements/UniquenessMeasurement.py +96 -0
  100. swarmauri_standard/measurements/ZeroMeasurement.py +17 -0
  101. swarmauri_standard/measurements/__init__.py +41 -0
  102. swarmauri_standard/messages/AgentMessage.py +25 -0
  103. swarmauri_standard/messages/FunctionMessage.py +14 -0
  104. swarmauri_standard/messages/HumanMessage.py +40 -0
  105. swarmauri_standard/messages/SystemMessage.py +8 -0
  106. swarmauri_standard/messages/__init__.py +16 -0
  107. swarmauri_standard/parsers/BeautifulSoupElementParser.py +42 -0
  108. swarmauri_standard/parsers/CSVParser.py +46 -0
  109. swarmauri_standard/parsers/HTMLTagStripParser.py +38 -0
  110. swarmauri_standard/parsers/KeywordExtractorParser.py +47 -0
  111. swarmauri_standard/parsers/Md2HtmlParser.py +37 -0
  112. swarmauri_standard/parsers/OpenAPISpecParser.py +44 -0
  113. swarmauri_standard/parsers/PhoneNumberExtractorParser.py +34 -0
  114. swarmauri_standard/parsers/PythonParser.py +54 -0
  115. swarmauri_standard/parsers/RegExParser.py +35 -0
  116. swarmauri_standard/parsers/URLExtractorParser.py +39 -0
  117. swarmauri_standard/parsers/XMLParser.py +42 -0
  118. swarmauri_standard/parsers/__init__.py +29 -0
  119. swarmauri_standard/pipelines/Pipeline.py +50 -0
  120. swarmauri_standard/pipelines/__init__.py +13 -0
  121. swarmauri_standard/prompts/Prompt.py +5 -0
  122. swarmauri_standard/prompts/PromptGenerator.py +5 -0
  123. swarmauri_standard/prompts/PromptMatrix.py +5 -0
  124. swarmauri_standard/prompts/PromptTemplate.py +5 -0
  125. swarmauri_standard/prompts/__init__.py +16 -0
  126. swarmauri_standard/schema_converters/AnthropicSchemaConverter.py +29 -0
  127. swarmauri_standard/schema_converters/CohereSchemaConverter.py +33 -0
  128. swarmauri_standard/schema_converters/GeminiSchemaConverter.py +72 -0
  129. swarmauri_standard/schema_converters/GroqSchemaConverter.py +38 -0
  130. swarmauri_standard/schema_converters/MistralSchemaConverter.py +35 -0
  131. swarmauri_standard/schema_converters/OpenAISchemaConverter.py +35 -0
  132. swarmauri_standard/schema_converters/ShuttleAISchemaConverter.py +35 -0
  133. swarmauri_standard/schema_converters/__init__.py +37 -0
  134. swarmauri_standard/service_registries/ServiceRegistry.py +10 -0
  135. swarmauri_standard/service_registries/__init__.py +16 -0
  136. swarmauri_standard/state/DictState.py +50 -0
  137. swarmauri_standard/state/__init__.py +13 -0
  138. swarmauri_standard/swarms/Swarm.py +36 -0
  139. swarmauri_standard/swarms/__init__.py +13 -0
  140. swarmauri_standard/task_mgt_strategies/RoundRobinStrategy.py +73 -0
  141. swarmauri_standard/task_mgt_strategies/__init__.py +13 -0
  142. swarmauri_standard/toolkits/AccessibilityToolkit.py +47 -0
  143. swarmauri_standard/toolkits/Toolkit.py +5 -0
  144. swarmauri_standard/toolkits/__init__.py +14 -0
  145. swarmauri_standard/tools/AdditionTool.py +39 -0
  146. swarmauri_standard/tools/AutomatedReadabilityIndexTool.py +123 -0
  147. swarmauri_standard/tools/CalculatorTool.py +56 -0
  148. swarmauri_standard/tools/CodeExtractorTool.py +140 -0
  149. swarmauri_standard/tools/CodeInterpreterTool.py +69 -0
  150. swarmauri_standard/tools/ColemanLiauIndexTool.py +125 -0
  151. swarmauri_standard/tools/FleschKincaidTool.py +172 -0
  152. swarmauri_standard/tools/FleschReadingEaseTool.py +103 -0
  153. swarmauri_standard/tools/GunningFogTool.py +152 -0
  154. swarmauri_standard/tools/ImportMemoryModuleTool.py +96 -0
  155. swarmauri_standard/tools/JSONRequestsTool.py +190 -0
  156. swarmauri_standard/tools/MatplotlibCsvTool.py +84 -0
  157. swarmauri_standard/tools/MatplotlibTool.py +121 -0
  158. swarmauri_standard/tools/Parameter.py +10 -0
  159. swarmauri_standard/tools/RequestsTool.py +182 -0
  160. swarmauri_standard/tools/SentenceComplexityTool.py +84 -0
  161. swarmauri_standard/tools/TemperatureConverterTool.py +70 -0
  162. swarmauri_standard/tools/TestTool.py +34 -0
  163. swarmauri_standard/tools/WeatherTool.py +38 -0
  164. swarmauri_standard/tools/__init__.py +35 -0
  165. swarmauri_standard/tracing/CallableTracer.py +32 -0
  166. swarmauri_standard/tracing/ChainTracer.py +51 -0
  167. swarmauri_standard/tracing/SimpleTraceContext.py +21 -0
  168. swarmauri_standard/tracing/SimpleTracer.py +40 -0
  169. swarmauri_standard/tracing/TracedVariable.py +28 -0
  170. swarmauri_standard/tracing/VariableTracer.py +23 -0
  171. swarmauri_standard/tracing/__init__.py +17 -0
  172. swarmauri_standard/transports/PubSubTransport.py +118 -0
  173. swarmauri_standard/transports/__init__.py +13 -0
  174. swarmauri_standard/utils/LazyLoader.py +37 -0
  175. swarmauri_standard/utils/__init__.py +0 -0
  176. swarmauri_standard/utils/_get_subclasses.py +72 -0
  177. swarmauri_standard/utils/_lazy_import.py +22 -0
  178. swarmauri_standard/utils/apply_metaclass.py +4 -0
  179. swarmauri_standard/utils/base64_encoder.py +17 -0
  180. swarmauri_standard/utils/base64_to_file_path.py +9 -0
  181. swarmauri_standard/utils/base64_to_img_url.py +44 -0
  182. swarmauri_standard/utils/base64_to_in_memory_img.py +9 -0
  183. swarmauri_standard/utils/decorate.py +24 -0
  184. swarmauri_standard/utils/duration_manager.py +13 -0
  185. swarmauri_standard/utils/file_path_to_base64.py +10 -0
  186. swarmauri_standard/utils/file_path_to_img_url.py +45 -0
  187. swarmauri_standard/utils/file_path_to_in_memory_img.py +6 -0
  188. swarmauri_standard/utils/get_class_hash.py +35 -0
  189. swarmauri_standard/utils/img_url_to_base64.py +12 -0
  190. swarmauri_standard/utils/img_url_to_file_path.py +8 -0
  191. swarmauri_standard/utils/img_url_to_in_memory_img.py +9 -0
  192. swarmauri_standard/utils/in_memory_img_to_base64.py +9 -0
  193. swarmauri_standard/utils/in_memory_img_to_file_path.py +4 -0
  194. swarmauri_standard/utils/in_memory_img_to_img_url.py +50 -0
  195. swarmauri_standard/utils/json_validator.py +17 -0
  196. swarmauri_standard/utils/load_documents_from_folder.py +58 -0
  197. swarmauri_standard/utils/load_documents_from_json.py +28 -0
  198. swarmauri_standard/utils/memoize.py +16 -0
  199. swarmauri_standard/utils/method_signature_extractor_decorator.py +113 -0
  200. swarmauri_standard/utils/print_notebook_metadata.py +82 -0
  201. swarmauri_standard/utils/retry_decorator.py +94 -0
  202. swarmauri_standard/utils/sql_log.py +76 -0
  203. swarmauri_standard/utils/timeout_wrapper.py +42 -0
  204. swarmauri_standard/vector_stores/SqliteVectorStore.py +173 -0
  205. swarmauri_standard/vector_stores/TfidfVectorStore.py +74 -0
  206. swarmauri_standard/vector_stores/__init__.py +14 -0
  207. swarmauri_standard/vectors/Vector.py +5 -0
  208. swarmauri_standard/vectors/__init__.py +14 -0
  209. swarmauri_standard-0.6.0.dev4.dist-info/METADATA +80 -0
  210. swarmauri_standard-0.6.0.dev4.dist-info/RECORD +211 -0
  211. swarmauri_standard-0.6.0.dev4.dist-info/WHEEL +4 -0
@@ -0,0 +1,37 @@
1
+ # Standard Library
2
+
3
+
4
+ The Standard Library extends the Core Library with concrete implementations of models, agents, tools, parsers, and more. It aims to provide ready-to-use components that can be easily integrated into machine learning projects.
5
+
6
+ ## Features
7
+
8
+ - **Predefined Models and Agents**: Implements standard models and agents ready for use.
9
+ - **Toolkit**: A collection of tools for various tasks (e.g., weather information, math operations).
10
+ - **Parsers Implementations**: Various parsers for text data, including HTML and CSV parsers.
11
+ - **Conversations and Chunkers**: Manage conversation histories and chunk text data.
12
+ - **Vectorizers**: Transform text data into vector representations.
13
+ - **Document Stores and Vector Stores**: Concrete implementations for storing and retrieving data.
14
+
15
+ ## Getting Started
16
+
17
+ To make the best use of the Standard Library, first ensure that the Core Library is set up in your project as the Standard Library builds upon it.
18
+
19
+ ```python
20
+ # Example usage of a concrete model from the Standard Library
21
+ from swarmauri.standard.models.concrete import OpenAIModel
22
+
23
+ # Initialize the model with necessary configuration
24
+ model = OpenAIModel(api_key="your_api_key_here")
25
+ ```
26
+
27
+ ## Documentation
28
+
29
+ For more detailed guides and API documentation, check the [Docs](/docs) directory within the library. You'll find examples, configuration options, and best practices for utilizing the provided components.
30
+
31
+ ## Contributing
32
+
33
+ Your contributions can help the Standard Library grow! Whether it's adding new tools, improving models, or writing documentation, we appreciate your help. Please send a pull request with your contributions.
34
+
35
+ ## License
36
+
37
+ Please see the `LICENSE` file in the repository for details.
@@ -0,0 +1,37 @@
1
+ __long_desc__ = """
2
+ # Swarmauri Standard SDK
3
+
4
+ The Swarmauri Standard SDK offers a comprehensive suite of tools designed for building distributed, extensible systems using the Swarmauri framework.
5
+
6
+ ## Standard
7
+ - **Base Classes**: Provide a foundation for constructing Swarmauri components, with standardized methods and properties.
8
+ - **Mixins**: Reusable code fragments designed to be integrated into various classes, offering shared functionality across different components.
9
+ - **Concrete Classes**: Ready-to-use, pre-implemented classes that fulfill standard system needs while adhering to Swarmauri principles. **These classes are the first in line for ongoing support and maintenance, ensuring they remain stable, performant, and up to date with future SDK developments.**
10
+
11
+ # Features
12
+
13
+ - **Polymorphism**: Allows for dynamic behavior switching between components, enabling flexible, context-aware system behavior.
14
+ - **Discriminated Unions**: Provides a robust method for handling multiple possible object types in a type-safe manner.
15
+ - **Serialization**: Efficiently encode and decode data for transmission across different environments and system components, with support for both standard and custom serialization formats.
16
+ - **Intensional and Extensional Programming**: Leverages both rule-based (intensional) and set-based (extensional) approaches to building and manipulating complex data structures, offering developers a wide range of tools for system design.
17
+
18
+ ## Use Cases
19
+
20
+ - **Modular Systems**: Develop scalable, pluggable systems that can evolve over time by adding or modifying components without disrupting the entire ecosystem.
21
+ - **Distributed Architectures**: Build systems with distributed nodes that seamlessly communicate using the SDK’s standardized interfaces.
22
+ - **Third-Party Integrations**: Extend the system's capabilities by easily incorporating third-party tools, libraries, and services.
23
+ - **Prototype and Experimentation**: Test cutting-edge ideas using the experimental components in the SDK, while retaining the reliability of core and standard features for production systems.
24
+
25
+ # Future Development
26
+
27
+ The Swarmauri SDK is an evolving platform, and the community is encouraged to contribute to its growth. Upcoming releases will focus on enhancing the framework's modularity, providing more advanced serialization methods, and expanding the community-driven component library.
28
+
29
+ Visit us at: https://swarmauri.com
30
+ Follow us at: https://github.com/swarmauri
31
+ """
32
+ from .__version__ import __version__
33
+
34
+ __all__ = [
35
+ "__version__",
36
+ # other packages you want to expose
37
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.5.2.dev1"
@@ -0,0 +1,19 @@
1
+ from typing import Any, Optional, Dict, Literal
2
+ from swarmauri_base.agents.AgentBase import AgentBase
3
+ from swarmauri.conversations.concrete.MaxSystemContextConversation import MaxSystemContextConversation
4
+ from swarmauri.messages.concrete.HumanMessage import HumanMessage
5
+
6
+
7
+ class QAAgent(AgentBase):
8
+ conversation: MaxSystemContextConversation = MaxSystemContextConversation(max_size=2)
9
+ type: Literal['QAAgent'] = 'QAAgent'
10
+
11
+ def exec(self,
12
+ input_str: Optional[str] = "",
13
+ llm_kwargs: Optional[Dict] = {}
14
+ ) -> Any:
15
+
16
+ self.conversation.add_message(HumanMessage(content=input_str))
17
+ self.llm.predict(conversation=self.conversation, **llm_kwargs)
18
+
19
+ return self.conversation.get_last().content
@@ -0,0 +1,99 @@
1
+ from typing import Any, Optional, Union, Dict, Literal
2
+ from swarmauri_core.messages import IMessage
3
+
4
+ from swarmauri_base.agents.AgentBase import AgentBase
5
+ from swarmauri_base.agents.AgentRetrieveMixin import AgentRetrieveMixin
6
+ from swarmauri_base.agents.AgentConversationMixin import AgentConversationMixin
7
+ from swarmauri_base.agents.AgentVectorStoreMixin import AgentVectorStoreMixin
8
+ from swarmauri_base.agents.AgentSystemContextMixin import AgentSystemContextMixin
9
+
10
+ from swarmauri.messages.concrete import (HumanMessage,
11
+ SystemMessage,
12
+ AgentMessage)
13
+
14
+ from swarmauri_core.typing import SubclassUnion
15
+ from swarmauri_base.llms.LLMBase import LLMBase
16
+ from swarmauri_base.conversations.ConversationBase import ConversationBase
17
+ from swarmauri_base.vector_stores.VectorStoreBase import VectorStoreBase
18
+
19
+ class RagAgent(AgentRetrieveMixin,
20
+ AgentVectorStoreMixin,
21
+ AgentSystemContextMixin,
22
+ AgentConversationMixin,
23
+ AgentBase):
24
+ """
25
+ RagAgent (Retriever-And-Generator Agent) extends DocumentAgentBase,
26
+ specialized in retrieving documents based on input queries and generating responses.
27
+ """
28
+ llm: SubclassUnion[LLMBase]
29
+ conversation: SubclassUnion[ConversationBase]
30
+ vector_store: SubclassUnion[VectorStoreBase]
31
+ system_context: Union[SystemMessage, str]
32
+ type: Literal['RagAgent'] = 'RagAgent'
33
+
34
+ def _create_preamble_context(self):
35
+ substr = self.system_context.content
36
+ substr += '\n\n'
37
+ substr += '\n'.join([doc.content for doc in self.last_retrieved])
38
+ return substr
39
+
40
+ def _create_post_context(self):
41
+ substr = '\n'.join([doc.content for doc in self.last_retrieved])
42
+ substr += '\n\n'
43
+ substr += self.system_context.content
44
+ return substr
45
+
46
+ def exec(self,
47
+ input_data: Optional[Union[str, IMessage]] = "",
48
+ top_k: int = 5,
49
+ preamble: bool = True,
50
+ fixed: bool = False,
51
+ llm_kwargs: Optional[Dict] = {}
52
+ ) -> Any:
53
+ try:
54
+ # Check if the input is a string, then wrap it in a HumanMessage
55
+ if isinstance(input_data, str):
56
+ human_message = HumanMessage(content=input_data)
57
+ elif isinstance(input_data, IMessage):
58
+ human_message = input_data
59
+ else:
60
+ raise TypeError("Input data must be a string or an instance of Message.")
61
+
62
+ # Add the human message to the conversation
63
+ self.conversation.add_message(human_message)
64
+
65
+ # Retrieval and set new substr for system context
66
+ if top_k > 0 and len(self.vector_store.documents) > 0:
67
+ self.last_retrieved = self.vector_store.retrieve(query=input_data, top_k=top_k)
68
+
69
+ if preamble:
70
+ substr = self._create_preamble_context()
71
+ else:
72
+ substr = self._create_post_context()
73
+
74
+ else:
75
+ if fixed:
76
+ if preamble:
77
+ substr = self._create_preamble_context()
78
+ else:
79
+ substr = self._create_post_context()
80
+ else:
81
+ substr = self.system_context.content
82
+ self.last_retrieved = []
83
+
84
+ # Use substr to set system context
85
+ system_context = SystemMessage(content=substr)
86
+ self.conversation.system_context = system_context
87
+
88
+
89
+ # Retrieve the conversation history and predict a response
90
+ if llm_kwargs:
91
+ self.llm.predict(conversation=self.conversation, **llm_kwargs)
92
+ else:
93
+ self.llm.predict(conversation=self.conversation)
94
+
95
+ return self.conversation.get_last().content
96
+
97
+ except Exception as e:
98
+ print(f"RagAgent error: {e}")
99
+ raise e
@@ -0,0 +1,28 @@
1
+ from typing import Any, Optional, Dict, Literal, List, Union
2
+
3
+ from swarmauri_base.agents.AgentBase import AgentBase
4
+ from swarmauri_base.agents.AgentConversationMixin import AgentConversationMixin
5
+ from swarmauri.messages.concrete import HumanMessage
6
+
7
+ from swarmauri_core.typing import SubclassUnion
8
+ from swarmauri_base.conversations.ConversationBase import ConversationBase
9
+
10
+ from swarmauri.messages.concrete.HumanMessage import contentItem
11
+
12
+
13
+ class SimpleConversationAgent(AgentConversationMixin, AgentBase):
14
+ conversation: SubclassUnion[ConversationBase] #
15
+ type: Literal["SimpleConversationAgent"] = "SimpleConversationAgent"
16
+
17
+ def exec(
18
+ self,
19
+ input_data: Optional[Union[str, List[contentItem]]] = "",
20
+ llm_kwargs: Optional[Dict] = {},
21
+ ) -> Any:
22
+
23
+ if input_str:
24
+ human_message = HumanMessage(content=input_str)
25
+ self.conversation.add_message(human_message)
26
+
27
+ self.llm.predict(conversation=self.conversation, **llm_kwargs)
28
+ return self.conversation.get_last().content
@@ -0,0 +1,47 @@
1
+ from pydantic import ConfigDict
2
+ from typing import Any, Optional, Union, Dict, Literal
3
+ import json
4
+ import logging
5
+ from swarmauri_core.messages import IMessage
6
+
7
+ from swarmauri_base.llms.LLMBase import LLMBase
8
+ from swarmauri_base.agents.AgentBase import AgentBase
9
+ from swarmauri_base.agents.AgentConversationMixin import AgentConversationMixin
10
+ from swarmauri_base.agents.AgentToolMixin import AgentToolMixin
11
+ from swarmauri.messages.concrete import HumanMessage, AgentMessage, FunctionMessage
12
+
13
+ from swarmauri_core.typing import SubclassUnion
14
+ from swarmauri_base.toolkits.ToolkitBase import ToolkitBase
15
+ from swarmauri_base.conversations.ConversationBase import ConversationBase
16
+
17
+ class ToolAgent(AgentToolMixin, AgentConversationMixin, AgentBase):
18
+ llm: SubclassUnion[LLMBase]
19
+ toolkit: SubclassUnion[ToolkitBase]
20
+ conversation: SubclassUnion[ConversationBase] # 🚧 Placeholder
21
+ model_config = ConfigDict(extra='forbid', arbitrary_types_allowed=True)
22
+ type: Literal['ToolAgent'] = 'ToolAgent'
23
+
24
+ def exec(self,
25
+ input_data: Optional[Union[str, IMessage]] = "",
26
+ llm_kwargs: Optional[Dict] = {}) -> Any:
27
+
28
+ # Check if the input is a string, then wrap it in a HumanMessage
29
+ if isinstance(input_data, str):
30
+ human_message = HumanMessage(content=input_data)
31
+ elif isinstance(input_data, IMessage):
32
+ human_message = input_data
33
+ else:
34
+ raise TypeError("Input data must be a string or an instance of Message.")
35
+
36
+ # Add the human message to the conversation
37
+ self.conversation.add_message(human_message)
38
+
39
+ #predict a response
40
+ self.conversation = self.llm.predict(
41
+ conversation=self.conversation,
42
+ toolkit=self.toolkit,
43
+ **llm_kwargs)
44
+
45
+ logging.info(self.conversation.get_last().content)
46
+
47
+ return self.conversation.get_last().content
@@ -0,0 +1,16 @@
1
+ from swarmauri.utils._lazy_import import _lazy_import
2
+
3
+ # List of agent names (file names without the ".py" extension) and corresponding class names
4
+ agent_files = [
5
+ ("swarmauri.agents.concrete.QAAgent", "QAAgent"),
6
+ ("swarmauri.agents.concrete.RagAgent", "RagAgent"),
7
+ ("swarmauri.agents.concrete.SimpleConversationAgent", "SimpleConversationAgent"),
8
+ ("swarmauri.agents.concrete.ToolAgent", "ToolAgent"),
9
+ ]
10
+
11
+ # Lazy loading of agent classes, storing them in variables
12
+ for module_name, class_name in agent_files:
13
+ globals()[class_name] = _lazy_import(module_name, class_name)
14
+
15
+ # Adding the lazy-loaded agent classes to __all__
16
+ __all__ = [class_name for _, class_name in agent_files]
@@ -0,0 +1,29 @@
1
+ from typing import Any, Callable, List, Dict, Optional
2
+ from swarmauri_core.chains.ICallableChain import ICallableChain, CallableDefinition
3
+
4
+
5
+ class CallableChain(ICallableChain):
6
+
7
+ def __init__(self, callables: Optional[List[CallableDefinition]] = None):
8
+
9
+ self.callables = callables if callables is not None else []
10
+
11
+ def __call__(self, *initial_args, **initial_kwargs):
12
+ result = None
13
+ for func, args, kwargs in self.callables:
14
+ if result is not None:
15
+ # If there was a previous result, use it as the first argument for the next function
16
+ args = [result] + list(args)
17
+ result = func(*args, **kwargs)
18
+ return result
19
+
20
+ def add_callable(self, func: Callable[[Any], Any], args: List[Any] = None, kwargs: Dict[str, Any] = None) -> None:
21
+ # Add a new callable to the chain
22
+ self.callables.append((func, args or [], kwargs or {}))
23
+
24
+ def __or__(self, other: "CallableChain") -> "CallableChain":
25
+ if not isinstance(other, CallableChain):
26
+ raise TypeError("Operand must be an instance of CallableChain")
27
+
28
+ new_chain = CallableChain(self.callables + other.callables)
29
+ return new_chain
@@ -0,0 +1,8 @@
1
+ from typing import Literal
2
+ from swarmauri_base.chains.ChainStepBase import ChainStepBase
3
+
4
+ class ChainStep(ChainStepBase):
5
+ """
6
+ Represents a single step within an execution chain.
7
+ """
8
+ type: Literal['ChainStep'] = 'ChainStep'
@@ -0,0 +1,48 @@
1
+ from typing import Any, Dict, List, Callable, Optional, Tuple, Union, Literal
2
+ from swarmauri_core.typing import SubclassUnion
3
+ from swarmauri_base.tools.ToolBase import ToolBase
4
+ from swarmauri.chains.concrete.ChainStep import ChainStep
5
+ from swarmauri_base.chains.ChainContextBase import ChainContextBase
6
+ from swarmauri_core.chains.IChain import IChain
7
+
8
+
9
+ class ContextChain(IChain, ChainContextBase):
10
+ """
11
+ Enhanced to support ChainSteps with return parameters, storing return values as instance state variables.
12
+ Implements the IChain interface including get_schema_info and remove_step methods.
13
+ """
14
+
15
+ type: Literal["ContextChain"] = "ContextChain"
16
+
17
+ def add_step(
18
+ self,
19
+ key: str,
20
+ method: SubclassUnion[ToolBase],
21
+ args: Tuple = (),
22
+ kwargs: Dict[str, Any] = {},
23
+ ref: Optional[str] = None,
24
+ ):
25
+ # Directly store args, kwargs, and optionally a return_key without resolving them
26
+ step = ChainStep(key=key, method=method, args=args, kwargs=kwargs, ref=ref)
27
+ self.steps.append(step)
28
+
29
+ def remove_step(self, step: ChainStep) -> None:
30
+ self.steps = [s for s in self._steps if s.key != step.key]
31
+
32
+ def execute(self, *args, **kwargs) -> Dict[str, Any]:
33
+ # Execute the chain and manage result storage based on return_key
34
+ for step in self.steps:
35
+ resolved_args = [self._resolve_placeholders(arg) for arg in step.args]
36
+ resolved_kwargs = {
37
+ k: self._resolve_placeholders(v)
38
+ for k, v in step.kwargs.items()
39
+ if k != "ref"
40
+ }
41
+ result = step.method(*resolved_args, **resolved_kwargs)
42
+ if step.ref: # step.ref is used here as the return_key analogy
43
+ resolved_ref = self._resolve_ref(step.ref)
44
+ self.context[resolved_ref] = result
45
+ self.update(
46
+ **{resolved_ref: result}
47
+ ) # Update context with new state value
48
+ return self.context # or any specific result you intend to return
@@ -0,0 +1,5 @@
1
+ from typing import Literal
2
+ from swarmauri_base.chains.PromptContextChainBase import PromptContextChainBase
3
+
4
+ class PromptContextChain(PromptContextChainBase):
5
+ type: Literal['PromptContextChain'] = 'PromptContextChain'
@@ -0,0 +1,15 @@
1
+ from swarmauri.utils._lazy_import import _lazy_import
2
+
3
+ chains_files = [
4
+ ("swarmauri.chains.concrete.CallableChain import", "CallableChain"),
5
+ ("swarmauri.chains.concrete.ChainStep", "ChainStep"),
6
+ ("swarmauri.chains.concrete.PromptContextChain", "PromptContextChain"),
7
+ ("swarmauri.chains.concrete.ContextChain", "ContextChain"),
8
+ ]
9
+
10
+ # Lazy loading of chain classes, storing them in variables
11
+ for module_name, class_name in chains_files:
12
+ globals()[class_name] = _lazy_import(module_name, class_name)
13
+
14
+ # Adding the lazy-loaded chain classes to __all__
15
+ __all__ = [class_name for _, class_name in chains_files]
@@ -0,0 +1,35 @@
1
+ from typing import List, Union, Any, Literal
2
+ import re
3
+ from swarmauri_base.chunkers.ChunkerBase import ChunkerBase
4
+
5
+ class DelimiterBasedChunker(ChunkerBase):
6
+ """
7
+ A concrete implementation of IChunker that splits text into chunks based on specified delimiters.
8
+ """
9
+ version: str = "0.1.0.dev13"
10
+ delimiters: List[str] = ['.', '!', '?']
11
+ type: Literal['DelimiterBasedChunker'] = 'DelimiterBasedChunker'
12
+
13
+ def chunk_text(self, text: Union[str, Any], *args, **kwargs) -> List[str]:
14
+ """
15
+ Chunks the given text based on the delimiters specified during initialization.
16
+
17
+ Parameters:
18
+ - text (Union[str, Any]): The input text to be chunked.
19
+
20
+ Returns:
21
+ - List[str]: A list of text chunks split based on the specified delimiters.
22
+ """
23
+ delimiter_pattern = f"({'|'.join(map(re.escape, self.delimiters))})"
24
+
25
+ # Split the text based on the delimiter pattern, including the delimiters in the result
26
+ chunks = re.split(delimiter_pattern, text)
27
+
28
+ # Combine delimiters with the preceding text chunk since re.split() separates them
29
+ combined_chunks = []
30
+ for i in range(0, len(chunks), 2): # Step by 2 to process text chunk with its following delimiter
31
+ combined_chunks.append(chunks[i] + (chunks[i + 1] if i + 1 < len(chunks) else ''))
32
+
33
+ # Remove whitespace
34
+ combined_chunks = [chunk.strip() for chunk in combined_chunks]
35
+ return combined_chunks
@@ -0,0 +1,32 @@
1
+ from typing import List, Union, Any, Literal
2
+ from swarmauri_base.chunkers.ChunkerBase import ChunkerBase
3
+
4
+ class FixedLengthChunker(ChunkerBase):
5
+ """
6
+ Concrete implementation of ChunkerBase that divides text into fixed-length chunks.
7
+
8
+ This chunker breaks the input text into chunks of a specified size, making sure
9
+ that each chunk has exactly the number of characters specified by the chunk size,
10
+ except for possibly the last chunk.
11
+ """
12
+ chunk_size: int = 256
13
+ type: Literal['FixedLengthChunker'] = 'FixedLengthChunker'
14
+
15
+ def chunk_text(self, text: Union[str, Any], *args, **kwargs) -> List[str]:
16
+ """
17
+ Splits the input text into fixed-length chunks.
18
+
19
+ Parameters:
20
+ - text (Union[str, Any]): The input text to be chunked.
21
+
22
+ Returns:
23
+ - List[str]: A list of text chunks, each of a specified fixed length.
24
+ """
25
+ # Check if the input is a string, if not, attempt to convert to a string.
26
+ if not isinstance(text, str):
27
+ text = str(text)
28
+
29
+ # Using list comprehension to split text into chunks of fixed size
30
+ chunks = [text[i:i+self.chunk_size] for i in range(0, len(text), self.chunk_size)]
31
+
32
+ return chunks
@@ -0,0 +1,44 @@
1
+ from typing import List, Union, Any, Optional, Literal
2
+ import re
3
+ from swarmauri_base.chunkers.ChunkerBase import ChunkerBase
4
+
5
+ class MdSnippetChunker(ChunkerBase):
6
+ version: str = "0.1.0.dev1"
7
+ language: Optional[str] = None
8
+ type: Literal['MdSnippetChunker'] = 'MdSnippetChunker'
9
+ def chunk_text(self, text: Union[str, Any], *args, **kwargs) -> List[tuple]:
10
+ """
11
+ Extracts paired comments and code blocks from Markdown content based on the
12
+ specified programming language.
13
+ """
14
+ if self.language:
15
+ # If language is specified, directly extract the corresponding blocks
16
+ pattern = fr'```{self.language}\s*(.*?)```'
17
+ scripts = re.findall(pattern, text, re.DOTALL)
18
+ comments_temp = re.split(pattern, text, flags=re.DOTALL)
19
+ else:
20
+ # Extract blocks and languages dynamically if no specific language is provided
21
+ scripts = []
22
+ languages = []
23
+ for match in re.finditer(r'```(\w+)?\s*(.*?)```', text, re.DOTALL):
24
+ if match.group(1) is not None: # Checks if a language identifier is present
25
+ languages.append(match.group(1))
26
+ scripts.append(match.group(2))
27
+ else:
28
+ languages.append('') # Default to an empty string if no language is found
29
+ scripts.append(match.group(2))
30
+ comments_temp = re.split(r'```.*?```', text, flags=re.DOTALL)
31
+
32
+ comments = [comment.strip() for comment in comments_temp]
33
+
34
+ if text.strip().startswith('```'):
35
+ comments = [''] + comments
36
+ if text.strip().endswith('```'):
37
+ comments.append('')
38
+
39
+ if self.language:
40
+ structured_output = [(comments[i], self.language, scripts[i].strip()) for i in range(len(scripts))]
41
+ else:
42
+ structured_output = [(comments[i], languages[i], scripts[i].strip()) for i in range(len(scripts))]
43
+
44
+ return structured_output
@@ -0,0 +1,31 @@
1
+ from typing import Literal
2
+ import re
3
+ from swarmauri_base.chunkers.ChunkerBase import ChunkerBase
4
+
5
+ class SentenceChunker(ChunkerBase):
6
+ """
7
+ A simple implementation of the ChunkerBase to chunk text into sentences.
8
+
9
+ This class uses basic punctuation marks (., !, and ?) as indicators for sentence boundaries.
10
+ """
11
+ type: Literal['SentenceChunker'] = 'SentenceChunker'
12
+
13
+ def chunk_text(self, text, *args, **kwargs):
14
+ """
15
+ Chunks the given text into sentences using basic punctuation.
16
+
17
+ Args:
18
+ text (str): The input text to be chunked into sentences.
19
+
20
+ Returns:
21
+ List[str]: A list of sentence chunks.
22
+ """
23
+ # Split text using a simple regex pattern that looks for periods, exclamation marks, or question marks.
24
+ # Note: This is a very simple approach and might not work well with abbreviations or other edge cases.
25
+ sentence_pattern = r'(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|!)\s'
26
+ sentences = re.split(sentence_pattern, text)
27
+
28
+ # Filter out any empty strings that may have resulted from the split operation
29
+ sentences = [sentence.strip() for sentence in sentences if sentence]
30
+
31
+ return sentences
@@ -0,0 +1,35 @@
1
+ from typing import List, Literal
2
+ from swarmauri_base.chunkers.ChunkerBase import ChunkerBase
3
+
4
+
5
+ class SlidingWindowChunker(ChunkerBase):
6
+ """
7
+ A concrete implementation of ChunkerBase that uses sliding window technique
8
+ to break the text into chunks.
9
+ """
10
+ window_size: int = 256
11
+ step_size: int = 256
12
+ overlap: bool = False
13
+ type: Literal['SlidingWindowChunker'] = 'SlidingWindowChunker'
14
+
15
+ def chunk_text(self, text: str, *args, **kwargs) -> List[str]:
16
+ """
17
+ Splits the input text into chunks based on the sliding window technique.
18
+
19
+ Parameters:
20
+ - text (str): The input text to be chunked.
21
+
22
+ Returns:
23
+ - List[str]: A list of text chunks.
24
+ """
25
+ step_size = self.step_size if self.overlap else self.window_size # Non-overlapping if window size equals step size.
26
+
27
+
28
+ words = text.split() # Tokenization by whitespaces. More sophisticated tokenization might be necessary.
29
+ chunks = []
30
+
31
+ for i in range(0, len(words) - self.window_size + 1, step_size):
32
+ chunk = ' '.join(words[i:i+self.window_size])
33
+ chunks.append(chunk)
34
+
35
+ return chunks
@@ -0,0 +1,17 @@
1
+ from swarmauri.utils._lazy_import import _lazy_import
2
+
3
+ # List of chunker names (file names without the ".py" extension) and corresponding class names
4
+ chunkers_files = [
5
+ ("swarmauri.chunkers.concrete.DelimiterBasedChunker", "DelimiterBasedChunker"),
6
+ ("swarmauri.chunkers.concrete.FixedLengthChunker", "FixedLengthChunker"),
7
+ ("swarmauri.chunkers.concrete.MdSnippetChunker", "MdSnippetChunker"),
8
+ ("swarmauri.chunkers.concrete.SentenceChunker", "SentenceChunker"),
9
+ ("swarmauri.chunkers.concrete.SlidingWindowChunker", "SlidingWindowChunker"),
10
+ ]
11
+
12
+ # Lazy loading of chunker classes, storing them in variables
13
+ for module_name, class_name in chunkers_files:
14
+ globals()[class_name] = _lazy_import(module_name, class_name)
15
+
16
+ # Adding the lazy-loaded chunker classes to __all__
17
+ __all__ = [class_name for _, class_name in chunkers_files]
@@ -0,0 +1,10 @@
1
+ from typing import Literal
2
+ from swarmauri_base.control_panels.ControlPanelBase import ControlPanelBase
3
+
4
+
5
+ class ControlPanel(ControlPanelBase):
6
+ """
7
+ Concrete implementation of the ControlPanelBase.
8
+ """
9
+
10
+ type: Literal["ControlPanel"] = "ControlPanel"
@@ -0,0 +1,13 @@
1
+ from swarmauri.utils._lazy_import import _lazy_import
2
+
3
+ # List of control_panels names (file names without the ".py" extension) and corresponding class names
4
+ control_panels_files = [
5
+ ("swarmauri.control_panels.concrete.ControlPanel", "ControlPanel"),
6
+ ]
7
+
8
+ # Lazy loading of task_mgt_strategies classes, storing them in variables
9
+ for module_name, class_name in control_panels_files:
10
+ globals()[class_name] = _lazy_import(module_name, class_name)
11
+
12
+ # Adding the lazy-loaded state classes to __all__
13
+ __all__ = [class_name for _, class_name in control_panels_files]
@@ -0,0 +1,8 @@
1
+ from typing import Literal
2
+ from swarmauri_base.conversations.ConversationBase import ConversationBase
3
+
4
+ class Conversation(ConversationBase):
5
+ """
6
+ Concrete implementation of ConversationBase, managing conversation history and operations.
7
+ """
8
+ type: Literal['Conversation'] = 'Conversation'