docs cleanup

pull/791/head
Kye Gomez 2 months ago
parent 007eb5c011
commit 4108bac9eb

@ -228,9 +228,8 @@ nav:
- Multi-Agent Collaboration: - Multi-Agent Collaboration:
- Swarms DAO: "swarms/examples/swarms_dao.md" - Swarms DAO: "swarms/examples/swarms_dao.md"
- Swarms UI: - Swarms UI:
- Overview: "swarms/ui/main.md" - Overview: "swarms/ui/main.md"
- Contributors: - Contributors:
- Bounty Program: "corporate/bounty_program.md" - Bounty Program: "corporate/bounty_program.md"
@ -304,11 +303,11 @@ nav:
# - Tools API: # - Tools API:
# - Overview: "swarms_platform/tools_api.md" # - Overview: "swarms_platform/tools_api.md"
# - Add Tools: "swarms_platform/fetch_tools.md" # - Add Tools: "swarms_platform/fetch_tools.md"
- Corporate: # - Corporate:
- Culture: "corporate/culture.md" # - Culture: "corporate/culture.md"
- Hiring: "corporate/hiring.md" # - Hiring: "corporate/hiring.md"
- Swarms Goals & Milestone Tracking; A Vision for 2024 and Beyond: "corporate/2024_2025_goals.md" # - Swarms Goals & Milestone Tracking; A Vision for 2024 and Beyond: "corporate/2024_2025_goals.md"
- Web3: # - Web3:
# - Overview: "finance/index.md" # # - Overview: "finance/index.md"
- Swarms Wallet: "finance/wallet.md" # - Swarms Wallet: "finance/wallet.md"
- Swarms Subscription: "finance/subscription.md" # - Swarms Subscription: "finance/subscription.md"

@ -15,34 +15,6 @@ The `ConcurrentWorkflow` class is designed to facilitate the concurrent executio
## Class Definitions ## Class Definitions
### AgentOutputSchema
The `AgentOutputSchema` class is a data model that captures the output and metadata for each agent's execution. It inherits from `pydantic.BaseModel` and provides structured fields to store essential information.
| Attribute | Type | Description |
|---------------|----------------|-----------------------------------------------------------|
| `run_id` | `Optional[str]`| Unique ID for the run, automatically generated using `uuid`. |
| `agent_name` | `Optional[str]`| Name of the agent that executed the task. |
| `task` | `Optional[str]`| The task or query given to the agent. |
| `output` | `Optional[str]`| The output generated by the agent. |
| `start_time` | `Optional[datetime]`| The time when the agent started the task. |
| `end_time` | `Optional[datetime]`| The time when the agent completed the task. |
| `duration` | `Optional[float]` | The total time taken to complete the task, in seconds. |
### MetadataSchema
The `MetadataSchema` class is another data model that aggregates the outputs from all agents involved in the workflow. It also inherits from `pydantic.BaseModel` and includes fields for additional workflow-level metadata.
| Attribute | Type | Description |
|----------------|------------------------|-----------------------------------------------------------|
| `swarm_id` | `Optional[str]` | Unique ID for the workflow run, generated using `uuid`. |
| `task` | `Optional[str]` | The task or query given to all agents. |
| `description` | `Optional[str]` | A description of the workflow, typically indicating concurrent execution. |
| `agents` | `Optional[List[AgentOutputSchema]]` | A list of agent outputs and metadata. |
| `timestamp` | `Optional[datetime]` | The timestamp when the workflow was executed. |
## ConcurrentWorkflow
The `ConcurrentWorkflow` class is the core class that manages the concurrent execution of agents. It inherits from `BaseSwarm` and includes several key attributes and methods to facilitate this process. The `ConcurrentWorkflow` class is the core class that manages the concurrent execution of agents. It inherits from `BaseSwarm` and includes several key attributes and methods to facilitate this process.
### Attributes ### Attributes
@ -59,6 +31,10 @@ The `ConcurrentWorkflow` class is the core class that manages the concurrent exe
| `return_str_on` | `bool` | Flag to return output as string. Defaults to `False`. | | `return_str_on` | `bool` | Flag to return output as string. Defaults to `False`. |
| `agent_responses` | `List[str]` | List of agent responses as strings. | | `agent_responses` | `List[str]` | List of agent responses as strings. |
| `auto_generate_prompts`| `bool` | Flag indicating whether to auto-generate prompts for agents. | | `auto_generate_prompts`| `bool` | Flag indicating whether to auto-generate prompts for agents. |
| `output_type` | `OutputType` | Type of output format to return. Defaults to `"dict"`. |
| `return_entire_history`| `bool` | Flag to return entire conversation history. Defaults to `False`. |
| `conversation` | `Conversation` | Conversation object to track agent interactions. |
| `max_workers` | `int` | Maximum number of worker threads. Defaults to CPU count. |
## Methods ## Methods
@ -74,12 +50,14 @@ Initializes the `ConcurrentWorkflow` class with the provided parameters.
| `description` | `str` | `"Execution of multiple agents concurrently"` | A brief description of the workflow. | | `description` | `str` | `"Execution of multiple agents concurrently"` | A brief description of the workflow. |
| `agents` | `List[Agent]` | `[]` | A list of agents to be executed concurrently. | | `agents` | `List[Agent]` | `[]` | A list of agents to be executed concurrently. |
| `metadata_output_path`| `str` | `"agent_metadata.json"` | Path to save the metadata output. | | `metadata_output_path`| `str` | `"agent_metadata.json"` | Path to save the metadata output. |
| `auto_save` | `bool` | `False` | Flag indicating whether to automatically save the metadata. | | `auto_save` | `bool` | `True` | Flag indicating whether to automatically save the metadata. |
| `output_schema` | `BaseModel` | `MetadataSchema` | The output schema for the metadata. | | `output_schema` | `BaseModel` | `MetadataSchema` | The output schema for the metadata. |
| `max_loops` | `int` | `1` | Maximum number of loops for the workflow. | | `max_loops` | `int` | `1` | Maximum number of loops for the workflow. |
| `return_str_on` | `bool` | `False` | Flag to return output as string. | | `return_str_on` | `bool` | `False` | Flag to return output as string. |
| `agent_responses` | `List[str]` | `[]` | List of agent responses as strings. | | `agent_responses` | `List[str]` | `[]` | List of agent responses as strings. |
| `auto_generate_prompts`| `bool` | `False` | Flag indicating whether to auto-generate prompts for agents. | | `auto_generate_prompts`| `bool` | `False` | Flag indicating whether to auto-generate prompts for agents. |
| `output_type` | `OutputType` | `"dict"` | Type of output format to return. |
| `return_entire_history`| `bool` | `False` | Flag to return entire conversation history. |
#### Raises #### Raises
@ -97,26 +75,6 @@ workflow.activate_auto_prompt_engineering()
# All agents in the workflow will now auto-generate prompts. # All agents in the workflow will now auto-generate prompts.
``` ```
### ConcurrentWorkflow._run_agent
Runs a single agent with the provided task and tracks its output and metadata.
#### Parameters
| Parameter | Type | Description |
|-------------|-------------------------|-----------------------------------------------------------|
| `agent` | `Agent` | The agent instance to run. |
| `task` | `str` | The task or query to give to the agent. |
| `executor` | `ThreadPoolExecutor` | The thread pool executor to use for running the agent task. |
#### Returns
- `AgentOutputSchema`: The metadata and output from the agent's execution.
#### Detailed Explanation
This method handles the execution of a single agent by offloading the task to a thread using `ThreadPoolExecutor`. It also tracks the time taken by the agent to complete the task and logs relevant information. If an exception occurs during execution, it captures the error and includes it in the output. The method implements retry logic for improved reliability.
### ConcurrentWorkflow.transform_metadata_schema_to_str ### ConcurrentWorkflow.transform_metadata_schema_to_str
Transforms the metadata schema into a string format. Transforms the metadata schema into a string format.
@ -131,28 +89,6 @@ Transforms the metadata schema into a string format.
- `str`: The metadata schema as a formatted string. - `str`: The metadata schema as a formatted string.
#### Detailed Explanation
This method converts the metadata stored in `MetadataSchema` into a human-readable string format, particularly focusing on the agent names and their respective outputs. This is useful for quickly reviewing the results of the concurrent workflow in a more accessible format.
### ConcurrentWorkflow._execute_agents_concurrently
Executes multiple agents concurrently with the same task.
#### Parameters
| Parameter | Type | Description |
|-------------|--------------|-----------------------------------------------------------|
| `task` | `str` | The task or query to give to all agents. |
#### Returns
- `MetadataSchema`: The aggregated metadata and outputs from all agents.
#### Detailed Explanation
This method is responsible for managing the concurrent execution of all agents. It uses `asyncio.gather` to run multiple agents simultaneously and collects their outputs into a `MetadataSchema` object. This aggregated metadata can then be saved or returned depending on the workflow configuration. The method includes retry logic for improved reliability.
### ConcurrentWorkflow.save_metadata ### ConcurrentWorkflow.save_metadata
Saves the metadata to a JSON file based on the `auto_save` flag. Saves the metadata to a JSON file based on the `auto_save` flag.
@ -166,25 +102,29 @@ workflow.save_metadata()
### ConcurrentWorkflow.run ### ConcurrentWorkflow.run
Runs the workflow for the provided task, executes agents concurrently, and saves metadata. Executes the workflow for the provided task.
#### Parameters #### Parameters
| Parameter | Type | Description | | Parameter | Type | Description |
|-------------|--------------|-----------------------------------------------------------| |-------------|---------------------|-----------------------------------------------------------|
| `task` | `str` | The task or query to give to all agents. | | `task` | `Optional[str]` | The task or query to give to all agents. |
| `img` | `Optional[str]` | The image to be processed by the agents. |
| `*args` | `tuple` | Additional positional arguments. |
| `**kwargs` | `dict` | Additional keyword arguments. |
#### Returns #### Returns
- `Union[Dict[str, Any], str]`: The final metadata as a dictionary or a string, depending on the `return_str_on` flag. - `Any`: The result of the execution, format depends on output_type and return_entire_history settings.
#### Detailed Explanation #### Raises
This is the main method that a user will call to execute the workflow. It manages the entire process from starting the agents to collecting and optionally saving the metadata. The method also provides flexibility in how the results are returned—either as a JSON dictionary or as a formatted string. - `ValueError`: If an invalid device is specified.
- `Exception`: If any other error occurs during execution.
### ConcurrentWorkflow.run_batched ### ConcurrentWorkflow.run_batched
Runs the workflow for a batch of tasks, executing agents concurrently for each task. Runs the workflow for a batch of tasks.
#### Parameters #### Parameters
@ -194,7 +134,7 @@ Runs the workflow for a batch of tasks, executing agents concurrently for each t
#### Returns #### Returns
- `List[Union[Dict[str, Any], str]]`: A list of final metadata for each task, either as a dictionary or a string. - `List[Union[Dict[str, Any], str]]`: A list of final metadata for each task.
#### Example #### Example
@ -204,96 +144,7 @@ results = workflow.run_batched(tasks)
print(results) print(results)
``` ```
### ConcurrentWorkflow.run_async
Runs the workflow asynchronously for the given task.
#### Parameters
| Parameter | Type | Description |
|-------------|--------------|-----------------------------------------------------------|
| `task` | `str` | The task or query to give to all agents. |
#### Returns
- `asyncio.Future`: A future object representing the asynchronous operation.
#### Example
```python
async def run_async_example():
future = workflow.run_async(task="Example task")
result = await future
print(result)
```
### ConcurrentWorkflow.run_batched_async
Runs the workflow asynchronously for a batch of tasks.
#### Parameters
| Parameter | Type | Description |
|-------------|--------------|-----------------------------------------------------------|
| `tasks` | `List[str]` | A list of tasks or queries to give to all agents. |
#### Returns
- `List[asyncio.Future]`: A list of future objects representing the asynchronous operations for each task.
#### Example
```python
tasks = ["Task 1", "Task 2"]
futures = workflow.run_batched_async(tasks)
results = await asyncio.gather(*futures)
print(results)
```
### ConcurrentWorkflow.run_parallel
Runs the workflow in parallel for a batch of tasks.
#### Parameters
| Parameter | Type | Description |
|-------------|--------------|-----------------------------------------------------------|
| `tasks` | `List[str]` | A list of tasks or queries to give to all agents. |
#### Returns
- `List[Union[Dict[str, Any], str]]`: A list of final metadata for each task, either as a dictionary or a string.
#### Example
```python
tasks = ["Task 1", "Task 2"]
results = workflow.run_parallel(tasks)
print(results)
```
### ConcurrentWorkflow.run_parallel_async
Runs the workflow in parallel asynchronously for a batch of tasks.
#### Parameters
| Parameter | Type | Description |
|-------------|--------------|-----------------------------------------------------------|
| `tasks` | `List[str]` | A list of tasks or queries to give to all agents. |
#### Returns
- `List[asyncio.Future]`: A list of future objects representing the asynchronous operations for each task.
#### Example
```python
tasks = ["Task 1", "Task 2"]
futures = workflow.run_parallel_async(tasks)
results = await asyncio.gather(*futures)
print(results)
```
## Usage Examples ## Usage Examples
@ -303,15 +154,6 @@ print(results)
import os import os
from swarms import Agent, ConcurrentWorkflow, OpenAIChat from swarms import Agent, ConcurrentWorkflow, OpenAIChat
# Initialize agents
model = OpenAIChat(
api_key=os.getenv("OPENAI_API_KEY"),
model_name="gpt-4o-mini",
temperature=0.1,
)
# Define custom system prompts for each social media platform # Define custom system prompts for each social media platform
TWITTER_AGENT_SYS_PROMPT = """ TWITTER_AGENT_SYS_PROMPT = """
You are a Twitter marketing expert specializing in real estate. Your task is to create engaging, concise tweets to promote properties, analyze trends to maximize engagement, and use appropriate hashtags and timing to reach potential buyers. You are a Twitter marketing expert specializing in real estate. Your task is to create engaging, concise tweets to promote properties, analyze trends to maximize engagement, and use appropriate hashtags and timing to reach potential buyers.
@ -338,7 +180,7 @@ agents = [
Agent( Agent(
agent_name="Twitter-RealEstate-Agent", agent_name="Twitter-RealEstate-Agent",
system_prompt=TWITTER_AGENT_SYS_PROMPT, system_prompt=TWITTER_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4o",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="twitter_realestate_agent.json", saved_state_path="twitter_realestate_agent.json",
@ -348,7 +190,7 @@ agents = [
Agent( Agent(
agent_name="Instagram-RealEstate-Agent", agent_name="Instagram-RealEstate-Agent",
system_prompt=INSTAGRAM_AGENT_SYS_PROMPT, system_prompt=INSTAGRAM_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4o",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="instagram_realestate_agent.json", saved_state_path="instagram_realestate_agent.json",
@ -358,7 +200,7 @@ agents = [
Agent( Agent(
agent_name="Facebook-RealEstate-Agent", agent_name="Facebook-RealEstate-Agent",
system_prompt=FACEBOOK_AGENT_SYS_PROMPT, system_prompt=FACEBOOK_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4o",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="facebook_realestate_agent.json", saved_state_path="facebook_realestate_agent.json",
@ -368,7 +210,7 @@ agents = [
Agent( Agent(
agent_name="LinkedIn-RealEstate-Agent", agent_name="LinkedIn-RealEstate-Agent",
system_prompt=LINKEDIN_AGENT_SYS_PROMPT, system_prompt=LINKEDIN_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4o",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="linkedin_realestate_agent.json", saved_state_path="linkedin_realestate_agent.json",
@ -378,7 +220,7 @@ agents = [
Agent( Agent(
agent_name="Email-RealEstate-Agent", agent_name="Email-RealEstate-Agent",
system_prompt=EMAIL_AGENT_SYS_PROMPT, system_prompt=EMAIL_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4o",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="email_realestate_agent.json", saved_state_path="email_realestate_agent.json",
@ -476,28 +318,7 @@ for task, result in zip(tasks, results):
print(f"Result: {result}\n") print(f"Result: {result}\n")
``` ```
### Example 5: Asynchronous Execution
```python
import asyncio
# Initialize workflow
workflow = ConcurrentWorkflow(
name="Real Estate Marketing Swarm",
agents=agents,
metadata_output_path="metadata_async.json",
description="Concurrent swarm of content generators for real estate!",
auto_save=True
)
async def run_async_workflow():
task = "Develop a marketing strategy for a sustainable, off-grid mountain retreat in Colorado."
result = await workflow.run_async(task)
print(result)
# Run the async workflow
asyncio.run(run_async_workflow())
```
## Tips and Best Practices ## Tips and Best Practices

@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"
[tool.poetry] [tool.poetry]
name = "swarms" name = "swarms"
version = "7.4.8" version = "7.5.1"
description = "Swarms - TGSC" description = "Swarms - TGSC"
license = "MIT" license = "MIT"
authors = ["Kye Gomez <kye@apac.ai>"] authors = ["Kye Gomez <kye@apac.ai>"]

@ -80,6 +80,7 @@ from swarms.structs.swarms_api import (
SwarmsAPIClient, SwarmsAPIClient,
SwarmValidationError, SwarmValidationError,
) )
from swarms.structs.agent_builder import AgentsBuilder
__all__ = [ __all__ = [
"Agent", "Agent",
@ -152,4 +153,5 @@ __all__ = [
"SwarmAPIError", "SwarmAPIError",
"SwarmValidationError", "SwarmValidationError",
"AgentInput", "AgentInput",
"AgentsBuilder",
] ]

@ -1,61 +1,131 @@
import os import os
from typing import List from typing import List, Optional, Tuple
from loguru import logger
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from swarms.structs.agent import Agent from swarms import Agent
from swarms.utils.any_to_str import any_to_str
from swarms.utils.function_caller_model import OpenAIFunctionCaller from swarms.utils.function_caller_model import OpenAIFunctionCaller
from swarms.utils.loguru_logger import initialize_logger from swarms.utils.litellm_tokenizer import count_tokens
from swarms.structs.agents_available import showcase_available_agents
from swarms.structs.swarms_api import AgentInput as AgentConfig
logger = initialize_logger(log_folder="auto_swarm_builder")
class Agents(BaseModel):
"""Configuration for a list of agents"""
agents: List[AgentConfig] = Field(
description="The list of agents that make up the swarm",
)
BOSS_SYSTEM_PROMPT = """ BOSS_SYSTEM_PROMPT = """
Manage a swarm of worker agents to efficiently serve the user by deciding whether to create new agents or delegate tasks. Ensure operations are efficient and effective. # Swarm Intelligence Orchestrator
### Instructions: You are the Chief Orchestrator of a sophisticated agent swarm. Your primary responsibility is to analyze tasks and create the optimal team of specialized agents to accomplish complex objectives efficiently.
1. **Task Assignment**: ## Agent Creation Protocol
- Analyze available worker agents when a task is presented.
- Delegate tasks to existing agents with clear, direct, and actionable instructions if an appropriate agent is available. 1. **Task Analysis**:
- If no suitable agent exists, create a new agent with a fitting system prompt to handle the task. - Thoroughly analyze the user's task to identify all required skills, knowledge domains, and subtasks
- Break down complex problems into discrete components that can be assigned to specialized agents
2. **Agent Creation**: - Identify potential challenges and edge cases that might require specialized handling
- Name agents according to the task they are intended to perform (e.g., "Twitter Marketing Agent").
- Provide each new agent with a concise and clear system prompt that includes its role, objectives, and any tools it can utilize. 2. **Agent Design Principles**:
- Create highly specialized agents with clearly defined roles and responsibilities
3. **Efficiency**: - Design each agent with deep expertise in their specific domain
- Minimize redundancy and maximize task completion speed. - Provide agents with comprehensive and extremely extensive system prompts that include:
- Avoid unnecessary agent creation if an existing agent can fulfill the task. * Precise definition of their role and scope of responsibility
* Detailed methodology for approaching problems in their domain
4. **Communication**: * Specific techniques, frameworks, and mental models to apply
- Be explicit in task delegation instructions to avoid ambiguity and ensure effective task execution. * Guidelines for output format and quality standards
- Require agents to report back on task completion or encountered issues. * Instructions for collaboration with other agents
* In-depth examples and scenarios to illustrate expected behavior and decision-making processes
5. **Reasoning and Decisions**: * Extensive background information relevant to the tasks they will undertake
- Offer brief reasoning when selecting or creating agents to maintain transparency.
- Avoid using an agent if unnecessary, with a clear explanation if no agents are suitable for a task. 3. **Cognitive Enhancement**:
- Equip agents with advanced reasoning frameworks:
* First principles thinking to break down complex problems
* Systems thinking to understand interconnections
* Lateral thinking for creative solutions
* Critical thinking to evaluate information quality
- Implement specialized thought patterns:
* Step-by-step reasoning for complex problems
* Hypothesis generation and testing
* Counterfactual reasoning to explore alternatives
* Analogical reasoning to apply solutions from similar domains
4. **Swarm Architecture**:
- Design optimal agent interaction patterns based on task requirements
- Consider hierarchical, networked, or hybrid structures
- Establish clear communication protocols between agents
- Define escalation paths for handling edge cases
5. **Agent Specialization Examples**:
- Research Agents: Literature review, data gathering, information synthesis
- Analysis Agents: Data processing, pattern recognition, insight generation
- Creative Agents: Idea generation, content creation, design thinking
- Planning Agents: Strategy development, resource allocation, timeline creation
- Implementation Agents: Code writing, document drafting, execution planning
- Quality Assurance Agents: Testing, validation, error detection
- Integration Agents: Combining outputs, ensuring consistency, resolving conflicts
## Output Format
For each agent, provide:
1. **Agent Name**: Clear, descriptive title reflecting specialization
2. **Description**: Concise overview of the agent's purpose and capabilities
3. **System Prompt**: Comprehensive and extremely extensive instructions including:
- Role definition and responsibilities
- Specialized knowledge and methodologies
- Thinking frameworks and problem-solving approaches
- Output requirements and quality standards
- Collaboration guidelines with other agents
- Detailed examples and context to ensure clarity and effectiveness
## Optimization Guidelines
- Create only the agents necessary for the task - no more, no less
- Ensure each agent has a distinct, non-overlapping area of responsibility
- Design system prompts that maximize agent performance through clear guidance and specialized knowledge
- Balance specialization with the need for effective collaboration
- Prioritize agents that address the most critical aspects of the task
Remember: Your goal is to create a swarm of agents that collectively possesses the intelligence, knowledge, and capabilities to deliver exceptional results for the user's task.
"""
# Output Format
Present your plan in clear, bullet-point format or short concise paragraphs, outlining task assignment, agent creation, efficiency strategies, and communication protocols. class AgentSpec(BaseModel):
agent_name: Optional[str] = Field(
None,
description="The unique name assigned to the agent, which identifies its role and functionality within the swarm.",
)
description: Optional[str] = Field(
None,
description="A detailed explanation of the agent's purpose, capabilities, and any specific tasks it is designed to perform.",
)
system_prompt: Optional[str] = Field(
None,
description="The initial instruction or context provided to the agent, guiding its behavior and responses during execution.",
)
model_name: Optional[str] = Field(
description="The name of the AI model that the agent will utilize for processing tasks and generating outputs. For example: gpt-4o, gpt-4o-mini, openai/o3-mini"
)
auto_generate_prompt: Optional[bool] = Field(
description="A flag indicating whether the agent should automatically create prompts based on the task requirements."
)
max_tokens: Optional[int] = Field(
None,
description="The maximum number of tokens that the agent is allowed to generate in its responses, limiting output length.",
)
temperature: Optional[float] = Field(
description="A parameter that controls the randomness of the agent's output; lower values result in more deterministic responses."
)
role: Optional[str] = Field(
description="The designated role of the agent within the swarm, which influences its behavior and interaction with other agents."
)
max_loops: Optional[int] = Field(
description="The maximum number of times the agent is allowed to repeat its task, enabling iterative processing if necessary."
)
# Notes
- Preserve transparency by always providing reasoning for task-agent assignments and creation. class Agents(BaseModel):
- Ensure instructions to agents are unambiguous to minimize error. """Configuration for a collection of agents that work together as a swarm to accomplish tasks."""
""" agents: List[AgentSpec] = Field(
description="A list containing the specifications of each agent that will participate in the swarm, detailing their roles and functionalities."
)
class AgentsBuilder: class AgentsBuilder:
@ -74,8 +144,8 @@ class AgentsBuilder:
def __init__( def __init__(
self, self,
name: str = None, name: str = "swarm-creator-01",
description: str = None, description: str = "This is a swarm that creates swarms",
verbose: bool = True, verbose: bool = True,
max_loops: int = 1, max_loops: int = 1,
): ):
@ -89,7 +159,9 @@ class AgentsBuilder:
f"Initialized AutoSwarmBuilder: {name} {description}" f"Initialized AutoSwarmBuilder: {name} {description}"
) )
def run(self, task: str, image_url: str = None, *args, **kwargs): def run(
self, task: str, image_url: str = None, *args, **kwargs
) -> Tuple[List[Agent], int]:
"""Run the swarm on a given task. """Run the swarm on a given task.
Args: Args:
@ -102,9 +174,11 @@ class AgentsBuilder:
The output from the swarm's execution The output from the swarm's execution
""" """
logger.info(f"Running swarm on task: {task}") logger.info(f"Running swarm on task: {task}")
agents = self._create_agents(task, image_url, *args, **kwargs) agents, tokens = self._create_agents(
task, image_url, *args, **kwargs
)
return agents return agents, tokens
def _create_agents(self, task: str, *args, **kwargs): def _create_agents(self, task: str, *args, **kwargs):
"""Create the necessary agents for a task. """Create the necessary agents for a task.
@ -123,29 +197,37 @@ class AgentsBuilder:
api_key=os.getenv("OPENAI_API_KEY"), api_key=os.getenv("OPENAI_API_KEY"),
temperature=0.1, temperature=0.1,
base_model=Agents, base_model=Agents,
model_name="gpt-4o",
) )
agents_dictionary = model.run(task) agents_dictionary = model.run(task)
logger.info(f"Agents dictionary: {agents_dictionary}")
# Convert dictionary to SwarmConfig if needed logger.info("Agents successfully created")
if isinstance(agents_dictionary, dict): logger.info(f"Agents: {len(agents_dictionary.agents)}")
agents_dictionary = Agents(**agents_dictionary)
total_tokens = any_to_str(agents_dictionary)
tokens = count_tokens(total_tokens)
# logger.info(f"Tokens: {tokens}")
# # Convert dictionary to SwarmConfig if needed
# if isinstance(agents_dictionary, dict):
# agents_dictionary = Agents(**agents_dictionary)
# Create agents from config # Create agents from config
agents = [] agents = []
for agent_config in agents_dictionary.agents: for agent_config in agents_dictionary.agents:
# Convert dict to AgentConfig if needed # Convert dict to AgentConfig if needed
if isinstance(agent_config, dict): if isinstance(agent_config, dict):
agent_config = AgentConfig(**agent_config) agent_config = Agents(**agent_config)
agent = self.build_agent( agent = self.build_agent(
agent_name=agent_config.name, agent_name=agent_config.model_name,
agent_description=agent_config.description, agent_description=agent_config.description,
agent_system_prompt=agent_config.system_prompt, agent_system_prompt=agent_config.system_prompt,
model_name=agent_config.model_name, model_name=agent_config.model_name,
max_loops=agent_config.max_loops, max_loops=agent_config.max_loops,
dynamic_temperature_enabled=agent_config.dynamic_temperature_enabled, dynamic_temperature_enabled=True,
auto_generate_prompt=agent_config.auto_generate_prompt, auto_generate_prompt=agent_config.auto_generate_prompt,
role=agent_config.role, role=agent_config.role,
max_tokens=agent_config.max_tokens, max_tokens=agent_config.max_tokens,
@ -153,17 +235,7 @@ class AgentsBuilder:
) )
agents.append(agent) agents.append(agent)
# Showcasing available agents return agents, tokens
agents_available = showcase_available_agents(
name=self.name,
description=self.description,
agents=agents,
)
for agent in agents:
agent.system_prompt += "\n" + agents_available
return agents
def build_agent( def build_agent(
self, self,

@ -1,4 +1,3 @@
import asyncio
import os import os
import uuid import uuid
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
@ -10,7 +9,6 @@ from pydantic import BaseModel, Field
from swarms.structs.agent import Agent from swarms.structs.agent import Agent
from swarms.structs.base_swarm import BaseSwarm from swarms.structs.base_swarm import BaseSwarm
from swarms.utils.file_processing import create_file_in_folder from swarms.utils.file_processing import create_file_in_folder
import concurrent.futures
from swarms.utils.loguru_logger import initialize_logger from swarms.utils.loguru_logger import initialize_logger
from swarms.structs.conversation import Conversation from swarms.structs.conversation import Conversation
from swarms.structs.swarm_id_generator import generate_swarm_id from swarms.structs.swarm_id_generator import generate_swarm_id
@ -255,7 +253,7 @@ class ConcurrentWorkflow(BaseSwarm):
) )
self.conversation.add( self.conversation.add(
"user", "User",
task, task,
) )
@ -393,105 +391,6 @@ class ConcurrentWorkflow(BaseSwarm):
results.append(result) results.append(result)
return results return results
def run_async(self, task: str) -> asyncio.Future:
"""
Runs the workflow asynchronously for the given task, executes agents concurrently, and saves metadata in a production-grade manner.
Args:
task (str): The task or query to give to all agents.
Returns:
asyncio.Future: A future object representing the asynchronous operation.
Example:
>>> async def run_async_example():
>>> future = workflow.run_async(task="Example task")
>>> result = await future
>>> print(result)
"""
logger.info(
f"Running concurrent workflow asynchronously with {len(self.agents)} agents."
)
return asyncio.ensure_future(self.run(task))
def run_batched_async(
self, tasks: List[str]
) -> List[asyncio.Future]:
"""
Runs the workflow asynchronously for a batch of tasks, executes agents concurrently for each task, and saves metadata in a production-grade manner.
Args:
tasks (List[str]): A list of tasks or queries to give to all agents.
Returns:
List[asyncio.Future]: A list of future objects representing the asynchronous operations for each task.
Example:
>>> tasks = ["Task 1", "Task 2"]
>>> futures = workflow.run_batched_async(tasks)
>>> results = await asyncio.gather(*futures)
>>> print(results)
"""
futures = []
for task in tasks:
future = self.run_async(task)
futures.append(future)
return futures
def run_parallel(
self, tasks: List[str]
) -> List[Union[Dict[str, Any], str]]:
"""
Runs the workflow in parallel for a batch of tasks, executes agents concurrently for each task, and saves metadata in a production-grade manner.
Args:
tasks (List[str]): A list of tasks or queries to give to all agents.
Returns:
List[Union[Dict[str, Any], str]]: A list of final metadata for each task, either as a dictionary or a string.
Example:
>>> tasks = ["Task 1", "Task 2"]
>>> results = workflow.run_parallel(tasks)
>>> print(results)
"""
with ThreadPoolExecutor(
max_workers=os.cpu_count()
) as executor:
futures = {
executor.submit(self.run, task): task
for task in tasks
}
results = []
for future in concurrent.futures.as_completed(futures):
result = future.result()
results.append(result)
return results
def run_parallel_async(
self, tasks: List[str]
) -> List[asyncio.Future]:
"""
Runs the workflow in parallel asynchronously for a batch of tasks, executes agents concurrently for each task, and saves metadata in a production-grade manner.
Args:
tasks (List[str]): A list of tasks or queries to give to all agents.
Returns:
List[asyncio.Future]: A list of future objects representing the asynchronous operations for each task.
Example:
>>> tasks = ["Task 1", "Task 2"]
>>> futures = workflow.run_parallel_async(tasks)
>>> results = await asyncio.gather(*futures)
>>> print(results)
"""
futures = []
for task in tasks:
future = self.run_async(task)
futures.append(future)
return futures
# if __name__ == "__main__": # if __name__ == "__main__":
# # Assuming you've already initialized some agents outside of this class # # Assuming you've already initialized some agents outside of this class

@ -25,12 +25,11 @@ class AgentInput(BaseModel):
) )
system_prompt: Optional[str] = Field( system_prompt: Optional[str] = Field(
None, None,
description="The initial prompt or instructions given to the agent, up to 500 characters.", description="The initial prompt or instructions given to the agent.",
) )
model_name: Optional[str] = Field( model_name: Optional[str] = Field(
"gpt-4o", "gpt-4o",
description="The name of the model used by the agent, limited to 500 characters.", description="The name of the model used by the agent. Model names can be configured like provider/model_name",
max_length=500,
) )
auto_generate_prompt: Optional[bool] = Field( auto_generate_prompt: Optional[bool] = Field(
False, False,

Loading…
Cancel
Save