@@ -125,7 +125,12 @@ class Client < OpenAI::Internal::Transport::BaseClient
125125 #
126126 # @return [Hash{String=>String}]
127127 private def auth_headers ( security :)
128- { bearer_auth :, admin_api_key_auth :} . slice ( *security . keys ) . values . reduce ( { } , :merge )
128+ headers = { bearer_auth :, admin_api_key_auth :} . slice ( *security . keys ) . values . reduce ( { } , :merge )
129+ if headers . empty? && security . any? { |_ , enabled | enabled }
130+ raise ArgumentError ,
131+ "Could not resolve authentication method. Expected either api_key or admin_api_key to be set."
132+ end
133+ headers
129134 end
130135
131136 # @api private
@@ -137,6 +142,14 @@ class Client < OpenAI::Internal::Transport::BaseClient
137142 { "authorization" => "Bearer #{ @api_key } " }
138143 end
139144
145+ # @api private
146+ #
147+ # @return [Hash{String=>String}]
148+ private def admin_api_key_auth
149+ return { } if @admin_api_key . nil?
150+
151+ { "authorization" => "Bearer #{ @admin_api_key } " }
152+ end
140153
141154 # Creates and returns a new client for interacting with the API.
142155 #
@@ -204,6 +217,7 @@ class Client < OpenAI::Internal::Transport::BaseClient
204217 def initialize (
205218 api_key : ENV [ "OPENAI_API_KEY" ] ,
206219 admin_api_key : ENV [ "OPENAI_ADMIN_KEY" ] ,
220+ workload_identity : nil ,
207221 organization : ENV [ "OPENAI_ORG_ID" ] ,
208222 project : ENV [ "OPENAI_PROJECT_ID" ] ,
209223 webhook_secret : ENV [ "OPENAI_WEBHOOK_SECRET" ] ,
@@ -215,6 +229,14 @@ def initialize(
215229 )
216230 base_url ||= "https://api.openai.com/v1"
217231
232+ if !api_key . nil? && !workload_identity . nil?
233+ raise ArgumentError , "`api_key` and `workload_identity` are mutually exclusive"
234+ end
235+
236+ if api_key . nil? && admin_api_key . nil? && workload_identity . nil?
237+ raise ArgumentError ,
238+ "Missing credentials. Please pass an `api_key`, `workload_identity`, `admin_api_key`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable."
239+ end
218240
219241 headers = {
220242 "openai-organization" => ( @organization = organization &.to_s ) ,
@@ -232,7 +254,16 @@ def initialize(
232254 headers = parsed . merge ( headers )
233255 end
234256
235- @api_key = api_key &.to_s
257+ if workload_identity . nil?
258+ @api_key = api_key &.to_s
259+ @workload_identity_auth = nil
260+ else
261+ @api_key = WORKLOAD_IDENTITY_API_KEY_PLACEHOLDER
262+ @workload_identity_auth = OpenAI ::Auth ::WorkloadIdentityAuth . new (
263+ workload_identity ,
264+ organization &.to_s
265+ )
266+ end
236267 @admin_api_key = admin_api_key &.to_s
237268 @webhook_secret = webhook_secret &.to_s
238269
0 commit comments