Class: Langchain::Tool::Calculator

Inherits:
Object
  • Object
show all
Extended by:
Langchain::ToolDefinition
Includes:
DependencyHelper
Defined in:
lib/langchain/tool/calculator.rb

Overview

A calculator tool that falls back to the Google calculator widget

Gem requirements:

gem "eqn", "~> 1.6.5"
gem "google_search_results", "~> 2.0.0"

Usage:

calculator = Langchain::Tool::Calculator.new

Instance Method Summary collapse

Methods included from Langchain::ToolDefinition

define_function, function_schemas, tool_name

Methods included from DependencyHelper

#depends_on

Constructor Details

#initializeCalculator

Returns a new instance of Calculator.



22
23
24
# File 'lib/langchain/tool/calculator.rb', line 22

def initialize
  depends_on "eqn"
end

Instance Method Details

#execute(input:) ⇒ String

Evaluates a pure math expression or if equation contains non-math characters (e.g.: “12F in Celsius”) then it uses the google search calculator to evaluate the expression

Parameters:

  • input (String)

    math expression

Returns:

  • (String)

    Answer



30
31
32
33
34
35
36
# File 'lib/langchain/tool/calculator.rb', line 30

def execute(input:)
  Langchain.logger.debug("#{self.class} - Executing \"#{input}\"")

  Eqn::Calculator.calc(input)
rescue Eqn::ParseError, Eqn::NoVariableValueError
  "\"#{input}\" is an invalid mathematical expression"
end