Class: OpenAI::Internal::Transport::BaseClient Abstract Private
- Inherits:
-
Object
- Object
- OpenAI::Internal::Transport::BaseClient
- Extended by:
- Util::SorbetRuntimeSupport
- Defined in:
- lib/openai/internal/transport/base_client.rb,
sig/openai/internal/transport/base_client.rbs
Overview
This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.
Direct Known Subclasses
Constant Summary collapse
- MAX_REDIRECTS =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
from whatwg fetch spec
20- PLATFORM_HEADERS =
This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.
rubocop:disable Style/MutableConstant
{ "x-stainless-arch" => OpenAI::Internal::Util.arch, "x-stainless-lang" => "ruby", "x-stainless-os" => OpenAI::Internal::Util.os, "x-stainless-package-version" => OpenAI::VERSION, "x-stainless-runtime" => ::RUBY_ENGINE, "x-stainless-runtime-version" => ::RUBY_ENGINE_VERSION }
Instance Attribute Summary collapse
- #base_url ⇒ URI::Generic readonly private
- #headers ⇒ Hash{String=>String} readonly private
- #idempotency_header ⇒ String? readonly private
- #initial_retry_delay ⇒ Float readonly private
- #log_level ⇒ Symbol readonly private
- #logger ⇒ #debug, ... readonly private
- #max_retries ⇒ Integer readonly private
- #max_retry_delay ⇒ Float readonly private
- #on_retry ⇒ Proc? readonly private
- #requester ⇒ OpenAI::_HTTPClient readonly private
- #timeout ⇒ Float? readonly private
Class Method Summary collapse
- .follow_redirect(request, status:, response_headers:) ⇒ Hash{Symbol=>Object} private
- .reap_connection!(status, stream:) ⇒ void private
- .request_body_replayable?(body) ⇒ Boolean private
- .should_retry?(status, headers:) ⇒ Boolean private
- .validate!(req) ⇒ void private
Instance Method Summary collapse
-
#initialize(base_url:, timeout: 0.0, max_retries: 0, initial_retry_delay: 0.0, max_retry_delay: 0.0, headers: {}, idempotency_header: nil, http_client: nil, logger: nil, log_level: nil, on_retry: nil) ⇒ BaseClient
constructor
private
A new instance of BaseClient.
- #inspect ⇒ String private
-
#request(method, path, query: {}, headers: {}, body: nil, unwrap: nil, page: nil, stream: nil, stream_mode: nil, model: OpenAI::Internal::Type::Unknown, security: {bearer_auth: true, admin_api_key_auth: true}, options: {}) ⇒ Object
private
Execute the request specified by
req. - #request_streaming_body(req, on_response = nil) {|chunk| ... } ⇒ void private
- #send_request(request, redirect_count:, retry_count:, send_retry_header:) { ... } ⇒ OpenAI::HTTPClient::Response private
Methods included from Util::SorbetRuntimeSupport
const_missing, define_sorbet_constant!, sorbet_constant_defined?, to_sorbet_type, to_sorbet_type
Constructor Details
#initialize(base_url:, timeout: 0.0, max_retries: 0, initial_retry_delay: 0.0, max_retry_delay: 0.0, headers: {}, idempotency_header: nil, http_client: nil, logger: nil, log_level: nil, on_retry: nil) ⇒ BaseClient
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.
Returns a new instance of BaseClient.
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
# File 'lib/openai/internal/transport/base_client.rb', line 295 def initialize( base_url:, timeout: 0.0, max_retries: 0, initial_retry_delay: 0.0, max_retry_delay: 0.0, headers: {}, idempotency_header: nil, http_client: nil, logger: nil, log_level: nil, on_retry: nil ) unless http_client.nil? || http_client.respond_to?(:execute) raise ArgumentError, "`http_client` must respond to `execute`" end unless on_retry.nil? || on_retry.respond_to?(:call) raise ArgumentError, "`on_retry` must respond to `call`" end if log_level.nil? log_level = ENV.fetch("OPENAI_LOG", logger.nil? ? :off : :info) end @log_level = OpenAI::Internal::Logging.normalize_level(log_level) OpenAI::Internal::Logging.validate_logger!(logger) @logger = logger @logger ||= OpenAI::Internal::Logging.default_logger unless @log_level == :off @on_retry = on_retry @requester = http_client || OpenAI::NetHTTPClient.new @headers = OpenAI::Internal::Util.normalized_headers( self.class::PLATFORM_HEADERS, { "accept" => "application/json", "content-type" => "application/json", "user-agent" => user_agent }, headers ) @base_url_components = OpenAI::Internal::Util.parse_uri(base_url) @base_url = OpenAI::Internal::Util.unparse_uri(@base_url_components) @idempotency_header = idempotency_header&.to_s&.downcase @timeout = timeout @max_retries = max_retries @initial_retry_delay = initial_retry_delay @max_retry_delay = max_retry_delay end |
Instance Attribute Details
#base_url ⇒ URI::Generic (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.
249 250 251 |
# File 'lib/openai/internal/transport/base_client.rb', line 249 def base_url @base_url end |
#headers ⇒ Hash{String=>String} (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.
264 265 266 |
# File 'lib/openai/internal/transport/base_client.rb', line 264 def headers @headers end |
#idempotency_header ⇒ String? (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.
267 268 269 |
# File 'lib/openai/internal/transport/base_client.rb', line 267 def idempotency_header @idempotency_header end |
#initial_retry_delay ⇒ Float (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.
258 259 260 |
# File 'lib/openai/internal/transport/base_client.rb', line 258 def initial_retry_delay @initial_retry_delay end |
#log_level ⇒ Symbol (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.
273 274 275 |
# File 'lib/openai/internal/transport/base_client.rb', line 273 def log_level @log_level end |
#logger ⇒ #debug, ... (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.
270 271 272 |
# File 'lib/openai/internal/transport/base_client.rb', line 270 def logger @logger end |
#max_retries ⇒ Integer (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.
255 256 257 |
# File 'lib/openai/internal/transport/base_client.rb', line 255 def max_retries @max_retries end |
#max_retry_delay ⇒ Float (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.
261 262 263 |
# File 'lib/openai/internal/transport/base_client.rb', line 261 def max_retry_delay @max_retry_delay end |
#on_retry ⇒ Proc? (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.
276 277 278 |
# File 'lib/openai/internal/transport/base_client.rb', line 276 def on_retry @on_retry end |
#requester ⇒ OpenAI::_HTTPClient (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.
280 281 282 |
# File 'lib/openai/internal/transport/base_client.rb', line 280 def requester @requester end |
#timeout ⇒ Float? (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.
252 253 254 |
# File 'lib/openai/internal/transport/base_client.rb', line 252 def timeout @timeout end |
Class Method Details
.follow_redirect(request, status:, response_headers:) ⇒ Hash{Symbol=>Object}
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.
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
# File 'lib/openai/internal/transport/base_client.rb', line 140 def follow_redirect(request, status:, response_headers:) method, url, headers = request.fetch_values(:method, :url, :headers) location = Kernel.then do URI.join(url, response_headers["location"]) rescue ArgumentError = "Server responded with status #{status} but no valid location header." raise( OpenAI::Errors::APIConnectionError.new( url: url, response: response_headers, message: ) ) end unless %w[http https].include?(location.scheme) && !location.host.to_s.empty? = "Server responded with status #{status} but no valid location header." raise OpenAI::Errors::APIConnectionError.new(url: url, message: ) end request = {**request, url: location} case [url.scheme, location.scheme] in ["https", "http"] = "Tried to redirect to a insecure URL" raise( OpenAI::Errors::APIConnectionError.new( url: url, response: response_headers, message: ) ) else nil end # from whatwg fetch spec case [status, method] in [301 | 302, :post] | [303, _] request = { **request, method: method == :head ? :head : :get, headers: headers.reject { |name, _| REDIRECT_ENTITY_HEADERS.include?(name.to_s.downcase) }, body: nil, redirect_body_forbidden: true } else end # from undici origin = OpenAI::Internal::Util.uri_origin(URI(url.to_s)) redirect_origin = OpenAI::Internal::Util.uri_origin(URI(location.to_s)) if url.host.start_with?("[") && !url.hostname.start_with?("v", "V") origin = origin.sub(url.host, "[#{IPAddr.new(url.hostname)}]") end if location.host.start_with?("[") && !location.hostname.start_with?("v", "V") redirect_origin = redirect_origin.sub(location.host, "[#{IPAddr.new(location.hostname)}]") end unless origin.casecmp?(redirect_origin) unless request[:body].nil? # An attacker who controls a trusted endpoint's redirect destination could receive the body. = "Cannot follow a cross-origin redirect with a request body." raise( OpenAI::Errors::APIConnectionError.new( url: URI(redirect_origin), message: ) ) end headers = request.fetch(:headers).reject do |name, _| name == "host" || OpenAI::Internal::Logging.credential_header?(name) end request = {**request, headers: headers} end unless request_body_replayable?(request[:body]) = "Cannot follow a body-preserving redirect with a non-replayable request body." raise( OpenAI::Errors::APIConnectionError.new( url: location, response: response_headers, message: ) ) end request end |
.reap_connection!(status, stream:) ⇒ void
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.
This method returns an undefined value.
237 238 239 240 241 242 243 244 245 |
# File 'lib/openai/internal/transport/base_client.rb', line 237 def reap_connection!(status, stream:) case status in (..199) | (300..499) stream&.each { next } in OpenAI::Errors::APIConnectionError | (500..) OpenAI::Internal::Util.close_fused!(stream) else end end |
.request_body_replayable?(body) ⇒ Boolean
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.
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/openai/internal/transport/base_client.rb', line 102 def request_body_replayable?(body) case body in nil | String | StringIO | Pathname true in OpenAI::FilePart request_body_replayable?(body.content) in Hash body.each_value.all? { request_body_replayable?(_1) } in Array body.all? { request_body_replayable?(_1) } in IO | Enumerable false else !body.respond_to?(:read) end end |
.should_retry?(status, headers:) ⇒ Boolean
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.
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
# File 'lib/openai/internal/transport/base_client.rb', line 80 def should_retry?(status, headers:) coerced = OpenAI::Internal::Util.coerce_boolean(headers["x-should-retry"]) case [coerced, status] in [true | false, _] coerced in [_, 408 | 409 | 429 | (500..)] # retry on: # 408: timeouts # 409: locks # 429: rate limits # 500+: unknown errors true else false end end |
.validate!(req) ⇒ void
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.
This method returns an undefined value.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/openai/internal/transport/base_client.rb', line 47 def validate!(req) keys = [ :method, :path, :query, :headers, :body, :unwrap, :page, :stream, :stream_mode, :model, :security, :options ] case req in Hash req.each_key do |k| unless keys.include?(k) raise ArgumentError.new("Request `req` keys must be one of #{keys}, got #{k.inspect}") end end else raise ArgumentError.new("Request `req` must be a Hash or RequestOptions, got #{req.inspect}") end end |
Instance Method Details
#inspect ⇒ String
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.
986 987 988 989 |
# File 'lib/openai/internal/transport/base_client.rb', line 986 def inspect safe_base_url = OpenAI::Internal::Logging.safe_url(@base_url) "#<#{self.class.name}:0x#{object_id.to_s(16)} base_url=#{safe_base_url} max_retries=#{@max_retries} timeout=#{@timeout}>" end |
#request(method, path, query: {}, headers: {}, body: nil, unwrap: nil, page: nil, stream: nil, stream_mode: nil, model: OpenAI::Internal::Type::Unknown, security: {bearer_auth: true, admin_api_key_auth: true}, options: {}) ⇒ Object
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.
Execute the request specified by req. This is the method that all resource
methods call into.
825 826 827 828 829 830 |
# File 'lib/openai/internal/transport/base_client.rb', line 825 def request(req) url, response, log_context = perform_request(req) finish_request(log_context, response) do parse_response(req, url: url, response: response) end end |
#request_streaming_body(req, on_response = nil) {|chunk| ... } ⇒ void
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.
This method returns an undefined value.
834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 |
# File 'lib/openai/internal/transport/base_client.rb', line 834 def request_streaming_body(req, on_response = nil) if req[:options].to_h[:include_raw_body] raise ArgumentError, "include_raw_body is not supported for streaming downloads" end _url, response, log_context = perform_request(req) finish_request(log_context, response) do on_response&.call response.body.each { |chunk| yield chunk } nil end ensure OpenAI::Internal::Util.close_fused!(response.body) if response end |
#send_request(request, redirect_count:, retry_count:, send_retry_header:) { ... } ⇒ OpenAI::HTTPClient::Response
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.
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 |
# File 'lib/openai/internal/transport/base_client.rb', line 603 def send_request(request, redirect_count:, retry_count:, send_retry_header:, &context_provider) # Generated clients override this hook. A block keeps observability # state out of their stable keyword signature and is forwarded by # their existing `super` calls. log_context = context_provider.call if send_retry_header request = request.merge( headers: request.fetch(:headers).merge("x-stainless-retry-count" => retry_count.to_s) ) end url, max_retries = request.fetch_values(:url, :max_retries) = url.class.new(*URI.split(url.to_s)) prepared_request = request trusted_origin = request[:redirect_trusted_origin] request_dispatched = false begin encoded_headers, encoded_body = OpenAI::Internal::Util.encode_content( request.fetch(:headers), request[:body] ) attempt_request = request.except(:redirect_trusted_origin, :redirect_body_forbidden).merge( url: .class.new(*URI.split(.to_s)), headers: encoded_headers.transform_values(&:dup), body: encoded_body ) prepared_request = validate_prepared_request( prepare_request( attempt_request, redirect_count: redirect_count, retry_count: retry_count ), original_request: request ) prepared_url = prepared_request.fetch(:url) prepared_origin = OpenAI::Internal::Util.uri_origin(URI(prepared_url.to_s)) if prepared_url.host&.start_with?("[") && !prepared_url.hostname.start_with?("v", "V") prepared_origin = prepared_origin.sub(prepared_url.host, "[#{IPAddr.new(prepared_url.hostname)}]") end trusted_origin ||= prepared_origin = OpenAI::Internal::Util.uri_origin(URI(.to_s)) if .host.start_with?("[") && !.hostname.start_with?("v", "V") = .sub(.host, "[#{IPAddr.new(.hostname)}]") end cross_origin = redirect_count.positive? && !trusted_origin.casecmp?() escaped_origin = redirect_count.positive? && !.casecmp?(prepared_origin) = cross_origin || escaped_origin body_forbidden = request[:redirect_body_forbidden] || cross_origin if || body_forbidden safe_headers = prepared_request.fetch(:headers).reject do |name, _| normalized_name = name.to_s.downcase ( && (normalized_name == "host" || OpenAI::Internal::Logging.credential_header?(name))) || (body_forbidden && REDIRECT_ENTITY_HEADERS.include?(normalized_name)) end prepared_request = prepared_request.merge( url: ? : prepared_url, method: body_forbidden ? request.fetch(:method) : prepared_request.fetch(:method), headers: safe_headers, body: body_forbidden ? nil : prepared_request[:body] ) end url, max_retries, timeout = prepared_request.fetch_values(:url, :max_retries, :timeout) input = OpenAI::HTTPClient::Request.new( method: prepared_request.fetch(:method), url: url, headers: prepared_request.fetch(:headers), body: prepared_request[:body], timeout: timeout ) log_context.request_started(input, redirect_count: redirect_count) request_dispatched = true http_response = @requester.execute(input) unless http_response.is_a?(OpenAI::HTTPClient::Response) raise TypeError, "`http_client#execute` must return an OpenAI::HTTPClient::Response" end http_response = log_context.response_received(http_response) status = http_response.status headers = http_response.headers stream = http_response.body rescue OpenAI::Errors::APIConnectionError => e status = e stream = nil headers = {} log_context.attempt_failed(e) end terminal_status = case status in 300..399 prepared_request[:follow_redirects] == false in (400..) retry_count >= max_retries || !self.class.should_retry?(status, headers: headers) else false end if terminal_status raise_status_error!( url: url, status: status, headers: headers, response: http_response, stream: stream ) end if status.is_a?(OpenAI::Errors::APIConnectionError) && (retry_count >= max_retries || (request_dispatched && !request_retryable_after_connection_error?(prepared_request, error: status))) raise status end case status in ..299 http_response in 300..399 if redirect_count >= self.class::MAX_REDIRECTS self.class.reap_connection!(status, stream: stream) = "Failed to complete the request within #{self.class::MAX_REDIRECTS} redirects." raise OpenAI::Errors::APIConnectionError.new(url: url, response: http_response, message: ) in 300..399 self.class.reap_connection!(status, stream: stream) redirect_body = request[:body] redirect_body = prepared_request[:body] if redirect_body.nil? || prepared_request[:body].nil? redirect_source = request.merge( method: prepared_request.fetch(:method), url: prepared_request.fetch(:url), body: redirect_body ) redirected_request = self.class.follow_redirect( redirect_source, status: status, response_headers: headers ) redirected_request = redirected_request.merge(body: nil) if request[:body].nil? redirected_request = redirected_request.merge(redirect_trusted_origin: trusted_origin) send_request( redirected_request, redirect_count: redirect_count + 1, retry_count: retry_count, send_retry_header: send_retry_header, &context_provider ) in (400..) | OpenAI::Errors::APIConnectionError self.class.reap_connection!(status, stream: stream) delay = retry_delay(headers, retry_count: retry_count) validate_retry_delay!(request, delay: delay) log_context.retry_scheduled( status, delay: delay, response: http_response&., retry_count: retry_count, max_retries: max_retries ) sleep(delay) send_request( request, redirect_count: redirect_count, retry_count: retry_count + 1, send_retry_header: send_retry_header, &context_provider ) end end |