Class: Anthropic::Helpers::Bedrock::Client

Inherits:
Client show all
Includes:
AWSAuth
Defined in:
lib/anthropic/helpers/bedrock/client.rb,
sig/anthropic/helpers/bedrock/client.rbs

Constant Summary collapse

DEFAULT_VERSION =

Returns:

  • (String)
"bedrock-2023-05-31"
Anthropic =

Returns:

  • (:request_options opts)

Constants inherited from Client

Client::DEFAULT_INITIAL_RETRY_DELAY, Client::DEFAULT_MAX_RETRIES, Client::DEFAULT_MAX_RETRY_DELAY, Client::DEFAULT_TIMEOUT_IN_SECONDS, Client::MODEL_NONSTREAMING_TOKENS

Constants inherited from Internal::Transport::BaseClient

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

Instance Attribute Summary collapse

Attributes inherited from Client

#auth_token, #credentials, #token_cache, #webhook_key

Attributes inherited from Internal::Transport::BaseClient

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

Instance Method Summary collapse

Methods inherited from Client

#calculate_nonstreaming_timeout, #retry_request?

Methods inherited from Internal::Transport::BaseClient

follow_redirect, #inspect, reap_connection!, #request, #retry_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(aws_region: nil, base_url: nil, 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, aws_access_key: nil, aws_secret_key: nil, aws_session_token: nil, aws_profile: nil, api_key: nil, middleware: nil) ⇒ Client

Creates and returns a new client for interacting with the AWS Bedrock API for Anthropic models.

AWS credentials are resolved according to the AWS SDK's default resolution order, described at https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/setup-config.html#credchain or https://github.com/aws/aws-sdk-ruby?tab=readme-ov-file#configuration

Parameters:

  • aws_region (String, nil) (defaults to: nil)

    Enforce the AWS Region to use. If unset, the region is set according to the AWS SDK's default resolution order, described at https://github.com/aws/aws-sdk-ruby?tab=readme-ov-file#configuration

  • aws_access_key (String, nil) (defaults to: nil)

    Optional AWS access key to use for authentication. Overrides profile and credential provider chain

  • aws_secret_key (String, nil) (defaults to: nil)

    Optional AWS secret access key to use for authentication. Overrides profile and credential provider chain

  • aws_session_token (String, nil) (defaults to: nil)

    Optional AWS session token to use for authentication. Overrides profile and credential provider chain

  • aws_profile (String, nil) (defaults to: nil)

    Optional AWS profile to use for authentication. Overrides the credential provider chain

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

    Optional API key for Bearer token authentication. Mutually exclusive with AWS credentials. Falls back to the AWS_BEARER_TOKEN_BEDROCK environment variable if not provided.

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

    Override the default base URL for the API, e.g., "https://api.example.com/v2/"

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

    The maximum number of times to retry a request if it fails

  • timeout (Float) (defaults to: self.class::DEFAULT_TIMEOUT_IN_SECONDS)

    The number of seconds to wait for a response before timing out

  • initial_retry_delay (Float) (defaults to: self.class::DEFAULT_INITIAL_RETRY_DELAY)

    The number of seconds to wait before retrying a request

  • max_retry_delay (Float) (defaults to: self.class::DEFAULT_MAX_RETRY_DELAY)

    The maximum number of seconds to wait before retrying a request

  • middleware (Array<#call>, #call, nil) (defaults to: nil)

    Per-attempt HTTP around-middleware. See Middleware. Middleware sees the canonical Anthropic request shape; the Bedrock URL rewrite and SigV4 signing happen inside the continuation, per attempt.



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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
# File 'lib/anthropic/helpers/bedrock/client.rb', line 63

def initialize(
  aws_region: nil,
  base_url: nil,
  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,
  aws_access_key: nil,
  aws_secret_key: nil,
  aws_session_token: nil,
  aws_profile: nil,
  api_key: nil,
  middleware: nil
)
  api_key ||= ENV["AWS_BEARER_TOKEN_BEDROCK"]

  has_aws_credentials = !aws_access_key.nil? || !aws_secret_key.nil? || !aws_session_token.nil? || !aws_profile.nil?
  if !api_key.nil? && has_aws_credentials
    raise ArgumentError.new(
      "Cannot specify both `api_key` and AWS credentials (`aws_access_key`, `aws_secret_key`, `aws_session_token`, `aws_profile`)"
    )
  end

  if api_key.nil?
    begin
      require("aws-sdk-bedrockruntime")
    rescue LoadError
      message = <<~MSG

        In order to access Anthropic models on Bedrock you must require the `aws-sdk-bedrockruntime` gem.
        You can install it by adding the following to your Gemfile:

            gem "aws-sdk-bedrockruntime"

        and then running `bundle install`.

        Alternatively, if you are not using Bundler, simply run:

            gem install aws-sdk-bedrockruntime
      MSG

      raise RuntimeError.new(message)
    end

    @aws_region, @aws_credentials = resolve_region_and_credentials(
      aws_region: aws_region,
      aws_secret_key: aws_secret_key,
      aws_access_key: aws_access_key,
      aws_session_token: aws_session_token,
      aws_profile: aws_profile
    )

    @signer = Aws::Sigv4::Signer.new(
      service: "bedrock",
      region: @aws_region,
      credentials: @aws_credentials
    )
  else
    @aws_region = aws_region
  end

  base_url ||= ENV.fetch(
    "ANTHROPIC_BEDROCK_BASE_URL",
    "https://bedrock-runtime.#{@aws_region}.amazonaws.com"
  )

  # For AWSAuth#auth_headers: suppress key headers in SigV4 mode; in
  # API-key mode fall through to the base bearer-token handling.
  @use_sig_v4 = !@signer.nil?
  @use_bearer_auth = false

  # The Bedrock bearer rides the base client's `auth_token` slot;
  # {#resolve_default_credentials?} keeps first-party credential
  # auto-discovery out of the picture when it is absent.
  super(
    auth_token: @signer ? nil : api_key,
    base_url: base_url,
    timeout: timeout,
    max_retries: max_retries,
    initial_retry_delay: initial_retry_delay,
    max_retry_delay: max_retry_delay,
    middleware: middleware
  )
end

Instance Attribute Details

#aws_credentialsAws::Credentials (readonly)

Returns:

  • (Aws::Credentials)


24
25
26
# File 'lib/anthropic/helpers/bedrock/client.rb', line 24

def aws_credentials
  @aws_credentials
end

#aws_regionString (readonly)

Returns:

  • (String)


21
22
23
# File 'lib/anthropic/helpers/bedrock/client.rb', line 21

def aws_region
  @aws_region
end

#betaAnthropic::Resources::Beta (readonly)



18
19
20
# File 'lib/anthropic/helpers/bedrock/client.rb', line 18

def beta
  @beta
end

#completionsAnthropic::Resources::Completions (readonly)



15
16
17
# File 'lib/anthropic/helpers/bedrock/client.rb', line 15

def completions
  @completions
end

#messagesAnthropic::Resources::Messages (readonly)



12
13
14
# File 'lib/anthropic/helpers/bedrock/client.rb', line 12

def messages
  @messages
end

Instance Method Details

#api_keyString?

Returns:

  • (String, nil)


27
# File 'lib/anthropic/helpers/bedrock/client.rb', line 27

def api_key = @auth_token

#modelsbot

The Models API is not available on Bedrock, so the resource the parent wires up would target routes the Bedrock host does not serve — keep it unavailable, matching the SDK's other Bedrock clients.

Returns:

  • (bot)

Raises:

  • (NotImplementedError)


162
163
164
165
166
167
# File 'lib/anthropic/helpers/bedrock/client.rb', line 162

def models
  # rubocop:disable Layout/LineLength
  message = "Please instead use https://docs.anthropic.com/en/api/claude-on-amazon-bedrock#list-available-models to list available models on Bedrock."
  # rubocop:enable Layout/LineLength
  raise NotImplementedError.new(message)
end

#resolve_region_and_credentials(aws_region:, aws_secret_key:, aws_access_key:, aws_session_token:, aws_profile:) ⇒ Array<String, Aws::Credentials>

Parameters:

  • aws_region (String, nil)
  • aws_secret_key (String, nil)
  • aws_access_key (String, nil)
  • aws_session_token (String, nil)
  • aws_profile (String, nil)

Returns:

  • (Array<String, Aws::Credentials>)


266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/anthropic/helpers/bedrock/client.rb', line 266

private def resolve_region_and_credentials(
  aws_region:,
  aws_secret_key:,
  aws_access_key:,
  aws_session_token:,
  aws_profile:
)
  client_options = {
    access_key_id: aws_access_key,
    secret_access_key: aws_secret_key,
    session_token: aws_session_token,
    profile: aws_profile
  }
  (client_options[:region] = aws_region) unless aws_region.nil?

  bedrock_client = Aws::BedrockRuntime::Client.new(client_options)
  [bedrock_client.config.region, bedrock_client.config.credentials.credentials]
end