Conditional Branching

Dynamic workflow paths with if/then/else patterns

Conditional branching lets you create dynamic workflows that take different paths based on runtime conditions. Use the if: pattern to evaluate variables and route execution accordingly.

python
from praisonaiagents import Agent, when

agent = Agent(name="router", instructions="Branch based on runtime variables")
branch = when(condition="{{tier}} == 'pro'", then_steps=["pro_handler"], else_steps=["standard"])
agent.start("Route this customer request")

The user triggers a flow; conditions pick the next step from runtime values.

Diagram

Conditional Branching

📋 Input

🔀 Condition

✅ Then/Else

➡️ Continue

Quick Start

  1. Python or YAML
    Python
    from praisonaiagents import AgentFlow, WorkflowContext, StepResult, if_
    
    def approve(ctx: WorkflowContext) -> StepResult:
        return StepResult(output="Approved!")
    
    def reject(ctx: WorkflowContext) -> StepResult:
        return StepResult(output="Rejected!")
    
    workflow = AgentFlow(
        steps=[
            if_(
                condition="{{score}} >= 70",
                then_steps=[approve],
                else_steps=[reject]
            )
        ],
        variables={"score": 85}
    )
    result = workflow.start("Evaluate")
    # Output: "Approved!"
    YAML
    workflow:
      variables:
        score: 85
    
      steps:
        - if:
            condition: "{{score}} >= 70"
            then:
              - agent: approver
                action: "Approve the application"
            else:
              - agent: rejector
                action: "Reject the application"

Condition Syntax

Numeric Comparisons

Compare numbers using standard operators:

python
# Greater than
if_(condition="{{score}} > 80", then_steps=[...])

# Less than or equal
if_(condition="{{count}} <= 10", then_steps=[...])

# Equal
if_(condition="{{age}} == 18", then_steps=[...])

# Not equal
if_(condition="{{status_code}} != 200", then_steps=[...])

String Equality

Match exact string values:

python
# String equals
if_(
    condition="{{status}} == approved",
    then_steps=[process_approved],
    else_steps=[process_pending]
)

# String not equals
if_(
    condition="{{tier}} != free",
    then_steps=[premium_features]
)

Contains Check

Check if a string contains a substring:

python
# Using 'in' keyword
if_(
    condition="error in {{message}}",
    then_steps=[handle_error],
    else_steps=[continue_normal]
)

# Using 'contains' keyword
if_(
    condition="{{response}} contains success",
    then_steps=[celebrate]
)

Nested Property Access

Access nested object properties:

python
workflow = AgentFlow(
    steps=[
        if_(
            condition="{{user.subscription.tier}} == premium",
            then_steps=[premium_service]
        )
    ],
    variables={
        "user": {
            "name": "Alice",
            "subscription": {"tier": "premium"}
        }
    }
)

If Without Else

The else_steps parameter is optional. If omitted, nothing happens when the condition is false:

python
# Only send notification if opted in
workflow = AgentFlow(
    steps=[
        if_(
            condition="{{notify}} == true",
            then_steps=[send_notification]
            # No else - just skip if false
        ),
        continue_workflow  # Always runs
    ],
    variables={"notify": "true"}
)

If Inside Loop

Combine conditional branching with loops for per-item decisions:

Diagram

For Each Customer

Yes

No

Customer

Premium?

VIP Service

Standard Service

Python

python
from praisonaiagents import AgentFlow, WorkflowContext, StepResult, if_, loop

def vip_service(ctx: WorkflowContext) -> StepResult:
    customer = ctx.variables.get("customer", {})
    return StepResult(output=f"VIP service for {customer['name']}")

def standard_service(ctx: WorkflowContext) -> StepResult:
    customer = ctx.variables.get("customer", {})
    return StepResult(output=f"Standard service for {customer['name']}")

workflow = AgentFlow(
    steps=[
        loop(
            steps=[
                if_(
                    condition="{{customer.tier}} == premium",
                    then_steps=[vip_service],
                    else_steps=[standard_service]
                )
            ],
            over="customers",
            var_name="customer"
        )
    ],
    variables={
        "customers": [
            {"name": "Alice", "tier": "premium"},
            {"name": "Bob", "tier": "standard"},
            {"name": "Charlie", "tier": "premium"}
        ]
    }
)
workflow.start("Assign services")

YAML

yaml
workflow:
  variables:
    customers:
      - name: Alice
        tier: premium
      - name: Bob
        tier: standard
      - name: Charlie
        tier: premium

  steps:
    - loop:
        over: customers
        var_name: customer
        steps:
          - if:
              condition: "{{customer.tier}} == premium"
              then:
                - agent: vip_handler
                  action: "Provide VIP service to {{customer.name}}"
              else:
                - agent: standard_handler
                  action: "Provide standard service to {{customer.name}}"

Nested Conditions

Create decision trees with nested if statements:

python
workflow = AgentFlow(
    steps=[
        if_(
            condition="{{tier}} == premium",
            then_steps=[
                # Nested condition for premium users
                if_(
                    condition="{{spend}} > 10000",
                    then_steps=[vip_treatment],
                    else_steps=[regular_premium]
                )
            ],
            else_steps=[basic_support]
        )
    ],
    variables={"tier": "premium", "spend": 15000}
)
Diagram

Yes

No

Yes

No

Start

Premium?

High Spend?

Basic Support

VIP Treatment

Regular Premium

How It Works

The user starts a flow with variables; if_ evaluates the condition and runs the matching branch.

Diagram
BranchIfAgentFlowUserBranchIfAgentFlowUserstart() with variablesEvaluate conditionRun then_steps or else_stepsStepResultFinal result

API Reference

if_() Function

python
def if_(
    condition: str,
    then_steps: List[Any],
    else_steps: Optional[List[Any]] = None
) -> If
condition string

Condition expression with {{variable}} placeholders

then_steps list

Steps to execute when condition is true

else_steps list

Steps to execute when condition is false (optional)

If Class

python
from praisonaiagents import If

conditional = If(
    condition="{{score}} > 80",
    then_steps=[approve],
    else_steps=[reject]
)

MAX_NESTING_DEPTH

python
from praisonaiagents import MAX_NESTING_DEPTH

print(MAX_NESTING_DEPTH)  # 5

Best Practices

Use Clear Condition Names

Make conditions readable: {{user.is_verified}} == true is clearer than {{v}} == 1

Provide Default Values

Handle missing variables gracefully – undefined variables evaluate to empty strings

Keep Branches Simple

Each branch should do one thing well. Complex logic should be in separate functions.

Test Both Branches

Always test both the true and false paths of your conditions

Related