From 5555481410cdec345ce4e0f3c4d60ede1f5be742 Mon Sep 17 00:00:00 2001 From: CI-DEV <154627941+IlumCI@users.noreply.github.com> Date: Mon, 1 Dec 2025 10:39:26 +0200 Subject: [PATCH 01/11] Update swarm_router.py --- swarms/structs/swarm_router.py | 35 +++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/swarms/structs/swarm_router.py b/swarms/structs/swarm_router.py index 57a67a12..0d8884d5 100644 --- a/swarms/structs/swarm_router.py +++ b/swarms/structs/swarm_router.py @@ -23,9 +23,10 @@ from swarms.structs.agent_rearrange import AgentRearrange from swarms.structs.batched_grid_workflow import BatchedGridWorkflow from swarms.structs.concurrent_workflow import ConcurrentWorkflow from swarms.structs.council_as_judge import CouncilAsAJudge +from swarms.structs.debate_with_judge import DebateWithJudge from swarms.structs.groupchat import GroupChat from swarms.structs.heavy_swarm import HeavySwarm -from swarms.structs.hiearchical_swarm import HierarchicalSwarm +from swarms.structs.hierarchical_swarm import HierarchicalSwarm from swarms.structs.interactive_groupchat import InteractiveGroupChat from swarms.structs.ma_utils import list_all_agents from swarms.structs.majority_voting import MajorityVoting @@ -58,6 +59,7 @@ SwarmType = Literal[ "HeavySwarm", "BatchedGridWorkflow", "LLMCouncil", + "DebateWithJudge", ] @@ -306,12 +308,23 @@ class SwarmRouter: if ( self.swarm_type != "HeavySwarm" + and self.swarm_type != "DebateWithJudge" and self.agents is None ): raise SwarmRouterConfigError( "SwarmRouter: No agents provided for the swarm. Check the docs to learn of required parameters. https://docs.swarms.world/en/latest/swarms/structs/agent/" ) + if self.swarm_type == "DebateWithJudge": + if self.agents is None or len(self.agents) != 3: + raise SwarmRouterConfigError( + "SwarmRouter: DebateWithJudge requires exactly 3 agents: " + "pro_agent (arguing in favor), con_agent (arguing against), " + "and judge_agent (evaluating and synthesizing). " + f"Provided {len(self.agents) if self.agents else 0} agent(s). " + "Check the docs: https://docs.swarms.world/en/latest/swarms/structs/swarm_router/" + ) + if ( self.swarm_type == "AgentRearrange" and self.rearrange_flow is None @@ -430,6 +443,7 @@ class SwarmRouter: "ConcurrentWorkflow": self._create_concurrent_workflow, "BatchedGridWorkflow": self._create_batched_grid_workflow, "LLMCouncil": self._create_llm_council, + "DebateWithJudge": self._create_debate_with_judge, } def _create_heavy_swarm(self, *args, **kwargs): @@ -457,6 +471,25 @@ class SwarmRouter: chairman_model=self.chairman_model, ) + def _create_debate_with_judge(self, *args, **kwargs): + """Factory function for DebateWithJudge.""" + if len(self.agents) != 3: + raise SwarmRouterConfigError( + "DebateWithJudge requires exactly 3 agents: " + "pro_agent (arguing in favor), con_agent (arguing against), " + "and judge_agent (evaluating and synthesizing). " + f"Provided {len(self.agents)} agent(s)." + ) + + return DebateWithJudge( + pro_agent=self.agents[0], + con_agent=self.agents[1], + judge_agent=self.agents[2], + max_rounds=self.max_loops, + output_type=self.output_type, + verbose=self.verbose, + ) + def _create_agent_rearrange(self, *args, **kwargs): """Factory function for AgentRearrange.""" return AgentRearrange( From 38a21613c6102a988cf4d97aa499d46fdeb83faf Mon Sep 17 00:00:00 2001 From: CI-DEV <154627941+IlumCI@users.noreply.github.com> Date: Mon, 1 Dec 2025 10:41:58 +0200 Subject: [PATCH 02/11] Update swarm_router.md --- docs/swarms/structs/swarm_router.md | 59 +++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/docs/swarms/structs/swarm_router.md b/docs/swarms/structs/swarm_router.md index 44bd1c8b..28b7b521 100644 --- a/docs/swarms/structs/swarm_router.md +++ b/docs/swarms/structs/swarm_router.md @@ -125,6 +125,7 @@ The `SwarmRouter` supports many various multi-agent architectures for various ap | `HeavySwarm` | Heavy swarm architecture with question and worker agents | | `BatchedGridWorkflow` | Batched grid workflow for parallel task processing | | `LLMCouncil` | Council of specialized LLM agents with peer review and synthesis | +| `DebateWithJudge` | Debate architecture with Pro/Con agents and a Judge for self-refinement | | `auto` | Automatically selects best swarm type via embedding search | ## Basic Usage @@ -482,6 +483,64 @@ LLMCouncil creates a council of specialized agents (GPT-5.1, Gemini, Claude, Gro The council automatically tracks all messages in a conversation object and supports flexible output formats. Note: LLMCouncil uses default council members and doesn't require the `agents` parameter. +### DebateWithJudge + +Use Case: Structured debate architecture where two agents (Pro and Con) present opposing arguments, and a Judge agent evaluates and synthesizes the arguments over multiple rounds to progressively refine the answer. + +```python +from swarms import Agent, SwarmRouter + +# Create three specialized agents for the debate +pro_agent = Agent( + agent_name="Pro-Agent", + system_prompt="You are an expert at presenting strong, well-reasoned arguments in favor of positions. " + "You provide compelling evidence and logical reasoning to support your stance.", + model_name="gpt-4.1", + max_loops=1, +) + +con_agent = Agent( + agent_name="Con-Agent", + system_prompt="You are an expert at presenting strong, well-reasoned counter-arguments. " + "You identify weaknesses in opposing arguments and present compelling evidence against positions.", + model_name="gpt-4.1", + max_loops=1, +) + +judge_agent = Agent( + agent_name="Judge-Agent", + system_prompt="You are an impartial judge evaluating debates. You carefully assess both arguments, " + "identify strengths and weaknesses, and provide refined synthesis that incorporates " + "the best elements from both sides.", + model_name="gpt-4.1", + max_loops=1, +) + +# Initialize the SwarmRouter with DebateWithJudge +debate_router = SwarmRouter( + name="DebateWithJudge", + description="Structured debate with Pro/Con agents and Judge for self-refinement", + swarm_type="DebateWithJudge", + agents=[pro_agent, con_agent, judge_agent], # Must be exactly 3 agents + max_loops=3, # Number of debate rounds + output_type="str-all-except-first", # Output format + verbose=True # Show progress and intermediate results +) + +# Run a debate on a topic +result = debate_router.run( + "Should artificial intelligence development be regulated by governments?" +) +``` + +DebateWithJudge implements a multi-round debate system where: +1. **Pro Agent** presents arguments in favor of the topic +2. **Con Agent** presents counter-arguments against the topic +3. **Judge Agent** evaluates both arguments and provides synthesis +4. The process repeats for N rounds (specified by `max_loops`), with each round refining the discussion based on the judge's feedback + +The architecture progressively improves the answer through iterative refinement, making it ideal for complex topics requiring thorough analysis from multiple perspectives. Note: DebateWithJudge requires exactly 3 agents (pro_agent, con_agent, judge_agent) in that order. + ## Advanced Features ### Processing Documents From 790aae1786d288bc12ae9d4a4af5638c71c18587 Mon Sep 17 00:00:00 2001 From: CI-DEV <154627941+IlumCI@users.noreply.github.com> Date: Mon, 1 Dec 2025 22:36:09 +0200 Subject: [PATCH 03/11] Update swarm_router.py --- swarms/structs/swarm_router.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swarms/structs/swarm_router.py b/swarms/structs/swarm_router.py index 0d8884d5..0ebbe04c 100644 --- a/swarms/structs/swarm_router.py +++ b/swarms/structs/swarm_router.py @@ -26,7 +26,7 @@ from swarms.structs.council_as_judge import CouncilAsAJudge from swarms.structs.debate_with_judge import DebateWithJudge from swarms.structs.groupchat import GroupChat from swarms.structs.heavy_swarm import HeavySwarm -from swarms.structs.hierarchical_swarm import HierarchicalSwarm +from swarms.structs.hiearchical_swarm import HierarchicalSwarm from swarms.structs.interactive_groupchat import InteractiveGroupChat from swarms.structs.ma_utils import list_all_agents from swarms.structs.majority_voting import MajorityVoting From cba961ca68101c2da6cdbd2fec5e0434b8637e8e Mon Sep 17 00:00:00 2001 From: CI-DEV <154627941+IlumCI@users.noreply.github.com> Date: Mon, 1 Dec 2025 22:36:50 +0200 Subject: [PATCH 04/11] Update swarm_router.py --- swarms/structs/swarm_router.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swarms/structs/swarm_router.py b/swarms/structs/swarm_router.py index 0ebbe04c..26ed4003 100644 --- a/swarms/structs/swarm_router.py +++ b/swarms/structs/swarm_router.py @@ -26,7 +26,7 @@ from swarms.structs.council_as_judge import CouncilAsAJudge from swarms.structs.debate_with_judge import DebateWithJudge from swarms.structs.groupchat import GroupChat from swarms.structs.heavy_swarm import HeavySwarm -from swarms.structs.hiearchical_swarm import HierarchicalSwarm +from swarms.structs.hiearchical_swarm import HiearchicalSwarm from swarms.structs.interactive_groupchat import InteractiveGroupChat from swarms.structs.ma_utils import list_all_agents from swarms.structs.majority_voting import MajorityVoting From 15e897a4e0cff5625ee61d1c5396a5a6f36c7807 Mon Sep 17 00:00:00 2001 From: CI-DEV <154627941+IlumCI@users.noreply.github.com> Date: Mon, 1 Dec 2025 22:45:54 +0200 Subject: [PATCH 05/11] Update swarm_router.py --- swarms/structs/swarm_router.py | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/swarms/structs/swarm_router.py b/swarms/structs/swarm_router.py index 26ed4003..b81598b6 100644 --- a/swarms/structs/swarm_router.py +++ b/swarms/structs/swarm_router.py @@ -471,24 +471,6 @@ class SwarmRouter: chairman_model=self.chairman_model, ) - def _create_debate_with_judge(self, *args, **kwargs): - """Factory function for DebateWithJudge.""" - if len(self.agents) != 3: - raise SwarmRouterConfigError( - "DebateWithJudge requires exactly 3 agents: " - "pro_agent (arguing in favor), con_agent (arguing against), " - "and judge_agent (evaluating and synthesizing). " - f"Provided {len(self.agents)} agent(s)." - ) - - return DebateWithJudge( - pro_agent=self.agents[0], - con_agent=self.agents[1], - judge_agent=self.agents[2], - max_rounds=self.max_loops, - output_type=self.output_type, - verbose=self.verbose, - ) def _create_agent_rearrange(self, *args, **kwargs): """Factory function for AgentRearrange.""" From 521f883a678574ca6045e71ec90b27ed965a8e13 Mon Sep 17 00:00:00 2001 From: CI-DEV <154627941+IlumCI@users.noreply.github.com> Date: Mon, 1 Dec 2025 23:22:51 +0200 Subject: [PATCH 06/11] Update swarm_router.py --- swarms/structs/swarm_router.py | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/swarms/structs/swarm_router.py b/swarms/structs/swarm_router.py index b81598b6..70609436 100644 --- a/swarms/structs/swarm_router.py +++ b/swarms/structs/swarm_router.py @@ -26,7 +26,7 @@ from swarms.structs.council_as_judge import CouncilAsAJudge from swarms.structs.debate_with_judge import DebateWithJudge from swarms.structs.groupchat import GroupChat from swarms.structs.heavy_swarm import HeavySwarm -from swarms.structs.hiearchical_swarm import HiearchicalSwarm +from swarms.structs.hierarchical_swarm import HierarchicalSwarm from swarms.structs.interactive_groupchat import InteractiveGroupChat from swarms.structs.ma_utils import list_all_agents from swarms.structs.majority_voting import MajorityVoting @@ -50,7 +50,7 @@ SwarmType = Literal[ "GroupChat", "MultiAgentRouter", "AutoSwarmBuilder", - "HiearchicalSwarm", + "HierarchicalSwarm", "auto", "MajorityVoting", "MALT", @@ -434,7 +434,7 @@ class SwarmRouter: "MALT": self._create_malt, "CouncilAsAJudge": self._create_council_as_judge, "InteractiveGroupChat": self._create_interactive_group_chat, - "HiearchicalSwarm": self._create_hierarchical_swarm, + "HierarchicalSwarm": self._create_hierarchical_swarm, "MixtureOfAgents": self._create_mixture_of_agents, "MajorityVoting": self._create_majority_voting, "GroupChat": self._create_group_chat, @@ -471,6 +471,16 @@ class SwarmRouter: chairman_model=self.chairman_model, ) + def _create_debate_with_judge(self, *args, **kwargs): + """Factory function for DebateWithJudge.""" + return DebateWithJudge( + pro_agent=self.agents[0], + con_agent=self.agents[1], + judge_agent=self.agents[2], + max_rounds=self.max_loops, + output_type=self.output_type, + verbose=self.verbose, + ) def _create_agent_rearrange(self, *args, **kwargs): """Factory function for AgentRearrange.""" From cf7b805d47ac41c7b51a74f366c00ceba98023e2 Mon Sep 17 00:00:00 2001 From: Hugh <155223694+hughiwnl@users.noreply.github.com> Date: Mon, 1 Dec 2025 14:42:58 -0800 Subject: [PATCH 07/11] refactored tests for llm council to have 5 tests and added requests to requirements.txt --- requirements.txt | 3 +- test_llm_council.py | 241 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 test_llm_council.py diff --git a/requirements.txt b/requirements.txt index c33b46b3..27307c2d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -19,10 +19,11 @@ pytest networkx aiofiles httpx +requests # vllm>=0.2.0 aiohttp mcp numpy schedule uvloop; sys_platform == 'linux' or sys_platform == 'darwin' # linux or macos only -winloop; sys_platform == 'win32' # windows only +winloop; sys_platform == 'win32' # windows only \ No newline at end of file diff --git a/test_llm_council.py b/test_llm_council.py new file mode 100644 index 00000000..8198acb5 --- /dev/null +++ b/test_llm_council.py @@ -0,0 +1,241 @@ +""" +Test file for LLM Council functionality. + +Tests core functionalities of the LLM Council including: +- Initialization (default and custom) +- Running queries +- Batch processing +- Output formatting +""" + +import pytest +from loguru import logger +from dotenv import load_dotenv +from swarms.structs.llm_council import LLMCouncil +from swarms.structs.agent import Agent + +load_dotenv() + + +def test_llm_council_default_initialization(): + """Test LLM Council initialization with default council members.""" + try: + logger.info("Testing LLM Council default initialization...") + + council = LLMCouncil( + verbose=False, + output_type="dict-all-except-first" + ) + + assert council is not None, "Council should be initialized" + assert council.name == "LLM Council", "Default name should be 'LLM Council'" + assert len(council.council_members) > 0, "Should have council members" + assert council.chairman is not None, "Chairman should be initialized" + assert council.conversation is not None, "Conversation should be initialized" + + logger.info(f"✓ Council initialized with {len(council.council_members)} members") + logger.info("✓ Default initialization test passed") + + except Exception as e: + logger.error(f"✗ Default initialization test failed: {e}") + raise + + +def test_llm_council_custom_initialization(): + """Test LLM Council initialization with custom council members.""" + try: + logger.info("Testing LLM Council custom initialization...") + + # Create custom council members with simpler models + custom_members = [ + Agent( + agent_name="TestAgent1", + agent_description="First test agent", + system_prompt="You are a helpful test agent.", + model_name="gpt-4o-mini", + max_loops=1, + verbose=False, + ), + Agent( + agent_name="TestAgent2", + agent_description="Second test agent", + system_prompt="You are a helpful test agent.", + model_name="gpt-4o-mini", + max_loops=1, + verbose=False, + ), + ] + + council = LLMCouncil( + name="Custom Council", + council_members=custom_members, + chairman_model="gpt-4o-mini", + verbose=False, + output_type="string" + ) + + assert council is not None, "Council should be initialized" + assert council.name == "Custom Council", "Name should match custom value" + assert len(council.council_members) == 2, "Should have 2 custom members" + assert council.council_members[0].agent_name == "TestAgent1", "First member should match" + assert council.council_members[1].agent_name == "TestAgent2", "Second member should match" + assert council.output_type == "string", "Output type should be 'string'" + + logger.info("✓ Custom initialization test passed") + + except Exception as e: + logger.error(f"✗ Custom initialization test failed: {e}") + raise + + +def test_llm_council_run(): + """Test LLM Council run method with a simple query.""" + try: + logger.info("Testing LLM Council run method...") + + # Use simpler models for testing + custom_members = [ + Agent( + agent_name="TestAgent1", + agent_description="First test agent", + system_prompt="You are a helpful test agent. Provide concise answers.", + model_name="gpt-4o-mini", + max_loops=1, + verbose=False, + ), + Agent( + agent_name="TestAgent2", + agent_description="Second test agent", + system_prompt="You are a helpful test agent. Provide concise answers.", + model_name="gpt-4o-mini", + max_loops=1, + verbose=False, + ), + ] + + council = LLMCouncil( + council_members=custom_members, + chairman_model="gpt-4o-mini", + verbose=False, + output_type="dict-all-except-first" + ) + + query = "What is 2 + 2? Provide a brief answer." + result = council.run(query) + + assert result is not None, "Result should not be None" + assert council.conversation is not None, "Conversation should exist" + assert len(council.conversation.messages) > 0, "Conversation should have messages" + + logger.info("✓ Run method test passed") + + except Exception as e: + logger.error(f"✗ Run method test failed: {e}") + raise + + +def test_llm_council_batched_run(): + """Test LLM Council batched_run method with multiple tasks.""" + try: + logger.info("Testing LLM Council batched_run method...") + + # Use simpler models for testing + custom_members = [ + Agent( + agent_name="TestAgent1", + agent_description="First test agent", + system_prompt="You are a helpful test agent. Provide concise answers.", + model_name="gpt-4o-mini", + max_loops=1, + verbose=False, + ), + Agent( + agent_name="TestAgent2", + agent_description="Second test agent", + system_prompt="You are a helpful test agent. Provide concise answers.", + model_name="gpt-4o-mini", + max_loops=1, + verbose=False, + ), + ] + + council = LLMCouncil( + council_members=custom_members, + chairman_model="gpt-4o-mini", + verbose=False, + output_type="dict-all-except-first" + ) + + tasks = [ + "What is 1 + 1?", + "What is 3 + 3?", + ] + + results = council.batched_run(tasks) + + assert results is not None, "Results should not be None" + assert len(results) == len(tasks), f"Should have {len(tasks)} results" + assert all(result is not None for result in results), "All results should not be None" + + logger.info(f"✓ Batched run test passed with {len(results)} results") + + except Exception as e: + logger.error(f"✗ Batched run test failed: {e}") + raise + + +def test_llm_council_output_types(): + """Test LLM Council with different output types.""" + try: + logger.info("Testing LLM Council with different output types...") + + # Use simpler models for testing + custom_members = [ + Agent( + agent_name="TestAgent1", + agent_description="First test agent", + system_prompt="You are a helpful test agent. Provide concise answers.", + model_name="gpt-4o-mini", + max_loops=1, + verbose=False, + ), + Agent( + agent_name="TestAgent2", + agent_description="Second test agent", + system_prompt="You are a helpful test agent. Provide concise answers.", + model_name="gpt-4o-mini", + max_loops=1, + verbose=False, + ), + ] + + output_types = ["string", "dict-all-except-first", "final"] + + for output_type in output_types: + logger.info(f"Testing output type: {output_type}") + + council = LLMCouncil( + council_members=custom_members, + chairman_model="gpt-4o-mini", + verbose=False, + output_type=output_type + ) + + query = "What is 5 + 5? Provide a brief answer." + result = council.run(query) + + assert result is not None, f"Result should not be None for output type {output_type}" + assert council.output_type == output_type, f"Output type should be {output_type}" + + logger.info(f"✓ Output type '{output_type}' test passed") + + logger.info("✓ All output types test passed") + + except Exception as e: + logger.error(f"✗ Output types test failed: {e}") + raise + + +if __name__ == "__main__": + pytest.main([__file__, "-v"]) + From 8b2136712567d9780608c9bf35df82f69c6ed1ae Mon Sep 17 00:00:00 2001 From: Hugh <155223694+hughiwnl@users.noreply.github.com> Date: Mon, 1 Dec 2025 14:47:02 -0800 Subject: [PATCH 08/11] moved files back to test folder --- test_llm_council.py => tests/structs/test_llm_council.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test_llm_council.py => tests/structs/test_llm_council.py (100%) diff --git a/test_llm_council.py b/tests/structs/test_llm_council.py similarity index 100% rename from test_llm_council.py rename to tests/structs/test_llm_council.py From b56b9eeacab7269866f6b394b9beabc4c2999ba5 Mon Sep 17 00:00:00 2001 From: Hugh <155223694+hughiwnl@users.noreply.github.com> Date: Mon, 1 Dec 2025 14:56:26 -0800 Subject: [PATCH 09/11] added checks to conversation history --- requirements.txt | 1 + tests/structs/test_llm_council.py | 23 ++++++++++++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 27307c2d..4b1ef65b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -20,6 +20,7 @@ networkx aiofiles httpx requests +litellm # vllm>=0.2.0 aiohttp mcp diff --git a/tests/structs/test_llm_council.py b/tests/structs/test_llm_council.py index 8198acb5..80003e21 100644 --- a/tests/structs/test_llm_council.py +++ b/tests/structs/test_llm_council.py @@ -123,11 +123,32 @@ def test_llm_council_run(): query = "What is 2 + 2? Provide a brief answer." result = council.run(query) + # Basic assertions assert result is not None, "Result should not be None" assert council.conversation is not None, "Conversation should exist" - assert len(council.conversation.messages) > 0, "Conversation should have messages" + assert len(council.conversation.conversation_history) > 0, "Conversation should have messages" + + # Enhanced assertions to verify workflow steps + messages = council.conversation.conversation_history + + # Step 1: Verify User query was added + user_messages = [msg for msg in messages if msg.get("role") == "User"] + assert len(user_messages) > 0, "User query should be in conversation" + + # Step 2: Verify all council members responded + member_responses = [msg for msg in messages if msg.get("role") in ["TestAgent1", "TestAgent2"]] + assert len(member_responses) == len(custom_members), f"All {len(custom_members)} council members should have responded" + + # Step 3: Verify evaluations were performed + evaluation_messages = [msg for msg in messages if "-Evaluation" in msg.get("role", "")] + assert len(evaluation_messages) == len(custom_members), f"All {len(custom_members)} members should have evaluated" + + # Step 4: Verify Chairman synthesis occurred + chairman_messages = [msg for msg in messages if msg.get("role") == "Chairman"] + assert len(chairman_messages) > 0, "Chairman should have synthesized final response" logger.info("✓ Run method test passed") + logger.info(f"✓ Verified {len(member_responses)} member responses, {len(evaluation_messages)} evaluations, and {len(chairman_messages)} chairman synthesis") except Exception as e: logger.error(f"✗ Run method test failed: {e}") From c7fbc11d096442844ab556d8d5a11c128678cf7e Mon Sep 17 00:00:00 2001 From: Hugh <155223694+hughiwnl@users.noreply.github.com> Date: Mon, 1 Dec 2025 19:54:09 -0800 Subject: [PATCH 10/11] actually removed all mentions of linear swarm --- docs/llm.txt | 50 --- docs/swarms/examples/unique_swarms.md | 51 --- docs/swarms/structs/circular_swarm.md | 396 ++++++++++++++++++ .../utils/unique_swarms_examples.py | 26 -- swarms/structs/__init__.py | 2 - swarms/structs/swarming_architectures.py | 43 -- tests/structs/test_swarm_architectures.py | 16 - 7 files changed, 396 insertions(+), 188 deletions(-) create mode 100644 docs/swarms/structs/circular_swarm.md diff --git a/docs/llm.txt b/docs/llm.txt index 51f90399..2a0709b1 100644 --- a/docs/llm.txt +++ b/docs/llm.txt @@ -24130,31 +24130,6 @@ flowchart LR - Maintains strict ordering of task processing -### Linear Swarm -```python -def linear_swarm(agents: AgentListType, tasks: List[str], return_full_history: bool = True) -``` - -**Information Flow:** -```mermaid -flowchart LR - Input[Task Input] --> A1 - subgraph Sequential Processing - A1((Agent 1)) --> A2((Agent 2)) - A2 --> A3((Agent 3)) - A3 --> A4((Agent 4)) - A4 --> A5((Agent 5)) - end - A5 --> Output[Final Result] -``` - -**Best Used When:** - -- Tasks need sequential, pipeline-style processing - -- Each agent performs a specific transformation step - -- Order of processing is critical ### Star Swarm ```python @@ -24420,7 +24395,6 @@ from swarms.structs.swarming_architectures import ( exponential_swarm, fibonacci_swarm, grid_swarm, - linear_swarm, mesh_swarm, one_to_three, prime_swarm, @@ -24528,29 +24502,6 @@ def run_healthcare_grid_swarm(): print("\nGrid swarm processing completed") print(result) -def run_finance_linear_swarm(): - """Loan approval process using linear swarm""" - print_separator() - print("FINANCE - LOAN APPROVAL PROCESS (Linear Swarm)") - - agents = create_finance_agents()[:3] - tasks = [ - "Review loan application and credit history", - "Assess risk factors and compliance requirements", - "Generate final loan recommendation" - ] - - print("\nTasks:") - for i, task in enumerate(tasks, 1): - print(f"{i}. {task}") - - result = linear_swarm(agents, tasks) - print("\nResults:") - for log in result['history']: - print(f"\n{log['agent_name']}:") - print(f"Task: {log['task']}") - print(f"Response: {log['response']}") - def run_healthcare_star_swarm(): """Complex medical case management using star swarm""" print_separator() @@ -24684,7 +24635,6 @@ async def run_all_examples(): # Finance examples run_finance_circular_swarm() - run_finance_linear_swarm() run_finance_mesh_swarm() run_mathematical_finance_swarms() diff --git a/docs/swarms/examples/unique_swarms.md b/docs/swarms/examples/unique_swarms.md index 00f55e95..a4a37bb6 100644 --- a/docs/swarms/examples/unique_swarms.md +++ b/docs/swarms/examples/unique_swarms.md @@ -61,32 +61,6 @@ flowchart LR - Maintains strict ordering of task processing -### Linear Swarm -```python -def linear_swarm(agents: AgentListType, tasks: List[str], return_full_history: bool = True) -``` - -**Information Flow:** -```mermaid -flowchart LR - Input[Task Input] --> A1 - subgraph Sequential Processing - A1((Agent 1)) --> A2((Agent 2)) - A2 --> A3((Agent 3)) - A3 --> A4((Agent 4)) - A4 --> A5((Agent 5)) - end - A5 --> Output[Final Result] -``` - -**Best Used When:** - -- Tasks need sequential, pipeline-style processing - -- Each agent performs a specific transformation step - -- Order of processing is critical - ### Star Swarm ```python def star_swarm(agents: AgentListType, tasks: List[str], return_full_history: bool = True) @@ -351,7 +325,6 @@ from swarms.structs.swarming_architectures import ( exponential_swarm, fibonacci_swarm, grid_swarm, - linear_swarm, mesh_swarm, one_to_three, prime_swarm, @@ -459,29 +432,6 @@ def run_healthcare_grid_swarm(): print("\nGrid swarm processing completed") print(result) -def run_finance_linear_swarm(): - """Loan approval process using linear swarm""" - print_separator() - print("FINANCE - LOAN APPROVAL PROCESS (Linear Swarm)") - - agents = create_finance_agents()[:3] - tasks = [ - "Review loan application and credit history", - "Assess risk factors and compliance requirements", - "Generate final loan recommendation" - ] - - print("\nTasks:") - for i, task in enumerate(tasks, 1): - print(f"{i}. {task}") - - result = linear_swarm(agents, tasks) - print("\nResults:") - for log in result['history']: - print(f"\n{log['agent_name']}:") - print(f"Task: {log['task']}") - print(f"Response: {log['response']}") - def run_healthcare_star_swarm(): """Complex medical case management using star swarm""" print_separator() @@ -615,7 +565,6 @@ async def run_all_examples(): # Finance examples run_finance_circular_swarm() - run_finance_linear_swarm() run_finance_mesh_swarm() run_mathematical_finance_swarms() diff --git a/docs/swarms/structs/circular_swarm.md b/docs/swarms/structs/circular_swarm.md new file mode 100644 index 00000000..f192531c --- /dev/null +++ b/docs/swarms/structs/circular_swarm.md @@ -0,0 +1,396 @@ +# `CircularSwarm` + +The `CircularSwarm` is a multi-agent orchestration pattern that implements a circular workflow where agents process tasks in a round-robin manner. Each task is passed through all agents in sequence, creating a circular information flow pattern that ensures every agent processes every task. + +```mermaid +graph LR + subgraph Circular Flow + A1((Agent 1)) --> A2((Agent 2)) + A2 --> A3((Agent 3)) + A3 --> A4((Agent 4)) + A4 --> A1 + end + Task1[Task 1] --> A1 + Task2[Task 2] --> A2 + Task3[Task 3] --> A3 +``` + +## Overview + +The Circular Swarm follows a clear workflow pattern: + +1. **Task Distribution**: Each task is distributed to the first agent in the sequence +2. **Circular Processing**: Each agent processes the task and passes it to the next agent in the circle +3. **Full Coverage**: Every agent processes every task exactly once +4. **Context Preservation**: All conversation history and context is maintained throughout the process +5. **Ordered Execution**: Tasks are processed in a predictable, ordered manner + +## Key Features + +| Feature | Description | +|------------------------------|-----------------------------------------------------------------------------------------------| +| **Circular Flow** | Tasks move in a circular pattern through all agents | +| **Full Coverage** | Each agent processes each task exactly once | +| **Predictable Ordering** | Maintains strict ordering of task processing | +| **Context Preservation** | Full conversation history maintained for each agent | +| **Flexible Output Formats** | Support for various output types (dict, str, list) | +| **Simple Architecture** | Easy to understand and implement | + +## Two Implementation Options + +The Circular Swarm is available in two forms: + +1. **Function-based**: `circular_swarm()` - Simple function for quick usage +2. **Class-based**: `CircularSwarm` - Object-oriented approach with more control + +## Function-Based Implementation + +### `circular_swarm()` + +A simple function that implements circular swarm processing. + +#### Parameters + +| Parameter | Type | Default | Required | Description | +|-----------|------|---------|----------|-------------| +| `agents` | `AgentListType` | - | **Yes** | List of Agent objects to participate in the swarm | +| `tasks` | `List[str]` | - | **Yes** | List of tasks to be processed by the agents | +| `output_type` | `OutputType` | `"dict"` | No | Format for output (dict, str, list) | + +#### Returns + +| Type | Description | +|------|-------------| +| `Union[Dict[str, Any], List[str]]` | The formatted output of the swarm's processing. If output_type is "dict", returns a dictionary containing the conversation history. If output_type is "list", returns a list of responses. | + +#### Raises + +| Exception | Condition | +|-----------|-----------| +| `ValueError` | If agents or tasks lists are empty | + +#### Example + +```python +from swarms import Agent +from swarms.structs.swarming_architectures import circular_swarm + +# Create specialized agents +research_agent = Agent( + agent_name="Researcher", + system_prompt="You are a research specialist. Analyze and gather information.", + model_name="gpt-4o-mini", +) + +analysis_agent = Agent( + agent_name="Analyst", + system_prompt="You are a data analyst. Analyze data and provide insights.", + model_name="gpt-4o-mini", +) + +writing_agent = Agent( + agent_name="Writer", + system_prompt="You are a technical writer. Create clear, concise documentation.", + model_name="gpt-4o-mini", +) + +# Execute circular swarm +agents = [research_agent, analysis_agent, writing_agent] +tasks = [ + "Research the latest trends in AI", + "Analyze market opportunities", + "Create a summary report" +] + +result = circular_swarm(agents, tasks, output_type="dict") +print(result) +``` + +## Class-Based Implementation + +### `CircularSwarm` + +An object-oriented implementation that provides more control and configurability. + +### Constructor + +#### `CircularSwarm.__init__()` + +Initializes a new CircularSwarm instance. + +##### Parameters + +| Parameter | Type | Default | Required | Description | +|-----------|------|---------|----------|-------------| +| `agents` | `AgentListType` | - | **Yes** | List of Agent objects or nested list of Agent objects | +| `name` | `str` | `"CircularSwarm"` | No | The name identifier for this swarm instance | +| `description` | `str` | `"A circular swarm where agents pass tasks in a circular manner"` | No | A description of the swarm's purpose and capabilities | +| `output_type` | `str` | `"dict"` | No | Type of output format, one of 'dict', 'list', 'string', 'json', 'yaml', 'xml', etc. | + +##### Returns + +| Type | Description | +|------|-------------| +| `CircularSwarm` | A new CircularSwarm instance | + +##### Raises + +| Exception | Condition | +|-----------|-----------| +| `ValueError` | If no agents are provided | + +### Core Methods + +### `run()` + +Executes the circular swarm with the given tasks. + +#### Parameters + +| Parameter | Type | Default | Required | Description | +|-----------|------|---------|----------|-------------| +| `tasks` | `List[str]` | - | **Yes** | List of tasks to be processed by the swarm | + +#### Returns + +| Type | Description | +|------|-------------| +| `Union[Dict, List, str]` | The conversation history in the requested format | + +#### Raises + +| Exception | Condition | +|-----------|-----------| +| `ValueError` | If agents or tasks lists are empty | + +#### Example + +```python +from swarms import Agent +from swarms.structs.various_alt_swarms import CircularSwarm + +# Create specialized agents +market_agent = Agent( + agent_name="Market-Analyst", + agent_description="Expert in market analysis and trends", + model_name="gpt-4o-mini", +) + +risk_agent = Agent( + agent_name="Risk-Manager", + agent_description="Specialist in risk assessment and mitigation", + model_name="gpt-4o-mini", +) + +portfolio_agent = Agent( + agent_name="Portfolio-Manager", + agent_description="Expert in portfolio optimization", + model_name="gpt-4o-mini", +) + +# Initialize the circular swarm +swarm = CircularSwarm( + name="Investment-Analysis-Swarm", + description="A circular swarm for comprehensive investment analysis", + agents=[market_agent, risk_agent, portfolio_agent], + output_type="dict", +) + +# Execute tasks +tasks = [ + "Analyze Tesla stock performance for Q4 2024", + "Assess market risks and potential hedging strategies", + "Recommend portfolio adjustments based on analysis" +] + +result = swarm.run(tasks=tasks) +print(result) +``` + +## Use Cases + +### When to Use Circular Swarm + +Circular Swarm is ideal for scenarios where: + +- **Round-Robin Processing**: You need each agent to process every task in sequence +- **Iterative Refinement**: Tasks benefit from multiple perspectives in a specific order +- **Quality Assurance**: Each task needs to be reviewed by all agents +- **Predictable Workflow**: You need a consistent, ordered processing pattern +- **Simple Coordination**: You want a straightforward, easy-to-understand workflow + +### Example Use Cases + +1. **Content Review Pipeline** + - Writer → Editor → Fact-Checker → Publisher + - Each piece of content goes through all stages + +2. **Financial Analysis Workflow** + - Market Analyst → Risk Assessor → Portfolio Manager → Compliance Officer + - Each analysis is reviewed by all specialists + +3. **Software Development Process** + - Developer → Code Reviewer → QA Tester → Documentation Writer + - Each feature goes through all stages + +4. **Quality Control Systems** + - Inspector → Validator → Approver → Archivist + - Each item is checked by all quality control agents + +## Output Types + +The `CircularSwarm` supports various output formats through the `output_type` parameter: + +| Output Type | Description | Use Case | +|-------------|-------------|----------| +| `"dict"` | Returns conversation history as a dictionary | When you need structured data with full context | +| `"list"` | Returns conversation history as a list | For sequential processing or simple iteration | +| `"str"` | Returns conversation history as a string | For simple text output or logging | +| `"json"` | Returns conversation history as JSON string | For API responses or data exchange | +| `"yaml"` | Returns conversation history as YAML string | For configuration files or documentation | +| `"xml"` | Returns conversation history as XML string | For structured data exchange | + +## Advanced Examples + +### Financial Analysis Swarm + +```python +from swarms import Agent +from swarms.structs.various_alt_swarms import CircularSwarm + +# Create specialized financial agents +market_research_agent = Agent( + agent_name="Market-Research-Specialist", + agent_description="Expert in market research, trend analysis, and competitive intelligence", + system_prompt="""You are a senior market research specialist with expertise in: + - Market trend analysis and forecasting + - Competitive landscape assessment + - Consumer behavior analysis + - Industry report generation""", + model_name="gpt-4o-mini", +) + +financial_analyst_agent = Agent( + agent_name="Financial-Analyst", + agent_description="Specialist in financial statement analysis and valuation", + system_prompt="""You are a senior financial analyst with deep expertise in: + - Financial statement analysis + - Valuation methodologies + - Investment research and due diligence + - Risk assessment and portfolio analysis""", + model_name="gpt-4o-mini", +) + +compliance_agent = Agent( + agent_name="Compliance-Officer", + agent_description="Expert in regulatory compliance and risk management", + system_prompt="""You are a compliance officer with expertise in: + - Regulatory compliance verification + - Risk identification and mitigation + - Legal requirement assessment + - Audit preparation""", + model_name="gpt-4o-mini", +) + +# Initialize the circular swarm +financial_swarm = CircularSwarm( + name="Financial-Analysis-Circular-Swarm", + description="A circular swarm for comprehensive financial analysis", + agents=[market_research_agent, financial_analyst_agent, compliance_agent], + output_type="dict", +) + +# Execute financial analysis +tasks = [ + "Conduct a comprehensive analysis of Tesla (TSLA) stock", + "Evaluate market position and financial health", + "Assess regulatory compliance and investment risks" +] + +result = financial_swarm.run(tasks=tasks) +print(result) +``` + +### Content Creation Workflow + +```python +from swarms import Agent +from swarms.structs.swarming_architectures import circular_swarm + +# Create content creation agents +researcher = Agent( + agent_name="Researcher", + system_prompt="You are a research specialist. Gather comprehensive information on topics.", + model_name="gpt-4o-mini", +) + +writer = Agent( + agent_name="Writer", + system_prompt="You are a technical writer. Create clear, engaging content based on research.", + model_name="gpt-4o-mini", +) + +editor = Agent( + agent_name="Editor", + system_prompt="You are an editor. Review and refine content for clarity, grammar, and style.", + model_name="gpt-4o-mini", +) + +fact_checker = Agent( + agent_name="Fact-Checker", + system_prompt="You are a fact-checker. Verify the accuracy of information and claims.", + model_name="gpt-4o-mini", +) + +# Execute circular swarm +agents = [researcher, writer, editor, fact_checker] +tasks = [ + "Create an article about the future of AI", + "Write a blog post on sustainable technology", + "Develop content for a product launch" +] + +result = circular_swarm(agents, tasks, output_type="dict") +``` + +## Best Practices + +| Best Practice | Description | +|------------------------------|--------------------------------------------------------------------------------------------------| +| **Agent Specialization** | Create agents with specific, well-defined expertise areas | +| **Clear Task Descriptions** | Provide detailed, actionable task descriptions | +| **Appropriate Agent Count** | Balance between thoroughness and performance (3-5 agents is often optimal) | +| **Context Preservation** | Leverage the built-in conversation history for continuity | +| **Error Handling** | Implement proper error handling for production use | +| **Output Format Selection** | Choose the output format that best suits your downstream processing needs | + +## Comparison with Other Swarm Types + +| Swarm Type | Processing Pattern | Best For | +|------------|-------------------|----------| +| **Circular Swarm** | Each agent processes each task in sequence | Round-robin review, iterative refinement | +| **Star Swarm** | Central agent coordinates, others process | Centralized coordination | +| **Mesh Swarm** | Random task distribution from queue | Load balancing, parallel processing | +| **Sequential Workflow** | Linear chain, output feeds next input | Pipeline processing, dependencies | +| **Concurrent Workflow** | All agents process simultaneously | Parallel execution, independent tasks | + +## Performance Considerations + +- **Agent Count**: More agents increase processing time (each task goes through all agents) +- **Task Count**: More tasks multiply the total processing time +- **Model Selection**: Choose appropriate models for your use case and budget +- **Context Size**: Conversation history grows with each agent, which may affect token usage + +## Error Handling + +The `CircularSwarm` includes error handling with validation. Common issues and solutions: + +- **No Agents**: Ensure at least one agent is provided +- **Empty Tasks**: Verify that the tasks list is not empty +- **Model Issues**: Check that all agents have valid model configurations +- **Output Format**: Ensure the output_type is one of the supported formats + +## Summary + +The `CircularSwarm` provides a simple yet powerful pattern for ensuring every agent processes every task in a predictable, ordered manner. It's ideal for workflows that require comprehensive review, iterative refinement, or quality assurance processes where each task must pass through all agents in sequence. + diff --git a/examples/multi_agent/utils/unique_swarms_examples.py b/examples/multi_agent/utils/unique_swarms_examples.py index 7f577e0b..09788cbf 100644 --- a/examples/multi_agent/utils/unique_swarms_examples.py +++ b/examples/multi_agent/utils/unique_swarms_examples.py @@ -8,7 +8,6 @@ from swarms.structs.swarming_architectures import ( exponential_swarm, fibonacci_swarm, grid_swarm, - linear_swarm, mesh_swarm, one_to_three, prime_swarm, @@ -121,30 +120,6 @@ def run_healthcare_grid_swarm(): print(result) -def run_finance_linear_swarm(): - """Loan approval process using linear swarm""" - print_separator() - print("FINANCE - LOAN APPROVAL PROCESS (Linear Swarm)") - - agents = create_finance_agents()[:3] - tasks = [ - "Review loan application and credit history", - "Assess risk factors and compliance requirements", - "Generate final loan recommendation", - ] - - print("\nTasks:") - for i, task in enumerate(tasks, 1): - print(f"{i}. {task}") - - result = linear_swarm(agents, tasks) - print("\nResults:") - for log in result["history"]: - print(f"\n{log['agent_name']}:") - print(f"Task: {log['task']}") - print(f"Response: {log['response']}") - - def run_healthcare_star_swarm(): """Complex medical case management using star swarm""" print_separator() @@ -287,7 +262,6 @@ async def run_all_examples(): # Finance examples run_finance_circular_swarm() - run_finance_linear_swarm() run_finance_mesh_swarm() run_mathematical_finance_swarms() diff --git a/swarms/structs/__init__.py b/swarms/structs/__init__.py index ec292632..18f46c5c 100644 --- a/swarms/structs/__init__.py +++ b/swarms/structs/__init__.py @@ -90,7 +90,6 @@ from swarms.structs.swarming_architectures import ( geometric_swarm, grid_swarm, harmonic_swarm, - linear_swarm, log_swarm, mesh_swarm, one_to_one, @@ -128,7 +127,6 @@ __all__ = [ "geometric_swarm", "grid_swarm", "harmonic_swarm", - "linear_swarm", "log_swarm", "mesh_swarm", "one_to_one", diff --git a/swarms/structs/swarming_architectures.py b/swarms/structs/swarming_architectures.py index c286b653..f2c09bed 100644 --- a/swarms/structs/swarming_architectures.py +++ b/swarms/structs/swarming_architectures.py @@ -107,49 +107,6 @@ def grid_swarm( return history_output_formatter(conversation, output_type) -# Linear Swarm: Agents process tasks in a sequential linear manner -def linear_swarm( - agents: AgentListType, - tasks: List[str], - output_type: OutputType = "dict", -) -> Union[Dict[str, Any], List[str]]: - """ - Implements a linear swarm where agents process tasks in a sequential manner. - - Args: - agents (AgentListType): A list of Agent objects to participate in the swarm. - tasks (List[str]): A list of tasks to be processed by the agents. - output_type (OutputType, optional): The format of the output. Defaults to "dict". - - Returns: - Union[Dict[str, Any], List[str]]: The formatted output of the swarm's processing. - If output_type is "dict", returns a dictionary containing the conversation history. - If output_type is "list", returns a list of responses. - - Raises: - ValueError: If agents or tasks lists are empty. - """ - if not agents or not tasks: - raise ValueError("Agents and tasks lists cannot be empty.") - - conversation = Conversation() - - for agent in agents: - if tasks: - task = tasks.pop(0) - conversation.add( - role="User", - content=task, - ) - response = agent.run(conversation.get_str()) - conversation.add( - role=agent.agent_name, - content=response, - ) - - return history_output_formatter(conversation, output_type) - - # Star Swarm: A central agent first processes all tasks, followed by others def star_swarm( agents: AgentListType, diff --git a/tests/structs/test_swarm_architectures.py b/tests/structs/test_swarm_architectures.py index cbe7d4d8..7be89129 100644 --- a/tests/structs/test_swarm_architectures.py +++ b/tests/structs/test_swarm_architectures.py @@ -8,7 +8,6 @@ from swarms.structs.swarming_architectures import ( geometric_swarm, grid_swarm, harmonic_swarm, - linear_swarm, log_swarm, mesh_swarm, one_to_one, @@ -69,21 +68,6 @@ def test_grid_swarm(): assert len(result) > 0 -def test_linear_swarm(): - """Test linear swarm sequential processing""" - agents = create_test_agents(3) - tasks = ["Research task", "Write content", "Review output"] - - result = linear_swarm(agents, tasks) - - assert isinstance(result, list) - assert len(result) > 0 - - for log in result: - assert "role" in log - assert "content" in log - - def test_star_swarm(): """Test star swarm with central and peripheral agents""" agents = create_test_agents(4) From 03302fee6356d2bc4042f720215057b9f53390bf Mon Sep 17 00:00:00 2001 From: Hugh <155223694+hughiwnl@users.noreply.github.com> Date: Mon, 1 Dec 2025 20:02:39 -0800 Subject: [PATCH 11/11] removed circular swarm docs --- docs/swarms/structs/circular_swarm.md | 396 -------------------------- 1 file changed, 396 deletions(-) delete mode 100644 docs/swarms/structs/circular_swarm.md diff --git a/docs/swarms/structs/circular_swarm.md b/docs/swarms/structs/circular_swarm.md deleted file mode 100644 index f192531c..00000000 --- a/docs/swarms/structs/circular_swarm.md +++ /dev/null @@ -1,396 +0,0 @@ -# `CircularSwarm` - -The `CircularSwarm` is a multi-agent orchestration pattern that implements a circular workflow where agents process tasks in a round-robin manner. Each task is passed through all agents in sequence, creating a circular information flow pattern that ensures every agent processes every task. - -```mermaid -graph LR - subgraph Circular Flow - A1((Agent 1)) --> A2((Agent 2)) - A2 --> A3((Agent 3)) - A3 --> A4((Agent 4)) - A4 --> A1 - end - Task1[Task 1] --> A1 - Task2[Task 2] --> A2 - Task3[Task 3] --> A3 -``` - -## Overview - -The Circular Swarm follows a clear workflow pattern: - -1. **Task Distribution**: Each task is distributed to the first agent in the sequence -2. **Circular Processing**: Each agent processes the task and passes it to the next agent in the circle -3. **Full Coverage**: Every agent processes every task exactly once -4. **Context Preservation**: All conversation history and context is maintained throughout the process -5. **Ordered Execution**: Tasks are processed in a predictable, ordered manner - -## Key Features - -| Feature | Description | -|------------------------------|-----------------------------------------------------------------------------------------------| -| **Circular Flow** | Tasks move in a circular pattern through all agents | -| **Full Coverage** | Each agent processes each task exactly once | -| **Predictable Ordering** | Maintains strict ordering of task processing | -| **Context Preservation** | Full conversation history maintained for each agent | -| **Flexible Output Formats** | Support for various output types (dict, str, list) | -| **Simple Architecture** | Easy to understand and implement | - -## Two Implementation Options - -The Circular Swarm is available in two forms: - -1. **Function-based**: `circular_swarm()` - Simple function for quick usage -2. **Class-based**: `CircularSwarm` - Object-oriented approach with more control - -## Function-Based Implementation - -### `circular_swarm()` - -A simple function that implements circular swarm processing. - -#### Parameters - -| Parameter | Type | Default | Required | Description | -|-----------|------|---------|----------|-------------| -| `agents` | `AgentListType` | - | **Yes** | List of Agent objects to participate in the swarm | -| `tasks` | `List[str]` | - | **Yes** | List of tasks to be processed by the agents | -| `output_type` | `OutputType` | `"dict"` | No | Format for output (dict, str, list) | - -#### Returns - -| Type | Description | -|------|-------------| -| `Union[Dict[str, Any], List[str]]` | The formatted output of the swarm's processing. If output_type is "dict", returns a dictionary containing the conversation history. If output_type is "list", returns a list of responses. | - -#### Raises - -| Exception | Condition | -|-----------|-----------| -| `ValueError` | If agents or tasks lists are empty | - -#### Example - -```python -from swarms import Agent -from swarms.structs.swarming_architectures import circular_swarm - -# Create specialized agents -research_agent = Agent( - agent_name="Researcher", - system_prompt="You are a research specialist. Analyze and gather information.", - model_name="gpt-4o-mini", -) - -analysis_agent = Agent( - agent_name="Analyst", - system_prompt="You are a data analyst. Analyze data and provide insights.", - model_name="gpt-4o-mini", -) - -writing_agent = Agent( - agent_name="Writer", - system_prompt="You are a technical writer. Create clear, concise documentation.", - model_name="gpt-4o-mini", -) - -# Execute circular swarm -agents = [research_agent, analysis_agent, writing_agent] -tasks = [ - "Research the latest trends in AI", - "Analyze market opportunities", - "Create a summary report" -] - -result = circular_swarm(agents, tasks, output_type="dict") -print(result) -``` - -## Class-Based Implementation - -### `CircularSwarm` - -An object-oriented implementation that provides more control and configurability. - -### Constructor - -#### `CircularSwarm.__init__()` - -Initializes a new CircularSwarm instance. - -##### Parameters - -| Parameter | Type | Default | Required | Description | -|-----------|------|---------|----------|-------------| -| `agents` | `AgentListType` | - | **Yes** | List of Agent objects or nested list of Agent objects | -| `name` | `str` | `"CircularSwarm"` | No | The name identifier for this swarm instance | -| `description` | `str` | `"A circular swarm where agents pass tasks in a circular manner"` | No | A description of the swarm's purpose and capabilities | -| `output_type` | `str` | `"dict"` | No | Type of output format, one of 'dict', 'list', 'string', 'json', 'yaml', 'xml', etc. | - -##### Returns - -| Type | Description | -|------|-------------| -| `CircularSwarm` | A new CircularSwarm instance | - -##### Raises - -| Exception | Condition | -|-----------|-----------| -| `ValueError` | If no agents are provided | - -### Core Methods - -### `run()` - -Executes the circular swarm with the given tasks. - -#### Parameters - -| Parameter | Type | Default | Required | Description | -|-----------|------|---------|----------|-------------| -| `tasks` | `List[str]` | - | **Yes** | List of tasks to be processed by the swarm | - -#### Returns - -| Type | Description | -|------|-------------| -| `Union[Dict, List, str]` | The conversation history in the requested format | - -#### Raises - -| Exception | Condition | -|-----------|-----------| -| `ValueError` | If agents or tasks lists are empty | - -#### Example - -```python -from swarms import Agent -from swarms.structs.various_alt_swarms import CircularSwarm - -# Create specialized agents -market_agent = Agent( - agent_name="Market-Analyst", - agent_description="Expert in market analysis and trends", - model_name="gpt-4o-mini", -) - -risk_agent = Agent( - agent_name="Risk-Manager", - agent_description="Specialist in risk assessment and mitigation", - model_name="gpt-4o-mini", -) - -portfolio_agent = Agent( - agent_name="Portfolio-Manager", - agent_description="Expert in portfolio optimization", - model_name="gpt-4o-mini", -) - -# Initialize the circular swarm -swarm = CircularSwarm( - name="Investment-Analysis-Swarm", - description="A circular swarm for comprehensive investment analysis", - agents=[market_agent, risk_agent, portfolio_agent], - output_type="dict", -) - -# Execute tasks -tasks = [ - "Analyze Tesla stock performance for Q4 2024", - "Assess market risks and potential hedging strategies", - "Recommend portfolio adjustments based on analysis" -] - -result = swarm.run(tasks=tasks) -print(result) -``` - -## Use Cases - -### When to Use Circular Swarm - -Circular Swarm is ideal for scenarios where: - -- **Round-Robin Processing**: You need each agent to process every task in sequence -- **Iterative Refinement**: Tasks benefit from multiple perspectives in a specific order -- **Quality Assurance**: Each task needs to be reviewed by all agents -- **Predictable Workflow**: You need a consistent, ordered processing pattern -- **Simple Coordination**: You want a straightforward, easy-to-understand workflow - -### Example Use Cases - -1. **Content Review Pipeline** - - Writer → Editor → Fact-Checker → Publisher - - Each piece of content goes through all stages - -2. **Financial Analysis Workflow** - - Market Analyst → Risk Assessor → Portfolio Manager → Compliance Officer - - Each analysis is reviewed by all specialists - -3. **Software Development Process** - - Developer → Code Reviewer → QA Tester → Documentation Writer - - Each feature goes through all stages - -4. **Quality Control Systems** - - Inspector → Validator → Approver → Archivist - - Each item is checked by all quality control agents - -## Output Types - -The `CircularSwarm` supports various output formats through the `output_type` parameter: - -| Output Type | Description | Use Case | -|-------------|-------------|----------| -| `"dict"` | Returns conversation history as a dictionary | When you need structured data with full context | -| `"list"` | Returns conversation history as a list | For sequential processing or simple iteration | -| `"str"` | Returns conversation history as a string | For simple text output or logging | -| `"json"` | Returns conversation history as JSON string | For API responses or data exchange | -| `"yaml"` | Returns conversation history as YAML string | For configuration files or documentation | -| `"xml"` | Returns conversation history as XML string | For structured data exchange | - -## Advanced Examples - -### Financial Analysis Swarm - -```python -from swarms import Agent -from swarms.structs.various_alt_swarms import CircularSwarm - -# Create specialized financial agents -market_research_agent = Agent( - agent_name="Market-Research-Specialist", - agent_description="Expert in market research, trend analysis, and competitive intelligence", - system_prompt="""You are a senior market research specialist with expertise in: - - Market trend analysis and forecasting - - Competitive landscape assessment - - Consumer behavior analysis - - Industry report generation""", - model_name="gpt-4o-mini", -) - -financial_analyst_agent = Agent( - agent_name="Financial-Analyst", - agent_description="Specialist in financial statement analysis and valuation", - system_prompt="""You are a senior financial analyst with deep expertise in: - - Financial statement analysis - - Valuation methodologies - - Investment research and due diligence - - Risk assessment and portfolio analysis""", - model_name="gpt-4o-mini", -) - -compliance_agent = Agent( - agent_name="Compliance-Officer", - agent_description="Expert in regulatory compliance and risk management", - system_prompt="""You are a compliance officer with expertise in: - - Regulatory compliance verification - - Risk identification and mitigation - - Legal requirement assessment - - Audit preparation""", - model_name="gpt-4o-mini", -) - -# Initialize the circular swarm -financial_swarm = CircularSwarm( - name="Financial-Analysis-Circular-Swarm", - description="A circular swarm for comprehensive financial analysis", - agents=[market_research_agent, financial_analyst_agent, compliance_agent], - output_type="dict", -) - -# Execute financial analysis -tasks = [ - "Conduct a comprehensive analysis of Tesla (TSLA) stock", - "Evaluate market position and financial health", - "Assess regulatory compliance and investment risks" -] - -result = financial_swarm.run(tasks=tasks) -print(result) -``` - -### Content Creation Workflow - -```python -from swarms import Agent -from swarms.structs.swarming_architectures import circular_swarm - -# Create content creation agents -researcher = Agent( - agent_name="Researcher", - system_prompt="You are a research specialist. Gather comprehensive information on topics.", - model_name="gpt-4o-mini", -) - -writer = Agent( - agent_name="Writer", - system_prompt="You are a technical writer. Create clear, engaging content based on research.", - model_name="gpt-4o-mini", -) - -editor = Agent( - agent_name="Editor", - system_prompt="You are an editor. Review and refine content for clarity, grammar, and style.", - model_name="gpt-4o-mini", -) - -fact_checker = Agent( - agent_name="Fact-Checker", - system_prompt="You are a fact-checker. Verify the accuracy of information and claims.", - model_name="gpt-4o-mini", -) - -# Execute circular swarm -agents = [researcher, writer, editor, fact_checker] -tasks = [ - "Create an article about the future of AI", - "Write a blog post on sustainable technology", - "Develop content for a product launch" -] - -result = circular_swarm(agents, tasks, output_type="dict") -``` - -## Best Practices - -| Best Practice | Description | -|------------------------------|--------------------------------------------------------------------------------------------------| -| **Agent Specialization** | Create agents with specific, well-defined expertise areas | -| **Clear Task Descriptions** | Provide detailed, actionable task descriptions | -| **Appropriate Agent Count** | Balance between thoroughness and performance (3-5 agents is often optimal) | -| **Context Preservation** | Leverage the built-in conversation history for continuity | -| **Error Handling** | Implement proper error handling for production use | -| **Output Format Selection** | Choose the output format that best suits your downstream processing needs | - -## Comparison with Other Swarm Types - -| Swarm Type | Processing Pattern | Best For | -|------------|-------------------|----------| -| **Circular Swarm** | Each agent processes each task in sequence | Round-robin review, iterative refinement | -| **Star Swarm** | Central agent coordinates, others process | Centralized coordination | -| **Mesh Swarm** | Random task distribution from queue | Load balancing, parallel processing | -| **Sequential Workflow** | Linear chain, output feeds next input | Pipeline processing, dependencies | -| **Concurrent Workflow** | All agents process simultaneously | Parallel execution, independent tasks | - -## Performance Considerations - -- **Agent Count**: More agents increase processing time (each task goes through all agents) -- **Task Count**: More tasks multiply the total processing time -- **Model Selection**: Choose appropriate models for your use case and budget -- **Context Size**: Conversation history grows with each agent, which may affect token usage - -## Error Handling - -The `CircularSwarm` includes error handling with validation. Common issues and solutions: - -- **No Agents**: Ensure at least one agent is provided -- **Empty Tasks**: Verify that the tasks list is not empty -- **Model Issues**: Check that all agents have valid model configurations -- **Output Format**: Ensure the output_type is one of the supported formats - -## Summary - -The `CircularSwarm` provides a simple yet powerful pattern for ensuring every agent processes every task in a predictable, ordered manner. It's ideal for workflows that require comprehensive review, iterative refinement, or quality assurance processes where each task must pass through all agents in sequence. -