Class: Legion::Extensions::Llm::Bedrock::Provider

Inherits:
Provider
  • Object
show all
Includes:
Logging::Helper
Defined in:
lib/legion/extensions/llm/bedrock/provider.rb

Overview

Amazon Bedrock provider implementation for the Legion::Extensions::Llm contract.

Defined Under Namespace

Modules: Capabilities

Constant Summary collapse

STATIC_MODELS =
[
  { model: 'anthropic.claude-3-haiku-20240307-v1:0', alias: 'claude-3-haiku' },
  { model: 'anthropic.claude-sonnet-4-20250514-v1:0', alias: 'anthropic.claude-sonnet-4' },
  { model: 'amazon.titan-text-express-v1', alias: 'titan-text-express' },
  { model: 'amazon.titan-embed-text-v2:0', alias: 'titan-embed-text-v2', usage_type: :embedding },
  { model: 'meta.llama3-2-11b-instruct-v1:0', alias: 'llama-3.2-11b-instruct' },
  { model: 'mistral.mistral-large-3-675b-instruct', alias: 'mistral-large-3' }
].freeze
ALIASES =
STATIC_MODELS.to_h { |entry| [entry.fetch(:alias), entry.fetch(:model)] }.freeze
CONTEXT_WINDOWS =
{
  'anthropic.claude-sonnet-4' => 200_000,
  'anthropic.claude-haiku-4' => 200_000,
  'anthropic.claude-opus-4' => 200_000,
  'anthropic.claude-3-5-sonnet' => 200_000,
  'anthropic.claude-3-5-haiku' => 200_000,
  'anthropic.claude-3-haiku' => 200_000,
  'anthropic.claude-3-opus' => 200_000,
  'anthropic.claude-3-sonnet' => 200_000,
  'meta.llama3' => 128_000,
  'meta.llama3-1' => 128_000,
  'meta.llama3-2' => 128_000,
  'meta.llama3-3' => 128_000,
  'mistral.mistral-large' => 128_000,
  'mistral.mistral-small' => 128_000,
  'amazon.titan-text-express' => 8_192,
  'amazon.titan-text-premier' => 32_000,
  'amazon.nova-pro' => 300_000,
  'amazon.nova-lite' => 300_000,
  'amazon.nova-micro' => 128_000
}.freeze
INFERENCE_PROFILE_PREFIXES =
%w[anthropic. meta. mistral. cohere. ai21.].freeze
REGION_PREFIX =

Region-based inference profile prefix mapping. Bare model IDs (e.g. anthropic.claude-sonnet-4) get the region prefix.

{
  'us-east-1' => 'us', 'us-east-2' => 'us', 'us-west-1' => 'us', 'us-west-2' => 'us',
  'eu-central-1' => 'eu', 'eu-west-1' => 'eu', 'eu-west-2' => 'eu', 'eu-west-3' => 'eu',
  'ap-south-1' => 'ap', 'ap-southeast-1' => 'ap', 'ap-southeast-2' => 'ap', 'ap-northeast-1' => 'ap'
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.capabilitiesObject



70
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 70

def capabilities = Capabilities

.configuration_optionsObject



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 56

def configuration_options
  %i[
    bedrock_region
    bedrock_endpoint
    bedrock_access_key_id
    bedrock_secret_access_key
    bedrock_session_token
    bedrock_profile
    bedrock_stub_responses
    bearer_token
  ]
end

.configuration_requirementsObject



69
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 69

def configuration_requirements = []

.default_tierObject



54
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 54

def default_tier = :cloud

.default_transportObject



53
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 53

def default_transport = :aws_sdk

.inference_profile_id(model, region: nil) ⇒ Object



82
83
84
85
86
87
88
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 82

def inference_profile_id(model, region: nil)
  return model if model.start_with?('us.', 'eu.', 'ap.', 'arn:')
  return model unless INFERENCE_PROFILE_PREFIXES.any? { |p| model.start_with?(p) }

  prefix = region ? region_prefix(region) : 'us'
  "#{prefix}.#{model}"
end

.region_prefix(region) ⇒ Object



98
99
100
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 98

def region_prefix(region)
  REGION_PREFIX.fetch(region.to_s, 'us')
end

.registry_publisherObject



72
73
74
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 72

def registry_publisher
  Bedrock.registry_publisher
end

.resolve_model_id(model_id, config: nil) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



76
77
78
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 76

def resolve_model_id(model_id, config: nil) # rubocop:disable Lint/UnusedMethodArgument
  ALIASES.fetch(model_id.to_s, model_id.to_s)
end

.slugObject



52
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 52

def slug = 'bedrock'

Instance Method Details

#api_baseObject



120
121
122
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 120

def api_base
  config.bedrock_endpoint || "https://bedrock-runtime.#{region}.amazonaws.com"
end

#chat(messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {}, thinking: nil, **_provider_options) ⇒ Object



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
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
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 207

def chat(
  messages:,
  model:,
  temperature: nil,
  max_tokens: nil,
  tools: {},
  tool_prefs: nil,
  params: {},
  thinking: nil,
  **_provider_options
)
  log.info { "bedrock.provider.chat: model=#{model_id(model)} messages=#{messages.size}" }

  # Bedrock Converse API silently drops thinking config and tool_use blocks
  # for Claude Sonnet 4+. Use invoke_model with native Anthropic payload.
  if anthropic_model?(model_id(model)) && (thinking || (tools && !tools.empty?))
    return invoke_model_chat(messages:, model:, temperature:, max_tokens:, tools:, tool_prefs:,
                             thinking:, params:)
  end

  request = Utils.deep_merge(
    converse_request(messages, model:, temperature:, max_tokens:, tools:, tool_prefs:, thinking:),
    params
  )
  log.debug do
    "bedrock.provider.chat: request prepared model=#{model_id(model)} tools=#{tools.size} " \
      "tool_choice=#{tool_choice_label(tool_prefs)} param_keys=#{params.keys.map(&:to_s).sort.join(',')}"
  end

  # Log the thinking config being sent
  thinking_config = request.dig(:additional_model_request_fields, :thinking)
  log.debug { "bedrock.provider.chat: thinking_config=#{thinking_config.inspect}" } if thinking_config

  start_time = Time.now
  response = begin
    runtime_client.converse(**request)
  rescue StandardError => e
    elapsed = ((Time.now - start_time) * 1000).round
    log.error do
      "bedrock.provider.chat: converse failed model=#{model_id(model)} " \
        "error=#{e.class}: #{e.message} elapsed_ms=#{elapsed}"
    end
    raise
  end
  elapsed = ((Time.now - start_time) * 1000).round

  # Dump raw Bedrock response for debugging
  raw_debug = response.respond_to?(:to_h) ? response.to_h : response.inspect[0, 2000]
  dump_path = ENV.fetch('BEDROCK_DEBUG_OUTPUT', nil)
  if dump_path
    begin
      dump_file = File.join(dump_path, "bedrock_chat_#{Time.now.strftime('%Y%m%d_%H%M%S')}.json")
      File.write(dump_file, Legion::JSON.pretty_generate(raw_debug))
      log.debug { "bedrock.provider.chat: raw response dumped to #{dump_file}" }
    rescue StandardError => e
      log.warn { "bedrock.provider.chat: failed to dump raw response: #{e.message}" }
    end
  end

  # Log response metadata
  usage = value(response, :usage) || {}
  additional_fields = value(response, :additional_model_response_fields)
  output = value(response, :output)
  content_blocks = output ? value(output, :message) : nil
  # AWS SDK content blocks are structs, not hashes — use safe inspection
  block_types = if content_blocks
                  Array(value(content_blocks, :content)).map do |b|
                    if b.respond_to?(:reasoning)
                      'reasoning'
                    elsif b.respond_to?(:text)
                      'text'
                    elsif b.respond_to?(:tool_use)
                      'tool_use'
                    else
                      b.class.name
                    end
                  end.inspect
                else
                  'none'
                end
  af_keys = if additional_fields.respond_to?(:to_h)
              additional_fields.to_h.keys.map(&:to_s).sort
            else
              additional_fields.respond_to?(:keys) ? additional_fields.keys.map(&:to_s).sort : []
            end

  log.debug do
    "bedrock.provider.chat: response received model=#{model_id(model)} elapsed_ms=#{elapsed} " \
      "usage=#{usage.inspect} additional_fields_keys=#{af_keys.inspect} " \
      "content_block_types=#{block_types}"
  end

  parse_converse_response(response, model_id(model))
end

#complete(messages, tools:, temperature:, model:, params: {}, headers: {}, schema: nil, thinking: nil, tool_prefs: nil) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 377

def complete(messages, tools:, temperature:, model:, params: {}, headers: {}, schema: nil, thinking: nil, # rubocop:disable Lint/UnusedMethodArgument
             tool_prefs: nil, &)
  payload = params.dup
  payload[:additional_model_request_fields] ||= {}
  payload[:additional_model_request_fields][:response_format] = schema if schema

  if block_given?
    stream(messages:, model:, temperature:, tools:, tool_prefs:, params: payload, thinking:, &)
  else
    chat(messages:, model:, temperature:, tools:, tool_prefs:, params: payload, thinking:)
  end
end

#completion_urlObject



124
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 124

def completion_url = 'Converse'

#count_tokens(messages:, model:, system: nil, params: {}) ⇒ Object



335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 335

def count_tokens(
  messages:,
  model:,
  system: nil,
  params: {}
)
  log.debug { "bedrock.provider.count_tokens: model=#{model_id(model)}" }
  request = Utils.deep_merge(
    {
      model_id: self.class.inference_profile_id(model_id(model), region: region),
      input: { converse: { messages: format_messages(messages), system: system_blocks(system) }.compact }
    },
    params
  )
  response = runtime_client.count_tokens(**request)
  { input_tokens: value(response, :input_tokens), raw: normalize_response(response) }
end

#count_tokens_urlObject



128
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 128

def count_tokens_url = 'CountTokens'

#discover_offerings(live: false, **filters) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 134

def discover_offerings(live: false, **filters)
  unless live
    return @cached_offerings if @cached_offerings&.any?

    log.debug { 'bedrock.provider.discover_offerings: returning static catalog' }
    return static_offerings(**filters)
  end

  log.info { "bedrock.provider.discover_offerings: listing foundation models (region=#{region})" }
  response = bedrock_client.list_foundation_models(**filters)
  @cached_offerings = Array(value(response, :model_summaries)).filter_map do |summary|
    offering = offering_from_summary(summary)
    model_id = offering.respond_to?(:model) ? offering.model : (offering[:model] || offering[:id])
    next unless model_allowed?(model_id.to_s)

    offering
  end
  log.info { "bedrock.provider.discover_offerings: found #{@cached_offerings.size} models" }
  @cached_offerings
end

#embed(text:, model:, dimensions: nil, params: {}, **_provider_options) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 353

def embed(
  text:,
  model:,
  dimensions: nil,
  params: {},
  **_provider_options
)
  mid = model_id(model)
  unless titan_embed?(mid)
    raise NotImplementedError,
          "Bedrock embedding payload for #{mid} is not standardized"
  end

  log.info { "bedrock.provider.embed: model=#{mid}" }
  body = Utils.deep_merge({ inputText: text, dimensions: dimensions }.compact, params)
  response = runtime_client.invoke_model(
    model_id: mid,
    content_type: 'application/json',
    accept: 'application/json',
    body: Legion::JSON.generate(body)
  )
  parse_embedding_response(response, model: mid)
end

#embedding_urlObject



127
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 127

def embedding_url(**) = 'InvokeModel'

#health(live: false) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 167

def health(live: false)
  baseline = {
    provider: :bedrock,
    region: region,
    configured: true,
    ready: true,
    live: live,
    credentials: credential_source
  }
  unless live
    log.debug { "bedrock.provider.health: offline check (region=#{region})" }
    return baseline.merge(checked: false)
  end

  log.info { "bedrock.provider.health: live check (region=#{region})" }
  bedrock_client.list_foundation_models
  log.info { 'bedrock.provider.health: live check passed' }
  baseline.merge(checked: true)
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: 'bedrock.provider.health')
  baseline.merge(checked: true, ready: false, error: e.class.name, message: e.message)
end

#list_modelsObject



198
199
200
201
202
203
204
205
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 198

def list_models(**)
  log.info { 'bedrock.provider.list_models: fetching live model list' }
  response = bedrock_client.list_foundation_models
  models = Array(value(response, :model_summaries)).filter_map { |summary| model_info_from_summary(summary) }
  log.info { "bedrock.provider.list_models: found #{models.size} models" }
  self.class.registry_publisher.publish_models_async(models, readiness: readiness(live: false))
  models
end

#models_urlObject



126
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 126

def models_url = 'ListFoundationModels'

#offering_for(model:, model_family: nil, instance_id: :default, **metadata) ⇒ Object



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 155

def offering_for(model:, model_family: nil, instance_id: :default, **)
  model_id = self.class.resolve_model_id(model)
  build_offering(
    model: model_id,
    alias_name: alias_for(model_id),
    model_family: model_family || model_family_for(model_id),
    instance_id: instance_id,
    usage_type: .delete(:usage_type) || usage_type_for(model_id),
    metadata: 
  )
end

#readiness(live: false) ⇒ Object



190
191
192
193
194
195
196
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 190

def readiness(live: false)
  log.debug { "bedrock.provider.readiness: checking (live=#{live})" }
  health(live: live).merge(local: false, remote: true, api_base: api_base,
                           endpoints: endpoint_manifest).tap do ||
    self.class.registry_publisher.publish_readiness_async() if live
  end
end

#regionObject



130
131
132
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 130

def region
  config.bedrock_region || settings[:region] || 'us-east-1'
end

#stream(messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {}, thinking: nil, **_provider_options) ⇒ Object



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
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 302

def stream(messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {},
           thinking: nil, **_provider_options, &)
  log.info do
    "bedrock.provider.stream: model=#{model_id(model)} messages=#{messages.size} tools=#{tools.size}"
  end

  # Bedrock Converse API silently drops thinking config and tool_use blocks
  # for Claude Sonnet 4+. Use invoke_model with native Anthropic payload.
  if anthropic_model?(model_id(model)) && (thinking || (tools && !tools.empty?))
    return invoke_model_stream(messages:, model:, temperature:, max_tokens:, tools:, tool_prefs:,
                               thinking:, params:, &)
  end

  request = Utils.deep_merge(
    converse_request(messages, model:, temperature:, max_tokens:, tools:, tool_prefs:, thinking:),
    params
  )
  log.debug do
    "bedrock.provider.stream: request prepared model=#{model_id(model)} tools=#{tools.size} " \
      "tool_choice=#{tool_choice_label(tool_prefs)} param_keys=#{params.keys.map(&:to_s).sort.join(',')}"
  end

  # Log the thinking config being sent
  thinking_config = request.dig(:additional_model_request_fields, :thinking)
  log.debug { "bedrock.provider.stream: thinking_config=#{thinking_config.inspect}" } if thinking_config

  start_time = Time.now
  result = stream_converse(request, model_id(model), &)
  elapsed = ((Time.now - start_time) * 1000).round
  log.debug { "bedrock.provider.stream: completed model=#{model_id(model)} elapsed_ms=#{elapsed}" }
  result
end

#stream_urlObject



125
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 125

def stream_url = 'ConverseStream'