Class: OpenAI::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/openai_ruby/client.rb

Constant Summary collapse

BASE_URL =
"https://api.openai.com"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, options = {}) ⇒ Client

Returns a new instance of Client.



9
10
11
12
# File 'lib/openai_ruby/client.rb', line 9

def initialize(api_key, options = {})
  @api_key = api_key
  @options = options
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



7
8
9
# File 'lib/openai_ruby/client.rb', line 7

def api_key
  @api_key
end

#optionsObject (readonly)

Returns the value of attribute options.



7
8
9
# File 'lib/openai_ruby/client.rb', line 7

def options
  @options
end

Instance Method Details

#create_chat_completion(params = {}) ⇒ Object



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

def create_chat_completion(params = {})
  parser = EventStreamParser::Parser.new

  params.deep_stringify_keys!
  if params["stream"]
    connection.post("/v1/chat/completions") do |req|
      req.body = params.to_json
      req.options.on_data = proc do |chunk, overall_received_bytes, env|
        if env && env.status != 200
          raise_error = Faraday::Response::RaiseError.new
          raise_error.on_complete(env.merge(body: try_parse_json(chunk)))
        end

        parser.feed(chunk) do |_type, data|
          yield(JSON.parse(data)) if block_given? && data != "[DONE]"
        end
      end
    end
  else
    connection.post("/v1/chat/completions", params.to_json)
  end
end

#create_completion(params = {}) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/openai_ruby/client.rb', line 14

def create_completion(params = {})
  Faraday.post(
    "#{BASE_URL}/v1/completions",
    params.to_json,
    headers
  )
end

#create_edit(params = {}) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/openai_ruby/client.rb', line 45

def create_edit(params = {})
  Faraday.post(
    "#{BASE_URL}/v1/edits",
    params.to_json,
    headers
  )
end

#imagesObject



53
54
55
# File 'lib/openai_ruby/client.rb', line 53

def images
  @images ||= OpenAI::Images.new(connection)
end