Class: IprogChatgpt::Client

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

Constant Summary collapse

API_ENDPOINT =
"https://api.openai.com/v1/chat/completions"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, model = "gpt-3.5-turbo") ⇒ Client

Returns a new instance of Client.



11
12
13
14
# File 'lib/iprog_chatgpt/client.rb', line 11

def initialize(api_key, model = "gpt-3.5-turbo")
  @api_key = api_key
  @model   = model
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



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

def api_key
  @api_key
end

#modelObject (readonly)

Returns the value of attribute model.



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

def model
  @model
end

Instance Method Details

#chat(prompt) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/iprog_chatgpt/client.rb', line 16

def chat(prompt)
  uri = URI(API_ENDPOINT)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri.path, { 'Content-Type' => 'application/json', 'Authorization' => "Bearer #{api_key}" })
  request.body = { model: model, messages: [{ role: "user", content: prompt }] }.to_json

  response = http.request(request)
  
  JSON.parse(response.body)
end