OpenAI API + Ruby! ❤️ GPT-5 & Realtime WebRTC compatible!
OpenAI API + Ruby! ❤️ GPT-5 & Realtime WebRTC compatible!
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!
Add this line to your application's Gemfile:
gem "ruby-openai"And then execute:
bundle installOr install with:
gem install ruby-openaiand require with:
require "openai"For a quick test you can pass your token directly to a new client:
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.
)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.
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.
endThen you can create a client like this:
client = OpenAI::Client.newYou 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:
client = OpenAI::Client.new(access_token: "access_token_goes_here", admin_token: "admin_token_goes_here")request_timeout when initializing the client.…or when configuring the gem:
…You can dynamically pass headers per client object, which will be merged with any headers set globally with OpenAI.configure:
client = OpenAI::Client.new(access_token: "access_token_goes_here")
client.add_headers("X-Proxy-TTL" => "43200")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:
client = OpenAI::Client.new(log_errors: true)You can pass Faraday middleware to the client in a block, eg:
client = OpenAI::Client.new do |f|
f.response :logger, Logger.new($stdout), bodies: true
end client = OpenAI::Client.new do |f|
f.proxy = { uri: "http://localhost:8888" }
endTo use the Azure OpenAI Service API, you can configure the gem like this:
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"
endwhere AZURE_OPENAI_URI is e.g. https://custom-domain.openai.azure.com/openai/deployments/gpt-35-turbo
Deepseek is compatible with the OpenAI chat API. Get an access token from here, then:
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 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:
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:
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 API Chat is broadly compatible with the OpenAI API, with a few minor differences. Get an access token from here, then:
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 API Chat is also broadly compatible with the OpenAI API, and currently in beta. Get an access token from here, then:
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?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
No open issues yet, or sync has not completed.