Take Your Rails App to the Next Level with ChatGPT API: A Guide to Integrating NLP Capabilities

Demian Ardus

Demian Ardus

CTO & Co-Founder @NeoCoast
Take Your Rails App to the Next Level with ChatGPT API: A Guide to Integrating NLP Capabilities

Introduction to ChatGPT API and its capabilities

ChatGPT API is an artificial intelligence-based API that allows developers to integrate Natural Language Processing (NLP) capabilities into their applications. The API uses a large, pre-trained neural network to generate responses to user input in a conversational manner. This allows developers to create chatbots, virtual assistants, and other conversational interfaces that can understand and respond to natural language input.

Some use cases for ChatGPT API include:

  • Chatbots: Chatbots are becoming increasingly popular as a way for businesses to provide customer support or automate certain tasks. ChatGPT API can be used to power the conversational abilities of a chatbot, allowing it to understand and respond to natural language input.

  • Virtual assistants: Virtual assistants, such as Apple's Siri or Amazon's Alexa, use NLP to understand and respond to user input. ChatGPT API can be used to create a similar virtual assistant that can answer questions and perform tasks for users.

  • Language translation: ChatGPT API can be used to translate text from one language to another. By inputting text in one language and requesting a translation, ChatGPT API can generate a translated response in real-time.

  • Content creation: ChatGPT API can be used to generate content for articles, social media posts, or other publications. By inputting a topic or prompt, ChatGPT API can generate a well-written response that can be used as the basis for content creation.

Overall, ChatGPT API provides a powerful tool for developers to integrate NLP capabilities into their applications, enabling them to create more natural and intuitive interfaces for their users.

Registering for a ChatGPT API key

To use the ChatGPT API, we need to register for an API key on the OpenAi website. Once we have registered, we can obtain our API key which we will use to authenticate requests to the API.

Setting up a Rails app to use the ChatGPT API

To use ChatGPT API in a Rails app, we first need to create a new Rails project and add the necessary dependencies to our Gemfile. We can use the ruby-openai gem to make API requests to the ChatGPT API and parse the responses.

To get started, let's create a new Rails app:

rails new chatgpt-app

Next, we'll add the ruby-openai gem to our Gemfile:

# Gemfile
gem 'ruby-openai'

Then, we'll run bundle install to install the new gem and its dependencies:

bundle install

Now we're ready to make API requests to ChatGPT API in our Rails app.

First, lets create an initializer for our Open AI client, where we will set up our API key (ideally you want to use an ENV var for this and do ENV.fetch('OPENAI_ACCESS_TOKEN'), but for the purpose of this example we can just place it here).

# config/initializers/openai.rb
OpenAI.configure do |config|
config.access_token = YOUR_API_KEY

Here's an example of how to use ruby-openai to send a request to the API and receive a response:

Let's first define a route for us to be able to actually see the response in our browsers:

# config/routes.rb
Rails.application.routes.draw do
get '/chatgpt', to: 'chatgpt#index'

And now our new controller:

# app/controllers/chatgpt_controller.rb
class ChatgptController < ApplicationController
def index
openai_client = OpenAI::Client.new
prompt = "Hello world!"
response = openai_client.chat(
parameters: {
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: prompt}],
temperature: 0.7,
# Extract the generated text from the response
generated_text = response.dig("choices", 0, "message", "content")
# Return the generated text
render plain: generated_text

The code creates a new instance of the OpenAI ruby client and defines a string prompt. The chat method sends a prompt to OpenAI's GPT-3 language model and receives a response. The parameters that are passed include the name of the GPT model to be used, the prompt to send to the model, and the temperature to use when generating the response. The temperature parameter controls the creativity vs. conservativity of the model response (from OpenAI's own documentation: "higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.").

We should now be able to start our server (rails s), and go to localhost:3000/chatgpt in our browsers or use Postman to see the response from the API. You can also play around by changing the prompt and temperature and seeing what results you get.

With this code as a starting point, we can begin integrating the ChatGPT API into our Rails app.

Trivia game using Chat GPT API

For the purpose of playing around and being able to provide a real life example for this article, I decided to build a quick app that did have some sort of usage for the ChatGPT API.

As I was starting to think about some app ideas, it came to my mind that it'd be great to use the one and only ChatGPT to be the master of this experiment, so I decided to ask him not only for an idea, but for both an idea and the code for the app itself.

We (ChatGPT and I) decided to build a trivia application that uses the API to generate categories, questions, and possible answers dynamically.

This ChatGPT 3.5 Trivia Application is a Ruby on Rails application that allows users to create game rounds and generate as many random questions as they wish to play. All categories, questions, and possible answers are built on-the-fly using the ChatGPT API.

Around 95% of the code and comments you will find on the repo were written by ChatGPT 3.5, with me providing guidance on what we wanted to achieve for our end-users. The remaining 5% was me tweaking some of its outputs to make things work. While most of the time I was able to make it fix its own mistakes, there were some situations where I had to code it myself to reach a solution.

You'll also be able to find some code that's not "ideal", and some improvements to be made that any experienced Rails dev could tell, but for the sake of this experiment I decided to make as few changes as possible to the ChatGPT outputs.

The application has the following features:

  • User authentication: Users can sign up, log in, and log out of the application. The background animation for the login page was ChatGPT's definition of "a cool animation on the background using just CSS".
  • Round creation: Users can create game rounds dynamically.
  • Question creation: Users can create as many questions as they want while playing one round.
  • Answer questions: Users can answer each question via multiple choice.
  • Dashboards: The application tracks users' answers and awards points for correct answers.

Overall, the ChatGPT 3.5 Trivia Application demonstrates how the ChatGPT API can be used to create dynamic content for end-users in a Rails application.

Conclusion and next steps

In this article, we learned how to set up a Rails app to use ChatGPT API and how to send requests and parse responses from the API. We also built a simple trivia app using ChatGPT API. For me, it's clear that starting to take advantage of this tool will open up a world of possibilities for new and innovative applications.

For this small example, next steps could be polishing the Trivia app response parser to be safer against API issues or unexpected formats on the response, adding some more features to it, or thinking about a brand new idea on how we can put this awesome tool to use.


ChatGPT was also used as an assistant to write almost this entire article (except conlusion and disclaimer) :) Let's embrace the tools we are provided with!