diff --git a/Gemfile b/Gemfile index 900e882a..56bd0f34 100644 --- a/Gemfile +++ b/Gemfile @@ -6,6 +6,7 @@ gemspec # Development dependencies. Not included in the publised gem. gem "byebug", "~> 11.1.3" gem "dotenv", "~> 2.8.1" # >= v3 will require removing support for Ruby 2.7 from CI. +gem "mime-types", "~> 3.5" gem "rake", "~> 13.2.1" gem "rspec", "~> 3.13" gem "rubocop", "~> 1.74.0" diff --git a/Gemfile.lock b/Gemfile.lock index 2b19c222..4361f6d5 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -32,6 +32,9 @@ GEM json (2.10.2) language_server-protocol (3.17.0.4) lint_roller (1.1.0) + mime-types (3.5.2) + mime-types-data (~> 3.2015) + mime-types-data (3.2024.0604) multipart-post (2.3.0) parallel (1.26.3) parser (3.3.7.1) @@ -87,6 +90,7 @@ PLATFORMS DEPENDENCIES byebug (~> 11.1.3) dotenv (~> 2.8.1) + mime-types (~> 3.5) rake (~> 13.2.1) rspec (~> 3.13) rubocop (~> 1.74.0) diff --git a/lib/openai.rb b/lib/openai.rb index 4c29c24a..6ea30b91 100644 --- a/lib/openai.rb +++ b/lib/openai.rb @@ -21,6 +21,7 @@ require_relative "openai/version" require_relative "openai/batches" require_relative "openai/usage" +require_relative "openai/mime_types" module OpenAI class Error < StandardError; end diff --git a/lib/openai/http.rb b/lib/openai/http.rb index 5459f64c..3f30d710 100644 --- a/lib/openai/http.rb +++ b/lib/openai/http.rb @@ -87,11 +87,9 @@ def multipart_parameters(parameters) # Faraday::UploadIO does not require a path, so we will pass it # only if it is available. This allows StringIO objects to be # passed in as well. - path = value.respond_to?(:path) ? value.path : nil - # Doesn't seem like OpenAI needs mime_type yet, so not worth - # the library to figure this out. Hence the empty string - # as the second argument. - Faraday::UploadIO.new(value, "", path) + return Faraday::UploadIO.new(value, "", nil) unless value.respond_to?(:path) + + Faraday::UploadIO.new(value, mime_type_for(value.path), value.path) end end @@ -108,5 +106,9 @@ def configure_json_post_request(req, parameters) req.headers = headers req.body = req_parameters.to_json end + + def mime_type_for(path) + MIME::Types.of(path).first.to_s + end end end diff --git a/lib/openai/mime_types.rb b/lib/openai/mime_types.rb new file mode 100644 index 00000000..c741b3c4 --- /dev/null +++ b/lib/openai/mime_types.rb @@ -0,0 +1,17 @@ +require "mime/types" + +module OpenAI + module MimeTypes + REGISTER_MIME_TYPES = { "jsonl" => "application/json" }.freeze + + def self.register + REGISTER_MIME_TYPES.each do |register_type, mime_type| + next if MIME::Types.of(register_type).any? + + MIME::Types[mime_type].first.add_extensions(register_type) + end + end + end +end + +OpenAI::MimeTypes.register