### Start Mock Server Source: https://github.com/openai/openai-ruby/blob/main/CONTRIBUTING.md Set up a mock server against the OpenAPI spec to run tests. Refer to the provided link for setup instructions. ```bash $ ./scripts/mock ``` -------------------------------- ### Add and Run Example Script Source: https://github.com/openai/openai-ruby/blob/main/CONTRIBUTING.md Make an example script executable and run it against your API. ```ruby #!/usr/bin/env ruby # frozen_string_literal: true require_relative "../lib/openai" # ... ``` ```bash $ chmod +x './examples/.rb' # run the example against your api $ ruby './examples/.rb' ``` -------------------------------- ### Complete Webhook Example in Ruby Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/09-webhooks-auth.md This snippet demonstrates a full implementation of a webhook endpoint using Sinatra and the OpenAI Ruby client. It includes setup, request parsing, signature verification, event handling for various types, and error management. Ensure you have the 'sinatra' and 'openai' gems installed and your API and webhook secrets configured as environment variables. ```ruby # Gemfile gem "sinatra" gem "openai" # app.rb require "sinatra" require "openai" require "json" client = OpenAI::Client.new( api_key: ENV["OPENAI_API_KEY"], webhook_secret: ENV["OPENAI_WEBHOOK_SECRET"] ) post "/webhook" do content_type :json # Get raw body and headers request_body = request.body.read headers_hash = request.env .select { |k| k.start_with?("HTTP_") } .transform_keys { |k| k.sub(/^HTTP_/, "").downcase.tr("_", "-") } begin # Verify and parse webhook event = client.webhooks.unwrap(body: request_body, headers: headers_hash) # Process event case event.type when "response.completed" puts "Response completed: #{event.id}" # Handle completion process_response(event.data) when "response.failed" puts "Response failed: #{event.id}" # Handle failure log_error(event.data) when "batch.completed" puts "Batch completed: #{event.id}" # Handle batch completion process_batch(event.data) else puts "Unknown event type: #{event.type}" end # Return 200 to acknowledge receipt status 200 { status: "received" }.to_json rescue OpenAI::Errors::InvalidWebhookSignatureError => e puts "Invalid webhook signature: #{e.message}" status 400 { error: "Invalid signature" }.to_json rescue StandardError => e puts "Error processing webhook: #{e.message}" puts e.backtrace.join("\n") status 500 { error: "Internal error" }.to_json end end def process_response(data) # Process response data puts "Processing response: #{data.inspect}" end def process_batch(data) # Process batch data puts "Processing batch: #{data.inspect}" end def log_error(data) # Log error data puts "Logging error: #{data.inspect}" end ``` -------------------------------- ### Complete Chat Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/INDEX.md A full example demonstrating how to initialize the client, send a chat completion request, and process the response. Ensure your OPENAI_API_KEY environment variable is set. ```ruby require "openai" client = OpenAI::Client.new(api_key: ENV["OPENAI_API_KEY"]) messages = [ { role: "system", content: "You are a helpful assistant" }, { role: "user", content: "What is the capital of France?" } ] response = client.chat.completions.create( messages: messages, model: "gpt-4o" ) puts response.choices[0].message.content puts "Tokens: #{response.usage.total_tokens}" ``` -------------------------------- ### Development Configuration Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/03-configuration.md Example configuration for a development environment, including API key, organization, retry count, and timeout. ```ruby client = OpenAI::Client.new( api_key: ENV["OPENAI_API_KEY"], organization: ENV["OPENAI_ORG_ID"], max_retries: 3, timeout: 120.0 ) ``` -------------------------------- ### Bootstrap Project Dependencies Source: https://github.com/openai/openai-ruby/blob/main/CONTRIBUTING.md Run this command to install all required dependencies for the project. ```bash $ ./scripts/bootstrap ``` -------------------------------- ### Testing Configuration Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/03-configuration.md Example configuration for a testing environment, using a test API key, a local base URL, zero retries, and a short timeout. ```ruby client = OpenAI::Client.new( api_key: "test-key", base_url: "http://localhost:3000/v1", max_retries: 0, timeout: 30.0 ) ``` -------------------------------- ### Production Configuration Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/03-configuration.md Example configuration for a production environment, emphasizing higher retry counts, longer timeouts, and specific retry delays. ```ruby client = OpenAI::Client.new( api_key: ENV["OPENAI_API_KEY"], organization: ENV["OPENAI_ORG_ID"], project: ENV["OPENAI_PROJECT_ID"], max_retries: 5, timeout: 600.0, initial_retry_delay: 1.0, max_retry_delay: 16.0 ) ``` -------------------------------- ### Full Example: Data Extraction with Models Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Illustrates a complete example of data extraction using custom models for people's information and extraction status. It shows how to parse the response and access extracted data. ```ruby class PersonInfo < OpenAI::BaseModel required :first_name, String required :last_name, String required :age, Integer, nil?: true required :email, String, nil?: true end class ExtractionResult < OpenAI::BaseModel required :people, OpenAI::ArrayOf[PersonInfo] required :extraction_status, OpenAI::EnumOf[:success, :partial, :failed] end response = client.responses.create( model: "gpt-4o", input: [ { role: "user", content: "Extract person info from: John Smith, age 30, john@example.com. Also Alice Johnson." } ], text: ExtractionResult ) response.output.each do |output| if output.is_a?(OpenAI::Models::Responses::ResponseOutputText) result = output.parsed # Instance of ExtractionResult result.people.each do |person| puts "#{person.first_name} #{person.last_name}" puts " Age: #{person.age}" if person.age puts " Email: #{person.email}" if person.email end puts "Status: #{result.extraction_status}" end end ``` -------------------------------- ### Batch Processing Setup Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/INDEX.md Shows how to prepare and create a batch processing job. It involves uploading a file and then creating a batch with specified endpoint and completion window. ```ruby file = client.files.create( file: Pathname("batch.jsonl"), purpose: "batch" ) batch = client.batches.create( input_file_id: file.id, endpoint: "/v1/chat/completions", completion_window: "24h" ) ``` -------------------------------- ### Handle NotFoundError Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of catching a NotFoundError when trying to retrieve a non-existent file. ```ruby begin client.files.retrieve("file-nonexistent") rescue OpenAI::Errors::NotFoundError => e puts "File not found: #{e.message}" end ``` -------------------------------- ### Clustering with Embeddings (Pseudo-code) Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/07-embeddings-models.md Illustrates the initial step of getting embeddings for texts, which can then be used for clustering. This example uses 'text-embedding-3-small' and provides pseudo-code for the clustering part. ```ruby # Get embeddings for texts texts = ["Python code", "JavaScript snippet", "Java program", "Ruby script"] response = client.embeddings.create( input: texts, model: "text-embedding-3-small" ) embeddings = response.data.map(&:embedding) # Simple k-means clustering (pseudo-code) # In practice, use a proper clustering library ``` -------------------------------- ### High Availability Configuration Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/03-configuration.md Example configuration optimized for high availability, featuring a higher maximum retry count and adjusted retry delay parameters. ```ruby client = OpenAI::Client.new( api_key: ENV["OPENAI_API_KEY"], max_retries: 10, timeout: 120.0, initial_retry_delay: 0.5, max_retry_delay: 60.0 ) ``` -------------------------------- ### Install Gem from Git Source: https://github.com/openai/openai-ruby/blob/main/CONTRIBUTING.md Add this line to your Gemfile to install the openai gem directly from its GitHub repository. ```ruby gem "openai", git: "https://github.com/openai/openai-ruby" ``` -------------------------------- ### Create Assistant with Function Tool Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md This example shows how to create an AI assistant, specifying its model, name, instructions, and defining a function tool for retrieving weather information. ```ruby # Create assistant assistant = client.beta.assistants.create( model: "gpt-4o", name: "My Assistant", instructions: "You are a helpful assistant", tools: [ { type: "function", function: { name: "get_weather", description: "Get weather information", parameters: { type: "object", properties: { location: { type: "string" } } } } } ] ) ``` -------------------------------- ### OpenAI::UnionOf Usage Examples Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Demonstrates how to define fields that can accept one of multiple specified types. ```ruby # Union of primitives required :value, OpenAI::UnionOf[String, Integer] ``` -------------------------------- ### Handle AuthenticationError Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of catching an AuthenticationError when API authentication fails. ```ruby begin client.chat.completions.create(...) rescue OpenAI::Errors::AuthenticationError => e puts "Authentication failed. Check your API key." end ``` -------------------------------- ### Handle OAuthError Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of rescuing OAuthError during workload identity setup. It demonstrates accessing the `error_code` and `message` for debugging. ```ruby begin # During workload identity setup rescue OpenAI::Errors::OAuthError => e puts "OAuth error: #{e.error_code}" puts "Details: #{e.message}" end ``` -------------------------------- ### Complete Batch Processing Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/08-completions-batches.md This snippet demonstrates the full lifecycle of a batch job, from creating requests and writing them to a file, to uploading, submitting, polling for completion, and processing results. It requires an initialized OpenAI client. ```ruby class BatchProcessor def initialize(client) @client = client end def process_completions(prompts) # Create requests requests = prompts.map.with_index do |prompt, i| { custom_id: "completion-" + i.to_s, method: "POST", url: "/v1/chat/completions", body: { model: "gpt-4o", messages: [{ role: "user", content: prompt }] } } end # Write to file File.write("batch.jsonl", requests.map(&:to_json).join("\n")) # Upload and submit file = @client.files.create( file: Pathname("batch.jsonl"), purpose: "batch" ) batch = @client.batches.create( input_file_id: file.id, endpoint: "/v1/chat/completions", completion_window: "24h" ) # Poll for completion until ["completed", "failed", "expired"].include?(batch.status) puts "Batch " + batch.id + ": " + batch.status sleep(30) batch = @client.batches.retrieve(batch.id) end # Download results process_results(batch) end private def process_results(batch) return if batch.output_file_id.nil? # Retrieve output content output = @client.request( method: :get, path: "/files/" + batch.output_file_id + "/content" ) results = {} output.split("\n").each do |line| next if line.empty? result = JSON.parse(line) if result["status_code"] == 200 content = result["body"]["choices"][0]["message"]["content"] results[result["custom_id"]] = content else results[result["custom_id"]] = "ERROR: " + result['status_code'] end end results end end # Usage processor = BatchProcessor.new(client) results = processor.process_completions([ "What is 2+2?", "Explain photosynthesis", "Write a haiku" ]) results.each do |id, response| puts id + ": " + response end ``` -------------------------------- ### Install OpenAI Ruby Gem Source: https://github.com/openai/openai-ruby/blob/main/README.md Add the OpenAI gem to your application's Gemfile to install it via Bundler. ```ruby gem "openai", "~> 0.66.1" ``` -------------------------------- ### Example: Multi-Turn Conversation Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/04-chat-completions.md Demonstrates how to maintain context for multi-turn conversations. ```APIDOC ## Example: Multi-Turn Conversation ```ruby messages = [ { role: "system", content: "You are a helpful math tutor." } ] # First turn response = client.chat.completions.create( messages: messages, model: "gpt-4o" ) messages << response.choices[0].message # Second turn messages << { role: "user", content: "What is 2 + 2?" } response = client.chat.completions.create( messages: messages, model: "gpt-4o" ) messages << response.choices[0].message puts messages ``` ``` -------------------------------- ### Handle RateLimitError Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of catching a RateLimitError, which might occur after automatic retries are exhausted. ```ruby begin # Multiple rapid requests rescue OpenAI::Errors::RateLimitError => e # Automatically retried, but catch if retries exhausted puts "Rate limit exceeded. Wait before retrying." end ``` -------------------------------- ### Per-Request Options Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/INDEX.md Demonstrates how to set per-request options such as retries, timeout, idempotency key, and custom headers when creating a chat completion. ```ruby response = client.chat.completions.create( messages: [...], model: "gpt-4o", request_options: { max_retries: 5, timeout: 120.0, idempotency_key: "unique-key", extra_headers: { "X-Custom" => "value" } } ) ``` -------------------------------- ### OpenAI::EnumOf Usage Examples Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Demonstrates how to define fields with enumerated values, supporting symbols, strings, and integers. ```ruby # Symbol enum required :status, OpenAI::EnumOf[:pending, :confirmed, :cancelled] # String enum required :color, OpenAI::EnumOf["red", "green", "blue"] # Integer enum required :level, OpenAI::EnumOf[1, 2, 3] ``` -------------------------------- ### OpenAI::ArrayOf Usage Examples Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Demonstrates how to define arrays of specific types, including primitives, objects, and nested arrays. ```ruby # Array of strings required :tags, OpenAI::ArrayOf[String] # Array of objects required :items, OpenAI::ArrayOf[Item] # Nested arrays (not recommended) required :matrix, OpenAI::ArrayOf[OpenAI::ArrayOf[Integer]] ``` -------------------------------- ### Batch Moderation Check Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md This example demonstrates how to moderate multiple text inputs simultaneously by passing an array of strings to the `create` method. ```ruby responses = client.moderations.create( input: [ "First text to check", "Second text to check", "Third text to check" ] ) responses.results.each_with_index do |result, index| puts "Input #{index}: #{result.flagged ? 'FLAGGED' : 'OK'}" end ``` -------------------------------- ### Stream Responses API Example Source: https://github.com/openai/openai-ruby/blob/main/helpers.md Initiates a streaming request to the Responses API and iterates through text delta events. ```ruby stream = client.responses.stream( input: "Tell me a story about programming", model: "gpt-4o" ) stream.each do |event| case event when OpenAI::Streaming::ResponseTextDeltaEvent print(event.delta) end end puts ``` -------------------------------- ### Stream Chat Completions API Example Source: https://github.com/openai/openai-ruby/blob/main/helpers.md Initiates a streaming request to the Chat Completions API and iterates through content delta events. ```ruby stream = client.chat.completions.stream( model: "gpt-4", messages: [{role: "user", content: "Tell me a story about programming"}] ) stream.each do |event| case event when OpenAI::Streaming::ChatContentDeltaEvent print(event.delta) end end puts ``` -------------------------------- ### Creating a Chat Completion System Message Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/12-types.md Provides an example of how to format a system message parameter for chat completion requests, used to set the behavior of the assistant. ```ruby { role: "system", content: "You are a helpful assistant" } ``` -------------------------------- ### Define Basic Person Model Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Example of defining a simple structured output model with required string and integer fields. ```ruby class Person < OpenAI::BaseModel required :name, String required :age, Integer end ``` -------------------------------- ### Chat Completions with JSON Schema Output Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Example of using Chat Completions with a specified JSON schema for structured string output. ```ruby class Article < OpenAI::BaseModel required :title, String required :author, String required :content, String required :word_count, Integer end response = client.chat.completions.create( messages: [ { role: "system", content: "Write an article" }, { role: "user", content: "Topic: AI" } ], model: "gpt-4o", response_format: { type: "json_schema", json_schema: { name: "article", schema: Article.to_json_schema, strict: true } } ) # Parse response require "json" article_data = JSON.parse(response.choices[0].message.content) article = Article.new(article_data) ``` -------------------------------- ### Configuring Chat Completion Tool Choice Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/12-types.md Provides examples for setting the `tool_choice` parameter in chat completion requests to control whether the model should call a tool. Options include 'auto', 'required', or specifying a particular function. ```ruby # Auto: model decides { type: "auto" } ``` ```ruby # Required: must call a tool { type: "required" } ``` ```ruby # Specific tool { type: "function", function: { name: "get_weather" } } ``` -------------------------------- ### Raw JSON Schema for Responses Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Provides an example of using raw JSON schema for defining the expected output format when models are not suitable. This allows for precise control over the response structure. ```ruby response = client.responses.create( model: "gpt-4o", input: [ { role: "system", content: "Extract structured data" }, { role: "user", content: "..." } ], text: { format: { type: "json_schema", name: "data", strict: true, schema: { type: "object", properties: { name: { type: "string" }, age: { type: "integer" } }, required: ["name", "age"], additionalProperties: false } } } ) ``` -------------------------------- ### Handle PermissionDeniedError Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of catching a PermissionDeniedError when an operation is not permitted. ```ruby begin client.admin.organization.projects.create(...) rescue OpenAI::Errors::PermissionDeniedError => e puts "You don't have permission for this operation" end ``` -------------------------------- ### Preview Documentation Source: https://github.com/openai/openai-ruby/blob/main/CONTRIBUTING.md Generate and preview the project's documentation. An optional port can be specified. ```bash $ bundle exec rake docs:preview [PORT=8808] ``` -------------------------------- ### Handle ConversionError Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of catching a ConversionError when the API returns an unexpected data type. ```ruby begin # API returns unexpected type rescue OpenAI::Errors::ConversionError => e puts "Failed to parse response: #{e.message}" puts "Use #{e.message.split("Use").last}" # Shows how to access raw value end ``` -------------------------------- ### Create a Vector Store Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md Shows how to create a new vector store with a name and metadata. ```ruby store = client.vector_stores.create( name: "My Documents", metadata: { project: "research" } ) puts "Store ID: #{store.id}" ``` -------------------------------- ### Handle BadRequestError Example Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of catching a BadRequestError when making an API call with invalid parameters. ```ruby begin client.chat.completions.create( messages: [{ role: "invalid_role", content: "..." }], model: "gpt-4o" ) rescue OpenAI::Errors::BadRequestError => e puts "Invalid request: #{e.message}" puts "Error code: #{e.code}" puts "Parameter: #{e.param}" end ``` -------------------------------- ### Initialize OpenAI Client Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/INDEX.md Instantiate the OpenAI client with API key, organization ID, and project ID. Ensure environment variables are set for these credentials. ```ruby client = OpenAI::Client.new( api_key: ENV["OPENAI_API_KEY"], organization: ENV["OPENAI_ORG_ID"], project: ENV["OPENAI_PROJECT_ID"] ) ``` -------------------------------- ### Initialize Client with Custom Configuration Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/01-client.md Initialize the OpenAI client with custom configurations including API key, organization, project, max retries, and timeout. ```ruby client = OpenAI::Client.new( api_key: ENV["OPENAI_API_KEY"], organization: "org-123", project: "proj-456", max_retries: 5, timeout: 120.0 ) ``` -------------------------------- ### Initialize Client with Admin API Key Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/INDEX.md Initialize the OpenAI client using an admin API key for administrative tasks. Use this key with caution. ```ruby client = OpenAI::Client.new(admin_api_key: "admin-...") ``` -------------------------------- ### Create and Manage a Thread Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md Demonstrates creating a thread, adding a user message, running an assistant, polling for completion, and retrieving messages. ```ruby thread = client.beta.threads.create message = client.beta.threads.messages.create( thread_id: thread.id, role: "user", content: "What's the weather in NYC?" ) run = client.beta.threads.runs.create( thread_id: thread.id, assistant_id: assistant.id ) until ["completed", "failed"].include?(run.status) run = client.beta.threads.runs.retrieve(thread.id, run.id) sleep(1) end messages = client.beta.threads.messages.list(thread.id) messages.data.each do |msg| puts "#{msg.role}: #{msg.content[0].text.value}" end ``` -------------------------------- ### Initialize Client with API Key Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/01-client.md Basic initialization of the OpenAI client using an API key. Ensure the OPENAI_API_KEY environment variable is set. ```ruby require "openai" client = OpenAI::Client.new( api_key: ENV["OPENAI_API_KEY"] ) response = client.chat.completions.create( messages: [{ role: "user", content: "Hello!" }], model: "gpt-4o" ) ``` -------------------------------- ### OpenAI::Resources::Beta::Assistants#create Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md Creates an AI assistant with specified model, name, instructions, and tools. ```APIDOC ## OpenAI::Resources::Beta::Assistants#create ### Description Creates an AI assistant with specified model, name, instructions, and tools. ### Method `create(model:, name:, instructions:, tools: [], request_options: {})` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * `model` (String) - Required - The model to use for the assistant (e.g., "gpt-4o"). * `name` (String) - Required - The name of the assistant. * `instructions` (String) - Required - Instructions for the assistant. * `tools` (Array) - Optional - Tools to add to the assistant (e.g., function calling). * `request_options` (Hash) - Optional - Per-request configuration ### Request Example ```ruby # Create assistant assistant = client.beta.assistants.create( model: "gpt-4o", name: "My Assistant", instructions: "You are a helpful assistant", tools: [ { type: "function", function: { name: "get_weather", description: "Get weather information", parameters: { type: "object", properties: { location: { type: "string" } } } } } ] ) ``` ### Response #### Success Response `OpenAI::Models::Beta::Assistant` ### Response Example ```ruby puts "Assistant created: #{assistant.id}" ``` ``` -------------------------------- ### Initialize OpenAI Client with Constructor Options Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/03-configuration.md Configure the OpenAI client by passing various options directly to the constructor. This is useful for setting API keys, organization IDs, timeouts, and retry settings programmatically. ```ruby client = OpenAI::Client.new( api_key: ENV["OPENAI_API_KEY"], admin_api_key: ENV["OPENAI_ADMIN_KEY"], workload_identity: nil, organization: ENV["OPENAI_ORG_ID"], project: ENV["OPENAI_PROJECT_ID"], webhook_secret: ENV["OPENAI_WEBHOOK_SECRET"], base_url: ENV["OPENAI_BASE_URL"], max_retries: 2, timeout: 600.0, initial_retry_delay: 0.5, max_retry_delay: 8.0 ) ``` -------------------------------- ### Initialize OpenAI Client and Access Chat Completions Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/04-chat-completions.md Instantiate the OpenAI client with your API key and access the chat completions resource. ```ruby client = OpenAI::Client.new(api_key: "sk-...") # Access completions completion = client.chat.completions ``` -------------------------------- ### Multi-Turn Conversation Initialization Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/04-chat-completions.md Initialize a multi-turn conversation by providing an array of messages, starting with a system message. ```ruby messages = [ { role: "system", content: "You are a helpful math tutor." } ] ``` -------------------------------- ### Webhook Initialization and Unwrapping Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/INDEX.md Demonstrates how to initialize the client with a webhook secret and then unwrap incoming webhook requests to verify their authenticity. ```ruby client = OpenAI::Client.new( api_key: "sk-…", webhook_secret: ENV["OPENAI_WEBHOOK_SECRET"] ) event = client.webhooks.unwrap(request_body, request.env) ``` -------------------------------- ### Define Event Model with Enum Status Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Example of defining a structured output model with an enumerated field for status. ```ruby class Event < OpenAI::BaseModel required :name, String required :status, OpenAI::EnumOf[:pending, :confirmed, :cancelled] end ``` -------------------------------- ### Initialize Client with Environment Variables Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/01-client.md Initialize the OpenAI client, which automatically reads API key, organization ID, and project ID from environment variables. ```ruby # OPENAI_API_KEY, OPENAI_ORG_ID, OPENAI_PROJECT_ID will be read automatically client = OpenAI::Client.new ``` -------------------------------- ### OpenAI::Client Initialization Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/01-client.md Initializes the OpenAI client with various configuration options for API interaction. ```APIDOC ## OpenAI::Client Constructor ### Description Initializes the OpenAI client with API keys, organization/project IDs, and other configuration settings for interacting with the OpenAI API. ### Constructor Parameters #### Parameters - **api_key** (String) - Optional - Your OpenAI API key. Mutually exclusive with `workload_identity`. - **admin_api_key** (String) - Optional - Your OpenAI admin API key for administrative operations. - **workload_identity** (OpenAI::Auth::WorkloadIdentity) - Optional - OAuth2 workload identity configuration for token exchange authentication. Mutually exclusive with `api_key`. - **organization** (String) - Optional - OpenAI organization ID for organization-level API calls. - **project** (String) - Optional - OpenAI project ID for project-level API calls. - **webhook_secret** (String) - Optional - Secret key for verifying webhook signatures. - **base_url** (String) - Optional - Override the default base URL for the API. Can be set via `ENV["OPENAI_BASE_URL"]`. - **max_retries** (Integer) - Optional - Maximum number of retry attempts for failed requests. - **timeout** (Float) - Optional - Per-request timeout in seconds. - **initial_retry_delay** (Float) - Optional - Initial retry delay in seconds. Uses exponential backoff with jitter. - **max_retry_delay** (Float) - Optional - Maximum retry delay in seconds. ### Resource Properties The Client provides access to API resources as read-only properties: - **completions** (OpenAI::Resources::Completions) - Access to legacy completions endpoint - **chat** (OpenAI::Resources::Chat) - Access to chat completions (includes streaming) - **embeddings** (OpenAI::Resources::Embeddings) - Generate embeddings for text - **files** (OpenAI::Resources::Files) - Manage uploaded files - **images** (OpenAI::Resources::Images) - Generate and edit images - **audio** (OpenAI::Resources::Audio) - Text-to-speech, speech-to-text - **moderations** (OpenAI::Resources::Moderations) - Content moderation - **models** (OpenAI::Resources::Models) - List and retrieve model information - **fine_tuning** (OpenAI::Resources::FineTuning) - Fine-tune models - **graders** (OpenAI::Resources::Graders) - Access grader models - **vector_stores** (OpenAI::Resources::VectorStores) - Manage vector stores for retrieval - **webhooks** (OpenAI::Resources::Webhooks) - Manage and verify webhooks - **beta** (OpenAI::Resources::Beta) - Beta features and assistants - **batches** (OpenAI::Resources::Batches) - Batch API for asynchronous requests - **uploads** (OpenAI::Resources::Uploads) - Upload large files in parts - **admin** (OpenAI::Resources::Admin) - Administrative API access - **responses** (OpenAI::Resources::Responses) - Response generation API - **realtime** (OpenAI::Resources::Realtime) - Real-time API access - **conversations** (OpenAI::Resources::Conversations) - Manage conversations - **evals** (OpenAI::Resources::Evals) - Manage evaluations - **containers** (OpenAI::Resources::Containers) - Manage containers - **skills** (OpenAI::Resources::Skills) - Manage skills - **videos** (OpenAI::Resources::Videos) - Video API access ``` -------------------------------- ### Define Person Model with Nested Address Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Example of defining a structured output model with a nested object type. ```ruby class Address < OpenAI::BaseModel required :street, String required :city, String required :country, String end class Person < OpenAI::BaseModel required :name, String required :age, Integer required :address, Address end ``` -------------------------------- ### Error Handling for File Operations Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/05-file-handling.md Provides examples of how to handle potential errors during file operations using begin-rescue blocks. ```APIDOC ## Error Handling ### Description Illustrates how to gracefully handle common errors that may occur during file upload operations, such as invalid requests or API issues. ### Method N/A (Client-side error handling) ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby begin file = client.files.create( file: Pathname("data.jsonl"), purpose: "fine-tune" ) rescue OpenAI::Errors::BadRequestError => e puts "Invalid file: #{e.message}" rescue OpenAI::Errors::NotFoundError => e puts "File not found" rescue OpenAI::Errors::APIError => e puts "Upload failed: #{e.message}" end ``` ### Response N/A (Error messages are printed to standard output in the example) ``` -------------------------------- ### Initialize OpenAI Client Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/01-client.md Instantiate the OpenAI client with various configuration options. API key or workload identity is required for authentication. Other parameters control retry behavior, timeouts, and organization-specific settings. ```ruby OpenAI::Client.new( api_key: "YOUR_API_KEY", organization: "YOUR_ORG_ID" ) ``` -------------------------------- ### File Upload for Assistants API Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/05-file-handling.md Shows how to upload files to be used within the Assistants API, for example, as documents for analysis. ```APIDOC ## POST /files (Assistants API Document Upload) ### Description Uploads a file to be associated with an Assistant, allowing it to access and process the file's content. ### Method `POST` ### Endpoint `/v1/files` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (Pathname) - Required - The document file to upload. - **purpose** (String) - Required - Must be set to `"assistants"`. ### Request Example ```ruby # Upload document file = client.files.create( file: Pathname("document.pdf"), purpose: "assistants" ) # Use in assistant (example) message = client.beta.threads.messages.create( thread_id: "thread-123", role: "user", content: [ { type: "text", text: "Analyze this:" }, { type: "file", file_id: file.id } ] ) ``` ### Response (See Simple File Upload response structure) ``` -------------------------------- ### Initialize OpenAI Client and Create Chat Completion Source: https://github.com/openai/openai-ruby/blob/main/README.md Initialize the OpenAI client with your API key and create a chat completion request. The API key is automatically read from the OPENAI_API_KEY environment variable if not explicitly provided. ```ruby 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) ``` -------------------------------- ### File Upload for Fine-Tuning Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/05-file-handling.md Demonstrates uploading a file specifically for use in fine-tuning an OpenAI model. ```APIDOC ## POST /files (Fine-Tuning Data Upload) ### Description Uploads a dataset file intended for use as training data in a fine-tuning job. ### Method `POST` ### Endpoint `/v1/files` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (Pathname) - Required - The training data file (e.g., JSONL format). - **purpose** (String) - Required - Must be set to `"fine-tune"`. ### Request Example ```ruby # Upload training data training_file = client.files.create( file: Pathname("training.jsonl"), purpose: "fine-tune" ) # Start fine-tuning job (example) job = client.fine_tuning.jobs.create( model: "gpt-3.5-turbo", training_file: training_file.id ) ``` ### Response (See Simple File Upload response structure) ``` -------------------------------- ### Define Response Model with Union Type Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Example of defining a structured output model where a field can be one of several types. ```ruby class Response < OpenAI::BaseModel required :result, OpenAI::UnionOf[String, Integer, Array] end ``` -------------------------------- ### Run Tests Source: https://github.com/openai/openai-ruby/blob/main/CONTRIBUTING.md Execute all tests for the project. ```bash $ bundle exec rake test ``` -------------------------------- ### Define Team Model with Array of Persons Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Example of defining a structured output model containing an array of other structured models. ```ruby class Team < OpenAI::BaseModel required :name, String required :members, OpenAI::ArrayOf[Person] end ``` -------------------------------- ### Using RequestOptions as a Hash Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/03-configuration.md Demonstrates the simpler method of passing request options as a hash directly within the API call. This is useful for quick configurations. ```ruby # As a hash (simpler) response = client.chat.completions.create( messages: [...], model: "gpt-4o", request_options: { max_retries: 5, timeout: 120.0 } ) ``` -------------------------------- ### Define Person Model with Nullable Nickname Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Example of defining a structured output model with an optional, nullable string field. ```ruby class Person < OpenAI::BaseModel required :name, String required :age, Integer required :nickname, String, nil?: true # nullable end ``` -------------------------------- ### Administrative API Operations Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md Demonstrates listing organization users, creating a project, and creating an API key for a project. ```ruby # List organization users users = client.admin.organization.users.list # Create project project = client.admin.organization.projects.create( name: "My Project" ) # Create API key api_key = client.admin.organization.projects.api_keys.create( project_id: project.id ) ``` -------------------------------- ### Retrieve Batch Status Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/08-completions-batches.md Get the current status and details of a specific batch using its ID. Useful for monitoring progress. ```ruby batch = client.batches.retrieve("batch_123") puts "Status: #{batch.status}" puts "Processed: #{batch.request_counts.completed}" puts "Failed: #{batch.request_counts.failed}" if batch.status == "completed" puts "Output file: #{batch.output_file_id}" end ``` -------------------------------- ### File Listing with Auto-Pagination Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/05-file-handling.md Demonstrates how to list files and automatically paginate through the results using the `auto_paging_each` method. ```APIDOC ## GET /files (Pagination) ### Description Retrieves a list of uploaded files. The results support auto-pagination, allowing easy iteration over all available files. ### Method `GET` ### Endpoint `/v1/files` ### Parameters #### Path Parameters None #### Query Parameters - **limit** (Integer) - Optional - The maximum number of items to return per page. - **order** (String) - Optional - The sort order for the files ('asc' or 'desc'). - **after** (String) - Optional - A cursor for pagination. Return files after this file ID. - **before** (String) - Optional - A cursor for pagination. Return files before this file ID. ### Request Example (Auto-paging) ```ruby all_files = [] page = client.files.list(limit: 100) # Method 1: Auto-paging each page.auto_paging_each do |file| all_files << file puts "Loaded #{file.filename}" end ``` ### Request Example (Manual Pagination) ```ruby all_files = [] page = client.files.list(limit: 100) # Method 2: Manual pagination loop do page.data.each { |file| all_files << file } break unless page.next_page? page = page.next_page end ``` ### Response #### Success Response (200) - **data** (Array) - A list of file objects. - **object** (String) - The type of object, usually "list". - **has_more** (Boolean) - Indicates if there are more results available. #### Response Example ```json { "data": [ { "id": "file-xyz789", "object": "file", "filename": "data.jsonl", "purpose": "fine-tune", "bytes": 1024, "created_at": 1678886400 } // ... more files ], "object": "list", "has_more": true } ``` ``` -------------------------------- ### Handle SubjectTokenProviderError Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of handling SubjectTokenProviderError when setting up workload identity. It shows how to access the provider class and the underlying cause of the error. ```ruby begin provider = OpenAI::Auth::SubjectTokenProviders::K8sServiceAccountTokenProvider.new workload_identity = OpenAI::Auth::WorkloadIdentity.new(provider: provider) client = OpenAI::Client.new(workload_identity: workload_identity) rescue OpenAI::Errors::SubjectTokenProviderError => e puts "Token provider failed: #{e.message}" puts "Provider: #{e.provider.class}" puts "Cause: #{e.cause.message}" end ``` -------------------------------- ### Set Organization and Project IDs via Environment Variables Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/09-webhooks-auth.md Use environment variables OPENAI_ORG_ID and OPENAI_PROJECT_ID to configure organization and project for the client. ```bash export OPENAI_ORG_ID="org-123" export OPENAI_PROJECT_ID="proj-456" ``` -------------------------------- ### Manage Evaluation Runs Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md Shows how to create an evaluation run with a specified model and configuration, and then retrieve its results. ```ruby # Create eval run eval_run = client.evals.runs.create( model: "gpt-4o", config: { /* config */ } ) # Get eval results results = client.evals.runs.retrieve(eval_run.id) ``` -------------------------------- ### Responses API with Structured Output Model Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/06-structured-output.md Example of using the Responses API to extract structured data into a defined Ruby model. ```ruby class CalendarEvent < OpenAI::BaseModel required :name, String required :date, String required :participants, OpenAI::ArrayOf[String] end response = client.responses.create( model: "gpt-4o", input: [ { role: "system", content: "Extract event information" }, { role: "user", content: "Alice and Bob are meeting on Friday at 2pm" } ], text: CalendarEvent ) # Response includes parsed output response.output.each do |output| if output.is_a?(OpenAI::Models::Responses::ResponseOutputText) event = output.parsed # Instance of CalendarEvent puts "Event: #{event.name}" puts "Date: #{event.date}" end end ``` -------------------------------- ### Streaming Structured Outputs with Responses API Source: https://github.com/openai/openai-ruby/blob/main/helpers.md Example of streaming structured output (Haiku object) using the Responses API and parsing it from a ResponseTextDoneEvent. ```ruby class Haiku < OpenAI::BaseModel field :first_line, String field :second_line, String field :third_line, String end stream = client.responses.stream( input: "Write a haiku about Ruby", model: "gpt-4o", text: Haiku ) stream.each do |event| case event when OpenAI::Streaming::ResponseTextDoneEvent haiku = event.parsed puts("First line: #{haiku.first_line}") puts("Second line: #{haiku.second_line}") puts("Third line: #{haiku.third_line}") end end ``` -------------------------------- ### Add Files to a Vector Store Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md Demonstrates uploading a file and then adding it to a specific vector store using file batches. ```ruby # Upload file file = client.files.create( file: Pathname("document.pdf"), purpose: "assistants" ) # Create file batch batch = client.vector_stores.file_batches.create( vector_store_id: store.id, file_ids: [file.id] ) puts "Files added: #{batch.file_counts.completed}" ``` -------------------------------- ### Handle OpenAI API Errors Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md Provides an example of how to catch and handle specific OpenAI API errors like BadRequestError and general APIError. ```ruby begin response = client.moderations.create(input: "test") rescue OpenAI::Errors::BadRequestError => e puts "Invalid input: #{e.message}" rescue OpenAI::Errors::APIError => e puts "API error: #{e.message}" end ``` -------------------------------- ### Handle InvalidWebhookSignatureError Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/02-errors.md Example of rescuing InvalidWebhookSignatureError to handle webhook signature validation failures. It suggests logging the issue and returning an error response. ```ruby begin event = client.webhooks.unwrap(raw_body, headers) rescue OpenAI::Errors::InvalidWebhookSignatureError => e puts "Webhook signature invalid. Request may be forged." # Return 400 to webhook sender end ``` -------------------------------- ### Vision API with Image URL Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/INDEX.md Example of using the chat completions API with vision capabilities, including an image URL in the user's message content. ```ruby response = client.chat.completions.create( messages: [{ role: "user", content: [ { type: "text", text: "Describe this" }, { type: "image_url", image_url: { url: "https://..." } } ] }], model: "gpt-4o" ) ``` -------------------------------- ### Create Fine-Tuning Job Source: https://github.com/openai/openai-ruby/blob/main/_autodocs/11-other-resources.md Initiate a fine-tuning job for a model using your custom training data. Ensure your training file is in JSONL format and uploaded. ```ruby # Prepare training data (JSONL format) # Each line: {"messages": [{"role": "user", "content": "..."}, ...] } training_file = client.files.create( file: Pathname("training_data.jsonl"), purpose: "fine-tune" ) # Start fine-tuning job job = client.fine_tuning.jobs.create( model: "gpt-3.5-turbo", training_file: training_file.id, suffix: "my-suffix", hyperparameters: { epochs: 3, learning_rate_multiplier: 1.0 } ) puts "Job ID: #{job.id}" puts "Status: #{job.status}" ```