Docs
Calculator Tool

Calculator Tool

LLMs are inefficient while performing arithmetic operations. The Calculator Tool is a simple and efficient tool for performing arithmetic operations.

Installation

Install peer dependencies:

npm i expr-eval

Copy the code

Add the following code to your utils/calculatorTool.ts file:

calculatorTool.ts
import { Parser } from "expr-eval";
 
export class CalculatorTool {
  async evaluate(input: string): Promise<string> {
    try {
      return Parser.evaluate(input).toString();
    } catch (error) {
      console.error("Error calculating expression:", error);
      return "Error Calculating Expression";
    }
  }
 
  async evaluateMultiVar(
    expression: string,
    variables: Record<string, number>
  ): Promise<string> {
    try {
      const substitutedExpression = this.substituteVariables(
        expression,
        variables
      );
      return Parser.evaluate(substitutedExpression).toString();
    } catch (error) {
      console.error("Error evaluating multi-variable expression:", error);
      return "Error evaluating expression";
    }
  }
 
  private substituteVariables(
    expression: string,
    variables: Record<string, number>
  ): string {
    Object.entries(variables).forEach(([variable, value]) => {
      expression = expression.replace(
        new RegExp(variable, "g"),
        value.toString()
      );
    });
    return expression;
  }
}
 
 

Usage

import { CalculatorTool } from "@/utils/calculatorTool";
 
 const calculator = new CalculatorTool();
 
 //for simple expressions
  const simpleExpression = "2 * (3 + 4) - 100 / (99 - 1)";
  const simpleResult = await calculator.evaluate(simpleExpression);
 
  // For complex expressions
  const complexExpression = "2 * (a + b) - 100 / (c - 1)";
  const variables = { a: 3, b: 4, c: 99 };
 
  const complexResult = await calculator.evaluateMultiVar(
    complexExpression,
    variables
  );
  console.log( "Simple Result: ", simpleResult, "Complex Result : ", complexResult);
 
/**
 Simple Result:  12.979591836734693 Complex Result :  12.979591836734693
**/

Props

evaluate

PropTypeDescription
inputstringThe mathematical input string.

evaluateMultiVar

PropTypeDescription
expressionstringThe mathematical input expression.
variablesVariables of the mathematical expression.

Credits

This component is built on top of Langchain's Calculator Tool