Class: SharedTools::Tools::Eval::PythonEvalTool

Inherits:
RubyLLM::Tool
  • Object
show all
Defined in:
lib/shared_tools/tools/eval/python_eval_tool.rb

Overview

Examples:

tool = SharedTools::Tools::Eval::PythonEvalTool.new
tool.execute(code: "print('Hello'); result = 2 + 2")

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger: nil) ⇒ PythonEvalTool

Returns a new instance of PythonEvalTool.

Parameters:

  • logger (Logger) (defaults to: nil)

    optional logger



29
30
31
# File 'lib/shared_tools/tools/eval/python_eval_tool.rb', line 29

def initialize(logger: nil)
  @logger = logger || RubyLLM.logger
end

Class Method Details

.nameObject



11
# File 'lib/shared_tools/tools/eval/python_eval_tool.rb', line 11

def self.name = 'eval_python'

Instance Method Details

#execute(code:) ⇒ Hash

Returns execution result.

Parameters:

  • code (String)

    Python code to execute

Returns:

  • (Hash)

    execution result



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/shared_tools/tools/eval/python_eval_tool.rb', line 36

def execute(code:)
  @logger.info("Requesting permission to execute Python code")

  if code.strip.empty?
    error_msg = "Python code cannot be empty"
    @logger.error(error_msg)
    return { error: error_msg }
  end

  # Show user the code and ask for confirmation
  allowed = SharedTools.execute?(tool: self.class.to_s, stuff: code)

  unless allowed
    @logger.warn("User declined to execute the Python code")
    return { error: "User declined to execute the Python code" }
  end

  @logger.info("Executing Python code")

  begin
    require 'tempfile'
    require 'open3'
    require 'json'

    # Create a Python script that captures both output and result
    python_script = create_python_wrapper(code)

    # Write to temporary file
    temp_file = Tempfile.new(['python_eval', '.py'])
    temp_file.write(python_script)
    temp_file.flush

    # Execute the Python script
    stdout, stderr, status = Open3.capture3("python3", temp_file.path)

    temp_file.close
    temp_file.unlink

    if status.success?
      @logger.debug("Python code execution completed successfully")
      parse_python_output(stdout)
    else
      @logger.error("Python code execution failed: #{stderr}")
      {
        error: stderr.strip,
        success: false
      }
    end
  rescue => e
    @logger.error("Failed to execute Python code: #{e.message}")
    {
      error: e.message,
      backtrace: e.backtrace&.first(5),
      success: false
    }
  end
end