Module: Pikuri::Tool::Calculator

Defined in:
lib/pikuri/tool/calculator.rb

Overview

Evaluates a basic arithmetic expression using Dentaku, with light preprocessing so the LLM can emit Python-flavored syntax (notably ** for exponentiation) instead of learning Dentaku’s dialect.

Scope is intentionally narrow: operators (+, -, *, /, **, %), parentheses, and decimal numbers. No variables, functions, or booleans — those would mean teaching the model a dialect, which we specifically want to avoid for this tool.

Class Method Summary collapse

Class Method Details

.calculate(expression) ⇒ String

Evaluate expression and return the result formatted as a String. Parse, unbound-variable, and division-by-zero failures are caught and returned as “Error: …” strings so the model can read the failure as the next observation and self-correct rather than crashing the agent loop.

Parameters:

  • expression (String)

Returns:

  • (String)

    numeric result, or “Error: …” on failure



34
35
36
37
38
39
40
41
# File 'lib/pikuri/tool/calculator.rb', line 34

def self.calculate(expression)
  result = Dentaku::Calculator.new.evaluate!(normalize(expression))
  format_result(result)
rescue Dentaku::ZeroDivisionError, ZeroDivisionError
  'Error: division by zero'
rescue Dentaku::Error => e
  "Error: #{e.message}"
end

.normalize(expression) ⇒ String

Translate the operator differences between Python and Dentaku. In practice that is only **^; everything else in the supported subset is byte-identical.

Parameters:

  • expression (String)

    raw expression as the model wrote it

Returns:

  • (String)

    expression with Python-style operators rewritten



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

def self.normalize(expression)
  expression.gsub('**', '^')
end