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: "执行基本算术运算",
|
|
inputSchema: z.object({
|
|
operation: z.enum(["add", "subtract", "multiply", "divide"]).describe("要执行的算术运算"),
|
|
a: z.number().describe("第一个数字"),
|
|
b: z.number().describe("第二个数字"),
|
|
}),
|
|
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}`,
|
|
};
|
|
},
|
|
}); |