Class: Legion::Extensions::Llm::Bedrock::Provider
- Inherits:
-
Provider
- Object
- Provider
- Legion::Extensions::Llm::Bedrock::Provider
- 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
- .capabilities ⇒ Object
- .configuration_options ⇒ Object
- .configuration_requirements ⇒ Object
- .default_tier ⇒ Object
- .default_transport ⇒ Object
- .inference_profile_id(model, geo_prefix: 'us', region: nil) ⇒ Object
- .normalize_geo_prefix(value) ⇒ Object
- .registry_publisher ⇒ Object
-
.resolve_model_id(model_id, config: nil) ⇒ Object
rubocop:disable Lint/UnusedMethodArgument.
- .slug ⇒ Object
Instance Method Summary collapse
- #api_base ⇒ Object
- #chat(messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {}, thinking: nil, **_provider_options) ⇒ Object
-
#complete(messages, tools:, temperature:, model:, params: {}, headers: {}, schema: nil, thinking: nil, tool_prefs: nil) ⇒ Object
rubocop:disable Lint/UnusedMethodArgument.
- #completion_url ⇒ Object
- #count_tokens(messages:, model:, system: nil, params: {}) ⇒ Object
- #count_tokens_url ⇒ Object
- #discover_live_offerings(filters, provider_health, live:) ⇒ Object
- #discover_offerings(live: false, **filters) ⇒ Object
- #discovery_registry_readiness(provider_health, live:) ⇒ Object
- #embed(text:, model:, dimensions: nil, params: {}, **_provider_options) ⇒ Object
- #embedding_url ⇒ Object
- #geo_prefix ⇒ Object
- #health(live: false) ⇒ Object
- #list_models(**filters) ⇒ Object
- #log_discover_complete(offerings) ⇒ Object
- #log_model_discovered(model) ⇒ Object
- #models_url ⇒ Object
- #offering_for(model:, model_family: nil, instance_id: :default, **metadata) ⇒ Object
- #readiness(live: false) ⇒ Object
- #region ⇒ Object
- #settings ⇒ Object
- #stream(messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {}, thinking: nil, **_provider_options) ⇒ Object
- #stream_url ⇒ Object
- #translator ⇒ Object
Class Method Details
.capabilities ⇒ Object
77 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 77 def capabilities = Capabilities |
.configuration_options ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 62 def %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_requirements ⇒ Object
76 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 76 def configuration_requirements = [] |
.default_tier ⇒ Object
60 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 60 def default_tier = :cloud |
.default_transport ⇒ Object
59 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 59 def default_transport = :aws_sdk |
.inference_profile_id(model, geo_prefix: 'us', region: nil) ⇒ Object
89 90 91 92 93 94 95 96 97 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 89 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
99 100 101 102 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 99 def normalize_geo_prefix(value) candidate = value.to_s.downcase %w[us eu ap].include?(candidate) ? candidate : 'us' end |
.registry_publisher ⇒ Object
79 80 81 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 79 def registry_publisher Bedrock.registry_publisher end |
.resolve_model_id(model_id, config: nil) ⇒ Object
rubocop:disable Lint/UnusedMethodArgument
83 84 85 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 83 def resolve_model_id(model_id, config: nil) # rubocop:disable Lint/UnusedMethodArgument ALIASES.fetch(model_id.to_s, model_id.to_s) end |
.slug ⇒ Object
58 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 58 def slug = 'bedrock' |
Instance Method Details
#api_base ⇒ Object
130 131 132 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 130 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
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 301 302 303 304 305 306 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 212 def chat( messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {}, thinking: nil, ** ) enforce_model_allowed!(model_id(model)) log.info { "bedrock.provider.chat: model=#{model_id(model)} 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(, 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.} 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.}" } 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
421 422 423 424 425 426 427 428 429 430 431 432 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 421 def complete(, 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_url ⇒ Object
134 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 134 def completion_url = 'Converse' |
#count_tokens(messages:, model:, system: nil, params: {}) ⇒ Object
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 378 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: (), 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_url ⇒ Object
138 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 138 def count_tokens_url = 'CountTokens' |
#discover_live_offerings(filters, provider_health, live:) ⇒ Object
318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 318 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
203 204 205 206 207 208 209 210 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 203 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
308 309 310 311 312 313 314 315 316 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 308 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
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 396 def ( text:, model:, dimensions: nil, params: {}, ** ) mid = model_id(model) enforce_model_allowed!(mid) unless (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) ) (response, model: mid) end |
#embedding_url ⇒ Object
137 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 137 def (**) = 'InvokeModel' |
#geo_prefix ⇒ Object
144 145 146 147 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 144 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
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 161 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.) end |
#list_models(**filters) ⇒ Object
192 193 194 195 196 197 198 199 200 201 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 192 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
337 338 339 340 341 342 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 337 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
330 331 332 333 334 335 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 330 def log_model_discovered(model) log.debug( "[#{slug}] instance=#{provider_instance_id} action=model_discovered " \ "model=#{model.id} family=#{model.family}" ) end |
#models_url ⇒ Object
136 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 136 def models_url = 'ListFoundationModels' |
#offering_for(model:, model_family: nil, instance_id: :default, **metadata) ⇒ Object
149 150 151 152 153 154 155 156 157 158 159 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 149 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
184 185 186 187 188 189 190 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 184 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 |
#region ⇒ Object
140 141 142 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 140 def region config.bedrock_region || settings[:region] || 'us-east-1' end |
#settings ⇒ Object
126 127 128 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 126 def settings Bedrock.default_settings end |
#stream(messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {}, thinking: nil, **_provider_options) ⇒ Object
344 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 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 344 def stream(messages:, model:, temperature: nil, max_tokens: nil, tools: {}, tool_prefs: nil, params: {}, thinking: nil, **, &) enforce_model_allowed!(model_id(model)) log.info do "bedrock.provider.stream: model=#{model_id(model)} 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(, 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_url ⇒ Object
135 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 135 def stream_url = 'ConverseStream' |
#translator ⇒ Object
122 123 124 |
# File 'lib/legion/extensions/llm/bedrock/provider.rb', line 122 def translator @translator ||= Translator.new(region: region) end |