How to Integrate ChatGPT with Ruby on Rails

Total Blog Views: 110

Blog Status: publish

Created By: swaz_ahmed Created at: 06-15-2024

Tags: ror chatgpt OpenAi

ChatGPT With Ruby on Rails

Incorporating advanced AI capabilities into web applications can significantly enhance user experience and engagement. One such capability is integrating ChatGPT, ChatGpt has quickly become one of the most talked about AI tools, providing human-like conversational abilities.This guide will walk you through the process of integrating ChatGPT into a Ruby on Rails web application.

 

Step 1: Setting Up the Gem

 

First add the 'OpenAi' gem to your gemfile. This gem allows you to interact with the OpenAI API easily.

 

gem 'openai'

 

Run 'bundle install' to install the gem

Step 2: Set up your API key

You'll need to add an 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, here's the step by step guide to create a .env file 

  • Install the 'dotenv-rails' gem.

               Add the gem to your Gemfile:

 

 gem 'dotenv-rails'

 

  • Create a  .env file

                Create a .env file in the root directory of your Rails application. This file  will hold your environment variables.

touch .env

 

  •   Add the OpenAi key to the .env file 

             Open the  .env  and add the OpenAI key like this:

 

OPEN_API_KEY = your_openai_api_key_here
  •   Use the environment variable in your configuration like this

             In your 'config/initializers/openai.rb'  access the API key using   'ENV[OPEN_API_KEY]' :

 

OpenAI.configure do |config|
config.api_key = ENV['OPENAI_API_KEY']
end

 

Step 3: Create a Controller and define routes 

 

In your 'app/contollers/openai_contoller.rb' file add:

 

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

 

 

Next, define the route for this controller in the 'config/routes.rb' file:

 

Rails.application.routes.draw to
  get  'openai' to: 'openai#index'
end

 

Step 4: Create a service to call ChatGpt API

 

Next, create a service object to handle communication with the ChatGpt API. This will help keep your code organized and maintainable.

 

class ChatGptService
    def initialize
        @client = OpenAI::Client.new
     end

     def ask(question)
          response = @client.completions(
            engine: 'davinci-codex'
            prompt: question,
            max_tokens: 150
              )
            response['choices'].first['text'].strip
         end
end 

 

 

Step 5: Setup the view to get Response:

 

You can Setup view as per your requirement:

 

<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>

 

Conclusion 

 

Integrating ChatGPT with a Ruby on Rails application opens up a world of possibilities for creating interactive and intelligent web applications. By following this guide, you now have a solid foundation to build upon, enabling you to provide users with an enhanced experience through AI-driven conversations.


swaz_ahmed

I am swaz_ahmed blogger on shadbox. I am influencer,content writer,author and publisher. Feel free to ask me any question and suggestions.



Comments



Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads