Class: RubyLLM::Toolbox::Tools::Calculator

Inherits:
Base
  • Object
show all
Defined in:
lib/ruby_llm/toolbox/tools/calculator.rb

Overview

SAFE. Evaluates an arithmetic expression without eval, so it can’t execute code. Supports + - * / % **, parentheses, unary minus, the functions sqrt/abs/sin/cos/tan/ln/log10/exp/floor/ceil/round, and the constants pi and e.

Instance Attribute Summary

Attributes inherited from Base

#config

Instance Method Summary collapse

Methods inherited from Base

#call, exec_tool!, exec_tool?, #initialize, #name

Constructor Details

This class inherits a constructor from RubyLLM::Toolbox::Base

Instance Method Details

#execute(expression:) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/ruby_llm/toolbox/tools/calculator.rb', line 22

def execute(expression:)
  return error("expression must not be empty", code: :empty) if expression.to_s.strip.empty?

  value = SafeMath.evaluate(expression)
  "#{expression.strip} = #{format_number(value)}"
rescue SafeMath::Error => e
  error(e.message, code: :bad_expression)
end