Documentation Index
Fetch the complete documentation index at: https://docs.swarms.world/llms.txt
Use this file to discover all available pages before exploring further.
Overview
TheSequentialWorkflow class orchestrates the execution of a sequence of agents in a defined workflow. This class enables the construction and execution of a workflow where multiple agents (or callables) are executed in a specified order, passing tasks and optional data through the chain.
Key Features
- Sequential Execution: Agents execute one after another in a defined order
- Synchronous and Asynchronous Support: Both blocking and non-blocking execution modes
- Batched Processing: Execute multiple tasks through the same workflow
- Concurrent Task Processing: Run multiple tasks concurrently using thread pools
- Team Awareness: Agents can be aware of their position in the team structure
- Auto-save Support: Automatically save conversation history to workspace
- Flexible Output Types: Support for various output formats (dict, list, string)
Installation
Class Definition
Parameters
Unique identifier for the workflow instance
Human-readable name for the workflow
Description of the workflow’s purpose
List of agents or callables to execute in sequence. Cannot be None or empty.
Maximum number of times to execute the workflow. Must be greater than 0.
Format of the output from the workflow. Options include “dict”, “list”, “str”, etc.
Optional callable for managing shared memory between agents
If True, appends a collaborative prompt to each agent’s system prompt
Whether agents are aware of the team structure and their position
Whether to enable autosaving of conversation history to workspace
Whether to enable verbose logging
If
True, a judge agent scores the final output’s semantic alignment with the original task after the pipeline completes. If the score falls below drift_threshold, the pipeline reruns and the cycle repeats until the score meets the threshold. If the judge output cannot be parsed, drift checking is skipped and the last result is returned as-is.Minimum alignment score (0.0–1.0) to consider the output acceptable. A warning is logged when the score falls below this value, and the pipeline reruns. Used only when
drift_detection=True.Model used by the drift detection judge agent. Used only when
drift_detection=True.Methods
run(task, img=None, imgs=None, *args, **kwargs)
Executes a specified task through the agents in the dynamically constructed flow.
If drift_detection is configured, a judge agent scores the final output’s semantic alignment with the original task after the pipeline completes. If the score falls below drift_threshold, the pipeline reruns and the cycle repeats until the score meets the threshold.
The task for the agents to execute
An optional image input forwarded to every agent that supports it
Optional list of images. Accepted for API compatibility; only
img is currently forwarded to the underlying flow.The final result, formatted per
output_typerun_batched(tasks)
Executes a batch of tasks through the agents sequentially.
A list of tasks for the agents to execute. Must be a non-empty list of strings.
A list of final results after processing through all agents
run_async(task)
Executes the specified task through the agents asynchronously.
The task for the agents to execute. Must be a non-empty string.
The final result after processing through all agents
run_concurrent(tasks)
Executes a batch of tasks through the agents concurrently using ThreadPoolExecutor.
A list of tasks for the agents to execute. Must be a non-empty list of strings.
A list of final results after processing through all agents
run_stream(task, img=None, with_events=False, **kwargs)
Stream tokens from each agent in pipeline order, in real time. Each agent’s tokens are yielded the moment the LLM produces them; once an agent finishes, its full output is handed off to the next agent — the same hand-off as run(), just streamed.
Delegates to AgentRearrange.run_stream internally.
Initial task passed to the first agent in the pipeline.
Optional image input forwarded to every agent.
When
False, yield plain token strings. When True, yield structured event dicts (agent_start, token, agent_end) — useful for per-agent UI panels or attributing each token to its emitting agent.Sync generator. Yields plain token strings by default, or event dicts when
with_events=True.arun_stream(task, img=None, with_events=False, **kwargs)
Async generator version of run_stream. Drop-in for any async caller (FastAPI’s StreamingResponse, async background workers, etc.). Same parameter and yield semantics as the sync version.
Async generator. Yields plain token strings by default, or event dicts when
with_events=True.Structured events
When called withwith_events=True, both methods yield three event types:
| Type | Fields | When emitted |
|---|---|---|
agent_start | agent | Right before an agent begins streaming |
token | agent, token | For every token the agent emits |
agent_end | agent, output | After the agent finishes; carries the full output |
max_loops > 1 and drift_detection are not applied in streaming mode. Use run() if you need those.sequential_flow()
Constructs a string representation of the agent execution order.
A string showing the order of agent execution (e.g., “AgentA -> AgentB -> AgentC”)
reliability_check()
Validates the workflow configuration and prepares agents for execution.
Raises:
ValueError: If the agents list is None or empty, or if max_loops is set to 0
Attributes
| Attribute | Type | Description |
|---|---|---|
id | str | Unique identifier for the workflow instance |
name | str | Human-readable name for the workflow |
description | str | Description of the workflow’s purpose |
agents | List[Union[Agent, Callable]] | List of agents or callables to execute in sequence |
max_loops | int | Maximum number of times to execute the workflow |
output_type | OutputType | Format of the output from the workflow |
shared_memory_system | callable | Optional shared memory helper |
multi_agent_collab_prompt | bool | Whether the collaboration prompt is appended to each agent |
team_awareness | bool | Whether team-awareness is enabled on the underlying AgentRearrange |
autosave | bool | Whether conversation history is autosaved to disk |
verbose | bool | Whether verbose logging is on |
drift_threshold | float | Minimum alignment score required when drift_detection=True |
drift_agent | Optional[Agent] | Judge agent used for drift detection; None when disabled |
swarm_workspace_dir | Optional[str] | Workspace directory used for autosave; populated by _setup_autosave() |
flow | str | String representation of the agent execution order |
agent_rearrange | AgentRearrange | Internal helper for managing agent execution |
Usage Examples
Basic Sequential Workflow
Batched Task Processing
Concurrent Task Execution
Async Execution
With Team Awareness
Custom Output Types
With Autosave
Error Handling
Best Practices
- Agent Design: Ensure each agent has a clear, specific role in the sequence
- Error Handling: Use try-except blocks around workflow execution
- Verbose Mode: Enable verbose logging during development for debugging
- Autosave: Enable autosave for important workflows to preserve conversation history
- Task Clarity: Provide clear, specific tasks to get the best results
- Resource Management: Use
run_concurrentfor I/O-bound tasks to improve performance - Team Awareness: Enable team awareness for complex workflows where context matters
Common Use Cases
- Content Creation Pipelines: Research -> Write -> Edit workflows
- Data Processing: Extract -> Transform -> Load (ETL) pipelines
- Analysis Workflows: Collect -> Analyze -> Report sequences
- Quality Assurance: Create -> Review -> Approve chains
- Multi-Stage Reasoning: Break complex problems into sequential steps
Related Classes
- AgentRearrange: For more complex, non-linear agent orchestration
- ConcurrentWorkflow: For parallel agent execution
- GraphWorkflow: For DAG-based agent workflows
- Agent: The base agent class used in workflows