Class: CompletionKit::CsvProcessor

Inherits:
Object
  • Object
show all
Defined in:
app/services/completion_kit/csv_processor.rb

Class Method Summary collapse

Class Method Details

.apply_variables(prompt, variables) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'app/services/completion_kit/csv_processor.rb', line 55

def self.apply_variables(prompt, variables)
  result = prompt.template.dup

  variables.each do |name, value|
    result.gsub!(/\{\{\s*#{Regexp.escape(name.to_s)}\s*\}\}/, value.to_s)
  end

  result
end

.extract_variables(prompt) ⇒ Object



37
38
39
40
41
# File 'app/services/completion_kit/csv_processor.rb', line 37

def self.extract_variables(prompt)
  return [] if prompt.nil? || prompt.template.blank?

  prompt.template.scan(/\{\{([^}]+)\}\}/).flatten.map(&:strip).uniq
end

.process(run) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'app/services/completion_kit/csv_processor.rb', line 5

def self.process(run)
  return [] if run.csv_data.blank?

  begin
    csv_data = CSV.parse(run.csv_data, headers: true)
    rows = csv_data.map(&:to_h)

    if rows.empty?
      run.errors.add(:csv_data, "No data rows found in CSV")
      return []
    end

    return [] unless validate_variables(run, rows.first.keys)

    rows
  rescue CSV::MalformedCSVError => e
    run.errors.add(:csv_data, "Invalid CSV format: #{e.message}")
    []
  end
end

.process_self(run) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'app/services/completion_kit/csv_processor.rb', line 26

def self.process_self(run)
  return [] unless run.dataset&.csv_data.present?

  begin
    csv_data = CSV.parse(run.dataset.csv_data, headers: true)
    csv_data.map(&:to_h)
  rescue CSV::MalformedCSVError
    []
  end
end

.validate_variables(run, headers) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'app/services/completion_kit/csv_processor.rb', line 43

def self.validate_variables(run, headers)
  prompt_variables = extract_variables(run.prompt)
  missing_variables = prompt_variables - headers

  if missing_variables.any?
    run.errors.add(:csv_data, "Missing required variables in CSV: #{missing_variables.join(', ')}")
    return false
  end

  true
end