examples re-shuffle

pull/852/merge
Kye Gomez 3 days ago
parent abcb5821e2
commit 6496feff10

@ -107,25 +107,6 @@ Main class for routing tasks to different swarm types.
| `concurrent_run` | `task: str, *args, **kwargs` | Execute a task using concurrent execution |
| `concurrent_batch_run` | `tasks: List[str], *args, **kwargs` | Execute multiple tasks concurrently |
## Function: swarm_router
A convenience function to create and run a SwarmRouter instance.
| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | str | "swarm-router" | Name of the swarm router. |
| `description` | str | "Routes your task to the desired swarm" | Description of the router. |
| `max_loops` | int | 1 | Maximum number of execution loops. |
| `agents` | List[Union[Agent, Callable]] | [] | List of agents or callables. |
| `swarm_type` | SwarmType | "SequentialWorkflow" | Type of swarm to use. |
| `autosave` | bool | False | Whether to autosave results. |
| `flow` | str | None | Flow configuration. |
| `return_json` | bool | True | Whether to return results as JSON. |
| `auto_generate_prompts` | bool | False | Whether to auto-generate prompts. |
| `task` | str | None | Task to execute. |
| `rules` | str | None | Rules to inject into every agent. |
| `*args` | | | Additional positional arguments passed to SwarmRouter.run() |
| `**kwargs` | | | Additional keyword arguments passed to SwarmRouter.run() |
## Installation
@ -564,184 +545,3 @@ result = swarm_router(
task="Analyze the quarterly report"
)
```
I'll help you create tables for each section while maintaining their titles. I'll convert the bullet points into organized tables.
## Best Practices
**1. Choose the Right Swarm Type**
| Swarm Type | Use Case |
|------------|----------|
| `SequentialWorkflow` | Tasks that need to be executed in order |
| `ConcurrentWorkflow` | Independent tasks that can run in parallel |
| `MALT` | Complex language processing tasks |
| `DeepResearchSwarm` | Comprehensive research tasks |
| `CouncilAsAJudge` | Consensus-based decision making |
| `auto` | When unsure which swarm type is best |
**2. Configure Multi-Agent Collaboration**
| Feature | Purpose |
|---------|----------|
| `multi_agent_collab_prompt` | Enable better agent cooperation |
| `GroupChat` swarm type | Interactive agent discussions |
| Shared memory | Share context between agents |
**3. Optimize Performance**
| Feature | Purpose |
|---------|----------|
| `output_type` | Set appropriate output format |
| `autosave` | Enable for long-running tasks |
| `concurrent_batch_run` | Process multiple independent tasks |
| `max_loops` | Set reasonable limits to prevent infinite loops |
**4. Error Handling and Logging**
| Feature | Purpose |
|---------|----------|
| `get_logs()` | Regular log checking |
| Error handling | Proper application error management |
| `reliability_check` | Verify system reliability |
**5. Agent Configuration**
| Feature | Purpose |
|---------|----------|
| System prompts | Provide clear and specific instructions |
| Model settings | Configure appropriate temperature and parameters |
| CSV loading | Manage large agent sets efficiently |
**6. Resource Management**
| Feature | Purpose |
|---------|----------|
| `no_cluster_ops` | Work with limited resources |
| Background tasks | Handle long-running operations |
| Resource cleanup | Proper cleanup and release |
**7. Security and Rules**
| Feature | Purpose |
|---------|----------|
| `rules` | Enforce agent behavior constraints |
| Authentication | Implement proper API security |
| Input validation | Sanitize and validate inputs |
**8. Monitoring and Debugging**
| Feature | Purpose |
|---------|----------|
| Logging system | Effective system monitoring |
| Performance monitoring | Track swarm performance |
| Error reporting | Implement proper error tracking |
**9. Scalability**
| Feature | Purpose |
|---------|----------|
| Horizontal scaling | Design for system expansion |
| Batch sizes | Configure appropriate concurrent operations |
| Resource limitations | Consider system constraints |
**10. Documentation and Maintenance**
| Feature | Purpose |
|---------|----------|
| Custom configurations | Document system extensions |
| Performance metrics | Track swarm performance |
| Agent prompts | Regular updates of prompts and rules |
## Common Use Cases
**1. Document Analysis**
| Component | Purpose |
|-----------|----------|
| `DeepResearchSwarm` | Comprehensive document analysis |
| `MALT` | Complex language processing |
| `SequentialWorkflow` | Structured document processing |
**2. Decision Making**
| Component | Purpose |
|-----------|----------|
| `CouncilAsAJudge` | Consensus-based decisions |
| `MajorityVoting` | Democratic decision making |
| `GroupChat` | Interactive decision processes |
**3. Research and Analysis**
| Component | Purpose |
|-----------|----------|
| `DeepResearchSwarm` | Deep research tasks |
| `MixtureOfAgents` | Combine multiple expert agents |
| `HiearchicalSwarm` | Organized research workflows |
**4. Data Processing**
| Component | Purpose |
|-----------|----------|
| `ConcurrentWorkflow` | Parallel data processing |
| `SpreadSheetSwarm` | Structured data operations |
| `SequentialWorkflow` | Ordered data transformations |
**5. Collaborative Tasks**
| Feature | Purpose |
|---------|----------|
| `multi_agent_collab_prompt` | Better cooperation |
| `GroupChat` | Interactive collaboration |
| Shared memory | Context sharing |
## Troubleshooting
**1. Common Issues**
| Area | Action |
|------|---------|
| Agent configurations | Check configurations and prompts |
| Swarm type | Verify compatibility with task |
| Resource usage | Monitor limitations |
**2. Performance Issues**
| Area | Action |
|------|---------|
| Operations | Optimize batch sizes and concurrent operations |
| Memory | Check for leaks and resource cleanup |
| System resources | Monitor scaling |
**3. Integration Issues**
| Area | Action |
|------|---------|
| API configurations | Verify settings and authentication |
| External services | Check compatibility |
| Network | Monitor connectivity and timeouts |
## Future Development
**1. Planned Features**
| Feature | Description |
|---------|-------------|
| Swarm types | Additional specialized tasks |
| Collaboration | Enhanced mechanisms |
| Performance | Improved optimizations |
**2. Contributing**
| Area | Action |
|------|---------|
| Guidelines | Follow contribution rules |
| Bug reports | Submit issues and requests |
| Community | Participate in discussions |
**3. Roadmap**
| Feature | Description |
|---------|-------------|
| AI models | Integration with more models |
| Tools | Enhanced monitoring and debugging |
| Performance | Improved scalability |

@ -0,0 +1,13 @@
from swarms.structs.deep_research_swarm import DeepResearchSwarm
def main():
swarm = DeepResearchSwarm(
name="Deep Research Swarm",
description="A swarm of agents that can perform deep research on a given topic",
)
swarm.run("What are the latest news in the AI an crypto space")
main()

@ -0,0 +1,23 @@
from swarms.structs.deep_research_swarm import DeepResearchSwarm
def main():
swarm = DeepResearchSwarm(
name="Deep Research Swarm",
description="A swarm of agents that can perform deep research on a given topic",
output_type="string", # Change to string output type for better readability
)
# Format the query as a proper question
query = "What are the latest developments and news in the AI and cryptocurrency space?"
try:
result = swarm.run(query)
print("\nResearch Results:")
print(result)
except Exception as e:
print(f"Error occurred: {str(e)}")
if __name__ == "__main__":
main()

@ -16,7 +16,8 @@ def fetch_hackernews_headlines(limit: int = 5):
"""Fetch top headlines from Hacker News using its public API."""
try:
ids = httpx.get(
"https://hacker-news.firebaseio.com/v0/topstories.json", timeout=10
"https://hacker-news.firebaseio.com/v0/topstories.json",
timeout=10,
).json()
except Exception:
return []
@ -29,7 +30,12 @@ def fetch_hackernews_headlines(limit: int = 5):
).json()
except Exception:
continue
headlines.append({"title": item.get("title", "No title"), "url": item.get("url", "")})
headlines.append(
{
"title": item.get("title", "No title"),
"url": item.get("url", ""),
}
)
return headlines
@ -96,7 +102,9 @@ if __name__ == "__main__":
for article in headlines:
content = fetch_article_content(article["url"])
summary = summarize_article(content)
summaries.append({"title": article["title"], "summary": summary})
summaries.append(
{"title": article["title"], "summary": summary}
)
print("\nArticle Summaries:\n")
for s in summaries:

@ -22,3 +22,25 @@ reasoning_agent_router.run(
# "What is the best possible financial strategy to maximize returns but minimize risk? Give a list of etfs to invest in and the percentage of the portfolio to allocate to each etf.",
# ]
# )
# from swarms import ReasoningAgentRouter
# calculus_router = ReasoningAgentRouter(
# agent_name="calculus-expert",
# description="A calculus problem solving agent",
# model_name="gpt-4o-mini",
# system_prompt="You are a calculus expert. Solve differentiation and integration problems methodically.",
# swarm_type="self-consistency",
# num_samples=3, # Generate 3 samples to ensure consistency
# output_type="list",
# )
# # Example calculus problem
# calculus_problem = "Find the derivative of f(x) = x³ln(x) - 5x²"
# # Get the solution
# solution = calculus_router.run(calculus_problem)
# print(solution)

@ -442,7 +442,5 @@ agent = Agent(
)
# agent.run("Use defi stats to find the best defi project to invest in")
agent.run(
"Get the price of bitcoin on both functions get_htx_crypto_price and get_crypto_price and also get the market sentiment for bitcoin"
)
agent.run("Get the market sentiment for bitcoin")
# Automatically executes any number and combination of tools you have uploaded to the tools parameter!

@ -1,8 +0,0 @@
from swarms.structs.long_agent import LongAgent
if __name__ == "__main__":
long_agent = LongAgent(
token_count_per_agent=3000, output_type="final"
)
print(long_agent.run([""]))

@ -1,20 +0,0 @@
from swarms import ReasoningAgentRouter
calculus_router = ReasoningAgentRouter(
agent_name="calculus-expert",
description="A calculus problem solving agent",
model_name="gpt-4o-mini",
system_prompt="You are a calculus expert. Solve differentiation and integration problems methodically.",
swarm_type="self-consistency",
num_samples=3, # Generate 3 samples to ensure consistency
output_type="list",
)
# Example calculus problem
calculus_problem = "Find the derivative of f(x) = x³ln(x) - 5x²"
# Get the solution
solution = calculus_router.run(calculus_problem)
print(solution)

File diff suppressed because it is too large Load Diff

@ -55,7 +55,6 @@ from swarms.structs.swarm_arange import SwarmRearrange
from swarms.structs.swarm_router import (
SwarmRouter,
SwarmType,
swarm_router,
)
from swarms.structs.swarming_architectures import (
broadcast,
@ -135,7 +134,6 @@ __all__ = [
"run_agents_with_different_tasks",
"run_agent_with_timeout",
"run_agents_with_resource_monitoring",
"swarm_router",
"run_agents_with_tasks_concurrently",
"GroupChat",
"expertise_based",

@ -332,9 +332,7 @@ class SwarmRouter:
)
logger.info("🚀 [SYSTEM] Swarm is ready for deployment")
def _create_swarm(
self, task: str = None, *args, **kwargs
):
def _create_swarm(self, task: str = None, *args, **kwargs):
"""
Dynamically create and return the specified swarm type or automatically match the best swarm type for a given task.
@ -768,85 +766,3 @@ class SwarmRouter:
results.append(None)
return results
def swarm_router(
name: str = "swarm-router",
description: str = "Routes your task to the desired swarm",
max_loops: int = 1,
agents: List[Union[Agent, Callable]] = [],
swarm_type: SwarmType = "SequentialWorkflow", # "SpreadSheetSwarm" # "auto"
autosave: bool = False,
flow: str = None,
return_json: bool = True,
auto_generate_prompts: bool = False,
task: str = None,
rules: str = None,
*args,
**kwargs,
) -> SwarmRouter:
"""
Create and run a SwarmRouter instance with the given configuration.
Args:
name (str, optional): Name of the swarm router. Defaults to "swarm-router".
description (str, optional): Description of the router. Defaults to "Routes your task to the desired swarm".
max_loops (int, optional): Maximum number of execution loops. Defaults to 1.
agents (List[Union[Agent, Callable]], optional): List of agents or callables. Defaults to [].
swarm_type (SwarmType, optional): Type of swarm to use. Defaults to "SequentialWorkflow".
autosave (bool, optional): Whether to autosave results. Defaults to False.
flow (str, optional): Flow configuration. Defaults to None.
return_json (bool, optional): Whether to return results as JSON. Defaults to True.
auto_generate_prompts (bool, optional): Whether to auto-generate prompts. Defaults to False.
task (str, optional): Task to execute. Defaults to None.
*args: Additional positional arguments passed to SwarmRouter.run()
**kwargs: Additional keyword arguments passed to SwarmRouter.run()
Returns:
Any: Result from executing the swarm router
Raises:
ValueError: If invalid arguments are provided
Exception: If an error occurs during router creation or task execution
"""
try:
logger.info(
f"Creating SwarmRouter with name: {name}, swarm_type: {swarm_type}"
)
if not agents:
logger.warning(
"No agents provided, router may have limited functionality"
)
if task is None:
logger.warning("No task provided")
swarm_router = SwarmRouter(
name=name,
description=description,
max_loops=max_loops,
agents=agents,
swarm_type=swarm_type,
autosave=autosave,
flow=flow,
return_json=return_json,
auto_generate_prompts=auto_generate_prompts,
rules=rules,
)
logger.info(f"Executing task with SwarmRouter: {task}")
result = swarm_router.run(task, *args, **kwargs)
logger.info(
f"Task execution completed successfully: {result}"
)
return result
except ValueError as e:
logger.error(
f"Invalid arguments provided to swarm_router: {str(e)}"
)
raise
except Exception as e:
logger.error(f"Error in swarm_router execution: {str(e)}")
raise

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save