Calling an agent inside a step
Workflows can call agents to generate dynamic responses from within a step. This example shows how to define an agent, register it with the Mastra instance, and invoke it using .generate()
inside a workflow step. The workflow takes a city name as input and returns a fact about the corresponding city.
Creating an agent
Create a simple agent that returns facts about a city.
src/mastra/agents/example-city-agent.ts
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")
});
Registering an agent
To call an agent from a workflow, the agent must be registered in the Mastra instance.
src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";
import { cityAgent } from "./agents/example-city-agent";
export const mastra = new Mastra({
// ...
agents: { cityAgent },
});
Calling an agent
Get a reference to the registered agent using getAgent()
, then call .generate()
inside the step, passing in the input data.
src/mastra/workflows/example-call-agent.ts
import { createWorkflow, createStep } from "@mastra/core/workflows";
import { z } from "zod";
const step1 = createStep({
id: "step-1",
description: "passes value from input to agent",
inputSchema: z.object({
city: z.string()
}),
outputSchema: z.object({
facts: z.string()
}),
execute: async ({ inputData, mastra }) => {
const { city } = inputData;
const agent = mastra.getAgent("cityAgent");
const response = await agent.generate(`Create an interesting fact about ${city}`);
return {
facts: response.text
};
}
});
export const callAgent = createWorkflow({
id: "agent-workflow",
inputSchema: z.object({
city: z.string()
}),
outputSchema: z.object({
facts: z.string()
})
})
.then(step1)
.commit();