Demonstrating the "ruby-openai" Ruby Gem in the Rails console using a personal API

Here is a demonstration of the Ruby gem ruby-openai in the Rails console.

- Get an OpenAI API Key

To get an OpenAI API key, you'll need to sign up for an account on the OpenAI website. Here's a step-by-step guide:

API Details
  1. Go to https://beta.openai.com/signup
  2. Enter your email address and create a password
  3. Click the "Sign up" button
  4. Check your email for a message from OpenAI with the subject "Welcome to OpenAI"
  5. Click the "Verify email" button in the email
  6. On the verification page, enter your password and click the "Verify email" button
  7. After your email has been verified, you'll be taken to the OpenAI dashboard
  8. From the dashboard, you can access your API key by clicking the "API keys" tab in the left-hand menu

- Create a Rails app

To create a new Rails app, open a terminal and navigate to the location where you want to create your app. Then, run the following command:

Rails Bundle Detail
rails new app-name

- Add the GitHub - alexrudall/ruby-openai: OpenAI API + Ruby! 🤖❤️ gem

Replace "app-name" with the desired name for your app. This will create a new Rails app with the specified name in the current directory.

If you want to create a Rails app with a specific version of Rails, you can specify the version by adding -v followed by the version number. For example:

rails _6.0.3.2_ new app-name

This will create a new Rails app with version 6.0.3.2.

If you want to use a specific version of Ruby, you can specify the version in the shebang at the top of the rails executable. For example:

#!/usr/bin/env ruby-2.7.1

This will use Ruby 2.7.1 to create the Rails app.

- Add the ruby-openai gem and bundle

To add the ruby-openai gem to a Rails application, you will first need to include the gem in your Gemfile. Open your Gemfile, which is typically located in the root of your Rails project, and add the following line:

gem 'ruby-openai'

Then run the following command to install the gem and add it to your application's dependencies:

bundle install

Or macos, you can bundle in the vendor directory.

This will install the ruby-openai gem and make it available for use in your Rails application.

- Demonstration 1

prompt = "write ruby method to convert a date string to unixtime include comments in code"

Ruby::OpenAI.configure do |config|
    config.access_token = ENV.fetch('OPENAI_API_KEY')
end

client = OpenAI::Client.new

response = client.completions(
 parameters: {
    model: "text-davinci-003",
    prompt: prompt,
    max_tokens:1024,
})

In the Rails console run the above, then view the results:

puts response["choices"].map { |c| c["text"] }

Code Generated by OpenAI using the "text-davinci-003" model

def date_to_unixtime(date_string)
  #Converts a given string in the format YYYY-MM-DD to Unix time
  DateTime.parse(date_string).to_time.to_i
end

- Demonstration 2

prompt="write a method in ruby to calculate the distance between the earth and the moon based on the date and add comments to the code"

Run the same code as above and the results are:

def distance_earth_moon(date)
    # The moon moves away from the earth by an average of 3.82 cm each year.
    # This method takes in a date and calculates the approximate distance 
    # between the earth and moon
    
    # Calculate the years between 2000 and the date entered
    years_passed = date.year - 2000

    # Multiply the years by the rate of distance increase per year
    distance_increase = years_passed * 3.82

    # Add the rate of increase to the original distance
    moon_distance = 384400 + distance_increase

    # Return the approximate distance between the earth and moon
    return moon_distance
end

Results:

irb(main):127:0> distance_earth_moon(Time.now)

=> 384487.86

- Demonstration 3

Run the same query with the "text-davinci-002" model instead of "text-davinci-003"

#calculates the distance between the earth and the moon based on the date
#requires the 'date' gem
# @param year [Integer]
# @param month [Integer]
# @param day [Integer]
# @return [Float] the distance in km
def moon_distance(year, month, day)
  require 'date'
  # average distance fromcenter of earth to center of moon
  average_distance = 384401
  # number of days since Jan 1, 2000
  days_since_jan_1_2000 = Date.new(year, month, day).mjd - Date.new(2000, 1, 1).mjd
  # actual distance = average distance + sin(days since Jan 1, 2000) * 2.5
  Float((average_distance + Math.sin(days_since_jan_1_2000) * 2.5).round(2))
end

Results:

irb(main):170:0> moon_distance(2023,1,7)
=> 384401.24

- Demonstration 4

Run the same query with the "text-davinci-001" model instead of "text-davinci-003"

# This code calculates the distance between the earth and the moon # based on the date. It takes into account the elliptical nature # of their orbits. The results are in kilometers. def calculate_distance(date) 
# The distance between the earth and the moon is constantly changing. # We need to use the current date to get an accurate measurement. date = Date.today # The distance between the earth and the moon is about 384,000 kilometers. # We'll use that as our starting point. distance = 384000 # The moon orbits the earth in an elliptical pattern. # We need to use the equation of an ellipse to calculate the distance # at any given point in time. a = date.year - distance / 2 / 365.24 b = date.month - distance / 12 / 365.24 c = date.day - distance / 24 / 365.24 # This equation gives us the distance between the earth and the moon # at any given point in time. distance = (a*a) + (b*b) - (c*c) # We'll use the formula for a circle to calculate the radius of the moon's orbit. radius = 2*distance # The moon's orbit is about 356,000 kilometers. # We'll use that as our final distance. distance = radius*3600 # The results are in kilometers. return distance

We can see that each evolution of the Davinci model results in better results, especially from 001, which did not generate any code, but only description of the code.

In conclusion, it's easy to experiment with OpenAI models using the OpenAI API. I may write a Discourse plugin to create a DiscourseGTPChatBot, or maybe not. Let's see what direction I go with this API.

For now, I will continue to experiment with different models and basic capabilities of the OpenAI API.

Models can be found using this method from the console:

client.models.list

The results of the list method are too extensive to copy-and-paste here.

2 Likes

- Demonstration 5

Using the same API client above, generate an image:

Image 1

 prompt="a unix computer with an ai coming out of the top like a jack-in-a-box"
 response = client.images.generate(parameters: { prompt: prompt, size: "256x256" })
 puts response.dig("data", 0, "url")

Results:

Image 2

prompt="a unix computer with an ai coming out of the top like a jack-in-a-box with 'unix' written on the computer in red in latin"

Results (Better):

Image 3

prompt="a unix computer with an ai coming out of the top like a jack-in-a-box with 'unix' written on the computer in red in latin and with purple legs which look like a spider"

Results:

Image 4

prompt="a kitten writing ruby code on a mac studio computer"

Results:

Image 5

prompt="a chicken looking at an egg and wondering which came first, the chicken or the egg"

Results:

Image 6

prompt="a dog in a superposition of quantum states reading a physics book in the multiverse"

Results:

Screenshot 2023-01-08 at 10.48.53 AM

This is very cool coming from a generative AI API, don't you think?

2 Likes

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.