swarms 7.7.2__py3-none-any.whl → 7.7.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. swarms/prompts/ag_prompt.py +51 -19
  2. swarms/prompts/agent_system_prompts.py +13 -4
  3. swarms/prompts/multi_agent_collab_prompt.py +18 -0
  4. swarms/prompts/prompt.py +6 -10
  5. swarms/schemas/__init__.py +0 -3
  6. swarms/structs/__init__.py +2 -4
  7. swarms/structs/agent.py +201 -160
  8. swarms/structs/aop.py +8 -1
  9. swarms/structs/auto_swarm_builder.py +271 -210
  10. swarms/structs/conversation.py +22 -65
  11. swarms/structs/hiearchical_swarm.py +93 -122
  12. swarms/structs/ma_utils.py +96 -0
  13. swarms/structs/mixture_of_agents.py +20 -103
  14. swarms/structs/multi_agent_router.py +32 -95
  15. swarms/structs/output_types.py +3 -16
  16. swarms/structs/stopping_conditions.py +30 -0
  17. swarms/structs/swarm_router.py +56 -4
  18. swarms/structs/swarming_architectures.py +576 -185
  19. swarms/telemetry/main.py +1 -7
  20. swarms/tools/mcp_client.py +209 -53
  21. swarms/tools/mcp_integration.py +1 -53
  22. swarms/utils/generate_keys.py +64 -0
  23. swarms/utils/history_output_formatter.py +2 -0
  24. {swarms-7.7.2.dist-info → swarms-7.7.3.dist-info}/METADATA +98 -263
  25. {swarms-7.7.2.dist-info → swarms-7.7.3.dist-info}/RECORD +28 -32
  26. swarms/schemas/agent_input_schema.py +0 -149
  27. swarms/structs/agents_available.py +0 -87
  28. swarms/structs/graph_swarm.py +0 -612
  29. swarms/structs/queue_swarm.py +0 -193
  30. swarms/structs/swarm_builder.py +0 -395
  31. swarms/structs/swarm_output_type.py +0 -23
  32. {swarms-7.7.2.dist-info → swarms-7.7.3.dist-info}/LICENSE +0 -0
  33. {swarms-7.7.2.dist-info → swarms-7.7.3.dist-info}/WHEEL +0 -0
  34. {swarms-7.7.2.dist-info → swarms-7.7.3.dist-info}/entry_points.txt +0 -0
@@ -1,107 +1,131 @@
1
1
  import os
2
2
  from typing import List
3
-
3
+ from loguru import logger
4
4
  from pydantic import BaseModel, Field
5
5
 
6
6
  from swarms.structs.agent import Agent
7
7
  from swarms.utils.function_caller_model import OpenAIFunctionCaller
8
- from swarms.structs.swarm_router import SwarmRouter
9
- from swarms.utils.loguru_logger import initialize_logger
10
- from swarms.structs.agents_available import showcase_available_agents
8
+ from swarms.structs.ma_utils import set_random_models_for_agents
9
+ from swarms.structs.swarm_router import SwarmRouter, SwarmRouterConfig
10
+ from dotenv import load_dotenv
11
+
12
+
13
+ load_dotenv()
11
14
 
12
- logger = initialize_logger(log_folder="auto_swarm_builder")
15
+ BOSS_SYSTEM_PROMPT = """
16
+ You are an expert swarm manager and agent architect. Your role is to create and coordinate a team of specialized AI agents, each with distinct personalities, roles, and capabilities. Your primary goal is to ensure the swarm operates efficiently while maintaining clear communication and well-defined responsibilities.
17
+
18
+ ### Core Principles:
19
+
20
+ 1. **Deep Task Understanding**:
21
+ - First, thoroughly analyze the task requirements, breaking them down into core components and sub-tasks
22
+ - Identify the necessary skills, knowledge domains, and personality traits needed for each component
23
+ - Consider potential challenges, dependencies, and required coordination between agents
24
+ - Map out the ideal workflow and information flow between agents
25
+
26
+ 2. **Agent Design Philosophy**:
27
+ - Each agent must have a clear, specific purpose and domain of expertise
28
+ - Agents should have distinct personalities that complement their roles
29
+ - Design agents to be self-aware of their limitations and when to seek help
30
+ - Ensure agents can effectively communicate their progress and challenges
31
+
32
+ 3. **Agent Creation Framework**:
33
+ For each new agent, define:
34
+ - **Role & Purpose**: Clear, specific description of what the agent does and why
35
+ - **Personality Traits**: Distinct characteristics that influence how the agent thinks and communicates
36
+ - **Expertise Level**: Specific knowledge domains and skill sets
37
+ - **Communication Style**: How the agent presents information and interacts
38
+ - **Decision-Making Process**: How the agent approaches problems and makes choices
39
+ - **Limitations & Boundaries**: What the agent cannot or should not do
40
+ - **Collaboration Protocol**: How the agent works with others
41
+
42
+ 4. **System Prompt Design**:
43
+ Create detailed system prompts that include:
44
+ - Role and purpose explanation
45
+ - Personality description and behavioral guidelines
46
+ - Specific capabilities and tools available
47
+ - Communication protocols and reporting requirements
48
+ - Problem-solving approach and decision-making framework
49
+ - Collaboration guidelines and team interaction rules
50
+ - Quality standards and success criteria
51
+
52
+ 5. **Swarm Coordination**:
53
+ - Design clear communication channels between agents
54
+ - Establish protocols for task handoffs and information sharing
55
+ - Create feedback loops for continuous improvement
56
+ - Implement error handling and recovery procedures
57
+ - Define escalation paths for complex issues
58
+
59
+ 6. **Quality Assurance**:
60
+ - Set clear success criteria for each agent and the overall swarm
61
+ - Implement verification steps for task completion
62
+ - Create mechanisms for self-assessment and improvement
63
+ - Establish protocols for handling edge cases and unexpected situations
64
+
65
+ ### Output Format:
66
+
67
+ When creating a new agent or swarm, provide:
68
+
69
+ 1. **Agent Design**:
70
+ - Role and purpose statement
71
+ - Personality profile
72
+ - Capabilities and limitations
73
+ - Communication style
74
+ - Collaboration protocols
75
+
76
+ 2. **System Prompt**:
77
+ - Complete, detailed prompt that embodies the agent's identity
78
+ - Clear instructions for behavior and decision-making
79
+ - Specific guidelines for interaction and reporting
80
+
81
+ 3. **Swarm Architecture**:
82
+ - Team structure and hierarchy
83
+ - Communication flow
84
+ - Task distribution plan
85
+ - Quality control measures
86
+
87
+ ### Notes:
88
+
89
+ - Always prioritize clarity and specificity in agent design
90
+ - Ensure each agent has a unique, well-defined role
91
+ - Create detailed, comprehensive system prompts
92
+ - Maintain clear documentation of agent capabilities and limitations
93
+ - Design for scalability and adaptability
94
+ - Focus on creating agents that can work together effectively
95
+ - Consider edge cases and potential failure modes
96
+ - Implement robust error handling and recovery procedures
97
+ """
13
98
 
14
99
 
15
100
  class AgentConfig(BaseModel):
16
101
  """Configuration for an individual agent in a swarm"""
17
102
 
18
103
  name: str = Field(
19
- description="The name of the agent", example="Research-Agent"
104
+ description="The name of the agent",
20
105
  )
21
106
  description: str = Field(
22
107
  description="A description of the agent's purpose and capabilities",
23
- example="Agent responsible for researching and gathering information",
24
108
  )
25
109
  system_prompt: str = Field(
26
110
  description="The system prompt that defines the agent's behavior",
27
- example="You are a research agent. Your role is to gather and analyze information...",
28
111
  )
112
+
29
113
  # max_loops: int = Field(
30
- # description="Maximum number of reasoning loops the agent can perform",
31
- # example=3,
114
+ # description="The maximum number of loops for the agent to run",
32
115
  # )
33
116
 
117
+ class Config:
118
+ arbitrary_types_allowed = True
34
119
 
35
- class SwarmConfig(BaseModel):
36
- """Configuration for a swarm of cooperative agents"""
37
120
 
38
- name: str = Field(
39
- description="The name of the swarm",
40
- example="Research-Writing-Swarm",
41
- )
42
- description: str = Field(
43
- description="The description of the swarm's purpose and capabilities",
44
- example="A swarm of agents that work together to research topics and write articles",
45
- )
121
+ class AgentsConfig(BaseModel):
122
+ """Configuration for a list of agents in a swarm"""
123
+
46
124
  agents: List[AgentConfig] = Field(
47
- description="The list of agents that make up the swarm",
48
- example=[
49
- AgentConfig(
50
- name="Research-Agent",
51
- description="Gathers information",
52
- system_prompt="You are a research agent...",
53
- ),
54
- AgentConfig(
55
- name="Writing-Agent",
56
- description="Writes content",
57
- system_prompt="You are a writing agent...",
58
- ),
59
- ],
60
- )
61
- max_loops: int = Field(
62
- description="The maximum number of loops to run the swarm",
63
- example=1,
125
+ description="A list of agent configurations",
64
126
  )
65
127
 
66
128
 
67
- BOSS_SYSTEM_PROMPT = """
68
- 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.
69
-
70
- ### Instructions:
71
-
72
- 1. **Task Assignment**:
73
- - Analyze available worker agents when a task is presented.
74
- - Delegate tasks to existing agents with clear, direct, and actionable instructions if an appropriate agent is available.
75
- - If no suitable agent exists, create a new agent with a fitting system prompt to handle the task.
76
-
77
- 2. **Agent Creation**:
78
- - Name agents according to the task they are intended to perform (e.g., "Twitter Marketing Agent").
79
- - Provide each new agent with a concise and clear system prompt that includes its role, objectives, and any tools it can utilize.
80
-
81
- 3. **Efficiency**:
82
- - Minimize redundancy and maximize task completion speed.
83
- - Avoid unnecessary agent creation if an existing agent can fulfill the task.
84
-
85
- 4. **Communication**:
86
- - Be explicit in task delegation instructions to avoid ambiguity and ensure effective task execution.
87
- - Require agents to report back on task completion or encountered issues.
88
-
89
- 5. **Reasoning and Decisions**:
90
- - Offer brief reasoning when selecting or creating agents to maintain transparency.
91
- - Avoid using an agent if unnecessary, with a clear explanation if no agents are suitable for a task.
92
-
93
- # Output Format
94
-
95
- Present your plan in clear, bullet-point format or short concise paragraphs, outlining task assignment, agent creation, efficiency strategies, and communication protocols.
96
-
97
- # Notes
98
-
99
- - Preserve transparency by always providing reasoning for task-agent assignments and creation.
100
- - Ensure instructions to agents are unambiguous to minimize error.
101
-
102
- """
103
-
104
-
105
129
  class AutoSwarmBuilder:
106
130
  """A class that automatically builds and manages swarms of AI agents.
107
131
 
@@ -114,6 +138,7 @@ class AutoSwarmBuilder:
114
138
  description (str): A description of the swarm's purpose
115
139
  verbose (bool, optional): Whether to output detailed logs. Defaults to True.
116
140
  max_loops (int, optional): Maximum number of execution loops. Defaults to 1.
141
+ random_models (bool, optional): Whether to use random models for agents. Defaults to True.
117
142
  """
118
143
 
119
144
  def __init__(
@@ -122,183 +147,219 @@ class AutoSwarmBuilder:
122
147
  description: str = None,
123
148
  verbose: bool = True,
124
149
  max_loops: int = 1,
150
+ random_models: bool = True,
125
151
  ):
152
+ """Initialize the AutoSwarmBuilder.
153
+
154
+ Args:
155
+ name (str): The name of the swarm
156
+ description (str): A description of the swarm's purpose
157
+ verbose (bool): Whether to output detailed logs
158
+ max_loops (int): Maximum number of execution loops
159
+ random_models (bool): Whether to use random models for agents
160
+ """
126
161
  self.name = name
127
162
  self.description = description
128
163
  self.verbose = verbose
129
164
  self.max_loops = max_loops
130
- self.agents_pool = []
165
+ self.random_models = random_models
166
+
131
167
  logger.info(
132
- f"Initialized AutoSwarmBuilder: {name} {description}"
168
+ f"Initializing AutoSwarmBuilder with name: {name}, description: {description}"
133
169
  )
134
170
 
135
- # @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
136
- def run(self, task: str, image_url: str = None, *args, **kwargs):
171
+ def run(self, task: str, *args, **kwargs):
137
172
  """Run the swarm on a given task.
138
173
 
139
174
  Args:
140
- task (str): The task to be accomplished
141
- image_url (str, optional): URL of an image input if needed. Defaults to None.
142
- *args: Variable length argument list
143
- **kwargs: Arbitrary keyword arguments
175
+ task (str): The task to execute
176
+ *args: Additional positional arguments
177
+ **kwargs: Additional keyword arguments
144
178
 
145
179
  Returns:
146
- The output from the swarm's execution
147
- """
148
- logger.info(f"Running swarm on task: {task}")
149
- agents = self._create_agents(task, image_url, *args, **kwargs)
150
- logger.info(f"Agents created {len(agents)}")
151
- logger.info("Routing task through swarm")
152
- output = self.swarm_router(agents, task, image_url)
153
- logger.info(f"Swarm execution complete with output: {output}")
154
- return output
155
-
156
- # @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
157
- def _create_agents(self, task: str, *args, **kwargs):
158
- """Create the necessary agents for a task.
180
+ Any: The result of the swarm execution
159
181
 
160
- Args:
161
- task (str): The task to create agents for
162
- *args: Variable length argument list
163
- **kwargs: Arbitrary keyword arguments
164
-
165
- Returns:
166
- list: List of created agents
182
+ Raises:
183
+ Exception: If there's an error during execution
167
184
  """
168
- logger.info("Creating agents for task")
169
- model = OpenAIFunctionCaller(
170
- system_prompt=BOSS_SYSTEM_PROMPT,
171
- api_key=os.getenv("OPENAI_API_KEY"),
172
- temperature=0.1,
173
- base_model=SwarmConfig,
174
- )
175
-
176
- agents_dictionary = model.run(task)
177
- logger.info(f"Agents dictionary: {agents_dictionary}")
185
+ try:
186
+ logger.info(f"Starting swarm execution for task: {task}")
187
+ agents = self.create_agents(task)
188
+ logger.info(f"Created {len(agents)} agents")
178
189
 
179
- # Convert dictionary to SwarmConfig if needed
180
- if isinstance(agents_dictionary, dict):
181
- agents_dictionary = SwarmConfig(**agents_dictionary)
190
+ if self.random_models:
191
+ logger.info("Setting random models for agents")
192
+ agents = set_random_models_for_agents(agents=agents)
182
193
 
183
- # Set swarm config
184
- self.name = agents_dictionary.name
185
- self.description = agents_dictionary.description
186
- self.max_loops = getattr(
187
- agents_dictionary
188
- ) # Default to 1 if not set
194
+ return self.initialize_swarm_router(
195
+ agents=agents, task=task
196
+ )
197
+ except Exception as e:
198
+ logger.error(
199
+ f"Error in swarm execution: {str(e)}", exc_info=True
200
+ )
201
+ raise
189
202
 
190
- logger.info(
191
- f"Swarm config: {self.name}, {self.description}, {self.max_loops}"
192
- )
203
+ def create_agents(self, task: str):
204
+ """Create agents for a given task.
193
205
 
194
- # Create agents from config
195
- agents = []
196
- for agent_config in agents_dictionary.agents:
197
- # Convert dict to AgentConfig if needed
198
- if isinstance(agent_config, dict):
199
- agent_config = AgentConfig(**agent_config)
200
-
201
- agent = self.build_agent(
202
- agent_name=agent_config.name,
203
- agent_description=agent_config.description,
204
- agent_system_prompt=agent_config.system_prompt,
205
- )
206
- agents.append(agent)
206
+ Args:
207
+ task (str): The task to create agents for
207
208
 
208
- # Showcasing available agents
209
- agents_available = showcase_available_agents(
210
- name=self.name,
211
- description=self.description,
212
- agents=agents,
213
- )
209
+ Returns:
210
+ List[Agent]: List of created agents
214
211
 
215
- for agent in agents:
216
- agent.system_prompt += "\n" + agents_available
212
+ Raises:
213
+ Exception: If there's an error during agent creation
214
+ """
215
+ try:
216
+ logger.info(f"Creating agents for task: {task}")
217
+ model = OpenAIFunctionCaller(
218
+ system_prompt=BOSS_SYSTEM_PROMPT,
219
+ api_key=os.getenv("OPENAI_API_KEY"),
220
+ temperature=0.5,
221
+ base_model=AgentsConfig,
222
+ )
217
223
 
218
- return agents
224
+ logger.info(
225
+ "Getting agent configurations from boss agent"
226
+ )
227
+ output = model.run(
228
+ f"Create the agents for the following task: {task}"
229
+ )
230
+ logger.debug(
231
+ f"Received agent configurations: {output.model_dump()}"
232
+ )
233
+ output = output.model_dump()
234
+
235
+ agents = []
236
+ if isinstance(output, dict):
237
+ for agent_config in output["agents"]:
238
+ logger.info(
239
+ f"Building agent: {agent_config['name']}"
240
+ )
241
+ agent = self.build_agent(
242
+ agent_name=agent_config["name"],
243
+ agent_description=agent_config["description"],
244
+ agent_system_prompt=agent_config[
245
+ "system_prompt"
246
+ ],
247
+ )
248
+ agents.append(agent)
249
+ logger.info(
250
+ f"Successfully built agent: {agent_config['name']}"
251
+ )
252
+
253
+ return agents
254
+ except Exception as e:
255
+ logger.error(
256
+ f"Error creating agents: {str(e)}", exc_info=True
257
+ )
258
+ raise
219
259
 
220
260
  def build_agent(
221
261
  self,
222
262
  agent_name: str,
223
263
  agent_description: str,
224
264
  agent_system_prompt: str,
225
- max_loops: int = 1,
226
- ):
227
- """Build a single agent with the given specifications.
265
+ ) -> Agent:
266
+ """Build a single agent with enhanced error handling.
228
267
 
229
268
  Args:
230
269
  agent_name (str): Name of the agent
231
- agent_description (str): Description of the agent's purpose
232
- agent_system_prompt (str): The system prompt for the agent
270
+ agent_description (str): Description of the agent
271
+ agent_system_prompt (str): System prompt for the agent
233
272
 
234
273
  Returns:
235
- Agent: The constructed agent instance
274
+ Agent: The constructed agent
275
+
276
+ Raises:
277
+ Exception: If there's an error during agent construction
236
278
  """
237
279
  logger.info(f"Building agent: {agent_name}")
238
- agent = Agent(
239
- agent_name=agent_name,
240
- description=agent_description,
241
- system_prompt=agent_system_prompt,
242
- model_name="gpt-4o",
243
- max_loops=max_loops,
244
- autosave=True,
245
- dashboard=False,
246
- verbose=True,
247
- dynamic_temperature_enabled=True,
248
- saved_state_path=f"{agent_name}.json",
249
- user_name="swarms_corp",
250
- retry_attempts=1,
251
- context_length=200000,
252
- return_step_meta=False,
253
- output_type="str", # "json", "dict", "csv" OR "string" soon "yaml" and
254
- streaming_on=False,
255
- auto_generate_prompt=True,
256
- )
257
-
258
- return agent
280
+ try:
281
+ agent = Agent(
282
+ agent_name=agent_name,
283
+ description=agent_description,
284
+ system_prompt=agent_system_prompt,
285
+ verbose=self.verbose,
286
+ dynamic_temperature_enabled=False,
287
+ )
288
+ logger.info(f"Successfully built agent: {agent_name}")
289
+ return agent
290
+ except Exception as e:
291
+ logger.error(
292
+ f"Error building agent {agent_name}: {str(e)}",
293
+ exc_info=True,
294
+ )
295
+ raise
259
296
 
260
- def swarm_router(
261
- self,
262
- agents: List[Agent],
263
- task: str,
264
- image_url: str = None,
265
- *args,
266
- **kwargs,
267
- ):
268
- """Route tasks between agents in the swarm.
297
+ def initialize_swarm_router(self, agents: List[Agent], task: str):
298
+ """Initialize and run the swarm router.
269
299
 
270
300
  Args:
271
- agents (List[Agent]): List of available agents
272
- task (str): The task to route
273
- image_url (str, optional): URL of an image input if needed. Defaults to None.
274
- *args: Variable length argument list
275
- **kwargs: Arbitrary keyword arguments
301
+ agents (List[Agent]): List of agents to use
302
+ task (str): The task to execute
276
303
 
277
304
  Returns:
278
- The output from the routed task execution
305
+ Any: The result of the swarm router execution
306
+
307
+ Raises:
308
+ Exception: If there's an error during router initialization or execution
279
309
  """
280
- logger.info("Routing task through swarm")
281
- swarm_router_instance = SwarmRouter(
282
- name=self.name,
283
- description=self.description,
284
- agents=agents,
285
- swarm_type="auto",
286
- max_loops=1,
287
- )
310
+ try:
311
+ logger.info("Initializing swarm router")
312
+ model = OpenAIFunctionCaller(
313
+ system_prompt=BOSS_SYSTEM_PROMPT,
314
+ api_key=os.getenv("OPENAI_API_KEY"),
315
+ temperature=0.5,
316
+ base_model=SwarmRouterConfig,
317
+ )
288
318
 
289
- return swarm_router_instance.run(
290
- self.name + " " + self.description + " " + task,
291
- )
319
+ logger.info("Creating swarm specification")
320
+ swarm_spec = model.run(
321
+ f"Create the swarm spec for the following task: {task}"
322
+ )
323
+ logger.debug(
324
+ f"Received swarm specification: {swarm_spec.model_dump()}"
325
+ )
326
+ swarm_spec = swarm_spec.model_dump()
327
+
328
+ logger.info("Initializing SwarmRouter")
329
+ swarm_router = SwarmRouter(
330
+ name=swarm_spec["name"],
331
+ description=swarm_spec["description"],
332
+ max_loops=1,
333
+ swarm_type=swarm_spec["swarm_type"],
334
+ rearrange_flow=swarm_spec["rearrange_flow"],
335
+ rules=swarm_spec["rules"],
336
+ multi_agent_collab_prompt=swarm_spec[
337
+ "multi_agent_collab_prompt"
338
+ ],
339
+ agents=agents,
340
+ output_type="dict",
341
+ )
292
342
 
343
+ logger.info("Starting swarm router execution")
344
+ return swarm_router.run(task)
345
+ except Exception as e:
346
+ logger.error(
347
+ f"Error in swarm router initialization/execution: {str(e)}",
348
+ exc_info=True,
349
+ )
350
+ raise
293
351
 
294
- # example = AutoSwarmBuilder(
295
- # name="ChipDesign-Swarm",
296
- # description="A swarm of specialized AI agents collaborating on chip architecture, logic design, verification, and optimization to create novel semiconductor designs",
297
- # max_loops=1,
298
- # )
352
+ def batch_run(self, tasks: List[str]):
353
+ """Run the swarm on a list of tasks.
354
+
355
+ Args:
356
+ tasks (List[str]): List of tasks to execute
357
+
358
+ Returns:
359
+ List[Any]: List of results from each task execution
360
+
361
+ Raises:
362
+ Exception: If there's an error during batch execution
363
+ """
299
364
 
300
- # print(
301
- # example.run(
302
- # "Design a new AI accelerator chip optimized for transformer model inference. Consider the following aspects: 1) Overall chip architecture and block diagram 2) Memory hierarchy and interconnects 3) Processing elements and data flow 4) Power and thermal considerations 5) Physical layout recommendations -> "
303
- # )
304
- # )
365
+ return [self.run(task) for task in tasks]