Workflow Class
The Workflow class enables you to create state machines for complex sequences of operations with conditional branching and data validation.
Usage exampleDirect link to Usage example
src/mastra/workflows/test-workflow.ts
import { createWorkflow } from "@mastra/core/workflows";
import { z } from "zod";
export const workflow = createWorkflow({
id: "test-workflow",
inputSchema: z.object({
value: z.string(),
}),
outputSchema: z.object({
value: z.string(),
}),
});
Constructor parametersDirect link to Constructor parameters
id:
string
Unique identifier for the workflow
inputSchema:
z.ZodType<any>
Zod schema defining the input structure for the workflow
outputSchema:
z.ZodType<any>
Zod schema defining the output structure for the workflow
stateSchema?:
z.ZodObject<any>
Optional Zod schema for the workflow state. Automatically injected when using Mastra's state system. If not specified, type is 'any'.
options?:
WorkflowOptions
Optional options for the workflow
WorkflowOptionsDirect link to WorkflowOptions
tracingPolicy?:
TracingPolicy
Optional tracing policy for the workflow
validateInputs?:
boolean
= false
Optional flag to determine whether to validate the workflow inputs. This also applies default values from zodSchemas on the workflow/step input/resume data. If input/resume data validation fails on start/resume, the workflow will not start/resume, it throws an error instead. If input data validation fails on a step execution, the step fails, causing the workflow to fail and the error is returned.
shouldPersistSnapshot?:
(params: { stepResults: Record<string, StepResult<any, any, any, any>>; workflowStatus: WorkflowRunStatus }) => boolean
= () => true
Optional flag to determine whether to persist the workflow snapshot
Running with initial stateDirect link to Running with initial state
When starting a workflow run, you can pass initialState to set the starting values for the workflow's state:
const run = await workflow.createRunAsync();
const result = await run.start({
inputData: { value: "hello" },
initialState: {
counter: 0,
items: [],
},
});
The initialState object should match the structure defined in the workflow's stateSchema. See Workflow State for more details.
Workflow statusDirect link to Workflow status
A workflow's status indicates its current execution state. The possible values are:
success:
string
All steps finished executing successfully, with a valid result output
failed:
string
Workflow encountered an error during execution, with error details available
suspended:
string
Workflow execution is paused waiting for resume, with suspended step information