Class: Providers::OpenAI

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

Instance Method Summary collapse

Constructor Details

#initializeOpenAI

Returns a new instance of OpenAI.



8
9
10
11
12
13
14
15
16
# File 'lib/providers/openai.rb', line 8

def initialize
  @connection = Faraday.new(url: "https://api.openai.com") do |faraday|
    faraday.request :json
    faraday.response :json
    faraday.adapter Faraday.default_adapter
  end

  @api_key = Zuno.configuration.openai_api_key
end

Instance Method Details

#chat_completion(messages, model, options = {}, raw_response) ⇒ Object



18
19
20
21
22
23
24
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
55
56
# File 'lib/providers/openai.rb', line 18

def chat_completion(messages, model, options = {}, raw_response)
  response = @connection.post("/v1/chat/completions") do |req|
    req.headers["Content-Type"] = "application/json"
    req.headers["Authorization"] = "Bearer #{@api_key}"
    req.body = {
      model: model,
      messages: messages,
    }.merge(options).to_json

    if options[:stream]
      parser = EventStreamParser::Parser.new
      req.options.on_data = Proc.new do |chunk, size|
        if raw_response
          yield chunk
        else
          parser.feed(chunk) do |type, data, id, reconnection_time|
            return if data == "[DONE]"
            content = JSON.parse(data)["choices"][0]["delta"]["content"]
            yield OpenStruct.new(content: content) if content
          end
        end
      end
    end
  end

  unless options[:stream]
    if raw_response
      return response.body
    else
      if response.body["error"]
        raise response.body["error"]["message"]
      elsif response.body["choices"][0]["message"]["content"]
        OpenStruct.new(content: response.body["choices"][0]["message"]["content"])
      elsif response.body["choices"][0]["message"]["tool_calls"]
        OpenStruct.new(tool_calls: response.body["choices"][0]["message"]["tool_calls"])
      end
    end
  end
end