Class: OllamaAgent::Tools::SafeCalculator
- Defined in:
- lib/ollama_agent/tools/safe_calculator.rb
Overview
Safe arithmetic evaluator using the Shunting-yard algorithm.
Supports +, -, *, /, ** and parentheses on numeric literals. Does NOT use eval ā the expression is parsed into tokens, converted to reverse-Polish notation, and evaluated on a stack.
Constant Summary collapse
- OPERATORS =
Operator table: precedence, associativity, arity. Unary +/- are prefixed with āuā to distinguish from binary operators.
{ "+" => { precedence: 1, assoc: :left, arity: 2 }, "-" => { precedence: 1, assoc: :left, arity: 2 }, "*" => { precedence: 2, assoc: :left, arity: 2 }, "/" => { precedence: 2, assoc: :left, arity: 2 }, "**" => { precedence: 3, assoc: :right, arity: 2 }, "u+" => { precedence: 4, assoc: :right, arity: 1 }, "u-" => { precedence: 4, assoc: :right, arity: 1 } }.freeze
Constants inherited from Base
Instance Attribute Summary
Attributes inherited from Base
#description, #input_schema, #name, #output_schema, #requires_approval, #risk_level
Instance Method Summary collapse
Methods inherited from Base
#initialize, #to_anthropic_schema, #to_ollama_schema, #to_s, tool_description, tool_name, tool_output_schema, tool_requires_approval, tool_risk, tool_schema
Constructor Details
This class inherits a constructor from OllamaAgent::Tools::Base
Instance Method Details
#call(args, context: {}) ⇒ Object
42 43 44 45 46 47 48 49 50 |
# File 'lib/ollama_agent/tools/safe_calculator.rb', line 42 def call(args, context: {}) expression = args["expression"].to_s tokens = tokenize(expression) rpn = to_rpn(tokens) value = eval_rpn(rpn) value.finite? ? value.to_s : "Error: result is non-finite (division by zero?)" rescue StandardError => e "Error: #{e.}" end |