ワークフロー付きツール
ツールにワークフローを組み合わせることで、標準ツールと同様に動作する再利用可能なマルチステッププロセスを作成できます。複雑なロジックをシンプルなインターフェースに隠蔽したい場合に有効です。
ワークフローの作成
この例では、2つのステップで構成されるワークフローを定義します:
- getCityCoordinates: 指定された都市の位置情報データを取得します。
- getCityTemperature: 座標を使用して現在の気温を取得します。
このワークフローはcity
を入力として受け取り、temperature
を出力します。
src/mastra/workflows/example-temperature-workflow.ts
import { createWorkflow, createStep } from "@mastra/core/workflows";
import { z } from "zod";
const getCityCoordinates = createStep({
id: "get-city-coordinates",
description: "都市のジオコーディング情報を取得",
inputSchema: z.object({
city: z.string()
}),
outputSchema: z.object({
longitude: z.number(),
latitude: z.number()
}),
execute: async ({ inputData }) => {
const { city } = inputData;
const response = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${city}&count=1`);
const { results } = await response.json();
const { latitude, longitude } = results[0];
return {
latitude,
longitude
};
}
});
const getCityTemperature = createStep({
id: "get-city-temperature",
description: "緯度・経度から気温を取得",
inputSchema: z.object({
latitude: z.number(),
longitude: z.number()
}),
outputSchema: z.object({
temperature: z.string()
}),
execute: async ({ inputData }) => {
const { latitude, longitude } = inputData;
const response = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t_weather=true`);
const { current_weather, current_weather_units } = await response.json();
return {
temperature: `${current_weather.temperature} ${current_weather_units.temperature}`
};
}
});
export const temperatureWorkflow = createWorkflow({
id: "temperature-workflow",
inputSchema: z.object({
city: z.string()
}),
outputSchema: z.object({
temperature: z.string()
})
})
.then(getCityCoordinates)
.then(getCityTemperature)
.commit();
ツールからワークフローを実行する
このツールはワークフローをラップし、標準的なツールインターフェースを通じて公開します。入力としてcity
を受け取り、内部のワークフローを実行し、結果のtemperature
を返します。
src/mastra/tools/temperature-tool.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const getTemperatureTool = createTool({
id: "get-temperature-tool",
description: "Gets the temperature for a city",
inputSchema: z.object({
city: z.string()
}),
outputSchema: z.object({
temperature: z.string()
}),
execute: async ({ context, mastra }) => {
const { city } = context;
const workflow = mastra!.getWorkflow("temperatureWorkflow");
const run = await workflow!.createRunAsync({});
const runResult = await run!.start({
inputData: {
city
}
});
const { temperature } = (runResult as any).result;
return {
temperature
};
}
});
View Example on GitHub