Skip to main content
Conditional execution gates tasks and workflow steps on runtime values using one when syntax that works in both AgentFlow pipelines and Task teams.
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.

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

1

Task or AgentFlow

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"
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}
)

Condition Syntax

String Expression Conditions

Use {{variable}} placeholders with comparison operators:
OperatorExampleDescription
>{{score}} > 80Greater than
>={{score}} >= 80Greater than or equal
<{{score}} < 50Less than
<={{score}} <= 50Less than or equal
=={{status}} == approvedEqual to
!={{status}} != rejectedNot equal to
in{{word}} in {{text}}Contains (substring)
contains{{list}} contains {{item}}Contains (list)
String comparisons don’t require quotes: {{status}} == approved works correctly.

Examples

# 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:
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:
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):
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"]
    }
)
The condition parameter still works for backward compatibility, but routing is preferred for clarity.

should_run Callable

For complex logic, use a callable:
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

from praisonaiagents import when

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

Nested Conditions

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

How It Works


Best Practices

Keep conditions readable and simple. Complex logic should go in should_run callables.
# ✅ Good - Simple and clear
when="{{score}} > 80"

# ❌ Avoid - Too complex
when="{{score}} > 80 and {{status}} == approved and {{count}} < 10"
Always specify both branches to make the flow explicit:
# ✅ Good - Both branches defined
Task(
    when="{{approved}}",
    then_task="proceed",
    else_task="wait"
)

# ⚠️ Incomplete - Missing else branch
Task(
    when="{{approved}}",
    then_task="proceed"
)
When the LLM needs to make a decision, use routing with task_type="decision":
Task(
    name="classifier",
    description="Classify the input",
    task_type="decision",
    routing={
        "positive": ["positive_handler"],
        "negative": ["negative_handler"],
        "neutral": ["neutral_handler"]
    }
)

Migration Guide

From condition to routing

# Old syntax (still works)
Task(condition={"yes": ["next"], "no": ["stop"]})

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

Adding when to existing Tasks

# 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

ParameterTypeDescription
whenstrString expression condition
then_taskstrTask name to run if condition is True
else_taskstrTask name to run if condition is False
routingDict[str, List[str]]Map decision values to task names
should_runCallableCustom condition function

Task Methods

MethodReturnsDescription
evaluate_when(context)boolEvaluate the when condition
get_next_task(context)strGet next task based on condition

AgentFlow

Learn about deterministic pipelines

AgentTeam

Multi-agent task orchestration