41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
|
|
import { createTool } from "@mastra/core/tools";
|
||
|
|
import { z } from "zod";
|
||
|
|
|
||
|
|
export const calculatorTool = createTool({
|
||
|
|
id: "calculator",
|
||
|
|
description: "Perform basic arithmetic operations",
|
||
|
|
inputSchema: z.object({
|
||
|
|
operation: z.enum(["add", "subtract", "multiply", "divide"]).describe("The arithmetic operation to perform"),
|
||
|
|
a: z.number().describe("First number"),
|
||
|
|
b: z.number().describe("Second number"),
|
||
|
|
}),
|
||
|
|
outputSchema: z.object({
|
||
|
|
result: z.number(),
|
||
|
|
operation: z.string(),
|
||
|
|
}),
|
||
|
|
execute: async ({ context }) => {
|
||
|
|
const { operation, a, b } = context;
|
||
|
|
let result: number;
|
||
|
|
switch (operation) {
|
||
|
|
case "add":
|
||
|
|
result = a + b;
|
||
|
|
break;
|
||
|
|
case "subtract":
|
||
|
|
result = a - b;
|
||
|
|
break;
|
||
|
|
case "multiply":
|
||
|
|
result = a * b;
|
||
|
|
break;
|
||
|
|
case "divide":
|
||
|
|
if (b === 0) throw new Error("Division by zero");
|
||
|
|
result = a / b;
|
||
|
|
break;
|
||
|
|
default:
|
||
|
|
throw new Error(`Unknown operation: ${operation}`);
|
||
|
|
}
|
||
|
|
return {
|
||
|
|
result,
|
||
|
|
operation: `${a} ${operation} ${b}`,
|
||
|
|
};
|
||
|
|
},
|
||
|
|
});
|