diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index ce410146..f7b48b81 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -228,9 +228,8 @@ nav: - Multi-Agent Collaboration: - Swarms DAO: "swarms/examples/swarms_dao.md" - - Swarms UI: - - Overview: "swarms/ui/main.md" - + - Swarms UI: + - Overview: "swarms/ui/main.md" - Contributors: - Bounty Program: "corporate/bounty_program.md" @@ -304,11 +303,11 @@ nav: # - Tools API: # - Overview: "swarms_platform/tools_api.md" # - Add Tools: "swarms_platform/fetch_tools.md" - - Corporate: - - Culture: "corporate/culture.md" - - Hiring: "corporate/hiring.md" - - Swarms Goals & Milestone Tracking; A Vision for 2024 and Beyond: "corporate/2024_2025_goals.md" - - Web3: - # - Overview: "finance/index.md" - - Swarms Wallet: "finance/wallet.md" - - Swarms Subscription: "finance/subscription.md" + # - Corporate: + # - Culture: "corporate/culture.md" + # - Hiring: "corporate/hiring.md" + # - Swarms Goals & Milestone Tracking; A Vision for 2024 and Beyond: "corporate/2024_2025_goals.md" + # - Web3: + # # - Overview: "finance/index.md" + # - Swarms Wallet: "finance/wallet.md" + # - Swarms Subscription: "finance/subscription.md" diff --git a/docs/swarms/structs/concurrentworkflow.md b/docs/swarms/structs/concurrentworkflow.md index 8269b9fc..a517177b 100644 --- a/docs/swarms/structs/concurrentworkflow.md +++ b/docs/swarms/structs/concurrentworkflow.md @@ -15,34 +15,6 @@ The `ConcurrentWorkflow` class is designed to facilitate the concurrent executio ## 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. ### 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`. | | `agent_responses` | `List[str]` | List of agent responses as strings. | | `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 @@ -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. | | `agents` | `List[Agent]` | `[]` | A list of agents to be executed concurrently. | | `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. | | `max_loops` | `int` | `1` | Maximum number of loops for the workflow. | | `return_str_on` | `bool` | `False` | Flag to return output as string. | | `agent_responses` | `List[str]` | `[]` | List of agent responses as strings. | | `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 @@ -97,26 +75,6 @@ workflow.activate_auto_prompt_engineering() # 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 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. -#### 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 Saves the metadata to a JSON file based on the `auto_save` flag. @@ -166,25 +102,29 @@ workflow.save_metadata() ### ConcurrentWorkflow.run -Runs the workflow for the provided task, executes agents concurrently, and saves metadata. +Executes the workflow for the provided task. #### Parameters -| Parameter | Type | Description | -|-------------|--------------|-----------------------------------------------------------| -| `task` | `str` | The task or query to give to all agents. | +| Parameter | Type | Description | +|-------------|---------------------|-----------------------------------------------------------| +| `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 -- `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 -Runs the workflow for a batch of tasks, executing agents concurrently for each task. +Runs the workflow for a batch of tasks. #### Parameters @@ -194,7 +134,7 @@ Runs the workflow for a batch of tasks, executing agents concurrently for each t #### 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 @@ -204,96 +144,7 @@ results = workflow.run_batched(tasks) 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 @@ -303,15 +154,6 @@ print(results) import os 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 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. @@ -338,7 +180,7 @@ agents = [ Agent( agent_name="Twitter-RealEstate-Agent", system_prompt=TWITTER_AGENT_SYS_PROMPT, - llm=model, + model_name="gpt-4o", max_loops=1, dynamic_temperature_enabled=True, saved_state_path="twitter_realestate_agent.json", @@ -348,7 +190,7 @@ agents = [ Agent( agent_name="Instagram-RealEstate-Agent", system_prompt=INSTAGRAM_AGENT_SYS_PROMPT, - llm=model, + model_name="gpt-4o", max_loops=1, dynamic_temperature_enabled=True, saved_state_path="instagram_realestate_agent.json", @@ -358,7 +200,7 @@ agents = [ Agent( agent_name="Facebook-RealEstate-Agent", system_prompt=FACEBOOK_AGENT_SYS_PROMPT, - llm=model, + model_name="gpt-4o", max_loops=1, dynamic_temperature_enabled=True, saved_state_path="facebook_realestate_agent.json", @@ -368,7 +210,7 @@ agents = [ Agent( agent_name="LinkedIn-RealEstate-Agent", system_prompt=LINKEDIN_AGENT_SYS_PROMPT, - llm=model, + model_name="gpt-4o", max_loops=1, dynamic_temperature_enabled=True, saved_state_path="linkedin_realestate_agent.json", @@ -378,7 +220,7 @@ agents = [ Agent( agent_name="Email-RealEstate-Agent", system_prompt=EMAIL_AGENT_SYS_PROMPT, - llm=model, + model_name="gpt-4o", max_loops=1, dynamic_temperature_enabled=True, saved_state_path="email_realestate_agent.json", @@ -476,28 +318,7 @@ for task, result in zip(tasks, results): 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 diff --git a/pyproject.toml b/pyproject.toml index 4e1df2a9..82fcb8f7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api" [tool.poetry] name = "swarms" -version = "7.4.8" +version = "7.5.1" description = "Swarms - TGSC" license = "MIT" authors = ["Kye Gomez "] diff --git a/swarms/structs/__init__.py b/swarms/structs/__init__.py index 951dc203..81a537e6 100644 --- a/swarms/structs/__init__.py +++ b/swarms/structs/__init__.py @@ -80,6 +80,7 @@ from swarms.structs.swarms_api import ( SwarmsAPIClient, SwarmValidationError, ) +from swarms.structs.agent_builder import AgentsBuilder __all__ = [ "Agent", @@ -152,4 +153,5 @@ __all__ = [ "SwarmAPIError", "SwarmValidationError", "AgentInput", + "AgentsBuilder", ] diff --git a/swarms/structs/agent_builder.py b/swarms/structs/agent_builder.py index d720611f..bcb096e3 100644 --- a/swarms/structs/agent_builder.py +++ b/swarms/structs/agent_builder.py @@ -1,61 +1,131 @@ import os -from typing import List +from typing import List, Optional, Tuple +from loguru import logger 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.loguru_logger import initialize_logger -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", - ) - +from swarms.utils.litellm_tokenizer import count_tokens 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. - -### Instructions: - -1. **Task Assignment**: - - 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. - - If no suitable agent exists, create a new agent with a fitting system prompt to handle the task. - -2. **Agent Creation**: - - 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. - -3. **Efficiency**: - - Minimize redundancy and maximize task completion speed. - - Avoid unnecessary agent creation if an existing agent can fulfill the task. - -4. **Communication**: - - Be explicit in task delegation instructions to avoid ambiguity and ensure effective task execution. - - Require agents to report back on task completion or encountered issues. - -5. **Reasoning and Decisions**: - - 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. +# Swarm Intelligence Orchestrator + +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. + +## Agent Creation Protocol + +1. **Task Analysis**: + - 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 + - Identify potential challenges and edge cases that might require specialized handling + +2. **Agent Design Principles**: + - Create highly specialized agents with clearly defined roles and responsibilities + - Design each agent with deep expertise in their specific domain + - Provide agents with comprehensive and extremely extensive system prompts that include: + * Precise definition of their role and scope of responsibility + * Detailed methodology for approaching problems in their domain + * Specific techniques, frameworks, and mental models to apply + * Guidelines for output format and quality standards + * Instructions for collaboration with other agents + * In-depth examples and scenarios to illustrate expected behavior and decision-making processes + * Extensive background information relevant to the tasks they will undertake + +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. -- Ensure instructions to agents are unambiguous to minimize error. +class Agents(BaseModel): + """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: @@ -74,8 +144,8 @@ class AgentsBuilder: def __init__( self, - name: str = None, - description: str = None, + name: str = "swarm-creator-01", + description: str = "This is a swarm that creates swarms", verbose: bool = True, max_loops: int = 1, ): @@ -89,7 +159,9 @@ class AgentsBuilder: 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. Args: @@ -102,9 +174,11 @@ class AgentsBuilder: The output from the swarm's execution """ 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): """Create the necessary agents for a task. @@ -123,29 +197,37 @@ class AgentsBuilder: api_key=os.getenv("OPENAI_API_KEY"), temperature=0.1, base_model=Agents, + model_name="gpt-4o", ) agents_dictionary = model.run(task) - logger.info(f"Agents dictionary: {agents_dictionary}") - # Convert dictionary to SwarmConfig if needed - if isinstance(agents_dictionary, dict): - agents_dictionary = Agents(**agents_dictionary) + logger.info("Agents successfully created") + logger.info(f"Agents: {len(agents_dictionary.agents)}") + + 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 agents = [] for agent_config in agents_dictionary.agents: # Convert dict to AgentConfig if needed if isinstance(agent_config, dict): - agent_config = AgentConfig(**agent_config) + agent_config = Agents(**agent_config) agent = self.build_agent( - agent_name=agent_config.name, + agent_name=agent_config.model_name, agent_description=agent_config.description, agent_system_prompt=agent_config.system_prompt, model_name=agent_config.model_name, 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, role=agent_config.role, max_tokens=agent_config.max_tokens, @@ -153,17 +235,7 @@ class AgentsBuilder: ) agents.append(agent) - # Showcasing available agents - 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 + return agents, tokens def build_agent( self, diff --git a/swarms/structs/concurrent_workflow.py b/swarms/structs/concurrent_workflow.py index 774f6e03..88654a93 100644 --- a/swarms/structs/concurrent_workflow.py +++ b/swarms/structs/concurrent_workflow.py @@ -1,4 +1,3 @@ -import asyncio import os import uuid from concurrent.futures import ThreadPoolExecutor @@ -10,7 +9,6 @@ from pydantic import BaseModel, Field from swarms.structs.agent import Agent from swarms.structs.base_swarm import BaseSwarm from swarms.utils.file_processing import create_file_in_folder -import concurrent.futures from swarms.utils.loguru_logger import initialize_logger from swarms.structs.conversation import Conversation from swarms.structs.swarm_id_generator import generate_swarm_id @@ -255,7 +253,7 @@ class ConcurrentWorkflow(BaseSwarm): ) self.conversation.add( - "user", + "User", task, ) @@ -393,105 +391,6 @@ class ConcurrentWorkflow(BaseSwarm): results.append(result) 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__": # # Assuming you've already initialized some agents outside of this class diff --git a/swarms/structs/swarms_api.py b/swarms/structs/swarms_api.py index c402714d..d8cf90a8 100644 --- a/swarms/structs/swarms_api.py +++ b/swarms/structs/swarms_api.py @@ -25,12 +25,11 @@ class AgentInput(BaseModel): ) system_prompt: Optional[str] = Field( 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( "gpt-4o", - description="The name of the model used by the agent, limited to 500 characters.", - max_length=500, + description="The name of the model used by the agent. Model names can be configured like provider/model_name", ) auto_generate_prompt: Optional[bool] = Field( False,