ツールの追加
AIエージェントを構築する際には、外部のデータや機能で能力を拡張する必要が生じることがよくあります。Mastra では、tools
パラメータを使ってエージェントにツールを渡せます。ツールは、データの取得や計算の実行など特定の関数を呼び出す手段をエージェントに提供し、ユーザーの問い合わせへの回答を支援します。
前提条件
この例では openai
モデルを使用します。.env
ファイルに OPENAI_API_KEY
を追加してください。
.env
OPENAI_API_KEY=<your-api-key>
ツールの作成
このツールはロンドンの過去の天気データを提供し、当年1月1日から今日までの、日ごとの最高/最低気温、降水量、風速、降雪量、天気状況の配列を返します。この構成により、エージェントは直近の天候トレンドに容易にアクセスし、把握できます。
src/mastra/tools/example-london-weather-tool.ts
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const londonWeatherTool = createTool({
id: "london-weather-tool",
description: "Returns year-to-date historical weather data for London",
outputSchema: z.object({
date: z.array(z.string()),
temp_max: z.array(z.number()),
temp_min: z.array(z.number()),
rainfall: z.array(z.number()),
windspeed: z.array(z.number()),
snowfall: z.array(z.number())
}),
execute: async () => {
const startDate = `${new Date().getFullYear()}-01-01`;
const endDate = new Date().toISOString().split("T")[0];
const response = await fetch(
`https://archive-api.open-meteo.com/v1/archive?latitude=51.5072&longitude=-0.1276&start_date=${startDate}&end_date=${endDate}&daily=temperature_2m_max,temperature_2m_min,precipitation_sum,windspeed_10m_max,snowfall_sum&timezone=auto`
);
const { daily } = await response.json();
return {
date: daily.time,
temp_max: daily.temperature_2m_max,
temp_min: daily.temperature_2m_min,
rainfall: daily.precipitation_sum,
windspeed: daily.windspeed_10m_max,
snowfall: daily.snowfall_sum
};
}
});
エージェントにツールを追加する
このエージェントは、ロンドンの過去の天候に関する質問に回答するために londonWeatherTool
を使用します。すべての問い合わせでこのツールを使うこと、そして応答を当年(カレンダー年)の現在日付までに利用可能なデータに限定することが、明確に指示されています。
src/mastra/agents/example-london-weather-agent.ts
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
import { londonWeatherTool } from "../tools/example-london-weather-tool";
export const londonWeatherAgent = new Agent({
name: "london-weather-agent",
description: "Provides historical information about London weather",
instructions: `You are a helpful assistant with access to historical weather data for London.
- The data is limited to the current calendar year, from January 1st up to today's date.
- Use the provided tool (londonWeatherTool) to retrieve relevant data.
- Answer the user's question using that data.
- Keep responses concise, factual, and informative.
- If the question cannot be answered with available data, say so clearly.`,
model: openai("gpt-4o"),
tools: { londonWeatherTool }
});
使用例
getAgent()
でエージェントの参照を取得し、プロンプトを渡して generate()
を呼び出します。
src/test-london-weather-agent.ts
import "dotenv/config";
import { mastra } from "./mastra";
const agent = mastra.getAgent("londonWeatherAgent");
const response = await agent.generate("How many times has it rained this year?");
console.log(response.text);
View Example on GitHub (outdated)