Created
February 25, 2025 18:09
-
-
Save abhiaiyer91/47810a5bf51c1859588250a0bd200092 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Workflow, Step } from '@mastra/core'; | |
import { z } from 'zod'; | |
async function main() { | |
// Step A: Increment the counter | |
const incrementStep = new Step({ | |
id: 'increment', | |
description: 'Increments the current value by 1', | |
outputSchema: z.object({ | |
newValue: z.number(), | |
}), | |
execute: async ({ context }) => { | |
// Get the current value (either from trigger or previous increment) | |
const currentValue = context.getStepResult<{ newValue: number }>('increment')?.newValue || | |
context.getStepResult<{ startValue: number }>('trigger')?.startValue || 0; | |
// Increment the value | |
const newValue = currentValue + 1; | |
console.log(`Step A: ${newValue}`); | |
return { newValue }; | |
}, | |
}); | |
// Step B: Check if we've reached the target | |
const checkTargetStep = new Step({ | |
id: 'checkTarget', | |
description: 'Checks if the current value has reached the target', | |
outputSchema: z.object({ | |
reachedTarget: z.boolean(), | |
}), | |
execute: async ({ context }) => { | |
const currentValue = context.getStepResult<{ newValue: number }>('increment')?.newValue || 0; | |
const target = context.getStepResult<{ target: number }>('trigger')?.target || 0; | |
// Check if we've reached the target | |
const reachedTarget = currentValue >= target; | |
console.log(`Step B: ${reachedTarget}`); | |
return { reachedTarget }; | |
}, | |
}); | |
// Create the workflow | |
const counterWorkflow = new Workflow({ | |
name: 'counter-workflow', | |
triggerSchema: z.object({ | |
target: z.number(), | |
startValue: z.number(), | |
}), | |
}); | |
// Define the workflow steps with cyclical dependency | |
counterWorkflow | |
.step(incrementStep) | |
.then(checkTargetStep) | |
.after(checkTargetStep) | |
.step(incrementStep, { | |
when: { | |
ref: { step: checkTargetStep, path: 'reachedTarget' }, | |
query: { $eq: false }, | |
}, | |
}) | |
.then(checkTargetStep) | |
.commit(); | |
// Run the workflow | |
const { runId, start } = counterWorkflow.createRun(); | |
console.log('Starting workflow run:', runId); | |
// Example with target: 3, startValue: 0 | |
const result = await start({ | |
triggerData: { | |
target: 10, | |
startValue: 0 | |
} | |
}); | |
console.log('Exit'); | |
console.log('Results:', result.results); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment