Class: NitroIntelligence::Client::Handlers::TextToSpeechHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/nitro_intelligence/client/handlers/text_to_speech_handler.rb

Constant Summary collapse

ALLOWED_EXTRA_PARAMETERS =
OpenAI::Models::Audio::SpeechCreateParams.fields.keys.uniq.freeze

Instance Method Summary collapse

Constructor Details

#initialize(client:) ⇒ TextToSpeechHandler

Returns a new instance of TextToSpeechHandler.



9
10
11
# File 'lib/nitro_intelligence/client/handlers/text_to_speech_handler.rb', line 9

def initialize(client:)
  @client = client
end

Instance Method Details

#create(message: "", parameters: {}) ⇒ Object



13
14
15
16
# File 'lib/nitro_intelligence/client/handlers/text_to_speech_handler.rb', line 13

def create(message: "", parameters: {})
  validate_and_resolve!(parameters)
  perform_request(message:, parameters:)
end

#perform_request(message: "", parameters: {}) ⇒ Object



18
19
20
21
22
23
# File 'lib/nitro_intelligence/client/handlers/text_to_speech_handler.rb', line 18

def perform_request(message: "", parameters: {})
  @client.audio.speech.create(
    input: message,
    **parameters.slice(*ALLOWED_EXTRA_PARAMETERS)
  )
end

#validate_and_resolve!(parameters) ⇒ Object

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/nitro_intelligence/client/handlers/text_to_speech_handler.rb', line 25

def validate_and_resolve!(parameters)
  model_name = parameters[:model] || NitroIntelligence.model_catalog.default_text_to_speech_model&.name
  model = NitroIntelligence.model_catalog.lookup_by_name(model_name)

  # Check model supported
  raise ArgumentError, "Unsupported model: '#{model_name}'" unless model

  default_parameters = {
    metadata: {},
    model: model.name,
    voice: model.default_voice,
    response_format: model.default_response_format,
  }

  parameters.replace(default_parameters.merge(parameters))

  # Check voice supported
  unless model.voices.include?(parameters[:voice])
    raise ArgumentError,
          "Unsupported voice: '#{parameters[:voice]}'. " \
          "Supported voices for #{model.name} are: #{model.voices}"
  end

  # Check format supported
  return if model.response_formats.include?(parameters[:response_format])

  raise ArgumentError,
        "Unsupported response_format: '#{parameters[:response_format]}'. " \
        "Supported response_formats for #{model.name} are: #{model.response_formats}"
end