Official Ruby SDK for the OpenAI API
The OpenAI Ruby library provides convenient access to the OpenAI REST API from any Ruby 3.3.0+ application. It ships with comprehensive types & docstrings in Yard, RBS, and RBI – see below for usage with Sorbet. The standard library's net/http is used as the HTTP transport, with connection pooling via the connection_pool gem.
Documentation for releases of this gem can be found on RubyDoc.
The REST API documentation can be found on platform.openai.com.
To use this gem, install via Bundler by adding the following to your application's Gemfile:
gem "openai", "~> 0.90.0"require "bundler/setup"
require "openai"
openai = OpenAI::Client.new(
api_key: ENV["OPENAI_API_KEY"] # This is the default and can be omitted
)
chat_completion = openai.chat.completions.create(messages: [{role: "user", content: "Say this is a test"}], model: "gpt-5.2")
puts(chat_completion)We provide support for streaming responses using Server-Sent Events (SSE).
stream = openai.responses.stream(
input: "Write a haiku about OpenAI.",
model: "gpt-5.2"
)
stream.each do |event|
puts(event.type)
endRecord a clip and play generated speech with optional FFmpeg/FFplay helpers. See the local audio guide for setup, device selection and examples.
The SDK supports block-scoped, typed Realtime WebSocket sessions for
server-side text, committed-turn transcription, one-turn voice, WebRTC call
creation, and sideband control of existing WebRTC or SIP calls. Add the
optional async-websocket gem for WebSocket connections, then use
client.realtime.connect:
client.realtime.connect(model: "gpt-realtime-2.1") do |connection|
connection.session.update(type: :realtime, output_modalities: [:text])
connection.conversation.items.create(
type: :message,
role: :user,
content: [{type: :input_text, text: "Hello"}]
)
connection.response.create
connection.each do |event|
print(event.delta) if event.is_a?(OpenAI::Realtime::ResponseTextDeltaEvent)
break if event.is_a?(OpenAI::Realtime::ResponseDoneEvent)
end
endWebRTC calls can be created with client.realtime.calls.create; its HTTP
response preserves the SDP answer and the Location header needed to attach a
sideband connection. See the Realtime WebSocket guide and the runnable
text, transcription, voice, and sideband examples
for lifecycle, authentication, proxy, TLS, and custom transport details.
The Responses API also supports a persistent, block-scoped WebSocket for
sequential and multiplexed response creation. Add the optional
async-websocket gem, then send response.create events through
client.responses.connect:
client.responses.connect do |connection|
connection.response.create(
model: "gpt-5.2",
input: "Say hello.",
stream_id: "turn_1"
)
connection.each do |event|
print(event.delta) if event.type == :"response.output_text.delta"
break if event.type == :"response.completed"
end
endThe connection is intentionally single-owner: callers serialize writes and
use one reader (receive or each). The SDK forwards response fields and
stream_id values without imposing additional client-side policy. Known
server events are decoded into generated models on a best-effort basis, while
newer event types remain observable as UnknownServerEvent values. The SDK
does not automatically reconnect or replay an ambiguous write. When the server
closes a connection, open a new connection and continue with
previous_response_id when the response was stored.
See the Responses WebSocket guide and runnable workflows for tool turns, multiplexing, stored continuation, stateless replay, and operation deadlines.
List methods in the OpenAI API are paginated.
This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
page = openai.fine_tuning.jobs.list(limit: 20)
# Fetch single item from page.
job = page.data[0]
puts(job.id)
# Automatically fetches more pages as needed.
page.auto_paging_each do |job|
puts(job.id)
endAlternatively, you can use the #next_page? and #next_page methods for more granular control working with pages.
if page.next_page?
new_page = page.next_page
puts(new_page.data[0].id)
endRequest parameters that correspond to file uploads can be passed as raw contents, a Pathname instance, StringIO, or more.
Raw String and StringIO values, and IO objects without a path, do not carry format-identifying metadata. The SDK sends them using the fallback filename upload; raw String values default to text/plain, while StringIO and pathless IO values default to application/octet-stream. For format-sensitive endpoints, such as audio transcriptions, wrap each value in OpenAI::FilePart and provide an extension-bearing filename and content type.
…Note that you can also pass a raw IO descriptor, but this disables retries, as the library can't be sure if the descriptor is a file or pipe (which cannot be rewound).
Polling helpers wait for file processing and return the final resource. Durations are
expressed in seconds. By default, the helpers honor the API's recommended polling
interval, fall back to 5 seconds, and stop after 30 minutes. Pass timeout: nil to
wait indefinitely.
To keep a finite overall deadline strict, each polling retrieval includes
authentication and request replay time and does not perform transport-level retries.
Pass timeout: nil to retain the client's configured retry behavior.
file = openai.files.wait_for_processing(
file_object.id,
poll_interval: 2,
timeout: 10 * 60
)
vector_file = openai.vector_stores.files.upload_and_poll(
vector_store.id,
file: Pathname("handbook.pdf"),
attributes: {department: "engineering"}
)
batch = openai.vector_stores.file_batches.upload_and_poll(
vector_store.id,
files: [Pathname("one.pdf"), Pathname("two.pdf")],
file_ids: [file_object.id],
max_concurrency: 3
)The vector store helpers return terminal failed and cancelled resources instead
of raising, so inspect status, last_error, or file_counts as appropriate. An
overall polling timeout raises OpenAI::Errors::PollingTimeoutError; its resource
attribute contains the last object returned by the API, or nil if the deadline
elapsed before the first response.
Batch inputs are enumerated before requests begin so the 2,000-file API limit can be checked without orphaning uploads. IO streams yielded by an enumerable must remain open until the helper returns; use paths for block-scoped lazy enumeration. Batch uploads are concurrent but not transactional. If one upload fails, the helper stops starting queued uploads and raises that error; files uploaded successfully before the failure remain available through the Files API.
OpenAI::Client accepts an http_client for advanced transport requirements.
Provide an object that implements execute(request) and returns an
OpenAI::HTTPClient::Response; subclassing OpenAI::HTTPClient is the easiest
way to make that contract explicit. The request exposes the SDK-prepared HTTP
method, URL, headers, encoded body, and timeout. Response bodies are enumerable
byte-string chunks (or a single buffered string), so large and streaming
responses do not need to be buffered.
The OpenAI client owns API authentication, redirects, and API-level retries.
The custom HTTP client owns connection pooling and lifecycle, must enforce
request.timeout, and should raise OpenAI::Errors::APIConnectionError or
OpenAI::Errors::APITimeoutError for retryable transport failures. Other
exceptions propagate without an SDK retry. The SDK does not close an injected
HTTP client. Connection failures are treated as potentially post-send by
default, so non-idempotent requests are not retried automatically. When a
transport can prove that no request bytes were sent, it may raise either error
with request_may_have_been_sent: false to allow the SDK retry policy to
retry a replayable request safely.
The default OpenAI::NetHTTPClient implements this contract with pooled
Net::HTTP connections. It accepts an optional block for native connection
configuration, as shown below. Call close to retire its current pools; the
HTTP client remains reusable and creates fresh connections on its next request.
To opt in and activate mTLS for an organization or project, follow the OpenAI Mutual TLS Beta Program guide. If you use an intermediate chain, confirm that certificate-chain support is enabled for your organization.
For API-key requests that also require mutual TLS (mTLS), set the mTLS endpoint
explicitly and pass a configured OpenAI::NetHTTPClient as http_client.
OpenAI::Client accepts an HTTP client object so advanced transport behavior
does not require a separate SDK option for every use case. The default
OpenAI::NetHTTPClient accepts a block that configures each native
Net::HTTP connection before it is pooled and started.
Ruby's native TLS properties configure the client identity. The certificate file must contain the leaf certificate first, followed by any intermediate certificates needed when certificate-chain support is enabled for your organization:
…The SDK cannot infer whether custom HTTP configuration uses mTLS, so it does not
automatically change base_url. An explicit base_url, including an EU or
custom endpoint, is always preserved. Scope client certificates to the expected
origin, as above, so they cannot be presented elsewhere. Use the
OpenAI::NetHTTPClient block for TLS and other connection-level configuration.
Server trust remains separate from the client identity and can be customized
with Net::HTTP properties such as cert_store or ca_file.
Each OpenAI::NetHTTPClient owns its connection pool, so separate HTTP client
instances do not share connections or credentials.
After a process forks, create new OpenAI and HTTP clients in the child. Keep the
certificate configuration captured by an HTTP client immutable. For certificate
rotation, build and atomically swap in new OpenAI::NetHTTPClient and
OpenAI::Client instances, then call close on the retired HTTP client after
in-flight work finishes. See the complete custom HTTP client mTLS
example.
Use the standard client with the Azure provider to call model deployments through
the Azure OpenAI v1 API. The provider accepts an Azure resource endpoint and
adds /openai/v1 when needed:
require "openai"
client = OpenAI::Client.new(
provider: OpenAI::Providers.azure(
endpoint: ENV.fetch("AZURE_OPENAI_ENDPOINT"),
api_key: ENV.fetch("AZURE_OPENAI_API_KEY")
)
)
response = client.responses.create(
model: ENV.fetch("AZURE_OPENAI_DEPLOYMENT"),
input: "Say hello!"
)
puts(response.output_text)Omit endpoint and api_key to use AZURE_OPENAI_ENDPOINT and
AZURE_OPENAI_API_KEY. For Microsoft Entra authentication, pass a callable
that returns a current bearer token. The provider invokes it before every
request attempt, including retries:
client = OpenAI::Client.new(
provider: OpenAI::Providers.azure(
endpoint: ENV.fetch("AZURE_OPENAI_ENDPONo open issues yet, or sync has not completed.