---
title: "Agent Architecture Patterns: Building Intelligent Systems That Scale in 2026"
date: 2025-11-10T00:00:00.000Z
description: "Master 4 essential agent architecture patterns for 2026: sequential, parallel, loop, and custom agents. Learn concepts, real-world examples, and when to use each pattern for optimal performance."
tags: [agent architecture, AI agents, sequential agents, parallel agents, loop agents, custom agents, agent design patterns, AI system design, multi-agent systems]
canonical: https://vatsalshah.ca/blog/agent-architecture-patterns
---
## Introduction

**Understanding agent architecture patterns is fundamental to building intelligent systems that can handle complex workflows efficiently.** Whether you're processing documents sequentially, analyzing data in parallel, iterating through loops, or creating custom workflows, choosing the right architecture pattern significantly impacts performance, reliability, and cost.

**The Business Impact:**
- **Efficiency**: Proper architecture patterns reduce processing time by 50-70%
- **Scalability**: Parallel patterns enable handling thousands of concurrent tasks
- **Reliability**: Structured patterns prevent errors and improve system stability
- **Cost Reduction**: Optimized patterns reduce infrastructure costs by 40-60%
- **Maintainability**: Clear patterns make systems easier to understand and modify

**Real Results from Implementation:**
- **E-commerce**: Order processing time reduced by 65% using sequential agent patterns
- **Financial Services**: Risk analysis completed 3x faster with parallel agent architectures
- **Content Generation**: Automated content workflows improved throughput by 80% using loop patterns
- **Healthcare**: Patient data processing reduced manual intervention by 90% with custom workflows

**What You'll Learn:**
- 4 essential agent architecture patterns and their core concepts
- When to use each pattern for optimal performance
- Real-world business examples and use cases
- Best practices for implementing each pattern
- How to combine patterns for complex workflows

> **Note:** This guide focuses on architectural concepts and real-world applications. For production deployment guidance, see our [Production-Ready AI Agent Architecture guide](/blog/production-ready-ai-agent-architecture).

**Code Examples:** The implementation examples in this article use the Agent Development Kit (ADK) to demonstrate how each pattern works in practice. ADK provides a clean, standardized way to build agent workflows, making it easier to understand the core concepts. The patterns themselves are framework-agnostic and can be implemented using any agent development toolkit.

---

## 1. Sequential Agents: Step-by-Step Processing

Sequential agents execute tasks one after another in a defined order, where each agent's output becomes the next agent's input. Think of it like an assembly line where each station depends on the previous one completing its work. [A five-agent content pipeline built as a sequential chain](/blog/ai-powered-instagram-content-generator-multi-agent-workflow) is a working example of this pattern end to end.

**Sequential Agent Flow:**

```mermaid
flowchart LR
    A[Input] --> B[Agent 1]
    B --> C[Agent 2]
    C --> D[Agent 3]
    D --> E[Agent 4]
    E --> F[Output]
    
    style A fill:#e1f5ff
    style F fill:#e1f5ff
    style B fill:#fff4e1
    style C fill:#fff4e1
    style D fill:#fff4e1
    style E fill:#fff4e1
```

### 1.1 Core Concept

Sequential agents follow a **linear execution model** where:
- Each agent waits for the previous one to complete
- Data flows in one direction: Input → Agent 1 → Agent 2 → ... → Output
- Failures at any stage stop the entire pipeline
- Each stage can validate and transform the data before passing it forward

**Key Characteristics:**
- **Dependency Chain**: Each agent depends on the previous agent's output
- **Order Matters**: Changing the order changes the result
- **Error Propagation**: One failure stops the entire chain
- **Resource Efficiency**: Lower memory footprint than parallel execution

### 1.2 When to Use Sequential Agents

**Perfect For:**
- **Document Processing Pipelines**: Extract text → Analyze sentiment → Generate summary → Format output
- **Data Transformation Workflows**: Raw data → Clean → Validate → Transform → Store
- **Multi-Stage Validation**: Input validation → Business rule validation → Compliance check → Approval
- **Content Generation**: Research → Draft → Review → Edit → Publish
- **E-commerce Order Processing**: Validate order → Check inventory → Process payment → Generate shipping label → Send confirmation

**Not Ideal For:**
- Independent tasks that don't depend on each other
- Tasks that can run simultaneously
- High-throughput scenarios where speed is critical

### 1.3 Real-World Business Examples

**Example 1: Customer Onboarding System**

A financial services company uses sequential agents for customer onboarding:

1. **Document Extraction Agent**: Extracts information from uploaded ID documents
2. **Verification Agent**: Validates extracted data against government databases
3. **Risk Assessment Agent**: Analyzes customer risk profile based on verified data
4. **Account Creation Agent**: Creates account if all checks pass
5. **Welcome Communication Agent**: Sends personalized welcome email

**Business Impact**: Reduced onboarding time from 2 days to 15 minutes, improving customer satisfaction by 85%.

**Example 2: Content Publishing Pipeline**

A media company uses sequential agents for content publishing:

1. **Research Agent**: Gathers information from multiple sources
2. **Draft Agent**: Creates initial content based on research
3. **Fact-Check Agent**: Verifies claims and statistics
4. **SEO Optimization Agent**: Optimizes content for search engines
5. **Formatting Agent**: Formats content for publication
6. **Publishing Agent**: Publishes to multiple platforms

**Business Impact**: Increased content production by 300% while maintaining quality standards.

### 1.4 Implementation Example: Customer Onboarding System

<details>
<summary><strong>🛠️ Click to view Sequential Agent Implementation with ADK</strong></summary>

```python
from adk import Agent, SequentialWorkflow
from adk.tools import document_parser, database_query, email_sender
from typing import Dict, Any
from datetime import datetime

# Define individual agents using ADK
document_extraction_agent = Agent(
    name="document_extractor",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a document extraction specialist. Extract key information from 
    customer documents including name, date of birth, address, document type, 
    and document number. Return structured data with confidence scores.
    """,
    description="Extracts information from uploaded ID documents",
    tools=[document_parser]
)

verification_agent = Agent(
    name="verification_agent",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a verification specialist. Validate extracted customer data against 
    government databases. Check for matches and return verification scores.
    Raise errors if verification fails.
    """,
    description="Validates extracted data against government databases",
    tools=[database_query]
)

risk_assessment_agent = Agent(
    name="risk_assessor",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a risk assessment specialist. Analyze customer risk profile based 
    on verified data. Calculate risk scores and determine risk levels (low, 
    medium, high). Provide recommendations for account approval.
    """,
    description="Analyzes customer risk profile and provides recommendations"
)

account_creation_agent = Agent(
    name="account_creator",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are an account creation specialist. Create customer accounts if all 
    checks pass. Generate unique account IDs and set account status. Only 
    create accounts when recommendation is 'approve'.
    """,
    description="Creates customer accounts after all validations pass"
)

welcome_communication_agent = Agent(
    name="welcome_communicator",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a communication specialist. Send personalized welcome emails to 
    new customers. Use appropriate email templates based on account type.
    """,
    description="Sends personalized welcome emails to new customers",
    tools=[email_sender]
)

# Create sequential workflow using ADK
onboarding_workflow = SequentialWorkflow(
    name="customer_onboarding",
    agents=[
        document_extraction_agent,
        verification_agent,
        risk_assessment_agent,
        account_creation_agent,
        welcome_communication_agent
    ]
)

# Usage example
async def main():
    # Prepare customer data
    customer_data = {
        'customer_id': 'CUST001',
        'document_name': 'passport.pdf',
        'email': 'customer@example.com',
        'document_content': '...'  # Document content or file path
    }
    
    # Execute sequential workflow
    result = await onboarding_workflow.run(customer_data)
    
    if result.success:
        print(f"\n✓ Onboarding completed successfully!")
        print(f"  Account ID: {result.output.get('account_id')}")
        print(f"  Risk Level: {result.output.get('risk_level')}")
        print(f"  Email Sent: {result.output.get('welcome_email_sent')}")
    else:
        print(f"\n✗ Onboarding failed: {result.error}")

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

**Key ADK Concepts Demonstrated:**
- **Agent Definition**: Each agent is defined with name, model, instruction, and tools
- **SequentialWorkflow**: Chains agents together to execute in order
- **Tool Integration**: Agents can use tools like document_parser, database_query, email_sender
- **Data Flow**: Output from one agent automatically becomes input to the next
- **Error Handling**: ADK handles errors and propagates them through the workflow

</details>

### 1.5 Best Practices

**Error Handling:**
- Implement validation at each stage
- Use try-catch blocks to handle failures gracefully
- Log errors with context for debugging
- Consider retry mechanisms for transient failures

**Performance Optimization:**
- Cache results when possible
- Minimize data transformation overhead
- Use streaming for large datasets
- Set appropriate timeouts for each stage

**Monitoring:**
- Track execution time for each agent
- Monitor success/failure rates
- Alert on performance degradation
- Maintain audit trails for compliance

For more on building reliable systems, see our guide on [10 Best Practices for Reliable AI Agents](/blog/10-best-practices-reliable-ai-agents).

---

## 2. Parallel Agents: Concurrent Processing

Parallel agents execute multiple tasks simultaneously, dramatically reducing total processing time. Think of it like having multiple workers tackling different parts of a project at the same time.

**Parallel Agent Flow:**

```mermaid
flowchart TD
    A[Input] --> B[Agent 1]
    A --> C[Agent 2]
    A --> D[Agent 3]
    A --> E[Agent 4]
    
    B --> F[Results Aggregator]
    C --> F
    D --> F
    E --> F
    F --> G[Output]
    
    style A fill:#e1f5ff
    style G fill:#e1f5ff
    style B fill:#fff4e1
    style C fill:#fff4e1
    style D fill:#fff4e1
    style E fill:#fff4e1
    style F fill:#e8f5e9
```

### 2.1 Core Concept

Parallel agents follow a **concurrent execution model** where:
- Multiple agents process different tasks simultaneously
- All agents receive the same input (or parts of it)
- Results are aggregated after all agents complete
- Independent failures don't stop other agents

**Key Characteristics:**
- **Independence**: Agents don't depend on each other's output
- **Speed**: Dramatically faster than sequential execution
- **Resource Intensive**: Requires more CPU, memory, and network resources
- **Fault Tolerance**: One failure doesn't stop others

### 2.2 When to Use Parallel Agents

**Perfect For:**
- **Independent Data Analysis**: Analyzing different datasets simultaneously
- **Multi-Source Validation**: Checking customer data against multiple databases at once
- **E-commerce Order Processing**: Checking inventory, validating payment, calculating shipping, and sending notifications concurrently
- **Content Aggregation**: Fetching content from multiple sources simultaneously
- **Risk Assessment**: Running multiple risk checks in parallel

**Not Ideal For:**
- Tasks with dependencies between agents
- Resource-constrained environments
- When order of execution matters

### 2.3 Real-World Business Examples

**Example 1: E-commerce Order Processing**

An e-commerce platform uses parallel agents to process orders:

1. **Inventory Check Agent**: Verifies product availability (runs in parallel)
2. **Payment Validation Agent**: Validates payment information (runs in parallel)
3. **Shipping Calculator Agent**: Calculates shipping costs (runs in parallel)
4. **Fraud Detection Agent**: Checks for suspicious patterns (runs in parallel)
5. **Results Aggregator**: Combines all results and makes final decision

**Business Impact**: Reduced order processing time from 5 seconds to 1.2 seconds, handling 10x more orders during peak periods.

**Example 2: Financial Risk Analysis**

A bank uses parallel agents for loan risk assessment:

1. **Credit Score Agent**: Checks credit history (runs in parallel)
2. **Income Verification Agent**: Validates income documents (runs in parallel)
3. **Debt Analysis Agent**: Analyzes existing debt obligations (runs in parallel)
4. **Market Analysis Agent**: Assesses market conditions (runs in parallel)
5. **Decision Engine**: Combines all analyses for final decision

**Business Impact**: Reduced loan processing time from 3 days to 2 hours, improving customer experience and reducing operational costs by 60%.

**Example 3: Content Research System**

A research platform uses parallel agents to gather information:

1. **Web Search Agent**: Searches web sources (runs in parallel)
2. **Database Query Agent**: Queries internal databases (runs in parallel)
3. **API Fetch Agent**: Retrieves data from external APIs (runs in parallel)
4. **Document Analysis Agent**: Analyzes uploaded documents (runs in parallel)
5. **Content Aggregator**: Combines all sources into comprehensive report

**Business Impact**: Reduced research time from 4 hours to 15 minutes, enabling researchers to handle 16x more projects.

### 2.4 Implementation Example: E-commerce Order Processing

<details>
<summary><strong>🛠️ Click to view Parallel Agent Implementation with ADK</strong></summary>

```python
from adk import Agent, ParallelWorkflow
from adk.tools import inventory_api, payment_gateway, shipping_api, fraud_detection_service
from typing import Dict, Any

# Define agents for parallel execution using ADK
inventory_check_agent = Agent(
    name="inventory_checker",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are an inventory specialist. Check product availability for order items.
    Verify stock levels and confirm if all items are available. Return availability 
    status for each item and overall order availability.
    """,
    description="Checks inventory availability for order items",
    tools=[inventory_api]
)

payment_validation_agent = Agent(
    name="payment_validator",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a payment validation specialist. Validate payment information including 
    card number, payment method, and amount. Verify payment credentials and return 
    validation status.
    """,
    description="Validates payment information for orders",
    tools=[payment_gateway]
)

shipping_calculator_agent = Agent(
    name="shipping_calculator",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a shipping specialist. Calculate shipping costs based on order weight, 
    destination, and shipping method. Return shipping cost, carrier, and estimated 
    delivery time.
    """,
    description="Calculates shipping costs and delivery estimates",
    tools=[shipping_api]
)

fraud_detection_agent = Agent(
    name="fraud_detector",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a fraud detection specialist. Analyze order patterns, customer history, 
    and transaction details to detect potential fraud. Calculate risk scores and 
    determine risk levels (low, medium, high). Provide recommendations.
    """,
    description="Detects fraudulent patterns in orders",
    tools=[fraud_detection_service]
)

# Create parallel workflow using ADK
order_processing_workflow = ParallelWorkflow(
    name="order_processing",
    agents={
        'inventory_check': inventory_check_agent,
        'payment_validation': payment_validation_agent,
        'shipping_calculator': shipping_calculator_agent,
        'fraud_detection': fraud_detection_agent
    },
    aggregator=lambda results: {
        'order_status': 'approved' if (
            results['inventory_check'].get('available') and
            results['payment_validation'].get('valid') and
            results['fraud_detection'].get('risk_level') == 'low'
        ) else 'rejected',
        'inventory_available': results['inventory_check'].get('available', False),
        'payment_valid': results['payment_validation'].get('valid', False),
        'fraud_risk': results['fraud_detection'].get('risk_level', 'unknown'),
        'shipping_cost': results['shipping_calculator'].get('cost', 0),
        'estimated_delivery': results['shipping_calculator'].get('delivery_days', 0)
    }
)

# Usage example
async def main():
    # Prepare order data
    order_data = {
        'order_id': 'ORD-2025-001',
        'items': [
            {'id': 'ITEM-001', 'quantity': 2, 'weight': 1.5},
            {'id': 'ITEM-002', 'quantity': 1, 'weight': 0.8}
        ],
        'total': 149.99,
        'payment': {
            'method': 'credit_card',
            'card_number': '4111111111111111'
        },
        'shipping_address': {
            'city': 'New York',
            'zip': '10001'
        },
        'customer_history': {
            'account_age_days': 180,
            'previous_orders': 5
        }
    }
    
    # Execute parallel workflow
    print("Processing order in parallel...\n")
    result = await order_processing_workflow.run(order_data)
    
    if result.success:
        print(f"\n✓ Order processing completed!")
        print(f"  Order Status: {result.output.get('order_status')}")
        print(f"  Inventory: {'Available' if result.output.get('inventory_available') else 'Unavailable'}")
        print(f"  Payment: {'Valid' if result.output.get('payment_valid') else 'Invalid'}")
        print(f"  Fraud Risk: {result.output.get('fraud_risk')}")
        print(f"  Shipping Cost: ${result.output.get('shipping_cost')}")
        print(f"  Execution Time: {result.execution_time:.2f}s")
    else:
        print(f"\n✗ Order processing failed: {result.error}")

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

**Key ADK Concepts Demonstrated:**
- **ParallelWorkflow**: Executes multiple agents simultaneously
- **Agent Independence**: Each agent receives the same input and works independently
- **Result Aggregation**: Custom aggregator function combines parallel results
- **Tool Integration**: Each agent uses specialized tools (APIs, services)
- **Error Isolation**: Individual agent failures don't stop other agents

</details>

### 2.5 Best Practices

**Resource Management:**
- Set limits on concurrent agents to prevent resource exhaustion
- Use connection pooling for database and API calls
- Implement rate limiting for external services
- Monitor resource usage (CPU, memory, network)

**Error Handling:**
- Handle individual agent failures without stopping others
- Implement partial success scenarios
- Use circuit breakers for external dependencies
- Aggregate errors for comprehensive reporting

**Performance Optimization:**
- Balance parallelism with resource constraints
- Use async/await patterns for I/O-bound tasks
- Consider batching for similar operations
- Cache frequently accessed data

**Result Aggregation:**
- Define clear aggregation rules
- Handle conflicting results from different agents
- Implement voting mechanisms when needed
- Provide confidence scores for aggregated results

For more on scaling multi-agent systems, see our [AI Agent Orchestration guide](/blog/ai-agent-orchestration-multi-agent-systems-2025).

---

## 3. Loop Agents: Iterative Processing

Loop agents execute tasks repeatedly until a condition is met. Think of it like refining a product through multiple iterations until it meets quality standards.

**Loop Agent Flow:**

```mermaid
flowchart TD
    A[Input] --> B[Initialize]
    B --> C[Agent Execution]
    C --> D{Condition Met?}
    D -->|No| E[Update State]
    E --> C
    D -->|Yes| F[Output]
    
    style A fill:#e1f5ff
    style F fill:#e1f5ff
    style C fill:#fff4e1
    style D fill:#e8f5e9
    style E fill:#fce4ec
```

### 3.1 Core Concept

Loop agents follow an **iterative execution model** where:
- An agent executes repeatedly with updated state
- Each iteration improves or refines the result
- Execution continues until a termination condition is met
- State is maintained across iterations

**Key Characteristics:**
- **Iterative Refinement**: Each loop improves the result
- **Condition-Based Termination**: Stops when criteria are met
- **State Management**: Maintains context across iterations
- **Convergence**: Can detect when further iterations won't help

### 3.2 When to Use Loop Agents

**Perfect For:**
- **Content Refinement**: Iteratively improving content quality until it meets standards
- **Optimization Problems**: Finding optimal solutions through iterative improvement
- **Batch Processing**: Processing items in batches until all are complete
- **Retry Logic**: Retrying failed operations with exponential backoff
- **Convergence Algorithms**: Iterating until values converge to a stable state

**Not Ideal For:**
- One-time operations
- Tasks that don't benefit from iteration
- When iteration count is unpredictable and could be infinite

### 3.3 Real-World Business Examples

**Example 1: Content Quality Improvement**

A content marketing platform uses loop agents to improve content quality:

1. **Initial Draft**: Agent generates initial content
2. **Quality Check**: Agent evaluates content quality (readability, SEO, engagement)
3. **Refinement Loop**: If quality < threshold:
   - Improve readability
   - Enhance SEO optimization
   - Add engaging elements
   - Re-check quality
4. **Termination**: Stop when quality score ≥ 0.9 or max iterations reached

**Business Impact**: Improved content quality scores by 45% while reducing manual editing time by 70%.

**Example 2: Inventory Optimization**

A retail company uses loop agents to optimize inventory levels:

1. **Initial State**: Current inventory levels
2. **Demand Prediction**: Agent predicts demand for next period
3. **Optimization Loop**: 
   - Calculate optimal reorder points
   - Simulate different scenarios
   - Adjust based on constraints
   - Re-evaluate until convergence
4. **Termination**: Stop when solution converges or max iterations reached

**Business Impact**: Reduced inventory costs by 25% while maintaining 99% stock availability.

**Example 3: Customer Support Ticket Routing**

A customer support system uses loop agents for intelligent ticket routing:

1. **Initial Classification**: Agent classifies ticket based on keywords
2. **Confidence Check**: Agent calculates confidence score
3. **Refinement Loop**: If confidence < threshold:
   - Analyze customer history
   - Check similar past tickets
   - Refine classification
   - Recalculate confidence
4. **Termination**: Route ticket when confidence ≥ 0.85 or after 3 iterations

**Business Impact**: Improved routing accuracy from 72% to 94%, reducing resolution time by 40%.

**Example 4: A/B Testing Optimization**

A marketing platform uses loop agents to optimize ad campaigns:

1. **Initial Campaign**: Launch campaign with initial parameters
2. **Performance Analysis**: Agent analyzes performance metrics
3. **Optimization Loop**:
   - Adjust targeting parameters
   - Modify creative elements
   - Test new variations
   - Measure improvements
4. **Termination**: Stop when performance improvement < 1% or max iterations reached

**Business Impact**: Increased conversion rates by 35% through continuous optimization.

### 3.4 Implementation Example: Content Quality Improvement

<details>
<summary><strong>🛠️ Click to view Loop Agent Implementation with ADK</strong></summary>

```python
from adk import Agent, LoopWorkflow
from adk.tools import content_analyzer, seo_optimizer, readability_checker
from typing import Dict, Any

# Define content refinement agent using ADK
content_refinement_agent = Agent(
    name="content_refiner",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a content quality specialist. Iteratively improve content quality by:
    1. Enhancing readability and clarity
    2. Optimizing SEO keywords and structure
    3. Adding engaging elements and examples
    
    Analyze current content quality and make targeted improvements. Return updated 
    content with quality score and list of improvements made.
    """,
    description="Iteratively refines content to improve quality scores",
    tools=[content_analyzer, seo_optimizer, readability_checker]
)

# Define quality evaluation agent
quality_evaluator_agent = Agent(
    name="quality_evaluator",
    model="gemini-2.0-flash-exp",
    instruction="""
    You are a quality evaluation specialist. Evaluate content quality across 
    multiple dimensions: readability, SEO optimization, engagement, and overall 
    quality. Return a quality score between 0 and 1.
    """,
    description="Evaluates content quality and returns scores"
)

# Create loop workflow using ADK
content_improvement_workflow = LoopWorkflow(
    name="content_quality_improvement",
    agent=content_refinement_agent,
    evaluator=quality_evaluator_agent,
    max_iterations=10,
    condition=lambda result, iteration: (
        result.get('quality_score', 0) < 0.9 and iteration < 10
    ),
    state_manager=lambda state, result: {
        **state,
        'content': result.get('content', state.get('content', '')),
        'quality_score': result.get('quality_score', state.get('quality_score', 0)),
        'refinements': state.get('refinements', []) + result.get('improvements_made', []),
        'iteration': iteration
    }
)

# Usage example
async def main():
    # Prepare initial content
    initial_content = {
        'content': "Initial draft content that needs improvement for better quality and engagement.",
        'quality_score': 0.5,
        'target_quality': 0.9
    }
    
    # Execute loop workflow
    print("Starting content quality improvement loop...\n")
    result = await content_improvement_workflow.run(initial_content)
    
    if result.success:
        print(f"\n✓ Content refinement completed!")
        print(f"  Final Quality Score: {result.output.get('quality_score', 0):.2f}")
        print(f"  Total Iterations: {result.iterations}")
        print(f"  Execution Time: {result.execution_time:.2f}s")
        print(f"  Total Refinements: {len(result.output.get('refinements', []))}")
        
        print(f"\nQuality Improvement History:")
        for entry in result.quality_history:
            print(f"  Iteration {entry['iteration']}: {entry['quality_score']:.2f}")
    else:
        print(f"\n✗ Content refinement failed: {result.error}")

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

**Key ADK Concepts Demonstrated:**
- **LoopWorkflow**: Executes agent repeatedly until condition is met
- **Condition Function**: Determines when to stop looping (quality threshold reached)
- **State Management**: Maintains state across iterations (content, quality score, refinements)
- **Evaluator Agent**: Separate agent evaluates quality at each iteration
- **Iteration Tracking**: ADK tracks iteration count and quality history
- **Termination Logic**: Stops when quality threshold met or max iterations reached

</details>

### 3.5 Best Practices

**Termination Conditions:**
- Set maximum iteration limits to prevent infinite loops
- Define clear convergence criteria
- Implement timeout mechanisms
- Monitor for oscillation (values bouncing between states)

**State Management:**
- Maintain state across iterations efficiently
- Track iteration history for debugging
- Implement state snapshots for recovery
- Clear unnecessary state to prevent memory issues

**Performance:**
- Monitor iteration count and execution time
- Optimize each iteration for speed
- Consider early exit conditions
- Cache intermediate results when possible

**Quality Control:**
- Validate improvements in each iteration
- Implement rollback mechanisms
- Track quality metrics over iterations
- Set minimum improvement thresholds

---

## 4. Custom Agents: Flexible Workflow Patterns

Custom agents combine sequential, parallel, and loop patterns to create complex, domain-specific workflows. Think of it as orchestrating a team where different members work in different ways depending on the task.

**Custom Agent Flow:**

```mermaid
flowchart TD
    A[Input] --> B{Decision Point}
    B -->|Path 1| C[Sequential Chain]
    B -->|Path 2| D[Parallel Execution]
    B -->|Path 3| E[Loop Processing]
    
    C --> F[Conditional Branch]
    D --> F
    E --> F
    
    F -->|Condition A| G[Agent A]
    F -->|Condition B| H[Agent B]
    
    G --> I[Final Output]
    H --> I
    
    style A fill:#e1f5ff
    style I fill:#e1f5ff
    style B fill:#e8f5e9
    style F fill:#e8f5e9
```

### 4.1 Core Concept

Custom agents follow a **hybrid execution model** where:
- Different patterns are used for different parts of the workflow
- Conditional logic routes tasks to appropriate patterns
- Complex business rules are encoded in the workflow structure
- Maximum flexibility for domain-specific requirements

**Key Characteristics:**
- **Pattern Combination**: Mixes sequential, parallel, and loop patterns
- **Conditional Routing**: Decisions determine execution path
- **Domain-Specific**: Tailored to exact business needs
- **Complex Logic**: Handles intricate business workflows

### 4.2 When to Use Custom Agents

**Perfect For:**
- **Complex Business Workflows**: Multi-stage processes with conditional logic
- **Domain-Specific Requirements**: Unique business rules and processes
- **Multi-Path Scenarios**: Different paths based on input or conditions
- **Hybrid Processing**: Combining different patterns for optimal performance
- **Enterprise Systems**: Large-scale systems with varied requirements

**Not Ideal For:**
- Simple, linear workflows (use sequential)
- Independent parallel tasks (use parallel)
- Simple iterative tasks (use loop)

### 4.3 Real-World Business Examples

**Example 1: Customer Onboarding with Conditional Routing**

A fintech company uses custom agents for customer onboarding:

**Workflow Structure:**
1. **Sequential Phase**: Document extraction → Data validation → Initial risk check
2. **Conditional Branch**: 
   - **If low risk**: Parallel processing (credit check + account creation + welcome email)
   - **If medium risk**: Sequential review (manual review → approval → account creation)
   - **If high risk**: Loop processing (additional verification iterations until cleared)
3. **Final Phase**: Sequential (compliance check → account activation → notification)

**Business Impact**: Reduced onboarding time by 70% while improving risk detection accuracy by 50%.

**Example 2: E-commerce Order Fulfillment**

An e-commerce platform uses custom agents for order fulfillment:

**Workflow Structure:**
1. **Parallel Phase**: Inventory check + Payment validation + Fraud detection
2. **Conditional Branch**:
   - **If all checks pass**: Sequential (reserve inventory → process payment → generate shipping label)
   - **If inventory issue**: Loop (check alternative warehouses until found or exhausted)
   - **If payment fails**: Sequential (notify customer → retry payment → update order status)
3. **Final Phase**: Parallel (send confirmation email + update inventory + trigger fulfillment)

**Business Impact**: Improved order fulfillment rate from 87% to 96% while reducing processing time by 60%.

**Example 3: Healthcare Patient Triage System**

A hospital uses custom agents for patient triage:

**Workflow Structure:**
1. **Parallel Phase**: Vital signs collection + Symptom analysis + Medical history retrieval
2. **Conditional Branch**:
   - **If critical**: Sequential (immediate alert → doctor notification → emergency protocol)
   - **If urgent**: Loop (continuous monitoring → escalation if condition worsens)
   - **If routine**: Parallel (schedule appointment + prepare records + send instructions)
3. **Final Phase**: Sequential (documentation → billing → follow-up scheduling)

**Business Impact**: Reduced critical patient response time by 40% and improved resource allocation efficiency by 55%.

**Example 4: Content Moderation System**

A social media platform uses custom agents for content moderation:

**Workflow Structure:**
1. **Parallel Phase**: Image analysis + Text analysis + User history check + Spam detection
2. **Conditional Branch**:
   - **If clearly safe**: Sequential (approve → publish → log)
   - **If clearly unsafe**: Sequential (reject → notify user → flag account)
   - **If uncertain**: Loop (human review → additional AI analysis → decision)
3. **Final Phase**: Sequential (update moderation database + adjust user trust score + generate report)

**Business Impact**: Improved moderation accuracy from 82% to 94% while reducing false positives by 65%.

### 4.4 Implementation Example: Customer Onboarding with Conditional Routing

<details>
<summary><strong>🛠️ Click to view Custom Agent Implementation with ADK</strong></summary>

```python
from adk import Agent, SequentialWorkflow, ParallelWorkflow, LoopWorkflow, CustomWorkflow
from adk.tools import document_parser, database_query, credit_api, email_sender
from typing import Dict, Any

# Phase 1: Sequential agents for initial processing
document_extraction_agent = Agent(
    name="document_extractor",
    model="gemini-2.0-flash-exp",
    instruction="Extract customer information from uploaded documents",
    description="Extracts data from customer documents",
    tools=[document_parser]
)

data_validation_agent = Agent(
    name="data_validator",
    model="gemini-2.0-flash-exp",
    instruction="Validate extracted customer data for completeness and accuracy",
    description="Validates extracted customer data",
    tools=[database_query]
)

risk_assessment_agent = Agent(
    name="risk_assessor",
    model="gemini-2.0-flash-exp",
    instruction="""
    Assess customer risk level based on extracted and validated data. 
    Return risk_level: 'low', 'medium', or 'high' along with risk_score.
    """,
    description="Assesses customer risk profile"
)

# Phase 2: Parallel agents for low-risk path
credit_check_agent = Agent(
    name="credit_checker",
    model="gemini-2.0-flash-exp",
    instruction="Check customer credit score and determine credit approval",
    description="Checks customer credit score",
    tools=[credit_api]
)

account_creation_agent = Agent(
    name="account_creator",
    model="gemini-2.0-flash-exp",
    instruction="Create customer account with unique account ID",
    description="Creates customer accounts"
)

welcome_email_agent = Agent(
    name="welcome_sender",
    model="gemini-2.0-flash-exp",
    instruction="Send personalized welcome email to new customers",
    description="Sends welcome emails",
    tools=[email_sender]
)

# Phase 2: Sequential agents for medium-risk path
manual_review_agent = Agent(
    name="manual_reviewer",
    model="gemini-2.0-flash-exp",
    instruction="Perform manual review of customer application",
    description="Conducts manual review for medium-risk customers"
)

approval_agent = Agent(
    name="approver",
    model="gemini-2.0-flash-exp",
    instruction="Process approval after manual review",
    description="Processes approvals"
)

# Phase 2: Loop agent for high-risk path
verification_agent = Agent(
    name="verifier",
    model="gemini-2.0-flash-exp",
    instruction="""
    Perform additional verification for high-risk customers. 
    Improve verification score iteratively until threshold is met.
    """,
    description="Performs iterative verification for high-risk customers"
)

# Phase 3: Final sequential agents
compliance_agent = Agent(
    name="compliance_checker",
    model="gemini-2.0-flash-exp",
    instruction="Perform compliance checks before account activation",
    description="Checks compliance requirements"
)

activation_agent = Agent(
    name="account_activator",
    model="gemini-2.0-flash-exp",
    instruction="Activate customer account and set status to active",
    description="Activates customer accounts"
)

notification_agent = Agent(
    name="notifier",
    model="gemini-2.0-flash-exp",
    instruction="Send final notification confirming account activation",
    description="Sends final notifications",
    tools=[email_sender]
)

# Create custom workflow using ADK
onboarding_workflow = CustomWorkflow(
    name="customer_onboarding",
    phases=[
        # Phase 1: Sequential initial processing
        SequentialWorkflow(
            name="initial_processing",
            agents=[
                document_extraction_agent,
                data_validation_agent,
                risk_assessment_agent
            ]
        ),
        # Phase 2: Conditional routing based on risk level
        {
            'condition': lambda data: data.get('risk_level'),
            'routes': {
                'low': ParallelWorkflow(
                    name="low_risk_processing",
                    agents={
                        'credit_check': credit_check_agent,
                        'account_creation': account_creation_agent,
                        'welcome_email': welcome_email_agent
                    },
                    aggregator=lambda results: {
                        **results['credit_check'],
                        **results['account_creation'],
                        **results['welcome_email']
                    }
                ),
                'medium': SequentialWorkflow(
                    name="medium_risk_processing",
                    agents=[
                        manual_review_agent,
                        approval_agent,
                        account_creation_agent
                    ]
                ),
                'high': LoopWorkflow(
                    name="high_risk_processing",
                    agent=verification_agent,
                    max_iterations=5,
                    condition=lambda result, iteration: (
                        result.get('verification_score', 0) < 0.8 and iteration < 5
                    ),
                    on_complete=lambda data: account_creation_agent.run(data)
                )
            }
        },
        # Phase 3: Final sequential processing
        SequentialWorkflow(
            name="final_processing",
            agents=[
                compliance_agent,
                activation_agent,
                notification_agent
            ]
        )
    ]
)

# Usage example
async def main():
    # Prepare customer data
    customer_data = {
        'customer_id': 'CUST001',
        'email': 'customer@example.com',
        'document_uploaded': True,
        'document_content': '...'  # Document content or file path
    }
    
    # Execute custom workflow
    print("Starting custom onboarding workflow...\n")
    result = await onboarding_workflow.run(customer_data)
    
    if result.success:
        print(f"\n✓ Workflow completed successfully!")
        print(f"  Execution Time: {result.execution_time:.2f}s")
        print(f"  Execution Path: {' → '.join(result.execution_path)}")
        print(f"  Account ID: {result.output.get('account_id', 'N/A')}")
        print(f"  Status: {result.output.get('status', 'N/A')}")
        print(f"  Risk Level: {result.output.get('risk_level', 'N/A')}")
    else:
        print(f"\n✗ Workflow failed: {result.error}")

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

**Key ADK Concepts Demonstrated:**
- **CustomWorkflow**: Combines multiple workflow patterns (sequential, parallel, loop)
- **Conditional Routing**: Routes to different workflows based on data conditions (risk level)
- **Nested Workflows**: Workflows can contain other workflows as phases
- **Pattern Combination**: Uses sequential, parallel, and loop patterns in one workflow
- **Dynamic Execution Path**: Execution path adapts based on conditional routing
- **State Management**: State flows through all phases automatically
- **Error Handling**: ADK handles errors at each phase level

</details>

### 4.5 Best Practices

**Workflow Design:**
- Map out business logic clearly before implementation
- Use visual workflow diagrams for complex processes
- Document decision points and conditions
- Design for maintainability and future changes

**Pattern Selection:**
- Use sequential for dependent tasks
- Use parallel for independent tasks
- Use loops for iterative refinement
- Combine patterns strategically

**Error Handling:**
- Implement error handling at each pattern level
- Define fallback paths for failures
- Log decisions and state changes
- Provide rollback mechanisms

**Performance Optimization:**
- Optimize each pattern individually
- Minimize unnecessary conditional checks
- Cache results when appropriate
- Monitor performance at each stage

**Testing:**
- Test each pattern independently
- Test conditional branches thoroughly
- Test edge cases and error scenarios
- Use integration tests for full workflows

For implementation guidance, see our [Production-Ready AI Agent Architecture guide](/blog/production-ready-ai-agent-architecture). When building complex workflows, proper [context engineering](/blog/context-engineering-vs-prompt-engineering-2025-guide) becomes essential for managing agent-to-agent communication.

---

## 5. Choosing the Right Pattern

### 5.1 Decision Framework

**Use Sequential Agents When:**
- Tasks have strict dependencies
- Order of execution matters
- You need clear audit trails
- Resource constraints are a concern

**Use Parallel Agents When:**
- Tasks are independent
- Speed is critical
- You have sufficient resources
- Tasks can run simultaneously

**Use Loop Agents When:**
- Iterative refinement is needed
- Optimization is required
- Convergence is expected
- Quality improvement is the goal

**Use Custom Agents When:**
- Workflow is complex with multiple paths
- Business rules are domain-specific
- You need to combine patterns
- Flexibility is more important than simplicity

### 5.2 Performance Comparison

| Pattern | Speed | Resource Usage | Complexity | Best For |
|---------|-------|----------------|------------|----------|
| **Sequential** | Slowest | Lowest | Simplest | Dependent tasks |
| **Parallel** | Fastest | Highest | Moderate | Independent tasks |
| **Loop** | Variable | Moderate | Moderate | Iterative refinement |
| **Custom** | Variable | Variable | Most Complex | Complex workflows |

### 5.3 Cost Considerations

**Sequential Agents:**
- **Infrastructure Cost**: Low (minimal resource requirements)
- **Development Cost**: Low (simple to implement)
- **Maintenance Cost**: Low (easy to debug and maintain)
- **Best ROI**: When dependencies are clear and order matters

**Parallel Agents:**
- **Infrastructure Cost**: High (requires more resources)
- **Development Cost**: Moderate (requires concurrency management)
- **Maintenance Cost**: Moderate (more complex error handling)
- **Best ROI**: When speed improvement justifies resource costs

**Loop Agents:**
- **Infrastructure Cost**: Moderate (depends on iteration count)
- **Development Cost**: Moderate (requires termination logic)
- **Maintenance Cost**: Moderate (requires monitoring)
- **Best ROI**: When iterative improvement adds significant value

**Custom Agents:**
- **Infrastructure Cost**: Variable (depends on complexity)
- **Development Cost**: High (requires careful design)
- **Maintenance Cost**: High (complex workflows need more attention)
- **Best ROI**: When business requirements justify complexity

---

## Conclusion

**Understanding and implementing the right agent architecture pattern is crucial for building efficient, scalable AI systems.** Each pattern serves specific use cases and offers different trade-offs:

- **Sequential Agents**: Perfect for dependent, step-by-step processes with clear dependencies
- **Parallel Agents**: Ideal for independent, concurrent tasks where speed is critical
- **Loop Agents**: Best for iterative refinement and optimization scenarios
- **Custom Agents**: Maximum flexibility for complex, domain-specific workflows

**Key Takeaways:**
1. **Match Pattern to Task**: Choose patterns based on task characteristics, not convenience
2. **Consider Trade-offs**: Balance speed, resources, complexity, and maintainability
3. **Start Simple**: Begin with sequential or parallel, add complexity only when needed
4. **Monitor Performance**: Track metrics to optimize and improve over time
5. **Plan for Scale**: Design with future growth and complexity in mind

**The ROI of Proper Architecture:**
- **50-70% reduction** in processing time through pattern optimization
- **3x faster** execution with parallel patterns for independent tasks
- **80% improvement** in throughput with loop patterns for iterative refinement
- **90% reduction** in manual intervention with custom workflows

**Real-World Impact:**
Organizations that implement proper agent architecture patterns see significant improvements in:
- **Operational Efficiency**: Faster processing and reduced manual work
- **Cost Reduction**: Optimized resource usage and infrastructure costs
- **Customer Experience**: Faster response times and improved service quality
- **Scalability**: Ability to handle growth without proportional cost increases

For implementation guidance in production environments, see our [Production-Ready AI Agent Architecture guide](/blog/production-ready-ai-agent-architecture). When building multi-agent systems, [AI agent orchestration](/blog/ai-agent-orchestration-multi-agent-systems-2025) patterns become essential for managing complex workflows.

**The future of AI belongs to well-architected agent systems.** Organizations that invest in proper agent architecture patterns today will have a significant competitive advantage in the autonomous AI economy.

---

## Further Reading

- [Production-Ready AI Agent Architecture](/blog/production-ready-ai-agent-architecture)
- [AI Agent Orchestration: Multi-Agent Systems That Actually Work in 2025](/blog/ai-agent-orchestration-multi-agent-systems-2025)
- [10 Best Practices for Reliable AI Agent Systems](/blog/10-best-practices-reliable-ai-agents)
- [The Key Components of a Production-Ready AI Agent Architecture](/blog/production-ready-ai-agent-architecture)
- [25+ Disruptive AI Agent Business Ideas You Should Launch in 2025 & Beyond](/blog/25-disruptive-ai-agent-business-ideas-2025)
---

<FAQSection
  title="Frequently Asked Questions"
  questions={[
    {
      question: "When should I use sequential vs parallel agents?",
      answer:
        "Use sequential agents when tasks have dependencies (output of one feeds into the next), like document processing pipelines. Use parallel agents when tasks are independent and can run simultaneously, like checking inventory, validating payment, and calculating shipping costs at the same time. Sequential is for workflows, parallel is for independent operations.",
    },
    {
      question: "How do I prevent infinite loops in loop agents?",
      answer:
        "Always set a maximum iteration limit and implement clear termination conditions. Use convergence checks for optimization loops (stop when improvement is minimal), condition functions for goal-based loops (stop when goal is achieved), and timeout mechanisms for long-running processes. Monitor iteration history to detect patterns and prevent oscillation.",
    },
    {
      question: "Can I combine different agent patterns?",
      answer:
        "Yes! Custom agents allow you to combine sequential, parallel, and loop patterns in complex workflows. For example, you might have parallel execution within a sequential chain, or sequential steps within a loop. This flexibility enables domain-specific workflows tailored to your exact business needs.",
    },
    {
      question: "What's the performance difference between sequential and parallel agents?",
      answer:
        "For independent tasks, parallel agents can be 3-10x faster depending on the number of tasks and system resources. Sequential agents are necessary when tasks depend on each other, but they're slower since tasks run one after another. Always use parallel patterns when possible for independent tasks to maximize performance.",
    },
    {
      question: "How do I handle errors in agent workflows?",
      answer:
        "Implement error handling at each pattern level: try-catch blocks for sequential agents, individual failure handling for parallel agents (so one failure doesn't stop others), retry logic with exponential backoff for loop agents, and comprehensive error handling with fallback paths for custom agents. Always log errors with context for debugging.",
    },
    {
      question: "What are the best practices for custom agent workflows?",
      answer:
        "Design clear workflow structures, use visual diagrams for complex processes, document decision points and conditions, implement error handling at each pattern level, optimize each pattern individually, test each pattern independently, and design for maintainability. Keep workflows modular and reusable where possible.",
    },
    {
      question: "How do I optimize agent performance?",
      answer:
        "For sequential agents: minimize data transformation overhead, use streaming for large datasets. For parallel agents: balance parallelism with resource constraints, use async patterns for I/O-bound tasks. For loop agents: optimize each iteration, implement early exit conditions. For custom agents: optimize each pattern individually, minimize unnecessary conditional checks.",
    },
    {
      question: "What's the cost difference between different patterns?",
      answer:
        "Sequential agents have the lowest infrastructure and development costs but are slower. Parallel agents have higher infrastructure costs (more resources needed) but provide the best speed. Loop agents have moderate costs depending on iteration count. Custom agents have variable costs based on complexity but provide maximum flexibility. Choose based on your specific requirements and budget.",
    },
  ]}
/>
