removed nonexistent functionality from sequential workflow docs

pull/1153/head
Steve-Dusty 3 days ago
parent 567b25e8e1
commit 732335d8ee

@ -1,283 +1,375 @@
# SequentialWorkflow Documentation
**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:**
- Workflows where each step depends on the previous one, such as assembly lines or sequential data processing.
- 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
graph TD
A[First Agent] --> B[Second Agent]
B --> C[Third Agent]
C --> D[Fourth Agent]
style A fill:#e1f5fe
style B fill:#f3e5f5
style C fill:#e8f5e8
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
| Attribute | Type | Description |
|------------------|---------------|--------------------------------------------------|
| `agents` | `List[Agent]` | The list of agents in the workflow. |
| `flow` | `str` | A string representing the order of agents. |
| `agent_rearrange`| `AgentRearrange` | Manages the dynamic execution of agents with sequential awareness. |
| `team_awareness` | `bool` | **NEW**: Enables sequential awareness features. Defaults to `False`. |
| `time_enabled` | `bool` | **NEW**: Enables timestamps in conversation. Defaults to `False`. |
| `message_id_on` | `bool` | **NEW**: Enables message IDs in conversation. Defaults to `False`. |
| `id` | `str` | Unique identifier for the workflow instance. Defaults to `"sequential_workflow"`. |
| `name` | `str` | Human-readable name for the workflow. Defaults to `"SequentialWorkflow"`. |
| `description` | `str` | Description of the workflow's purpose. |
| `agents` | `List[Union[Agent, Callable]]` | The list of agents or callables in the workflow. |
| `max_loops` | `int` | Maximum number of times to execute the workflow. Defaults to `1`. |
| `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
### `__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:**
- `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`.
- `team_awareness` (`bool`, optional): **NEW**: Enables sequential awareness features. Defaults to `False`.
- `time_enabled` (`bool`, optional): **NEW**: Enables timestamps in conversation. Defaults to `False`.
- `message_id_on` (`bool`, optional): **NEW**: Enables message IDs in conversation. Defaults to `False`.
- `output_type` (`OutputType`, optional): Output format for the workflow. Defaults to `"dict"`.
- `shared_memory_system` (`callable`, optional): Callable for shared memory management. Defaults to `None`.
- `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.
- `**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:**
- `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:**
- `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:**
- `agent_name` (`str`): The name of the agent to get awareness for.
- `task` (`str`): The task for the agents to execute.
- **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:**
- `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
from swarms import Agent, SequentialWorkflow
# Initialize agents for individual tasks
agent1 = Agent(
agent_name="ICD-10 Code Analyzer",
system_prompt="Analyze medical data and provide relevant ICD-10 codes.",
model_name="gpt-4.1",
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,
# Agent 1: The Researcher
researcher = Agent(
agent_name="Researcher",
system_prompt="Your job is to research the provided topic and provide a detailed summary.",
model_name="gpt-4o-mini",
)
# Create the Sequential workflow with enhanced awareness
workflow = SequentialWorkflow(
agents=[agent1, agent2, agent3],
max_loops=1,
verbose=False,
team_awareness=True, # Enable sequential awareness
time_enabled=True, # Enable timestamps
message_id_on=True # Enable message IDs
# Agent 2: The Writer
writer = Agent(
agent_name="Writer",
system_prompt="Your job is to take the research summary and write a beautiful, engaging blog post about it.",
model_name="gpt-4o-mini",
)
# Get workflow structure information
flow_structure = workflow.get_sequential_flow_structure()
print("Workflow Structure:")
print(flow_structure)
# Create a sequential workflow where the researcher's output feeds into the writer's input
workflow = SequentialWorkflow(agents=[researcher, writer])
# Get awareness for specific agents
analyzer_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Analyzer")
summarizer_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Summarizer")
validator_awareness = workflow.get_agent_sequential_awareness("ICD-10 Code Validator")
# Run the workflow on a task
final_post = workflow.run("The history and future of artificial intelligence")
print(final_post)
```
print(f"\nAnalyzer Awareness: {analyzer_awareness}")
print(f"Summarizer Awareness: {summarizer_awareness}")
print(f"Validator Awareness: {validator_awareness}")
### Legal Practice Workflow
# Run the workflow
result = workflow.run(
"Analyze the medical report and provide the appropriate ICD-10 codes."
)
print(f"\nFinal Result: {result}")
```
This example shows how to create a sequential workflow with multiple specialized legal agents.
**Expected Output:**
```
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
```
```python
from swarms import Agent, SequentialWorkflow
## **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**
When `team_awareness=True`, the system automatically adds awareness information to each agent's conversation context before they run:
# Corporate Attorney Agent
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)
- **Middle Agents**: Receive info about both the agent ahead and behind
- **Last Agent**: Receives info about the agent ahead only
# IP Attorney Agent
ip_agent = Agent(
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**
Each agent receives context like:
```
Sequential awareness: Agent ahead: ICD-10 Code Analyzer | Agent behind: ICD-10 Code Validator
# Initialize and run the workflow
swarm = SequentialWorkflow(
agents=[litigation_agent, corporate_agent, ip_agent],
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**
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
### Startup Idea Validation Workflow
## **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
# Create specialized agents
researcher = Agent(
agent_name="Researcher",
system_prompt="Conduct thorough research on the given topic."
)
from swarms import Agent, SequentialWorkflow
analyzer = Agent(
agent_name="Data Analyzer",
system_prompt="Analyze research data and identify key insights."
# 1. Generate an idea
idea_generator = Agent(
agent_name="IdeaGenerator",
system_prompt="Generate a unique startup idea.",
model_name="gpt-4o-mini"
)
reporter = Agent(
agent_name="Report Writer",
system_prompt="Write comprehensive reports based on analysis."
# 2. Validate the idea
validator = Agent(
agent_name="Validator",
system_prompt="Take this startup idea and analyze its market viability.",
model_name="gpt-4o-mini"
)
# Create workflow with awareness
workflow = SequentialWorkflow(
agents=[researcher, analyzer, reporter],
team_awareness=True,
time_enabled=True
# 3. Create a pitch
pitch_creator = Agent(
agent_name="PitchCreator",
system_prompt="Write a 3-sentence elevator pitch for this validated startup idea.",
model_name="gpt-4o-mini"
)
# Run with enhanced coordination
result = workflow.run("Research and analyze the impact of AI on healthcare")
# Create the sequential workflow
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
# Create code review agents
linter = Agent(
agent_name="Code Linter",
system_prompt="Check code for syntax errors and style violations."
from swarms import Agent, SequentialWorkflow
# Chief Metallurgist
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(
agent_name="Code Reviewer",
system_prompt="Review code quality and suggest improvements."
# Materials Scientist
materials_scientist = Agent(
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(
agent_name="Code Tester",
system_prompt="Write and run tests for the reviewed code."
# Process Engineer
process_engineer = Agent(
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
workflow = SequentialWorkflow(
agents=[linter, reviewer, tester],
team_awareness=True
# Quality Assurance Specialist
qa_specialist = Agent(
agent_name="QA-Specialist",
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
result = workflow.run("Review and test the authentication module")
# Applications Engineer
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.
- **Automatic Context**: No manual configuration needed - awareness is automatically provided when `team_awareness=True`.
- **Backward Compatibility**: Existing workflows continue to work without changes.
- **Performance**: Sequential awareness adds minimal overhead while significantly improving coordination.
1. **Clear Agent Roles**: Give each agent a specific, well-defined role with a detailed system prompt.
2. **Ordered Dependencies**: Arrange agents in an order that makes sense for your workflow (e.g., research before writing).
3. **Agent Names**: Use descriptive agent names that clearly indicate their function.
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
2023-05-08 10:30:15.456 | INFO | SequentialWorkflow:run:45 - Starting sequential workflow execution
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
2023-05-08 10:30:15.456 | INFO | Sequential Workflow Name: SequentialWorkflow is ready to run.
```
## 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.
- **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.
## Notes
## **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
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
## Related Architectures
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