The chaining pattern

The chaining pattern: the output of step 1 becomes the input to step 2. Think of it as a pipeline. For example: get weather (step 1) then decide thermostat setting based on the weather (step 2).

06-ai-workflows.ipynb
python
def get_weather_forecast():
    """Step 1: Get weather data."""
    return "Sunny and 95°F"

def climate_workflow():
    # Step 1: Get data
    weather = get_weather_forecast()

    # Step 2: LLM decides action based on step 1 output
    action = ask_llm(
        "You are a smart thermostat. Based on the "
        "weather, decide a target temperature.",
        f"Current Weather: {weather}"
    )

    return f"Weather: {weather} -> Action: {action}"

print(climate_workflow())
# "Weather: Sunny and 95°F -> Action: Set to 72°F"

The chain: step 1 gets weather, step 2 uses an LLM to decide the thermostat setting based on step 1 output.

Chaining: output of step 1 feeds into step 2

06-ai-workflows.ipynb
python
# Combining Router + Chain:
# 1. Router classifies: "Set temperature for weather"
#    -> CLIMATE category
# 2. Climate handler runs a chain:
#    get_weather() -> decide_thermostat()

def smart_home_system(query):
    category = smart_home_router(query)

    if category == "CLIMATE":
        return climate_workflow()  # Chain!
    elif category == "LIGHTING":
        return handle_lighting(query)
    elif category == "SECURITY":
        return handle_security(query)

The router dispatches to a handler, and the handler can internally use chaining for multi-step workflows.

Matching exercise: Match workflow patterns to use cases

Loading practice…

Quiz: Quiz

Loading practice…