Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 41

Invoking Sub-Workflows for Modular Tasks

Recommended resources

Introduction

In our previous lesson, you built a workflow constructor that could parse a static JSON definition and transform it into a live, executable Directed Acyclic Graph (DAG). This was a foundational step, enabling our system to understand and prepare a flat sequence of dependent tasks. However, as complexity grows, flat workflows become unwieldy, much like monolithic applications. To build sophisticated and maintainable agentic systems, we need principles of modularity and reuse.

This lesson directly addresses that need, focusing on the learning outcome: Implement sub-workflow invocation to create modular and reusable components within a larger task. We will extend our graph model to support hierarchy, where a single node in a parent graph can represent and invoke an entire, self-contained sub-workflow. For you, with your background in distributed systems, this concept will be highly analogous to a service orchestrator making a blocking or non-blocking call to a specialized microservice, which executes its own internal logic before returning a result. We are essentially building the architectural primitives for inter-agent communication and delegation from first principles.


Part 1: The Conceptual Model: Supervisor and Delegates

The core idea behind sub-workflows is to move from a single, monolithic plan to a hierarchy of collaborating agents. This is often described using a supervisor/delegate (or coordinator/worker) model. A high-level "supervisor" agent owns the main goal but delegates specific, well-defined sub-tasks to specialized "delegate" agents. Each delegate is itself a complete workflow, with its own prompts, tools, and logic.

The "Agentic Workflow Patterns from Scratch" article provides excellent examples of this in action.

Designing Cognitive Architectures: Agentic Workflow ...

This article explores several high-level patterns for agentic systems. We will focus on two that perfectly illustrate the supervisor/delegate model.

First, read about Pattern 3: Semantic Routing. Pay attention to how the TravelPlannerAgent acts as a coordinator, analyzing the user's intent and routing the request to a single, specialized sub-agent (like FlightSearchAgent). This is an example of conditional invocation of a sub-workflow. Next, read Pattern 4: Parallel Delegation. Here, the TravelPlannerAgent also acts as a coordinator, but instead of choosing one delegate, it distributes tasks to multiple sub-agents that run concurrently. This demonstrates parallel invocation of sub-workflows.

These patterns show that invoking a sub-workflow isn't just about calling a function; it's a powerful orchestration primitive that enables conditional logic, parallelism, and task specialization.

This chart of agentic patterns shows "Multi-Agent Systems" as a key architecture. The "Decompose Task -> Specialist Agent" flow is precisely the pattern we are implementing, where a coordinator decomposes a goal and invokes specialized sub-workflows.

Part 2: Formalizing the Mechanism: Recursive Delegation

To build this from scratch, we need a more formal model than just high-level patterns. The concept of a "Recursive Agent Hive" provides the rigorous, first-principles foundation we need.

Recursive Agent Hive Architecture

This resource formalizes the architecture of systems that can dynamically spawn sub-agents to solve problems. It provides the algorithmic blueprint for our implementation.

Start by reading the section 1. Formal Models and System Definitions. Focus on the definition of a recursive multi-agent system (RMAS). The key element is the delegation function Δ, which represents the core decision an agent makes: either execute the task directly or decompose it and delegate it to child agents. This function formalizes the logic our orchestrator will need. Next, review the Recursive Delegation Workflow under section 3. Algorithms and Coordination Protocols. This five-step algorithm, from receiving a task to aggregating results, is the exact process our system must implement to handle sub-workflow invocation. It defines the lifecycle of a delegated task.

This recursive model is the theoretical underpinning of what we are building. An agent (our workflow orchestrator) at any level can decide to become a supervisor, spawning child agents (new workflow instances) to handle sub-problems. This structure allows for arbitrary levels of nesting and complexity.


Part 3: Implementation Strategy: Extending the Graph Model

To implement sub-workflow invocation, we must evolve the graph model you designed in the previous lesson. The key change is to introduce the concept of a node that represents not a single task, but an entire graph.

Here is a practical strategy for modifying your existing code:

  1. Introduce Node Types: Modify your Node class or the data schema to include a type attribute. This could be an enum with values like TASK (for a simple tool/LLM call) and SUB_WORKFLOW.

  2. Define the Sub-Workflow Node: When a node's type is SUB_WORKFLOW, it needs additional metadata:

    • graph_definition_path: A string pointing to the JSON or YAML file that defines the sub-workflow's DAG. This makes our workflows modular and reusable.
    • input_mapping: A dictionary defining how to pass data from the parent graph's state into the initial state of the sub-workflow. For example, {"sub_task_prompt": "parent_node_2.output"}.
    • output_mapping: A dictionary defining how to integrate the final results from the sub-workflow back into the parent graph's state. For example, {"summary_result": "sub_graph_final_output.summary"}.
  3. Update the Orchestrator (Execution Engine): Your main execution loop, which iterates through the topological sort of the graph, needs new logic. When it encounters a node:

    • If type is TASK: Execute it as before (e.g., call a tool).
    • If type is SUB_WORKFLOW:
      a. Pause its own execution.
      b. Use the graph_definition_path to create a new instance of your WorkflowConstructor and build the sub-graph in memory.
      c. Use the input_mapping to prepare the initial state for the sub-graph.
      d. Create a new instance of your Orchestrator to execute this sub-graph. Your experience with async programming is relevant here; this invocation can be awaited.
      e. Once the sub-graph execution completes, use the output_mapping to extract the results and update the parent graph's state.
      f. Mark the SUB_WORKFLOW node as complete and continue the parent graph's execution.

This recursive instantiation is the core of the implementation. Your orchestrator effectively calls itself to handle nested graphs.


Part 4: Managing State and Data Flow

The most critical part of this process is managing the flow of information between the parent and child workflows. The sub-workflow must be an encapsulated, black-box-like component. It should receive explicit inputs and produce explicit outputs, without having implicit access to the parent's entire state.

A video from LangChain, while using a framework, provides an excellent visual and logical demonstration of how this data handoff works in practice. We will use it to understand the principle, not the specific API calls.

How to Build Multi AI Agents with Langgraph

This video demonstrates a supervisor agent orchestrating researcher and copywriter sub-agents. We'll focus on how the supervisor invokes a sub-agent and manages the data exchange.

Watch the segment explaining the supervisor's handoff tool and the invocation of the sub-graph, from Here's the handoff tool. Pay close attention to these key moments: The go_to command: The supervisor uses a command to explicitly route execution to a different node that represents the sub-agent. This is the programmatic "handoff." Invoking the sub-graph: The code calls researcher_graph.invoke(...). Notice that it passes a specific, curated input: a single HumanMessage containing just the task_description. The sub-agent does not see the supervisor's full conversation history. This demonstrates the principle of encapsulation. Extracting the result: After the sub-graph finishes, the supervisor accesses its final state (research_response.get("research_reports")) and updates its own state. This shows how results are passed back from the child to the parent.

This sequence—prepare inputs, invoke, retrieve outputs, update state—is the fundamental interaction pattern you will need to implement. The input_mapping and output_mapping fields in our proposed schema are the declarative way to define this interaction for each sub-workflow node.


Conclusion

In this lesson, we have laid out the architecture for creating modular, hierarchical agentic systems. By treating entire workflows as callable components, you move beyond simple, linear chains into building complex, reusable, and specialized agent colonies. This is a significant step towards engineering production-grade, scalable systems.

Key Takeaways:

  • Sub-workflow invocation enables modularity and reuse by allowing one graph to call another, analogous to a microservices architecture.
  • The supervisor/delegate model is a common pattern where a coordinator agent delegates tasks to specialized sub-agents (sub-workflows).
  • The implementation requires extending your graph model with node types (TASK vs. SUB_WORKFLOW) and metadata for defining the sub-workflow's location and data mapping.
  • The orchestrator implements recursion, creating new instances of itself to execute sub-graphs.
  • A clear data contract (input_mapping, output_mapping) is crucial for managing state between parent and child workflows, ensuring encapsulation.

Preview of the Next Module:
Now that we can construct intricate, nested workflows, the potential for failure increases. A failure in a deeply nested sub-workflow could cascade and bring down the entire task. The next module, "Agent Reliability and Recovery Patterns," will tackle this head-on. We will explore essential engineering patterns like retries with exponential backoff, circuit breakers for failing services, and idempotent tool design—all critical for building robust agentic systems that can gracefully handle the inevitable failures of a distributed environment.