Created
June 28, 2023 07:43
-
-
Save kaiwren/50d914ccb2aecb1430dfd3c82a0bbf57 to your computer and use it in GitHub Desktop.
Open AI API Access in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# gem 'wrest' in Gemfile | |
# optionally, `Wrest.logger = Rails.logger` in `config/initializers/wrest.rb` | |
module OpenAI | |
def self.base_uri | |
'https://api.openai.com/v1'.to_uri( | |
default_headers: { | |
'Content-Type' => 'application/json', | |
'Authorization' => "Bearer #{ENV.fetch('OPENAI_KEY', nil)}" | |
} | |
) | |
end | |
class Client | |
PATH = '/chat/completions'.freeze | |
def initialize(model = 'gpt-3.5-turbo') | |
@uri = OpenAI.base_uri[PATH] | |
@model = model | |
end | |
# messages = [{ role: 'user', content: 'Say this is a test!' }] | |
# https://platform.openai.com/docs/api-reference/chat/create | |
def chat_completions_create(messages, temperature = 0.8) | |
@uri.post( | |
{ | |
model: @model, | |
messages: messages, | |
temperature: temperature | |
}.to_json | |
).deserialise | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment