Class: LlmRescuer::Tools::ReadSourceCodeTool

Inherits:
RubyLLM::Tool
  • Object
show all
Defined in:
lib/llm_rescuer/tools/read_source_code_tool.rb

Instance Method Summary collapse

Instance Method Details

#execute(file_path:, around_line_number:, context_lines:) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/llm_rescuer/tools/read_source_code_tool.rb', line 10

def execute(file_path:, around_line_number:, context_lines:)
  around_line_number = around_line_number.to_i
  context_lines = context_lines.to_i
  return {error: "Unauthorized file path"} unless file_path.start_with?(LlmRescuer.prefix)

  return {error: "File not found"} unless File.file?(file_path)

  lines = File.readlines(file_path)

  start = [around_line_number - context_lines - 1, 0].max
  end_ = [around_line_number + context_lines - 1, lines.size - 1].min

  snippet = lines[start..end_].each_with_index.map do |src, i|
    num = start + i + 1
    prefix = (num == around_line_number) ? "=> " : "   "
    format("#{prefix}%4d | %s", num, src)
  end

  puts "#{file_path}:#{around_line_number}\n\n"
  puts snippet.join
rescue => e
  {error: e.message}
end