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
List of agents or callables to execute in sequence. Cannot be None or empty.
Format of the output from the workflow. One of
"list", "dict", "dictionary", "str", "string", "all", "final", "last", "json", "yaml", "dict-all-except-first", "str-all-except-first", "dict-final", "list-final". The default "dict" returns the run’s conversation as a list of {"role", "content"} message dicts.If True, each agent receives a collaboration preamble as a system turn for the
duration of the run.
This used to append the preamble to every agent’s
system_prompt with +=, on
the caller’s live Agent objects, at construction time — so constructing the
workflow twice appended it twice, and the text never reached the model because
the prompt is baked into the LLM when it is built. It is now passed through to
AgentRearrange and delivered as a system turn instead.If
True, the step-by-step flow structure is added to the shared conversation as a system message. Each agent always receives the names of the agents ahead and behind it as a system turn, whether or not this is set.If
True, the run’s conversation is written to conversation_history.json in the workflow’s workspace directory after every run(), including one that fails. Off by default, so a run writes nothing to disk.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, at most drift_max_retries times. 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 while retries remain. Used only when
drift_detection=True.Model used by the drift detection judge agent. Used only when
drift_detection=True.Maximum number of pipeline reruns when the alignment score stays below
drift_threshold. Once exhausted, the last output is returned with a
warning. 0 disables reruns, so the output is scored but never regenerated.
Used only when drift_detection=True. Must be >= 0; a negative value
raises ValueError.A comms channel the workflow posts to: the task as
User, then each agent’s answer in order. Agents also read what the channel already holds, so a later run on the same channel continues the conversation. Any channel set on a member agent is detached with a warning, so each message is posted once. See Comms Channels.shared_memory_system has been removed; nothing read it. The constructor still accepts *args and **kwargs, so passing it, or any other unknown keyword, raises no error and has no effect.Methods
run(task, img=None, imgs=None, *args, **kwargs)
Executes a specified task through the agents in the dynamically constructed flow.
Each call starts a fresh conversation on the internal AgentRearrange, so a reused workflow does not carry the previous task’s transcript. With autosave=True, the conversation is saved after the run, even when it fails. An agent that raises stops the pipeline, and the exception propagates to the caller.
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, at most drift_max_retries times, then returns the last output with a warning.
run_batched(tasks)
Executes a batch of tasks through the agents, one task after another. Each task runs on its own clone of the flow, with a fresh conversation and deep-copied agents where the agent supports it, so no task sees another task’s transcript.
run_async(task)
Executes the specified task through the agents asynchronously, by running the internal AgentRearrange.run() in a worker thread with asyncio.to_thread. Drift detection and autosave are not applied on this path; use run() if you need them.
async run_concurrent(tasks)
Executes a batch of tasks through the agents concurrently on a thread pool sized to os.cpu_count(). Each task runs on its own clone of the flow, so concurrent tasks never share a conversation or an agent’s memory. This method is async and must be awaited, but it waits on the thread pool synchronously, so it blocks the event loop until every task finishes.
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.
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:
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.
reliability_check()
Validates the workflow configuration and prepares agents for execution.
Raises:
ValueError: If the agents list is None or empty, if max_loops is set to 0, or ifdrift_max_retriesis negative
Attributes
Usage Examples
Basic Sequential Workflow
Batched Task Processing
Concurrent Task Execution
run_concurrent is async, so it must be awaited:
Async Execution
With Team Awareness
Custom Output Types
With Autosave
WORKSPACE_DIR is unset, it defaults to ./agent_workspace.
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