Use ChatGPT API with Ruby on Rails

Khaled Elabady
2 min readApr 17, 2023

Integrate ChatGPT API into your Ruby on Rails application.

ChatGPT => is a conversational AI model developed by OpenAI that generates human-like responses to text inputs .

Using ChatGPT API with Ruby on Rails can be done through sending HTTP requests to the API endpoint.

1 . Install the ‘httparty’ gem

gem 'httparty'
bundle install

2. Save the API Key to Rails credentials

You will save it to the Rails credentials file , to keep the API key secure .

EDITOR="nano" bin/rails credentials:edit

add the following line to the file

chatgpt_api_key: your-api-key-here

3. Create a ChatGPT service

Create a service chatgpt_service.rb in the app/services directory of your Rails application and add the following code:

class ChatgptService
include HTTParty

attr_reader :api_url, :options, :model, :message

def initialize(message, model = 'gpt-3.5-turbo')
api_key = Rails.application.credentials.chatgpt_api_key
@options = {
headers: {
'Content-Type' => 'application/json',
'Authorization' => "Bearer #{chatgpt_api_key}"
}
}
@api_url = 'https://api.openai.com/v1/chat/completions'
@model = model
@message = message
end

def call
body = {
model:,
messages: [{ role: 'user', content: message }]
}
response = HTTParty.post(api_url, body: body.to_json, headers: options[:headers], timeout: 10)
raise response['error']['message'] unless response.code == 200

response['choices'][0]['message']['content']
end

class << self
def call(message, model = 'gpt-3.5-turbo')
new(message, model).call
end
end
end

The HTTParty gem to send a POST request to the ChatGPT API with a prompt, model, and other parameters. It then parses the response and returns the text of the first choice.

4. Calling the service

ChatgptService.call('What is your name?')

# => "I am an AI language model created by OpenAI, so I don't have a name. You can call me OpenAI or AI assistant."

You can then render the response in your view.

--

--