Class: Agents::GptResponse

Inherits:
Response show all
Defined in:
lib/responses/gpt_response.rb

Overview

The response from a GPT request.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw_text) ⇒ GptResponse

Returns a new instance of GptResponse.

Parameters:

  • raw_text (String)

    The raw text the GPT service returned.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/responses/gpt_response.rb', line 12

def initialize(raw_text)
  @raw_text = raw_text

  begin
    @data = extract_json_data(raw_text)
    @response_text   = data["response"] || raw_text
    @suggested_actions = data["actions"] || []
  rescue
    @data = {}
    @response_text   = raw_text
    @suggested_actions = []
  end
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



8
9
10
# File 'lib/responses/gpt_response.rb', line 8

def data
  @data
end

#raw_textObject (readonly)

Returns the value of attribute raw_text.



5
6
7
# File 'lib/responses/gpt_response.rb', line 5

def raw_text
  @raw_text
end

#response_textObject (readonly)

Returns the value of attribute response_text.



6
7
8
# File 'lib/responses/gpt_response.rb', line 6

def response_text
  @response_text
end

#suggested_actionsObject (readonly)

Returns the value of attribute suggested_actions.



7
8
9
# File 'lib/responses/gpt_response.rb', line 7

def suggested_actions
  @suggested_actions
end

Instance Method Details

#extract_json_data(string) ⇒ Object

TODO: Extract this into an object:



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/responses/gpt_response.rb', line 27

def extract_json_data(string)
  # Check if the string is valid JSON.
  begin
    json_obj = JSON.parse(string)
    return json_obj
  rescue JSON::ParserError => error
    Agents.logger.info "Whole string was not pure JSON. #{error}"
  end

  # Search for JSON using regular expression
  match_data = string.match(/\{.*\}/m)
  if match_data
    begin
      Agents.logger.info "Found some JSON in the string."

      json_obj = JSON.parse(match_data[0])
      return json_obj
    rescue JSON::ParserError
      Agents.logger.info "Extracted string was not pure JSON. #{error}"
    end
  end
end