Dynamic Routing

Functions can route data to different nodes based on custom logic, enabling dynamic branching.

Using RouteTo for Dynamic Routing

The RouteTo class allows functions to dynamically choose which downstream functions to execute and what data to pass to them.
from tensorlake import RouteTo, tensorlake_function

@tensorlake_function()
def handle_error(text: str) -> str:
    return f"Error handled: {text}"

@tensorlake_function()
def handle_normal(text: str) -> str:
    return f"Normal processing: {text}"

@tensorlake_function()
def process_urgent(text: str) -> str:
    return f"Urgent processing: {text}"

@tensorlake_function(next=[handle_error, handle_normal, process_urgent])
def analyze_text(text: str) -> RouteTo[str, handle_error | handle_normal | process_urgent]:
    """Route text to different handlers based on content."""
    processed_text = text.upper()

    if 'error' in text.lower():
        # Route only to error handler
        return RouteTo(processed_text, [handle_error])
    elif 'urgent' in text.lower():
        # Route to both normal and urgent handlers
        return RouteTo(processed_text, [handle_normal, process_urgent])
    else:
        # Route only to normal handler
        return RouteTo(processed_text, [handle_normal])

Conditional Routing with Value Transformation

You can also transform the data while routing:
@tensorlake_function()
def process_even(value: int) -> int:
    return value * 2

@tensorlake_function()
def process_odd_a(value: int) -> int:
    return value + 10

@tensorlake_function()
def process_odd_b(value: int) -> int:
    return value + 20

@tensorlake_function(next=[process_even, process_odd_a, process_odd_b])
def route_by_parity(value: int) -> RouteTo[int, process_even | process_odd_a | process_odd_b]:
    """Route based on whether the value is even or odd."""
    if value % 2 == 0:
        # Even numbers: increment by 1 and route to even processor
        return RouteTo(value + 1, [process_even])
    else:
        # Odd numbers: increment by 2 and route to both odd processors
        return RouteTo(value + 2, [process_odd_a, process_odd_b])

Early Graph Termination

Functions can also terminate execution early by returning an empty routing list:
@tensorlake_function()
def final_step(text: str) -> str:
    return f"Final: {text}"

@tensorlake_function(next=final_step)
def conditional_termination(text: str) -> RouteTo[str, final_step]:
    """Conditionally terminate the graph early."""
    processed = text + "_processed"

    if "stop" in text.lower():
        # Terminate early - don't execute final_step
        return RouteTo(processed, [])
    else:
        # Continue to final_step
        return RouteTo(processed, [final_step])