Class: Rubygpt::Response::ChatCompletion

Inherits:
BaseResponse show all
Defined in:
lib/rubygpt/response/chat_completion.rb

Overview

Represents the ChatCompletion response from the Chat API platform.openai.com/docs/api-reference/chat/object

Defined Under Namespace

Classes: Choice

Instance Attribute Summary

Attributes inherited from BaseResponse

#api_response

Instance Method Summary collapse

Constructor Details

#initialize(api_response) ⇒ ChatCompletion

Initializes the ChatCompletion object

Parameters:

  • api_response (StandardApiResponse)

    The response from the API, standardized by the connection object



54
55
56
57
# File 'lib/rubygpt/response/chat_completion.rb', line 54

def initialize(api_response)
  super
  @choices = @choices.map { |choice| Choice.new(**choice.transform_keys(&:to_sym)) }.sort_by(&:index) if @choices
end

Instance Method Details

#costObject



75
76
77
# File 'lib/rubygpt/response/chat_completion.rb', line 75

def cost
  usage["total_tokens"] || usage[:total_tokens]
end

#failed?Boolean

Returns:

  • (Boolean)


71
72
73
# File 'lib/rubygpt/response/chat_completion.rb', line 71

def failed?
  choices.any?(&:failed?)
end

#messagesObject

The list of message strings generated by the model.

return [Array<String>]



62
63
64
# File 'lib/rubygpt/response/chat_completion.rb', line 62

def messages
  @messages ||= choices.map { |choice| choice.message.content }
end

#read(message_separator: "\n") ⇒ Object

Messages combined into a single string, separated by newlines



67
68
69
# File 'lib/rubygpt/response/chat_completion.rb', line 67

def read(message_separator: "\n")
  @read ||= messages.join(message_separator)
end

#to_hObject



79
80
81
# File 'lib/rubygpt/response/chat_completion.rb', line 79

def to_h
  { id:, object:, created:, model:, system_fingerprint:, usage:, choices: choices.map(&:to_h) }.compact
end