Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
R

ruby-openai

> 后端框架
Open source

OpenAI API + Ruby! ❤️ GPT-5 & Realtime WebRTC compatible!

3.2K stars0 likes4 views
WebsiteGitHub

About

OpenAI API + Ruby! ❤️ GPT-5 & Realtime WebRTC compatible!

Ruby OpenAI

Use the OpenAI API with Ruby! ❤️

Stream GPT-5 chats with the Responses API, initiate Realtime WebRTC conversations, and much more...

Sponsors

InferToGo - The inference addon for your PaaS application.

SerpApi - Search API - Enhance your LLM's knowledge with data from search engines like Google and Bing using our simple API.

Ruby AI Builders Discord | X | Anthropic Gem | Midjourney Gem | ♥️ Thanks to all sponsors!

Contents

  • Ruby OpenAI
    • Contents
    • Project Policies
    • Installation
      • Bundler
      • Gem install
    • How to use
      • Quickstart
      • With Config
        • Custom timeout or base URI
        • Extra Headers per Client
        • Logging
          • Errors
          • Faraday middleware
        • Azure
        • Deepseek
        • Ollama
        • Groq
        • Gemini
      • Counting Tokens
      • Models
      • Chat
        • Streaming Chat
        • Vision
        • JSON Mode
      • Responses API
        • Create a Response
        • Follow-up Messages
        • Tool Calls
        • Streaming
        • Retrieve a Response
        • Delete a Response
        • List Input Items
      • Functions
      • Completions
      • Embeddings
      • Batches
      • Files
        • For fine-tuning purposes
        • For assistant purposes
      • Finetunes
      • Vector Stores
      • Vector Store Files
      • Vector Store File Batches
      • Conversations
      • Assistants
      • Threads and Messages
      • Runs
        • Create and Run
        • Vision in a thread
        • Runs involving function tools
        • Exploring chunks used in File Search
      • Image Generation
        • DALL·E 2
        • DALL·E 3
      • Image Edit
      • Image Variations
      • Moderations
      • Whisper
        • Translate
        • Transcribe
        • Speech
      • Real-Time
      • Usage
      • Errors
    • Development
      • To check for deprecations
    • Release
    • Contributing
    • License
    • Code of Conduct

Project Policies

  • Security policy
  • Support and end-of-life policy
  • Migration guides
  • Changelog

Installation

Bundler

Add this line to your application's Gemfile:

ruby
gem "ruby-openai"

And then execute:

bash
bundle install

Gem install

Or install with:

bash
gem install ruby-openai

and require with:

ruby
require "openai"

How to use

  • Get your API key from https://platform.openai.com/account/api-keys
  • If you belong to multiple organizations, you can get your Organization ID from https://platform.openai.com/account/org-settings

Quickstart

For a quick test you can pass your token directly to a new client:

ruby
client = OpenAI::Client.new(
  access_token: "access_token_goes_here",
  log_errors: true # Highly recommended in development, so you can see what errors OpenAI is returning. Not recommended in production because it could leak private data to your logs.
)

With Config

For a more robust setup, you can configure the gem with your API keys, for example in an openai.rb initializer file. Never hardcode secrets into your codebase - instead use something like dotenv to pass the keys safely into your environments.

ruby
OpenAI.configure do |config|
  config.access_token = ENV.fetch("OPENAI_ACCESS_TOKEN")
  config.admin_token = ENV.fetch("OPENAI_ADMIN_TOKEN") # Optional, used for admin endpoints, created here: https://platform.openai.com/settings/organization/admin-keys
  config.organization_id = ENV.fetch("OPENAI_ORGANIZATION_ID") # Optional
  config.log_errors = true # Highly recommended in development, so you can see what errors OpenAI is returning. Not recommended in production because it could leak private data to your logs.
end

Then you can create a client like this:

ruby
client = OpenAI::Client.new

You can still override the config defaults when making new clients; any options not included will fall back to any global config set with OpenAI.configure. e.g. in this example the organization_id, request_timeout, etc. will fallback to any set globally using OpenAI.configure, with only the access_token and admin_token overridden:

ruby
client = OpenAI::Client.new(access_token: "access_token_goes_here", admin_token: "admin_token_goes_here")

Custom timeout or base URI

  • The default timeout for any request using this library is 120 seconds. You can change that by passing a number of seconds to the request_timeout when initializing the client.
  • You can also change the base URI used for all requests, eg. to use observability tools like Helicone or Velvet
  • You can also add arbitrary other headers e.g. for openai-caching-proxy-worker, eg.:
…

or when configuring the gem:

…

Extra Headers per Client

You can dynamically pass headers per client object, which will be merged with any headers set globally with OpenAI.configure:

ruby
client = OpenAI::Client.new(access_token: "access_token_goes_here")
client.add_headers("X-Proxy-TTL" => "43200")

Logging

Errors

By default, ruby-openai does not log any Faraday::Errors encountered while executing a network request to avoid leaking data (e.g. 400s, 500s, SSL errors and more - see here for a complete list of subclasses of Faraday::Error and what can cause them).

If you would like to enable this functionality, you can set log_errors to true when configuring the client:

ruby
client = OpenAI::Client.new(log_errors: true)
Faraday middleware

You can pass Faraday middleware to the client in a block, eg:

  • To enable verbose logging with Ruby's Logger:
ruby
client = OpenAI::Client.new do |f|
  f.response :logger, Logger.new($stdout), bodies: true
end
  • To add a web debugging proxy like Charles:
ruby
  client = OpenAI::Client.new do |f|
    f.proxy = { uri: "http://localhost:8888" }
  end

Azure

To use the Azure OpenAI Service API, you can configure the gem like this:

ruby
OpenAI.configure do |config|
  config.access_token = ENV.fetch("AZURE_OPENAI_API_KEY")
  config.uri_base = ENV.fetch("AZURE_OPENAI_URI")
  config.api_type = :azure
  config.api_version = "2023-03-15-preview"
end

where AZURE_OPENAI_URI is e.g. https://custom-domain.openai.azure.com/openai/deployments/gpt-35-turbo

Deepseek

Deepseek is compatible with the OpenAI chat API. Get an access token from here, then:

ruby
client = OpenAI::Client.new(
  access_token: "deepseek_access_token_goes_here",
  uri_base: "https://api.deepseek.com/"
)

client.chat(
  parameters: {
    model: "deepseek-chat", # Required.
    messages: [{ role: "user", content: "Hello!"}], # Required.
    temperature: 0.7,
    stream: proc do |chunk, _event|
     print chunk.dig("choices", 0, "delta", "content")
    end
  }
)

Ollama

Ollama allows you to run open-source LLMs, such as Llama 3, locally. It offers chat compatibility with the OpenAI API.

You can download Ollama here. On macOS you can install and run Ollama like this:

bash
brew install ollama
ollama serve
ollama pull llama3:latest # In new terminal tab.

Create a client using your Ollama server and the pulled model, and stream a conversation for free:

ruby
client = OpenAI::Client.new(
  uri_base: "http://localhost:11434"
)

client.chat(
  parameters: {
    model: "llama3", # Required.
    messages: [{ role: "user", content: "Hello!"}], # Required.
    temperature: 0.7,
    stream: proc do |chunk, _event|
      print chunk.dig("choices", 0, "delta", "content")
    end
  }
)

# => Hi! It's nice to meet you. Is there something I can help you with, or would you like to chat?

Groq

Groq API Chat is broadly compatible with the OpenAI API, with a few minor differences. Get an access token from here, then:

ruby
client = OpenAI::Client.new(
  access_token: "groq_access_token_goes_here",
  uri_base: "https://api.groq.com/openai"
)

client.chat(
  parameters: {
    model: "llama3-8b-8192", # Required.
    messages: [{ role: "user", content: "Hello!"}], # Required.
    temperature: 0.7,
    stream: proc do |chunk, _event|
     print chunk.dig("choices", 0, "delta", "content")
    end
  }
)

Gemini

Gemini API Chat is also broadly compatible with the OpenAI API, and currently in beta. Get an access token from here, then:

ruby
client = OpenAI::Client.new(
  access_token: "gemini_access_token_goes_here",
  uri_base: "https://generativelanguage.googleapis.com/v1beta/openai/"
)

client.chat(
  parameters: {
    model: "gemini-1.5-flash", # Required.
    messages: [{ role: "user", content: "Hello!"}], # Required.
    temperature: 0.7,
    stream: proc do |chunk, _bytesize|
     print chunk.dig("choices", 0, "delta", "content")
    end
  }
)

# => Hello there! How can I help you today?

Counting Tokens

OpenAI parses prompt text into tokens, which are words or portions of words. (These tokens are unrelated to your API access_token.) Counting tokens can help you estimate your costs. It can also help you ensure your prompt text size is within the max-token limit

Issues· 55 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyaiapi-clientchatgptdall-e

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架