Skip to content

Conditional Branches

Conditional Branches

In Lesson 3, you learned to make decisions. Now, let's use those decisions to create conditional branches - programs that take different paths based on the input.

Why Conditional Branches?

Real-world applications often need different processing for different cases:

  • Simple questions → Quick answer
  • Complex questions → Detailed reasoning
  • Urgent tickets → Fast track processing
  • Normal tickets → Standard queue

How Conditional Branches Work

The Branch module combines decision-making with conditional execution:

graph LR
    Input --> Decision
    Decision -->|easy| A[Easy Branch]
    Decision -->|difficult| B[Hard Branch]
    A --> Outputs
    B --> Outputs

Only ONE branch executes - the others output None.

(easy_result, hard_result) = await synalinks.Branch(
    question="How complex is this query?",
    labels=["easy", "difficult"],
    branches=[
        synalinks.Generator(data_model=SimpleAnswer, ...),    # For "easy"
        synalinks.Generator(data_model=DetailedAnswer, ...),  # For "difficult"
    ],
    language_model=language_model,
)(inputs)

# If query was "easy": easy_result has data, hard_result is None
# If query was "difficult": easy_result is None, hard_result has data

Handling None Outputs

Since unselected branches return None, you can use logical operators to merge results (covered in Lesson 5):

final_result = easy_result | hard_result  # Gets the non-None result

Complete Example

import asyncio
from dotenv import load_dotenv
import synalinks

class Query(synalinks.DataModel):
    query: str = synalinks.Field(description="The user query")

class Answer(synalinks.DataModel):
    answer: str = synalinks.Field(description="The correct answer")

class AnswerWithThinking(synalinks.DataModel):
    thinking: str = synalinks.Field(description="Your step by step thinking")
    answer: str = synalinks.Field(description="The correct answer")

async def main():
    load_dotenv()
    language_model = synalinks.LanguageModel(model="openai/gpt-4.1")

    inputs = synalinks.Input(data_model=Query)

    # Branch routes to different generators based on decision
    (easy_branch, hard_branch) = await synalinks.Branch(
        question="Evaluate the difficulty to answer the provided query",
        labels=["easy", "difficult"],
        language_model=language_model,
        branches=[
            synalinks.Generator(data_model=Answer, language_model=language_model),
            synalinks.Generator(data_model=AnswerWithThinking, language_model=language_model),
        ],
    )(inputs)

    program = synalinks.Program(
        inputs=inputs,
        outputs=[easy_branch, hard_branch],
        name="conditional_branches",
    )

    # One output will be None depending on which branch was taken
    results = await program(Query(query="What is 2 + 2?"))
    print(f"Easy branch: {results[0]}")  # Has data
    print(f"Hard branch: {results[1]}")  # None

asyncio.run(main())

Key Takeaways

  • Branch Module: Combines Decision with multiple processing paths - routes inputs to different modules based on classification.
  • Exclusive Execution: Only one branch executes per input; others return None.
  • Tuple Output: Branch returns a tuple of outputs, one per label, where only the selected branch has data.
  • OR Operator: Use result1 | result2 to merge branch outputs and get the non-None result.

Program Visualization

conditional_branches

API References

Answer

Bases: DataModel

A simple, direct answer (for easy questions).

Source code in examples/4_conditional_branches.py
class Answer(synalinks.DataModel):
    """A simple, direct answer (for easy questions)."""

    answer: str = synalinks.Field(
        description="The correct answer",
    )

AnswerWithThinking

Bases: DataModel

A detailed answer with reasoning (for hard questions).

Source code in examples/4_conditional_branches.py
class AnswerWithThinking(synalinks.DataModel):
    """A detailed answer with reasoning (for hard questions)."""

    thinking: str = synalinks.Field(
        description="Your step by step thinking",
    )
    answer: str = synalinks.Field(
        description="The correct answer",
    )

Query

Bases: DataModel

A user query to process.

Source code in examples/4_conditional_branches.py
class Query(synalinks.DataModel):
    """A user query to process."""

    query: str = synalinks.Field(
        description="The user query",
    )