ステップとしてのエージェント
vNextワークフローでは、createStep(agent)
を使用してMastraエージェントを直接ステップとして使用できます:
import { Mastra } from "@mastra/core";
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { createWorkflow, createStep } from "@mastra/core/workflows/vNext";
import { z } from "zod";
const myAgent = new Agent({
name: "myAgent",
instructions: "You are a helpful assistant that answers questions concisely.",
model: openai("gpt-4o"),
});
// Input preparation step
const preparationStep = createStep({
id: "preparation",
inputSchema: z.object({
question: z.string(),
}),
outputSchema: z.object({
formattedPrompt: z.string(),
}),
execute: async ({ inputData }) => {
return {
formattedPrompt: `Answer this question briefly: ${inputData.question}`,
};
},
});
const agentStep = createStep(myAgent);
// Create a simple workflow
const myWorkflow = createWorkflow({
id: "simple-qa-workflow",
inputSchema: z.object({
question: z.string(),
}),
outputSchema: z.string(),
steps: [preparationStep, agentStep],
});
// Define workflow sequence
myWorkflow
.then(preparationStep)
.map({
prompt: {
step: preparationStep,
path: "formattedPrompt",
},
})
.then(agentStep)
.commit();
// Create Mastra instance
const mastra = new Mastra({
agents: {
myAgent,
},
vnext_workflows: {
myWorkflow,
},
});
const workflow = mastra.vnext_getWorkflow("myWorkflow");
const run = workflow.createRun();
// Run the workflow with a question
const res = await run.start({
inputData: {
question: "What is machine learning?",
},
});
if (res.status === "success") {
console.log("Answer:", res.result);
} else if (res.status === "failed") {
console.error("Workflow failed:", res.error);
}
ステップとしてのツール
vNextワークフローでは、createStep(tool)
を使用してMastraツールを直接ステップとして使用できます:
import { createTool, Mastra } from "@mastra/core";
import { createWorkflow, createStep } from "@mastra/core/workflows/vNext";
import { z } from "zod";
// Create a weather tool
const weatherTool = createTool({
id: "weather-tool",
description: "Get weather information for a location",
inputSchema: z.object({
location: z.string().describe("The city name"),
}),
outputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
}),
execute: async ({ context: { location } }) => {
return {
temperature: 22,
conditions: "Sunny",
};
},
});
// Create a step that formats the input
const locationStep = createStep({
id: "location-formatter",
inputSchema: z.object({
city: z.string(),
}),
outputSchema: z.object({
location: z.string(),
}),
execute: async ({ inputData }) => {
return {
location: inputData.city,
};
},
});
// Create a step that formats the output
const formatResultStep = createStep({
id: "format-result",
inputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
}),
outputSchema: z.object({
weatherReport: z.string(),
}),
execute: async ({ inputData }) => {
return {
weatherReport: `Current weather: ${inputData.temperature}°C and ${inputData.conditions}`,
};
},
});
const weatherToolStep = createStep(weatherTool);
// Create the workflow
const weatherWorkflow = createWorkflow({
id: "weather-workflow",
inputSchema: z.object({
city: z.string(),
}),
outputSchema: z.object({
weatherReport: z.string(),
}),
steps: [locationStep, weatherToolStep, formatResultStep],
});
// Define workflow sequence
weatherWorkflow
.then(locationStep)
.then(weatherToolStep)
.then(formatResultStep)
.commit();
// Create Mastra instance
const mastra = new Mastra({
vnext_workflows: {
weatherWorkflow,
},
});
const workflow = mastra.vnext_getWorkflow("weatherWorkflow");
const run = workflow.createRun();
// Run the workflow
const result = await run.start({
inputData: {
city: "Tokyo",
},
});
if (result.status === "success") {
console.log(result.result.weatherReport);
} else if (result.status === "failed") {
console.error("Workflow failed:", result.error);
}
エージェント内のツールとしてのワークフロー
import { openai } from "@ai-sdk/openai";
import { Mastra } from "@mastra/core";
import { Agent } from "@mastra/core/agent";
import { createTool } from "@mastra/core/tools";
import { createWorkflow, createStep } from "@mastra/core/workflows/vNext";
import { z } from "zod";
// Define the weather fetching step
const fetchWeather = createStep({
id: "fetch-weather",
inputSchema: z.object({
city: z.string().describe("The city to get the weather for"),
}),
outputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
city: z.string(),
}),
execute: async ({ inputData }) => {
return {
temperature: 25,
conditions: "Sunny",
city: inputData.city,
};
},
});
// Define the activity planning step
const planActivities = createStep({
id: "plan-activities",
inputSchema: z.object({
temperature: z.number(),
conditions: z.string(),
city: z.string(),
}),
outputSchema: z.object({
activities: z.array(z.string()),
}),
execute: async ({ inputData }) => {
mastra
.getLogger()
?.debug(`Planning activities for ${inputData.city} based on weather`);
const activities = [];
if (inputData.temperature > 20 && inputData.conditions === "Sunny") {
activities.push("Visit the park", "Go hiking", "Have a picnic");
} else if (inputData.temperature < 10) {
activities.push("Visit a museum", "Go to a cafe", "Indoor shopping");
} else {
activities.push(
"Sightseeing tour",
"Visit local attractions",
"Try local cuisine",
);
}
return {
activities,
};
},
});
// Create the weather workflow
const weatherWorkflow = createWorkflow({
id: "weather-workflow",
inputSchema: z.object({
city: z.string().describe("The city to get the weather for"),
}),
outputSchema: z.object({
activities: z.array(z.string()),
}),
steps: [fetchWeather, planActivities],
})
.then(fetchWeather)
.then(planActivities)
.commit();
// Create a tool that uses the workflow
const activityPlannerTool = createTool({
id: "get-weather-specific-activities",
description:
"Get weather-specific activities for a city based on current weather conditions",
inputSchema: z.object({
city: z.string().describe("The city to get activities for"),
}),
outputSchema: z.object({
activities: z.array(z.string()),
}),
execute: async ({ context: { city }, mastra }) => {
mastra.getLogger()?.debug(`Tool executing for city: ${city}`);
const workflow = mastra?.vnext_getWorkflow("weatherWorkflow");
if (!workflow) {
throw new Error("Weather workflow not found");
}
const run = workflow.createRun();
const result = await run.start({
inputData: {
city: city,
},
});
if (result.status === "success") {
return {
activities: result.result.activities,
};
}
throw new Error(`Workflow execution failed: ${result.status}`);
},
});
// Create an agent that uses the tool
const activityPlannerAgent = new Agent({
name: "activityPlannerAgent",
model: openai("gpt-4o"),
instructions: `
You are an activity planner. You suggest fun activities based on the weather in a city.
Use the weather-specific activities tool to get activity recommendations.
Format your response in a friendly, conversational way.
`,
tools: { activityPlannerTool },
});
// Create the Mastra instance
const mastra = new Mastra({
vnext_workflows: {
weatherWorkflow,
},
agents: {
activityPlannerAgent,
},
});
const response = await activityPlannerAgent.generate(
"What activities do you recommend for a visit to Tokyo?",
);
console.log("\nAgent response:");
console.log(response.text);