Module: RubyLLM::Protocols::Converse::Chat
- Defined in:
- lib/ruby_llm/protocols/converse/chat.rb
Overview
Chat methods for Bedrock Converse API.
Constant Summary collapse
- FINISH_REASONS =
{ 'end_turn' => :stop, 'stop_sequence' => :stop, 'max_tokens' => :max_tokens, 'model_context_window_exceeded' => :max_tokens, 'tool_use' => :tool_calls, 'guardrail_intervened' => :content_filter, 'content_filtered' => :content_filter }.freeze
- BEDROCK_INLINE_DOCUMENT_LIMIT =
4_500_000- PROMPT_CACHE_OPTIONS =
%i[ttl].freeze
- COUNT_TOKENS_KEYS =
%i[messages system toolConfig additionalModelRequestFields].freeze
- RANGED_EFFORTS =
%w[low medium high].freeze
- MINIMUM_BUDGET_TOKENS =
1- NOVA_DEFAULT_REASONING_EFFORT =
'low'
Class Method Summary collapse
-
.append_citations_content(citations_content, text, citations) ⇒ Object
A citationsContent block replaces the text block for a cited span: the generated text lives in its content member, and each citation points back at the source document or search result.
- .automatic_cache_target(system_messages, chat_messages, caching) ⇒ Object
-
.budget_ceiling(model, minimum, max_output_tokens) ⇒ Object
Bedrock rejects a budget that leaves no room for the answer.
- .budget_tokens_schema(model) ⇒ Object
- .build_output_config(schema) ⇒ Object
- .cache_boundary?(message, automatic_cache_target, caching: nil) ⇒ Boolean
- .cacheable_message?(message) ⇒ Boolean
- .citation_source_index(location) ⇒ Object
-
.citation_url(data, location) ⇒ Object
Search result citations carry the developer-provided source string.
- .completion_url ⇒ Object
- .converse_cache_block_for(caching) ⇒ Object
- .count_tokens_url ⇒ Object
- .default_input_schema ⇒ Object
- .default_large_file_upload_threshold ⇒ Object
-
.effort_budget_tokens(effort, schema, model, max_output_tokens) ⇒ Object
Models that take a budget reject reasoning_effort, so effort has to become a budget.
- .enumerated_budget(effort, schema) ⇒ Object
-
.escape_model_id(model_id) ⇒ Object
Application inference profile ARNs contain '/', but Bedrock expects the model id to remain one path segment.
- .extract_server_tool_calls(content_blocks) ⇒ Object
- .extract_text_and_citations(content_blocks) ⇒ Object
- .finish_reasons ⇒ Object
- .format_additional_model_request_fields(thinking, model, max_output_tokens = nil) ⇒ Object
- .format_cache_option_keys(keys) ⇒ Object
- .format_inference_config(_model, temperature, max_output_tokens = nil) ⇒ Object
- .format_message_content(msg, caching: nil, automatic_cache_target: nil, citations: false) ⇒ Object
- .format_messages(messages, caching: nil, automatic_cache_target: nil, citations: false) ⇒ Object
- .format_non_tool_message(msg, caching: nil, automatic_cache_target: nil, citations: false) ⇒ Object
-
.format_nova_reasoning_fields(thinking, model) ⇒ Object
Nova 2 takes reasoningConfig with an effort level instead of a token budget, and rejects an enabled reasoningConfig that names no effort.
- .format_reasoning_fields(thinking, model, max_output_tokens = nil) ⇒ Object
- .format_role(role) ⇒ Object
- .format_structured_message_content(msg, citations: false) ⇒ Object
- .format_system(messages, caching: nil, automatic_cache_target: nil) ⇒ Object
- .format_thinking_block(thinking) ⇒ Object
- .format_thinking_blocks(msg) ⇒ Object
- .format_tool(tool) ⇒ Object
- .format_tool_choice(choice) ⇒ Object
- .format_tool_config(tools, tool_prefs) ⇒ Object
- .format_tool_result_block(msg) ⇒ Object
- .format_tool_result_content(msg) ⇒ Object
-
.foundation_model_id(model_id) ⇒ Object
Inference profile and foundation model ARNs name the model in their last segment.
- .input_tokens(usage) ⇒ Object
- .joined_text(parts) ⇒ Object
- .normalize_finish_reason(reason) ⇒ Object
- .nova_model?(model) ⇒ Boolean
- .parse_citation(data, text: nil, start_index: nil, end_index: nil) ⇒ Object
- .parse_completion_body(data, raw:) ⇒ Object
- .parse_count_tokens_response(response) ⇒ Object
- .parse_reasoning_content_block(block) ⇒ Object
- .parse_thinking(content_blocks) ⇒ Object
- .parse_thinking_blocks(content_blocks) ⇒ Object
- .parse_tool_calls(content_blocks) ⇒ Object
- .prompt_cache_options(caching) ⇒ Object
- .provider_file_attachable?(attachment) ⇒ Boolean
- .ranged_budget(effort, schema) ⇒ Object
- .reasoning_budget(thinking, effort, model, max_output_tokens) ⇒ Object
-
.reasoning_budget_schema(model) ⇒ Object
Bedrock only publishes Converse metadata for some regional entries, so use the schema from another entry for the same foundation model when needed.
- .reasoning_tokens(usage) ⇒ Object
- .render_count_tokens_payload(messages, tools:, model:, tool_prefs: nil, thinking: nil, schema: nil, citations: false, caching: nil) ⇒ Object
-
.render_payload(messages, tools:, temperature:, model:, stream: false, max_output_tokens: nil, schema: nil, thinking: nil, citations: false, caching: nil, tool_prefs: nil) ⇒ Object
rubocop:disable-next Lint/UnusedMethodArgument.
- .search_result_block(result) ⇒ Object
- .server_tool_result?(tool_result) ⇒ Boolean
-
.server_tool_use?(tool_use) ⇒ Boolean
Provider-executed tool steps come back with a distinguishing type, such as server_tool_use; function calls carry no type or the plain tool_use type.
- .supports_provider_file_references? ⇒ Boolean
- .text_tool_result_block(text) ⇒ Object
- .unknown_effort_message(effort, schema) ⇒ Object
Class Method Details
.append_citations_content(citations_content, text, citations) ⇒ Object
A citationsContent block replaces the text block for a cited span: the generated text lives in its content member, and each citation points back at the source document or search result.
554 555 556 557 558 559 560 561 562 563 564 565 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 554 def append_citations_content(citations_content, text, citations) block_text = joined_text(citations_content['content']) span = {} unless block_text.empty? span = { text: block_text, start_index: text.length, end_index: text.length + block_text.length } end Array(citations_content['citations']).each do |citation| citations << parse_citation(citation, **span) end text << block_text end |
.automatic_cache_target(system_messages, chat_messages, caching) ⇒ Object
267 268 269 270 271 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 267 def automatic_cache_target(, , caching) return unless caching (.reverse + .reverse).find { |msg| (msg) } end |
.budget_ceiling(model, minimum, max_output_tokens) ⇒ Object
Bedrock rejects a budget that leaves no room for the answer.
480 481 482 483 484 485 486 487 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 480 def budget_ceiling(model, minimum, max_output_tokens) ceiling = max_output_tokens - 1 return ceiling if minimum <= ceiling raise ArgumentError, "#{model&.id} reasons on a budget of at least #{minimum} tokens, and " \ "max_output_tokens: #{max_output_tokens} leaves room for #{ceiling}. " \ "Raise max_output_tokens above #{minimum} or turn thinking off." end |
.budget_tokens_schema(model) ⇒ Object
448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 448 def budget_tokens_schema(model) = RubyLLM::Support::Utils.deep_symbolize_keys(model&. || {}) raw_schema = .dig(:converse, :additionalRequestFieldsSchema) return unless raw_schema.is_a?(String) schema = JSON.parse(raw_schema, symbolize_names: true) budget = schema.is_a?(Hash) ? schema.dig(:reasoningConfig, :budgetTokens) : nil budget if budget.is_a?(Hash) rescue JSON::ParserError nil end |
.build_output_config(schema) ⇒ Object
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 365 def build_output_config(schema) return nil unless schema cleaned = RubyLLM::Support::Utils.deep_dup(schema[:schema]) cleaned.delete(:strict) cleaned.delete('strict') { textFormat: { type: 'json_schema', structure: { jsonSchema: { schema: JSON.generate(cleaned), name: schema[:name] } } } } end |
.cache_boundary?(message, automatic_cache_target, caching: nil) ⇒ Boolean
277 278 279 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 277 def cache_boundary?(, automatic_cache_target, caching: nil) caching != false && (.cache_until_here? || .equal?(automatic_cache_target)) end |
.cacheable_message?(message) ⇒ Boolean
273 274 275 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 273 def () !.tool_result? end |
.citation_source_index(location) ⇒ Object
596 597 598 599 600 601 602 603 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 596 def citation_source_index(location) %w[documentChar documentPage documentChunk].each do |key| index = location.dig(key, 'documentIndex') return index if index end location.dig('searchResultLocation', 'searchResultIndex') end |
.citation_url(data, location) ⇒ Object
Search result citations carry the developer-provided source string.
591 592 593 594 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 591 def citation_url(data, location) url = location.dig('web', 'url') || data['source'] url if url&.match?(%r{\Ahttps?://}i) end |
.completion_url ⇒ Object
32 33 34 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 32 def completion_url "/model/#{escape_model_id(@model.id)}/converse" end |
.converse_cache_block_for(caching) ⇒ Object
281 282 283 284 285 286 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 281 def converse_cache_block_for(caching) = (caching) point = { type: 'default' } point[:ttl] = [:ttl] if [:ttl] { cachePoint: point } end |
.count_tokens_url ⇒ Object
71 72 73 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 71 def count_tokens_url "/model/#{escape_model_id(@model.id)}/count-tokens" end |
.default_input_schema ⇒ Object
684 685 686 687 688 689 690 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 684 def default_input_schema { 'type' => 'object', 'properties' => {}, 'required' => [] } end |
.default_large_file_upload_threshold ⇒ Object
100 101 102 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 100 def default_large_file_upload_threshold BEDROCK_INLINE_DOCUMENT_LIMIT end |
.effort_budget_tokens(effort, schema, model, max_output_tokens) ⇒ Object
Models that take a budget reject reasoning_effort, so effort has to become a budget. Bedrock names the levels of an enumerated budget after the efforts they stand for; otherwise the effort spans the range the schema allows.
469 470 471 472 473 474 475 476 477 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 469 def effort_budget_tokens(effort, schema, model, max_output_tokens) budget = enumerated_budget(effort, schema) || ranged_budget(effort, schema) return nil unless budget minimum = schema[:minimum].is_a?(Integer) ? schema[:minimum] : MINIMUM_BUDGET_TOKENS return [budget, minimum].max unless max_output_tokens budget.clamp(minimum, budget_ceiling(model, minimum, max_output_tokens)) end |
.enumerated_budget(effort, schema) ⇒ Object
489 490 491 492 493 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 489 def enumerated_budget(effort, schema) levels = schema[:enum] level = levels.is_a?(Hash) ? levels[effort.to_sym] : nil level if level.is_a?(Integer) end |
.escape_model_id(model_id) ⇒ Object
Application inference profile ARNs contain '/', but Bedrock expects the model id to remain one path segment.
38 39 40 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 38 def escape_model_id(model_id) model_id.to_s.gsub('/', '%2F') end |
.extract_server_tool_calls(content_blocks) ⇒ Object
669 670 671 672 673 674 675 676 677 678 679 680 681 682 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 669 def extract_server_tool_calls(content_blocks) content_blocks.filter_map do |block| tool_use = block['toolUse'] tool_result = block['toolResult'] if tool_use && server_tool_use?(tool_use) ServerToolCall.new(type: tool_use['type'], name: tool_use['name'], id: tool_use['toolUseId'], input: tool_use['input'], raw: block) elsif tool_result && server_tool_result?(tool_result) ServerToolCall.new(type: tool_result['type'], id: tool_result['toolUseId'], result: tool_result['content'], raw: block) end end end |
.extract_text_and_citations(content_blocks) ⇒ Object
536 537 538 539 540 541 542 543 544 545 546 547 548 549 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 536 def extract_text_and_citations(content_blocks) text = +'' citations = [] content_blocks.each do |block| if block['text'].is_a?(String) text << block['text'] elsif block['citationsContent'].is_a?(Hash) append_citations_content(block['citationsContent'], text, citations) end end [text.empty? ? nil : text, citations] end |
.finish_reasons ⇒ Object
24 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 24 def finish_reasons = FINISH_REASONS |
.format_additional_model_request_fields(thinking, model, max_output_tokens = nil) ⇒ Object
356 357 358 359 360 361 362 363 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 356 def format_additional_model_request_fields(thinking, model, max_output_tokens = nil) fields = {} reasoning_fields = format_reasoning_fields(thinking, model, max_output_tokens) fields = RubyLLM::Support::Utils.deep_merge(fields, reasoning_fields) if reasoning_fields fields.empty? ? nil : fields end |
.format_cache_option_keys(keys) ⇒ Object
299 300 301 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 299 def format_cache_option_keys(keys) keys.map { |key| ":#{key}" }.join(', ') end |
.format_inference_config(_model, temperature, max_output_tokens = nil) ⇒ Object
303 304 305 306 307 308 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 303 def format_inference_config(_model, temperature, max_output_tokens = nil) config = {} config[:temperature] = temperature unless temperature.nil? config[:maxTokens] = max_output_tokens unless max_output_tokens.nil? config end |
.format_message_content(msg, caching: nil, automatic_cache_target: nil, citations: false) ⇒ Object
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 179 def (msg, caching: nil, automatic_cache_target: nil, citations: false) blocks = (msg, citations:) if msg.tool_call? msg.tool_calls.each_value do |tool_call| blocks << { toolUse: { toolUseId: tool_call.id, name: tool_call.name, input: tool_call.arguments } } end end blocks << converse_cache_block_for(caching) if cache_boundary?(msg, automatic_cache_target, caching:) blocks end |
.format_messages(messages, caching: nil, automatic_cache_target: nil, citations: false) ⇒ Object
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 146 def (, caching: nil, automatic_cache_target: nil, citations: false) rendered = [] tool_result_blocks = [] .each do |msg| if msg.tool_result? tool_result_blocks << format_tool_result_block(msg) next end unless tool_result_blocks.empty? rendered << { role: 'user', content: tool_result_blocks } tool_result_blocks = [] end = (msg, caching:, automatic_cache_target:, citations:) rendered << if end rendered << { role: 'user', content: tool_result_blocks } unless tool_result_blocks.empty? rendered end |
.format_non_tool_message(msg, caching: nil, automatic_cache_target: nil, citations: false) ⇒ Object
169 170 171 172 173 174 175 176 177 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 169 def (msg, caching: nil, automatic_cache_target: nil, citations: false) content = (msg, caching:, automatic_cache_target:, citations:) return nil if content.empty? { role: format_role(msg.role), content: content } end |
.format_nova_reasoning_fields(thinking, model) ⇒ Object
Nova 2 takes reasoningConfig with an effort level instead of a token budget, and rejects an enabled reasoningConfig that names no effort.
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 406 def format_nova_reasoning_fields(thinking, model) if thinking.budget raise ArgumentError, "#{model&.id} takes a reasoning effort, not a token budget of #{thinking.budget}. " \ 'Pass with_thinking(effort:) instead.' end return { reasoningConfig: { type: 'disabled' } } if thinking.enabled == false effort = thinking.effort.to_s return nil if effort == 'none' effort = NOVA_DEFAULT_REASONING_EFFORT if effort.empty? { reasoningConfig: { type: 'enabled', maxReasoningEffort: effort } } end |
.format_reasoning_fields(thinking, model, max_output_tokens = nil) ⇒ Object
387 388 389 390 391 392 393 394 395 396 397 398 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 387 def format_reasoning_fields(thinking, model, max_output_tokens = nil) return nil unless thinking&.enabled? return format_nova_reasoning_fields(thinking, model) if nova_model?(model) return { reasoning_config: { type: 'disabled' } } if thinking.enabled == false effort = thinking.effort.to_s budget = reasoning_budget(thinking, effort, model, max_output_tokens) return { reasoning_config: { type: 'enabled', budget_tokens: budget } } if budget return nil if effort.empty? || effort == 'none' { reasoning_effort: effort } end |
.format_role(role) ⇒ Object
249 250 251 252 253 254 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 249 def format_role(role) case role when :assistant then 'assistant' else 'user' end end |
.format_structured_message_content(msg, citations: false) ⇒ Object
198 199 200 201 202 203 204 205 206 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 198 def (msg, citations: false) blocks = msg.role == :assistant ? format_thinking_blocks(msg) : [] blocks.concat( Media.format_content(msg.content, msg., used_document_names: @used_document_names, citations:) ) blocks end |
.format_system(messages, caching: nil, automatic_cache_target: nil) ⇒ Object
256 257 258 259 260 261 262 263 264 265 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 256 def format_system(, caching: nil, automatic_cache_target: nil) .flat_map do |msg| blocks = Media.format_content(msg.content, msg., used_document_names: @used_document_names) if cache_boundary?(msg, automatic_cache_target, caching:) blocks + [converse_cache_block_for(caching)] else blocks end end end |
.format_thinking_block(thinking) ⇒ Object
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 515 def format_thinking_block(thinking) return nil unless thinking if thinking.text { reasoningContent: { reasoningText: { text: thinking.text, signature: thinking.signature }.compact } } elsif thinking.signature { reasoningContent: { redactedContent: thinking.signature } } end end |
.format_thinking_blocks(msg) ⇒ Object
208 209 210 211 212 213 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 208 def format_thinking_blocks(msg) blocks = msg.raw_reasoning['converse'] if msg.raw_reasoning.is_a?(Hash) return Support::Utils.deep_dup(blocks) if blocks [format_thinking_block(msg.thinking)].compact end |
.format_tool(tool) ⇒ Object
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 337 def format_tool(tool) input_schema = tool.parameters_schema || RubyLLM::Tool::SchemaDefinition.from_parameters(tool.declared_parameters)&.json_schema tool_spec = { toolSpec: { name: tool.name, description: tool.description, inputSchema: { json: input_schema || default_input_schema } } } return tool_spec if tool..empty? RubyLLM::Support::Utils.deep_merge(tool_spec, tool.) end |
.format_tool_choice(choice) ⇒ Object
324 325 326 327 328 329 330 331 332 333 334 335 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 324 def format_tool_choice(choice) case choice when :auto { auto: {} } when :none nil when :required { any: {} } else { tool: { name: choice.to_s } } end end |
.format_tool_config(tools, tool_prefs) ⇒ Object
310 311 312 313 314 315 316 317 318 319 320 321 322 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 310 def format_tool_config(tools, tool_prefs) return nil if tools.empty? config = { tools: tools.values.map { |tool| format_tool(tool) } } return config if tool_prefs.nil? || tool_prefs[:choice].nil? tool_choice = format_tool_choice(tool_prefs[:choice]) config[:toolChoice] = tool_choice if tool_choice config end |
.format_tool_result_block(msg) ⇒ Object
215 216 217 218 219 220 221 222 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 215 def format_tool_result_block(msg) { toolResult: { toolUseId: msg.tool_call_id, content: format_tool_result_content(msg) } } end |
.format_tool_result_content(msg) ⇒ Object
224 225 226 227 228 229 230 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 224 def format_tool_result_content(msg) search_results = RubyLLM::SearchResults.from_content(msg.content) return search_results.results.map { |result| search_result_block(result) } if search_results blocks = Media.format_content(msg.content, msg., used_document_names: @used_document_names) blocks.empty? ? [text_tool_result_block(nil)] : blocks end |
.foundation_model_id(model_id) ⇒ Object
Inference profile and foundation model ARNs name the model in their last segment.
461 462 463 464 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 461 def foundation_model_id(model_id) prefixes = Converse::REGION_PREFIXES.join('|') model_id.to_s.rpartition('/').last.sub(/\A(?:#{prefixes})\./, '') end |
.input_tokens(usage) ⇒ Object
134 135 136 137 138 139 140 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 134 def input_tokens(usage) # AWS Bedrock reports inputTokens as already non-cached; cacheReadInputTokens and # cacheWriteInputTokens are separate buckets, not folded into inputTokens. Subtracting # them (as inclusive providers require) understates input and floors to zero on cache # hits. See https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html usage['inputTokens'] end |
.joined_text(parts) ⇒ Object
586 587 588 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 586 def joined_text(parts) Array(parts).filter_map { |part| part['text'] if part.is_a?(Hash) }.join end |
.normalize_finish_reason(reason) ⇒ Object
26 27 28 29 30 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 26 def normalize_finish_reason(reason) return nil if reason.nil? finish_reasons.fetch(reason.to_s) { reason.to_s.to_sym } end |
.nova_model?(model) ⇒ Boolean
400 401 402 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 400 def nova_model?(model) foundation_model_id(model&.id).start_with?('amazon.nova') end |
.parse_citation(data, text: nil, start_index: nil, end_index: nil) ⇒ Object
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 567 def parse_citation(data, text: nil, start_index: nil, end_index: nil) location = data['location'] || {} page = location['documentPage'] || {} end_page = page['end'] cited_text = joined_text(data['sourceContent']) Citation.new( url: citation_url(data, location), title: data['title'], cited_text: cited_text.empty? ? nil : cited_text, text: text, start_index: start_index, end_index: end_index, source_index: citation_source_index(location), start_page: page['start'], end_page: end_page && (end_page - 1) ) end |
.parse_completion_body(data, raw:) ⇒ Object
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 109 def parse_completion_body(data, raw:) content_blocks = data.dig('output', 'message', 'content') || [] usage = data['usage'] || {} thinking_text, thinking_signature = parse_thinking(content_blocks) text_content, citations = extract_text_and_citations(content_blocks) Message.new( role: :assistant, content: text_content, citations: citations, thinking: Thinking.build(text: thinking_text, signature: thinking_signature), raw_reasoning: parse_thinking_blocks(content_blocks), tool_calls: parse_tool_calls(content_blocks), server_tool_calls: extract_server_tool_calls(content_blocks), input_tokens: input_tokens(usage), output_tokens: usage['outputTokens'], cache_read_tokens: usage['cacheReadInputTokens'], cache_write_tokens: usage['cacheWriteInputTokens'], thinking_tokens: reasoning_tokens(usage), finish_reason: normalize_finish_reason(data['stopReason']), model: data['modelId'] || @model&.id, raw: raw ) end |
.parse_count_tokens_response(response) ⇒ Object
92 93 94 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 92 def parse_count_tokens_response(response) response.body['inputTokens'] end |
.parse_reasoning_content_block(block) ⇒ Object
626 627 628 629 630 631 632 633 634 635 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 626 def parse_reasoning_content_block(block) reasoning_content = block['reasoningContent'] return [nil, nil] unless reasoning_content.is_a?(Hash) reasoning_text = reasoning_content['reasoningText'] || {} text = reasoning_text['text'].is_a?(String) ? reasoning_text['text'] : nil signature = reasoning_text['signature'] if reasoning_text['signature'].is_a?(String) signature ||= reasoning_content['redactedContent'] if reasoning_content['redactedContent'].is_a?(String) [text, signature] end |
.parse_thinking(content_blocks) ⇒ Object
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 605 def parse_thinking(content_blocks) text = nil signature = nil content_blocks.each do |block| chunk_text, chunk_signature = parse_reasoning_content_block(block) if chunk_text text ||= +'' text << chunk_text end signature ||= chunk_signature end [text, signature] end |
.parse_thinking_blocks(content_blocks) ⇒ Object
621 622 623 624 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 621 def parse_thinking_blocks(content_blocks) blocks = content_blocks.select { |block| block['reasoningContent'].is_a?(Hash) } { 'converse' => blocks } unless blocks.empty? end |
.parse_tool_calls(content_blocks) ⇒ Object
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 637 def parse_tool_calls(content_blocks) tool_calls = {} content_blocks.each do |block| tool_use = block['toolUse'] next unless tool_use next if server_tool_use?(tool_use) tool_call_id = tool_use['toolUseId'] tool_calls[tool_call_id] = ToolCall.new( id: tool_call_id, name: tool_use['name'], arguments: tool_use['input'] || {} ) end tool_calls.empty? ? nil : tool_calls end |
.prompt_cache_options(caching) ⇒ Object
288 289 290 291 292 293 294 295 296 297 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 288 def (caching) return {} unless caching = caching.to_h.transform_keys(&:to_sym) unsupported = .keys - PROMPT_CACHE_OPTIONS return if unsupported.empty? raise ArgumentError, "Bedrock Converse prompt caching accepts :ttl, got #{format_cache_option_keys(unsupported)}" end |
.provider_file_attachable?(attachment) ⇒ Boolean
104 105 106 107 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 104 def provider_file_attachable?() (.pdf? || .document? || .text?) && Media.supported_document_format?() end |
.ranged_budget(effort, schema) ⇒ Object
495 496 497 498 499 500 501 502 503 504 505 506 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 495 def ranged_budget(effort, schema) minimum = schema[:minimum] maximum = schema[:maximum] return nil unless minimum.is_a?(Integer) && maximum.is_a?(Integer) case effort when 'low' then minimum when 'medium' then minimum + ((maximum - minimum) / 2) when 'high' then maximum else raise ArgumentError, (effort, schema) end end |
.reasoning_budget(thinking, effort, model, max_output_tokens) ⇒ Object
422 423 424 425 426 427 428 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 422 def reasoning_budget(thinking, effort, model, max_output_tokens) return thinking.budget if thinking.budget.is_a?(Integer) return nil if effort.empty? || effort == 'none' schema = reasoning_budget_schema(model) schema && effort_budget_tokens(effort, schema, model, max_output_tokens) end |
.reasoning_budget_schema(model) ⇒ Object
Bedrock only publishes Converse metadata for some regional entries, so use the schema from another entry for the same foundation model when needed.
432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 432 def reasoning_budget_schema(model) schema = budget_tokens_schema(model) return schema if schema return unless model foundation_id = foundation_model_id(model.id) RubyLLM.models.all.each do |candidate| next unless candidate.provider == 'bedrock' && candidate.id != model.id next unless foundation_model_id(candidate.id) == foundation_id return schema if (schema = budget_tokens_schema(candidate)) end nil end |
.reasoning_tokens(usage) ⇒ Object
142 143 144 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 142 def reasoning_tokens(usage) usage['reasoningTokens'] || usage.dig('outputTokensDetails', 'reasoningTokens') end |
.render_count_tokens_payload(messages, tools:, model:, tool_prefs: nil, thinking: nil, schema: nil, citations: false, caching: nil) ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 75 def render_count_tokens_payload(, tools:, model:, tool_prefs: nil, thinking: nil, schema: nil, citations: false, caching: nil) request = render_payload( , tools: tools, tool_prefs: tool_prefs, temperature: nil, model: model, schema: schema, thinking: thinking, citations: citations, caching: caching ).slice(*COUNT_TOKENS_KEYS) { input: { converse: request } } end |
.render_payload(messages, tools:, temperature:, model:, stream: false, max_output_tokens: nil, schema: nil, thinking: nil, citations: false, caching: nil, tool_prefs: nil) ⇒ Object
rubocop:disable-next Lint/UnusedMethodArgument
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 43 def render_payload(, tools:, temperature:, model:, stream: false, max_output_tokens: nil, schema: nil, thinking: nil, citations: false, caching: nil, tool_prefs: nil) tool_prefs ||= {} @used_document_names = {} , = .partition { |msg| msg.role == :system } (caching) automatic_cache_target = automatic_cache_target(, , caching) payload = { messages: (, caching:, automatic_cache_target:, citations:) } system_blocks = format_system(, caching:, automatic_cache_target:) payload[:system] = system_blocks unless system_blocks.empty? payload[:inferenceConfig] = format_inference_config(model, temperature, max_output_tokens) tool_config = format_tool_config(tools, tool_prefs) payload[:toolConfig] = tool_config if tool_config additional_fields = format_additional_model_request_fields(thinking, model, max_output_tokens) payload[:additionalModelRequestFields] = additional_fields if additional_fields output_config = build_output_config(schema) payload[:outputConfig] = output_config if output_config payload end |
.search_result_block(result) ⇒ Object
232 233 234 235 236 237 238 239 240 241 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 232 def search_result_block(result) { searchResult: { source: result[:url] || result[:title], title: result[:title], content: [{ text: result[:text] }], citations: { enabled: true } } } end |
.server_tool_result?(tool_result) ⇒ Boolean
664 665 666 667 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 664 def server_tool_result?(tool_result) type = tool_result['type'] !type.nil? && type != 'tool_result' end |
.server_tool_use?(tool_use) ⇒ Boolean
Provider-executed tool steps come back with a distinguishing type, such as server_tool_use; function calls carry no type or the plain tool_use type.
659 660 661 662 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 659 def server_tool_use?(tool_use) type = tool_use['type'] !type.nil? && type != 'tool_use' end |
.supports_provider_file_references? ⇒ Boolean
96 97 98 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 96 def supports_provider_file_references? true end |
.text_tool_result_block(text) ⇒ Object
243 244 245 246 247 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 243 def text_tool_result_block(text) text = text.to_s text = '(no output)' if text.empty? { text: text } end |
.unknown_effort_message(effort, schema) ⇒ Object
508 509 510 511 512 513 |
# File 'lib/ruby_llm/protocols/converse/chat.rb', line 508 def (effort, schema) levels = schema[:enum].is_a?(Hash) ? schema[:enum].keys.map(&:to_s) : [] levels |= RANGED_EFFORTS "Bedrock has no reasoning budget for effort #{effort.inspect}. " \ "Use #{levels.join(', ')}, or pass an explicit budget." end |