Skip to main content

Welcome to a Grasp lesson

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

Lesson 40

Building a Workflow Constructor

Recommended resources

Introduction

In our last lesson, you engineered a "Planner" agent capable of translating a user's request into a structured JSON representation of a Directed Acyclic Graph (DAG). This was a crucial step in delegating the planning phase to an LLM. However, a JSON object is just a static blueprint. To bring this plan to life, we need a mechanism to read, understand, and prepare it for our execution engine.

This lesson directly addresses the learning outcome: Implement a workflow constructor that parses a graph definition and prepares it for execution. You will build the component that acts as the bridge between the declarative plan generated by the LLM and the imperative, executable objects within our system. This process is analogous to the front-end of a compiler, which parses source code and builds an in-memory Abstract Syntax Tree. Your background in software engineering will be directly applicable as we transform a data-interchange format into a robust, in-memory graph structure ready for orchestration.


Part 1: From a Static Definition to a Live Workflow

The component we are building, the workflow constructor, has a clear and vital role: it consumes a static graph definition (our JSON from the Planner) and instantiates a corresponding, executable graph object in memory.

This process involves several distinct steps:

  1. Parsing: Reading the raw structured data (e.g., a JSON string) and loading it into a native data structure.
  2. Validation: Ensuring the graph is well-formed, conforms to our schema, and is acyclic.
  3. Instantiation: Building the in-memory graph by creating node and edge objects that represent the tasks and their dependencies.
  4. Preparation: Processing the graph to determine a valid execution order, making it ready for the orchestration engine.

The diagram below shows a high-level architecture of a system called pyDag. Focus on the central PyDag component, which contains a Dag composed of Vertices (our nodes) and Edges (our dependencies). Our constructor's job is to build exactly this kind of structure from a file or a string.

This diagram illustrates how a central `Dag` object, containing vertices and edges, forms the core of a workflow execution system. Our constructor is responsible for creating this `Dag` object from a static definition.

Part 2: Parsing, Deserialization, and Validation

The first step is to transform the character stream of the JSON plan into a native object that our code can manipulate. This process is formally known as deserialization or parsing. While our Planner agent generates JSON, this principle applies to any structured format like YAML.

The image below illustrates the generic process for YAML. The "Load" path at the bottom shows the transformation from a character stream through parsing and composition into a "Native Data Structure" within an application. This is precisely what our constructor's first stage does.

This diagram shows the "Load" process, which transforms a text-based character stream into a native data structure within an application. This is the first step of our workflow constructor.

Once the data is loaded, we must validate it. While the LLM's structured output feature (from the previous lesson) guarantees syntactically correct JSON, it does not guarantee semantic correctness. Our constructor must be robust against logical errors in the generated plan.

Key validation checks include:

  • Schema Conformance: Does the loaded data match the expected structure (e.g., a list of steps, each with agent, task, and dependencies keys)? In Python, a library like Pydantic is ideal for this.
  • Dependency Integrity: Do all integer indices in the dependencies lists refer to valid, existing steps in the plan? An out-of-bounds index would crash the executor.
  • Acyclicity: Does the graph contain any cycles (e.g., Step A depends on B, and Step B depends on A)? A cyclic dependency would lead to a deadlock. This is the most critical validation for a DAG. We'll see how to detect this shortly.

Part 3: Building the In-Memory Graph Representation

With a validated data structure, we can now build the graph. This involves creating programmatic objects for the graph itself, its nodes (vertices), and its dependencies (edges).

A practical approach involves these steps:

  1. Define a Node class to hold task information (e.g., id, agent, prompt).
  2. Define a Graph class to contain a collection of nodes and the dependency relationships between them. This class will have methods like add_node and add_edge.
  3. First Pass (Node Creation): Iterate through the list of tasks from the parsed JSON. For each task, create a Node instance and add it to the Graph. It's helpful to store nodes in a structure that allows easy lookup, like a dictionary keyed by their original index.
  4. Second Pass (Edge Creation): Iterate through the tasks again. For each task, read its dependencies list. For each dependency index, create an edge in your Graph object linking the dependent node to the current node.

As you add each edge, you can perform cycle detection. A common method is to perform a depth-first search (DFS) starting from the new edge's source node. If you encounter the destination node again during the traversal of its own upstream dependencies, you have found a cycle.

The following article describes building a DAG-based scheduler. We'll focus on its description of the core data structure.

How to build a DAG based Task Scheduling tool for Multiprocessor systems using python | by Ramses Alexander Coraspe Valdez | ITNEXT

This article provides a step-by-step guide to building a task scheduler. We'll examine how it models the graph data structure itself.

In the section "Let’s build pyDag step by step," read subsection 2. DAG data structure. Focus on the description where it explains the need for an object class to contain the graph's structure and methods for adding vertices and edges, as well as performing validations like cycle detection. This mirrors the exact functionality our constructor needs.


Part 4: Preparing for Execution with Topological Sort

Once we have a validated, acyclic graph in memory, it's ready to be prepared for the execution engine. The engine needs to know which tasks can run now, which must wait, and in what order to proceed. For a DAG, the canonical algorithm for determining this is topological sorting.

A topological sort produces a linear ordering of the graph's nodes such that for every directed edge from node A to node B, node A comes before node B in the ordering. This ordering is not necessarily unique, but any valid ordering guarantees that all dependencies will be met.

A common and intuitive algorithm for this is Kahn's algorithm:

  1. Compute the "in-degree" (number of incoming edges) for every node in the graph.
  2. Initialize a queue with all nodes that have an in-degree of 0. These are the "root" nodes that have no dependencies and can be executed immediately.
  3. While the queue is not empty:
    a. Dequeue a node. Add it to our sorted list. This node is now "executed".
    b. For each neighbor of this node (i.e., each node that depends on it), decrement its in-degree by 1.
    c. If a neighbor's in-degree becomes 0, enqueue it. It's now ready for execution.

This process naturally reveals opportunities for parallelism. At any point, all nodes in the queue can be executed concurrently. The pyDag article you just looked at explains this concept beautifully.

How to build a DAG based Task Scheduling tool for Multiprocessor systems using python | by Ramses Alexander Coraspe Valdez | ITNEXT

Let's return to the pyDag article to understand how topological sort enables execution.

Read section 3. Topological Sorting and Parallel Execution. The text explains exactly why we need this algorithm: to get an order that respects dependencies. Pay close attention to the statement that the algorithm, in each step, provides the next set of tasks that can be run concurrently. This is the key insight: topological sort doesn't just give us a sequence; it gives us batches of parallelizable work, which is critical for an efficient orchestration engine.

The output of the topological sort is the final product of our constructor: a structured plan, perhaps a list of lists, where each inner list contains a "layer" of nodes that can be executed in parallel.

For a more formal and advanced perspective, the DynTaskMAS paper presents a similar idea with its Dynamic Task Graph Generator.

[PDF] DynTaskMAS: A Dynamic Task Graph-driven Framework for ...

This research paper describes a sophisticated multi-agent system. We'll look at its algorithm for graph construction to see a more formal representation of the process we're implementing.

First, read the paragraph describing the Dynamic Task Graph Generator (DTGG), from its beginning. Note how it defines the graph G = (V, E, W) and a recursive decomposition function D(ti). This is a formalization of our parsing and instantiation process. Next, examine Algorithm 1: Dynamic Task Graph Generator. The UPDATETASKGRAPH function and the helper DECOMPOSETASK provide pseudocode for iterating through new tasks, decomposing them, and adding vertices (V) and edges (E) to the graph. This is the core logic of our constructor, expressed algorithmically.


Part 5: Instantiating Executable Nodes

The final step of the constructor is to ensure the nodes in our in-memory graph are not just data containers, but are prepared for execution. This involves linking each node to the specific tool or agent it's supposed to run.

In the JSON plan from our previous lesson, each step had an agent field. Our constructor uses this field to annotate the Node object it creates. The execution engine will later use this annotation to dispatch the task to the correct handler—be it a Python function, a sub-agent, or an external API call. The pyDag article provides an excellent model for this with its "Engines and Handlers" concept.

How to build a DAG based Task Scheduling tool for Multiprocessor systems using python | by Ramses Alexander Coraspe Valdez | ITNEXT

This final reading from the pyDag article details how tasks are dynamically executed based on their type, a crucial function of the execution engine that our constructor must prepare for.

Read the section 4. Engines and Handlers. Focus on the concept that each task is tied to an engine. The example script property (gcs.project-pydag.module_name.spark.csv_gcs_to_bq) shows how a string can encode the location, module, and engine (spark) for a task. Our constructor would parse this and attach the "spark" engine type to the node. Now, look at the diagram and text under the heading "The process of running a task is totally dynamic". It describes how a generic run method calls a script_handler and an engine_handler. The engine_handler dynamically creates the right engine client (e.g., BQClient, DPClient) based on the task's properties. This is the handoff point: our constructor builds the node with the right properties, and the executor uses those properties to run the correct code. Finally, briefly review section 6. pyDag’s Architecture for a Multiprocessor Machine. The full architectural diagram brings everything together, showing how the Dag object feeds into the Topological Sort and ParallelProcessor, which in turn uses the Executor, EngineHandler, and Engines to run tasks. Your constructor is the entry point that builds the Dag at the heart of this system.

While we are building from scratch, it's helpful to see how this graph construction looks in a library like LangGraph. It provides a fluent API for what our constructor does programmatically.

Building Effective Agents with LangGraph

This video on LangGraph demonstrates how to build workflows programmatically. We'll observe the API calls used to define the graph structure.

Watch the segment from now I lay this out. Notice the calls to add_node to define the steps (our vertices) and set_entry_point and add_edge to define the dependencies (our edges). Your constructor would be making similar programmatic calls to build its internal graph object. Next, watch from build this in L graph. This demonstrates a fan-out/fan-in pattern. The code shows adding multiple nodes (LM call 1, 2, 3) that are all connected from the start, and then all connect to a single aggregator node. Your constructor would achieve this by parsing a plan where multiple tasks have no dependencies, and another task depends on all of them.

By parsing the agent type and attaching it to the node, our constructor produces a fully prepared, executable graph that the orchestration engine can begin to process.


Conclusion

In this lesson, you have designed the critical machinery that transforms a static plan into a dynamic, executable workflow. The workflow constructor is the lynchpin of an agentic system, connecting the abstract reasoning of a planner LLM to the concrete actions of an execution engine.

Key Takeaways:

  • A workflow constructor is responsible for parsing, validating, instantiating, and preparing a graph definition for execution.
  • Validation is crucial and must check for schema conformance, dependency integrity, and especially acyclicity to ensure the graph is a valid DAG.
  • An in-memory graph is built by creating Node and Edge objects based on the parsed definition.
  • Topological sorting is the fundamental algorithm used to determine a valid execution order and identify tasks that can be run in parallel.
  • The constructor prepares nodes for execution by annotating them with their required engine or agent type, enabling the executor to dispatch them to the correct handler.

Preview of the Next Lesson:
Our current constructor can build a single, flat graph. But to create truly complex and maintainable systems, we need modularity. In the next lesson, "Implement sub-workflow invocation to create modular and reusable components within a larger task," we will extend our graph model to support nesting, allowing one workflow to call another as a single step. This will enable you to build hierarchical and highly reusable agentic systems.