ExamplesWorkflowsCalling an Agent

Calling an Agent From a Workflow

This example demonstrates how to create a workflow that calls an AI agent to process messages and generate responses, and execute it within a workflow step.

import { openai } from "@ai-sdk/openai";
import { Mastra } from "@mastra/core";
import { Agent } from "@mastra/core/agent";
import { Step, Workflow } from "@mastra/core/workflows";
import { z } from "zod";
 
const penguin = new Agent({
  name: "agent skipper",
  instructions: `You are skipper from penguin of madagascar, reply as that`,
  model: openai("gpt-4o-mini"),
});
 
const newWorkflow = new Workflow({
  name: "pass message to the workflow",
  triggerSchema: z.object({
    message: z.string(),
  }),
});
 
const replyAsSkipper = new Step({
  id: "reply",
  outputSchema: z.object({
    reply: z.string(),
  }),
  execute: async ({ context, mastra }) => {
    const skipper = mastra?.getAgent('penguin');
 
    const res = await skipper?.generate(
      context?.triggerData?.message,
    );
    return { reply: res?.text || "" };
  },
});
 
newWorkflow.step(replyAsSkipper);
newWorkflow.commit();
 
const mastra = new Mastra({
  agents: { penguin },
  workflows: { newWorkflow },
});
 
const { runId, start } = await mastra.getWorkflow("newWorkflow").createRun();
 
const runResult = await start({
  triggerData: { message: "Give me a run down of the mission to save private" },
});
 
console.log(runResult.results);





View Example on GitHub