[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-7865":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":16,"stars30d":17,"stars90d":16,"forks30d":16,"starsTrendScore":16,"compositeScore":18,"rankGlobal":10,"rankLanguage":10,"license":19,"archived":20,"fork":20,"defaultBranch":21,"hasWiki":22,"hasPages":20,"topics":23,"createdAt":10,"pushedAt":10,"updatedAt":35,"readmeContent":36,"aiSummary":37,"trendingCount":16,"starSnapshotCount":16,"syncStatus":38,"lastSyncTime":39,"discoverSource":40},7865,"ruby-openai","alexrudall\u002Fruby-openai","alexrudall","OpenAI API + Ruby! 🤖❤️ GPT-5 & Realtime WebRTC compatible!","https:\u002F\u002Finsertrobot.com",null,"Ruby",3224,384,39,29,0,7,60.46,"MIT License",false,"main",true,[24,25,26,27,28,29,30,31,32,33,34],"ai","api-client","chatgpt","dall-e","gpt-4","gpt-4o","o1","openai","rails","ruby","whisper","2026-06-12 04:00:36","# Ruby OpenAI\n\n[![Gem Version](https:\u002F\u002Fimg.shields.io\u002Fgem\u002Fv\u002Fruby-openai.svg)](https:\u002F\u002Frubygems.org\u002Fgems\u002Fruby-openai)\n[![GitHub license](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Flicense-MIT-blue.svg)](https:\u002F\u002Fgithub.com\u002Falexrudall\u002Fruby-openai\u002Fblob\u002Fmain\u002FLICENSE.txt)\n[![CircleCI Build Status](https:\u002F\u002Fcircleci.com\u002Fgh\u002Falexrudall\u002Fruby-openai.svg?style=shield)](https:\u002F\u002Fcircleci.com\u002Fgh\u002Falexrudall\u002Fruby-openai)\n\nUse the [OpenAI API](https:\u002F\u002Fopenai.com\u002Fblog\u002Fopenai-api\u002F) with Ruby! 🤖❤️\n\nStream GPT-5 chats with the Responses API, initiate Realtime WebRTC conversations, and much more...\n\n**Sponsors**\n\n\u003Ctable>\n\u003Ctr>\n\u003Ctd width=\"300\" align=\"center\" valign=\"top\">\n\n[\u003Cimg src=\"https:\u002F\u002Fgithub.com\u002Fuser-attachments\u002Fassets\u002Fb97e036d-3f22-4116-be97-8f8d1c432a4f\" alt=\"InferToGo logo: man in suit falling, black and white\" width=\"300\" height=\"300\">](https:\u002F\u002Finfertogo.com\u002F?utm_source=ruby-openai)\n\n\u003Csub>_[InferToGo](https:\u002F\u002Finfertogo.com\u002F?utm_source=ruby-openai) - The inference addon for your PaaS application._\u003C\u002Fsub>\n\n\u003C\u002Ftd>\n\u003Ctd width=\"300\" align=\"center\" valign=\"top\">\n\n[\u003Cimg src=\"https:\u002F\u002Fgithub.com\u002Fuser-attachments\u002Fassets\u002F3feb834c-2721-404c-a64d-02104ed4aba7\" alt=\"SerpApi logo: Purple rounded square with 4 connected white holes\" width=\"300\" height=\"300\">](https:\u002F\u002Fserpapi.com\u002F?utm_source=ruby-openai)\n\n\u003Csub>_[SerpApi - Search API](https:\u002F\u002Fserpapi.com\u002F?utm_source=ruby-openai) - Enhance your LLM's knowledge with data from search engines like Google and Bing using our simple API._\u003C\u002Fsub>\n\n\u003C\u002Ftd>\n\u003C\u002Ftr>\n\u003C\u002Ftable>\n\n[🎮 Ruby AI Builders Discord](https:\u002F\u002Fdiscord.gg\u002Fk4Uc224xVD) | [🐦 X](https:\u002F\u002Fx.com\u002Falexrudall) | [🧠 Anthropic Gem](https:\u002F\u002Fgithub.com\u002Falexrudall\u002Fanthropic) | [🚂 Midjourney Gem](https:\u002F\u002Fgithub.com\u002Falexrudall\u002Fmidjourney) |  [♥️ Thanks to all sponsors!](https:\u002F\u002Fgithub.com\u002Fsponsors\u002Falexrudall)\n\n## Contents\n\n- [Ruby OpenAI](#ruby-openai)\n  - [Contents](#contents)\n  - [Project Policies](#project-policies)\n  - [Installation](#installation)\n    - [Bundler](#bundler)\n    - [Gem install](#gem-install)\n  - [How to use](#how-to-use)\n    - [Quickstart](#quickstart)\n    - [With Config](#with-config)\n      - [Custom timeout or base URI](#custom-timeout-or-base-uri)\n      - [Extra Headers per Client](#extra-headers-per-client)\n      - [Logging](#logging)\n        - [Errors](#errors)\n        - [Faraday middleware](#faraday-middleware)\n      - [Azure](#azure)\n      - [Deepseek](#deepseek)\n      - [Ollama](#ollama)\n      - [Groq](#groq)\n      - [Gemini](#gemini)\n    - [Counting Tokens](#counting-tokens)\n    - [Models](#models)\n    - [Chat](#chat)\n      - [Streaming Chat](#streaming-chat)\n      - [Vision](#vision)\n      - [JSON Mode](#json-mode)\n    - [Responses API](#responses-api)\n      - [Create a Response](#create-a-response)\n      - [Follow-up Messages](#follow-up-messages)\n      - [Tool Calls](#tool-calls)\n      - [Streaming](#streaming)\n      - [Retrieve a Response](#retrieve-a-response)\n      - [Delete a Response](#delete-a-response)\n      - [List Input Items](#list-input-items)\n    - [Functions](#functions)\n    - [Completions](#completions)\n    - [Embeddings](#embeddings)\n    - [Batches](#batches)\n    - [Files](#files)\n      - [For fine-tuning purposes](#for-fine-tuning-purposes)\n      - [For assistant purposes](#for-assistant-purposes)\n    - [Finetunes](#finetunes)\n    - [Vector Stores](#vector-stores)\n    - [Vector Store Files](#vector-store-files)\n    - [Vector Store File Batches](#vector-store-file-batches)\n    - [Conversations](#conversations)\n    - [Assistants](#assistants)\n    - [Threads and Messages](#threads-and-messages)\n    - [Runs](#runs)\n      - [Create and Run](#create-and-run)\n      - [Vision in a thread](#vision-in-a-thread)\n      - [Runs involving function tools](#runs-involving-function-tools)\n      - [Exploring chunks used in File Search](#exploring-chunks-used-in-file-search)\n    - [Image Generation](#image-generation)\n      - [DALL·E 2](#dalle-2)\n      - [DALL·E 3](#dalle-3)\n    - [Image Edit](#image-edit)\n    - [Image Variations](#image-variations)\n    - [Moderations](#moderations)\n    - [Whisper](#whisper)\n      - [Translate](#translate)\n      - [Transcribe](#transcribe)\n      - [Speech](#speech)\n    - [Real-Time](#real-time)\n    - [Usage](#usage)\n    - [Errors](#errors-1)\n  - [Development](#development)\n    - [To check for deprecations](#to-check-for-deprecations)\n  - [Release](#release)\n  - [Contributing](#contributing)\n  - [License](#license)\n  - [Code of Conduct](#code-of-conduct)\n\n## Project Policies\n\n- [Security policy](SECURITY.md)\n- [Support and end-of-life policy](SUPPORT.md)\n- [Migration guides](MIGRATION.md)\n- [Changelog](CHANGELOG.md)\n\n## Installation\n\n### Bundler\n\nAdd this line to your application's Gemfile:\n\n```ruby\ngem \"ruby-openai\"\n```\n\nAnd then execute:\n\n```bash\nbundle install\n```\n\n### Gem install\n\nOr install with:\n\n```bash\ngem install ruby-openai\n```\n\nand require with:\n\n```ruby\nrequire \"openai\"\n```\n\n## How to use\n\n- Get your API key from [https:\u002F\u002Fplatform.openai.com\u002Faccount\u002Fapi-keys](https:\u002F\u002Fplatform.openai.com\u002Faccount\u002Fapi-keys)\n- If you belong to multiple organizations, you can get your Organization ID from [https:\u002F\u002Fplatform.openai.com\u002Faccount\u002Forg-settings](https:\u002F\u002Fplatform.openai.com\u002Faccount\u002Forg-settings)\n\n### Quickstart\n\nFor a quick test you can pass your token directly to a new client:\n\n```ruby\nclient = OpenAI::Client.new(\n  access_token: \"access_token_goes_here\",\n  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.\n)\n```\n\n### With Config\n\nFor 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](https:\u002F\u002Fgithub.com\u002Fmotdotla\u002Fdotenv) to pass the keys safely into your environments.\n\n```ruby\nOpenAI.configure do |config|\n  config.access_token = ENV.fetch(\"OPENAI_ACCESS_TOKEN\")\n  config.admin_token = ENV.fetch(\"OPENAI_ADMIN_TOKEN\") # Optional, used for admin endpoints, created here: https:\u002F\u002Fplatform.openai.com\u002Fsettings\u002Forganization\u002Fadmin-keys\n  config.organization_id = ENV.fetch(\"OPENAI_ORGANIZATION_ID\") # Optional\n  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.\nend\n```\n\nThen you can create a client like this:\n\n```ruby\nclient = OpenAI::Client.new\n```\n\nYou 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:\n\n```ruby\nclient = OpenAI::Client.new(access_token: \"access_token_goes_here\", admin_token: \"admin_token_goes_here\")\n```\n\n#### Custom timeout or base URI\n\n- 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.\n- You can also change the base URI used for all requests, eg. to use observability tools like [Helicone](https:\u002F\u002Fdocs.helicone.ai\u002Fquickstart\u002Fintegrate-in-one-line-of-code) or [Velvet](https:\u002F\u002Fdocs.usevelvet.com\u002Fdocs\u002Fgetting-started)\n- You can also add arbitrary other headers e.g. for [openai-caching-proxy-worker](https:\u002F\u002Fgithub.com\u002F6\u002Fopenai-caching-proxy-worker), eg.:\n\n```ruby\nclient = OpenAI::Client.new(\n  access_token: \"access_token_goes_here\",\n  uri_base: \"https:\u002F\u002Foai.hconeai.com\u002F\",\n  request_timeout: 240,\n  extra_headers: {\n    \"X-Proxy-TTL\" => \"43200\", # For https:\u002F\u002Fgithub.com\u002F6\u002Fopenai-caching-proxy-worker#specifying-a-cache-ttl\n    \"X-Proxy-Refresh\": \"true\", # For https:\u002F\u002Fgithub.com\u002F6\u002Fopenai-caching-proxy-worker#refreshing-the-cache\n    \"Helicone-Auth\": \"Bearer HELICONE_API_KEY\", # For https:\u002F\u002Fdocs.helicone.ai\u002Fgetting-started\u002Fintegration-method\u002Fopenai-proxy\n    \"helicone-stream-force-format\" => \"true\", # Use this with Helicone otherwise streaming drops chunks # https:\u002F\u002Fgithub.com\u002Falexrudall\u002Fruby-openai\u002Fissues\u002F251\n  }\n)\n```\n\nor when configuring the gem:\n\n```ruby\nOpenAI.configure do |config|\n  config.access_token = ENV.fetch(\"OPENAI_ACCESS_TOKEN\")\n  config.admin_token = ENV.fetch(\"OPENAI_ADMIN_TOKEN\") # Optional, used for admin endpoints, created here: https:\u002F\u002Fplatform.openai.com\u002Fsettings\u002Forganization\u002Fadmin-keys\n  config.organization_id = ENV.fetch(\"OPENAI_ORGANIZATION_ID\") # Optional\n  config.log_errors = true # Optional\n  config.uri_base = \"https:\u002F\u002Foai.hconeai.com\u002F\" # Optional\n  config.request_timeout = 240 # Optional\n  config.extra_headers = {\n    \"X-Proxy-TTL\" => \"43200\", # For https:\u002F\u002Fgithub.com\u002F6\u002Fopenai-caching-proxy-worker#specifying-a-cache-ttl\n    \"X-Proxy-Refresh\": \"true\", # For https:\u002F\u002Fgithub.com\u002F6\u002Fopenai-caching-proxy-worker#refreshing-the-cache\n    \"Helicone-Auth\": \"Bearer HELICONE_API_KEY\" # For https:\u002F\u002Fdocs.helicone.ai\u002Fgetting-started\u002Fintegration-method\u002Fopenai-proxy\n  } # Optional\nend\n```\n\n#### Extra Headers per Client\n\nYou can dynamically pass headers per client object, which will be merged with any headers set globally with OpenAI.configure:\n\n```ruby\nclient = OpenAI::Client.new(access_token: \"access_token_goes_here\")\nclient.add_headers(\"X-Proxy-TTL\" => \"43200\")\n```\n\n#### Logging\n\n##### Errors\n\nBy default, `ruby-openai` does not log any `Faraday::Error`s encountered while executing a network request to avoid leaking data (e.g. 400s, 500s, SSL errors and more - see [here](https:\u002F\u002Fwww.rubydoc.info\u002Fgithub\u002Flostisland\u002Ffaraday\u002FFaraday\u002FError) for a complete list of subclasses of `Faraday::Error` and what can cause them).\n\nIf you would like to enable this functionality, you can set `log_errors` to `true` when configuring the client:\n\n```ruby\nclient = OpenAI::Client.new(log_errors: true)\n```\n\n##### Faraday middleware\n\nYou can pass [Faraday middleware](https:\u002F\u002Flostisland.github.io\u002Ffaraday\u002F#\u002Fmiddleware\u002Findex) to the client in a block, eg:\n\n- To enable verbose logging with Ruby's [Logger](https:\u002F\u002Fruby-doc.org\u002F3.2.2\u002Fstdlibs\u002Flogger\u002FLogger.html):\n\n```ruby\nclient = OpenAI::Client.new do |f|\n  f.response :logger, Logger.new($stdout), bodies: true\nend\n```\n\n- To add a web debugging proxy like [Charles](https:\u002F\u002Fwww.charlesproxy.com\u002Fdocumentation\u002Fwelcome\u002F):\n\n```ruby\n  client = OpenAI::Client.new do |f|\n    f.proxy = { uri: \"http:\u002F\u002Flocalhost:8888\" }\n  end\n```\n#### Azure\n\nTo use the [Azure OpenAI Service](https:\u002F\u002Flearn.microsoft.com\u002Fen-us\u002Fazure\u002Fcognitive-services\u002Fopenai\u002F) API, you can configure the gem like this:\n\n```ruby\nOpenAI.configure do |config|\n  config.access_token = ENV.fetch(\"AZURE_OPENAI_API_KEY\")\n  config.uri_base = ENV.fetch(\"AZURE_OPENAI_URI\")\n  config.api_type = :azure\n  config.api_version = \"2023-03-15-preview\"\nend\n```\n\nwhere `AZURE_OPENAI_URI` is e.g. `https:\u002F\u002Fcustom-domain.openai.azure.com\u002Fopenai\u002Fdeployments\u002Fgpt-35-turbo`\n\n#### Deepseek\n\n[Deepseek](https:\u002F\u002Fapi-docs.deepseek.com\u002F) is compatible with the OpenAI chat API. Get an access token from [here](https:\u002F\u002Fplatform.deepseek.com\u002Fapi_keys), then:\n\n```ruby\nclient = OpenAI::Client.new(\n  access_token: \"deepseek_access_token_goes_here\",\n  uri_base: \"https:\u002F\u002Fapi.deepseek.com\u002F\"\n)\n\nclient.chat(\n  parameters: {\n    model: \"deepseek-chat\", # Required.\n    messages: [{ role: \"user\", content: \"Hello!\"}], # Required.\n    temperature: 0.7,\n    stream: proc do |chunk, _event|\n     print chunk.dig(\"choices\", 0, \"delta\", \"content\")\n    end\n  }\n)\n```\n\n#### Ollama\n\nOllama allows you to run open-source LLMs, such as Llama 3, locally. It [offers chat compatibility](https:\u002F\u002Fgithub.com\u002Follama\u002Follama\u002Fblob\u002Fmain\u002Fdocs\u002Fopenai.md) with the OpenAI API.\n\nYou can download Ollama [here](https:\u002F\u002Follama.com\u002F). On macOS you can install and run Ollama like this:\n\n```bash\nbrew install ollama\nollama serve\nollama pull llama3:latest # In new terminal tab.\n```\n\nCreate a client using your Ollama server and the pulled model, and stream a conversation for free:\n\n```ruby\nclient = OpenAI::Client.new(\n  uri_base: \"http:\u002F\u002Flocalhost:11434\"\n)\n\nclient.chat(\n  parameters: {\n    model: \"llama3\", # Required.\n    messages: [{ role: \"user\", content: \"Hello!\"}], # Required.\n    temperature: 0.7,\n    stream: proc do |chunk, _event|\n      print chunk.dig(\"choices\", 0, \"delta\", \"content\")\n    end\n  }\n)\n\n# => Hi! It's nice to meet you. Is there something I can help you with, or would you like to chat?\n```\n\n#### Groq\n\n[Groq API Chat](https:\u002F\u002Fconsole.groq.com\u002Fdocs\u002Fquickstart) is broadly compatible with the OpenAI API, with a [few minor differences](https:\u002F\u002Fconsole.groq.com\u002Fdocs\u002Fopenai). Get an access token from [here](https:\u002F\u002Fconsole.groq.com\u002Fkeys), then:\n\n```ruby\nclient = OpenAI::Client.new(\n  access_token: \"groq_access_token_goes_here\",\n  uri_base: \"https:\u002F\u002Fapi.groq.com\u002Fopenai\"\n)\n\nclient.chat(\n  parameters: {\n    model: \"llama3-8b-8192\", # Required.\n    messages: [{ role: \"user\", content: \"Hello!\"}], # Required.\n    temperature: 0.7,\n    stream: proc do |chunk, _event|\n     print chunk.dig(\"choices\", 0, \"delta\", \"content\")\n    end\n  }\n)\n```\n\n#### Gemini\n\n[Gemini API Chat](https:\u002F\u002Fai.google.dev\u002Fgemini-api\u002Fdocs\u002Fopenai) is also broadly compatible with the OpenAI API, and [currently in beta](https:\u002F\u002Fai.google.dev\u002Fgemini-api\u002Fdocs\u002Fopenai#current-limitations). Get an access token from [here](https:\u002F\u002Faistudio.google.com\u002Fapp\u002Fapikey), then:\n\n```ruby\nclient = OpenAI::Client.new(\n  access_token: \"gemini_access_token_goes_here\",\n  uri_base: \"https:\u002F\u002Fgenerativelanguage.googleapis.com\u002Fv1beta\u002Fopenai\u002F\"\n)\n\nclient.chat(\n  parameters: {\n    model: \"gemini-1.5-flash\", # Required.\n    messages: [{ role: \"user\", content: \"Hello!\"}], # Required.\n    temperature: 0.7,\n    stream: proc do |chunk, _bytesize|\n     print chunk.dig(\"choices\", 0, \"delta\", \"content\")\n    end\n  }\n)\n\n# => Hello there! How can I help you today?\n```\n\n### Counting Tokens\n\nOpenAI parses prompt text into [tokens](https:\u002F\u002Fhelp.openai.com\u002Fen\u002Farticles\u002F4936856-what-are-tokens-and-how-to-count-them), which are words or portions of words. (These tokens are unrelated to your API access_token.) Counting tokens can help you estimate your [costs](https:\u002F\u002Fopenai.com\u002Fpricing). It can also help you ensure your prompt text size is within the max-token limits of your model's context window, and choose an appropriate [`max_tokens`](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat\u002Fcreate#chat\u002Fcreate-max_tokens) completion parameter so your response will fit as well.\n\nTo estimate the token-count of your text:\n\n```ruby\nOpenAI.rough_token_count(\"Your text\")\n```\n\nIf you need a more accurate count, try [tiktoken_ruby](https:\u002F\u002Fgithub.com\u002FIAPark\u002Ftiktoken_ruby).\n\n### Models\n\nThere are different models that can be used to generate text. For a full list and to retrieve information about a single model:\n\n```ruby\nclient.models.list\nclient.models.retrieve(id: \"gpt-4o\")\n```\n\nYou can also delete any finetuned model you generated, if you're an account Owner on your OpenAI organization:\n\n```ruby\nclient.models.delete(id: \"ft:gpt-4o-mini:acemeco:suffix:abc123\")\n```\n\n### Chat\n\nGPT is a model that can be used to generate text in a conversational style. You can use it to [generate a response](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat\u002Fcreate) to a sequence of [messages](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Fchat\u002Fintroduction):\n\n```ruby\nresponse = client.chat(\n  parameters: {\n    model: \"gpt-4o\", # Required.\n    messages: [{ role: \"user\", content: \"Hello!\"}], # Required.\n    temperature: 0.7,\n  }\n)\nputs response.dig(\"choices\", 0, \"message\", \"content\")\n# => \"Hello! How may I assist you today?\"\n```\n\n#### Streaming Chat\n\n[Quick guide to streaming Chat with Rails 7 and Hotwire](https:\u002F\u002Fgist.github.com\u002Falexrudall\u002Fcb5ee1e109353ef358adb4e66631799d)\n\nYou can stream from the API in realtime, which can be much faster and used to create a more engaging user experience. Pass a [Proc](https:\u002F\u002Fruby-doc.org\u002Fcore-2.6\u002FProc.html) (or any object with a `#call` method) to the `stream` parameter to receive the stream of completion chunks as they are generated. Each time one or more chunks is received, the proc will be called once with each chunk, parsed as a Hash. If OpenAI returns an error, `ruby-openai` will raise a Faraday error.\n\n```ruby\nclient.chat(\n  parameters: {\n    model: \"gpt-4o\", # Required.\n    messages: [{ role: \"user\", content: \"Describe a character called Anna!\"}], # Required.\n    temperature: 0.7,\n    stream: proc do |chunk, _event|\n      print chunk.dig(\"choices\", 0, \"delta\", \"content\")\n    end\n  }\n)\n# => \"Anna is a young woman in her mid-twenties, with wavy chestnut hair that falls to her shoulders...\"\n```\n\nNote: In order to get usage information, you can provide the [`stream_options` parameter](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat\u002Fcreate#chat-create-stream_options) and OpenAI will provide a final chunk with the usage. Here is an example:\n\n```ruby\nstream_proc = proc { |chunk, _bytesize| puts \"--------------\"; puts chunk.inspect; }\nclient.chat(\n  parameters: {\n    model: \"gpt-4o\",\n    stream: stream_proc,\n    stream_options: { include_usage: true },\n    messages: [{ role: \"user\", content: \"Hello!\"}],\n  }\n)\n# => --------------\n# => {\"id\"=>\"chatcmpl-7bbq05PiZqlHxjV1j7OHnKKDURKaf\", \"object\"=>\"chat.completion.chunk\", \"created\"=>1718750612, \"model\"=>\"gpt-4o-2024-05-13\", \"system_fingerprint\"=>\"fp_9cb5d38cf7\", \"choices\"=>[{\"index\"=>0, \"delta\"=>{\"role\"=>\"assistant\", \"content\"=>\"\"}, \"logprobs\"=>nil, \"finish_reason\"=>nil}], \"usage\"=>nil}\n# => --------------\n# => {\"id\"=>\"chatcmpl-7bbq05PiZqlHxjV1j7OHnKKDURKaf\", \"object\"=>\"chat.completion.chunk\", \"created\"=>1718750612, \"model\"=>\"gpt-4o-2024-05-13\", \"system_fingerprint\"=>\"fp_9cb5d38cf7\", \"choices\"=>[{\"index\"=>0, \"delta\"=>{\"content\"=>\"Hello\"}, \"logprobs\"=>nil, \"finish_reason\"=>nil}], \"usage\"=>nil}\n# => --------------\n# => ... more content chunks\n# => --------------\n# => {\"id\"=>\"chatcmpl-7bbq05PiZqlHxjV1j7OHnKKDURKaf\", \"object\"=>\"chat.completion.chunk\", \"created\"=>1718750612, \"model\"=>\"gpt-4o-2024-05-13\", \"system_fingerprint\"=>\"fp_9cb5d38cf7\", \"choices\"=>[{\"index\"=>0, \"delta\"=>{}, \"logprobs\"=>nil, \"finish_reason\"=>\"stop\"}], \"usage\"=>nil}\n# => --------------\n# => {\"id\"=>\"chatcmpl-7bbq05PiZqlHxjV1j7OHnKKDURKaf\", \"object\"=>\"chat.completion.chunk\", \"created\"=>1718750612, \"model\"=>\"gpt-4o-2024-05-13\", \"system_fingerprint\"=>\"fp_9cb5d38cf7\", \"choices\"=>[], \"usage\"=>{\"prompt_tokens\"=>9, \"completion_tokens\"=>9, \"total_tokens\"=>18}}\n```\n\n#### Vision\n\nYou can use the GPT-4 Vision model to generate a description of an image:\n\n```ruby\nmessages = [\n  { \"type\": \"text\", \"text\": \"What’s in this image?\"},\n  { \"type\": \"image_url\",\n    \"image_url\": {\n      \"url\": \"https:\u002F\u002Fupload.wikimedia.org\u002Fwikipedia\u002Fcommons\u002Fthumb\u002Fd\u002Fdd\u002FGfp-wisconsin-madison-the-nature-boardwalk.jpg\u002F2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg\",\n    },\n  }\n]\nresponse = client.chat(\n  parameters: {\n    model: \"gpt-4-vision-preview\", # Required.\n    messages: [{ role: \"user\", content: messages}], # Required.\n  }\n)\nputs response.dig(\"choices\", 0, \"message\", \"content\")\n# => \"The image depicts a serene natural landscape featuring a long wooden boardwalk extending straight ahead\"\n```\n\n#### JSON Mode\n\nYou can set the response_format to ask for responses in JSON:\n\n```ruby\nresponse = client.chat(\n  parameters: {\n    model: \"gpt-4o\",\n    response_format: { type: \"json_object\" },\n    messages: [{ role: \"user\", content: \"Hello! Give me some JSON please.\"}],\n    temperature: 0.7,\n  })\n  puts response.dig(\"choices\", 0, \"message\", \"content\")\n  # =>\n  # {\n  #   \"name\": \"John\",\n  #   \"age\": 30,\n  #   \"city\": \"New York\",\n  #   \"hobbies\": [\"reading\", \"traveling\", \"hiking\"],\n  #   \"isStudent\": false\n  # }\n```\n\nYou can stream it as well!\n\n```ruby\n  response = client.chat(\n    parameters: {\n      model: \"gpt-4o\",\n      messages: [{ role: \"user\", content: \"Can I have some JSON please?\"}],\n      response_format: { type: \"json_object\" },\n      stream: proc do |chunk, _event|\n        print chunk.dig(\"choices\", 0, \"delta\", \"content\")\n      end\n    }\n  )\n  # =>\n  # {\n  #   \"message\": \"Sure, please let me know what specific JSON data you are looking for.\",\n  #   \"JSON_data\": {\n  #     \"example_1\": {\n  #       \"key_1\": \"value_1\",\n  #       \"key_2\": \"value_2\",\n  #       \"key_3\": \"value_3\"\n  #     },\n  #     \"example_2\": {\n  #       \"key_4\": \"value_4\",\n  #       \"key_5\": \"value_5\",\n  #       \"key_6\": \"value_6\"\n  #     }\n  #   }\n  # }\n```\n\n### Responses API\n\n[OpenAI's most advanced interface for generating model responses](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fresponses). Supports text and image inputs, and text outputs. Create stateful interactions with the model, using the output of previous responses as input. Extend the model's capabilities with built-in tools for file search, web search, computer use, and more. Allow the model access to external systems and data using function calling.\n\n#### Create a Response\n\n```ruby\nresponse = client.responses.create(parameters: {\n  model: \"gpt-5\",\n  input: \"Hello! I'm Szymon!\",\n  reasoning: {\n    \"effort\": \"minimal\"\n  }\n})\nputs response.dig(\"output\", 0, \"content\", 0, \"text\")\n# => Thinking about how to answer this...\nputs response.dig(\"output\", 1, \"content\", 0, \"text\")\n# => Hi Szymon! Great to meet you. How can I help today?\n```\n\n#### Follow-up Messages\n\n```ruby\nfollowup = client.responses.create(parameters: {\n  model: \"gpt-4o\",\n  input: \"Remind me, what is my name?\",\n  previous_response_id: response[\"id\"]\n})\nputs followup.dig(\"output\", 0, \"content\", 0, \"text\")\n# => Your name is Szymon! How can I help you today?\n```\n\n#### Tool Calls\n\n```ruby\nresponse = client.responses.create(parameters: {\n  model: \"gpt-4o\",\n  input: \"What's the weather in Paris?\",\n  tools: [\n    {\n      \"type\" => \"function\",\n      \"name\" => \"get_current_weather\",\n      \"description\" => \"Get the current weather in a given location\",\n      \"parameters\" => {\n        \"type\" => \"object\",\n        \"properties\" => {\n          \"location\" => {\n            \"type\" => \"string\",\n            \"description\" => \"The geographic location to get the weather for\"\n          }\n        },\n        \"required\" => [\"location\"]\n      }\n    }\n  ]\n})\nputs response.dig(\"output\", 0, \"name\")\n# => \"get_current_weather\"\n```\n\n#### Streaming\n\n```ruby\nclient.responses.create(\n  parameters: {\n    model: \"gpt-4o\", # Required.\n    input: \"Hello!\", # Required.\n    stream: proc do |chunk, _event|\n      if chunk[\"type\"] == \"response.output_text.delta\"\n        print chunk[\"delta\"]\n        $stdout.flush  # Ensure output is displayed immediately\n      end\n    end\n  }\n)\n# => \"Hi there! How can I assist you today?...\"\n```\n\n#### Retrieve a Response\n\n```ruby\nretrieved_response = client.responses.retrieve(response_id: response[\"id\"])\nputs retrieved_response[\"object\"]\n# => \"response\"\n```\n\n#### Delete a Response\n\n```ruby\ndeletion = client.responses.delete(response_id: response[\"id\"])\nputs deletion[\"deleted\"]\n# => true\n```\n\n#### List Input Items\n\n```ruby\ninput_items = client.responses.input_items(response_id: response[\"id\"])\nputs input_items[\"object\"] # => \"list\"\n```\n\n### Functions\n\nYou can describe and pass in functions and the model will intelligently choose to output a JSON object containing arguments to call them - eg., to use your method `get_current_weather` to get the weather in a given location. Note that tool_choice is optional, but if you exclude it, the model will choose whether to use the function or not ([see here](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat\u002Fcreate#chat-create-tool_choice)).\n\n```ruby\ndef get_current_weather(location:, unit: \"fahrenheit\")\n  # Here you could use a weather api to fetch the weather.\n  \"The weather in #{location} is nice 🌞 #{unit}\"\nend\n\nmessages = [\n  {\n    \"role\": \"user\",\n    \"content\": \"What is the weather like in San Francisco?\",\n  },\n]\n\nresponse =\n  client.chat(\n    parameters: {\n      model: \"gpt-4o\",\n      messages: messages,  # Defined above because we'll use it again\n      tools: [\n        {\n          type: \"function\",\n          function: {\n            name: \"get_current_weather\",\n            description: \"Get the current weather in a given location\",\n            parameters: {  # Format: https:\u002F\u002Fjson-schema.org\u002Funderstanding-json-schema\n              type: :object,\n              properties: {\n                location: {\n                  type: :string,\n                  description: \"The city and state, e.g. San Francisco, CA\",\n                },\n                unit: {\n                  type: \"string\",\n                  enum: %w[celsius fahrenheit],\n                },\n              },\n              required: [\"location\"],\n            },\n          },\n        }\n      ],\n      # Optional, defaults to \"auto\"\n      # Can also put \"none\" or specific functions, see docs\n      tool_choice: \"required\"\n    },\n  )\n\nmessage = response.dig(\"choices\", 0, \"message\")\n\nif message[\"role\"] == \"assistant\" && message[\"tool_calls\"]\n  # For a subsequent message with the role \"tool\", OpenAI requires the preceding message to have a single tool_calls argument.\n  messages \u003C\u003C message\n\n  message[\"tool_calls\"].each do |tool_call|\n    tool_call_id = tool_call.dig(\"id\")\n    function_name = tool_call.dig(\"function\", \"name\")\n    function_args = JSON.parse(\n      tool_call.dig(\"function\", \"arguments\"),\n      { symbolize_names: true },\n    )\n    function_response =\n      case function_name\n      when \"get_current_weather\"\n        get_current_weather(**function_args)  # => \"The weather is nice 🌞\"\n      else\n        # decide how to handle\n      end\n\n    messages \u003C\u003C {\n      tool_call_id: tool_call_id,\n      role: \"tool\",\n      name: function_name,\n      content: function_response\n    }  # Extend the conversation with the results of the functions\n  end\n\n  second_response = client.chat(\n    parameters: {\n      model: \"gpt-4o\",\n      messages: messages\n    }\n  )\n\n  puts second_response.dig(\"choices\", 0, \"message\", \"content\")\n\n  # At this point, the model has decided to call functions, you've called the functions\n  # and provided the response back, and the model has considered this and responded.\nend\n# => \"It looks like the weather is nice and sunny in San Francisco! If you're planning to go out, it should be a pleasant day.\"\n```\n\n### Completions\n\nHit the OpenAI API for a completion using other GPT-3 models:\n\n```ruby\nresponse = client.completions(\n  parameters: {\n    model: \"gpt-4o\",\n    prompt: \"Once upon a time\",\n    max_tokens: 5\n  }\n)\nputs response[\"choices\"].map { |c| c[\"text\"] }\n# => [\", there lived a great\"]\n```\n\n### Embeddings\n\nYou can use the embeddings endpoint to get a vector of numbers representing an input. You can then compare these vectors for different inputs to efficiently check how similar the inputs are.\n\n```ruby\nresponse = client.embeddings(\n  parameters: {\n    model: \"text-embedding-ada-002\",\n    input: \"The food was delicious and the waiter...\"\n  }\n)\n\nputs response.dig(\"data\", 0, \"embedding\")\n# => Vector representation of your embedding\n```\n\n### Batches\n\nThe Batches endpoint allows you to create and manage large batches of API requests to run asynchronously. Currently, the supported endpoints for batches are `\u002Fv1\u002Fchat\u002Fcompletions` (Chat Completions API) and `\u002Fv1\u002Fembeddings` (Embeddings API).\n\nTo use the Batches endpoint, you need to first upload a JSONL file containing the batch requests using the Files endpoint. The file must be uploaded with the purpose set to `batch`. Each line in the JSONL file represents a single request and should have the following format:\n\n```json\n{\n  \"custom_id\": \"request-1\",\n  \"method\": \"POST\",\n  \"url\": \"\u002Fv1\u002Fchat\u002Fcompletions\",\n  \"body\": {\n    \"model\": \"gpt-4o\",\n    \"messages\": [\n      { \"role\": \"system\", \"content\": \"You are a helpful assistant.\" },\n      { \"role\": \"user\", \"content\": \"What is 2+2?\" }\n    ]\n  }\n}\n```\n\nOnce you have uploaded the JSONL file, you can create a new batch by providing the file ID, endpoint, and completion window:\n\n```ruby\nresponse = client.batches.create(\n  parameters: {\n    input_file_id: \"file-abc123\",\n    endpoint: \"\u002Fv1\u002Fchat\u002Fcompletions\",\n    completion_window: \"24h\"\n  }\n)\nbatch_id = response[\"id\"]\n```\n\nYou can retrieve information about a specific batch using its ID:\n\n```ruby\nbatch = client.batches.retrieve(id: batch_id)\n```\n\nTo cancel a batch that is in progress:\n\n```ruby\nclient.batches.cancel(id: batch_id)\n```\n\nYou can also list all the batches:\n\n```ruby\nclient.batches.list\n```\n\nOnce the batch[\"completed_at\"] is present, you can fetch the output or error files:\n\n```ruby\nbatch = client.batches.retrieve(id: batch_id)\noutput_file_id = batch[\"output_file_id\"]\noutput_response = client.files.content(id: output_file_id)\nerror_file_id = batch[\"error_file_id\"]\nerror_response = client.files.content(id: error_file_id)\n```\n\nThese files are in JSONL format, with each line representing the output or error for a single request. The lines can be in any order:\n\n```json\n{\n  \"id\": \"response-1\",\n  \"custom_id\": \"request-1\",\n  \"response\": {\n    \"id\": \"chatcmpl-abc123\",\n    \"object\": \"chat.completion\",\n    \"created\": 1677858242,\n    \"model\": \"gpt-4o\",\n    \"choices\": [\n      {\n        \"index\": 0,\n        \"message\": {\n          \"role\": \"assistant\",\n          \"content\": \"2+2 equals 4.\"\n        }\n      }\n    ]\n  }\n}\n```\n\nIf a request fails with a non-HTTP error, the error object will contain more information about the cause of the failure.\n\n### Files\n\n#### For fine-tuning purposes\n\nPut your data in a `.jsonl` file like this:\n\n```json\n{\"prompt\":\"Overjoyed with my new phone! ->\", \"completion\":\" positive\"}\n{\"prompt\":\"@lakers disappoint for a third straight night ->\", \"completion\":\" negative\"}\n```\n\nand pass the path (or a StringIO object) to `client.files.upload` to upload it to OpenAI, and then interact with it:\n\n```ruby\nclient.files.upload(parameters: { file: \"path\u002Fto\u002Fsentiment.jsonl\", purpose: \"fine-tune\" })\nclient.files.list\nclient.files.retrieve(id: \"file-123\")\nclient.files.content(id: \"file-123\")\nclient.files.delete(id: \"file-123\")\n```\n\n#### For assistant purposes\n\nYou can send a file path:\n\n```ruby\nclient.files.upload(parameters: { file: \"path\u002Fto\u002Ffile.pdf\", purpose: \"assistants\" })\n```\n\nor a File object\n\n```ruby\nmy_file = File.open(\"path\u002Fto\u002Ffile.pdf\", \"rb\")\nclient.files.upload(parameters: { file: my_file, purpose: \"assistants\" })\n```\n\nSee supported file types on [API documentation](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fassistants\u002Ftools\u002Ffile-search\u002Fsupported-files).\n\n### Finetunes\n\nUpload your fine-tuning data in a `.jsonl` file as above and get its ID:\n\n```ruby\nresponse = client.files.upload(parameters: { file: \"path\u002Fto\u002Fsarcasm.jsonl\", purpose: \"fine-tune\" })\nfile_id = JSON.parse(response.body)[\"id\"]\n```\n\nYou can then use this file ID to create a fine tuning job:\n\n```ruby\nresponse = client.finetunes.create(\n  parameters: {\n  training_file: file_id,\n  model: \"gpt-4o\"\n})\nfine_tune_id = response[\"id\"]\n```\n\nThat will give you the fine-tune ID. If you made a mistake you can cancel the fine-tune model before it is processed:\n\n```ruby\nclient.finetunes.cancel(id: fine_tune_id)\n```\n\nYou may need to wait a short time for processing to complete. Once processed, you can use list or retrieve to get the name of the fine-tuned model:\n\n```ruby\nclient.finetunes.list\nresponse = client.finetunes.retrieve(id: fine_tune_id)\nfine_tuned_model = response[\"fine_tuned_model\"]\n```\n\nThis fine-tuned model name can then be used in chat completions:\n\n```ruby\nresponse = client.chat(\n  parameters: {\n    model: fine_tuned_model,\n    messages: [{ role: \"user\", content: \"I love Mondays!\" }]\n  }\n)\nresponse.dig(\"choices\", 0, \"message\", \"content\")\n```\n\nYou can also capture the events for a job:\n\n```ruby\nclient.finetunes.list_events(id: fine_tune_id)\n```\n\nYou can also delete any finetuned model you generated, if you're an account Owner on your OpenAI organization:\n\n```ruby\nclient.models.delete(id: fine_tune_id)\n```\n\n### Vector Stores\n\nVector Store objects give the File Search tool the ability to search your files.\n\nYou can create a new vector store:\n\n```ruby\nresponse = client.vector_stores.create(\n  parameters: {\n    name: \"my vector store\",\n    file_ids: [\"file-abc123\", \"file-def456\"]\n  }\n)\n\nvector_store_id = response[\"id\"]\n```\n\nGiven a `vector_store_id` you can `retrieve` the current field values:\n\n```ruby\nclient.vector_stores.retrieve(id: vector_store_id)\n```\n\nYou can get a `list` of all vector stores currently available under the organization:\n\n```ruby\nclient.vector_stores.list\n```\n\nYou can modify an existing vector store, except for the `file_ids`:\n\n```ruby\nresponse = client.vector_stores.modify(\n  id: vector_store_id,\n  parameters: {\n    name: \"Modified Test Vector Store\",\n  }\n)\n```\n\nYou can search a vector store for relevant chunks based on a query:\n\n```ruby\nresponse = client.vector_stores.search(\n  id: vector_store_id,\n  parameters: {\n    query: \"What is the return policy?\",\n    max_num_results: 20,\n    ranking_options: {\n      # Add any ranking options here in line with the API documentation\n    },\n    rewrite_query: true,\n    filters: {\n      type: \"eq\",\n      property: \"region\",\n      value: \"us\"\n    }\n  }\n)\n```\n\nYou can delete vector stores:\n\n```ruby\nclient.vector_stores.delete(id: vector_store_id)\n```\n\n### Vector Store Files\n\nVector store files represent files inside a vector store.\n\nYou can create a new vector store file by attaching a File to a vector store.\n\n```ruby\nresponse = client.vector_store_files.create(\n  vector_store_id: \"vector-store-abc123\",\n  parameters: {\n    file_id: \"file-abc123\"\n  }\n)\n\nvector_store_file_id = response[\"id\"]\n```\n\nGiven a `vector_store_file_id` you can `retrieve` the current field values:\n\n```ruby\nclient.vector_store_files.retrieve(\n  vector_store_id: \"vector-store-abc123\",\n  id: vector_store_file_id\n)\n```\n\nYou can get a `list` of all vector store files currently available under the vector store:\n\n```ruby\nclient.vector_store_files.list(vector_store_id: \"vector-store-abc123\")\n```\n\nYou can delete a vector store file:\n\n```ruby\nclient.vector_store_files.delete(\n  vector_store_id: \"vector-store-abc123\",\n  id: vector_store_file_id\n)\n```\n\nNote: This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the delete file endpoint.\n\n### Vector Store File Batches\n\nVector store file batches represent operations to add multiple files to a vector store.\n\nYou can create a new vector store file batch by attaching multiple Files to a vector store.\n\n```ruby\nresponse = client.vector_store_file_batches.create(\n  vector_store_id: \"vector-store-abc123\",\n  parameters: {\n    file_ids: [\"file-abc123\", \"file-def456\"]\n  }\n)\n\nfile_batch_id = response[\"id\"]\n```\n\nGiven a `file_batch_id` you can `retrieve` the current field values:\n\n```ruby\nclient.vector_store_file_batches.retrieve(\n  vector_store_id: \"vector-store-abc123\",\n  id: file_batch_id\n)\n```\n\nYou can get a `list` of all vector store files in a batch currently available under the vector store:\n\n```ruby\nclient.vector_store_file_batches.list(\n  vector_store_id: \"vector-store-abc123\",\n  id: file_batch_id\n)\n```\n\nYou can cancel a vector store file batch (This attempts to cancel the processing of files in this batch as soon as possible):\n\n```ruby\nclient.vector_store_file_batches.cancel(\n  vector_store_id: \"vector-store-abc123\",\n  id: file_batch_id\n)\n```\n\n### Conversations\n\nThe [Conversations API](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fconversations) enables you to create and manage persistent conversations with your models. This is useful for maintaining conversation state across multiple interactions.\n\n**Supported Endpoints:**\n- `POST \u002Fv1\u002Fconversations` - Create a conversation\n- `GET \u002Fv1\u002Fconversations\u002F{id}` - Retrieve a conversation\n- `PATCH \u002Fv1\u002Fconversations\u002F{id}` - Modify a conversation\n- `DELETE \u002Fv1\u002Fconversations\u002F{id}` - Delete a conversation\n- `POST \u002Fv1\u002Fconversations\u002F{id}\u002Fitems` - Create items in a conversation\n- `GET \u002Fv1\u002Fconversations\u002F{id}\u002Fitems` - List items in a conversation\n- `GET \u002Fv1\u002Fconversations\u002F{id}\u002Fitems\u002F{item_id}` - Get a specific item\n- `DELETE \u002Fv1\u002Fconversations\u002F{id}\u002Fitems\u002F{item_id}` - Delete an item\n\n#### Creating a Conversation\n\nTo create a new conversation:\n\n```ruby\nresponse = client.conversations.create(\n  parameters: {\n    metadata: { purpose: \"customer_support\" }\n  }\n)\nconversation_id = response[\"id\"]\n```\n\n#### Retrieving a Conversation\n\nTo retrieve a specific conversation:\n\n```ruby\nconversation = client.conversations.retrieve(id: conversation_id)\n```\n\n#### Modifying a Conversation\n\nTo update a conversation's metadata:\n\n```ruby\nresponse = client.conversations.modify(\n  id: conversation_id,\n  parameters: {\n    metadata: { status: \"resolved\" }\n  }\n)\n```\n\n#### Deleting a Conversation\n\nTo delete a conversation:\n\n```ruby\nresponse = client.conversations.delete(id: conversation_id)\n```\n\n#### Managing Items in Conversations\n\nYou can add, retrieve, and manage items within a conversation.\n\n##### Creating Items\n\n```ruby\n# Create multiple items at once\nresponse = client.conversations.create_items(\n  conversation_id: conversation_id,\n  parameters: {\n    items: [\n      {\n        type: \"message\",\n        role: \"user\",\n        content: [\n          { type: \"input_text\", text: \"Hello!\" }\n        ]\n      },\n      {\n        type: \"message\",\n        role: \"assistant\",\n        content: [\n          { type: \"input_text\", text: \"How are you?\" }\n        ]\n      }\n    ]\n  }\n)\n```\n\n##### Listing Items\n\n```ruby\n# List all items in a conversation\nresponse = client.conversations.list_items(conversation_id: conversation_id)\nitems = response[\"data\"]\n\n# With parameters\nresponse = client.conversations.list_items(\n  conversation_id: conversation_id,\n  parameters: {\n    limit: 10,\n    order: \"asc\"\n  }\n)\n```\n\n##### Retrieving a Specific Item\n\n```ruby\nitem = client.conversations.get_item(\n  conversation_id: conversation_id,\n  item_id: item_id\n)\n```\n\n##### Deleting an Item\n\n```ruby\nresponse = client.conversations.delete_item(\n  conversation_id: conversation_id,\n  item_id: item_id\n)\n```\n\n### Assistants\n\nAssistants are stateful actors that can have many conversations and use tools to perform tasks (see [Assistant Overview](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fassistants\u002Foverview)).\n\nTo create a new assistant:\n\n```ruby\nresponse = client.assistants.create(\n  parameters: {\n    model: \"gpt-4o\",\n    name: \"OpenAI-Ruby test assistant\",\n    description: nil,\n    instructions: \"You are a Ruby dev bot. When asked a question, write and run Ruby code to answer the question\",\n    tools: [\n      { type: \"code_interpreter\" },\n      { type: \"file_search\" }\n    ],\n    tool_resources: {\n      code_interpreter: {\n        file_ids: [] # See Files section above for how to upload files\n      },\n      file_search: {\n        vector_store_ids: [] # See Vector Stores section above for how to add vector stores\n      }\n    },\n    \"metadata\": { my_internal_version_id: \"1.0.0\" }\n  }\n)\nassistant_id = response[\"id\"]\n```\n\nGiven an `assistant_id` you can `retrieve` the current field values:\n\n```ruby\nclient.assistants.retrieve(id: assistant_id)\n```\n\nYou can get a `list` of all assistants currently available under the organization:\n\n```ruby\nclient.assistants.list\n```\n\nYou can modify an existing assistant using the assistant's id (see [API documentation](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fassistants\u002FmodifyAssistant)):\n\n```ruby\nresponse = client.assistants.modify(\n  id: assistant_id,\n  parameters: {\n    name: \"Modified Test Assistant for OpenAI-Ruby\",\n    metadata: { my_internal_version_id: '1.0.1' }\n  }\n)\n```\n\nYou can delete assistants:\n\n```ruby\nclient.assistants.delete(id: assistant_id)\n```\n\n### Threads and Messages\n\nOnce you have created an assistant as described above, you need to prepare a `Thread` of `Messages` for the assistant to work on (see [introduction on Assistants](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fassistants\u002Fhow-it-works)). For example, as an initial setup you could do:\n\n```ruby\n# Create thread\nresponse = client.threads.create # Note: Once you create a thread, there is no way to list it\n                                 # or recover it currently (as of 2023-12-10). So hold onto the `id`\nthread_id = response[\"id\"]\n\n# Add initial message from user (see https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fmessages\u002FcreateMessage)\nmessage_id = client.messages.create(\n  thread_id: thread_id,\n  parameters: {\n    role: \"user\", # Required for manually created messages\n    content: \"Can you help me write an API library to interact with the OpenAI API please?\"\n  }\n)[\"id\"]\n\n# Retrieve individual message\nmessage = client.messages.retrieve(thread_id: thread_id, id: message_id)\n\n# Review all messages on the thread\nmessages = client.messages.list(thread_id: thread_id)\n```\n\nTo clean up after a thread is no longer needed:\n\n```ruby\n# To delete the thread (and all associated messages):\nclient.threads.delete(id: thread_id)\n\nclient.messages.retrieve(thread_id: thread_id, id: message_id) # -> Fails after thread is deleted\n```\n\n### Runs\n\nTo submit a thread to be evaluated with the model of an assistant, create a `Run` as follows:\n\n```ruby\n# Create run (will use instruction\u002Fmodel\u002Ftools from Assistant's definition)\nresponse = client.runs.create(\n  thread_id: thread_id,\n  parameters: {\n    assistant_id: assistant_id,\n    max_prompt_tokens: 256,\n    max_completion_tokens: 16\n  }\n)\nrun_id = response['id']\n```\n\nYou can stream the message chunks as they come through:\n\n```ruby\nclient.runs.create(\n  thread_id: thread_id,\n  parameters: {\n    assistant_id: assistant_id,\n    max_prompt_tokens: 256,\n    max_completion_tokens: 16,\n    stream: proc do |chunk, _event|\n      if chunk[\"object\"] == \"thread.message.delta\"\n        print chunk.dig(\"delta\", \"content\", 0, \"text\", \"value\")\n      end\n    end\n  }\n)\n```\n\nTo get the status of a Run:\n\n```ruby\nresponse = client.runs.retrieve(id: run_id, thread_id: thread_id)\nstatus = response['status']\n```\n\nThe `status` response can include the following strings `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, or `expired` which you can handle as follows:\n\n```ruby\nwhile true do\n  response = client.runs.retrieve(id: run_id, thread_id: thread_id)\n  status = response['status']\n\n  case status\n  when 'queued', 'in_progress', 'cancelling'\n    puts 'Sleeping'\n    sleep 1 # Wait one second and poll again\n  when 'completed'\n    break # Exit loop and report result to user\n  when 'requires_action'\n    # Handle tool calls (see below)\n  when 'cancelled', 'failed', 'expired'\n    puts response['last_error'].inspect\n    break # or `exit`\n  else\n    puts \"Unknown status response: #{status}\"\n  end\nend\n```\n\nIf the `status` response indicates that the `run` is `completed`, the associated `thread` will have one or more new `messages` attached:\n\n```ruby\n# Either retrieve all messages in bulk again, or...\nmessages = client.messages.list(thread_id: thread_id, parameters: { order: 'asc' })\n\n# Alternatively retrieve the `run steps` for the run which link to the messages:\nrun_steps = client.run_steps.list(thread_id: thread_id, run_id: run_id, parameters: { order: 'asc' })\nnew_message_ids = run_steps['data'].filter_map do |step|\n  if step['type'] == 'message_creation'\n    step.dig('step_details', \"message_creation\", \"message_id\")\n  end # Ignore tool calls, because they don't create new messages.\nend\n\n# Retrieve the individual messages\nnew_messages = new_message_ids.map do |msg_id|\n  client.messages.retrieve(id: msg_id, thread_id: thread_id)\nend\n\n# Find the actual response text in the content array of the messages\nnew_messages.each do |msg|\n  msg['content'].each do |content_item|\n    case content_item['type']\n    when 'text'\n      puts content_item.dig('text', 'value')\n      # Also handle annotations\n    when 'image_file'\n      # Use File endpoint to retrieve file contents via id\n      id = content_item.dig('image_file', 'file_id')\n    end\n  end\nend\n```\n\nYou can also update the metadata on messages, including messages that come from the assistant.\n\n```ruby\nmetadata = {\n  user_id: \"abc123\"\n}\nmessage = client.messages.modify(\n  id: message_id,\n  thread_id: thread_id,\n  parameters: { metadata: metadata },\n)\n```\n\nAt any time you can list all runs which have been performed on a particular thread or are currently running:\n\n```ruby\nclient.runs.list(thread_id: thread_id, parameters: { order: \"asc\", limit: 3 })\n```\n\n#### Create and Run\n\nYou can also create a thread and run in one call like this:\n\n```ruby\nresponse = client.runs.create_thread_and_run(parameters: { assistant_id: assistant_id })\nrun_id = response['id']\nthread_id = response['thread_id']\n```\n\n#### Vision in a thread\n\nYou can include images in a thread and they will be described & read by the LLM. In this example I'm using [this file](https:\u002F\u002Fupload.wikimedia.org\u002Fwikipedia\u002Fcommons\u002F7\u002F70\u002FExample.png):\n\n```ruby\nrequire \"openai\"\n\n# Make a client\nclient = OpenAI::Client.new(\n  access_token: \"access_token_goes_here\",\n  log_errors: true # Don't log errors in production.\n)\n\n# Upload image as a file\nfile_id = client.files.upload(\n  parameters: {\n    file: \"path\u002Fto\u002Fexample.png\",\n    purpose: \"assistants\",\n  }\n)[\"id\"]\n\n# Create assistant (You could also use an existing one here)\nassistant_id = client.assistants.create(\n  parameters: {\n    model: \"gpt-4o\",\n    name: \"Image reader\",\n    instructions: \"You are an image describer. You describe the contents of images.\",\n  }\n)[\"id\"]\n\n# Create thread\nthread_id = client.threads.create[\"id\"]\n\n# Add image in message\nclient.messages.create(\n  thread_id: thread_id,\n  parameters: {\n    role: \"user\", # Required for manually created messages\n    content: [\n      {\n        \"type\": \"text\",\n        \"text\": \"What's in this image?\"\n      },\n      {\n        \"type\": \"image_file\",\n        \"image_file\": { \"file_id\": file_id }\n      }\n    ]\n  }\n)\n\n# Run thread\nrun_id = client.runs.create(\n  thread_id: thread_id,\n  parameters: { assistant_id: assistant_id }\n)[\"id\"]\n\n# Wait until run in complete\nstatus = nil\nuntil status == \"completed\" do\n  sleep(0.1)\n  status = client.runs.retrieve(id: run_id, thread_id: thread_id)['status']\nend\n\n# Get the response\nmessages = client.messages.list(thread_id: thread_id, parameters: { order: 'asc' })\nmessages.dig(\"data\", -1, \"content\", 0, \"text\", \"value\")\n=> \"The image contains a placeholder graphic with a tilted, stylized representation of a postage stamp in the top part, which includes an abstract landscape with hills and a sun. Below the stamp, in the middle of the image, there is italicized text in a light golden color that reads, \\\"This is just an example.\\\" The background is a light pastel shade, and a yellow border frames the entire image.\"\n```\n\n#### Runs involving function tools\n\nIn case you are allowing the assistant to access `function` tools (they are defined in the same way as functions during chat completion), you might get a status code of `requires_action` when the assistant wants you to evaluate one or more function tools:\n\n```ruby\ndef get_current_weather(location:, unit: \"celsius\")\n  # Your function code goes here\n  if location =~ \u002FSan Francisco\u002Fi\n    return unit == \"celsius\" ? \"The weather is nice 🌞 at 27°C\" : \"The weather is nice 🌞 at 80°F\"\n  else\n    return unit == \"celsius\" ? \"The weather is icy 🥶 at -5°C\" : \"The weather is icy 🥶 at 23°F\"\n  end\nend\n\nif status == 'requires_action'\n  tools_to_call = response.dig('required_action', 'submit_tool_outputs', 'tool_calls')\n\n  my_tool_outputs = tools_to_call.map { |tool|\n    # Call the functions based on the tool's name\n    function_name = tool.dig('function', 'name')\n    arguments = JSON.parse(\n      tool.dig(\"function\", \"arguments\"),\n      { symbolize_names: true },\n    )\n\n    tool_output = case function_name\n    when \"get_current_weather\"\n      get_current_weather(**arguments)\n    end\n\n    {\n      tool_call_id: tool['id'],\n      output: tool_output,\n    }\n  }\n\n  client.runs.submit_tool_outputs(\n    thread_id: thread_id,\n    run_id: run_id,\n    parameters: { tool_outputs: my_tool_outputs }\n  )\nend\n```\n\nNote that you have 10 minutes to submit your tool output before the run expires.\n\n#### Exploring chunks used in File Search\n\nTake a deep breath. You might need a drink for this one.\n\nIt's possible for OpenAI to share what chunks it used in its internal RAG Pipeline to create its filesearch results.\n\nAn example spec can be found [here](https:\u002F\u002Fgithub.com\u002Falexrudall\u002Fruby-openai\u002Fblob\u002Fmain\u002Fspec\u002Fopenai\u002Fclient\u002Fassistant_file_search_spec.rb) that does this, just so you know it's possible.\n\nHere's how to get the chunks used in a file search. In this example I'm using [this file](https:\u002F\u002Fcss4.pub\u002F2015\u002Ftextbook\u002Fsomatosensory.pdf):\n\n```ruby\nrequire \"openai\"\n\n# Make a client\nclient = OpenAI::Client.new(\n  access_token: \"access_token_goes_here\",\n  log_errors: true # Don't log errors in production.\n)\n\n# Upload your file(s)\nfile_id = client.files.upload(\n  parameters: {\n    file: \"path\u002Fto\u002Fsomatosensory.pdf\",\n    purpose: \"assistants\"\n  }\n)[\"id\"]\n\n# Create a vector store to store the vectorised file(s)\nvector_store_id = client.vector_stores.create(parameters: {})[\"id\"]\n\n# Vectorise the file(s)\nvector_store_file_id = client.vector_store_files.create(\n  vector_store_id: vector_store_id,\n  parameters: { file_id: file_id }\n)[\"id\"]\n\n# Check that the file is vectorised (wait for status to be \"completed\")\nclient.vector_store_files.retrieve(vector_store_id: vector_store_id, id: vector_store_file_id)[\"status\"]\n\n# Create an assistant, referencing the vector store\nassistant_id = client.assistants.create(\n  parameters: {\n    model: \"gpt-4o\",\n    name: \"Answer finder\",\n    instructions: \"You are a file search tool. Find the answer in the given files, please.\",\n    tools: [\n      { type: \"file_search\" }\n    ],\n    tool_resources: {\n      file_search: {\n        vector_store_ids: [vector_store_id]\n      }\n    }\n  }\n)[\"id\"]\n\n# Create a thread with your question\nthread_id = client.threads.create(parameters: {\n  messages: [\n    { role: \"user\",\n      content: \"Find the description of a nociceptor.\" }\n  ]\n})[\"id\"]\n\n# Run the thread to generate the response. Include the \"GIVE ME THE CHUNKS\" incantation.\nrun_id = client.runs.create(\n  thread_id: thread_id,\n  parameters: {\n    assistant_id: assistant_id\n  },\n  query_parameters: { include: [\"step_details.tool_calls[*].file_search.results[*].content\"] } # incantation\n)[\"id\"]\n\n# Get the steps that happened in the run\nsteps = client.run_steps.list(\n  thread_id: thread_id,\n  run_id: run_id,\n  parameters: { order: \"asc\" }\n)\n\n# Retrieve all the steps. Include the \"GIVE ME THE CHUNKS\" incantation again.\nsteps = steps[\"data\"].map do |step|\n  client.run_steps.retrieve(\n    thread_id: thread_id,\n    run_id: run_id,\n    id: step[\"id\"],\n    parameters: { include: [\"step_details.tool_calls[*].file_search.results[*].content\"] } # incantation\n  )\nend\n\n# Now we've got the chunk info, buried deep. Loop through the steps and find chunks if included:\nchunks = steps.flat_map do |step|\n  included_results = step.dig(\"step_details\", \"tool_calls\", 0, \"file_search\", \"results\")\n\n  next if included_results.nil? || included_results.empty?\n\n  included_results.flat_map do |result|\n    result[\"content\"].map do |content|\n      content[\"text\"]\n    end\n  end\nend.compact\n\n# The first chunk will be the closest match to the prompt. Finally, if you want to view the completed message(s):\nclient.messages.list(thread_id: thread_id)\n```\n\n### Image Generation\n\nGenerate images using DALL·E 2 or DALL·E 3!\n\n#### DALL·E 2\n\nFor DALL·E 2 the size of any generated images must be one of `256x256`, `512x512` or `1024x1024` - if not specified the image will default to `1024x1024`.\n\n```ruby\nresponse = client.images.generate(\n  parameters: {\n    prompt: \"A baby sea otter cooking pasta wearing a hat of some sort\",\n    size: \"256x256\",\n  }\n)\nputs response.dig(\"data\", 0, \"url\")\n# => \"https:\u002F\u002Foaidalleapiprodscus.blob.core.windows.net\u002Fprivate\u002Forg-Rf437IxKhh...\"\n```\n\n![Ruby](https:\u002F\u002Fi.ibb.co\u002F6y4HJFx\u002Fimg-d-Tx-Rf-RHj-SO5-Gho-Cbd8o-LJvw3.png)\n\n#### DALL·E 3\n\nFor DALL·E 3 the size of any generated images must be one of `1024x1024`, `1024x1792` or `1792x1024`. Additionally the quality of the image can be specified to either `standard` or `hd`.\n\n```ruby\nresponse = client.images.generate(\n  parameters: {\n    prompt: \"A springer spaniel cooking pasta wearing a hat of some sort\",\n    model: \"dall-e-3\",\n    size: \"1024x1792\",\n    quality: \"standard\",\n  }\n)\nputs response.dig(\"data\", 0, \"url\")\n# => \"https:\u002F\u002Foaidalleapiprodscus.blob.core.windows.net\u002Fprivate\u002Forg-Rf437IxKhh...\"\n```\n\n![Ruby](https:\u002F\u002Fi.ibb.co\u002Fz2tCKv9\u002Fimg-Goio0l-S0i81-NUNa-BIx-Eh-CT6-L.png)\n\n### Image Edit\n\nFill in the transparent part of an image, or upload a mask with transparent sections to indicate the parts of an image that can be changed according to your prompt...\n\n```ruby\nresponse = client.images.edit(\n  parameters: {\n    prompt: \"A solid red Ruby on a blue background\",\n    image: \"image.png\",\n    mask: \"mask.png\",\n  }\n)\nputs response.dig(\"data\", 0, \"url\")\n# => \"https:\u002F\u002Foaidalleapiprodscus.blob.core.windows.net\u002Fprivate\u002Forg-Rf437IxKhh...\"\n```\n\n![Ruby](https:\u002F\u002Fi.ibb.co\u002FsWVh3BX\u002Fdalle-ruby.png)\n\nYou can also upload arrays of images, eg.\n\n```ruby\n  client = OpenAI::Client.new\n  response = client.images.edit(\n    parameters: {\n      model: \"gpt-image-1\",\n      image: [File.open(base_image_path, \"rb\"), \"image.png\"],\n      prompt: \"Take the first image as base and apply the second image as a watermark on the bottom right corner\",\n      size: \"1024x1024\"\n      # Removed response_format parameter as it's not supported with gpt-image-1\n    }\n  )\n```\n\n### Image Variations\n\nCreate n variations of an image.\n\n```ruby\nresponse = client.images.variations(parameters: { image: \"image.png\", n: 2 })\nputs response.dig(\"data\", 0, \"url\")\n# => \"https:\u002F\u002Foaidalleapiprodscus.blob.core.windows.net\u002Fprivate\u002Forg-Rf437IxKhh...\"\n```\n\n![Ruby](https:\u002F\u002Fi.ibb.co\u002FTWJLP2y\u002Fimg-miu-Wk-Nl0-QNy-Xtj-Lerc3c0l-NW.png)\n![Ruby](https:\u002F\u002Fi.ibb.co\u002FScBhDGB\u002Fimg-a9-Be-Rz-Au-Xwd-AV0-ERLUTSTGdi.png)\n\n### Moderations\n\nPass a string to check if it violates OpenAI's Content Policy:\n\n```ruby\nresponse = client.moderations(parameters: { input: \"I'm worried about that.\" })\nputs response.dig(\"results\", 0, \"category_scores\", \"hate\")\n# => 5.505014632944949e-05\n```\n\n### Whisper\n\nWhisper is a speech to text model that can be used to generate text based on audio files:\n\n#### Translate\n\nThe translations API takes as input the audio file in any of the supported languages and transcribes the audio into English.\n\n```ruby\nresponse = client.audio.translate(\n  parameters: {\n    model: \"whisper-1\",\n    file: File.open(\"path_to_file\", \"rb\"),\n  }\n)\nputs response[\"text\"]\n# => \"Translation of the text\"\n```\n\n#### Transcribe\n\nThe transcriptions API takes as input the audio file you want to transcribe and returns the text in the desired output file format.\n\nYou can pass the language of the audio file to improve transcription quality. Supported languages are listed [here](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fwhisper#available-models-and-languages). You need to provide the language as an ISO-639-1 code, eg. \"en\" for English or \"ne\" for Nepali. You can look up the codes [here](https:\u002F\u002Fen.wikipedia.org\u002Fwiki\u002FList_of_ISO_639_language_codes).\n\n```ruby\nresponse = client.audio.transcribe(\n  parameters: {\n    model: \"whisper-1\",\n    file: File.open(\"path_to_file\", \"rb\"),\n    language: \"en\", # Optional\n  }\n)\nputs response[\"text\"]\n# => \"Transcription of the text\"\n```\n\nIf you are using Ruby on Rails with Active Storage, you would need to send an audio or video file like this (User has_one_attached):\n```ruby\nuser.media.blob.open do |file|\n  response = client.audio.transcribe(\n    parameters: {\n        model: \"whisper-1\",\n        file: File.open(file, \"rb\"),\n        language: \"en\" # Optional\n    })\n  puts response[\"text\"]\n  # => \"Transcription of the text\"\nend\n```\n\n#### Speech\n\nThe speech API takes as input the text and a voice and returns the content of an audio file you can listen to.\n\n```ruby\nresponse = client.audio.speech(\n  parameters: {\n    model: \"tts-1\",\n    input: \"This is a speech test!\",\n    voice: \"alloy\",\n    response_format: \"mp3\", # Optional\n    speed: 1.0, # Optional\n  }\n)\nFile.binwrite('demo.mp3', response)\n# => mp3 file that plays: \"This is a speech test!\"\n```\n\n### Realtime\n\nThe [Realtime API](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Frealtime) allows you to create a live speech-to-speech session with an OpenAI model. It responds with a session object, plus a client_secret key which contains a usable ephemeral API token that can be used to [authenticate browser clients for a WebRTC connection](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Frealtime#connect-with-webrtc).\n\n```ruby\nresponse = client.realtime.create(parameters: { model: \"gpt-4o-realtime-preview-2024-12-17\" })\nputs \"ephemeral key: #{response.dig('client_secret', 'value')}\"\n# => \"ephemeral key: ek_abc123\"\n```\n\nThen in the client-side Javascript application, make a POST request to the Real-Time API with the ephemeral key and the SDP offer.\n\n```js\nconst OPENAI_REALTIME_URL = 'https:\u002F\u002Fapi.openai.com\u002Fv1\u002Frealtime\u002Fsessions'\nconst MODEL = 'gpt-4o-realtime-preview-2024-12-17'\n\nconst response = await fetch(`${OPENAI_REALTIME_URL}?model=${MODEL}`, {\n  method: 'POST',\n  headers: {\n    'Content-Type': 'application\u002Fsdp',\n    'Authorization': `Bearer ${ephemeralKey}`,\n    'OpenAI-Beta': 'realtime=v1'\n  },\n  body: offer.sdp\n})\n```\n\n### Usage\n\nThe Usage API provides information about the cost of various OpenAI services within your organization.\nTo use Admin APIs like Usage, you need to set an OPENAI_ADMIN_TOKEN, which can be generated [here](https:\u002F\u002Fplatform.openai.com\u002Fsettings\u002Forganization\u002Fadmin-keys).\n\n```ruby\nOpenAI.configure do |config|\n  config.admin_token = ENV.fetch(\"OPENAI_ADMIN_TOKEN\")\nend\n\n# or\n\nclient = OpenAI::Client.new(admin_token: \"123abc\")\n```\n\nYou can retrieve usage data for different endpoints and time periods:\n\n```ruby\none_day_ago = Time.now.to_i - 86_400\n\n# Retrieve costs data\nresponse = client.usage.costs(parameters: { start_time: one_day_ago })\nresponse[\"data\"].each do |bucket|\n  bucket[\"results\"].each do |result|\n    puts \"#{Time.at(bucket[\"start_time\"]).to_date}: $#{result.dig(\"amount\", \"value\").round(2)}\"\n  end\nend\n=> 2025-02-09: $0.0\n=> 2025-02-10: $0.42\n\n# Retrieve completions usage data\nresponse = client.usage.completions(parameters: { start_time: one_day_ago })\nputs response[\"data\"]\n\n# Retrieve embeddings usage data\nresponse = client.usage.embeddings(parameters: { start_time: one_day_ago })\nputs response[\"data\"]\n\n# Retrieve moderations usage data\nresponse = client.usage.moderations(parameters: { start_time: one_day_ago })\nputs response[\"data\"]\n\n# Retrieve image generation usage data\nresponse = client.usage.images(parameters: { start_time: one_day_ago })\nputs response[\"data\"]\n\n# Retrieve audio speech usage data\nresponse = client.usage.audio_speeches(parameters: { start_time: one_day_ago })\nputs response[\"data\"]\n\n# Retrieve audio transcription usage data\nresponse = client.usage.audio_transcriptions(parameters: { start_time: one_day_ago })\nputs response[\"data\"]\n\n# Retrieve vector stores usage data\nresponse = client.usage.vector_stores(parameters: { start_time: one_day_ago })\nputs response[\"data\"]\n```\n\n### Errors\n\nHTTP errors can be caught like this:\n\n```ruby\nbegin\n  OpenAI::Client.new.models.retrieve(id: \"gpt-4o\")\nrescue Faraday::Error => e\n  raise \"Got a Faraday error: #{e}\"\nend\n```\n\n## Development\n\nAfter checking out the repo, run `bin\u002Fsetup` to install dependencies. You can run `bin\u002Fconsole` for an interactive prompt that will allow you to experiment.\n\nTo install this gem onto your local machine, run `bundle exec rake install`.\n\nTo run all tests, execute the command `bundle exec rake`, which will also run the linter (Rubocop). This repository uses [VCR](https:\u002F\u002Fgithub.com\u002Fvcr\u002Fvcr) to log API requests.\n\n> [!WARNING]\n> If you have an `OPENAI_ACCESS_TOKEN` and `OPENAI_ADMIN_TOKEN` in your `ENV`, running the specs will hit the actual API, which will be slow and cost you money - 2 cents or more! Remove them from your environment with `unset` or similar if you just want to run the specs against the stored VCR responses.\n\n### To check for deprecations\n\n```\nbundle exec ruby -e \"Warning[:deprecated] = true; require 'rspec'; exit RSpec::Core::Runner.run(['spec\u002Fopenai\u002Fclient\u002Fhttp_spec.rb:25'])\"\n```\n\n## Release\n\nRuby OpenAI follows [Semantic Versioning](https:\u002F\u002Fsemver.org\u002Fspec\u002Fv2.0.0.html):\n\n- Major releases may include breaking changes, removals, or support changes.\n- Minor releases add backwards-compatible functionality.\n- Patch releases fix backwards-compatible bugs or security issues.\n\nBefore releasing, run the specs without VCR so they actually hit the API. This will cost 2 cents or more. Set OPENAI_ACCESS_TOKEN and OPENAI_ADMIN_TOKEN in your environment.\n\nThen update the version number in `version.rb`, update `CHANGELOG.md`, run `bundle install` to update Gemfile.lock, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https:\u002F\u002Frubygems.org).\n\nAfter the tag is pushed, publish or update the corresponding GitHub Release using the changelog entry.\n\nRelease notes are published through GitHub Releases, git tags, RubyGems, and `CHANGELOG.md`. Security releases are identified in the changelog and release notes, and may also use GitHub Security Advisories. Major releases, security releases, and end-of-life notices may also be shared through the community channels linked at the top of this README.\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at \u003Chttps:\u002F\u002Fgithub.com\u002Falexrudall\u002Fruby-openai>. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https:\u002F\u002Fgithub.com\u002Falexrudall\u002Fruby-openai\u002Fblob\u002Fmain\u002FCODE_OF_CONDUCT.md).\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https:\u002F\u002Fopensource.org\u002Flicenses\u002FMIT).\n\n## Code of Conduct\n\nEveryone interacting in the Ruby OpenAI project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https:\u002F\u002Fgithub.com\u002Falexrudall\u002Fruby-openai\u002Fblob\u002Fmain\u002FCODE_OF_CONDUCT.md).\n","ruby-openai 项目是一个使用 Ruby 语言与 OpenAI API 进行交互的库。它支持最新的 GPT-5 模型，并兼容实时 WebRTC 通信，允许开发者轻松地将高级 AI 功能集成到自己的应用中。该项目提供了丰富的功能，包括流式聊天处理、响应 API 的创建与管理以及视觉信息处理等。此外，该库还支持自定义配置选项，如超时设置、额外请求头和日志记录等功能，便于开发者根据具体需求调整。适用于需要利用 OpenAI 技术增强其产品能力的各种场景，尤其是那些希望在 Ruby on Rails 或其他基于 Ruby 的框架下快速实现 AI 驱动特性的开发者。",2,"2026-06-11 03:14:46","top_language"]