1. add the gem to the Gemfile
# Gemfile
gem "ruby-openai"
gem "dotenv-rails" # if you don't have it already

Then bundle install

  1. create a .env file if it doesn't exist (in Terminal)
touch .env
  1. Add you secret access_token from OpenAI and to the .env
OPENAI_ACCESS_TOKEN=*****
  1. create an initializer for the gem
touch config/initializers/openai.rb
  1. config the gem to your secret keys (in your openai.rb)
OpenAI.configure do |config|
  config.access_token = ENV.fetch("OPENAI_ACCESS_TOKEN")
  config.request_timeout = 240 # Optional
end
  1. create a services folder in your app (in Terminal)
mkdir app/services
  1. create a service object for Open AI (in Terminal)
touch app/services/openai_service.rb
  1. Restart your server rails restart
  2. setup the service object class
# app/services/openai_service.rb
require "openai"

class OpenaiService
  attr_reader :client, :prompt 

  def initialize(prompt)
    @client = OpenAI::Client.new
    @prompt = prompt
  end

  def call
    response = client.chat(
      parameters: {
          model: "gpt-3.5-turbo", # Required.
          messages: [{ role: "user", content: prompt }], # Required.
          temperature: 0.7,
          stream: false,
					max_tokens: 100 # might want to check this
      })
    # you might want to inspect the response and see what the api is giving you
    return response["choices"][0]["message"]["content"]
  end
end
  1. Now this service object is usable anywhere in your app. Most likely you’ll use it in one of your controllers like: