# Gemfile
gem "ruby-openai"
gem "dotenv-rails" # if you don't have it already
Then bundle install
touch .env
OPENAI_ACCESS_TOKEN=*****
touch config/initializers/openai.rb
OpenAI.configure do |config|
config.access_token = ENV.fetch("OPENAI_ACCESS_TOKEN")
config.request_timeout = 240 # Optional
end
mkdir app/services
touch app/services/openai_service.rb
rails restart
# 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