### Install and Serve Ollama Locally Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Install Ollama using Homebrew, start the Ollama server, and pull a model like Llama 3. These commands are for macOS. ```bash brew install ollama ollama serve ollama pull llama3:latest # In new terminal tab. ``` -------------------------------- ### Full Vision Example: Upload, Create Assistant, Message, Run, and Wait Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md A comprehensive example demonstrating the workflow for using vision capabilities. It includes uploading an image, creating an assistant, adding the image to a message, running the thread, and waiting for completion. ```ruby require "openai" # Make a client client = OpenAI::Client.new( access_token: "access_token_goes_here", log_errors: true # Don't log errors in production. ) # Upload image as a file file_id = client.files.upload( parameters: { file: "path/to/example.png", purpose: "assistants", } )["id"] # Create assistant (You could also use an existing one here) assistant_id = client.assistants.create( parameters: { model: "gpt-4o", name: "Image reader", instructions: "You are an image describer. You describe the contents of images.", } )["id"] # Create thread thread_id = client.threads.create["id"] # Add image in message client.messages.create( thread_id: thread_id, parameters: { role: "user", # Required for manually created messages content: [ { "type": "text", "text": "What's in this image?" }, { "type": "image_file", "image_file": { "file_id": file_id } } ] } ) # Run thread run_id = client.runs.create( thread_id: thread_id, parameters: { assistant_id: assistant_id } )["id"] # Wait until run in complete status = nil until status == "completed" do sleep(0.1) status = client.runs.retrieve(id: run_id, thread_id: thread_id)['status'] end ``` -------------------------------- ### Basic OpenAI Client Setup Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/module-openai.md Sets up the OpenAI client globally with an API key and organization ID from environment variables. ```ruby require "openai" OpenAI.configure do |config| config.access_token = ENV["OPENAI_API_KEY"] config.organization_id = ENV["OPENAI_ORG_ID"] end client = OpenAI::Client.new ``` -------------------------------- ### Install ruby-openai gem Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md After adding the gem to your Gemfile, run `bundle install` to install it. ```bash bundle install ``` -------------------------------- ### Initialize OpenAI Client and Batches Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/finetunes-batches.md Instantiate the OpenAI client and access the batches interface. This is the starting point for batch operations. ```ruby client = OpenAI::Client.new(access_token: "sk-...") batches = client.batches ``` -------------------------------- ### Install ruby-openai gem directly Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Alternatively, you can install the gem directly using `gem install`. ```bash gem install ruby-openai ``` -------------------------------- ### Streaming with Callback Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/errors.md This example demonstrates how to set up a streaming request with a callback to process chunks of data as they arrive. Errors during streaming are handled by Faraday. ```ruby client.chat( parameters: { model: "gpt-4", messages: [{ role: "user", content: "Hello" }], stream: proc { |chunk, response| puts chunk } } ) ``` -------------------------------- ### File Search with Vector Stores Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Guides through uploading a file, creating a vector store, and setting up an assistant for file search. Includes retrieving chunks used in the search results. ```ruby require "openai" # Make a client client = OpenAI::Client.new( access_token: "access_token_goes_here", log_errors: true # Don't log errors in production. ) # Upload your file(s) file_id = client.files.upload( parameters: { file: "path/to/somatosensory.pdf", purpose: "assistants" } )["id"] # Create a vector store to store the vectorised file(s) vector_store_id = client.vector_stores.create(parameters: {})["id"] # Vectorise the file(s) vector_store_file_id = client.vector_store_files.create( vector_store_id: vector_store_id, parameters: { file_id: file_id } )["id"] # Check that the file is vectorised (wait for status to be "completed") client.vector_store_files.retrieve(vector_store_id: vector_store_id, id: vector_store_file_id)["status"] # Create an assistant, referencing the vector store assistant_id = client.assistants.create( parameters: { model: "gpt-4o", name: "Answer finder", instructions: "You are a file search tool. Find the answer in the given files, please.", tools: [ { type: "file_search" } ], tool_resources: { file_search: { vector_store_ids: [vector_store_id] } } } )["id"] # Create a thread with your question thread_id = client.threads.create(parameters: { messages: [ { role: "user", content: "Find the description of a nociceptor." } ] })["id"] # Run the thread to generate the response. Include the "GIVE ME THE CHUNKS" incantation. run_id = client.runs.create( thread_id: thread_id, parameters: { assistant_id: assistant_id }, query_parameters: { include: ["step_details.tool_calls[*].file_search.results[*].content"] } # incantation )["id"] # Get the steps that happened in the run steps = client.run_steps.list( thread_id: thread_id, run_id: run_id, parameters: { order: "asc" } ) # Retrieve all the steps. Include the "GIVE ME THE CHUNKS" incantation again. steps = steps["data"].map do |step| client.run_steps.retrieve( thread_id: thread_id, run_id: run_id, id: step["id"], parameters: { include: ["step_details.tool_calls[*].file_search.results[*].content"] } # incantation ) end ``` -------------------------------- ### Configure OpenAI Client Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/START-HERE.md Configure the OpenAI client with your access token. This setup is required before making any API calls. ```ruby require "openai" OpenAI.configure do |config| config.access_token = "sk-..." end client = OpenAI::Client.new ``` -------------------------------- ### runs.create Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/threads-messages-runs.md Create and start a new run. This method initiates a run on a thread with a specified assistant. ```APIDOC ## POST /threads/{thread_id}/runs ### Description Create and start a new run. ### Method POST ### Endpoint /threads/{thread_id}/runs ### Parameters #### Path Parameters - **thread_id** (string) - Required - Thread ID #### Request Body - **parameters** (object) - Required - Run parameters - **assistant_id** (string) - Required - Assistant ID to run - **model** (string) - Optional - Override assistant's model - **instructions** (string) - Optional - Override assistant's instructions - **additional_instructions** (string) - Optional - Extra instructions for this run - **tools** (array) - Optional - Override assistant's tools - **file_ids** (array) - Optional - A list of file IDs that the assistant should use for this run. - **metadata** (object) - Optional - Set of 16 key-value pairs that can be used to store additional data. ### Request Example ```json { "thread_id": "thread_abc123", "parameters": { "assistant_id": "asst_abc123" } } { "thread_id": "thread_abc123", "parameters": { "assistant_id": "asst_abc123", "additional_instructions": "Please be concise" } } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the run. - **object** (string) - The type of object returned, should be `thread.run`. - **assistant_id** (string) - The ID of the assistant used for the run. - **thread_id** (string) - The ID of the thread that the run belongs to. - **status** (string) - The status of the run, initially `queued` or `in_progress`. - **created_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **expires_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **started_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **completed_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **failed_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **model** (string) - The model that the assistant used to execute this run. - **instructions** (string) - The instructions that the assistant used to execute this run. - **tools** (array) - Override the model's instructions for the run. - **file_ids** (array) - A list of file IDs that the assistant should use for this run. - **usage** (object) - Details about the run's usage. - **metadata** (object) - Set of 16 key-value pairs that can be used to store additional data. ``` -------------------------------- ### create_thread_and_run Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/threads-messages-runs.md Creates a new thread and starts a run on it in a single atomic operation. This is useful for initiating a conversation with an assistant. ```APIDOC ## create_thread_and_run ### Description Create a thread and start a run in one operation. ### Method POST (inferred) ### Endpoint /threads/runs (inferred) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **parameters** (Hash) - Required - Thread and run parameters - **parameters[:assistant_id]** (String) - Required - Assistant ID to run - **parameters[:thread]** (Hash) - Optional - Thread creation parameters - **parameters[:thread][:messages]** (Array) - Optional - Initial messages ### Request Example ```ruby run = client.runs.create_thread_and_run( parameters: { assistant_id: "asst_abc123", thread: { messages: [ { role: "user", content: "Hello!" } ] } } ) thread_id = run["thread_id"] run_id = run["id"] ``` ### Response #### Success Response (200) - **Run object** (Hash) - The created run object, which includes the newly created thread ID. #### Response Example (See Request Example for structure, includes thread_id and id) ``` -------------------------------- ### Configuration Options Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/README.md Details on all configuration options available for the ruby-openai gem, including global and per-client settings, environment variables, and Azure setup. ```APIDOC ## Configuration Options ### Description Covers all available configuration options for the ruby-openai gem, enabling customization of API interactions, authentication, and environment-specific settings. ### Global Configuration - **`OpenAI.configure`**: The primary method for setting global configuration options, such as API keys and default settings. ### Per-Client Overrides - Ability to override global configurations for individual `OpenAI::Client` instances, allowing for flexible usage scenarios. ### Environment Variables - Support for configuring the gem using environment variables, providing a convenient way to manage sensitive information like API keys. ### Azure Setup - Specific instructions and options for configuring the gem to work with Azure OpenAI services. ### Other Options - **Custom Headers and Middleware**: Options for adding custom HTTP headers or integrating middleware. - **Timeout Configuration**: Setting request timeouts to manage API call durations. - **Error Logging**: Configuring how errors are logged. Refer to `configuration.md` for a complete list and detailed explanations of all configuration parameters and their usage. ### Source Code Reference Links to the source code are provided in the format `configuration.md`. ``` -------------------------------- ### Function Calling with OpenAI API in Ruby Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Demonstrates how to define a function, set up a tool call with the OpenAI API, and process the response to call the function and get a final answer. Ensure the `get_current_weather` function is defined and the client is initialized. ```ruby def get_current_weather(location:, unit: "fahrenheit") # Here you could use a weather api to fetch the weather. "The weather in #{location} is nice 🌞 #{unit}" end messages = [ { "role": "user", "content": "What is the weather like in San Francisco?", }, ] response = client.chat( parameters: { model: "gpt-4o", messages: messages, # Defined above because we'll use it again tools: [ { type: "function", function: { name: "get_current_weather", description: "Get the current weather in a given location", parameters: { # Format: https://json-schema.org/understanding-json-schema type: :object, properties: { location: { type: :string, description: "The city and state, e.g. San Francisco, CA", }, unit: { type: "string", enum: %w[celsius fahrenheit], }, }, required: ["location"], }, }, } ], # Optional, defaults to "auto" # Can also put "none" or specific functions, see docs tool_choice: "required" }, ) message = response.dig("choices", 0, "message") if message["role"] == "assistant" && message["tool_calls"] # For a subsequent message with the role "tool", OpenAI requires the preceding message to have a single tool_calls argument. messages << message message["tool_calls"].each do |tool_call| tool_call_id = tool_call.dig("id") function_name = tool_call.dig("function", "name") function_args = JSON.parse( tool_call.dig("function", "arguments"), { symbolize_names: true }, ) function_response = case function_name when "get_current_weather" get_current_weather(**function_args) # => "The weather is nice 🌞" else # decide how to handle end messages << { tool_call_id: tool_call_id, role: "tool", name: function_name, content: function_response } # Extend the conversation with the results of the functions end second_response = client.chat( parameters: { model: "gpt-4o", messages: messages } ) puts second_response.dig("choices", 0, "message", "content") # At this point, the model has decided to call functions, you've called the functions # and provided the response back, and the model has considered this and responded. end # => "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." ``` -------------------------------- ### Create and Start a New Run Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/threads-messages-runs.md Initiate a new run for a thread, associating it with an assistant. You can override default assistant parameters like model and instructions. ```ruby run = client.runs.create( thread_id: "thread_abc123", parameters: { assistant_id: "asst_abc123" } ) un_id = run["id"] # With additional instructions run = client.runs.create( thread_id: "thread_abc123", parameters: { assistant_id: "asst_abc123", additional_instructions: "Please be concise" } ) ``` -------------------------------- ### OpenAI::Client - Main client class and all top-level API accessors Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/README.md Documentation for the main OpenAI::Client class, which provides access to all top-level API functionalities. This includes details on constructor signatures, instance methods, parameters, return types, error conditions, and usage examples. ```APIDOC ## OpenAI::Client ### Description Provides access to all top-level API functionalities within the ruby-openai gem. This class is the primary interface for interacting with the OpenAI API. ### Constructor Complete initialization with parameters and defaults. Refer to `api-reference/client.md` for full details. ### Instance Methods Full documentation for instance methods, including method signatures, parameter tables, return types, error conditions, and usage examples. Key methods include: - **chat**: For Chat Completions, including streaming. - **embeddings**: For generating embeddings. - **images**: For DALL·E image generation. - **audio**: For audio transcription and synthesis. - **files**: For file management operations like upload. Refer to `api-reference/client.md` for a complete list and detailed documentation. ### Usage Examples Practical usage examples are provided within the documentation for each method, demonstrating common patterns such as making chat requests and streaming responses. ### Source Code Reference Links to the source code are provided in the format `lib/openai/client.rb:line-number`. ``` -------------------------------- ### Configure OpenAI with Environment Variables Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/configuration.md This example shows how to configure the OpenAI gem using environment variables for sensitive information like API keys. It sets the access token, organization ID, and request timeout. ```ruby OpenAI.configure do |config| config.access_token = ENV["OPENAI_API_KEY"] config.organization_id = ENV["OPENAI_ORG_ID"] config.request_timeout = 300 end client = OpenAI::Client.new # Client uses configured values ``` -------------------------------- ### Create a Response using Responses API Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Initiate a new interaction with the Responses API. This example uses a hypothetical 'gpt-5' model and includes input and reasoning parameters. ```ruby response = client.responses.create(parameters: { model: "gpt-5", input: "Hello! I'm Szymon!", reasoning: { "effort": "minimal" } }) puts response.dig("output", 0, "content", 0, "text") # => Thinking about how to answer this... puts response.dig("output", 1, "content", 0, "text") # => Hi Szymon! Great to meet you. How can I help today? ``` -------------------------------- ### Create Thread and Run in One Operation Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/threads-messages-runs.md Use this method to create a new thread and immediately start a run with an assistant. It requires an assistant ID and can optionally include initial messages for the thread. ```ruby runs.create_thread_and_run(parameters: {}) ``` ```ruby run = client.runs.create_thread_and_run( parameters: { assistant_id: "asst_abc123", thread: { messages: [ { role: "user", content: "Hello!" } ] } } ) thread_id = run["thread_id"] run_id = run["id"] ``` -------------------------------- ### Initialize OpenAI Client and Finetunes Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/finetunes-batches.md Instantiate the OpenAI client and access the finetunes interface. Ensure you have your access token ready. ```ruby client = OpenAI::Client.new(access_token: "sk-...") finetunes = client.finetunes ``` -------------------------------- ### Initialize VectorStoreFiles Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/vector-stores.md Instantiate the VectorStoreFiles class with an OpenAI client instance. ```ruby OpenAI::VectorStoreFiles.new(client:) ``` -------------------------------- ### GET Request Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/http.md Make an HTTP GET request to a specified API endpoint path. Supports optional query parameters. ```APIDOC ## GET /path ### Description Make an HTTP GET request to retrieve data from an API endpoint. ### Method GET ### Endpoint /{path} ### Parameters #### Query Parameters - **parameters** (Hash) - Optional - Query parameters to include in the request. ### Request Example ```ruby response = client.get(path: "/models") response = client.get(path: "/files", parameters: { limit: 10 }) ``` ### Response #### Success Response - **(Hash or String)** - Parsed JSON response, or original string if parsing fails. ``` -------------------------------- ### Require ruby-openai Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md After installation, require the gem in your Ruby code. ```ruby require "openai" ``` -------------------------------- ### Initialize OpenAI Audio Client Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/audio.md Instantiate the Audio client using an existing OpenAI::Client instance. This client is required for all subsequent audio operations. ```ruby client = OpenAI::Client.new(access_token: "sk-...") audio = client.audio ``` -------------------------------- ### runs.retrieve Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/threads-messages-runs.md Get details about a specific run. This method retrieves a single run object by its ID. ```APIDOC ## GET /threads/{thread_id}/runs/{run_id} ### Description Get details about a run. ### Method GET ### Endpoint /threads/{thread_id}/runs/{run_id} ### Parameters #### Path Parameters - **thread_id** (string) - Required - Thread ID - **id** (string) - Required - Run ID ### Response #### Success Response (200) - **id** (string) - The ID of the run. - **object** (string) - The type of object returned, should be `thread.run`. - **assistant_id** (string) - The ID of the assistant used for the run. - **thread_id** (string) - The ID of the thread that the run belongs to. - **status** (string) - The status of the run. - **created_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **expires_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **started_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **completed_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **failed_at** (integer) - Unix timestamp, where the timestamp is in seconds. - **model** (string) - The model that the assistant used to execute this run. - **instructions** (string) - The instructions that the assistant used to execute this run. - **tools** (array) - Override the model's instructions for the run. - **file_ids** (array) - A list of file IDs that the assistant should use for this run. - **usage** (object) - Details about the run's usage. - **metadata** (object) - Set of 16 key-value pairs that can be used to store additional data. ``` -------------------------------- ### Initialize OpenAI Client Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/index.md Instantiate the OpenAI client with your access token. This is the first step before making any API requests. ```ruby client = OpenAI::Client.new(access_token: "sk-...") ``` -------------------------------- ### Retrieve a Specific Vector Store Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/vector-stores.md Get detailed information about a single vector store by its ID. ```ruby vs = client.vector_stores.retrieve(id: "vs_abc123") puts "Name: #{vs['name']}" puts "Files: #{vs['file_counts']['total']}" puts "Bytes: #{vs['usage_bytes']}" ``` -------------------------------- ### client.beta(apis) Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/client.md Create a new client instance with OpenAI-Beta headers for beta API features. ```APIDOC ## client.beta(apis) ### Description Create a new client instance with OpenAI-Beta headers for beta API features. ### Parameters #### Path Parameters - **apis** (Hash) - Required - Beta API identifiers and versions (e.g., `{ assistants: "v2" }`) ### Returns New Client instance with beta headers configured ### Example ```ruby beta_client = client.beta(assistants: "v2") assistants = beta_client.assistants.list ``` ``` -------------------------------- ### Common Workflow: Create Assistant and Thread Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/assistants.md Demonstrates the initial steps of a common workflow: creating an assistant and then creating a thread with an initial user message. ```ruby assistant = client.assistants.create( parameters: { model: "gpt-4", name: "Research Assistant", instructions: "You help users research topics" } ) assistant_id = assistant["id"] thread = client.threads.create( parameters: { messages: [ { role: "user", content: "What is quantum computing?" } ] } ) thread_id = thread["id"] ``` -------------------------------- ### Create Beta Client in Ruby Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/client.md Use this to create a new client instance with OpenAI-Beta headers for beta API features. Requires a hash of beta API identifiers and versions. ```ruby client.beta(apis) ``` ```ruby beta_client = client.beta(assistants: "v2") assistants = beta_client.assistants.list ``` -------------------------------- ### Initialize OpenAI Client Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/client.md Instantiate the OpenAI client with default or custom configurations. You can also provide a block to customize the Faraday connection. ```ruby client = OpenAI::Client.new ``` ```ruby client = OpenAI::Client.new( access_token: "sk-வுகளை", organization_id: "org-வுகளை", request_timeout: 300 ) ``` ```ruby client = OpenAI::Client.new do |conn| conn.use MyMiddleware end ``` -------------------------------- ### Check for Deprecations Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Runs a specific RSpec test file to check for deprecated features. This command requires RSpec and the gem to be installed. ```ruby bundle exec ruby -e "Warning[:deprecated] = true; require 'rspec'; exit RSpec::Core::Runner.run(['spec/openai/client/http_spec.rb:25'])" ``` -------------------------------- ### OpenAI::Models.new Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/models.md Initializes a new Models API client instance. Requires an existing OpenAI client. ```APIDOC ## OpenAI::Models.new ### Description Initializes a new Models API client instance. Requires an existing OpenAI client. ### Parameters #### Path Parameters - **client** (OpenAI::Client) - Required - OpenAI client instance ### Request Example ```ruby client = OpenAI::Client.new(access_token: "sk-...") models = OpenAI::Models.new(client: client) # Or access through the client models = client.models ``` ``` -------------------------------- ### Get Details of a Conversation Item Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Fetch detailed information for a specific item within a conversation. Both conversation and item IDs are mandatory. ```ruby conversations.get_item(conversation_id:, item_id:) ``` ```ruby item = client.conversations.get_item( conversation_id: "conv_abc123", item_id: "item_xyz789" ) ``` -------------------------------- ### Get Custom Headers Dictionary Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/http.md Retrieves the custom headers dictionary. It is lazily initialized, creating an empty hash on first access. ```ruby extra_headers ``` -------------------------------- ### Create Admin Client in Ruby Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/client.md Use this to create a new client instance with an admin token for administrative endpoints. Throws OpenAI::AuthenticationError if no admin_token is configured. ```ruby client.admin ``` ```ruby admin_client = client.admin usage_data = admin_client.usage.completions(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### Get Global Configuration Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/module-openai.md Retrieve the current global configuration object. This object holds all settable attributes for the gem's configuration. ```ruby token = OpenAI.configuration.access_token OpenAI.configuration.request_timeout = 300 ``` -------------------------------- ### Retrieve Fine-tuned Model Name Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Lists all fine-tuning jobs or retrieves details for a specific job to get the name of the resulting fine-tuned model. ```ruby client.finetunes.list response = client.finetunes.retrieve(id: fine_tune_id) fine_tuned_model = response["fine_tuned_model"] ``` -------------------------------- ### Initialize OpenAI::Realtime Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Instantiate the Realtime API client. Requires an initialized OpenAI::Client instance. The client is automatically configured with beta headers for the Realtime v1 API. ```ruby OpenAI::Realtime.new(client:) ``` -------------------------------- ### Get Moderations Usage Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves moderations API usage for the organization. This method requires an admin token and accepts an optional start_time parameter. ```ruby usage.moderations(parameters: {}) ``` ```ruby usage_data = client.usage.moderations(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### Configure Groq API Client Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Initialize the client with Groq's access token and API base URI for chat compatibility. Obtain your access token from the Groq console. ```ruby client = OpenAI::Client.new( access_token: "groq_access_token_goes_here", uri_base: "https://api.groq.com/openai" ) client.chat( parameters: { model: "llama3-8b-8192", # Required. messages: [{ role: "user", content: "Hello!"}], # Required. temperature: 0.7, stream: proc do |chunk, _event| print chunk.dig("choices", 0, "delta", "content") end } ) ``` -------------------------------- ### Get Embeddings Usage Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves embeddings API usage for the organization. This method requires an admin token and accepts an optional start_time parameter. ```ruby usage.embeddings(parameters: {}) ``` ```ruby usage_data = client.usage.embeddings(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### Custom Client Configuration Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/module-openai.md Demonstrates setting a global configuration and overriding it for a specific client instance with custom timeouts. ```ruby # Global config OpenAI.configure { |c| c.access_token = "sk-default-..." } # Override for specific client special_client = OpenAI::Client.new( access_token: "sk-special-...", request_timeout: 300 ) # Other clients use global config standard_client = OpenAI::Client.new ``` -------------------------------- ### Get Response Input Items Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieve input items associated with a response. Requires the response ID and optionally accepts query parameters. ```ruby items = client.responses.input_items(response_id: "response_abc123") ``` -------------------------------- ### File Upload and Fine-Tuning Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/overview.md This workflow covers uploading training data, creating a fine-tuning job, and checking its status. ```ruby # Upload training data file = client.files.upload( parameters: { file: "training.jsonl", purpose: "fine-tune" } ) # Create fine-tuning job job = client.finetunes.create( parameters: { model: "gpt-3.5-turbo", training_file: file["id"] } ) # Check status status = client.finetunes.retrieve(id: job["id"]) puts status["status"] # "queued", "running", "succeeded", etc. ``` -------------------------------- ### Make HTTP GET Request Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/http.md Use this method to retrieve data from an API endpoint. It accepts an API path and optional query parameters. ```ruby client.get(path: "/models") client.get(path: "/files", parameters: { limit: 10 }) ``` -------------------------------- ### Using Beta APIs Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/overview.md The client automatically adds beta headers for specific APIs like Assistants and Realtime. Manual beta headers can also be set. ```ruby # Assistants automatically use OpenAI-Beta: assistants=v2 assistants = client.assistants # Realtime automatically uses OpenAI-Beta: realtime=v1 realtime = client.realtime # Manual beta headers beta_client = client.beta(assistants: "v2", realtime: "v1") ``` -------------------------------- ### OpenAI module - Global configuration and utilities Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/README.md Documentation for the global OpenAI module, which handles configuration options and provides utility functions. Covers global configuration via `OpenAI.configure` and other utilities. ```APIDOC ## OpenAI Module ### Description Provides global configuration settings and utility functions for the ruby-openai gem. ### Configuration - **Global Configuration**: Set global API keys and other options using `OpenAI.configure`. - **Per-Client Overrides**: Configure individual client instances. - **Azure OpenAI Support**: Details on configuring for Azure environments. - **Custom Headers and Middleware**: Options for customizing HTTP requests. - **Timeout Configuration**: Setting request timeouts. - **Error Logging**: Facilities for logging errors. Refer to `configuration.md` for comprehensive details on all configuration options. ### Utilities Provides various utility functions. Refer to `api-reference/module-openai.md` for a complete list. ### Source Code Reference Links to the source code are provided in the format `source.rb:line-number`. ``` -------------------------------- ### Retrieve Batch Job Details Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/finetunes-batches.md Get specific details about a batch job using its ID. This includes its current status and request counts. ```ruby batch = client.batches.retrieve(id: "batch_abc123") puts "Status: #{batch['status']}" puts "Request counts: #{batch['request_counts']}" ``` -------------------------------- ### Get Assistants API Beta Version Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/assistants.md Retrieves the beta version string for the Assistants API. This version is automatically used in API calls. ```ruby OpenAI::Assistants::BETA_VERSION ``` -------------------------------- ### OpenAI.configuration= Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/module-openai.md Replaces the entire global configuration object with a new instance. ```APIDOC ## OpenAI.configuration= ### Description Replaces the entire configuration object. ### Method `configuration =` ### Parameters #### Parameter - `new_config` (OpenAI::Configuration) - New configuration instance ### Example ```ruby config = OpenAI::Configuration.new config.access_token = "sk-" OpenAI.configuration = config ``` ``` -------------------------------- ### Create Assistant with Vector Store Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/vector-stores.md Creates an assistant and configures it to use a specific vector store for file search. This step assumes the vector store has been populated with files. ```ruby assistants.create(parameters: { tool_resources: { file_search: { vector_store_ids: [vs_id] } } }) ``` -------------------------------- ### Chat Completion Request Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/overview.md Example of making a chat completion request using the OpenAI client. The response is a Hash parsed from the JSON response. ```ruby response = client.chat(parameters: { model: "gpt-4", messages: [...] }) # => { "id" => "chatcmpl-...", "choices" => [...], "usage" => {...} } ``` -------------------------------- ### OpenAI::Client Constructor Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/client.md Initializes a new instance of the OpenAI client. Supports custom configuration and Faraday middleware. ```APIDOC ## OpenAI::Client Constructor ### Description Initializes a new instance of the OpenAI client. Supports custom configuration and Faraday middleware. ### Constructor Signature ```ruby OpenAI::Client.new(config = {}, &faraday_middleware) ``` ### Parameters #### Constructor Parameters - **config** (Hash) - Optional - Configuration options for the client. Defaults to `{}`. - **faraday_middleware** (Proc) - Optional - A block to customize the Faraday connection. #### Configuration Options (via `config` hash) - **access_token** (String) - Optional - OpenAI API key. Falls back to global `OpenAI.configuration.access_token`. - **admin_token** (String) - Optional - Admin token for administrative endpoints. Falls back to global config. - **api_type** (Symbol/String) - Optional - API type (e.g., `:azure`). Falls back to global config. - **api_version** (String) - Optional - API version string. Defaults to `"v1"`. Falls back to global config. - **log_errors** (Boolean) - Optional - Whether to log HTTP errors. Defaults to `false`. Falls back to global config. - **organization_id** (String) - Optional - OpenAI organization ID. Falls back to global config. - **uri_base** (String) - Optional - Base URI for API calls. Defaults to `"https://api.openai.com/"`. Falls back to global config. - **request_timeout** (Integer) - Optional - Request timeout in seconds. Defaults to `120`. Falls back to global config. - **extra_headers** (Hash) - Optional - Additional HTTP headers to include. Defaults to `{}`. Falls back to global config. ### Example ```ruby # Initialize with default configuration client = OpenAI::Client.new # Initialize with custom configuration client = OpenAI::Client.new( access_token: "sk-...", organization_id: "org-...", request_timeout: 300 ) # Initialize with custom Faraday middleware client = OpenAI::Client.new do |conn| conn.use MyMiddleware end ``` ``` -------------------------------- ### Initialize Files API Client Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/files.md Instantiate the Files API client with an existing OpenAI client instance. ```ruby client = OpenAI::Client.new(access_token: "sk-...") files = client.files ``` -------------------------------- ### Initialize VectorStores Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/vector-stores.md Instantiate the VectorStores class with an OpenAI client instance. ```ruby client = OpenAI::Client.new(access_token: "sk-...") vector_stores = client.vector_stores ``` -------------------------------- ### Get Costs and Pricing Information Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves organization costs and pricing information. This method requires an admin token and accepts an optional start_time parameter. ```ruby usage.costs(parameters: {}) ``` ```ruby costs_data = client.usage.costs(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### Get Vector Stores Usage Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves vector store usage for the organization. This method requires an admin token and accepts an optional start_time parameter. ```ruby usage.vector_stores(parameters: {}) ``` ```ruby usage_data = client.usage.vector_stores(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### Initialize OpenAI Client with Overridden Config Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md When creating a new client, you can override specific global configuration defaults. Options not provided here will fall back to the globally configured values. ```ruby client = OpenAI::Client.new(access_token: "access_token_goes_here", admin_token: "admin_token_goes_here") ``` -------------------------------- ### Get Audio Transcriptions Usage Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves speech-to-text API usage for the organization. This method requires an admin token and accepts an optional start_time parameter. ```ruby usage.audio_transcriptions(parameters: {}) ``` ```ruby usage_data = client.usage.audio_transcriptions(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### client.admin Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/client.md Create a new client instance with admin token for administrative endpoints. ```APIDOC ## client.admin ### Description Create a new client instance with admin token for administrative endpoints. ### Returns New Client instance with access_token set to admin_token ### Throws OpenAI::AuthenticationError if no admin_token is configured ### Example ```ruby admin_client = client.admin usage_data = admin_client.usage.completions(parameters: { start_time: 1234567890 }) ``` ``` -------------------------------- ### Get Audio Speeches Usage Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves text-to-speech API usage for the organization. This method requires an admin token and accepts an optional start_time parameter. ```ruby usage.audio_speeches(parameters: {}) ``` ```ruby usage_data = client.usage.audio_speeches(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### Get Images Usage Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves image generation API usage for the organization. This method requires an admin token and accepts an optional start_time parameter. ```ruby usage.images(parameters: {}) ``` ```ruby usage_data = client.usage.images(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### Retrieve a Specific Run Step Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Get detailed information about a single run step. Requires thread ID, run ID, and step ID. ```ruby step = client.run_steps.retrieve( thread_id: "thread_abc123", run_id: "run_xyz789", id: "step_abc123" ) puts "Details: #{step['step_details']}" ``` -------------------------------- ### Initialize OpenAI::Responses Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Instantiate the Responses API client. Requires an initialized OpenAI::Client instance. ```ruby OpenAI::Responses.new(client:) ``` -------------------------------- ### Initialize Assistants API Client Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/assistants.md Instantiates the Assistants API client. Requires an initialized OpenAI::Client instance. ```ruby client = OpenAI::Client.new(access_token: "sk-...") assistants = client.assistants ``` -------------------------------- ### Estimate Token Count Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Use this method to get a rough estimate of the token count for a given text. For more accurate counts, consider using the tiktoken_ruby gem. ```ruby OpenAI.rough_token_count("Your text") ``` -------------------------------- ### OpenAI::Images.new Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/images.md Initializes a new Images API client instance. Requires an authenticated OpenAI client. ```APIDOC ## OpenAI::Images.new ### Description Initializes a new Images API client instance. Requires an authenticated OpenAI client. ### Parameters #### Path Parameters - **client** (OpenAI::Client) - Required - OpenAI client instance ### Request Example ```ruby client = OpenAI::Client.new(access_token: "sk-...") images = client.images ``` ``` -------------------------------- ### Upload Image File for Vision Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Uploads an image file to be used with the Assistants API, for example, for vision capabilities. Requires specifying the file path and purpose. ```ruby file_id = client.files.upload( parameters: { file: "path/to/example.png", purpose: "assistants", } )["id"] ``` -------------------------------- ### Assistant with Threads Workflow Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/overview.md This snippet demonstrates the workflow for creating an assistant, a thread, adding a message, running the assistant on the thread, and retrieving messages. ```ruby # Create assistant assistant = client.assistants.create( parameters: { model: "gpt-4", name: "My Assistant" } ) # Create thread thread = client.threads.create # Add message to thread client.messages.create( thread_id: thread["id"], parameters: { role: "user", content: "Hello!" } ) # Run assistant on thread run = client.runs.create( thread_id: thread["id"], parameters: { assistant_id: assistant["id"] } ) # Wait for completion and retrieve messages messages = client.messages.list(thread_id: thread["id"]) ``` -------------------------------- ### Initialize VectorStoreFileBatches Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/vector-stores.md Initializes the VectorStoreFileBatches manager with an OpenAI client instance. ```ruby OpenAI::VectorStoreFileBatches.new(client:) ``` -------------------------------- ### Perform Tool Calls with Responses API Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Enable the model to use external tools by defining them in the `tools` parameter. This example shows how to call a 'get_current_weather' function. ```ruby response = client.responses.create(parameters: { model: "gpt-4o", input: "What's the weather in Paris?", tools: [ { "type" => "function", "name" => "get_current_weather", "description" => "Get the current weather in a given location", "parameters" => { "type" => "object", "properties" => { "location" => { "type" => "string", "description" => "The geographic location to get the weather for" } }, "required" => ["location"] } } ] }) puts response.dig("output", 0, "name") # => "get_current_weather" ``` -------------------------------- ### Make Chat API Call Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/START-HERE.md Example of making a chat completion request using the configured OpenAI client. This demonstrates how to structure parameters for chat models. ```ruby response = client.chat( parameters: { model: "gpt-4", messages: [{ role: "user", content: "Hello" }] } ) ``` -------------------------------- ### Initialize Images API Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/images.md Instantiate the Images API with an OpenAI client instance. This is the first step before calling any image-related methods. ```ruby client = OpenAI::Client.new(access_token: "sk-...") images = client.images ``` -------------------------------- ### Get Code Interpreter Sessions Usage Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves code interpreter session usage for the organization. This method requires an admin token and accepts an optional start_time parameter. ```ruby usage.code_interpreter_sessions(parameters: {}) ``` ```ruby usage_data = client.usage.code_interpreter_sessions(parameters: { start_time: 1234567890 }) ``` -------------------------------- ### Create a Run Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Initiates a run for a given thread, using the assistant's defined instructions, model, and tools. Specify parameters like max prompt and completion tokens. ```ruby response = client.runs.create( thread_id: thread_id, parameters: { assistant_id: assistant_id, max_prompt_tokens: 256, max_completion_tokens: 16 } ) run_id = response['id'] ``` -------------------------------- ### Initialize OpenAI Client after Configuration Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md After configuring the gem globally, you can initialize the client without arguments, and it will use the configured settings. ```ruby client = OpenAI::Client.new ``` -------------------------------- ### Get Completions Usage Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/other-apis.md Retrieves completion API usage for the organization. This method requires an admin token and accepts optional query parameters for filtering by time or limit. ```ruby usage.completions(parameters: {}) ``` ```ruby usage_data = client.usage.completions( parameters: { start_time: 1234567890, end_time: 1234654290 } ) ``` -------------------------------- ### Run Test Suite Source: https://github.com/alexrudall/ruby-openai/blob/main/CONTRIBUTING.md Execute the project's test suite using Bundler and Rake. This should be run before submitting a pull request. ```bash bundle exec rake ``` -------------------------------- ### Batch Output JSON Format Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Example of the JSONL format for batch output files. Each line corresponds to a request and contains its ID, custom ID, and the API response. ```json { "id": "response-1", "custom_id": "request-1", "response": { "id": "chatcmpl-abc123", "object": "chat.completion", "created": 1677858242, "model": "gpt-4o", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "2+2 equals 4." } } ] } } ``` -------------------------------- ### OpenAI::Files Constructor Source: https://github.com/alexrudall/ruby-openai/blob/main/_autodocs/api-reference/files.md Initializes the Files API client. Requires an authenticated OpenAI client instance. ```APIDOC ## OpenAI::Files Constructor ### Description Initializes the Files API client. Requires an authenticated OpenAI client instance. ### Parameters #### Path Parameters - **client** (OpenAI::Client) - Required - OpenAI client instance ### Request Example ```ruby client = OpenAI::Client.new(access_token: "sk-...") files = client.files ``` ``` -------------------------------- ### Request JSON Output with Chat API Source: https://github.com/alexrudall/ruby-openai/blob/main/README.md Configure the chat API to return responses in JSON format by setting the `response_format` parameter. This example uses the gpt-4o model. ```ruby response = client.chat( parameters: { model: "gpt-4o", response_format: { type: "json_object" }, messages: [{ role: "user", content: "Hello! Give me some JSON please." }], temperature: 0.7, }) puts response.dig("choices", 0, "message", "content") # => # { # "name": "John", # "age": 30, # "city": "New York", # "hobbies": ["reading", "traveling", "hiking"], # "isStudent": false # } ```