Upload files using Pathname, StringIO, FilePart, and raw file contents
The OpenAI Ruby SDK provides flexible options for uploading files to the API. You can use file paths, raw contents, or specialized objects to control upload behavior.
The Pathname class is recommended for file uploads as it sends the filename and avoids loading large files into memory:
require "openai"require "pathname"client = OpenAI::Client.new# Use Pathname to send the filename and avoid paging a large file into memoryfile_object = client.files.create( file: Pathname("input.jsonl"), purpose: "fine-tune")puts(file_object.id)
Pathname is the recommended approach as it:
Automatically includes the filename in the upload
Streams the file without loading it entirely into memory
require "stringio"# Create file content in memorycontent = <<~JSONL {"prompt": "What is 2+2?", "completion": "4"} {"prompt": "What is the capital of France?", "completion": "Paris"}JSONLfile_object = client.files.create( file: StringIO.new(content), purpose: "fine-tune")puts(file_object.id)
The OpenAI::FilePart class gives you control over filename and content type:
require "pathname"# Control the filename and content typeimage = OpenAI::FilePart.new( Pathname('dog.jpg'), content_type: 'image/jpeg')edited = client.images.edit( prompt: "make this image look like a painting", model: "gpt-image-1", size: '1024x1024', image: image)puts(edited.data.first)
Raw IO descriptors disable automatic retries because the SDK cannot determine if the descriptor is a file (which can be rewound) or a pipe (which cannot).