Class: Anthropic::Internal::Transport::BaseClient Abstract Private
- Inherits:
-
Object
- Object
- Anthropic::Internal::Transport::BaseClient
- Extended by:
- Util::SorbetRuntimeSupport
- Defined in:
- lib/anthropic/internal/transport/base_client.rb,
sig/anthropic/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" => Anthropic::Internal::Util.arch, "x-stainless-lang" => "ruby", "x-stainless-os" => Anthropic::Internal::Util.os, "x-stainless-package-version" => Anthropic::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
- #max_retries ⇒ Integer readonly private
- #max_retry_delay ⇒ Float readonly private
-
#middleware ⇒ Array<#call>
readonly
private
The middleware chain (first = outermost).
- #open_telemetry_max_content_bytes ⇒ Integer readonly private
- #requester ⇒ Anthropic::Internal::Transport::PooledNetRequester readonly private
- #timeout ⇒ Float readonly private
Class Method Summary collapse
- .follow_redirect(request, status:, response_headers:, span: nil) ⇒ Hash{Symbol=>Object} private
- .reap_connection!(status, stream:) ⇒ void private
- .should_retry?(status, headers:) ⇒ Boolean private
- .validate!(req) ⇒ void private
Instance Method Summary collapse
-
#initialize(base_url:, proxy: nil, timeout: 0.0, max_retries: 0, initial_retry_delay: 0.0, max_retry_delay: 0.0, open_telemetry: nil, headers: {}, idempotency_header: nil, middleware: nil, requester: nil) ⇒ BaseClient
constructor
private
A new instance of BaseClient.
- #inspect ⇒ String private
-
#open_telemetry_attributes ⇒ Hash{String=>String}
private
What every span of this client starts with.
-
#open_telemetry_content? ⇒ Boolean
private
Whether this client's spans have the
contentattributes. -
#open_telemetry_tracer ⇒ OpenTelemetry::Trace::Tracer?
private
The tracer of this client's spans, or
nilwhen they are disabled. -
#request(method, path, query: {}, headers: {}, body: nil, unwrap: nil, page: nil, stream: nil, model: Anthropic::Internal::Type::Unknown, qualifiers: nil, span_name: nil, span_attributes: nil, span_created_id: nil, span_route: nil, span_query: nil, span_content_query: nil, options: {}) ⇒ Object
private
Execute the request specified by
req. - #retry_request?(status, headers:) ⇒ Boolean private
- #send_request(request, redirect_count:, retry_count:, send_retry_header:, span: nil) ⇒ Array(Integer, Net::HTTPResponse|nil, Hash{String=>String}, Enumerable<String>) 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:, proxy: nil, timeout: 0.0, max_retries: 0, initial_retry_delay: 0.0, max_retry_delay: 0.0, open_telemetry: nil, headers: {}, idempotency_header: nil, middleware: nil, requester: 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.
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 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 231 def initialize( base_url:, proxy: nil, timeout: 0.0, max_retries: 0, initial_retry_delay: 0.0, max_retry_delay: 0.0, open_telemetry: nil, headers: {}, idempotency_header: nil, middleware: nil, requester: nil ) @middleware = Array(middleware).freeze @requester = requester || Anthropic::Internal::Transport::PooledNetRequester.new(proxy: proxy) @headers = Anthropic::Internal::Util.normalized_headers( self.class::PLATFORM_HEADERS, { "accept" => "application/json", "content-type" => "application/json", "user-agent" => user_agent }, headers ) @base_url_components = Anthropic::Internal::Util.parse_uri(base_url) @base_url = Anthropic::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 open_telemetry = Anthropic::Internal::Tracing.client_option(open_telemetry) @tracer = Anthropic::Internal::Tracing.tracer(open_telemetry, open_telemetry_scope) @open_telemetry_content = Anthropic::Internal::Tracing.content?(open_telemetry) @open_telemetry_max_content_bytes = Anthropic::Internal::Tracing.max_content_bytes(open_telemetry) @open_telemetry_propagation = Anthropic::Internal::Tracing.propagation?(open_telemetry) 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.
191 192 193 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 191 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.
206 207 208 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 206 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.
209 210 211 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 209 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.
200 201 202 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 200 def initial_retry_delay @initial_retry_delay 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.
197 198 199 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 197 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.
203 204 205 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 203 def max_retry_delay @max_retry_delay end |
#middleware ⇒ Array<#call> (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.
Returns the middleware chain (first = outermost).
216 217 218 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 216 def middleware @middleware end |
#open_telemetry_max_content_bytes ⇒ 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.
292 293 294 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 292 def open_telemetry_max_content_bytes @open_telemetry_max_content_bytes end |
#requester ⇒ Anthropic::Internal::Transport::PooledNetRequester (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.
213 214 215 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 213 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.
194 195 196 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 194 def timeout @timeout end |
Class Method Details
.follow_redirect(request, status:, response_headers:, span: nil) ⇒ 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.
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 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 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 117 def follow_redirect(request, status:, response_headers:, span: nil) 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 Anthropic::Errors::APIConnectionError.new( url: url, response: response_headers, message: ) end request = {**request, url: location} case [url.scheme, location.scheme] in ["https", "http"] = "Tried to redirect to an insecure URL" raise Anthropic::Errors::APIConnectionError.new( url: url, response: response_headers, message: ) else nil end # from whatwg fetch spec case [status, method] in [301 | 302, :post] | [303, _] drop = %w[content-encoding content-language content-length content-location content-type] request = { **request, method: method == :head ? :head : :get, headers: headers.except(*drop), body: nil } else end # from undici if Anthropic::Internal::Util.uri_origin(url) != Anthropic::Internal::Util.uri_origin(location) # The trace context is for the API's origin only, like the credentials dropped here. drop = %w[authorization cookie host proxy-authorization] + Anthropic::Internal::Tracing.trace_header_names(span) # The sentinel keeps the strip durable: provider middleware # (Vertex OAuth, Bedrock SigV4) runs per attempt and would # otherwise re-add `authorization` on the redirected leg. request = { **request, headers: request.fetch(:headers).except(*drop, "x-api-key"), metadata: {**request.fetch(:metadata, {}), cross_origin_redirect: true} } 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.
179 180 181 182 183 184 185 186 187 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 179 def reap_connection!(status, stream:) case status in (..199) | (300..499) stream&.each { next } in Anthropic::Errors::APIConnectionError | (500..) Anthropic::Internal::Util.close_fused!(stream) else 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.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 71 def should_retry?(status, headers:) coerced = Anthropic::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.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 33 def validate!(req) keys = [ :method, :path, :query, :headers, :body, :unwrap, :page, :stream, :model, :qualifiers, :span_name, :span_attributes, :span_created_id, :span_route, :span_query, :span_content_query, :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.
896 897 898 899 900 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 896 def inspect # rubocop:disable Layout/LineLength "#<#{self.class.name}:0x#{object_id.to_s(16)} base_url=#{@base_url} max_retries=#{@max_retries} timeout=#{@timeout}>" # rubocop:enable Layout/LineLength end |
#open_telemetry_attributes ⇒ Hash{String=>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.
What every span of this client starts with. A client for another platform overrides it.
280 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 280 def open_telemetry_attributes = Anthropic::Internal::Tracing::CLIENT_ATTRIBUTES |
#open_telemetry_content? ⇒ 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.
Whether this client's spans have the content attributes.
287 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 287 def open_telemetry_content? = @open_telemetry_content |
#open_telemetry_tracer ⇒ OpenTelemetry::Trace::Tracer?
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.
The tracer of this client's spans, or nil when they are disabled.
299 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 299 def open_telemetry_tracer = @tracer |
#request(method, path, query: {}, headers: {}, body: nil, unwrap: nil, page: nil, stream: nil, model: Anthropic::Internal::Type::Unknown, qualifiers: nil, span_name: nil, span_attributes: nil, span_created_id: nil, span_route: nil, span_query: nil, span_content_query: nil, 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.
path in the OpenAPI document
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 801 def request(req) self.class.validate!(req) Anthropic::RequestOptions.validate!(req[:options].to_h) Anthropic::Internal::Tracing.request_option(req[:options].to_h[:open_telemetry]) return execute_request(req) if @tracer.nil? start_time = Anthropic::Internal::Util.monotonic_secs attributes = Anthropic::Internal::Tracing.api_call_span_attributes(self, req) span = Anthropic::Internal::Tracing.start_api_call_span( @tracer, {**req, span_attributes: attributes}, propagation: @open_telemetry_propagation ) return execute_request(req) if span.nil? result = {req: req, client: self, start_time: start_time} data = begin # The response is kept before its body is decoded: a body that cannot be decoded still has a status. result[:data] = OpenTelemetry::Trace.with_span(span) do execute_request(req, span: span) { result.update(status: _1, headers: _2) } end rescue StandardError => e result[:error] = e raise ensure unless result[:data].is_a?(Anthropic::Internal::Type::BaseStream) Anthropic::Internal::Tracing.end_api_call_span(span, result) end end return data unless data.is_a?(Anthropic::Internal::Type::BaseStream) # The stream that the application gets reads `data`, and ends the span once read or closed. Anthropic::Internal::Tracing.end_api_call_span_when_stream_ends(span, data, result) end |
#retry_request?(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.
508 509 510 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 508 def retry_request?(status, headers:) self.class.should_retry?(status, headers: headers) end |
#send_request(request, redirect_count:, retry_count:, send_retry_header:, span: nil) ⇒ Array(Integer, Net::HTTPResponse|nil, Hash{String=>String}, Enumerable<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.
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 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 |
# File 'lib/anthropic/internal/transport/base_client.rb', line 566 def send_request(request, redirect_count:, retry_count:, send_retry_header:, span: nil) if send_retry_header request.fetch(:headers)["x-stainless-retry-count"] = retry_count.to_s end url, max_retries, timeout = request.fetch_values(:url, :max_retries, :timeout) # Request-level middleware (from `request_options`) runs innermost # among user middleware — below client-level entries, above the # provider middleware. request_middleware = request.fetch(:middleware, []) # Per-attempt defensive copies: the `request` hash and its members are # reused across retry recursions (the SDK mutates `request[:headers]` # for retry-count/auth stamping), so the immutable view middleware sees # must not alias them. With no user middleware at all only the terminal # and the provider middleware read these (both are pure), so the deep # freeze is skipped. Only `headers` change across retries, so the frozen # `url`/`body`/`options` copies are cached on `request` and reused; the # redirect path drops the stale `url`/`body` copies. `metadata` is the # deliberate exception — it is the cross-attempt scratchpad a middleware # may write to. user_middleware_empty = @middleware.empty? && request_middleware.empty? freeze = user_middleware_empty ? ->(o) { o } : Anthropic::Internal::Util.method(:deep_frozen_copy) api_req = Anthropic::APIRequest.new( method: request.fetch(:method), url: (request[:frozen_url] ||= freeze.call(url)), headers: freeze.call(request.fetch(:headers)), body: (request[:frozen_body] ||= freeze.call(request[:body])), stream: request[:stream], cast_to: request[:cast_to], unwrap: request[:unwrap], options: ( request[:frozen_options] ||= freeze.call(request.fetch(:options, {}).merge(timeout: timeout)) ), retry_count: retry_count, metadata: request.fetch(:metadata, {}) ) # The provider request the response actually came from — captured # inside the terminal so error reporting, relative-redirect # resolution, and redirect re-sends see the post-`provider_middleware` # (Bedrock/Vertex) URL and body, not the canonical `/v1/messages` # shape. Falls back to the canonical values when middleware # short-circuits before `nxt.call`. adapted_url = url adapted_body = request[:body] attempt_body = nil attempt_headers = nil terminal = lambda do |r| adapted_url = r.url adapted_body = r.body Anthropic::Internal::Tracing.record_send(span, self, request, r.url) if span enc_headers, encoded = Anthropic::Internal::Util.encode_content(r.headers, r.body) input = { method: r.method, url: r.url, headers: enc_headers, body: encoded, deadline: Anthropic::Internal::Util.monotonic_secs + timeout } http_status, raw, body = @requester.execute(input) attempt_body = body res = Anthropic::APIResponse.wrap(http_status, raw, body, request: r) attempt_headers = res.headers res end begin chain = Anthropic::Middleware.build_chain( [*@middleware, *request_middleware, *provider_middleware], terminal ) mres = chain.call(api_req) unless mres.is_a?(Anthropic::APIResponse) raise TypeError, "middleware returned #{mres.class}, expected Anthropic::APIResponse" end status, response, headers, stream = mres.to_tuple rescue StandardError => e # A middleware may raise after `nxt.call` returned a live response # (e.g. `raise RetryableError if res.status >= 500`); release the # pooled connection its un-consumed body still holds. Anthropic::Internal::Util.close_fused!(attempt_body) raise unless retryable_error?(e) status = e # A middleware may raise after observing a live response (e.g. a 429 # carrying `Retry-After`); keep that response's headers so retry # backoff still honors server-driven delay. `nil` when the terminal # itself raised — a connection failure carries no response. headers = attempt_headers || {} end case status in ..299 [status, response, headers, stream] 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 Anthropic::Errors::APIConnectionError.new( url: adapted_url, response: response, message: ) in 300..399 self.class.reap_connection!(status, stream: stream) # Re-send the provider-adapted body: the redirect target is a # provider URL that fails the provider middleware's adapt gate, so # the canonical body would otherwise go out un-adapted on # Bedrock/Vertex. A SigV4-signed `StringIO` body was consumed by # the prior attempt and must be rewound before re-signing. adapted_body.rewind if adapted_body.is_a?(StringIO) || adapted_body.is_a?(IO) request = self.class.follow_redirect( request.merge(url: adapted_url, body: adapted_body), status: status, response_headers: headers, span: (span if @open_telemetry_propagation) ) # The redirect retargets the URL, and `follow_redirect` may drop the # body (303 → GET); the cached frozen copies would then be stale, so # they are recomputed on the redirected attempt. request.delete(:frozen_body) request.delete(:frozen_url) send_request( request, redirect_count: redirect_count + 1, retry_count: retry_count, send_retry_header: send_retry_header, span: span ) in Exception if retry_count >= max_retries raise status in (400..) if retry_count >= max_retries || !retry_request?(status, headers: headers) decoded = Kernel.then do Anthropic::Internal::Util.decode_content(headers, stream: stream, suppress_error: true) ensure self.class.reap_connection!(status, stream: stream) end decoded = decoded.string if decoded.is_a?(StringIO) raise Anthropic::Errors::APIStatusError.for( url: adapted_url, status: status, headers: headers, body: decoded, request: nil, response: response ) in (400..) | Exception self.class.reap_connection!(status, stream: stream) delay = retry_delay(headers, retry_count: retry_count) sleep(delay) # Refresh auth headers across retries: credential providers (e.g. OAuth # token caches invalidated by a 401) may return a different token now # than at initial build_request time. Skip keys the caller supplied so # per-request overrides aren't clobbered. user_keys = request.fetch(:user_header_keys, []) # A cross-origin redirect dropped the credential; it stays dropped. unless request.fetch(:metadata, {})[:cross_origin_redirect] auth_headers.each do |k, v| k_norm = k.to_s.downcase next if user_keys.include?(k_norm) request.fetch(:headers)[k_norm] = v.to_s.strip end end send_request( request, redirect_count: redirect_count, retry_count: retry_count + 1, send_retry_header: send_retry_header, span: span ) end end |