高度なツールの使用法
このページでは、Mastraでのツール使用に関するより高度なテクニックと機能について説明します。
アボートシグナル
generate()
または stream()
を使用してエージェントとのインタラクションを開始する際、AbortSignal
を提供することができます。Mastraは、そのインタラクション中に発生するツール実行に対して、このシグナルを自動的に転送します。
これにより、親エージェントの呼び出しが中断された場合に、ツール内の長時間実行される操作(ネットワークリクエストや集中的な計算など)をキャンセルすることができます。
ツールの execute
関数の2番目のパラメータで abortSignal
にアクセスできます。
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const longRunningTool = createTool({
id: "long-computation",
description: "Performs a potentially long computation",
inputSchema: z.object({ /* ... */ }),
execute: async ({ context }, { abortSignal }) => {
// Example: Forwarding signal to fetch
const response = await fetch("https://api.example.com/data", {
signal: abortSignal, // Pass the signal here
});
if (abortSignal?.aborted) {
console.log("Tool execution aborted.");
throw new Error("Aborted");
}
// Example: Checking signal during a loop
for (let i = 0; i < 1000000; i++) {
if (abortSignal?.aborted) {
console.log("Tool execution aborted during loop.");
throw new Error("Aborted");
}
// ... perform computation step ...
}
const data = await response.json();
return { result: data };
},\n});
これを使用するには、エージェントを呼び出す際に AbortController
のシグナルを提供します:
import { Agent } from "@mastra/core/agent";
// Assume 'agent' is an Agent instance with longRunningTool configured
const controller = new AbortController();
// Start the agent call
const promise = agent.generate("Perform the long computation.", {
abortSignal: controller.signal,
});
// Sometime later, if needed:
// controller.abort();
try {
const result = await promise;
console.log(result.text);
} catch (error) {
if (error.name === "AbortError") {
console.log("Agent generation was aborted.");
} else {
console.error("An error occurred:", error);
}
}
AI SDK ツールフォーマット
Mastraは、Vercel AI SDK(ai
パッケージ)で使用されるツールフォーマットとの互換性を維持しています。ai
パッケージのtool
関数を使用してツールを定義し、MastraのcreateTool
で作成されたツールと一緒にMastraエージェント内で直接使用することができます。
まず、ai
パッケージがインストールされていることを確認してください:
npm install ai
以下はVercel AI SDKフォーマットを使用して定義されたツールの例です:
src/mastra/tools/vercelWeatherTool.ts
import { tool } from "ai";
import { z } from "zod";
export const vercelWeatherTool = tool({
description: "Fetches current weather using Vercel AI SDK format",
parameters: z.object({
city: z.string().describe("The city to get weather for"),
}),
execute: async ({ city }) => {
console.log(`Fetching weather for ${city} (Vercel format tool)`);
// Replace with actual API call
const data = await fetch(`https://api.example.com/weather?city=${city}`);
return data.json();
},
});
このツールを他のツールと同様にMastraエージェントに追加することができます:
src/mastra/agents/mixedToolsAgent.ts
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
import { vercelWeatherTool } from "../tools/vercelWeatherTool"; // Vercel AI SDK tool
import { mastraTool } from "../tools/mastraTool"; // Mastra createTool tool
export const mixedToolsAgent = new Agent({
name: "Mixed Tools Agent",
instructions: "You can use tools defined in different formats.",
model: openai("gpt-4o-mini"),
tools: {
weatherVercel: vercelWeatherTool,
someMastraTool: mastraTool,
},
});
Mastraは両方のツールフォーマットをサポートしており、必要に応じて組み合わせて使用することができます。