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: 'anthropic.claude-sonnet-4-20250514-v1:0', alias: 'claude-sonnet-4-6' },
  { model: 'anthropic.claude-sonnet-4-20250514-v1:0', alias: 'claude-sonnet-4-5-20241022' },
  { model: 'anthropic.claude-opus-4-20250515-v1:0', alias: 'claude-opus-4-8' },
  { model: 'anthropic.claude-haiku-4-20250506-v1:0', alias: 'claude-haiku-4-5' },
  { 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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.capabilitiesObject



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

def capabilities = Capabilities

.configuration_optionsObject



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 63

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

.configuration_requirementsObject



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

def configuration_requirements = []

.default_tierObject



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

def default_tier = :cloud

.default_transportObject



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

def default_transport = :aws_sdk

.inference_profile_id(model, geo_prefix: 'us', region: nil) ⇒ Object



90
91
92
93
94
95
96
97
98
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 90

def inference_profile_id(model, geo_prefix: 'us', region: nil)
  return model if model.start_with?('arn:')

  canonical = model.sub(/\A(?:us|eu|ap)\./, '')
  return canonical unless INFERENCE_PROFILE_PREFIXES.any? { |p| canonical.start_with?(p) }

  prefix = normalize_geo_prefix(geo_prefix || region)
  "#{prefix}.#{canonical}"
end

.normalize_geo_prefix(value) ⇒ Object



100
101
102
103
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 100

def normalize_geo_prefix(value)
  candidate = value.to_s.downcase
  %w[us eu ap].include?(candidate) ? candidate : 'us'
end

.registry_publisherObject



80
81
82
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 80

def registry_publisher
  Bedrock.registry_publisher
end

.resolve_model_id(model_id, config: nil) ⇒ Object

rubocop:disable Lint/UnusedMethodArgument



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

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

.slugObject



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

def slug = 'bedrock'

Instance Method Details

#api_baseObject



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

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



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
301
302
303
304
305
306
307
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 213

def chat(
  messages:,
  model:,
  temperature: nil,
  max_tokens: nil,
  tools: {},
  tool_prefs: nil,
  params: {},
  thinking: nil,
  **_provider_options
)
  enforce_model_allowed!(model_id(model))
  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



422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 422

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



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

def completion_url = 'Converse'

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



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 379

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), geo_prefix: geo_prefix),
      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



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

def count_tokens_url = 'CountTokens'

#discover_live_offerings(filters, provider_health, live:) ⇒ Object



319
320
321
322
323
324
325
326
327
328
329
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 319

def discover_live_offerings(filters, provider_health, live:)
  readiness = discovery_registry_readiness(provider_health, live:)
  Array(list_models(live:, **filters)).filter_map do |model|
    self.class.registry_publisher.publish_models_async([model], readiness:)
    next unless model_matches_filters?(model, filters)
    next unless model_allowed?(model.id)

    log_model_discovered(model)
    offering_from_model(model, health: provider_health)
  end
end

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



204
205
206
207
208
209
210
211
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 204

def discover_offerings(live: false, **filters)
  return static_offerings(**filters) unless live

  provider_health = health(live:)
  @cached_offerings = discover_live_offerings(filters, provider_health, live:)
  log_discover_complete(@cached_offerings)
  @cached_offerings
end

#discovery_registry_readiness(provider_health, live:) ⇒ Object



309
310
311
312
313
314
315
316
317
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 309

def discovery_registry_readiness(provider_health, live:)
  {
    provider: slug.to_sym,
    configured: configured?,
    ready: provider_health[:ready] == true,
    live: live,
    health: provider_health
  }
end

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



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 397

def embed(
  text:,
  model:,
  dimensions: nil,
  params: {},
  **_provider_options
)
  mid = model_id(model)
  enforce_model_allowed!(mid)
  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



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

def embedding_url(**) = 'InvokeModel'

#geo_prefixObject



145
146
147
148
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 145

def geo_prefix
  configured = config.bedrock_geo_prefix if config.respond_to?(:bedrock_geo_prefix)
  self.class.normalize_geo_prefix(configured || settings[:geo_prefix])
end

#health(live: false) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 162

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_models(**filters) ⇒ Object



193
194
195
196
197
198
199
200
201
202
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 193

def list_models(**filters)
  request_filters = {}
  request_filters[:by_provider] = filters[:by_provider] if filters[:by_provider]

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

#log_discover_complete(offerings) ⇒ Object



338
339
340
341
342
343
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 338

def log_discover_complete(offerings)
  log.info(
    "[#{slug}] instance=#{provider_instance_id} action=discover_complete " \
    "model_count=#{Array(offerings).size}"
  )
end

#log_model_discovered(model) ⇒ Object



331
332
333
334
335
336
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 331

def log_model_discovered(model)
  log.debug(
    "[#{slug}] instance=#{provider_instance_id} action=model_discovered " \
    "model=#{model.id} family=#{model.family}"
  )
end

#models_urlObject



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

def models_url = 'ListFoundationModels'

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



150
151
152
153
154
155
156
157
158
159
160
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 150

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



185
186
187
188
189
190
191
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 185

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



141
142
143
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 141

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

#settingsObject



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

def settings
  Bedrock.default_settings
end

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



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 345

def stream(messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {},
           thinking: nil, **_provider_options, &)
  enforce_model_allowed!(model_id(model))
  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



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

def stream_url = 'ConverseStream'

#translatorObject



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

def translator
  @translator ||= Translator.new(region: region)
end