ChatGPT is a conversational AI model developed by OpenAI that generates human-like responses to text inputs. It can be integrated into various applications to enhance their user experience. This tutorial will discuss integrating ChatGPT API into a Ruby on Rails application.
Documentation
The documentation of ChatGPT can be found at https://platform.openai.com/docs/api-reference/chat/create , and you can request the API key athttps://platform.openai.com/account/api-keys.
Install HTTParty
We will use the HTTParty
gem to make HTTP requests to the ChatGPT API. You can install it by adding the following line to your Gemfile and running bundle install
:
gem 'httparty'
Save the API Key to Rails credentials
To keep the API key secure, we will save it to the Rails credentials file. You can edit the credentials file by running the following command in your terminal:
EDITOR="nano" bin/rails credentials:edit
This will open the credentials file in the nano
text editor. You can then add the following line to the file, replacing your-api-key-here
with your actual API key:
chatgpt_api_key: your-api-key-here
Save and close the file.
Create a ChatGPT service
We will create a Ruby class to handle requests to the ChatGPT API. Create a new file named chatgpt_service.rb
in the app/services
directory of your Rails application and add the following code:
# @note: This service is used to call the OpenAI API to generate a response to a message
# @note: The API key is stored in the credentials file
# @param message [String] The message to generate a response for
# @param model [String] The model to use for the response [gpt-3.5-turbo, gpt-3.5-turbo-0301]
# @return [String] The generated response
# @example
# ChatgptService.call('What is your name?', 'gpt-3.5-turbo')
# => "\n\nI am an AI language model created by OpenAI, so I don't have a name. You can call me OpenAI or AI assistant."
# API Docs: https://platform.openai.com/docs/api-reference/chat/create
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 #{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
This class uses 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.
Calling the service
You can use the ChatgptService
class to generate a response to a message. For example, you might add the following code to a Rails controller:
class ChatController < ApplicationController
def index
@response = ChatgptService.call(params[:message])
end
end
This action will call the ChatgptService
class with the message
parameter and assign the response to an instance variable named @response
. You can then render the response in your view.
You can call in the console:
ChatgptService.call('What is your name?')
# => "\n\nI am an AI language model created by OpenAI, so I don't have a name. You can call me OpenAI or AI assistant."
If you want to use the second model, gpt-3.5-turbo-0301
you can call it like this:
ChatgptService.call('What is your name?', 'gpt-3.5-turbo-0301')
# => "\n\nI am an AI language model created by OpenAI, so I don't have a name. You can call me OpenAI or AI assistant."
Happy Coding!
Contact me at sulman@hey.com
Top comments (0)