Class: OpenAI::Client

Inherits:
Internal::Transport::BaseClient show all
Defined in:
lib/openai/client.rb

Constant Summary collapse

DEFAULT_MAX_RETRIES =

Default max number of retries to attempt after a failed retryable request.

2
DEFAULT_TIMEOUT_IN_SECONDS =

Default per-request timeout.

600.0
DEFAULT_INITIAL_RETRY_DELAY =

Default initial retry delay in seconds. Overall delay is calculated using exponential backoff + jitter.

0.5
DEFAULT_MAX_RETRY_DELAY =

Default max retry delay in seconds.

8.0
WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER =
"workload-identity-auth"

Constants inherited from Internal::Transport::BaseClient

Internal::Transport::BaseClient::MAX_REDIRECTS, Internal::Transport::BaseClient::PLATFORM_HEADERS

Instance Attribute Summary collapse

Attributes inherited from Internal::Transport::BaseClient

#base_url, #headers, #idempotency_header, #initial_retry_delay, #max_retries, #max_retry_delay, #requester, #timeout

Instance Method Summary collapse

Methods inherited from Internal::Transport::BaseClient

follow_redirect, #inspect, reap_connection!, #request, should_retry?, validate!

Methods included from Internal::Util::SorbetRuntimeSupport

#const_missing, #define_sorbet_constant!, #sorbet_constant_defined?, #to_sorbet_type, to_sorbet_type

Constructor Details

#initialize(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: self.class::DEFAULT_MAX_RETRIES, timeout: self.class::DEFAULT_TIMEOUT_IN_SECONDS, initial_retry_delay: self.class::DEFAULT_INITIAL_RETRY_DELAY, max_retry_delay: self.class::DEFAULT_MAX_RETRY_DELAY) ⇒ Client

Creates and returns a new client for interacting with the API.

‘“api.example.com/v2/”`. Defaults to `ENV`

Parameters:

  • api_key (String, nil) (defaults to: ENV["OPENAI_API_KEY"])

    Defaults to ‘ENV`. Mutually exclusive with `workload_identity`.

  • admin_api_key (String, nil) (defaults to: ENV["OPENAI_ADMIN_KEY"])

    Defaults to ‘ENV`

  • workload_identity (OpenAI::Auth::WorkloadIdentity, nil) (defaults to: nil)

    OAuth2 workload identity configuration for token exchange authentication. Mutually exclusive with ‘api_key`.

  • organization (String, nil) (defaults to: ENV["OPENAI_ORG_ID"])

    Defaults to ‘ENV`.

  • project (String, nil) (defaults to: ENV["OPENAI_PROJECT_ID"])

    Defaults to ‘ENV`.

  • webhook_secret (String, nil) (defaults to: ENV["OPENAI_WEBHOOK_SECRET"])

    Defaults to ‘ENV`

  • base_url (String, nil) (defaults to: ENV["OPENAI_BASE_URL"])

    Override the default base URL for the API, e.g.,

  • max_retries (Integer) (defaults to: self.class::DEFAULT_MAX_RETRIES)

    Max number of retries to attempt after a failed retryable request.

  • timeout (Float) (defaults to: self.class::DEFAULT_TIMEOUT_IN_SECONDS)
  • initial_retry_delay (Float) (defaults to: self.class::DEFAULT_INITIAL_RETRY_DELAY)
  • max_retry_delay (Float) (defaults to: self.class::DEFAULT_MAX_RETRY_DELAY)


231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/openai/client.rb', line 231

def initialize(
  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: self.class::DEFAULT_MAX_RETRIES,
  timeout: self.class::DEFAULT_TIMEOUT_IN_SECONDS,
  initial_retry_delay: self.class::DEFAULT_INITIAL_RETRY_DELAY,
  max_retry_delay: self.class::DEFAULT_MAX_RETRY_DELAY
)
  base_url ||= "https://api.openai.com/v1"

  if !api_key.nil? && !workload_identity.nil?
    raise ArgumentError, "`api_key` and `workload_identity` are mutually exclusive"
  end

  if api_key.nil? && admin_api_key.nil? && workload_identity.nil?
    raise ArgumentError,
          "Missing credentials. Please pass an `api_key`, `workload_identity`, `admin_api_key`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable."
  end

  headers = {
    "openai-organization" => (@organization = organization&.to_s),
    "openai-project" => (@project = project&.to_s)
  }
  custom_headers_env = ENV["OPENAI_CUSTOM_HEADERS"]
  unless custom_headers_env.nil?
    parsed = {}
    custom_headers_env.split("\n").each do |line|
      colon = line.index(":")
      unless colon.nil?
        parsed[line[0...colon].strip] = line[(colon + 1)..].strip
      end
    end
    headers = parsed.merge(headers)
  end

  if workload_identity.nil?
    @api_key = api_key&.to_s
    @workload_identity_auth = nil
  else
    @api_key = WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER
    @workload_identity_auth = OpenAI::Auth::WorkloadIdentityAuth.new(
      workload_identity,
      organization&.to_s
    )
  end
  @admin_api_key = admin_api_key&.to_s
  @webhook_secret = webhook_secret&.to_s

  super(
    base_url: base_url,
    timeout: timeout,
    max_retries: max_retries,
    initial_retry_delay: initial_retry_delay,
    max_retry_delay: max_retry_delay,
    headers: headers
  )

  @completions = OpenAI::Resources::Completions.new(client: self)
  @chat = OpenAI::Resources::Chat.new(client: self)
  @embeddings = OpenAI::Resources::Embeddings.new(client: self)
  @files = OpenAI::Resources::Files.new(client: self)
  @images = OpenAI::Resources::Images.new(client: self)
  @audio = OpenAI::Resources::Audio.new(client: self)
  @moderations = OpenAI::Resources::Moderations.new(client: self)
  @models = OpenAI::Resources::Models.new(client: self)
  @fine_tuning = OpenAI::Resources::FineTuning.new(client: self)
  @graders = OpenAI::Resources::Graders.new(client: self)
  @vector_stores = OpenAI::Resources::VectorStores.new(client: self)
  @webhooks = OpenAI::Resources::Webhooks.new(client: self)
  @beta = OpenAI::Resources::Beta.new(client: self)
  @batches = OpenAI::Resources::Batches.new(client: self)
  @uploads = OpenAI::Resources::Uploads.new(client: self)
  @admin = OpenAI::Resources::Admin.new(client: self)
  @responses = OpenAI::Resources::Responses.new(client: self)
  @realtime = OpenAI::Resources::Realtime.new(client: self)
  @conversations = OpenAI::Resources::Conversations.new(client: self)
  @evals = OpenAI::Resources::Evals.new(client: self)
  @containers = OpenAI::Resources::Containers.new(client: self)
  @skills = OpenAI::Resources::Skills.new(client: self)
  @videos = OpenAI::Resources::Videos.new(client: self)
end

Instance Attribute Details

#adminOpenAI::Resources::Admin (readonly)



97
98
99
# File 'lib/openai/client.rb', line 97

def admin
  @admin
end

#admin_api_keyString? (readonly)

Returns:

  • (String, nil)


24
25
26
# File 'lib/openai/client.rb', line 24

def admin_api_key
  @admin_api_key
end

#api_keyString? (readonly)

Returns:

  • (String, nil)


21
22
23
# File 'lib/openai/client.rb', line 21

def api_key
  @api_key
end

#audioOpenAI::Resources::Audio (readonly)



62
63
64
# File 'lib/openai/client.rb', line 62

def audio
  @audio
end

#batchesOpenAI::Resources::Batches (readonly)

Create large batches of API requests to run asynchronously.



90
91
92
# File 'lib/openai/client.rb', line 90

def batches
  @batches
end

#betaOpenAI::Resources::Beta (readonly)



86
87
88
# File 'lib/openai/client.rb', line 86

def beta
  @beta
end

#chatOpenAI::Resources::Chat (readonly)



45
46
47
# File 'lib/openai/client.rb', line 45

def chat
  @chat
end

#completionsOpenAI::Resources::Completions (readonly)

Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.



42
43
44
# File 'lib/openai/client.rb', line 42

def completions
  @completions
end

#containersOpenAI::Resources::Containers (readonly)



114
115
116
# File 'lib/openai/client.rb', line 114

def containers
  @containers
end

#conversationsOpenAI::Resources::Conversations (readonly)

Manage conversations and conversation items.



107
108
109
# File 'lib/openai/client.rb', line 107

def conversations
  @conversations
end

#embeddingsOpenAI::Resources::Embeddings (readonly)

Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.



50
51
52
# File 'lib/openai/client.rb', line 50

def embeddings
  @embeddings
end

#evalsOpenAI::Resources::Evals (readonly)

Manage and run evals in the OpenAI platform.



111
112
113
# File 'lib/openai/client.rb', line 111

def evals
  @evals
end

#filesOpenAI::Resources::Files (readonly)

Files are used to upload documents that can be used with features like Assistants and Fine-tuning.



55
56
57
# File 'lib/openai/client.rb', line 55

def files
  @files
end

#fine_tuningOpenAI::Resources::FineTuning (readonly)



74
75
76
# File 'lib/openai/client.rb', line 74

def fine_tuning
  @fine_tuning
end

#gradersOpenAI::Resources::Graders (readonly)



77
78
79
# File 'lib/openai/client.rb', line 77

def graders
  @graders
end

#imagesOpenAI::Resources::Images (readonly)

Given a prompt and/or an input image, the model will generate a new image.



59
60
61
# File 'lib/openai/client.rb', line 59

def images
  @images
end

#modelsOpenAI::Resources::Models (readonly)

List and describe the various models available in the API.



71
72
73
# File 'lib/openai/client.rb', line 71

def models
  @models
end

#moderationsOpenAI::Resources::Moderations (readonly)

Given text and/or image inputs, classifies if those inputs are potentially harmful.



67
68
69
# File 'lib/openai/client.rb', line 67

def moderations
  @moderations
end

#organizationString? (readonly)

Returns:

  • (String, nil)


27
28
29
# File 'lib/openai/client.rb', line 27

def organization
  @organization
end

#projectString? (readonly)

Returns:

  • (String, nil)


30
31
32
# File 'lib/openai/client.rb', line 30

def project
  @project
end

#realtimeOpenAI::Resources::Realtime (readonly)



103
104
105
# File 'lib/openai/client.rb', line 103

def realtime
  @realtime
end

#responsesOpenAI::Resources::Responses (readonly)



100
101
102
# File 'lib/openai/client.rb', line 100

def responses
  @responses
end

#skillsOpenAI::Resources::Skills (readonly)



117
118
119
# File 'lib/openai/client.rb', line 117

def skills
  @skills
end

#uploadsOpenAI::Resources::Uploads (readonly)

Use Uploads to upload large files in multiple parts.



94
95
96
# File 'lib/openai/client.rb', line 94

def uploads
  @uploads
end

#vector_storesOpenAI::Resources::VectorStores (readonly)



80
81
82
# File 'lib/openai/client.rb', line 80

def vector_stores
  @vector_stores
end

#videosOpenAI::Resources::Videos (readonly)



120
121
122
# File 'lib/openai/client.rb', line 120

def videos
  @videos
end

#webhook_secretString? (readonly)

Returns:

  • (String, nil)


33
34
35
# File 'lib/openai/client.rb', line 33

def webhook_secret
  @webhook_secret
end

#webhooksOpenAI::Resources::Webhooks (readonly)



83
84
85
# File 'lib/openai/client.rb', line 83

def webhooks
  @webhooks
end

#workload_identity_authOpenAI::Auth::WorkloadIdentityAuth? (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



37
38
39
# File 'lib/openai/client.rb', line 37

def workload_identity_auth
  @workload_identity_auth
end