# SequentialWorkflow

The `SequentialWorkflow` class orchestrates agents to execute tasks in strict order, ensuring compliance and auditability for Web3 operations like cross-chain compliance checks, multi-signature approvals, and transactional dependencies in DeFi protocols. Ideal for processes requiring atomic step validation (e.g., KYC→FX→Payment processing).

***

#### **Key Features**

1. **Step-Wise Validation**: Each agent's output becomes the next agent's input.
2. **Max Loop Control**: Set `max_loops=3` for iterative workflows (e.g., failed TX retries).
3. **State Persistence**: Automatically stores intermediate results to IPFS.
4. **ZK-State Proofs**: Cryptographic verification of workflow order integrity.

***

#### **Class Definitions**

**1. WorkflowState (`BaseModel`)**

```python
from pydantic import BaseModel  
from datetime import datetime  

class WorkflowState(BaseModel):  
    workflow_id: str          # CID of initial input  
    current_step: int         # Execution sequence position  
    agent_outputs: dict       # {agent_id: {output: str, timestamp: datetime}}  
    zk_proof: str             # Zero-knowledge proof of correct step ordering  
```

**2. SequentialConfig**

```python
class SequentialConfig:  
    max_loops: int = 1        # Max iterations (e.g., for transaction retries)  
    gas_lock: bool = False    # Freeze gas price across steps  
    compliance_check: bool = True  # Auto-validate OFAC between steps  
```

***

#### **Core Methods**

**1. Initialize Workflow**

```python
def __init__(  
    self,  
    agents: List[BaseAgent],  
    config: SequentialConfig = SequentialConfig(),  
    **kwargs  
):  
    """  
    :param agents: Ordered list (KYC → Compliance → PaymentAgent)  
    :param config: Execution policy parameters  
    """  
    if len(agents) < 2:  
        raise ValueError("Sequential workflows require ≥2 agents")  
    self.agents = agents  
    self.web3 = Web3Provider()  
```

**2. Execute Workflow**

```python
def run(self, task: Union[str, Dict]) -> WorkflowState:  
    """  
    Processes task through agent sequence with on-chain validation  
    """  
    state = WorkflowState(workflow_id=generate_cid(task))  
    for idx, agent in enumerate(self.agents):  
        try:  
            # Inject on-chain context between steps  
            if idx > 0:  
                task += self.web3.get_last_tx(state.agent_outputs[idx-1])  

            output = agent.execute(  
                task,  
                gas_strategy="fixed" if config.gas_lock else "current"  
            )  
            state.agent_outputs[idx] = {  
                "agent_id": agent.id,  
                "output": output,  
                "timestamp": datetime.utcnow().isoformat()  
            }  
        except ComplianceError as e:  
            self._handle_chain_revert(state, idx)  
    state.zk_proof = self._generate_step_proofs(state)  
    return state  
```

***

#### **Enterprise Use Cases**

**1. Payroll Processing Pipeline**

*Sequence*:

1. **KYC Agent**: Validate 50K employee addresses against OFAC.
2. **FX Agent**: Convert EUR→USDC at optimal rate via Uniswap/Curve.
3. **Payment Agent**: Distribute funds across Ethereum, Polygon, Arbitrum.

*Code*:

```python
workflow = SequentialWorkflow(  
    agents=[kyc_agent, fx_agent, payment_agent],  
    config=SequentialConfig(max_loops=3)  
)  

result = workflow.run({"action": "payroll", "amount": "35000000"})  
```

**2. Multi-Chain Compliance**

*Agents*:

```python
agents = [  
    ChainalysisCheckAgent(),  
    SanctionsFilterAgent(),  
    CrossChainBroadcastAgent()  
]  
```

*Execution*:

```python
await workflow.run("Transfer 1M USDC to vendor@0x1234")  
```

***

#### **Performance Metrics**

| **Step**            | Avg. Processing Time | Cost/TX | Success Rate |
| ------------------- | -------------------- | ------- | ------------ |
| KYC Verification    | 0.4s                 | $0.08   | 99.8%        |
| FX Conversion       | 2.1s                 | $1.20   | 99.5%        |
| Cross-Chain Payment | 4.7s                 | $0.32   | 99.3%        |

***

#### **Best Practices**

**1. Workflow Structuring**

```python
# Optimal payment routing sequence  
workflow = SequentialWorkflow(  
    [  
        ComplianceAgent(),   
        GasOptimizerAgent(),  
        MEVShieldAgent()  
    ]  
)  
```

**2. Gas Strategy**

```python
# Lock gas during volatile periods  
workflow.run(  
    task,  
    config=SequentialConfig(gas_lock=True)  
)  
```

**3. Security**

* Use `compliance_check=True` (default) to auto-validate between steps.
* Enable ZK-proof anchoring for GDPR/audit requirements.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://agent-gpt.gitbook.io/agent-gpt/workflows/sequentialworkflow.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
