> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Conditional Execution

> Unified condition syntax for controlling task and workflow execution

Conditional execution gates tasks and workflow steps on runtime values using one `when` syntax that works in both `AgentFlow` pipelines and `Task` teams.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, when

agent = Agent(name="conditional", instructions="Run tasks only when conditions match.")
agent.start("Execute the follow-up step if the score is above 0.8.")
```

The user defines workflows; `when` expressions gate tasks and AgentFlow steps on runtime variables.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Conditional Execution"
        In[📝 User Request] --> Agent[🤖 Agent]
        Agent --> Cond{when condition}
        Cond -->|True| Then[✅ then_task]
        Cond -->|False| Else[❌ else_task]
    end

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef success fill:#10B981,stroke:#7C90A0,color:#fff
    classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff

    class In,Agent agent
    class Cond decision
    class Then success
    class Else process
```

## Overview

Conditional execution allows you to control workflow branching based on variables, scores, or other runtime values. PraisonAI supports:

* **String expression conditions** - Simple `{{variable}}` syntax for comparisons
* **Dictionary routing** - Map decision values to next tasks
* **Callable conditions** - Custom Python functions

## Quick Start

<Steps>
  <Step title="Task or AgentFlow">
    <CodeGroup>
      ```python Task with when (Recommended) theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
      from praisonaiagents import Task

      # Simple condition with then/else routing
      task = Task(
          name="score_check",
          description="Check if score passes threshold",
          when="{{score}} > 80",
          then_task="approve",
          else_task="reject"
      )

      # Evaluate the condition
      result = task.evaluate_when({"score": 90})  # True
      next_task = task.get_next_task({"score": 90})  # "approve"
      ```

      ```python AgentFlow with when() theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
      from praisonaiagents import AgentFlow, Agent, when

      agent = Agent(name="worker", instructions="Process data")

      flow = AgentFlow(
          agents=[agent],
          steps=[
              when(
                  condition="{{score}} >= 50",
                  then_steps=["high_score_handler"],
                  else_steps=["low_score_handler"]
              )
          ],
          variables={"score": 75}
      )
      ```
    </CodeGroup>
  </Step>
</Steps>

## Condition Syntax

### String Expression Conditions

Use `{{variable}}` placeholders with comparison operators:

| Operator   | Example                      | Description           |
| ---------- | ---------------------------- | --------------------- |
| `>`        | `{{score}} > 80`             | Greater than          |
| `>=`       | `{{score}} >= 80`            | Greater than or equal |
| `<`        | `{{score}} < 50`             | Less than             |
| `<=`       | `{{score}} <= 50`            | Less than or equal    |
| `==`       | `{{status}} == approved`     | Equal to              |
| `!=`       | `{{status}} != rejected`     | Not equal to          |
| `in`       | `{{word}} in {{text}}`       | Contains (substring)  |
| `contains` | `{{list}} contains {{item}}` | Contains (list)       |

<Tip>
  String comparisons don't require quotes: `{{status}} == approved` works correctly.
</Tip>

### Examples

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Numeric comparisons
"{{score}} > 80"
"{{count}} >= 10"
"{{price}} < 100.50"

# String comparisons
"{{status}} == approved"
"{{category}} != spam"

# Contains checks
"{{text}} contains error"
"{{tags}} in important"

# Boolean checks
"{{is_valid}}"  # True if truthy
```

## Task Condition Parameters

### `when` Parameter

The `when` parameter accepts a string expression condition:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Task

task = Task(
    name="quality_check",
    description="Check content quality",
    when="{{quality_score}} >= 7",
    then_task="publish",
    else_task="revise"
)
```

### `then_task` and `else_task`

Route to different tasks based on condition result:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
task = Task(
    name="review",
    description="Review submission",
    when="{{approved}} == true",
    then_task="finalize",    # Run if condition is True
    else_task="request_changes"  # Run if condition is False
)
```

### `routing` Parameter (Advanced)

For LLM-driven decisions, use the `routing` parameter (formerly `condition`):

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
task = Task(
    name="decision_task",
    description="Decide next action based on content",
    task_type="decision",
    routing={
        "approved": ["publish_task"],
        "rejected": ["edit_task"],
        "needs_review": ["review_task"]
    }
)
```

<Note>
  The `condition` parameter still works for backward compatibility, but `routing` is preferred for clarity.
</Note>

### `should_run` Callable

For complex logic, use a callable:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
def check_prerequisites(context):
    return context.get("data_ready", False) and context.get("approved", False)

task = Task(
    name="process",
    description="Process data",
    should_run=check_prerequisites
)
```

## AgentFlow Conditions

### `when()` Function

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import when

flow = AgentFlow(
    steps=[
        "step1",
        when(
            condition="{{result}} == success",
            then_steps=["success_handler"],
            else_steps=["error_handler"]
        ),
        "final_step"
    ]
)
```

### Nested Conditions

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flow = AgentFlow(
    steps=[
        when(
            condition="{{score}} >= 80",
            then_steps=[
                when(
                    condition="{{premium}} == true",
                    then_steps=["premium_path"],
                    else_steps=["standard_path"]
                )
            ],
            else_steps=["low_score_path"]
        )
    ]
)
```

## Flow Diagram

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    subgraph Condition["Condition Evaluation"]
        A[Task with when condition] --> B{Evaluate Expression}
        B -->|True| C[then_task]
        B -->|False| D[else_task]
    end

    classDef task fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff

    class A,C,D task
    class B decision
```

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Condition

    User->>Agent: Submit workflow with when conditions
    Agent->>Condition: Evaluate "{{score}} > 80"
    alt condition is True
        Condition-->>Agent: Route to then_task
    else condition is False
        Condition-->>Agent: Route to else_task
    end
    Agent-->>User: Workflow result
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Use simple conditions">
    Keep conditions readable and simple. Complex logic should go in `should_run` callables.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # ✅ Good - Simple and clear
    when="{{score}} > 80"

    # ❌ Avoid - Too complex
    when="{{score}} > 80 and {{status}} == approved and {{count}} < 10"
    ```
  </Accordion>

  <Accordion title="Provide both then_task and else_task">
    Always specify both branches to make the flow explicit:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    # ✅ Good - Both branches defined
    Task(
        when="{{approved}}",
        then_task="proceed",
        else_task="wait"
    )

    # ⚠️ Incomplete - Missing else branch
    Task(
        when="{{approved}}",
        then_task="proceed"
    )
    ```
  </Accordion>

  <Accordion title="Use routing for LLM decisions">
    When the LLM needs to make a decision, use `routing` with `task_type="decision"`:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    Task(
        name="classifier",
        description="Classify the input",
        task_type="decision",
        routing={
            "positive": ["positive_handler"],
            "negative": ["negative_handler"],
            "neutral": ["neutral_handler"]
        }
    )
    ```
  </Accordion>
</AccordionGroup>

## Migration Guide

### From `condition` to `routing`

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Old syntax (still works)
Task(condition={"yes": ["next"], "no": ["stop"]})

# New syntax (recommended)
Task(routing={"yes": ["next"], "no": ["stop"]})
```

### Adding `when` to existing Tasks

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Before - Using should_run callable
Task(
    should_run=lambda ctx: ctx.get("score", 0) > 80
)

# After - Using when expression (simpler)
Task(
    when="{{score}} > 80"
)
```

## API Reference

### Task Parameters

| Parameter    | Type                   | Description                            |
| ------------ | ---------------------- | -------------------------------------- |
| `when`       | `str`                  | String expression condition            |
| `then_task`  | `str`                  | Task name to run if condition is True  |
| `else_task`  | `str`                  | Task name to run if condition is False |
| `routing`    | `Dict[str, List[str]]` | Map decision values to task names      |
| `should_run` | `Callable`             | Custom condition function              |

### Task Methods

| Method                   | Returns | Description                      |
| ------------------------ | ------- | -------------------------------- |
| `evaluate_when(context)` | `bool`  | Evaluate the `when` condition    |
| `get_next_task(context)` | `str`   | Get next task based on condition |

## Related

<CardGroup cols={2}>
  <Card title="AgentFlow" icon="diagram-project" href="/features/agentflow">
    Learn about deterministic pipelines
  </Card>

  <Card title="AgentTeam" icon="users" href="/features/agentteam">
    Multi-agent task orchestration
  </Card>
</CardGroup>
