Created
January 22, 2025 17:58
-
-
Save sbatson5/1a74bdd5997602d1c840b8ba136a614b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Book::GenreAutomation | |
attr_accessor :book | |
def initialize(book_id) | |
self.book = Book.find(book_id) | |
end | |
def run | |
genres_array = fetch_genres_from_openai | |
return if genres_array.blank? | |
book.genres.clear | |
genres_array.each do |genre_name| | |
genre = Genre.find_by(name: genre_name) | |
puts "adding genre #{genre_name} to document profile #{book.id}" | |
book.genres << genre if genre.present? | |
end | |
end | |
def fetch_genres_from_openai | |
client = OpenAI::Client.new | |
# rubocop:todo Layout/LineLength | |
prompt = 'You are going to be given a book title, description, and author and a list of genres. Given that context, return a JSON array of genres that best fit the book. If you are unsure, you can leave the array empty.' | |
# rubocop:enable Layout/LineLength | |
genres = Genre.all.map(&:name).join(', ') | |
content = <<-CONTENT | |
#{prompt} | |
Book Title: | |
#{book.title} | |
Book Author(s): | |
#{book.authors.join(', ')} | |
Book Description: | |
#{book.description} | |
Genres: """ | |
#{genres} | |
""" | |
Return in this format: | |
{ genres: [] } | |
CONTENT | |
response = client.chat( | |
parameters: { | |
model: 'gpt-4o', # Required. | |
response_format: { type: 'json_object' }, | |
messages: [{ role: 'user', content: content }], # Required. | |
temperature: 0.7 | |
} | |
) | |
genres_json = response.dig('choices', 0, 'message', 'content') | |
JSON.parse(genres_json)['genres'] | |
rescue StandardError | |
puts "Error in DocumentProfile::GenreAutomation for #{documentProfile.id}" | |
[] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment