Merge pull request #1153 from Steve-Dusty/master

removed nonexistent functionality from sequential workflow docs
pull/1155/head
Kye Gomez 2 months ago committed by GitHub
commit 6f65541e8d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -1,283 +1,375 @@
# SequentialWorkflow Documentation # SequentialWorkflow Documentation
**Overview:** **Overview:**
A Sequential Swarm architecture processes tasks in a linear sequence. Each agent completes its task before passing the result to the next agent in the chain. This architecture ensures orderly processing and is useful when tasks have dependencies. The system now includes **sequential awareness** features that allow agents to know about the agents ahead and behind them in the workflow, significantly enhancing coordination and context understanding. [Learn more here in the docs:](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/) A Sequential Swarm architecture processes tasks in a linear sequence. Each agent completes its task before passing the result to the next agent in the chain. This architecture ensures orderly processing and is useful when tasks have dependencies.
**Use-Cases:** **Use-Cases:**
- Workflows where each step depends on the previous one, such as assembly lines or sequential data processing. - Workflows where each step depends on the previous one, such as assembly lines or sequential data processing.
- Scenarios requiring strict order of operations. - Scenarios requiring strict order of operations.
- **NEW**: Enhanced workflows where agents need context about their position in the sequence for better coordination. - Multi-step content creation, analysis, and refinement workflows.
```mermaid ```mermaid
graph TD graph TD
A[First Agent] --> B[Second Agent] A[First Agent] --> B[Second Agent]
B --> C[Third Agent] B --> C[Third Agent]
C --> D[Fourth Agent] C --> D[Fourth Agent]
style A fill:#e1f5fe style A fill:#e1f5fe
style B fill:#f3e5f5 style B fill:#f3e5f5
style C fill:#e8f5e8 style C fill:#e8f5e8
style D fill:#fff3e0 style D fill:#fff3e0
A -.->|"Awareness: None (first)"| A
B -.->|"Awareness: Ahead: A, Behind: C"| B
C -.->|"Awareness: Ahead: B, Behind: D"| C
D -.->|"Awareness: Ahead: C, Behind: None (last)"| D
``` ```
## **Sequential Awareness Feature**
The SequentialWorkflow now includes a powerful **sequential awareness** feature that automatically provides each agent with context about their position in the workflow:
### What Agents Know Automatically
- **Agent ahead**: The agent that completed their task before them
- **Agent behind**: The agent that will receive their output next
- **Workflow position**: Their step number and role in the sequence
### Benefits
1. **Better Coordination**: Agents can reference previous work and prepare output for the next step
2. **Context Understanding**: Each agent knows their role in the larger workflow
3. **Improved Quality**: Output is tailored for the next agent in the sequence
4. **Enhanced Logging**: Better tracking of agent interactions and workflow progress
## Attributes ## Attributes
| Attribute | Type | Description | | Attribute | Type | Description |
|------------------|---------------|--------------------------------------------------| |------------------|---------------|--------------------------------------------------|
| `agents` | `List[Agent]` | The list of agents in the workflow. | | `id` | `str` | Unique identifier for the workflow instance. Defaults to `"sequential_workflow"`. |
| `flow` | `str` | A string representing the order of agents. | | `name` | `str` | Human-readable name for the workflow. Defaults to `"SequentialWorkflow"`. |
| `agent_rearrange`| `AgentRearrange` | Manages the dynamic execution of agents with sequential awareness. | | `description` | `str` | Description of the workflow's purpose. |
| `team_awareness` | `bool` | **NEW**: Enables sequential awareness features. Defaults to `False`. | | `agents` | `List[Union[Agent, Callable]]` | The list of agents or callables in the workflow. |
| `time_enabled` | `bool` | **NEW**: Enables timestamps in conversation. Defaults to `False`. | | `max_loops` | `int` | Maximum number of times to execute the workflow. Defaults to `1`. |
| `message_id_on` | `bool` | **NEW**: Enables message IDs in conversation. Defaults to `False`. | | `output_type` | `OutputType` | Format of the output from the workflow. Defaults to `"dict"`. |
| `shared_memory_system` | `callable` | Optional callable for managing shared memory between agents. |
| `multi_agent_collab_prompt` | `bool` | If True, appends a collaborative prompt to each agent's system prompt. |
| `team_awareness` | `bool` | Enables sequential awareness features (passed to internal `AgentRearrange`). Defaults to `False`. |
| `flow` | `str` | A string representing the order of agents (e.g., "Agent1 -> Agent2 -> Agent3"). |
| `agent_rearrange`| `AgentRearrange` | Internal helper for managing agent execution. |
## Methods ## Methods
### `__init__(self, agents: List[Agent] = None, max_loops: int = 1, team_awareness: bool = False, time_enabled: bool = False, message_id_on: bool = False, *args, **kwargs)` ### `__init__(self, agents: List[Union[Agent, Callable]] = None, max_loops: int = 1, team_awareness: bool = False, *args, **kwargs)`
The constructor initializes the `SequentialWorkflow` object with enhanced sequential awareness capabilities. The constructor initializes the `SequentialWorkflow` object.
- **Parameters:** - **Parameters:**
- `agents` (`List[Agent]`, optional): The list of agents in the workflow. Defaults to `None`. - `id` (`str`, optional): Unique identifier for the workflow. Defaults to `"sequential_workflow"`.
- `name` (`str`, optional): Name of the workflow. Defaults to `"SequentialWorkflow"`.
- `description` (`str`, optional): Description of the workflow. Defaults to a standard description.
- `agents` (`List[Union[Agent, Callable]]`, optional): The list of agents or callables to execute in sequence.
- `max_loops` (`int`, optional): The maximum number of loops to execute the workflow. Defaults to `1`. - `max_loops` (`int`, optional): The maximum number of loops to execute the workflow. Defaults to `1`.
- `team_awareness` (`bool`, optional): **NEW**: Enables sequential awareness features. Defaults to `False`. - `output_type` (`OutputType`, optional): Output format for the workflow. Defaults to `"dict"`.
- `time_enabled` (`bool`, optional): **NEW**: Enables timestamps in conversation. Defaults to `False`. - `shared_memory_system` (`callable`, optional): Callable for shared memory management. Defaults to `None`.
- `message_id_on` (`bool`, optional): **NEW**: Enables message IDs in conversation. Defaults to `False`. - `multi_agent_collab_prompt` (`bool`, optional): If True, appends a collaborative prompt to each agent's system prompt. Defaults to `False`.
- `team_awareness` (`bool`, optional): Enables sequential awareness features in the underlying `AgentRearrange`. Defaults to `False`.
- `*args`: Variable length argument list. - `*args`: Variable length argument list.
- `**kwargs`: Arbitrary keyword arguments. - `**kwargs`: Arbitrary keyword arguments.
### `run(self, task: str) -> str` ### `run(self, task: str, img: Optional[str] = None, imgs: Optional[List[str]] = None, *args, **kwargs) -> str`
Runs the specified task through the agents in the dynamically constructed flow with enhanced sequential awareness. Runs the specified task through the agents in the dynamically constructed flow.
- **Parameters:** - **Parameters:**
- `task` (`str`): The task for the agents to execute. - `task` (`str`): The task for the agents to execute.
- `img` (`Optional[str]`, optional): An optional image input for the agents.
- `imgs` (`Optional[List[str]]`, optional): Optional list of images for the agents.
- `*args`: Additional positional arguments.
- `**kwargs`: Additional keyword arguments.
- **Returns:** - **Returns:**
- `str`: The final result after processing through all agents. - The final result after processing through all agents.
### `run_batched(self, tasks: List[str]) -> List[str]`
Executes a batch of tasks through the agents in the dynamically constructed flow.
- **Parameters:**
- `tasks` (`List[str]`): A list of tasks for the agents to execute.
### **NEW: Sequential Awareness Methods** - **Returns:**
- `List[str]`: A list of final results after processing through all agents.
#### `get_agent_sequential_awareness(self, agent_name: str) -> str` ### `async run_async(self, task: str) -> str`
Gets the sequential awareness information for a specific agent, showing which agents come before and after in the sequence. Executes the specified task through the agents asynchronously.
- **Parameters:** - **Parameters:**
- `agent_name` (`str`): The name of the agent to get awareness for. - `task` (`str`): The task for the agents to execute.
- **Returns:** - **Returns:**
- `str`: A string describing the agents ahead and behind in the sequence. - `str`: The final result after processing through all agents.
### `async run_concurrent(self, tasks: List[str]) -> List[str]`
#### `get_sequential_flow_structure(self) -> str` Executes a batch of tasks through the agents concurrently.
Gets the overall sequential flow structure information showing the complete workflow with relationships between agents. - **Parameters:**
- `tasks` (`List[str]`): A list of tasks for the agents to execute.
- **Returns:** - **Returns:**
- `str`: A string describing the complete sequential flow structure. - `List[str]`: A list of final results after processing through all agents.
## **Usage Example with Sequential Awareness:** ## Usage Examples
### Basic Sequential Workflow
This example demonstrates a simple two-agent workflow for researching and writing a blog post.
```python ```python
from swarms import Agent, SequentialWorkflow from swarms import Agent, SequentialWorkflow
# Initialize agents for individual tasks # Agent 1: The Researcher
agent1 = Agent( researcher = Agent(
agent_name="ICD-10 Code Analyzer", agent_name="Researcher",
system_prompt="Analyze medical data and provide relevant ICD-10 codes.", system_prompt="Your job is to research the provided topic and provide a detailed summary.",
model_name="gpt-4.1", model_name="gpt-4o-mini",
max_loops=1,
)
agent2 = Agent(
agent_name="ICD-10 Code Summarizer",
system_prompt="Summarize the findings and suggest ICD-10 codes.",
model_name="gpt-4.1",
max_loops=1,
)
agent3 = Agent(
agent_name="ICD-10 Code Validator",
system_prompt="Validate and finalize the ICD-10 code recommendations.",
model_name="gpt-4.1",
max_loops=1,
) )
# Create the Sequential workflow with enhanced awareness # Agent 2: The Writer
workflow = SequentialWorkflow( writer = Agent(
agents=[agent1, agent2, agent3], agent_name="Writer",
max_loops=1, system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
verbose=False, model_name="gpt-4o-mini",
team_awareness=True, # Enable sequential awareness
time_enabled=True, # Enable timestamps
message_id_on=True # Enable message IDs
) )
# Get workflow structure information # Create a sequential workflow where the researcher's output feeds into the writer's input
flow_structure = workflow.get_sequential_flow_structure() workflow = SequentialWorkflow(agents=[researcher, writer])
print("Workflow Structure:")
print(flow_structure)
# Get awareness for specific agents # Run the workflow on a task
analyzer_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Analyzer") final_post = workflow.run("The history and future of artificial intelligence")
summarizer_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Summarizer") print(final_post)
validator_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Validator") ```
print(f"\nAnalyzer Awareness: {analyzer_awareness}") ### Legal Practice Workflow
print(f"Summarizer Awareness: {summarizer_awareness}")
print(f"Validator Awareness: {validator_awareness}")
# Run the workflow This example shows how to create a sequential workflow with multiple specialized legal agents.
result = workflow.run(
"Analyze the medical report and provide the appropriate ICD-10 codes."
)
print(f"\nFinal Result: {result}")
```
**Expected Output:** ```python
``` from swarms import Agent, SequentialWorkflow
Workflow Structure:
Sequential Flow Structure:
Step 1: ICD-10 Code Analyzer
Step 2: ICD-10 Code Summarizer (follows: ICD-10 Code Analyzer) (leads to: ICD-10 Code Validator)
Step 3: ICD-10 Code Validator (follows: ICD-10 Code Summarizer)
Analyzer Awareness:
Summarizer Awareness: Sequential awareness: Agent ahead: ICD-10 Code Analyzer | Agent behind: ICD-10 Code Validator
Validator Awareness: Sequential awareness: Agent ahead: ICD-10 Code Summarizer
```
## **How Sequential Awareness Works** # Litigation Agent
litigation_agent = Agent(
agent_name="Alex Johnson",
system_prompt="As a Litigator, you specialize in navigating the complexities of lawsuits. Your role involves analyzing intricate facts, constructing compelling arguments, and devising effective case strategies to achieve favorable outcomes for your clients.",
model_name="gpt-4o-mini",
max_loops=1,
)
### 1. **Automatic Context Injection** # Corporate Attorney Agent
When `team_awareness=True`, the system automatically adds awareness information to each agent's conversation context before they run: corporate_agent = Agent(
agent_name="Emily Carter",
system_prompt="As a Corporate Attorney, you provide expert legal advice on business law matters. You guide clients on corporate structure, governance, compliance, and transactions, ensuring their business operations align with legal requirements.",
model_name="gpt-4o-mini",
max_loops=1,
)
- **First Agent**: No awareness info (starts the workflow) # IP Attorney Agent
- **Middle Agents**: Receive info about both the agent ahead and behind ip_agent = Agent(
- **Last Agent**: Receives info about the agent ahead only agent_name="Michael Smith",
system_prompt="As an IP Attorney, your expertise lies in protecting intellectual property rights. You handle various aspects of IP law, including patents, trademarks, copyrights, and trade secrets, helping clients safeguard their innovations.",
model_name="gpt-4o-mini",
max_loops=1,
)
### 2. **Enhanced Agent Prompts** # Initialize and run the workflow
Each agent receives context like: swarm = SequentialWorkflow(
``` agents=[litigation_agent, corporate_agent, ip_agent],
Sequential awareness: Agent ahead: ICD-10 Code Analyzer | Agent behind: ICD-10 Code Validator name="litigation-practice",
description="Handle all aspects of litigation with a focus on thorough legal analysis and effective case management.",
)
swarm.run("Create a report on how to patent an all-new AI invention and what platforms to use and more.")
``` ```
### 3. **Improved Coordination** ### Startup Idea Validation Workflow
Agents can now:
- Reference previous work more effectively
- Prepare output specifically for the next agent
- Understand their role in the larger workflow
- Provide better context for subsequent steps
## **Advanced Usage Examples** This example demonstrates a 3-step process for generating, validating, and pitching a startup idea.
### **Example 1: Research → Analysis → Report Workflow**
```python ```python
# Create specialized agents from swarms import Agent, SequentialWorkflow
researcher = Agent(
agent_name="Researcher",
system_prompt="Conduct thorough research on the given topic."
)
analyzer = Agent( # 1. Generate an idea
agent_name="Data Analyzer", idea_generator = Agent(
system_prompt="Analyze research data and identify key insights." agent_name="IdeaGenerator",
system_prompt="Generate a unique startup idea.",
model_name="gpt-4o-mini"
) )
reporter = Agent( # 2. Validate the idea
agent_name="Report Writer", validator = Agent(
system_prompt="Write comprehensive reports based on analysis." agent_name="Validator",
system_prompt="Take this startup idea and analyze its market viability.",
model_name="gpt-4o-mini"
) )
# Create workflow with awareness # 3. Create a pitch
workflow = SequentialWorkflow( pitch_creator = Agent(
agents=[researcher, analyzer, reporter], agent_name="PitchCreator",
team_awareness=True, system_prompt="Write a 3-sentence elevator pitch for this validated startup idea.",
time_enabled=True model_name="gpt-4o-mini"
) )
# Run with enhanced coordination # Create the sequential workflow
result = workflow.run("Research and analyze the impact of AI on healthcare") workflow = SequentialWorkflow(agents=[idea_generator, validator, pitch_creator])
# Run the workflow
elevator_pitch = workflow.run("Generate and validate a startup idea in the AI space")
print(elevator_pitch)
``` ```
### **Example 2: Code Review Workflow** ### Advanced: Materials Science Workflow
This example shows a complex workflow with multiple specialized materials science agents.
```python ```python
# Create code review agents from swarms import Agent, SequentialWorkflow
linter = Agent(
agent_name="Code Linter", # Chief Metallurgist
system_prompt="Check code for syntax errors and style violations." chief_metallurgist = Agent(
agent_name="Chief-Metallurgist",
system_prompt="As the Chief Metallurgist, you oversee the entire alloy development process, analyzing atomic structure, phase diagrams, and composition development.",
model_name="gpt-4o",
max_loops=1,
) )
reviewer = Agent( # Materials Scientist
agent_name="Code Reviewer", materials_scientist = Agent(
system_prompt="Review code quality and suggest improvements." agent_name="Materials-Scientist",
system_prompt="As the Materials Scientist, you analyze physical and mechanical properties including density, thermal properties, tensile strength, and microstructure.",
model_name="gpt-4o",
max_loops=1,
) )
tester = Agent( # Process Engineer
agent_name="Code Tester", process_engineer = Agent(
system_prompt="Write and run tests for the reviewed code." agent_name="Process-Engineer",
system_prompt="As the Process Engineer, you develop manufacturing processes including melting procedures, heat treatment protocols, and quality control methods.",
model_name="gpt-4o",
max_loops=1,
) )
# Create workflow # Quality Assurance Specialist
workflow = SequentialWorkflow( qa_specialist = Agent(
agents=[linter, reviewer, tester], agent_name="QA-Specialist",
team_awareness=True system_prompt="As the QA Specialist, you establish quality standards, testing protocols, and documentation requirements.",
model_name="gpt-4o",
max_loops=1,
) )
# Run code review process # Applications Engineer
result = workflow.run("Review and test the authentication module") applications_engineer = Agent(
agent_name="Applications-Engineer",
system_prompt="As the Applications Engineer, you analyze potential applications, performance requirements, and competitive positioning.",
model_name="gpt-4o",
max_loops=1,
)
# Cost Analyst
cost_analyst = Agent(
agent_name="Cost-Analyst",
system_prompt="As the Cost Analyst, you evaluate material costs, production costs, and economic viability.",
model_name="gpt-4o",
max_loops=1,
)
# Create the agent list
agents = [
chief_metallurgist,
materials_scientist,
process_engineer,
qa_specialist,
applications_engineer,
cost_analyst,
]
# Initialize the workflow
swarm = SequentialWorkflow(
name="alloy-development-system",
agents=agents,
)
# Run the workflow
result = swarm.run(
"""Analyze and develop a new high-strength aluminum alloy for aerospace applications
with improved fatigue resistance and corrosion resistance compared to 7075-T6,
while maintaining similar density and cost effectiveness."""
)
print(result)
``` ```
## **Notes:** ## Configuration Options
### Agent Parameters
| Parameter | Description | Default |
|-----------|-------------|---------|
| `agent_name` | Human-readable name for the agent | Required |
| `system_prompt` | Detailed role description and expertise | Required |
| `model_name` | LLM model to use | "gpt-4o-mini" |
| `max_loops` | Maximum number of processing loops | 1 |
### Workflow Parameters
| Parameter | Description | Default |
|-----------|-------------|---------|
| `agents` | List of agents to execute in sequence | Required |
| `name` | Name of the workflow | "SequentialWorkflow" |
| `description` | Description of workflow purpose | Standard description |
| `max_loops` | Number of times to execute workflow | 1 |
| `team_awareness` | Enable sequential awareness features | False |
## Best Practices
- **Enhanced Logging**: The workflow now logs sequential awareness information for better debugging and monitoring. 1. **Clear Agent Roles**: Give each agent a specific, well-defined role with a detailed system prompt.
- **Automatic Context**: No manual configuration needed - awareness is automatically provided when `team_awareness=True`. 2. **Ordered Dependencies**: Arrange agents in an order that makes sense for your workflow (e.g., research before writing).
- **Backward Compatibility**: Existing workflows continue to work without changes. 3. **Agent Names**: Use descriptive agent names that clearly indicate their function.
- **Performance**: Sequential awareness adds minimal overhead while significantly improving coordination. 4. **System Prompts**: Write comprehensive system prompts that explain the agent's expertise and responsibilities.
5. **Task Clarity**: Provide clear, specific tasks when calling `run()`.
### Logging and Error Handling ## Logging and Error Handling
The `run` method now includes enhanced logging to track the sequential awareness flow and captures detailed information about agent interactions: The `run` method includes comprehensive logging to track workflow execution:
```bash ```bash
2023-05-08 10:30:15.456 | INFO | SequentialWorkflow:run:45 - Starting sequential workflow execution 2023-05-08 10:30:15.456 | INFO | Sequential Workflow Name: SequentialWorkflow is ready to run.
2023-05-08 10:30:15.457 | INFO | SequentialWorkflow:run:52 - Added sequential awareness for ICD-10 Code Summarizer: Sequential awareness: Agent ahead: ICD-10 Code Analyzer | Agent behind: ICD-10 Code Validator
2023-05-08 10:30:15.458 | INFO | SequentialWorkflow:run:52 - Added sequential awareness for ICD-10 Code Validator: Sequential awareness: Agent ahead: ICD-10 Code Summarizer
``` ```
## Additional Tips All errors during execution are logged and re-raised for proper error handling.
## Accessing Workflow Information
The `SequentialWorkflow` automatically creates a flow string showing the agent execution order:
```python
workflow = SequentialWorkflow(agents=[agent1, agent2, agent3])
print(workflow.flow) # Output: "Agent1 -> Agent2 -> Agent3"
```
## Advanced Features
### Team Awareness
Enable `team_awareness=True` to provide agents with context about their position in the workflow (this feature is managed by the internal `AgentRearrange` object):
```python
workflow = SequentialWorkflow(
agents=[researcher, writer, editor],
team_awareness=True,
)
```
### Multi-Agent Collaboration Prompt
Set `multi_agent_collab_prompt=True` to automatically append a collaboration prompt to each agent's system prompt:
```python
workflow = SequentialWorkflow(
agents=[agent1, agent2, agent3],
multi_agent_collab_prompt=True,
)
```
- **Enable Team Awareness**: Set `team_awareness=True` to unlock the full potential of sequential coordination. ## Notes
- **Use Descriptive Agent Names**: Clear agent names make the awareness information more useful.
- **Monitor Logs**: Enhanced logging provides insights into how agents are coordinating.
- **Iterative Improvement**: Use the awareness features to refine agent prompts and improve workflow quality.
## **Benefits of Sequential Awareness** - The `SequentialWorkflow` internally uses `AgentRearrange` to manage agent execution.
- Each agent receives the output of the previous agent as its input.
- The workflow executes agents in the exact order they appear in the `agents` list.
- The workflow is designed for production use with comprehensive error handling and logging.
- For parallel execution, consider using `ConcurrentWorkflow` or `SpreadSheetSwarm` instead.
1. **Improved Quality**: Agents produce better output when they understand their context ## Related Architectures
2. **Better Coordination**: Reduced redundancy and improved handoffs between agents
3. **Enhanced Debugging**: Clear visibility into agent interactions and workflow progress
4. **Scalable Workflows**: Easy to add new agents while maintaining coordination
5. **Professional Workflows**: Mimics real-world team collaboration patterns
The SequentialWorkflow with sequential awareness represents a significant advancement in multi-agent coordination, enabling more sophisticated and professional workflows that closely mirror human team collaboration patterns. - **[ConcurrentWorkflow](https://docs.swarms.world/en/latest/swarms/structs/concurrent_workflow/)**: For running agents in parallel
- **[AgentRearrange](https://docs.swarms.world/en/latest/swarms/structs/agent_rearrange/)**: For complex agent relationships and dynamic flows
- **[SwarmRouter](https://docs.swarms.world/en/latest/swarms/structs/swarm_router/)**: Universal orchestrator for switching between different swarm types

Loading…
Cancel
Save