Skip to main content

Agent as a Step

Workflows can include agents as steps. This example shows how to define an agent as a step using createStep().

Creating an agent

Create a simple agent that returns facts about a city.

import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";

export const cityAgent = new Agent({
name: "city-agent",
description: "Create facts for a city",
instructions: "Return an interesting fact based on the city provided",
model: openai("gpt-4o"),
});

Agent input/output schema

Mastra agents use a default schema that expects a prompt string as input and returns a text string as output.

{
inputSchema: {
prompt: string
},
outputSchema: {
text: string
}
}

Agent as step

To use an agent as a step, pass it directly to createStep(). Use the .map() method to transform the workflow input into the shape the agent expects.

In this example, the workflow receives a city input, maps it to a prompt, then calls the agent. The agent returns a text string, which is passed directly to the workflow output. Although the output schema expects a facts field, no additional mapping is required.

import { createWorkflow, createStep } from "@mastra/core/workflows";
import { z } from "zod";

import { cityAgent } from "../agents/example-city-agent";

const step1 = createStep(cityAgent);

export const agentAsStep = createWorkflow({
id: "agent-step-workflow",
inputSchema: z.object({
city: z.string(),
}),
outputSchema: z.object({
facts: z.string(),
}),
})
.map(async ({ inputData }) => {
const { city } = inputData;
return {
prompt: `Create an interesting fact about ${city}`,
};
})

.then(step1)
.commit();

Workflows (Legacy)

The following links provide example documentation for legacy workflows: