ChatGPT With Ruby on Rails

SANJAY
Simform Engineering
3 min readAug 21, 2023

Learn how to integrate ChatGPT into a Ruby on Rails web application.

ChatGPT has quickly become one of the most talked about AI tools, providing human-like conversational abilities. In this post, I’ll demonstrate how to integrate ChatGPT into a Ruby on Rails web application. By leveraging the OpenAI API and Ruby client library, we can easily add advanced natural language features to our apps.

Let’s get started!

Step 1: Initialize a new Rails application.

rails new ChatGPTDemo

Step 2: Install gems.

Next, you must install the OpenAI Ruby gem in your Rails app. To do this, simply add the following line to your Gemfile:

gem ‘openai’
gem ‘httparty’

After adding run:

bundle install

Step 3: Set up your API key

After the bundle install, you’ll need to add an OpenAI API key. For that, go to the OpenAI website and create an account. After successfully signing up, you can find the API key from the URL below:

https://platform.openai.com/account/api-keys

To save the API key, you can use your .env file or credential file. Here, I’ve used credentials.yml.enc file to keep the API key secure.

EDITOR=”nano” bin/rails credentials:edit

It’ll open the nano editor to save your OpenAI API key into the credentials file.

openai_api_key: your-openai-key

After adding the key, just save and close it.

Additionally, you can checkout the rage limit and usage of the API here:

https://platform.openai.com/account/rate-limits
https://platform.openai.com/account/usage

Step 4: Create a controller to call service.

app/controllers/openai_controller.rb:

class OpenaiController < ApplicationController
def index
if params[:query]
@response = OpenaiService.new(params[:query]).call
end
end
end

Step 5: Create a service to call ChatGPT API.

Now, let’s create a service to call OpenAI API.

app/services/openai_service.rb:

  class OpenaiService
include HTTParty
attr_reader :api_url, :options, :query

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

def call
body = {
model: 'gpt-3.5-turbo', #Model can be change
messages: [{ role: 'user', content: query }]
}
response = HTTParty.post(api_url, body: body.to_json, headers: options[:headers], timeout: 500)
raise response['error']['message'] unless response.code == 200
response['choices'][0]['message']['content']
end
end

You can find the model list here.

Messages have two properties: role and content.

  • The ‘role’ can take one of three values: ‘system’, ‘user’, or the ‘assistant
  • The ‘content’ contains the text of the message from the role.

Step 6: Setup the view to get response

Finally, you can set up your view as per your requirement. I’ve added a search button as of now to find the content based on the request.

views/openai/index.html:

<div class="row">
<%= form_with url: openai_path, method: :get do |form| %>
<div class="form-group">
<%= form.label :query %>
<%= form.text_area :query %>
<%= form.submit 'get content' %>
</div>
<% end %>
</div>

Resources for ChatGPT:

Conclusion

We have walked you through the steps to set up a demo application that effectively leverages ChatGPT’s capabilities. From starting a Rails application and adding necessary gems to handling API keys securely, creating a controller, and setting up a service for OpenAI API calls, you now have a solid understanding of how to seamlessly integrate ChatGPT in a Ruby on Rails application. With this knowledge, you can explore further and tailor this integration to your specific requirements, unlocking the potential of AI-powered conversations in your applications.

Keep following the Simform Engineering publication to know more about such insights and the latest trends in the development ecosystem.

Follow Us: Twitter | LinkedIn

--

--

SANJAY
Simform Engineering

Team Manager of Ruby on Rails & Full Stack Developer