pull/483/head
Kye Gomez 7 months ago
parent 1cb5f8e2a7
commit 5eb46c869c

@ -1,63 +0,0 @@
# 2O+ Autonomous Agent Blogs
1. **The Ultimate Guide to Deploying Production-Ready Autonomous Agents with Swarms**
- A comprehensive start-to-finish guide on implementing Swarms in a production environment.
2. **5 Steps to Elevate Your AI with Swarms Multi-Modal Autonomous Agents**
- A walkthrough highlighting the simplicity of Swarms setup and deployment for various AI applications.
3. **Integrating Swarms Into Your Enterprise Workflow: A Step-By-Step Tutorial**
- A practical guide focusing on integrating Swarms into existing enterprise systems.
4. **Swarms Agent: Streamlining AI Deployment in Your Business**
- Exploring the benefits and technicalities of using the Agent feature to simplify complex AI workflows.
5. **From Zero to Hero: Building Your First Enterprise-Grade AI Agent with Swarms**
- A beginner-friendly walkthrough for building and deploying an AI agent using Swarms.
6. **Scaling AI with Swarms: Managing Multi-Agent Systems Efficiently**
- Strategies and best practices for scaling multi-agent systems in enterprise settings.
7. **Creating Resilient AI Systems with Swarms' Autonomous Agents**
- Discussing the robustness of Swarms agents and how they maintain performance under stress.
8. **Unlocking New Capabilities: Advanced Features of Swarms for AI Engineers**
- Diving into the more sophisticated features of Swarms and how they can be leveraged in complex projects.
9. **Swarms Quick Wins: Implementing AI Agents in Less Than 5 Lines of Code**
- A focused guide on rapidly deploying functional AI agents with minimal coding.
10. **Benchmarking Your AI: Performance Metrics with Swarms**
- How to use Swarms to measure and optimize the performance of AI agents.
11. **Swarms Case Studies: Real-World Success Stories from AI Engineers**
- Sharing stories and testimonials of how various organizations successfully implemented Swarms.
12. **Effortless Multi-Modal Model Deployment: A Swarms Walkthrough**
- Explaining how to use Swarms to deploy multi-modal models with ease.
13. **Future-Proof Your AI: Adapting to New Tech with Swarms**
- How Swarms' flexible architecture allows for easy updates and adaptation to new AI technologies.
14. **Enterprise AI Security: Ensuring Your Swarms Agents are Hack-Proof**
- Best practices for securing autonomous agents in enterprise applications.
15. **Migrating to Swarms: Transitioning From Legacy Systems**
- A guide for AI engineers on migrating existing AI systems to Swarms without downtime.
16. **Multi-Agent Collaboration: How Swarms Facilitates Teamwork Among AI**
- An insight into how Swarms allows for multiple AI agents to work together seamlessly.
17. **The Engineer's Toolkit: Swarms' Features Every AI Developer Must Know**
- Highlighting the most useful tools and features of Swarms from an AI developers perspective.
18. **Swarms for Different Industries: Customizing AI Agents for Niche Markets**
- Exploring how Swarms can be tailored to fit the needs of various industries such as healthcare, finance, and retail.
19. **Building Intelligent Workflows with Swarms Agent**
- A tutorial on using the Agent feature to create intelligent, responsive AI-driven workflows.
20. **Troubleshooting Common Issues When Deploying Swarms Autonomous Agents**
- A problem-solving guide for AI engineers on overcoming common challenges when implementing Swarms agents.
Each blog or walkthrough can be structured to not only showcase the functionality and benefits of the Swarms framework but also to establish the brand as a thought leader in the space of enterprise AI solutions.

@ -1,3 +0,0 @@
This section of the documentation is dedicated to examples highlighting Swarms functionality.
We try to keep all examples up to date, but if you think there is a bug please [submit a pull request](https://github.com/kyegomez/swarms-docs/tree/main/docs/examples). We are also more than happy to include new examples)

@ -1,239 +0,0 @@
# Enterprise-Grade Workflow Automation With Autonomous Agents
========================================================================
Welcome to this comprehensive walkthrough guide tutorial on the SequentialWorkflow feature of the Swarms Framework! In this tutorial, we will explore the purpose, usage, and key concepts of the SequentialWorkflow class, which is a part of the swarms package. Whether you are a beginner, intermediate, or expert developer, this tutorial will provide you with a clear understanding of how to effectively use the SequentialWorkflow class in your projects.
AI engineering is a dynamic and evolving field that involves the development and deployment of intelligent systems and applications. In this ever-changing landscape, AI engineers often face the challenge of orchestrating complex sequences of tasks, managing data flows, and ensuring the smooth execution of AI workflows. This is where the Workflow Class, such as the SequentialWorkflow class we discussed earlier, plays a pivotal role in enabling AI engineers to achieve their goals efficiently and effectively.
## The Versatile World of AI Workflows
AI workflows encompass a wide range of tasks and processes, from data preprocessing and model training to natural language understanding and decision-making. These workflows are the backbone of AI systems, guiding them through intricate sequences of actions to deliver meaningful results. Here are some of the diverse use cases where the Workflow Class can empower AI engineers:
### 1. Natural Language Processing (NLP) Pipelines
AI engineers often build NLP pipelines that involve multiple stages such as text preprocessing, tokenization, feature extraction, model inference, and post-processing. The Workflow Class enables the orderly execution of these stages, ensuring that textual data flows seamlessly through each step, resulting in accurate and coherent NLP outcomes.
### 2. Data Ingestion and Transformation
AI projects frequently require the ingestion of diverse data sources, including structured databases, unstructured text, and multimedia content. The Workflow Class can be used to design data ingestion workflows that extract, transform, and load (ETL) data efficiently, making it ready for downstream AI tasks like training and analysis.
### 3. Autonomous Agents and Robotics
In autonomous robotics and intelligent agent systems, workflows are essential for decision-making, sensor fusion, motion planning, and control. AI engineers can use the Workflow Class to create structured sequences of actions that guide robots and agents through dynamic environments, enabling them to make informed decisions and accomplish tasks autonomously.
### 4. Machine Learning Model Training
Training machine learning models involves a series of steps, including data preprocessing, feature engineering, model selection, hyperparameter tuning, and evaluation. The Workflow Class simplifies the orchestration of these steps, allowing AI engineers to experiment with different configurations and track the progress of model training.
### 5. Content Generation and Summarization
AI-driven content generation tasks, such as generating articles, reports, or summaries, often require multiple steps, including content creation and post-processing. The Workflow Class can be used to create content generation workflows, ensuring that the generated content meets quality and coherence criteria.
### 6. Adaptive Decision-Making
In AI systems that make real-time decisions based on changing data and environments, workflows facilitate adaptive decision-making. Engineers can use the Workflow Class to design decision-making pipelines that take into account the latest information and make informed choices.
## Enabling Efficiency and Maintainability
The Workflow Class provides AI engineers with a structured and maintainable approach to building, executing, and managing complex AI workflows. It offers the following advantages:
- Modularity: Workflows can be modularly designed, allowing engineers to focus on individual task implementations and ensuring code reusability.
- Debugging and Testing: The Workflow Class simplifies debugging and testing by providing a clear sequence of tasks and well-defined inputs and outputs for each task.
- Scalability: As AI projects grow in complexity, the Workflow Class can help manage and scale workflows by adding or modifying tasks as needed.
- Error Handling: The class supports error handling strategies, enabling engineers to define how to handle unexpected failures gracefully.
- Maintainability: With structured workflows, AI engineers can easily maintain and update AI systems as requirements evolve or new data sources become available.
The Workflow Class, such as the SequentialWorkflow class, is an indispensable tool in the toolkit of AI engineers. It empowers engineers to design, execute, and manage AI workflows across a diverse range of use cases. By providing structure, modularity, and maintainability to AI projects, the Workflow Class contributes significantly to the efficiency and success of AI engineering endeavors. As the field of AI continues to advance, harnessing the power of workflow orchestration will remain a key ingredient in building intelligent and adaptable systems, now lets get started with SequentialWorkflow.
## Official Swarms Links
Here is the Swarms website:
Here is the Swarms Github:
Here are the Swarms docs:
And, join the Swarm community!
Book a call with The Swarm Corporation here if youre interested in high performance custom swarms!
Now lets begin…
## Installation
Before we dive into the tutorial, make sure you have the following prerequisites in place:
Python installed on your system.
The swarms library installed. You can install it via pip using the following command:
`pip3 install --upgrade swarms`
Additionally, you will need an API key for the OpenAIChat model to run the provided code examples. Replace "YOUR_API_KEY" with your actual API key in the code examples where applicable.
## Getting Started
Lets start by importing the necessary modules and initializing the OpenAIChat model, which we will use in our workflow tasks.
```python
from swarms.models import OpenAIChat
from swarms.structs import Agent
from swarms.structs.sequential_workflow import SequentialWorkflow
# Replace "YOUR_API_KEY" with your actual OpenAI API key
api_key = "YOUR_API_KEY"
# Initialize the language model agent (e.g., GPT-3)
llm = OpenAIChat(
openai_api_key=api_key,
temperature=0.5,
max_tokens=3000,
)
We have initialized the OpenAIChat model, which will be used as a callable object in our tasks. Now, lets proceed to create the SequentialWorkflow.
Creating a SequentialWorkflow
To create a SequentialWorkflow, follow these steps:
# Initialize Agents for individual tasks
flow1 = Agent(llm=llm, max_loops=1, dashboard=False)
flow2 = Agent(llm=llm, max_loops=1, dashboard=False)
# Create the Sequential Workflow
workflow = SequentialWorkflow(max_loops=1)
``````
In this code snippet, we have initialized two Agent instances (flow1 and flow2) representing individual tasks within our workflow. These flows will use the OpenAIChat model we initialized earlier. We then create a SequentialWorkflow instance named workflow with a maximum loop count of 1. The max_loops parameter determines how many times the entire workflow can be run, and we set it to 1 for this example.
Adding Tasks to the SequentialWorkflow
Now that we have created the SequentialWorkflow, lets add tasks to it. In our example, well create two tasks: one for generating a 10,000-word blog on “health and wellness” and another for summarizing the generated blog.
```
### Add tasks to the workflow
workflow.add("Generate a 10,000 word blog on health and wellness.", flow1)
`workflow.add("Summarize the generated blog", flow2)`
The workflow.add() method is used to add tasks to the workflow. Each task is described using a human-readable description, such as "Generate a 10,000 word blog on health and wellness," and is associated with a agent (callable object) that will be executed as the task. In our example, flow1 and flow2 represent the tasks.
Running the SequentialWorkflow
With tasks added to the SequentialWorkflow, we can now run the workflow sequentially using the workflow.run() method.
### Run the workflow
`workflow.run()`
Executing workflow.run() will start the execution of tasks in the order they were added to the workflow. In our example, it will first generate the blog and then summarize it.
Accessing Task Results
After running the workflow, you can access the results of each task using the get_task_results() method.
# Get and display the results of each task in the workflow
```python
results = workflow.get_task_results()
for task_description, result in results.items():
print(f"Task: {task_description}, Result: {result}")
```
The workflow.get_task_results() method returns a dictionary where the keys are task descriptions, and the values are the corresponding results. You can then iterate through the results and print them, as shown in the code snippet.
Resetting a SequentialWorkflow
Sometimes, you might need to reset a SequentialWorkflow to start fresh. You can use the workflow.reset_workflow() method for this purpose.
### Reset the workflow
`workflow.reset_workflow()`
Resetting the workflow clears the results of each task, allowing you to rerun the workflow from the beginning without reinitializing it.
Updating Task Arguments
You can also update the arguments of a specific task in the workflow using the workflow.update_task() method.
### Update the arguments of a specific task in the workflow
`workflow.update_task("Generate a 10,000 word blog on health and wellness.", max_loops=2)`
In this example, we update the max_loops argument of the task with the description "Generate a 10,000 word blog on health and wellness" to 2. This can be useful if you want to change the behavior of a specific task without recreating the entire workflow.
# Conclusion: Mastering Workflow Orchestration in AI Engineering
In the ever-evolving landscape of artificial intelligence (AI), where the pace of innovation and complexity of tasks are ever-increasing, harnessing the power of workflow orchestration is paramount. In this comprehensive walkthrough guide, weve embarked on a journey through the world of workflow orchestration, focusing on the Workflow Class, with a specific emphasis on the SequentialWorkflow class. As we conclude this exploration, weve delved deep into the intricacies of orchestrating AI workflows, and its time to reflect on the valuable insights gained and the immense potential that this knowledge unlocks for AI engineers.
## The Art of Workflow Orchestration
At its core, workflow orchestration is the art of designing, managing, and executing sequences of tasks or processes in a structured and efficient manner. In the realm of AI engineering, where tasks can range from data preprocessing and model training to decision-making and autonomous actions, mastering workflow orchestration is a game-changer. It empowers AI engineers to streamline their work, ensure reliable execution, and deliver impactful results.
The Workflow Class, and particularly the SequentialWorkflow class weve explored, acts as a guiding light in this intricate journey. It provides AI engineers with a toolbox of tools and techniques to conquer the challenges of orchestrating AI workflows effectively. Through a disciplined approach and adherence to best practices, AI engineers can achieve the following:
### 1. Structured Workflow Design
A well-structured workflow is the cornerstone of any successful AI project. The Workflow Class encourages AI engineers to break down complex tasks into manageable units. Each task becomes a building block that contributes to the overarching goal. Whether its preprocessing data, training a machine learning model, or generating content, structured workflow design ensures clarity, modularity, and maintainability.
### 2. Efficient Task Sequencing
In AI, the order of tasks often matters. One tasks output can be another tasks input, and ensuring the correct sequence of execution is crucial. The SequentialWorkflow class enforces this sequential execution, eliminating the risk of running tasks out of order. It ensures that the workflow progresses systematically, following the predefined sequence of tasks.
### 3. Error Resilience and Recovery
AI systems must be resilient in the face of unexpected errors and failures. The Workflow Class equips AI engineers with error handling strategies, such as retries and fallbacks. These strategies provide the ability to gracefully handle issues, recover from failures, and continue the workflows execution without disruption.
### 4. Code Modularity and Reusability
Building AI workflows often involves implementing various tasks, each with its own logic. The Workflow Class encourages code modularity, allowing AI engineers to encapsulate tasks as separate units. This modularity promotes code reusability, making it easier to adapt and expand workflows as AI projects evolve.
### 5. Efficient Debugging and Testing
Debugging and testing AI workflows can be challenging without clear structure and boundaries. The Workflow Class provides a clear sequence of tasks with well-defined inputs and outputs. This structure simplifies the debugging process, as AI engineers can isolate and test individual tasks, ensuring that each component functions as intended.
### 6. Scalability and Adaptability
As AI projects grow in complexity, the Workflow Class scales effortlessly. AI engineers can add or modify tasks as needed, accommodating new data sources, algorithms, or requirements. This scalability ensures that workflows remain adaptable to changing demands and evolving AI landscapes.
### 7. Maintainability and Future-Proofing
Maintaining AI systems over time is a crucial aspect of engineering. The Workflow Class fosters maintainability by providing a clear roadmap of tasks and their interactions. AI engineers can revisit, update, and extend workflows with confidence, ensuring that AI systems remain effective and relevant in the long run.
## Empowering AI Engineers
The knowledge and skills gained from this walkthrough guide go beyond technical proficiency. They empower AI engineers to be architects of intelligent systems, capable of orchestrating AI workflows that solve real-world problems. The Workflow Class is a versatile instrument in their hands, enabling them to tackle diverse use cases and engineering challenges.
## Diverse Use Cases for Workflow Class
Throughout this guide, we explored a myriad of use cases where the Workflow Class shines:
Natural Language Processing (NLP) Pipelines: In NLP, workflows involve multiple stages, and the Workflow Class ensures orderly execution, resulting in coherent NLP outcomes.
Data Ingestion and Transformation: Data is the lifeblood of AI, and structured data workflows ensure efficient data preparation for downstream tasks.
Autonomous Agents and Robotics: For robots and intelligent agents, workflows enable autonomous decision-making and task execution.
Machine Learning Model Training: Model training workflows encompass numerous steps, and structured orchestration simplifies the process.
Content Generation and Summarization: Workflows for content generation ensure that generated content meets quality and coherence criteria.
Adaptive Decision-Making: In dynamic environments, workflows facilitate adaptive decision-making based on real-time data.
## Efficiency and Maintainability
AI engineers not only have the tools to tackle these use cases but also the means to do so efficiently. The Workflow Class fosters efficiency and maintainability, making AI engineering endeavors more manageable:
- Modularity: Encapsulate tasks as separate units, promoting code reusability and maintainability.
- Debugging and Testing: Streamline debugging and testing through clear task boundaries and well-defined inputs and outputs.
- Scalability: As AI projects grow, workflows scale with ease, accommodating new components and requirements.
Error Handling: Gracefully handle errors and failures, ensuring that AI systems continue to operate smoothly.
- Maintainability: AI systems remain adaptable and maintainable, even as the AI landscape evolves and requirements change.
## The Future of AI Engineering
As AI engineering continues to advance, workflow orchestration will play an increasingly pivotal role. The Workflow Class is not a static tool; it is a dynamic enabler of innovation. In the future, we can expect further enhancements and features to meet the evolving demands of AI engineering:
### 1. Asynchronous Support
Support for asynchronous task execution will improve the efficiency of workflows, especially when tasks involve waiting for external events or resources.
### 2. Context Managers
Introducing context manager support for tasks can simplify resource management, such as opening and closing files or database connections.
### 3. Workflow History
Maintaining a detailed history of workflow execution, including timestamps, task durations, and input/output data, will facilitate debugging and performance analysis.
### 4. Parallel Processing
Enhancing the module to support parallel processing with a pool of workers can significantly speed up the execution of tasks, especially for computationally intensive workflows.
### 5. Error Handling Strategies
Providing built-in error handling strategies, such as retries, fallbacks, and circuit breakers, will further enhance the resilience of workflows.
## Closing Thoughts
In conclusion, the journey through workflow orchestration in AI engineering has been both enlightening and empowering. The Workflow Class, and particularly the SequentialWorkflow class, has proven to be an invaluable ally in the AI engineers toolkit. It offers structure, modularity, and efficiency, ensuring that AI projects progress smoothly from inception to deployment.
As AI continues to permeate every aspect of our lives, the skills acquired in this guide will remain highly relevant and sought after. AI engineers armed with workflow orchestration expertise will continue to push the boundaries of what is possible, solving complex problems, and driving innovation.
But beyond the technical aspects, this guide also emphasizes the importance of creativity, adaptability, and problem-solving. AI engineering is not just about mastering tools; its about using them to make a meaningful impact on the world.
So, whether youre just starting your journey into AI engineering or youre a seasoned professional seeking to expand your horizons, remember that the power of workflow orchestration lies not only in the code but in the limitless potential it unlocks for you as an AI engineer. As you embark on your own AI adventures, may this guide serve as a reliable companion, illuminating your path and inspiring your journey towards AI excellence.
The world of AI is waiting for your innovation and creativity. With workflow orchestration as your guide, you have the tools to shape the future. The possibilities are boundless, and the future is yours to create.
Official Swarms Links
Here is the Swarms website:
Here is the Swarms Github:
Here are the Swarms docs:
And, join the Swarm community!
Book a call with The Swarm Corporation here if youre interested in high performance custom swarms!

@ -1,88 +0,0 @@
# check_device
# Module/Function Name: check_device
The `check_device` is a utility function in PyTorch designed to identify and return the appropriate device(s) for CUDA processing. If CUDA is not available, a CPU device is returned. If CUDA is available, the function returns a list of all available GPU devices.
The function examines the CUDA availability, checks for multiple GPUs, and finds additional properties for each device.
## Function Signature and Arguments
**Signature:**
```python
def check_device(
log_level: Any = logging.INFO,
memory_threshold: float = 0.8,
capability_threshold: float = 3.5,
return_type: str = "list",
) -> Union[torch.device, List[torch.device]]
```
| Parameter | Data Type | Default Value | Description |
| ------------- | ------------- | ------------- | ------------- |
| `log_level` | Any | logging.INFO | The log level. |
| `memory_threshold` | float | 0.8 | It is used to check the threshold of memory used on the GPU(s). |
| `capability_threshold` | float | 3.5 | It is used to consider only those GPU(s) which have higher compute capability compared to the threshold. |
| `return_type` | str | "list" | Depending on the `return_type` either a list of devices can be returned or a single device. |
This function does not take any mandatory argument. However, it supports optional arguments such as `log_level`, `memory_threshold`, `capability_threshold`, and `return_type`.
**Returns:**
- A single torch.device if one device or list of torch.devices if multiple CUDA devices are available, else returns the CPU device if CUDA is not available.
## Usage and Examples
### Example 1: Basic Usage
```python
import logging
import torch
from swarms.utils import check_device
# Basic usage
device = check_device(
log_level=logging.INFO,
memory_threshold=0.8,
capability_threshold=3.5,
return_type="list",
)
```
### Example 2: Using CPU when CUDA is not available
```python
import torch
from swarms.utils import check_device
# When CUDA is not available
device = check_device()
print(device) # If CUDA is not available it should return torch.device('cpu')
```
### Example 3: Multiple GPU Available
```python
import torch
from swarms.utils import check_device
# When multiple GPUs are available
device = check_device()
print(device) # Should return a list of available GPU devices
```
## Tips and Additional Information
- This function is useful when a user wants to exploit CUDA capabilities for faster computation but unsure of the available devices. This function abstracts all the necessary checks and provides a list of CUDA devices to the user.
- The `memory_threshold` and `capability_threshold` are utilized to filter the GPU devices. The GPUs which have memory usage above the `memory_threshold` and compute capability below the `capability_threshold` are not considered.
- As of now, CPU does not have memory or capability values, therefore, in the respective cases, it will be returned as default without any comparison.
## Relevant Resources
- For more details about the CUDA properties functions used (`torch.cuda.get_device_capability, torch.cuda.get_device_properties`), please refer to the official PyTorch [CUDA semantics documentation](https://pytorch.org/docs/stable/notes/cuda.html).
- For more information about Torch device objects, you can refer to the official PyTorch [device documentation](https://pytorch.org/docs/stable/tensor_attributes.html#torch-device).
- For a better understanding of how the `logging` module works in Python, see the official Python [logging documentation](https://docs.python.org/3/library/logging.html).

@ -1,86 +0,0 @@
# display_markdown_message
# Module Name: `display_markdown_message`
## Introduction
`display_markdown_message` is a useful utility function for creating visually-pleasing markdown messages within Python scripts. This function automatically manages multiline strings with lots of indentation and makes single-line messages with ">" tags easy to read, providing users with convenient and elegant logging or messaging capacity.
## Function Definition and Arguments
Function Definition:
```python
def display_markdown_message(message: str, color: str = "cyan"):
```
This function accepts two parameters:
|Parameter |Type |Default Value |Description |
|--- |--- |--- |--- |
|message |str |None |This is the message that is to be displayed. This should be a string. It can contain markdown syntax.|
|color |str |"cyan" |This allows you to choose the color of the message. Default is "cyan". Accepts any valid color name.|
## Functionality and Usage
This utility function is used to display a markdown formatted message on the console. It accepts a message as a string and an optional color for the message. The function is ideal for generating stylized print outputs such as headers, status updates or pretty notifications.
By default, any text within the string which is enclosed within `>` tags or `---` is treated specially:
- Lines encased in `>` tags are rendered as a blockquote in markdown.
- Lines consisting of `---` are rendered as horizontal rules.
The function automatically strips off leading and trailing whitespaces from any line within the message, maintaining aesthetic consistency in your console output.
### Usage Examples
#### Basic Example
```python
display_markdown_message("> This is an important message", color="red")
```
Output:
```md
> **This is an important message**
```
This example will print out the string "This is an important message" in red color, enclosed in a blockquote tag.
#### Multiline Example
```python
message = """
> Header
My normal message here.
---
Another important information
"""
display_markdown_message(message, color="green")
```
Output:
```md
> **Header**
My normal message here.
_____
Another important information
```
The output is a green colored markdown styled text with the "Header" enclosed in a blockquote, followed by the phrase "My normal message here", a horizontal rule, and finally another phrase, "Another important information".
## Additional Information
Use newline characters `\n` to separate the lines of the message. Remember, each line of the message is stripped of leading and trailing whitespaces. If you have special markdown requirements, you may need to revise the input message string accordingly.
Also, keep in mind the console or terminal's ability to display the chosen color. If a particular console does not support the chosen color, the output may fallback to the default console color.
For a full list of color names supported by the `Console` module, refer to the official [Console documentation](http://console.readthedocs.io/).
## References and Resources
- Python Strings: https://docs.python.org/3/tutorial/introduction.html#strings
- Python Markdown: https://pypi.org/project/markdown/
- Console module: https://console.readthedocs.io/

@ -1,118 +0,0 @@
# extract_code_from_markdown
# swarms.utils Module
The `swarms.utils` module provides utility functions designed to facilitate specific tasks within the main Swarm codebase. The function `extract_code_from_markdown` is a critical function within this module that we will document in this example.
## Overview and Introduction
Many software projects use Markdown extensively for writing documentation, tutorials, and other text documents that can be easily rendered and viewed in different formats, including HTML.
The `extract_code_from_markdown` function plays a crucial role within the swarms.utils library. As developers write large volumes of Markdown, they often need to isolate code snippets from the whole Markdown file body. These isolated snippets can be used to generate test cases, transform into other languages, or analyze for metrics.
## Function Definition: `extract_code_from_markdown`
```python
def extract_code_from_markdown(markdown_content: str) -> str:
"""
Extracts code blocks from a Markdown string and returns them as a single string.
Args:
- markdown_content (str): The Markdown content as a string.
Returns:
- str: A single string containing all the code blocks separated by newlines.
"""
# Regular expression for fenced code blocks
pattern = r"```(?:\w+\n)?(.*?)```"
matches = re.findall(pattern, markdown_content, re.DOTALL)
# Concatenate all code blocks separated by newlines
return "\n".join(code.strip() for code in matches)
```
### Arguments
The function `extract_code_from_markdown` takes one argument:
| Argument | Description | Type | Default Value |
|-----------------------|----------------------------------------|-------------|-------------------|
| markdown_content | The input markdown content as a string | str | N/A |
## Function Explanation and Usage
This function uses a regular expression to find all fenced code blocks in a Markdown string. The pattern `r"```(?:\w+\n)?(.*?)```"` matches strings that start and end with three backticks, optionally followed by a newline and then any number of any characters (the `.*?` part) until the first occurrence of another triple backtick set.
Once we have the matches, we join all the code blocks into a single string, each block separated by a newline.
The method's functionality is particularly useful when we need to extract code blocks from markdown content for secondary processing, such as syntax highlighting or execution in a different environment.
### Usage Examples
Below are three examples of how you might use this function:
#### Example 1:
Extracting code blocks from a simple markdown string.
```python
from swarms.utils import extract_code_from_markdown
markdown_string = """# Example
This is an example of a code block:
```python
print("Hello World!")
``` """
print(extract_code_from_markdown(markdown_string))
```
#### Example 2:
Extracting code blocks from a markdown file.
```python
import re
def extract_code_from_markdown(markdown_content: str) -> str:
pattern = r"```(?:\w+\n)?(.*?)```"
matches = re.findall(pattern, markdown_content, re.DOTALL)
return "\n".join(code.strip() for code in matches)
# Assume that 'example.md' contains multiple code blocks
with open("example.md") as file:
markdown_content = file.read()
print(extract_code_from_markdown(markdown_content))
```
#### Example 3:
Using the function in a pipeline to extract and then analyze code blocks.
```python
import re
def extract_code_from_markdown(markdown_content: str) -> str:
pattern = r"```(?:\w+\n)?(.*?)```"
matches = re.findall(pattern, markdown_content, re.DOTALL)
return "\n".join(code.strip() for code in matches)
def analyze_code_blocks(code: str):
# Add your analysis logic here
pass
# Assume that 'example.md' contains multiple code blocks
with open("example.md") as file:
markdown_content = file.read()
code_blocks = extract_code_from_markdown(markdown_content)
analyze_code_blocks(code_blocks)
```
## Conclusion
This concludes the detailed documentation of the `extract_code_from_markdown` function from the swarms.utils module. With this documentation, you should be able to understand the function's purpose, how it works, its parameters, and see examples of how to use it effectively.

@ -1,90 +0,0 @@
# find_image_path
Firstly, we will divide this documentation into multiple sections.
# Overview
The module **swarms.utils** has the main goal of providing necessary utility functions that are crucial during the creation of the swarm intelligence frameworks. These utility functions can include common operations such as handling input-output operations for files, handling text parsing, and handling basic mathematical computations necessary during the creation of swarm intelligence models.
The current function `find_image_path` in the module is aimed at extracting an image path from a given text document.
# Function Detailed Explanation
## Definition
The function `find_image_path` takes a singular argument as an input:
```python
def find_image_path(text):
# function body
```
## Parameter
The parameter `text` in the function is a string that represents the document or text from which the function is trying to extract all paths to the images present. The function scans the given text, looking for <em>absolute</em> or <em>relative</em> paths to image files (.png, .jpg, .jpeg) on the disk.
| Parameter Name | Data Type | Default Value | Description |
|:--------------:|:---------:|:-------------:|:--------:|
| `text` | `str` | - | The text content to scan for image paths |
## Return Value
The return value of the function `find_image_path` is a string that represents the longest existing image path extracted from the input text. If no image paths exist within the text, the function returns `None`.
| Return Value | Data Type | Description |
|:------------:|:-----------:|:-----------:|
| Path | `str` | Longest image path found in the text or `None` if no path found |
# Function's Code
The function `find_image_path` performs text parsing and pattern recognition to find image paths within the provided text. The function uses `regular expressions (re)` module to detect all potential paths.
```python
def find_image_path(text):
pattern = r"([A-Za-z]:\\[^:\n]*?\.(png|jpg|jpeg|PNG|JPG|JPEG))|(/[^:\n]*?\.(png|jpg|jpeg|PNG|JPG|JPEG))"
matches = [match.group() for match in re.finditer(pattern, text) if match.group()]
matches += [match.replace("\\", "") for match in matches if match]
existing_paths = [match for match in matches if os.path.exists(match)]
return max(existing_paths, key=len) if existing_paths else None
```
# Usage Examples
Let's consider examples of how the function `find_image_path` can be used in different scenarios.
**Example 1:**
Consider the case where a text without any image path is provided.
```python
from swarms.utils import find_image_path
text = "There are no image paths in this text"
print(find_image_path(text)) # Outputs: None
```
**Example 2:**
Consider the case where the text has multiple image paths.
```python
from swarms.utils import find_image_path
text = "Here is an image path: /home/user/image1.png. Here is another one: C:\\Users\\User\\Documents\\image2.jpeg"
print(
find_image_path(text)
) # Outputs: the longest image path (depends on your file system and existing files)
```
**Example 3:**
In the final example, we consider a case where the text has an image path, but the file does not exist.
```python
from swarms.utils import find_image_path
text = "Here is an image path: /home/user/non_existant.png"
print(find_image_path(text)) # Outputs: None
```
# Closing Notes
In conclusion, the `find_image_path` function is crucial in the `swarms.utils` module as it supports a key operation of identifying image paths within given input text. This allows users to automate the extraction of such data from larger documents/text. However, it's important to note the function returns only existing paths in your file system and only the longest if multiple exist.

@ -1,82 +0,0 @@
# limit_tokens_from_string
## Introduction
The `Swarms.utils` library contains utility functions used across codes that handle machine learning and other operations. The `Swarms.utils` library includes a notable function named `limit_tokens_from_string()`. This function particularly limits the number of tokens in a given string.
# Function: limit_tokens_from_string()
Within the `Swarms.utils` library, there is a method `limit_tokens_from_string(string: str, model: str = "gpt-4", limit: int = 500) -> str:`
## Description
The function `limit_tokens_from_string()` limits the number of tokens in a given string based on the specified threshold. It is primarily useful when you are handling large text data and need to chunk or limit your text to a certain length. Limiting token length could be useful in various scenarios such as when working with data with limited computational resources, or when dealing with models that accept a specific maximum limit of text.
## Parameters
| Parameter | Type | Default Value | Description
| :-----------| :----------- | :------------ | :------------|
| `string` | `str` | `None` | The input string from which the tokens need to be limited. |
| `model` | `str` | `"gpt-4"` | The model used to encode and decode the token. The function defaults to `gpt-4` but you can specify any model supported by `tiktoken`. If a model is not found, it falls back to use `gpt2` |
| `limit` | `int` | `500` | The limit up to which the tokens have to be sliced. Default limit is 500.|
## Returns
| Return | Type | Description
| :-----------| :----------- | :------------
| `out` | `str` | A string that is constructed back from the encoded tokens that have been limited to a count of `limit` |
## Method Detail and Usage Examples
The method `limit_tokens_from_string()` takes in three parameters - `string`, `model`, and `limit`.
First, it tries to get the encoding for the model specified in the `model` argument using `tiktoken.encoding_for_model(model)`. In case the specified model is not found, the function uses `gpt2` model encoding as a fallback.
Next, the input `string` is tokenized using the `encode` method on the `encoding` tensor. This results in the `encoded` tensor.
Then, the function slices the `encoded` tensor to get the first `limit` number of tokens.
Finally, the function converts back the tokens into the string using the `decode` method of the `encoding` tensor. The resulting string `out` is returned.
### Example 1:
```python
from swarms.utils import limit_tokens_from_string
# longer input string
string = "This is a very long string that needs to be tokenized. This string might exceed the maximum token limit, so it will need to be truncated."
# lower token limit
limit = 10
output = limit_tokens_from_string(string, limit=limit)
```
### Example 2:
```python
from swarms.utils import limit_tokens_from_string
# longer input string with different model
string = "This string will be tokenized using gpt2 model. If the string is too long, it will be truncated."
# model
model = "gpt2"
output = limit_tokens_from_string(string, model=model)
```
### Example 3:
```python
from swarms.utils import limit_tokens_from_string
# try with a random model string
string = "In case the method does not find the specified model, it will fall back to gpt2 model."
# model
model = "gpt-4"
output = limit_tokens_from_string(string, model=model)
```
**Note:** If specifying a model not supported by `tiktoken` intentionally, it will fall back to `gpt2` model for encoding.

@ -1,105 +0,0 @@
# load_model_torch
# load_model_torch: Utility Function Documentation
## Introduction:
`load_model_torch` is a utility function in the `swarms.utils` library that is designed to load a saved PyTorch model and move it to the designated device. It provides flexibility allowing the user to specify the model file location, the device where the loaded model should be moved to, whether to strictly enforce the keys in the state dictionary to match the keys returned by the model's `state_dict()`, and many more.
Moreover, if the saved model file only contains the state dictionary, but not the model architecture, you can pass the model architecture as an argument.
## Function Definition and Parameters:
```python
def load_model_torch(
model_path: str = None,
device: torch.device = None,
model: nn.Module = None,
strict: bool = True,
map_location=None,
*args,
**kwargs,
) -> nn.Module:
```
The following table describes the parameters in detail:
| Name | Type | Default Value | Description |
| ------ | ------ | ------------- | ------------|
| model_path | str | None | A string specifying the path to the saved model file on disk. _Required_ |
| device | torch.device | None | A `torch.device` object that specifies the target device for the loaded model. If not provided, the function checks for the availability of a GPU and uses it if available. If not, it defaults to CPU. |
| model | nn.Module | None | An instance of `torch.nn.Module` representing the model's architecture. This parameter is required if the model file only contains the model's state dictionary and not the model architecture. |
| strict | bool | True | A boolean that determines whether to strictly enforce that the keys in the state dictionary match the keys returned by the model's `state_dict()` function. If set to `True`, the function will raise a KeyError when the state dictionary and `state_dict()` keys do not match. |
| map_location | callable | None | A function to remap the storage locations of the loaded model's parameters. Useful for loading models saved on a device type that is different from the current one. |
| *args, **kwargs | - | - | Additional arguments and keyword arguments to be passed to `torch.load`.
Returns:
- `torch.nn.Module` - The loaded model after moving it to the desired device.
Raises:
- `FileNotFoundError` - If the saved model file is not found at the specified path.
- `RuntimeError` - If there was an error while loading the model.
## Example of Usage:
This function can be used directly inside your code as shown in the following examples:
### Example 1:
Loading a model without specifying a device results in the function choosing the most optimal available device automatically.
```python
import torch.nn as nn
from swarms.utils import load_model_torch
# Assume `mymodel.pth` is in the current directory
model_path = "./mymodel.pth"
# Define your model architecture if the model file only contains state dict
class MyModel(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(10, 2)
def forward(self, x):
return self.linear(x)
model = MyModel()
# Load the model
loaded_model = load_model_torch(model_path, model=model)
# Now you can use the loaded model for prediction or further training
```
### Example 2:
Explicitly specifying a device.
```python
# Assume `mymodel.pth` is in the current directory
model_path = "./mymodel.pth"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Load the model
loaded_model = load_model_torch(model_path, device=device)
```
### Example 3:
Using a model file that contains only the state dictionary, not the model architecture.
```python
# Assume `mymodel_state_dict.pth` is in the current directory
model_path = "./mymodel_state_dict.pth"
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Define your model architecture
model = MyModel()
# Load the model
loaded_model = load_model_torch(model_path, device=device, model=model)
```
This gives you an insight on how to use `load_model_torch` utility function from `swarms.utils` library efficiently. Always remember to pass the model path argument while the other arguments can be optional based on your requirements. Furthermore, handle exceptions properly for smooth functioning of your PyTorch related projects.

@ -1,79 +0,0 @@
# math_eval
The `math_eval` function is a python decorator that wraps around a function to run two functions on the same inputs and compare their results. The decorator can be used for testing functions that are expected to have equivalent functionality, or in situations where two different methods are used to calculate or retrieve a value, and the results need to be compared.
The `math_eval` function in this case accepts two functions as parameters: `func1` and `func2`, and returns a decorator. This returned decorator, when applied to a function, enhances that function to execute both `func1` and `func2`, and compare the results.
This can be particularly useful in situations when you are implementing a new function and wants to compare its behavior and results with that of an existing one under the same set of input parameters. It also logs the results if they do not match which could be quite useful during the debug process.
## Usage Example
Let's say you have two functions: `ground_truth` and `generated_func`, that have similar functionalities or serve the same purpose. You are writing a new function called `test_func`, and you'd like to compare the results of `ground_truth` and `generated_func` when `test_func` is run. Here is how you would use the `math_eval` decorator:
```python
@math_eval(ground_truth, generated_func)
def test_func(x):
return x
result1, result2 = test_func(5)
print(f"Result from ground_truth: {result1}")
print(f"Result from generated_func: {result2}")
```
## Parameters
| Parameter | Data Type | Description |
| ---- | ---- | ---- |
| func1 | Callable | The first function whose result you want to compare. |
| func2 | Callable | The second function whose result you want to compare. |
The data types for `func1` and `func2` cannot be specified as they can be any python function (or callable object). The decorator verifies that they are callable and exceptions are handled within the decorator function.
## Return Values
The `math_eval` function does not return a direct value, since it is a decorator. When applied to a function, it alters the behavior of the wrapped function to return two values:
1. `result1`: The result of running `func1` with the given input parameters.
2. `result2`: The result of running `func2` with the given input parameters.
These two return values are provided in that order as a tuple.
## Source Code
Here's how to implement the `math_eval` decorator:
```python
import functools
import logging
def math_eval(func1, func2):
"""Math evaluation decorator."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
result1 = func1(*args, **kwargs)
except Exception as e:
logging.error(f"Error in func1: {e}")
result1 = None
try:
result2 = func2(*args, **kwargs)
except Exception as e:
logging.error(f"Error in func2: {e}")
result2 = None
if result1 != result2:
logging.warning(f"Outputs do not match: {result1} != {result2}")
return result1, result2
return wrapper
return decorator
```
Please note that the code is logging exceptions to facilitate debugging, but the actual processing and handling of the exception would depend on how you want your application to respond to exceptions. Therefore, you may want to customize the error handling depending upon your application's requirements.

@ -1,87 +0,0 @@
# metrics_decorator
This documentation explains the use and functionality of the `metrics_decorator` function in the LLM (Large Language Models).
The `metrics_decorator` function is a standard Python decorator that augments a specific function by wrapping extra functionality around it. It is commonly used for things like timing, logging or memoization.
--
The `metrics_decorator` in LLM is specially designed to measure and calculate three key performance metrics when generating language models:
1. `Time to First Token`: Measures the elapsed time from the start of function execution until the generation of the first token.
2. `Generation Latency`: It measures the total time taken for a complete run.
3. `Throughput`: Calculates the rate of production of tokens per unit of time.
```python
def metrics_decorator(func: Callable):
"""
Metrics decorator for LLM
Args:
func (Callable): The function to be decorated.
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
"""
An inner function that wraps the decorated function. It calculates 'Time to First Token',
'Generation Latency' and 'Throughput' metrics.
Args:
self : The object instance.
*args : Variable length argument list of the decorated function.
**kwargs : Arbitrary keyword arguments of the decorated function.
"""
# Measure Time to First Token
start_time = time.time()
result = func(self, *args, **kwargs)
first_token_time = time.time()
# Measure Generation Latency
end_time = time.time()
# Calculate Throughput (assuming the function returns a list of tokens)
throughput = len(result) / (end_time - start_time)
return f"""
Time to First Token: {first_token_time - start_time}
Generation Latency: {end_time - start_time}
Throughput: {throughput}
"""
return wrapper
```
## Example Usage
Now let's discuss the usage of the `metrics_decorator` function with an example.
Assuming that we have a language generation function called `text_generator()` that generates a list of tokens.
```python
@metrics_decorator
def text_generator(self, text: str):
"""
Args:
text (str): The input text.
Returns:
A list of tokens generated from the input text.
"""
# language generation implementation goes here
return tokens
# Instantiate the class and call the decorated function
obj = ClassName()
obj.text_generator("Hello, world!")
```
When the decorated `text_generator()` function is called, it will measure and return:
- Time elapsed until the first token is generated.
- The total execution time of the function.
- The rate of tokens generation per unit time.
This example provides a basic overview of how a function can be decorated with the `metrics_decorator`. The provided `func` argument could be any method from any class, as long as it complies with the structure defined in `metrics_decorator`. It is worth noting that the decorated function must return a list of tokens for the `Throughput` metric to work correctly.
Remember, applying the `metrics_decorator` does not affect the original functionality of the decorated function, it just adds additional measurement and logging capabilities to it. It's a great utility for tracking and optimizing the performance of your language models.

@ -1,71 +0,0 @@
# pdf_to_text
## Introduction
The function `pdf_to_text` is a Python utility for converting a PDF file into a string of text content. It leverages the `pypdf` library, an excellent Python library for processing PDF files. The function takes in a PDF file's path and reads its content, subsequently returning the extracted textual data.
This function can be very useful when you want to extract textual information from PDF files automatically. For instance, when processing a large number of documents, performing textual analysis, or when you're dealing with text data that is only available in PDF format.
## Class / Function Definition
`pdf_to_text` is a standalone function defined as follows:
```python
def pdf_to_text(pdf_path: str) -> str:
```
## Parameters
| Parameter | Type | Description |
|:-:|---|---|
| pdf_path | str | The path to the PDF file to be converted |
## Returns
| Return Value | Type | Description |
|:-:|---|---|
| text | str | The text extracted from the PDF file. |
## Raises
| Exception | Description |
|---|---|
| FileNotFoundError | If the PDF file is not found at the specified path. |
| Exception | If there is an error in reading the PDF file. |
## Function Description
`pdf_to_text` utilises the `PdfReader` function from the `pypdf` library to read the PDF file. If the PDF file does not exist at the specified path or there was an error while reading the file, appropriate exceptions will be raised. It then iterates through each page in the PDF and uses the `extract_text` function to extract the text content from each page. These contents are then concatenated into a single variable and returned as the result.
## Usage Examples
To use this function, you first need to install the `pypdf` library. It can be installed via pip:
```python
!pip install pypdf
```
Then, you should import the `pdf_to_text` function:
```python
from swarms.utils import pdf_to_text
```
Here is an example of how to use `pdf_to_text`:
```python
# Define the path to the pdf file
pdf_path = "sample.pdf"
# Use the function to extract text
text = pdf_to_text(pdf_path)
# Print the extracted text
print(text)
```
## Tips and Additional Information
- Ensure that the PDF file path is valid and that the file exists at the specified location. If the file does not exist, a `FileNotFoundError` will be raised.
- This function reads the text from the PDF. It does not handle images, graphical elements, or any non-text content.
- If the PDF contains scanned images rather than textual data, the `extract_text` function may not be able to extract any text. In such cases, you would require OCR (Optical Character Recognition) tools to extract the text.
- Be aware of the possibility that the output string might contain special characters or escape sequences because they were part of the PDF's content. You might need to clean the resulting text according to your requirements.
- The function uses the pypdf library to facilitate the PDF reading and text extraction. For any issues related to PDF manipulation, consult the [pypdf library documentation](https://pypdf.readthedocs.io/en/stable/).

@ -1,103 +0,0 @@
# prep_torch_inference
```python
def prep_torch_inference(
model_path: str = None,
device: torch.device = None,
*args,
**kwargs,
):
"""
Prepare a Torch model for inference.
Args:
model_path (str): Path to the model file.
device (torch.device): Device to run the model on.
*args: Additional positional arguments.
**kwargs: Additional keyword arguments.
Returns:
torch.nn.Module: The prepared model.
"""
try:
model = load_model_torch(model_path, device)
model.eval()
return model
except Exception as e:
# Add error handling code here
print(f"Error occurred while preparing Torch model: {e}")
return None
```
This method is part of the 'swarms.utils' module. It accepts a model file path and a torch device as input and returns a model that is ready for inference.
## Detailed Functionality
The method loads a PyTorch model from the file specified by `model_path`. This model is then moved to the specified `device` if it is provided. Subsequently, the method sets the model to evaluation mode by calling `model.eval()`. This is a crucial step when preparing a model for inference, as certain layers like dropout or batch normalization behave differently during training vs during evaluation.
In the case of any exception (e.g., the model file not found or the device unavailable), it prints an error message and returns `None`.
## Parameters
| Parameter | Type | Description | Default |
|-----------|------|-------------|---------|
| model_path | str | Path to the model file. | None |
| device | torch.device | Device to run the model on. | None |
| args | tuple | Additional positional arguments. | None |
| kwargs | dict | Additional keyword arguments. | None |
## Returns
| Type | Description |
|------|-------------|
| torch.nn.Module | The prepared model ready for inference. Returns `None` if any exception occurs. |
## Usage Examples
Here are some examples of how you can use the `prep_torch_inference` method. Before that, you need to import the necessary modules as follows:
```python
import torch
from swarms.utils import load_model_torch, prep_torch_inference
```
### Example 1: Load a model for inference on CPU
```python
model_path = "saved_model.pth"
model = prep_torch_inference(model_path)
if model is not None:
print("Model loaded successfully and is ready for inference.")
else:
print("Failed to load the model.")
```
### Example 2: Load a model for inference on CUDA device
```python
model_path = "saved_model.pth"
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = prep_torch_inference(model_path, device)
if model is not None:
print(f"Model loaded successfully on device {device} and is ready for inference.")
else:
print("Failed to load the model.")
```
### Example 3: Load a model with additional arguments for `load_model_torch`
```python
model_path = "saved_model.pth"
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Suppose load_model_torch accepts an additional argument, map_location
model = prep_torch_inference(model_path, device, map_location=device)
if model is not None:
print(f"Model loaded successfully on device {device} and is ready for inference.")
else:
print("Failed to load the model.")
```
Please note, you need to ensure the given model path does exist and the device is available on your machine, else `prep_torch_inference` method will return `None`. Depending on the complexity and size of your models, loading them onto a specific device might take a while. So it's important that you take this into consideration when designing your machine learning workflows.

@ -1,110 +0,0 @@
# print_class_parameters
# Module Function Name: print_class_parameters
The `print_class_parameters` function is a utility function developed to help developers and users alike in retrieving and printing the parameters of a class constructor in Python, either in standard output or returned as a dictionary if the `api_format` is set to `True`.
This utility function utilizes the `inspect` module to fetch the signature of the class constructor and fetches the parameters from the obtained signature. The parameter values and their respective types are then outputted.
This function allows developers to easily inspect and understand the class' constructor parameters without the need to individually go through the class structure. This eases the testing and debugging process for developers and users alike, aiding in generating more efficient and readable code.
__Function Definition:__
```python
def print_class_parameters(cls, api_format: bool = False):
```
__Parameters:__
| Parameter | Type | Description | Default value |
|---|---|---|---|
| cls | type | The Python class to inspect. | None |
| api_format | bool | Flag to determine if the output should be returned in dictionary format (if set to True) or printed out (if set to False) | False |
__Functionality and Usage:__
Inside the `print_class_parameters` function, it starts by getting the signature of the constructor of the inputted class by invoking `inspect.signature(cls.__init__)`. It then extracts the parameters from the signature and stores it in the `params` variable.
If the `api_format` argument is set to `True`, instead of printing the parameters and their types, it stores them inside a dictionary where each key-value pair is a parameter name and its type. It then returns this dictionary.
If `api_format` is set to `False` or not set at all (defaulting to False), the function iterates over the parameters and prints the parameter name and its type. "self" parameters are excluded from the output as they are inherent to all class methods in Python.
A possible exception that may occur during the execution of this function is during the invocation of the `inspect.signature()` function call. If the inputted class does not have an `__init__` method or any error occurs during the retrieval of the class constructor's signature, an exception will be triggered. In that case, an error message that includes the error details is printed out.
__Usage and Examples:__
Assuming the existence of a class:
```python
class Agent:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
```
One could use `print_class_parameters` in its typical usage:
```python
print_class_parameters(Agent)
```
Results in:
```
Parameter: x, Type: <class 'int'>
Parameter: y, Type: <class 'int'>
```
Or, with `api_format` set to `True`
```python
output = print_class_parameters(Agent, api_format=True)
print(output)
```
Results in:
```
{'x': "<class 'int'>", 'y': "<class 'int'>"}
```
__Note:__
The function `print_class_parameters` is not limited to custom classes. It can inspect built-in Python classes such as `list`, `dict`, and others. However, it is most useful when inspecting custom-defined classes that aren't inherently documented in Python or third-party libraries.
__Source Code__
```python
def print_class_parameters(cls, api_format: bool = False):
"""
Print the parameters of a class constructor.
Parameters:
cls (type): The class to inspect.
Example:
>>> print_class_parameters(Agent)
Parameter: x, Type: <class 'int'>
Parameter: y, Type: <class 'int'>
"""
try:
# Get the parameters of the class constructor
sig = inspect.signature(cls.__init__)
params = sig.parameters
if api_format:
param_dict = {}
for name, param in params.items():
if name == "self":
continue
param_dict[name] = str(param.annotation)
return param_dict
# Print the parameters
for name, param in params.items():
if name == "self":
continue
print(f"Parameter: {name}, Type: {param.annotation}")
except Exception as e:
print(f"An error occurred while inspecting the class: {e}")
```
Loading…
Cancel
Save