Module: Raif::Concerns::LlmResponseParsing

Extended by:
ActiveSupport::Concern
Included in:
Raif::Conversation, ModelCompletion, Task
Defined in:
app/models/raif/concerns/llm_response_parsing.rb

Instance Method Summary collapse

Instance Method Details

#clean_html_fragment(html) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'app/models/raif/concerns/llm_response_parsing.rb', line 52

def clean_html_fragment(html)
  fragment = Nokogiri::HTML.fragment(html)

  fragment.traverse do |node|
    if node.text? && node.text.strip.empty?
      node.remove
    end
  end

  allowed_tags = self.class.allowed_tags || Rails::HTML5::SafeListSanitizer.allowed_tags
  allowed_attributes = self.class.allowed_attributes || Rails::HTML5::SafeListSanitizer.allowed_attributes

  ActionController::Base.helpers.sanitize(fragment.to_html, tags: allowed_tags, attributes: allowed_attributes).strip
end

#parsed_responseObject

Parses the response from the LLM into a structured format, based on the response_format. If the response format is JSON, it will be parsed using JSON.parse. If the response format is HTML, it will be sanitized via ActionController::Base.helpers.sanitize.

Returns:

  • (Object)

    The parsed response.



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'app/models/raif/concerns/llm_response_parsing.rb', line 38

def parsed_response
  return if raw_response.blank?

  @parsed_response ||= if response_format_json?
    json = raw_response.gsub("```json", "").gsub("```", "")
    JSON.parse(json)
  elsif response_format_html?
    html = raw_response.strip.gsub("```html", "").chomp("```")
    clean_html_fragment(html)
  else
    raw_response.strip
  end
end