INTEGRATING OPENAI IN RAILS

Total Blog Views: 104

Blog Status: publish

Created By: swaz_ahmed Created at: 01-06-2025

Tags: ruby-on-rails openai-api ruby-openai rails-integration gpt-4 rails-api ai-integration prompt-engineering api-authentication

What is ChatGPT?

ChatGPT is an artificial intelligence chatbot developed by OpenAI that allows us to have human-like conversations and generate images based on text descriptions. It is one of the greatest leaps in natural language processing.

Integrating OpenAI API in ruby application.

We can implement all the ChatGPT features in a ruby application to make it more engaging for users by integrating OpenAI API. For this, we are using the ruby-openai gem which allows us to use various OpenAI models which we can pick based on the use case.

STEP 1: Install gem
         Add the ruby-openai gem to the Gemfile.
          Then run bundle install to install the gem.

 


STEP 2: Configure OpenAI in Rails

 

export OPENAI_API_KEY="xxxxxxxxxxxxxxx"


  We have to generate an access key to get a response back, visit API keys page and create a new secret key.
 Copy the secret key and assign it to OPENAI_ACCESS_TOKEN environment variable.
 


STEP 3: Create an OpenAI Service.

 


 Create a service class to handle OpenAI requests(app/services/openai_service.rb)
   Now, edit app/services/openai_service.rb.

require 'openai'
  class OpenAIService
       def initialize
          @client = OpenAI::Client.new(access_token: ENV['OPENAI_API_KEY'])
       end
       def generate_text(prompt)
            response = @client.chat(
              parameters: {
                model: "gpt-4",
                messages: [{ role: "user", content: prompt }],
                temperature: 0.7
              }
            )
            response.dig("choices", 0, "message", "content")
          end
       end

 

 

STEP 4: Use OpenAI in Controllers.
        You can now use OpenAI in your controllers, for example.
 

  class AiController < ApplicationController
     def generate_response
          service = OpenAIService.new
          @response = service.generate_text(params[:prompt])
          render json: { response: @response }
     end
  end

 

 

STEP 5: Add Routes


     In the config/routes.rb file add the below line
         

get 'ai/generate', to: 'ai#generate_response'

 


STEP 6: Start your Rails server and test with.

 

 curl "http://localhost:3000/ai/generate?prompt=Hello AI, how are you?"

Expected response:
        { "response": "I'm an AI, and I'm here to assist you!" }


 


STEP 7: Add OpenAI to Your Frontend
           If using a Rails frontend, you can add an input field and button in a view,
 

 <!-- app/views/ai/index.html.erb -->
       <h1>Ask AI</h1>
        <form action="/ai/generate" method="get">
           <input type="text" name="prompt" placeholder="Enter your question" />
           <button type="submit">Ask</button>
         </form>

 

 

 Conclusion
            You've successfully integrated OpenAI into your Rails app! You can expand this by adding features like chatbots, content generation, and AI-powered automation.

 

 

 

 

 

 

 


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