Branching Paths
When processing data, you often need to take different actions based on intermediate results. This example shows how to create a workflow that splits into separate paths, where each path executes different steps based on the output of a previous step.
Control Flow Diagram
This example shows how to create a workflow that splits into separate paths, where each path executes different steps based on the output of a previous step.
Here’s the control flow diagram:
Creating the Steps
Let’s start by creating the steps and initializing the workflow.
import { Step, Workflow } from "@mastra/core";
import { z } from "zod"
const stepOne = new Step({
id: "stepOne",
execute: async ({ context: { machineContext } }) => ({
doubledValue: machineContext.triggerData.inputValue * 2
})
});
const stepTwo = new Step({
id: "stepTwo",
execute: async ({ context: { machineContext } }) => ({
isDivisibleByFive: machineContext.stepResults.stepOne.payload.doubledValue % 5 === 0
})
});
const stepThree = new Step({
id: "stepThree",
execute: async ({ context: { machineContext } }) => ({
incrementedValue: machineContext.stepResults.stepOne.payload.doubledValue + 1
})
});
const stepFour = new Step({
id: "stepFour",
execute: async ({ context: { machineContext } }) => ({
isDivisibleByThree: machineContext.stepResults.stepThree.payload.incrementedValue % 3 === 0
})
});
// Build the workflow
const myWorkflow = new Workflow({
name: "my-workflow",
triggerSchema: z.object({
inputValue: z.number(),
}),
});
Branching Paths and Chaining Steps
Now let’s execute the workflow and see the results.
myWorkflow
.step(stepOne)
.then(stepTwo)
.after(stepOne)
.step(stepThree)
.then(stepFour)
.commit();
const result = await myWorkflow.execute({ triggerData: { inputValue: 3 } });
View Example on GitHub