Subgraphs

Subgraphs are modular, reusable workflow components. Instead of one monolithic workflow, you build specialized subgraphs (data processing, analysis, reporting) that can be composed into larger systems, like LEGO blocks for workflows.

Data processing subgraph

Analysis subgraph

Reporting subgraph

Exactly, that is the main advantage. A data cleaning subgraph can be shared across your RAG pipeline, analytics workflow, and reporting system. Build once, compose everywhere.

patterns/25_subgraphs.py
python
class Subgraph:
    """Base class for reusable workflow components."""
    def __init__(self, name):
        self.name = name
        self.nodes = []

    def add_node(self, name, function):
        self.nodes.append({"name": name, "function": function})

    def execute(self, state):
        for node in self.nodes:
            state = node["function"](state)
        return state

class SubgraphOrchestrator:
    def __init__(self):
        self.subgraphs = []

    def add_subgraph(self, subgraph):
        self.subgraphs.append(subgraph)

    def execute_workflow(self, initial_state):
        state = initial_state
        for subgraph in self.subgraphs:
            state = subgraph.execute(state)
        return state

# Compose: DataProcessing → Analysis → Reporting
orchestrator = SubgraphOrchestrator()
orchestrator.add_subgraph(DataProcessingSubgraph())
orchestrator.add_subgraph(AnalysisSubgraph())
orchestrator.add_subgraph(ReportGenerationSubgraph())
result = orchestrator.execute_workflow(initial_data)

Base Subgraph class and SubgraphOrchestrator that chains them.

Quiz: Quiz

Loading practice…

Matching exercise: Match subgraph concepts

Loading practice…

Flashcards: Flashcards

Loading practice…

Subgraphs let you build complex workflows from simple, reusable pieces. Next, we formalize agent behavior with state machines.