Class: Lluminary::Providers::OpenAI

Inherits:
Base
  • Object
show all
Defined in:
lib/lluminary/providers/openai.rb

Overview

Provider for OpenAI’s GPT models. Implements the Base provider interface for OpenAI’s API.

Constant Summary collapse

NAME =
:openai
DEFAULT_MODEL =
Models::OpenAi::Gpt35Turbo

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**config_overrides) ⇒ OpenAI

Returns a new instance of OpenAI.



16
17
18
19
20
# File 'lib/lluminary/providers/openai.rb', line 16

def initialize(**config_overrides)
  super
  @config = { model: DEFAULT_MODEL }.merge(config)
  @client = ::OpenAI::Client.new(access_token: config[:api_key])
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



14
15
16
# File 'lib/lluminary/providers/openai.rb', line 14

def client
  @client
end

#configObject (readonly)

Returns the value of attribute config.



14
15
16
# File 'lib/lluminary/providers/openai.rb', line 14

def config
  @config
end

Instance Method Details

#call(prompt, _task) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/lluminary/providers/openai.rb', line 22

def call(prompt, _task)
  response =
    client.chat(
      parameters: {
        model: model.class::NAME,
        messages: [{ role: "user", content: prompt }],
        response_format: {
          type: "json_object"
        }
      }
    )

  content = response.dig("choices", 0, "message", "content")

  {
    raw: content,
    parsed:
      begin
        JSON.parse(content) if content
      rescue JSON::ParserError
        nil
      end
  }
end

#modelObject



47
48
49
# File 'lib/lluminary/providers/openai.rb', line 47

def model
  @model ||= config[:model].new
end

#modelsObject



51
52
53
54
# File 'lib/lluminary/providers/openai.rb', line 51

def models
  response = @client.models.list
  response["data"].map { |model| model["id"] }
end