-
-
Notifications
You must be signed in to change notification settings - Fork 717
feat: add hierarchical swarm demos and CLI support for auto-building β¦ #1318
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ZackBradshaw
wants to merge
1
commit into
kyegomez:master
Choose a base branch
from
ZackBradshaw:Improve-Hierarchical-Swarm
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| """Hierarchical Swarm Auto-Build Demo | ||
|
|
||
| Demonstrates: | ||
| - Auto-building agents from a natural-language prompt using `AutoSwarmBuilder` | ||
| - Adding built agents to departments via `DepartmentManager` | ||
| - Running the hierarchical swarm with parallel order execution | ||
|
|
||
| Note: This demo requires LLM credentials/configuration used by the project's LiteLLM/AutoSwarmBuilder. | ||
| """ | ||
|
|
||
| import logging | ||
|
|
||
| from swarms.structs.hiearchical_swarm import HierarchicalSwarm | ||
|
|
||
|
|
||
| logging.basicConfig(level=logging.INFO) | ||
|
|
||
|
|
||
| def main(): | ||
| swarm = HierarchicalSwarm( | ||
| name="HierarchicalAutoDemo", | ||
| description="Demo: auto-build agents and run hierarchical swarm", | ||
| max_loops=1, | ||
| interactive=False, | ||
| use_parallel_execution=True, | ||
| max_workers=8, | ||
| ) | ||
|
|
||
| prompt = ( | ||
| "Design a small 3-agent team for market analysis: " | ||
| "(1) Researcher: gathers background and raw data, " | ||
| "(2) DataAnalyst: analyzes numeric trends, and " | ||
| "(3) Summarizer: writes executive summary and action items. " | ||
| "For each agent provide name, description, system_prompt, and role." | ||
| ) | ||
|
|
||
| print("Auto-building agents from prompt...") | ||
| new_agents = swarm.auto_build_agents_from_prompt(prompt, department_name="Market") | ||
|
|
||
| print("Created agents:") | ||
| for a in new_agents: | ||
| try: | ||
| print(f" - {a.agent_name}: {getattr(a, 'agent_description', '')}") | ||
| except Exception: | ||
| print(" - <unknown agent>") | ||
|
|
||
| print("Running hierarchical swarm task...") | ||
| try: | ||
| result = swarm.run(task="Analyze Q1 market trends and provide top 5 action items.") | ||
| print("Swarm result:\n", result) | ||
| except Exception as e: | ||
| print("Error running swarm:", e) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| """Simple benchmark for HierarchicalSwarm order execution. | ||
|
|
||
| Creates fake agents whose `run` method sleeps for a short duration to | ||
| simulate work. Compares sequential vs parallel execution using | ||
| `HierarchicalSwarm.execute_orders`. | ||
|
|
||
| Run: | ||
| python examples/hierarchical_benchmark.py | ||
|
|
||
| """ | ||
| import time | ||
| import random | ||
|
|
||
| from concurrent.futures import ThreadPoolExecutor, as_completed | ||
|
|
||
|
|
||
| class FakeAgent: | ||
| def __init__(self, name: str, latency: float = 0.5): | ||
| self.agent_name = name | ||
| self.latency = latency | ||
|
|
||
| def run(self, task: str, *args, **kwargs): | ||
| # Simulate work | ||
| time.sleep(self.latency) | ||
| return f"{self.agent_name} done ({task})" | ||
|
|
||
|
|
||
| def build_agents_and_orders(num_agents: int, latency_mean: float = 0.5): | ||
| agents = [FakeAgent(f"agent_{i}", latency=random.uniform(latency_mean * 0.8, latency_mean * 1.2)) for i in range(num_agents)] | ||
| orders = [(a.agent_name, f"task_{i}") for i, a in enumerate(agents)] | ||
| agents_map = {a.agent_name: a for a in agents} | ||
| return agents_map, orders | ||
|
|
||
|
|
||
| def sequential_execute_orders(orders, agents_map): | ||
| outputs = [] | ||
| for agent_name, task in orders: | ||
| agent = agents_map[agent_name] | ||
| out = agent.run(task) | ||
| outputs.append(out) | ||
| return outputs | ||
|
|
||
|
|
||
| def parallel_execute_orders(orders, agents_map, max_workers=None): | ||
| outputs = [None] * len(orders) | ||
| with ThreadPoolExecutor(max_workers=max_workers) as exc: | ||
| future_to_idx = {} | ||
| for idx, (agent_name, task) in enumerate(orders): | ||
| agent = agents_map[agent_name] | ||
| fut = exc.submit(agent.run, task) | ||
| future_to_idx[fut] = idx | ||
|
|
||
| for fut in as_completed(future_to_idx): | ||
| idx = future_to_idx[fut] | ||
| try: | ||
| outputs[idx] = fut.result() | ||
| except Exception as e: | ||
| outputs[idx] = f"[ERROR] {e}" | ||
|
|
||
| return outputs | ||
|
|
||
|
|
||
| def run_benchmark(num_agents=8, latency_mean=0.5, max_workers=None): | ||
| agents_map, orders = build_agents_and_orders(num_agents, latency_mean=latency_mean) | ||
|
|
||
| # Sequential | ||
| t0 = time.time() | ||
| out_seq = sequential_execute_orders(orders, agents_map) | ||
| seq_time = time.time() - t0 | ||
|
|
||
| # Parallel | ||
| t0 = time.time() | ||
| out_par = parallel_execute_orders(orders, agents_map, max_workers=max_workers) | ||
| par_time = time.time() - t0 | ||
|
|
||
| print(f"Agents: {num_agents}, mean_latency: {latency_mean:.2f}s") | ||
| print(f"Sequential time: {seq_time:.2f}s") | ||
| print(f"Parallel time: {par_time:.2f}s") | ||
| print("Sequential outputs sample:", out_seq[:2]) | ||
| print("Parallel outputs sample: ", out_par[:2]) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| run_benchmark(num_agents=12, latency_mean=0.4) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| """Interactive Hierarchical Swarm UI Demo | ||
|
|
||
| This demo runs `HierarchicalSwarm` in interactive mode to show the | ||
| `HierarchicalSwarmDashboard` UI (Rich Live). It optionally auto-builds agents | ||
| from a prompt if LLM credentials are configured. | ||
|
|
||
| Run: | ||
| python examples/hierarchical_ui_demo.py | ||
|
|
||
| """ | ||
|
|
||
| import time | ||
| import logging | ||
|
|
||
| from swarms.structs.hiearchical_swarm import HierarchicalSwarm | ||
|
|
||
| logging.basicConfig(level=logging.INFO) | ||
|
|
||
|
|
||
| def main(): | ||
| swarm = HierarchicalSwarm( | ||
| name="HierarchicalUI", | ||
| description="Interactive UI demo for hierarchical swarm", | ||
| max_loops=2, | ||
| interactive=True, | ||
| use_parallel_execution=True, | ||
| max_workers=6, | ||
| ) | ||
|
|
||
| # Optionally auto-build a couple of agents if AutoSwarmBuilder is available | ||
| prompt = ( | ||
| "Create 2 lightweight agents: (1) NoteTaker that summarizes notes, " | ||
| "(2) Researcher that finds 3 data points. Return name, description, and system_prompt." | ||
| ) | ||
|
|
||
| try: | ||
| swarm.auto_build_agents_from_prompt(prompt, department_name="DemoTeam") | ||
| except Exception: | ||
| pass | ||
|
|
||
| # Run interactive loop - will prompt when needed | ||
| try: | ||
| result = swarm.run(task="Gather facts about the latest AI research breakthroughs.") | ||
| print("Run completed. Result:\n", result) | ||
| except KeyboardInterrupt: | ||
| print("Interrupted by user") | ||
| except Exception as e: | ||
| print("Error during interactive run:", e) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| """DepartmentManager: manage named departments of agents.""" | ||
| from typing import Any, Optional | ||
|
|
||
|
|
||
| class DepartmentManager: | ||
| """Manage departments (list of agent lists) for hierarchical swarms. | ||
|
|
||
| Departments are named groups of agents. This manager provides helpers to | ||
| add agents, list departments, and flatten agents for swarm execution. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| self.departments: dict[str, list[Any]] = {} | ||
|
|
||
| def add_department(self, name: str, agents: Optional[list[Any]] = None): | ||
| self.departments[name] = agents or [] | ||
|
|
||
| def add_agent_to_department(self, dept_name: str, agent: Any): | ||
| if dept_name not in self.departments: | ||
| self.add_department(dept_name) | ||
| self.departments[dept_name].append(agent) | ||
|
|
||
| def list_departments(self) -> list[str]: | ||
| return list(self.departments.keys()) | ||
|
|
||
| def flatten_agents(self) -> list[Any]: | ||
| out: list[Any] = [] | ||
| for agents in self.departments.values(): | ||
| out.extend(agents) | ||
| return out |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check failure
Code scanning / Pyre
Unbound name Error