Class: Typesafe::ChoiceAnswer

Inherits:
Answer
  • Object
show all
Defined in:
lib/typesafe/choice_answer.rb

Overview

The answer to a Choice question: the selected option, the probability distribution across every option, and a confidence between 0 and 1.

Typesafe::ChoiceAnswer.new(
choice: "billing",
probabilities: { "billing" => 0.88, "technical" => 0.12, "sales" => 0.0 },
confidence: 0.81
)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Answer

#==, #hash, #to_json

Constructor Details

#initialize(choice:, probabilities:, confidence:) ⇒ ChoiceAnswer

Returns a new instance of ChoiceAnswer.

Parameters:

  • choice (String)

    the selected option.

  • probabilities (Hash)

    option keys (String or Symbol) mapped to probabilities in 0..1; the values must sum to 1.

  • confidence (Numeric)

    the model's confidence, between 0 and 1.

Raises:

  • (ArgumentError)

    if any attribute is invalid.



27
28
29
30
31
32
# File 'lib/typesafe/choice_answer.rb', line 27

def initialize(choice:, probabilities:, confidence:)
  @choice = validate_string(choice, "choice")
  @probabilities = normalize_probabilities(probabilities)
  @confidence = validate_probability(confidence, "confidence")
  freeze
end

Instance Attribute Details

#choiceString (readonly)

Returns the highest-probability option.

Returns:

  • (String)

    the highest-probability option.



14
15
16
# File 'lib/typesafe/choice_answer.rb', line 14

def choice
  @choice
end

#confidenceNumeric (readonly)

Returns how certain the model is, between 0 and 1.

Returns:

  • (Numeric)

    how certain the model is, between 0 and 1.



20
21
22
# File 'lib/typesafe/choice_answer.rb', line 20

def confidence
  @confidence
end

#probabilitiesHash (readonly)

Returns every option mapped to its probability.

Returns:

  • (Hash)

    every option mapped to its probability.



17
18
19
# File 'lib/typesafe/choice_answer.rb', line 17

def probabilities
  @probabilities
end

Class Method Details

.from_h(hash) ⇒ ChoiceAnswer

Parameters:

  • hash (Hash)

    a choice answer entry from the API response, with String or Symbol keys.

Returns:



37
38
39
40
41
42
43
# File 'lib/typesafe/choice_answer.rb', line 37

def self.from_h(hash)
  new(
    choice: hash["choice"] || hash[:choice],
    probabilities: hash["probabilities"] || hash[:probabilities],
    confidence: hash["confidence"] || hash[:confidence]
  )
end

Instance Method Details

#to_hObject



49
50
51
# File 'lib/typesafe/choice_answer.rb', line 49

def to_h
  { type: type, choice: choice, probabilities: probabilities, confidence: confidence }
end

#typeObject



45
46
47
# File 'lib/typesafe/choice_answer.rb', line 45

def type
  "choice"
end