Class: GPT::Client

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

Constant Summary collapse

DEFAULT_BASE_URL =
'https://api.openai.com'.freeze
DEFAULT_TIMEOUT =
120

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key: ENV['OPENAI_API_KEY'] || ENV['OPENAI_ACCESS_TOKEN'], base_url: nil, timeout: nil, organization: ENV['OPENAI_ORG_ID'] || ENV['OPENAI_ORGANIZATION_ID'], project: ENV['OPENAI_PROJECT_ID']) ⇒ Client

Returns a new instance of Client.



8
9
10
11
12
13
14
# File 'lib/gpt/client.rb', line 8

def initialize(api_key: ENV['OPENAI_API_KEY'] || ENV['OPENAI_ACCESS_TOKEN'], base_url: nil, timeout: nil, organization: ENV['OPENAI_ORG_ID'] || ENV['OPENAI_ORGANIZATION_ID'], project: ENV['OPENAI_PROJECT_ID'])
  @api_key = api_key
  @base_url = base_url || DEFAULT_BASE_URL
  @timeout = (timeout || ENV['OPENAI_REQUEST_TIMEOUT'] || DEFAULT_TIMEOUT).to_i
  @organization = organization
  @project = project
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



6
7
8
# File 'lib/gpt/client.rb', line 6

def api_key
  @api_key
end

#base_urlObject (readonly)

Returns the value of attribute base_url.



6
7
8
# File 'lib/gpt/client.rb', line 6

def base_url
  @base_url
end

#organizationObject (readonly)

Returns the value of attribute organization.



6
7
8
# File 'lib/gpt/client.rb', line 6

def organization
  @organization
end

#projectObject (readonly)

Returns the value of attribute project.



6
7
8
# File 'lib/gpt/client.rb', line 6

def project
  @project
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



6
7
8
# File 'lib/gpt/client.rb', line 6

def timeout
  @timeout
end

Instance Method Details

#json_delete(path) ⇒ Object



24
25
26
# File 'lib/gpt/client.rb', line 24

def json_delete(path)
  request(:delete, path)
end

#json_get(path, query: nil) ⇒ Object



16
17
18
# File 'lib/gpt/client.rb', line 16

def json_get(path, query: nil)
  request(:get, path, query: query)
end

#json_post(path, body: nil) ⇒ Object



20
21
22
# File 'lib/gpt/client.rb', line 20

def json_post(path, body: nil)
  request(:post, path, body: body)
end

#sse_stream(path, body: nil, query: nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/gpt/client.rb', line 28

def sse_stream(path, body: nil, query: nil)
  uri = build_uri(path, query: query)
  http = build_http(uri)
  req = Net::HTTP::Post.new(uri)
  apply_headers(req)
  req['Accept'] = 'text/event-stream'
  req.content_type = 'application/json'
  req.body = body ? Oj.dump(body) : nil

  http.request(req) do |res|
    raise_http_error(res) unless res.is_a?(Net::HTTPSuccess)
    res.read_body do |chunk|
      yield chunk if block_given?
    end
  end
  true
end