Skip to content

Instantly share code, notes, and snippets.

@kaiwren
Created June 28, 2023 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaiwren/50d914ccb2aecb1430dfd3c82a0bbf57 to your computer and use it in GitHub Desktop.
Save kaiwren/50d914ccb2aecb1430dfd3c82a0bbf57 to your computer and use it in GitHub Desktop.
Open AI API Access in Ruby
# 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