---
title: "SequentialAgent Pipeline: Chaining Deterministic Multi-Stage Workflows"
date: "2026-11-29T08:55:11+07:00"
description: "Master Google ADK's SequentialAgent to build deterministic, multi-stage pipelines that pass context, transform data, and enforce predictable business logic."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-sequential-agent-pipeline-workflows.jpg"
alt: "Google ADK SequentialAgent Pipeline Architecture"
tags: ['google-adk', 'multi-agent', 'sequential-agent', 'python', 'architecture']
---

While autonomous agents with dynamic delegation are flexible, many enterprise business processes require **deterministic execution order**. For example, an automated content publishing system must *always* follow a strict order:
1. Ingest raw notes and extract facts.
2. Draft the article.
3. Validate regulatory and compliance rules.
4. Translate into target languages.

Allowing a model to decide which step to execute next introduces non-determinism, potential step omission, and unpredictable loops.

Google Agent Development Kit (ADK) provides `SequentialAgent` to chain agents into fixed, deterministic pipelines. In this tutorial, we will explore `SequentialAgent` mechanics, how data flows across stages using `output_key` and state injection, and how to build a production pipeline.

---

## 1. How `SequentialAgent` Works

A `SequentialAgent` is a container agent that manages a list of subordinate agents (`sub_agents`). When invoked, it executes each sub-agent in order:

```
[User Input]
     │
     ▼
┌──────────────────────────────────────────────┐
│ SequentialAgent: "document_pipeline"         │
│                                              │
│  Stage 1: Extractor Agent                    │
│    writes to session.state["facts"]          │
│          │                                   │
│          ▼                                   │
│  Stage 2: Drafter Agent                      │
│    reads {facts}, writes to ["draft"]        │
│          │                                   │
│          ▼                                   │
│  Stage 3: Compliance Validator Agent         │
│    reads {draft}, writes to ["approved_doc"] │
└──────────────────────────────────────────────┘
     │
     ▼
[Final Output]
```

### Key Behavioral Guarantees
- **Deterministic Sequence:** Sub-agents execute strictly in the order defined in `sub_agents=[agent_1, agent_2, ...]`.
- **Shared Session State:** All sub-agents operate within the same `Session`. Data written by an earlier stage is instantly visible to subsequent stages.
- **Dynamic Prompt Injection:** Later agents can reference prior outputs in their instructions using the `{state_key}` template syntax.

---

## 2. Passing Data Between Pipeline Stages

ADK provides two primary mechanisms to coordinate stage outputs:

1. **`output_key` Parameter:** When configuring an `Agent`, setting `output_key="my_key"` automatically saves the agent's final text response into `session.state["my_key"]`.
2. **Dynamic Template Substitution:** In any subsequent agent's `instruction`, you can write `{my_key}`. ADK substitutes this value from state before passing the prompt to Gemini.

---

## 3. Building an Automated Report Generation Pipeline

Let's build a complete three-stage pipeline that ingests raw telemetry logs, identifies anomalies, and generates an executive summary.

```python
import asyncio
from google.adk.agents import Agent, SequentialAgent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

# Stage 1: Data Analyzer
analyzer_agent = Agent(
    name="telemetry_analyzer",
    model="gemini-3.8-flash",
    instruction="""
    You are an expert site reliability analyst.
    Examine the provided raw logs. Identify all error codes, latency spikes,
    and service outages. Format your output as a clear bulleted list of key findings.
    """,
    output_key="analysis_findings",
)

# Stage 2: Root Cause Investigator
investigator_agent = Agent(
    name="root_cause_investigator",
    model="gemini-3.8-flash",
    instruction="""
    You are a root cause specialist.
    Based on the following incident findings:
    {analysis_findings}

    Hypothesize the primary root cause and assess the business impact (P0, P1, P2).
    """,
    output_key="root_cause_assessment",
)

# Stage 3: Executive Briefing Drafter
executive_drafter = Agent(
    name="executive_drafter",
    model="gemini-3.8-flash",
    instruction="""
    You are an executive communications specialist.
    Using the incident findings and root cause assessment:
    Findings: {analysis_findings}
    Root Cause: {root_cause_assessment}

    Write a concise 3-paragraph executive memo suitable for the VP of Engineering.
    Include a summary of the outage, immediate remediation steps, and long-term preventions.
    """,
    output_key="final_executive_memo",
)

# Assemble into Sequential Pipeline
incident_pipeline = SequentialAgent(
    name="incident_triage_pipeline",
    sub_agents=[
        analyzer_agent,
        investigator_agent,
        executive_drafter,
    ],
    description="Processes raw system logs into an executive incident briefing.",
)
```

---

## 4. Executing and Inspecting Pipeline State

We run the pipeline through an ADK `Runner` and inspect the intermediate states:

```python
async def run_pipeline():
    session_service = InMemorySessionService()
    runner = Runner(agent=incident_pipeline, session_service=session_service)
    session = await session_service.get_or_create("incident_001")

    raw_incident_logs = """
    2026-11-29 04:12:01 UTC - [api-gateway] - 504 Gateway Timeout (count: 420 req/s)
    2026-11-29 04:12:08 UTC - [db-pool] - ConnectionPoolExhausted: max connections 100 reached
    2026-11-29 04:12:15 UTC - [billing-service] - Thread deadlock detected in process_payment()
    2026-11-29 04:13:30 UTC - [k8s-scaler] - HPA failed to spin up replica pods due to cluster CPU quota
    """

    print("=== Executing Sequential Pipeline ===")
    async for event in runner.run_async(session=session, message=raw_incident_logs):
        if event.author:
            print(f"[{event.author} finished turn]")

    # Inspect the intermediate state outputs
    print("\n--- Intermediate State Keys ---")
    print("Findings Stored:", bool(session.state.get("analysis_findings")))
    print("Root Cause Stored:", bool(session.state.get("root_cause_assessment")))

    print("\n--- Final Executive Memo ---")
    print(session.state.get("final_executive_memo"))

if __name__ == "__main__":
    asyncio.run(run_pipeline())
```

---

## 5. SequentialAgent vs Autonomous Swarms

| Feature | `SequentialAgent` | Autonomous Swarm (`sub_agents` delegation) |
| :--- | :--- | :--- |
| **Execution Flow** | Deterministic, predefined order. | Model dynamically decides next agent. |
| **Token Predictability** | Highly predictable; exactly $N$ LLM turns. | Variable; depends on model delegation decisions. |
| **Risk of Infinite Loops** | Zero risk of loop; executes each stage once. | Requires hop limits and turn counters. |
| **Best For** | Multi-step transformations, ETL pipelines, regulatory audits. | Open-ended research, customer support triage, troubleshooting. |

---

## 6. Advanced Patterns: Combining Tools inside Sequential Stages

Individual sub-agents within a `SequentialAgent` can have their own specialized toolsets. For example:
- Stage 1 can have database querying tools to fetch raw records.
- Stage 2 can have calculation tools to perform statistical aggregations.
- Stage 3 can have webhook dispatch tools to deliver the finished report to Slack.

By isolating tools to the stages that need them, you minimize prompt token overhead and eliminate the risk of the model invoking tools at the wrong stage of the workflow.

**Takeaway:** `SequentialAgent` brings order, repeatability, and deterministic reliability to multi-stage AI workflows in Google ADK.

## Sources
- Google ADK Documentation: https://adk.dev/
- Google GenAI SDK: https://github.com/googleapis/python-genai
- Google Agents CLI Docs: https://github.com/google/agents-cli
