Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using OpenAI API with Ruby

Introduction

This tutorial demonstrates how to integrate and use the OpenAI API with Ruby to leverage advanced AI capabilities in your applications.

1. Setting Up Your OpenAI API Key

Before starting, make sure you have your OpenAI API key ready. You can obtain it from the OpenAI website after signing up for an account.

2. Making API Requests

To make requests to the OpenAI API using Ruby, you'll use Ruby's Net::HTTP library.

Text Completion

Here’s an example of making a request for text completion:

require 'net/http'
require 'uri'
require 'json'

apiKey = 'YOUR_API_KEY_HERE'
url = URI('https://api.openai.com/v1/completions')
data = {
  prompt: 'Translate English to French: Hello, how are you?',
  max_tokens: 50
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request['Content-Type'] = 'application/json'
request['Authorization'] = "Bearer #{apiKey}"
request.body = data.to_json

response = http.request(request)
puts "<div class=\"output\"><pre>#{JSON.parse(response.body).to_json}</pre></div>"
                    

Output: Bonjour, comment vas-tu ?

This Ruby script sends a POST request to the OpenAI API for text completion and prints the API response.

Code Generation

Here’s an example of making a request for code generation:

require 'net/http'
require 'uri'
require 'json'

apiKey = 'YOUR_API_KEY_HERE'
url = URI('https://api.openai.com/v1/engines/davinci-codex/completions')
data = {
  prompt: 'Generate Python code to sort an array using bubble sort',
  max_tokens: 150,
  stop: ['\n']
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request['Content-Type'] = 'application/json'
request['Authorization'] = "Bearer #{apiKey}"
request.body = data.to_json

response = http.request(request)
puts "<div class=\"output\"><pre>#{JSON.parse(response.body).to_json}</pre></div>"
                    
def sort_list(list):
    list.sort()
    return list

my_list = [3, 1, 4, 2]
print(sort_list(my_list))
                    

This Ruby script sends a POST request to the OpenAI Codex engine for code generation and prints the generated code.

3. Handling Responses

Once you receive a response from the API, you can handle it in your Ruby code.

Text Completion

Here’s how you might handle the completion response:

# Assuming response contains the API response
puts "<div class=\"output\"><pre>#{response.body}</pre></div>"
                    

In this example, response.body contains the JSON response from the OpenAI API.

Code Generation

Here’s how you might handle the code generation response:

# Assuming response contains the API response
puts "<div class=\"output\"><pre>#{response.body}</pre></div>"
                    

In this example, response.body contains the JSON response from the OpenAI API with the generated code.

4. Additional Use Case: Image Generation

You can also use the OpenAI API for image generation. Here’s an example of generating an image description:

require 'net/http'
require 'uri'
require 'json'

apiKey = 'YOUR_API_KEY_HERE'
url = URI('https://api.openai.com/v1/images')
data = {
  model: 'text-dalle-1',
  prompt: 'A peaceful lake surrounded by mountains at sunset',
  width: 600,
  height: 400
}

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request['Content-Type'] = 'application/json'
request['Authorization'] = "Bearer #{apiKey}"
request.body = data.to_json

response = http.request(request)
output = JSON.parse(response.body)
imageUrl = output['output']['url']

puts "<div class=\"output\"><img src=\"#{imageUrl}\" alt=\"Generated Image\"></div>"
                    

Output: The generated image based on the API response.

This Ruby script uses the DALL-E model to generate an image based on the provided prompt and displays the generated image.

5. Conclusion

Integrating the OpenAI API with Ruby empowers your applications with advanced AI capabilities. Experiment with different API endpoints and functionalities to enhance your projects further.