A digital illustration showing a sleek, modern humanoid robot acting as a virtual assistant, engaged with a Ruby on Rails interface on a large screen. The robot, accented with Ruby red, symbolizes the integration of ChatGPT with the Ruby on Rails framework, highlighting advanced virtual assistance capabilities in software development.

Integrating ChatGPT with Ruby on Rails for Virtual Assistance

Alessio Bussolari
3 min readNov 13, 2023

--

Learn how to integrate ChatGPT with a Ruby on Rails application to create an advanced virtual assistant, enhancing user experience and efficiency.

Introduction

Integrating ChatGPT, a state-of-the-art language model developed by OpenAI, with a Ruby on Rails application can significantly enhance user experience by providing intelligent and interactive virtual assistance. This integration can be utilized for customer support, data inquiries, or even for interactive user experiences.

Prerequisites

  1. Ruby on Rails Environment: Ensure you have a Rails application set up and running.
  2. OpenAI API Key: Since ChatGPT is an offering of OpenAI, you will need an API key from OpenAI to access the model.

Step-by-Step Integration Process

  • Setting Up OpenAI API Access: first, obtain an API key from OpenAI by registering on their platform and subscribing to the necessary API plans. Keep this key secure as it will be used to authenticate your requests.
  • Configuring the Rails Application: in your Rails application, add a service to handle interactions with the OpenAI API. This can be done by creating a new service file:
# app/services/chat_gpt_service.rb
require 'net/http'
require 'uri'
require 'json'

class ChatGptService
def initialize(prompt)
@prompt = prompt
end

def get_response
uri = URI.parse("https://api.openai.com/v1/engines/davinci-codex/completions")
request = Net::HTTP::Post.new(uri)
request.content_type = "application/json"
request["Authorization"] = "Bearer #{Rails.application.credentials.openai_api_key}"
request.body = JSON.dump({
"prompt" => @prompt,
"max_tokens" => 150
})

req_options = {
use_ssl: uri.scheme == "https"
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end

JSON.parse(response.body)["choices"].first["text"].strip
end
end
  • Securely Storing the API Key: Store your OpenAI API key securely in Rails credentials:
rails credentials:edit
  • Add the API key:

--

--

Alessio Bussolari

Ruby on Rails programmer since 2009. Current CTO at COSMIC SRL, where I lead the team in creating innovative solutions.