DocsHow toBuilding Workflows

Workflows in Mastra

Workflows are graph-based state machines that can execute complex sequences of operations. They provide a structured way to handle multi-step processes, parallel operations, and (soon) suspend-and-resume for human interactions.

Workflows are defined in a dedicated directory. The directory path is configured in your Mastra config file. When you use workflows with cloud observability providers, you can see the inputs and outputs of each step.

Building a Workflow

Here’s an simple example of a workflow that uses predefined tools to crawl a website, uses an LLM to structure the data, and then analyzes the sentiment of the content.

src/workflows/index.ts
const workflow = new Workflow('content-analyzer')
  .setTriggerSchema(z.object({
    url: z.string().url()
  }))
  .addStep('crawl', {
    action: async ({ tools, data }) => {
      const result = await tools.crawlWebpage({ url: data.url });
      return { rawText: result.text };
    },
    transitions: {
      structure: {
        condition: {
          ref: { stepId: 'crawl', path: 'rawText' },
          query: { $exists: true }
        }
      }
    }
  })
  .addStep('structure', {
    action: async ({ tools, data }) => {
      const result = await tools.structureReviews({ rawText: data.rawText });
      return { reviews: result };
    },
    variables: {
      rawText: { stepId: 'crawl', path: 'rawText' }
    }
  })
  .commit();
 
// Execute the workflow
const result = await workflow.executeWorkflow({
  url: 'https://example.com/reviews'
});

Register with Mastra

src/mastra/index.ts
import { workflow } from './workflows';
 
export const mastra = new Mastra({
  ...restOfConfig,
  workflows: [workflow],
});

Reference Documentation

More detailed documentation on transitions, conditions, variables, steps, and validation can be found in the reference docs: