Class: Luogu::PromptParser

Inherits:
Object
  • Object
show all
Defined in:
lib/luogu/prompt_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_path) ⇒ PromptParser

Returns a new instance of PromptParser.



4
5
6
7
8
9
# File 'lib/luogu/prompt_parser.rb', line 4

def initialize(file_path)
  @file_path = file_path
  @messages = []
  @ruby_code = nil
  @ruby_code_line = nil
end

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



3
4
5
# File 'lib/luogu/prompt_parser.rb', line 3

def file_path
  @file_path
end

#messagesObject (readonly)

Returns the value of attribute messages.



3
4
5
# File 'lib/luogu/prompt_parser.rb', line 3

def messages
  @messages
end

#ruby_codeObject (readonly)

Returns the value of attribute ruby_code.



3
4
5
# File 'lib/luogu/prompt_parser.rb', line 3

def ruby_code
  @ruby_code
end

#ruby_code_lineObject (readonly)

Returns the value of attribute ruby_code_line.



3
4
5
# File 'lib/luogu/prompt_parser.rb', line 3

def ruby_code_line
  @ruby_code_line
end

Instance Method Details

#find_line_number(text, search_str) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/luogu/prompt_parser.rb', line 44

def find_line_number(text, search_str)
  lines = text.split("\n")
  line_number = nil

  lines.each_with_index do |line, index|
    if line.include?(search_str)
      line_number = index + 1
      break
    end
  end

  line_number
end

#process_fileObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/luogu/prompt_parser.rb', line 20

def process_file
  @messages = [] 
  file = File.read(@file_path)

  if file =~ /@callback/
    callback_regex = /@callback\n```ruby\n(.*?)\n```/m
    @ruby_code = file[callback_regex, 1]
    @ruby_code_line = self.find_line_number(file, "@callback") + 2
    file = file.gsub(callback_regex, '')
  end

  file.split(/(?=@u|@a|@s)/).reject(&:empty?).each do |c|
    role = if c =~ /^@s/
      "system"
    elsif c =~ /^@u/
      "user"
    elsif c =~ /^@a/
      "assistant"
    end
    content = c.sub(/^@(u|a|s)\s+/, '').strip
    @messages << {role: role, content: content}
  end
end

#renderObject



11
12
13
14
# File 'lib/luogu/prompt_parser.rb', line 11

def render
  process_file if @messages.size == 0
  @messages
end

#to_jsonObject



16
17
18
# File 'lib/luogu/prompt_parser.rb', line 16

def to_json
  JSON.pretty_generate self.render
end