Class: Anthropic::Client

Inherits:
Internal::Transport::BaseClient show all
Defined in:
lib/anthropic/client.rb,
sig/anthropic/client.rbs

Constant Summary collapse

DEFAULT_MAX_RETRIES =

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

Returns:

  • (2)
2
DEFAULT_TIMEOUT_IN_SECONDS =

Default per-request timeout.

Returns:

  • (Float)
600.0
DEFAULT_INITIAL_RETRY_DELAY =

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

Returns:

  • (Float)
0.5
DEFAULT_MAX_RETRY_DELAY =

Default max retry delay in seconds.

Returns:

  • (Float)
8.0
MODEL_NONSTREAMING_TOKENS =

Models that have specific non-streaming token limits

{
  "claude-opus-4-20250514": 8_192,
  "claude-opus-4-0": 8_192,
  "claude-4-opus-20250514": 8_192,
  "anthropic.claude-opus-4-20250514-v1:0": 8_192,
  "claude-opus-4@20250514": 8_192,
  "anthropic.claude-opus-4-1-20250805-v1:0": 8192,
  "claude-opus-4-1@20250805": 8192
}.freeze

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, #middleware, #open_telemetry_max_content_bytes, #requester, #timeout

Instance Method Summary collapse

Methods inherited from Internal::Transport::BaseClient

follow_redirect, #inspect, #open_telemetry_attributes, #open_telemetry_content?, #open_telemetry_tracer, reap_connection!, #request, #send_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: nil, auth_token: nil, webhook_key: ENV["ANTHROPIC_WEBHOOK_SIGNING_KEY"], credentials: nil, config: nil, base_url: nil, proxy: nil, max_retries: self.class::DEFAULT_MAX_RETRIES, timeout: nil, open_telemetry: nil, initial_retry_delay: self.class::DEFAULT_INITIAL_RETRY_DELAY, max_retry_delay: self.class::DEFAULT_MAX_RETRY_DELAY, middleware: nil) ⇒ Client

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

Credential precedence, matching the credential-resolution spec and the Workload Identity Federation user guide:

  1. An explicit constructor argument — one of api_key:, auth_token:, credentials:, config:. The SDK uses it and does not fall back to credential env vars or profiles on disk. Passing more than one raises ArgumentError.
  2. ANTHROPIC_API_KEY, then ANTHROPIC_AUTH_TOKEN. Only consulted when no explicit credential argument was passed. An empty variable counts as unset. When both are set, the SDK warns once per process.
  3. ANTHROPIC_PROFILE — explicit profile selection.
  4. Direct env-var federation (+ANTHROPIC_IDENTITY_TOKEN+ + ANTHROPIC_FEDERATION_RULE_ID + ANTHROPIC_ORGANIZATION_ID).
  5. Fallback active profile from disk (+active_config+ pointer or the literal default).

A static env credential (step 2) shadows steps 3–5, silently disabling profile / federation auto-discovery.

net/http reads the http_proxy, https_proxy, and no_proxy environment variables.

Anthropic::Client::DEFAULT_TIMEOUT_IN_SECONDS when nil.

the application has registered a tracer provider with the OpenTelemetry API. true and false are short for {traces: true} and {traces: false}. Keys can be Strings, and an unknown key raises ArgumentError. A client that is given no option reads ENV["ANTHROPIC_OPEN_TELEMETRY"], where false is open_telemetry: false, ENV["ANTHROPIC_OPEN_TELEMETRY_PROPAGATION"], where false is propagation: false, ENV["ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE"] and ENV["ANTHROPIC_OPEN_TELEMETRY_TRACES_MAX_CONTENT_BYTES"]. A client that is given the option, even true or {}, reads none of them.

@option open_telemetry [#tracer] :tracer_provider Used in place of the registered tracer provider.

@option open_telemetry [Boolean] :propagation `false` sends no trace context headers, such as `traceparent`, with this
client's requests, for an application whose HTTP client instrumentation already
sends them, so that a request does not carry them twice. The spans are
unaffected. Defaults to `true`.

@option open_telemetry [Hash{Symbol=>Object}, Boolean] :traces The settings of the spans. `true` and `false` are short for `{enabled: true}`
and `{enabled: false}`. Its keys:

- `:enabled` (Boolean): `false` disables the spans, and the other keys are then
unused. Defaults to `true`.
- `:content_mode` (Symbol, String): `:content` adds the content of requests and
responses to the spans, and `:metadata_only` does not. Defaults to
`:metadata_only`.
- `:max_content_bytes` (Integer): the most bytes of content that one span holds,
1 or more. Content over the bound is cut, and the span then has
`anthropic.content.truncated`. Defaults to 0.75 MB.

Parameters:

  • api_key (String, nil) (defaults to: nil) —

    Defaults to ENV["ANTHROPIC_API_KEY"] when no explicit credential argument is passed.

  • auth_token (String, nil) (defaults to: nil) —

    Defaults to ENV["ANTHROPIC_AUTH_TOKEN"] when no explicit credential argument is passed and ANTHROPIC_API_KEY is not set.

  • credentials (#call, nil) (defaults to: nil) —

    Credential provider — any callable returning AccessToken.new(token:, expires_at:). The provider is wrapped in a TokenCache for thread-safe caching and proactive refresh (120s advisory / 30s mandatory before expiry). Common providers: WorkloadIdentity, CredentialsFile, StaticToken, or a custom lambda.

  • config (Hash, nil) (defaults to: nil) —

    In-memory configuration hash with the same shape as configs/<profile>.json. Must include an authentication object with a type field (+oidc_federation+ or user_oauth). For user_oauth, must also include authentication.credentials_path.

  • webhook_key (String, nil) (defaults to: ENV["ANTHROPIC_WEBHOOK_SIGNING_KEY"]) —

    Defaults to ENV["ANTHROPIC_WEBHOOK_SIGNING_KEY"]

  • base_url (String, nil) (defaults to: nil) —

    Override the default base URL for the API, e.g., "https://api.example.com/v2/". Defaults to ENV["ANTHROPIC_BASE_URL"], then to the profile's base_url if present, then to https://api.anthropic.com.

  • proxy (String, URI::Generic, nil) (defaults to: nil) —

    HTTP proxy URL, e.g., "http://user:[email protected]:8080". When nil,

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

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

  • timeout (Float, nil) (defaults to: nil) —

    Request timeout in seconds. Defaults to

  • open_telemetry (Hash{Symbol=>Object}, Boolean, nil) (defaults to: nil) —

    OpenTelemetry tracing of this client's API calls. Each call emits a span when

  • initial_retry_delay (Float) (defaults to: self.class::DEFAULT_INITIAL_RETRY_DELAY)
  • max_retry_delay (Float) (defaults to: self.class::DEFAULT_MAX_RETRY_DELAY)
  • middleware (Array<#call>, #call, nil) (defaults to: nil) —

    Per-attempt HTTP around-middleware. Each entry is a #call(req, nxt) -> Anthropic::APIResponse callable. See Middleware.

  • api_key: (String, nil) (defaults to: nil)
  • auth_token: (String, nil) (defaults to: nil)
  • webhook_key: (String, nil) (defaults to: ENV["ANTHROPIC_WEBHOOK_SIGNING_KEY"])
  • credentials: (Anthropic::Credentials::_AccessTokenProvider, nil) (defaults to: nil)
  • config: (::Hash[String, untyped], nil) (defaults to: nil)
  • base_url: (String, nil) (defaults to: nil)
  • proxy: (String, URI::Generic, nil) (defaults to: nil)
  • max_retries: (Integer) (defaults to: self.class::DEFAULT_MAX_RETRIES)
  • timeout: (Float, nil) (defaults to: nil)
  • open_telemetry: (Anthropic::Internal::Tracing::client_option, nil) (defaults to: nil)
  • initial_retry_delay: (Float) (defaults to: self.class::DEFAULT_INITIAL_RETRY_DELAY)
  • max_retry_delay: (Float) (defaults to: self.class::DEFAULT_MAX_RETRY_DELAY)
  • middleware: (Anthropic::Middleware::entry_or_array, nil) (defaults to: nil)

Raises:

  • (ArgumentError) —

    If more than one of api_key:, auth_token:, credentials:, config: is passed.



230
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
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
343
344
345
# File 'lib/anthropic/client.rb', line 230

def initialize(
  api_key: nil,
  auth_token: nil,
  webhook_key: ENV["ANTHROPIC_WEBHOOK_SIGNING_KEY"],
  credentials: nil,
  config: nil,
  base_url: nil,
  proxy: nil,
  max_retries: self.class::DEFAULT_MAX_RETRIES,
  timeout: nil,
  open_telemetry: nil,
  initial_retry_delay: self.class::DEFAULT_INITIAL_RETRY_DELAY,
  max_retry_delay: self.class::DEFAULT_MAX_RETRY_DELAY,
  middleware: nil
)
  @timeout_overridden = !timeout.nil?
  timeout ||= self.class::DEFAULT_TIMEOUT_IN_SECONDS

  credential =
    {api_key: api_key, auth_token: auth_token, credentials: credentials, config: config}.compact
  if credential.length > 1
    raise ArgumentError,
          "Pass at most one of `api_key:`, `auth_token:`, `credentials:`, or `config:`. " \
          "Received #{credential.keys.map { "`#{_1}:`" }.join(', ')}."
  end

  credential = env_credential if credential.empty? && resolve_default_credentials?

  @api_key = credential[:api_key]&.to_s
  @auth_token = credential[:auth_token]&.to_s
  @credentials = nil
  @token_cache = nil

  base_url ||= ENV["ANTHROPIC_BASE_URL"] if resolve_default_credentials?
  # `ANTHROPIC_BASE_URL` counts as explicit: it outranks a profile/config `base_url`.
  base_url_is_explicit = base_url && !base_url.empty?

  credential_headers = {}

  result =
    case credential
    in {credentials:}
      Anthropic::Credentials::CredentialResult.new(provider: credentials)
    in {config:}
      in_memory = Anthropic::Credentials::InMemoryConfig.new(config)
      Anthropic::Credentials::CredentialResult.new(
        provider: in_memory,
        extra_headers: in_memory.extra_headers,
        base_url: in_memory.resolved_base_url
      )
    in {} if resolve_default_credentials?
      Anthropic::Credentials.default_credentials(base_url: base_url || "https://api.anthropic.com")
    in {api_key: _} | {auth_token: _} | {}
      nil
    end

  if result
    @credentials = result.provider
    credential_headers = result.extra_headers
    base_url = result.base_url if !base_url_is_explicit && result.base_url
  end

  if @credentials
    @token_cache = Anthropic::Credentials::TokenCache.new(@credentials)
  end

  if resolve_default_credentials?
    base_url ||= "https://api.anthropic.com"
  elsif base_url.to_s.empty?
    raise ArgumentError.new(
      "No base_url was resolved for #{self.class.name}; " \
      "platform clients must supply their own endpoint."
    )
  end

  if @credentials.respond_to?(:bind_base_url)
    @credentials.bind_base_url(base_url)
  end

  headers = {
    "anthropic-version" => "2026-10-21"
  }
  custom_headers_env = ENV["ANTHROPIC_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
  headers = headers.merge(credential_headers)
  @webhook_key = webhook_key&.to_s

  super(
    base_url: base_url,
    proxy: proxy,
    timeout: timeout,
    open_telemetry: open_telemetry,
    max_retries: max_retries,
    initial_retry_delay: initial_retry_delay,
    max_retry_delay: max_retry_delay,
    headers: headers,
    middleware: middleware
  )

  @messages = Anthropic::Resources::Messages.new(client: self)
  @models = Anthropic::Resources::Models.new(client: self)
  @files = Anthropic::Resources::Files.new(client: self)
  @skills = Anthropic::Resources::Skills.new(client: self)
  @user_profiles = Anthropic::Resources::UserProfiles.new(client: self)
  @organization = Anthropic::Resources::Organization.new(client: self)
  @beta = Anthropic::Resources::Beta.new(client: self)
end

Instance Attribute Details

#api_key ⇒ String? (readonly)

Returns:

  • (String, nil)


53
54
55
# File 'lib/anthropic/client.rb', line 53

def api_key
  @api_key
end

#auth_token ⇒ String? (readonly)

Returns:

  • (String, nil)


56
57
58
# File 'lib/anthropic/client.rb', line 56

def auth_token
  @auth_token
end

#beta ⇒ Anthropic::Resources::Beta (readonly)



89
90
91
# File 'lib/anthropic/client.rb', line 89

def beta
  @beta
end

#credentials ⇒ Object? (readonly)

Returns:

  • (Object, nil)


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

def credentials
  @credentials
end

#files ⇒ Anthropic::Resources::Files (readonly)



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

def files
  @files
end

#messages ⇒ Anthropic::Resources::Messages (readonly)



68
69
70
# File 'lib/anthropic/client.rb', line 68

def messages
  @messages
end

#models ⇒ Anthropic::Resources::Models (readonly)



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

def models
  @models
end

#organization ⇒ Anthropic::Resources::Organization (readonly)



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

def organization
  @organization
end

#skills ⇒ Anthropic::Resources::Skills (readonly)



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

def skills
  @skills
end

#token_cache ⇒ Anthropic::Credentials::TokenCache? (readonly)



65
66
67
# File 'lib/anthropic/client.rb', line 65

def token_cache
  @token_cache
end

#user_profiles ⇒ Anthropic::Resources::UserProfiles (readonly)

Register the end customers that your platform serves, so each request can name who it's for. To get started, see the User profiles guide.



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

def user_profiles
  @user_profiles
end

#webhook_key ⇒ String? (readonly)

Returns:

  • (String, nil)


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

def webhook_key
  @webhook_key
end

Instance Method Details

#calculate_nonstreaming_timeout(max_tokens, max_nonstreaming_tokens = nil) ⇒ Float

Calculate the timeout for non-streaming requests based on token count

Parameters:

  • max_tokens (Integer) —

    The maximum number of tokens to generate

  • max_nonstreaming_tokens (Integer, nil) (defaults to: nil) —

    The maximum tokens allowed for non-streaming

Returns:

  • (Float) —

    The calculated timeout in seconds

Raises:

  • (ArgumentError) —

    If expected time exceeds default time or max_tokens exceeds max_nonstreaming_tokens



116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/anthropic/client.rb', line 116

def calculate_nonstreaming_timeout(max_tokens, max_nonstreaming_tokens = nil)
  maximum_time = 60 * 60 # 1 hour in seconds
  default_time = 60 * 10 # 10 minutes in seconds

  expected_time = maximum_time * max_tokens / 128_000.0
  if expected_time > default_time || (max_nonstreaming_tokens && max_tokens > max_nonstreaming_tokens)
    raise ArgumentError.new(
      "Streaming is required for operations that may take longer than 10 minutes. " \
      "See https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/ruby#streaming for more details"
    )
  end

  DEFAULT_TIMEOUT_IN_SECONDS
end

#message_threads? ⇒ 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 the platform this client talks to has message threads. Platform clients whose platform has none override this.

Returns:



367
# File 'lib/anthropic/client.rb', line 367

def message_threads? = true

#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.

Parameters:

  • status (Integer)
  • headers (Hash{String=>String})

Returns:



353
354
355
356
357
358
359
# File 'lib/anthropic/client.rb', line 353

def retry_request?(status, headers:)
  if status == 401 && @token_cache
    @token_cache.invalidate
    return true
  end
  super
end

#timeout_overridden? ⇒ 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.

Returns:



134
# File 'lib/anthropic/client.rb', line 134

def timeout_overridden? = @timeout_overridden