Module: Legion::LLM::Tools::Interceptors::PythonVenv

Defined in:
lib/legion/llm/tools/interceptors/python_venv.rb

Constant Summary collapse

VENV_DIR =
(ENV['LEGION_PYTHON_VENV'] || File.expand_path('~/.legionio/python')).freeze
PYTHON =
"#{VENV_DIR}/bin/python3".freeze
PIP =
"#{VENV_DIR}/bin/pip3".freeze
TOOL_PATTERN =
/\A(python3?|pip3?)\z/i

Class Method Summary collapse

Class Method Details

.match?(tool_name) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
# File 'lib/legion/llm/tools/interceptors/python_venv.rb', line 22

def match?(tool_name)
  TOOL_PATTERN.match?(tool_name.to_s)
end

.register!Object



16
17
18
19
20
# File 'lib/legion/llm/tools/interceptors/python_venv.rb', line 16

def register!
  Interceptor.register(:python_venv, matcher: method(:match?)) do |_tool_name, **args|
    rewrite(**args)
  end
end

.rewrite(**args) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/legion/llm/tools/interceptors/python_venv.rb', line 30

def rewrite(**args)
  return args unless venv_available?

  command = args[:command]
  return args unless command.is_a?(String)

  args.merge(command: rewrite_command(command))
end

.rewrite_command(command) ⇒ Object



39
40
41
42
43
# File 'lib/legion/llm/tools/interceptors/python_venv.rb', line 39

def rewrite_command(command)
  command
    .sub(/\Apython3(\s|\z)/, "#{PYTHON}\\1")
    .sub(/\Apip3(\s|\z)/,    "#{PIP}\\1")
end

.venv_available?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/legion/llm/tools/interceptors/python_venv.rb', line 26

def venv_available?
  File.exist?("#{VENV_DIR}/pyvenv.cfg")
end