[DOCS][Fix spreadsheat swarm and also fix swarm rearrange docs with old modules and libraries]

pull/1051/head
Kye Gomez 7 days ago
parent 2afbb86e1f
commit 16d2ade1e8

@ -1,6 +1,6 @@
# SpreadSheetSwarm Documentation # SpreadSheetSwarm Documentation
---
## Class Definition ## Class Definition
@ -189,20 +189,10 @@ swarm._save_to_csv()
```python ```python
import os import os
from swarms import Agent from swarms import Agent, SpreadSheetSwarm
from swarm_models import OpenAIChat
from swarms.prompts.finance_agent_sys_prompt import ( from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT, FINANCIAL_AGENT_SYS_PROMPT,
) )
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
# Example usage:
api_key = os.getenv("OPENAI_API_KEY")
# Model
model = OpenAIChat(
openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1
)
# Initialize your agents (assuming the Agent class and model are already defined) # Initialize your agents (assuming the Agent class and model are already defined)
@ -210,7 +200,7 @@ agents = [
Agent( Agent(
agent_name=f"Financial-Analysis-Agent-spreesheet-swarm:{i}", agent_name=f"Financial-Analysis-Agent-spreesheet-swarm:{i}",
system_prompt=FINANCIAL_AGENT_SYS_PROMPT, system_prompt=FINANCIAL_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="finance_agent.json", saved_state_path="finance_agent.json",
@ -242,9 +232,7 @@ swarm.run(
```python ```python
import os import os
from swarms import Agent from swarms import Agent, SpreadSheetSwarm
from swarm_models import OpenAIChat
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
# Define custom system prompts for QR code generation # Define custom system prompts for QR code generation
QR_CODE_AGENT_1_SYS_PROMPT = """ QR_CODE_AGENT_1_SYS_PROMPT = """
@ -255,20 +243,13 @@ QR_CODE_AGENT_2_SYS_PROMPT = """
You are a Python coding expert. Your task is to write a Python script to generate a QR code for the link: https://github.com/The-Swarm-Corporation/Cookbook. The code should save the QR code as an image file. You are a Python coding expert. Your task is to write a Python script to generate a QR code for the link: https://github.com/The-Swarm-Corporation/Cookbook. The code should save the QR code as an image file.
""" """
# Example usage:
api_key = os.getenv("OPENAI_API_KEY")
# Model
model = OpenAIChat(
openai_api_key=api_key, model_name="gpt-4o-mini", temperature=0.1
)
# Initialize your agents for QR code generation # Initialize your agents for QR code generation
agents = [ agents = [
Agent( Agent(
agent_name="QR-Code-Generator-Agent-Luma", agent_name="QR-Code-Generator-Agent-Luma",
system_prompt=QR_CODE_AGENT_1_SYS_PROMPT, system_prompt=QR_CODE_AGENT_1_SYS_PROMPT,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="qr_code_agent_luma.json", saved_state_path="qr_code_agent_luma.json",
@ -278,7 +259,7 @@ agents = [
Agent( Agent(
agent_name="QR-Code-Generator-Agent-Cookbook", agent_name="QR-Code-Generator-Agent-Cookbook",
system_prompt=QR_CODE_AGENT_2_SYS_PROMPT, system_prompt=QR_CODE_AGENT_2_SYS_PROMPT,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="qr_code_agent_cookbook.json", saved_state_path="qr_code_agent_cookbook.json",
@ -310,9 +291,7 @@ swarm.run(
```python ```python
import os import os
from swarms import Agent from swarms import Agent, SpreadSheetSwarm
from swarm_models import OpenAIChat
from swarms.structs.spreadsheet_swarm import SpreadSheetSwarm
# Define custom system prompts for each social media platform # Define custom system prompts for each social media platform
TWITTER_AGENT_SYS_PROMPT = """ TWITTER_AGENT_SYS_PROMPT = """
@ -344,7 +323,7 @@ agents = [
Agent( Agent(
agent_name="Twitter-Marketing-Agent", agent_name="Twitter-Marketing-Agent",
system_prompt=TWITTER_AGENT_SYS_PROMPT, system_prompt=TWITTER_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="twitter_agent.json", saved_state_path="twitter_agent.json",
@ -354,7 +333,7 @@ agents = [
Agent( Agent(
agent_name="Instagram-Marketing-Agent", agent_name="Instagram-Marketing-Agent",
system_prompt=INSTAGRAM_AGENT_SYS_PROMPT, system_prompt=INSTAGRAM_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="instagram_agent.json", saved_state_path="instagram_agent.json",
@ -364,7 +343,7 @@ agents = [
Agent( Agent(
agent_name="Facebook-Marketing-Agent", agent_name="Facebook-Marketing-Agent",
system_prompt=FACEBOOK_AGENT_SYS_PROMPT, system_prompt=FACEBOOK_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="facebook_agent.json", saved_state_path="facebook_agent.json",
@ -374,7 +353,7 @@ agents = [
Agent( Agent(
agent_name="Email-Marketing-Agent", agent_name="Email-Marketing-Agent",
system_prompt=EMAIL_AGENT_SYS_PROMPT, system_prompt=EMAIL_AGENT_SYS_PROMPT,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dynamic_temperature_enabled=True, dynamic_temperature_enabled=True,
saved_state_path="email_agent.json", saved_state_path="email_agent.json",
@ -404,22 +383,11 @@ swarm.run(
## Additional Information and Tips ## Additional Information and Tips
- **Thread Synchronization**: When working with multiple agents in a concurrent environment, it's crucial to ensure that access to shared resources is properly synchronized using locks to avoid race conditions. | Tip/Feature | Description |
|------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
- **Autosave Feature**: If you enable the `autosave_on` flag, ensure that the file path provided is correct and writable. This feature is handy for long-running tasks where you want to periodically save the state. | **Thread Synchronization** | When working with multiple agents in a concurrent environment, it's crucial to ensure that access to shared resources is properly synchronized using locks to avoid race conditions. |
| **Autosave Feature** | If you enable the `autosave_on` flag, ensure that the file path provided is correct and writable. This feature is handy for long-running tasks where you want to periodically save the state. |
- **Error Handling** | **Error Handling** | Implementing proper error handling within your agents can prevent the swarm from crashing during execution. Consider catching exceptions in the `run` method and logging errors appropriately. |
| **Custom Agents** | You can extend the `Agent` class to create custom agents that perform specific tasks tailored to your application's needs. |
: Implementing proper error handling within your agents can prevent the swarm from crashing during execution. Consider catching exceptions in the `run` method and logging errors appropriately.
- **Custom Agents**: You can extend the `Agent` class to create custom agents that perform specific tasks tailored to your application's needs.
--- ---
## References and Resources
- [Python's `queue` module](https://docs.python.org/3/library/queue.html)
- [Python's `threading` module](https://docs.python.org/3/library/threading.html)
- [CSV File Handling in Python](https://docs.python.org/3/library/csv.html)
- [JSON Handling in Python](https://docs.python.org/3/library/json.html)

@ -2,6 +2,8 @@
SwarmRearrange is a class for orchestrating multiple swarms in a sequential or parallel flow pattern. It provides thread-safe operations for managing swarm execution, history tracking, and flow validation. SwarmRearrange is a class for orchestrating multiple swarms in a sequential or parallel flow pattern. It provides thread-safe operations for managing swarm execution, history tracking, and flow validation.
Full Path: `from swarms.structs.swarm_rearrange import SwarmRearrange`
## Constructor Arguments ## Constructor Arguments
| Parameter | Type | Default | Description | | Parameter | Type | Default | Description |
@ -38,7 +40,9 @@ Executes the swarm arrangement according to the flow pattern.
The flow pattern uses arrow notation (`->`) to define execution order: The flow pattern uses arrow notation (`->`) to define execution order:
- Sequential: `"SwarmA -> SwarmB -> SwarmC"` - Sequential: `"SwarmA -> SwarmB -> SwarmC"`
- Parallel: `"SwarmA, SwarmB -> SwarmC"` - Parallel: `"SwarmA, SwarmB -> SwarmC"`
- Human intervention: Use `"H"` in the flow - Human intervention: Use `"H"` in the flow
## Examples ## Examples
@ -49,22 +53,10 @@ The flow pattern uses arrow notation (`->`) to define execution order:
from swarms.structs.swarm_rearrange import SwarmRearrange from swarms.structs.swarm_rearrange import SwarmRearrange
import os import os
from swarms import Agent, AgentRearrange from swarms import Agent, AgentRearrange
from swarm_models import OpenAIChat
# model = Anthropic(anthropic_api_key=os.getenv("ANTHROPIC_API_KEY")) # model = Anthropic(anthropic_api_key=os.getenv("ANTHROPIC_API_KEY"))
company = "TGSC" company = "TGSC"
# Get the OpenAI API key from the environment variable
api_key = os.getenv("GROQ_API_KEY")
# Model
model = OpenAIChat(
openai_api_base="https://api.groq.com/openai/v1",
openai_api_key=api_key,
model_name="llama-3.1-70b-versatile",
temperature=0.1,
)
# Initialize the Managing Director agent # Initialize the Managing Director agent
managing_director = Agent( managing_director = Agent(
@ -79,14 +71,8 @@ managing_director = Agent(
For the current potential acquisition of {company}, direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment. For the current potential acquisition of {company}, direct the tasks for the team to thoroughly analyze all aspects of the company, including its financials, industry position, technology, market potential, and regulatory compliance. Provide guidance and feedback as needed to ensure a rigorous and unbiased assessment.
""", """,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="managing-director.json",
) )
# Initialize the Vice President of Finance # Initialize the Vice President of Finance
@ -103,14 +89,8 @@ vp_finance = Agent(
Be sure to consider factors such as the sustainability of {company}' business model, the strength of its customer base, and its ability to generate consistent cash flows. Your analysis should be data-driven, objective, and aligned with Blackstone's investment criteria. Be sure to consider factors such as the sustainability of {company}' business model, the strength of its customer base, and its ability to generate consistent cash flows. Your analysis should be data-driven, objective, and aligned with Blackstone's investment criteria.
""", """,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="vp-finance.json",
) )
# Initialize the Industry Analyst # Initialize the Industry Analyst
@ -127,14 +107,8 @@ industry_analyst = Agent(
Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as {company}' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision. Your analysis should provide a clear and objective assessment of the attractiveness and future potential of the industrial robotics industry, as well as {company}' positioning within it. Consider both short-term and long-term factors, and provide evidence-based insights to inform the investment decision.
""", """,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="industry-analyst.json",
) )
# Initialize the Technology Expert # Initialize the Technology Expert
@ -151,14 +125,8 @@ tech_expert = Agent(
Your analysis should provide a comprehensive assessment of {company}' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements. Your analysis should provide a comprehensive assessment of {company}' technological strengths and weaknesses, as well as the sustainability of its competitive advantages. Consider both the current state of its technology and its future potential in light of industry trends and advancements.
""", """,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="tech-expert.json",
) )
# Initialize the Market Researcher # Initialize the Market Researcher
@ -175,14 +143,9 @@ market_researcher = Agent(
Your analysis should provide a data-driven assessment of the market opportunity for {company} and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections. Your analysis should provide a data-driven assessment of the market opportunity for {company} and the feasibility of achieving our investment return targets. Consider both bottom-up and top-down market perspectives, and identify any key sensitivities or assumptions in your projections.
""", """,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="market-researcher.json",
) )
# Initialize the Regulatory Specialist # Initialize the Regulatory Specialist
@ -199,14 +162,8 @@ regulatory_specialist = Agent(
Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding {company}, and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks. Your analysis should provide a comprehensive assessment of the regulatory and legal landscape surrounding {company}, and identify any material risks or potential deal-breakers. Consider both the current state and future outlook, and provide practical recommendations to mitigate identified risks.
""", """,
llm=model, model_name="gpt-4.1",
max_loops=1, max_loops=1,
dashboard=False,
streaming_on=True,
verbose=True,
stopping_token="<DONE>",
state_save_file_type="json",
saved_state_path="regulatory-specialist.json",
) )
# Create a list of agents # Create a list of agents
@ -284,51 +241,13 @@ arrangement = SwarmRearrange(
result = arrangement.run("Initial task") result = arrangement.run("Initial task")
``` ```
### Complex Multi-Stage Pipeline
```python
# Define multiple flow patterns
flows = [
"Collector -> Processor -> Analyzer",
"Analyzer -> ML -> Validator",
"Validator -> Reporter"
]
# Create arrangements for each flow
pipelines = [
SwarmRearrange(name=f"Pipeline{i}", swarms=swarms, flow=flow)
for i, flow in enumerate(flows)
]
# Create master arrangement
master = SwarmRearrange(
name="MasterPipeline",
swarms=pipelines,
flow="Pipeline0 -> Pipeline1 -> Pipeline2"
)
# Execute complete pipeline
result = master.run("Start analysis")
```
## Best Practices ## Best Practices
1. **Flow Validation**: Always validate flows before execution | Best Practice | Description |
2. **Error Handling**: Implement try-catch blocks around run() calls |------------------------|-----------------------------------------------------------------------------------------------|
3. **History Tracking**: Use track_history() for monitoring swarm execution | **Flow Validation** | Always validate flows before execution |
4. **Resource Management**: Set appropriate max_loops to prevent infinite execution | **Error Handling** | Implement try-catch blocks around `run()` calls |
5. **Logging**: Enable verbose mode during development for detailed logging | **History Tracking** | Use `track_history()` for monitoring swarm execution |
| **Resource Management**| Set appropriate `max_loops` to prevent infinite execution |
## Error Handling | **Logging** | Enable verbose mode during development for detailed logging |
The class implements comprehensive error handling:
```python
try:
arrangement = SwarmRearrange(swarms=swarms, flow=flow)
result = arrangement.run(task)
except ValueError as e:
logger.error(f"Flow validation error: {e}")
except Exception as e:
logger.error(f"Execution error: {e}")
```

Loading…
Cancel
Save