47 lines
1.4 KiB
JavaScript
47 lines
1.4 KiB
JavaScript
import { Parser } from "expr-eval";
|
|
import { Tool } from "@langchain/core/tools";
|
|
/**
|
|
* The Calculator class is a tool used to evaluate mathematical
|
|
* expressions. It extends the base Tool class.
|
|
* @example
|
|
* ```typescript
|
|
* import { Calculator } from "@langchain/community/tools/calculator";
|
|
*
|
|
* const calculator = new Calculator();
|
|
* const sum = await calculator.invoke("99 + 99");
|
|
* console.log("The sum of 99 and 99 is:", sum);
|
|
* // The sum of 99 and 99 is: 198
|
|
* ```
|
|
*/
|
|
export class Calculator extends Tool {
|
|
constructor() {
|
|
super(...arguments);
|
|
Object.defineProperty(this, "name", {
|
|
enumerable: true,
|
|
configurable: true,
|
|
writable: true,
|
|
value: "calculator"
|
|
});
|
|
Object.defineProperty(this, "description", {
|
|
enumerable: true,
|
|
configurable: true,
|
|
writable: true,
|
|
value: `Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.`
|
|
});
|
|
}
|
|
static lc_name() {
|
|
return "Calculator";
|
|
}
|
|
get lc_namespace() {
|
|
return [...super.lc_namespace, "calculator"];
|
|
}
|
|
/** @ignore */
|
|
async _call(input) {
|
|
try {
|
|
return Parser.evaluate(input).toString();
|
|
}
|
|
catch (error) {
|
|
return "I don't know how to do that.";
|
|
}
|
|
}
|
|
}
|