Skip to main content
This guide will help you make your first API call with the OpenAI Ruby SDK.
1

Set your API key

Set your OpenAI API key as an environment variable:
export OPENAI_API_KEY='your-api-key-here'
You can find your API key in your OpenAI dashboard.
2

Create a client

Initialize the OpenAI client:
require "bundler/setup"
require "openai"

client = OpenAI::Client.new(
  api_key: ENV["OPENAI_API_KEY"] # This is the default and can be omitted
)
If you don’t pass an api_key, the client will automatically use the OPENAI_API_KEY environment variable.
3

Make your first request

Create a chat completion:
completion = client.chat.completions.create(
  messages: [{ role: "user", content: "Say this is a test" }],
  model: "gpt-4"
)

puts completion.choices[0].message.content
# => "This is a test"

Complete Example

Here’s a complete, runnable example:
demo.rb
#!/usr/bin/env ruby
require "bundler/setup"
require "openai"

# Initialize the client (uses ENV["OPENAI_API_KEY"])
client = OpenAI::Client.new

# Create a chat completion
completion = client.chat.completions.create(
  model: "gpt-4",
  messages: [
    {
      role: "user",
      content: "Say this is a test"
    }
  ]
)

# Print the response
puts completion.choices.first&.message&.content
Run it:
ruby demo.rb

Streaming Responses

You can also stream responses as they’re generated:
stream = client.chat.completions.stream_raw(
  model: "gpt-4",
  messages: [
    {
      role: "user",
      content: "How do I output all files in a directory using Python?"
    }
  ]
)

stream.each do |chunk|
  next if chunk.choices.to_a.empty?
  
  print chunk.choices.first&.delta&.content
end
For streaming with the Responses API, use client.responses.stream() which provides a higher-level interface with event handlers.

Error Handling

Always handle potential errors when making API calls:
require "openai"

client = OpenAI::Client.new

begin
  completion = client.chat.completions.create(
    messages: [{ role: "user", content: "Hello!" }],
    model: "gpt-4"
  )
  
  puts completion.choices[0].message.content
rescue OpenAI::Errors::AuthenticationError => e
  puts "Authentication failed: #{e.message}"
rescue OpenAI::Errors::RateLimitError => e
  puts "Rate limit exceeded: #{e.message}"
rescue OpenAI::Errors::APIError => e
  puts "API error: #{e.message}"
end

Next Steps

Core Concepts

Learn about client configuration and core concepts

Chat Completions

Explore the Chat Completions API

Streaming

Master streaming responses

Examples

Browse more code examples

Build docs developers (and LLMs) love