Thursday, August 28, 2025

Integrating OpenAI with Ruby on Rails

 

Integrating OpenAI with Ruby on Rails: A Step-by-Step Guide

Artificial Intelligence is transforming how modern web applications are built, and OpenAI’s models can be seamlessly integrated into your Ruby on Rails projects to add natural language processing, chatbots, content generation, and more. In this guide, we’ll walk through how to set up OpenAI in a Rails application.


🔧 Step 1: Add the OpenAI Gem

First, install the ruby-openai gem. This gem provides a simple wrapper around OpenAI’s API.

# Gemfile gem "ruby-openai"

Run:

bundle install

🔑 Step 2: Configure API Key

Set your OpenAI API key as an environment variable (best practice is to use dotenv-rails or Rails credentials).

export OPENAI_ACCESS_TOKEN="your_api_key_here"

Or inside Rails credentials:

EDITOR="nano" bin/rails credentials:edit
openai: api_key: your_api_key_here

💻 Step 3: Initialize OpenAI Client

Create a service file for handling OpenAI requests, for example:

# app/services/openai_service.rb require "openai" class OpenaiService def initialize @client = OpenAI::Client.new(access_token: Rails.application.credentials.dig(:openai, :api_key)) end def chat(prompt) response = @client.chat( parameters: { model: "gpt-4o-mini", messages: [{ role: "user", content: prompt }], temperature: 0.7 } ) response.dig("choices", 0, "message", "content") end end

🚀 Step 4: Use OpenAI in a Controller

Example controller to call the service:

# app/controllers/ai_controller.rb class AiController < ApplicationController def generate prompt = params[:prompt] ai_service = OpenaiService.new @response = ai_service.chat(prompt) render json: { response: @response } end end

And add a route:

# config/routes.rb post "ai/generate", to: "ai#generate"

🌐 Step 5: Test the Endpoint

Send a POST request with a prompt:

curl -X POST http://localhost:3000/ai/generate \ -H "Content-Type: application/json" \ -d '{"prompt":"Explain Ruby on Rails in simple terms."}'

Response:

{ "response": "Ruby on Rails is a web framework that helps developers build web apps quickly..." }

📊 Possible Use Cases in Rails

  • Customer support chatbots

  • Blog/content generation

  • Code suggestions in developer tools

  • Semantic search & recommendations

  • Automating routine text tasks


✅ Final Thoughts

Integrating OpenAI with Ruby on Rails is straightforward using the ruby-openai gem. By following the steps above, you can add powerful AI-driven features to your Rails app and create a more interactive, intelligent experience for users.

No comments:

Post a Comment

FastAPI: The Modern Python Web Framework

  Introduction to FastAPI: The Modern Python Web Framework The world of web frameworks has always been competitive — from Django and Flask ...