Skip to Content
ExamplesAgentsMulti-Agent Workflow

Multi-Agent Workflow

This example demonstrates how to create an agentic workflow with work product being passed between multiple agents with a worker agent and a supervisor agent.

In this example, we create a sequential workflow that calls two agents in order:

  1. A Copywriter agent that writes the initial blog post
  2. An Editor agent that refines the content

First, import the required dependencies:

import { openai } from "@ai-sdk/openai"; import { anthropic } from "@ai-sdk/anthropic"; import { Agent } from "@mastra/core/agent"; import { Step, Workflow } from "@mastra/core/workflows"; import { z } from "zod";

Create the copywriter agent that will generate the initial blog post:

const copywriterAgent = new Agent({ name: "Copywriter", instructions: "You are a copywriter agent that writes blog post copy.", model: anthropic("claude-3-5-sonnet-20241022"), });

Define the copywriter step that executes the agent and handles the response:

const copywriterStep = new Step({ id: "copywriterStep", execute: async ({ context }) => { if (!context?.triggerData?.topic) { throw new Error("Topic not found in trigger data"); } const result = await copywriterAgent.generate( `Create a blog post about ${context.triggerData.topic}`, ); console.log("copywriter result", result.text); return { copy: result.text, }; }, });

Set up the editor agent to refine the copywriter’s content:

const editorAgent = new Agent({ name: "Editor", instructions: "You are an editor agent that edits blog post copy.", model: openai("gpt-4o-mini"), });

Create the editor step that processes the copywriter’s output:

const editorStep = new Step({ id: "editorStep", execute: async ({ context }) => { const copy = context?.getStepResult<{ copy: number }>("copywriterStep")?.copy; const result = await editorAgent.generate( `Edit the following blog post only returning the edited copy: ${copy}`, ); console.log("editor result", result.text); return { copy: result.text, }; }, });

Configure the workflow and execute the steps:

const myWorkflow = new Workflow({ name: "my-workflow", triggerSchema: z.object({ topic: z.string(), }), }); // Run steps sequentially. myWorkflow.step(copywriterStep).then(editorStep).commit(); const { runId, start } = myWorkflow.createRun(); const res = await start({ triggerData: { topic: "React JavaScript frameworks" }, }); console.log("Results: ", res.results);





View Example on GitHub