Looping step execution
This example demonstrates how to create a workflow that executes one or more of it’s steps in a loop until a condition is met
Define Looping workflow
Defines a workflow which calls the executes a nested workflow until the provided condition is met.
looping-workflow.ts
import { createWorkflow, createStep } from '@mastra/core/workflows/vNext'
import { z } from 'zod'
const incrementStep = createStep({
id: 'increment',
inputSchema: z.object({
value: z.number(),
}),
outputSchema: z.object({
value: z.number(),
}),
execute: async ({ inputData }) => {
return { value: inputData.value + 1 }
},
})
const sideEffectStep = createStep({
id: 'side-effect',
inputSchema: z.object({
value: z.number(),
}),
outputSchema: z.object({
value: z.number(),
}),
execute: async ({ inputData }) => {
console.log('log', inputData.value)
return { value: inputData.value }
},
})
const finalStep = createStep({
id: 'final',
inputSchema: z.object({
value: z.number(),
}),
outputSchema: z.object({
value: z.number(),
}),
execute: async ({ inputData }) => {
return { value: inputData.value }
},
})
const workflow = createWorkflow({
id: 'increment-workflow',
inputSchema: z.object({
value: z.number(),
}),
outputSchema: z.object({
value: z.number(),
}),
})
.dountil(
createWorkflow({
id: 'increment-workflow',
inputSchema: z.object({
value: z.number(),
}),
outputSchema: z.object({
value: z.number(),
}),
steps: [incrementStep, sideEffectStep],
})
.then(incrementStep)
.then(sideEffectStep)
.commit(),
async ({ inputData }) => inputData.value >= 10
)
.then(finalStep)
workflow.commit()
export { workflow as incrementWorkflow }
Register Workflow instance with Mastra class
Register the workflow with the mastra instance.
index.ts
import { Mastra } from '@mastra/core/mastra'
import { createLogger } from '@mastra/core/logger'
import { incrementWorkflow } from './workflows'
const mastra = new Mastra({
vnext_workflows: {
incrementWorkflow,
},
logger: createLogger({
name: 'Mastra',
level: 'info',
}),
})
export { mastra }
Execute the workflow
Here, we’ll get the increment workflow from the mastra instance, then create a run and execute the created run with the required inputData.
exec.ts
import { mastra } from "./"
const workflow = mastra.vnext_getWorkflow('incrementWorkflow')
const run = workflow.createRun()
const result = await run.start({ inputData: { value: 0 } })
console.dir(result, { depth: null })
View Example on GitHub