@jackhua/mini-langchain
Version:
A lightweight TypeScript implementation of LangChain with cost optimization features
79 lines • 3.08 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdvancedCalculatorTool = exports.CalculatorTool = void 0;
const base_1 = require("./base");
/**
* Calculator tool for mathematical operations
*/
class CalculatorTool extends base_1.BaseTool {
constructor() {
super(...arguments);
this.name = 'calculator';
this.description = 'Useful for performing mathematical calculations. Input should be a mathematical expression.';
}
async execute(input) {
try {
// Remove any non-mathematical characters for safety
const sanitized = input.replace(/[^0-9+\-*/().\s]/g, '');
// Use Function constructor instead of eval for better safety
// This still has risks but is better than raw eval
const result = new Function('return ' + sanitized)();
if (isNaN(result) || !isFinite(result)) {
throw new Error('Invalid calculation result');
}
return String(result);
}
catch (error) {
throw new Error(`Calculation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
exports.CalculatorTool = CalculatorTool;
/**
* Advanced calculator with more operations
*/
class AdvancedCalculatorTool extends base_1.BaseTool {
constructor() {
super(...arguments);
this.name = 'advanced_calculator';
this.description = 'Advanced calculator supporting sqrt, pow, sin, cos, tan, log, etc. Input format: "operation(value)" or "value1 operation value2"';
this.mathFunctions = {
sqrt: Math.sqrt,
pow: Math.pow,
sin: Math.sin,
cos: Math.cos,
tan: Math.tan,
log: Math.log,
log10: Math.log10,
exp: Math.exp,
abs: Math.abs,
floor: Math.floor,
ceil: Math.ceil,
round: Math.round,
pi: Math.PI,
e: Math.E
};
}
async execute(input) {
try {
let expression = input.toLowerCase().trim();
// Replace math functions with Math.function
Object.entries(this.mathFunctions).forEach(([func, impl]) => {
const regex = new RegExp(`\\b${func}\\b`, 'g');
expression = expression.replace(regex, `this.mathFunctions.${func}`);
});
// Create a function with math functions in scope
const compute = new Function('mathFunctions', `return ${expression}`);
const result = compute.call(this, this.mathFunctions);
if (isNaN(result) || !isFinite(result)) {
throw new Error('Invalid calculation result');
}
return String(result);
}
catch (error) {
throw new Error(`Advanced calculation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
}
exports.AdvancedCalculatorTool = AdvancedCalculatorTool;
//# sourceMappingURL=calculator.js.map