llm_gateway 0.8.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +36 -0
  3. data/README.md +190 -79
  4. data/Rakefile +5 -0
  5. data/docs/migration_guide_0.10.0.md +53 -0
  6. data/docs/migration_guide_0.9.0.md +166 -0
  7. data/docs/structured-output.md +28 -0
  8. data/lib/llm_gateway/adapter_definition.rb +64 -0
  9. data/lib/llm_gateway/adapters/adapter.rb +105 -21
  10. data/lib/llm_gateway/adapters/anthropic/messages_adapter.rb +8 -0
  11. data/lib/llm_gateway/adapters/anthropic_option_mapper.rb +29 -19
  12. data/lib/llm_gateway/adapters/groq/chat_completions_adapter.rb +8 -0
  13. data/lib/llm_gateway/adapters/groq/option_mapper.rb +7 -9
  14. data/lib/llm_gateway/adapters/normalized_stream_accumulator.rb +7 -3
  15. data/lib/llm_gateway/adapters/openai/chat_completions/option_mapper.rb +7 -9
  16. data/lib/llm_gateway/adapters/openai/chat_completions/stream_mapper.rb +1 -1
  17. data/lib/llm_gateway/adapters/openai/chat_completions_adapter.rb +6 -0
  18. data/lib/llm_gateway/adapters/openai/responses/option_mapper.rb +11 -9
  19. data/lib/llm_gateway/adapters/openai/responses/stream_mapper.rb +1 -1
  20. data/lib/llm_gateway/adapters/openai/responses_adapter.rb +6 -0
  21. data/lib/llm_gateway/adapters/openai_codex/responses_adapter.rb +8 -0
  22. data/lib/llm_gateway/adapters/stream_mapper.rb +4 -3
  23. data/lib/llm_gateway/agents/event.rb +31 -3
  24. data/lib/llm_gateway/agents/harness.rb +107 -74
  25. data/lib/llm_gateway/agents/in_memory_session_manager.rb +40 -9
  26. data/lib/llm_gateway/agents/tools/bash_tool.rb +6 -5
  27. data/lib/llm_gateway/agents/tools/edit_tool.rb +7 -6
  28. data/lib/llm_gateway/agents/tools/read_tool.rb +11 -10
  29. data/lib/llm_gateway/agents/tools/tool_utils.rb +2 -2
  30. data/lib/llm_gateway/agents/tools/write_tool.rb +4 -3
  31. data/lib/llm_gateway/errors.rb +3 -0
  32. data/lib/llm_gateway/models/catalog.rb +68 -0
  33. data/lib/llm_gateway/models/cost_calculator.rb +47 -0
  34. data/lib/llm_gateway/models/definition.rb +325 -0
  35. data/lib/llm_gateway/models/explicit.rb +46 -0
  36. data/lib/llm_gateway/models/generated.json +3055 -0
  37. data/lib/llm_gateway/models.rb +78 -0
  38. data/lib/llm_gateway/prompt.rb +55 -31
  39. data/lib/llm_gateway/proxy/adapter.rb +22 -12
  40. data/lib/llm_gateway/proxy/client.rb +4 -4
  41. data/lib/llm_gateway/proxy/protocol.rb +50 -0
  42. data/lib/llm_gateway/proxy/server.rb +12 -9
  43. data/lib/llm_gateway/tool.rb +49 -40
  44. data/lib/llm_gateway/utils.rb +12 -6
  45. data/lib/llm_gateway/version.rb +1 -1
  46. data/lib/llm_gateway.rb +5 -68
  47. data/scripts/generate_model_catalog.rb +195 -0
  48. metadata +14 -4
  49. data/lib/llm_gateway/client.rb +0 -35
  50. data/lib/llm_gateway/provider_registry.rb +0 -37
@@ -1,5 +1,6 @@
1
1
  require "securerandom"
2
2
  require "tmpdir"
3
+ require_relative "../../tool"
3
4
  require_relative "tool_utils"
4
5
 
5
6
  class BashTool < LlmGateway::Tool
@@ -17,7 +18,7 @@ class BashTool < LlmGateway::Tool
17
18
  required: [ "command" ]
18
19
  })
19
20
 
20
- def execute(input)
21
+ def execute(input, tool_use_id:)
21
22
  command = input[:command]
22
23
  timeout = input[:timeout]
23
24
 
@@ -25,16 +26,16 @@ class BashTool < LlmGateway::Tool
25
26
  out = format_output(result[:output], empty_text: result[:timed_out] ? "" : "(no output)")
26
27
 
27
28
  if result[:timed_out]
28
- return append_status(out, "Command timed out after #{timeout} seconds")
29
+ return tool_result(append_status(out, "Command timed out after #{timeout} seconds"), tool_use_id: tool_use_id)
29
30
  end
30
31
 
31
32
  if result[:exit_status] && result[:exit_status] != 0
32
- return append_status(out, "Command exited with code #{result[:exit_status]}")
33
+ return tool_result(append_status(out, "Command exited with code #{result[:exit_status]}"), tool_use_id: tool_use_id)
33
34
  end
34
35
 
35
- out
36
+ tool_result(out, tool_use_id: tool_use_id)
36
37
  rescue StandardError => e
37
- e.message
38
+ tool_result(e.message, tool_use_id: tool_use_id)
38
39
  end
39
40
 
40
41
  private
@@ -1,4 +1,5 @@
1
1
  require "json"
2
+ require_relative "../../tool"
2
3
  require_relative "tool_utils"
3
4
 
4
5
  class EditTool < LlmGateway::Tool
@@ -30,11 +31,11 @@ class EditTool < LlmGateway::Tool
30
31
  required: [ "path", "edits" ]
31
32
  })
32
33
 
33
- def execute(input)
34
+ def execute(input, tool_use_id:)
34
35
  path = input[:path]
35
36
  edits = prepare_edits(input[:edits])
36
37
 
37
- return "Edit tool input is invalid. edits must contain at least one replacement." if !edits.is_a?(Array) || edits.empty?
38
+ return tool_result("Edit tool input is invalid. edits must contain at least one replacement.", tool_use_id: tool_use_id) if !edits.is_a?(Array) || edits.empty?
38
39
 
39
40
  absolute_path = ToolUtils.resolve_to_cwd(path)
40
41
 
@@ -42,7 +43,7 @@ class EditTool < LlmGateway::Tool
42
43
  begin
43
44
  File.open(absolute_path, File::RDWR) { }
44
45
  rescue SystemCallError => e
45
- return "Could not edit file: #{path}. Error code: #{e.class.name.split("::").last}."
46
+ return tool_result("Could not edit file: #{path}. Error code: #{e.class.name.split("::").last}.", tool_use_id: tool_use_id)
46
47
  end
47
48
 
48
49
  raw_content = File.binread(absolute_path)
@@ -59,12 +60,12 @@ class EditTool < LlmGateway::Tool
59
60
  final_bytes = bom + restored.encode("UTF-8").b
60
61
 
61
62
  File.binwrite(absolute_path, final_bytes)
62
- "Successfully replaced #{edits.length} block(s) in #{path}."
63
+ tool_result("Successfully replaced #{edits.length} block(s) in #{path}.", tool_use_id: tool_use_id)
63
64
  end
64
65
  rescue EditError => e
65
- e.message
66
+ tool_result(e.message, tool_use_id: tool_use_id)
66
67
  rescue StandardError => e
67
- "Error editing file: #{e.message}"
68
+ tool_result("Error editing file: #{e.message}", tool_use_id: tool_use_id)
68
69
  end
69
70
 
70
71
  private
@@ -1,4 +1,5 @@
1
1
  require "base64"
2
+ require_relative "../../tool"
2
3
  require_relative "tool_utils"
3
4
 
4
5
  class ReadTool < LlmGateway::Tool
@@ -21,24 +22,24 @@ class ReadTool < LlmGateway::Tool
21
22
  IMAGE_TYPE_SNIFF_BYTES = 4100
22
23
  PNG_SIGNATURE = [ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a ].freeze
23
24
 
24
- def execute(input)
25
+ def execute(input, tool_use_id:)
25
26
  path = input[:path] || input["path"]
26
27
  offset = input[:offset] || input["offset"]
27
28
  limit = input[:limit] || input["limit"]
28
29
 
29
30
  absolute_path = ToolUtils.resolve_read_path(path)
30
31
 
31
- return "File not found: #{path}" unless File.exist?(absolute_path)
32
- return "Cannot read directory: #{path}" if File.directory?(absolute_path)
33
- return "File is not readable: #{path}" unless File.readable?(absolute_path)
32
+ return tool_result("File not found: #{path}", tool_use_id: tool_use_id) unless File.exist?(absolute_path)
33
+ return tool_result("Cannot read directory: #{path}", tool_use_id: tool_use_id) if File.directory?(absolute_path)
34
+ return tool_result("File is not readable: #{path}", tool_use_id: tool_use_id) unless File.readable?(absolute_path)
34
35
 
35
36
  mime_type = detect_supported_image_mime_type_from_file(absolute_path)
36
37
  if mime_type
37
38
  data = Base64.strict_encode64(File.binread(absolute_path))
38
- return [
39
+ return tool_result([
39
40
  { type: "text", text: "Read image file [#{mime_type}]" },
40
41
  { type: "image", data: data, media_type: mime_type }
41
- ]
42
+ ], tool_use_id: tool_use_id)
42
43
  end
43
44
 
44
45
  content = File.read(absolute_path, mode: "r:bom|utf-8")
@@ -46,7 +47,7 @@ class ReadTool < LlmGateway::Tool
46
47
  total_file_lines = all_lines.length
47
48
 
48
49
  start_line = [ 0, (offset || 1).to_i - 1 ].max
49
- return "Offset #{offset} is beyond end of file (#{all_lines.length} lines total)" if start_line >= all_lines.length
50
+ return tool_result("Offset #{offset} is beyond end of file (#{all_lines.length} lines total)", tool_use_id: tool_use_id) if start_line >= all_lines.length
50
51
 
51
52
  selected_content = if limit
52
53
  end_line = [ start_line + limit.to_i, all_lines.length ].min
@@ -60,7 +61,7 @@ class ReadTool < LlmGateway::Tool
60
61
 
61
62
  if truncation[:first_line_exceeds_limit]
62
63
  first_line_size = ToolUtils.format_size(all_lines[start_line].to_s.bytesize)
63
- return "[Line #{start_display} is #{first_line_size}, exceeds #{ToolUtils.format_size(ToolUtils::DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '#{start_display}p' #{path} | head -c #{ToolUtils::DEFAULT_MAX_BYTES}]"
64
+ return tool_result("[Line #{start_display} is #{first_line_size}, exceeds #{ToolUtils.format_size(ToolUtils::DEFAULT_MAX_BYTES)} limit. Use bash: sed -n '#{start_display}p' #{path} | head -c #{ToolUtils::DEFAULT_MAX_BYTES}]", tool_use_id: tool_use_id)
64
65
  end
65
66
 
66
67
  output = truncation[:content]
@@ -80,9 +81,9 @@ class ReadTool < LlmGateway::Tool
80
81
  output = "#{output}\n\n[#{remaining} more lines in file. Use offset=#{next_offset} to continue.]"
81
82
  end
82
83
 
83
- output
84
+ tool_result(output, tool_use_id: tool_use_id)
84
85
  rescue StandardError => e
85
- "Error reading file: #{e.message}"
86
+ tool_result("Error reading file: #{e.message}", tool_use_id: tool_use_id)
86
87
  end
87
88
 
88
89
  private
@@ -155,9 +155,9 @@ module ToolUtils
155
155
  bytes = str.dup.force_encoding("UTF-8").bytes
156
156
  return str if bytes.length <= max_bytes
157
157
 
158
- tail = bytes.last(max_bytes).pack("C*")
158
+ tail = bytes.last(max_bytes).pack("C*").force_encoding(Encoding::UTF_8)
159
159
  until tail.valid_encoding?
160
- tail = tail.bytes.drop(1).pack("C*")
160
+ tail = tail.bytes.drop(1).pack("C*").force_encoding(Encoding::UTF_8)
161
161
  end
162
162
  tail
163
163
  end
@@ -1,4 +1,5 @@
1
1
  require "fileutils"
2
+ require_relative "../../tool"
2
3
  require_relative "tool_utils"
3
4
 
4
5
  class WriteTool < LlmGateway::Tool
@@ -16,7 +17,7 @@ class WriteTool < LlmGateway::Tool
16
17
  required: [ "path", "content" ]
17
18
  })
18
19
 
19
- def execute(input)
20
+ def execute(input, tool_use_id:)
20
21
  path = input[:path] || input["path"]
21
22
  content = input[:content] || input["content"]
22
23
 
@@ -27,8 +28,8 @@ class WriteTool < LlmGateway::Tool
27
28
  File.write(absolute_path, content)
28
29
  end
29
30
 
30
- "Successfully wrote #{content.bytesize} bytes to #{path}"
31
+ tool_result("Successfully wrote #{content.bytesize} bytes to #{path}", tool_use_id: tool_use_id)
31
32
  rescue StandardError => e
32
- e.message
33
+ tool_result(e.message, tool_use_id: tool_use_id)
33
34
  end
34
35
  end
@@ -39,6 +39,9 @@ module LlmGateway
39
39
  class UnsupportedModel < ClientError; end
40
40
  class UnsupportedProvider < ClientError; end
41
41
  class MissingMapperForProvider < ClientError; end
42
+ class InvalidModelDefinition < BaseError; end
43
+ class ModelProviderMismatch < BaseError; end
44
+ class UnsupportedModelForAdapter < BaseError; end
42
45
 
43
46
  OVERFLOW_PATTERNS = [
44
47
  /prompt is too long/i, # Anthropic
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmGateway
4
+ module Models
5
+ class Catalog
6
+ def initialize(definitions = [])
7
+ @definitions = {}
8
+ definitions.each { |definition| register(definition) }
9
+ end
10
+
11
+ def register(definition, replace: false)
12
+ unless definition.is_a?(Definition)
13
+ raise ArgumentError, "Expected a model definition, got #{definition.inspect}"
14
+ end
15
+
16
+ key = [ definition.provider, definition.id ]
17
+ if @definitions.key?(key) && !replace
18
+ raise ArgumentError, "Duplicate model catalog entry: #{key.join("/")}"
19
+ end
20
+
21
+ @definitions[key] = definition
22
+ end
23
+
24
+ def find(reference = nil, provider: nil, id: nil)
25
+ provider, id = lookup_key(reference, provider:, id:)
26
+ @definitions[[ provider, id ]]
27
+ end
28
+
29
+ def fetch(reference = nil, provider: nil, id: nil)
30
+ provider, id = lookup_key(reference, provider:, id:)
31
+ @definitions.fetch([ provider, id ]) do
32
+ raise KeyError, "Unknown model catalog entry: #{provider}/#{id}"
33
+ end
34
+ end
35
+
36
+ def all(provider: nil)
37
+ return @definitions.values.freeze unless provider
38
+
39
+ @definitions.select { |(definition_provider, _), _| definition_provider == provider.to_s }.values.freeze
40
+ end
41
+
42
+ private
43
+
44
+ def lookup_key(reference, provider:, id:)
45
+ if reference
46
+ if provider || id
47
+ raise ArgumentError, "Pass either a model reference or provider:/id:, not both"
48
+ end
49
+ parse(reference)
50
+ else
51
+ if provider.nil? || provider.to_s.empty? || id.nil? || id.to_s.empty?
52
+ raise ArgumentError, "Both provider: and id: are required"
53
+ end
54
+ [ provider.to_s, id.to_s ]
55
+ end
56
+ end
57
+
58
+ def parse(reference)
59
+ provider, id = reference.to_s.split("/", 2)
60
+ if provider.nil? || provider.empty? || id.nil? || id.empty?
61
+ raise ArgumentError, "Model reference must be in provider/model form: #{reference.inspect}"
62
+ end
63
+
64
+ [ provider, id ]
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+
5
+ module LlmGateway
6
+ module Models
7
+ class CostCalculator
8
+ TOKENS_PER_MILLION = BigDecimal("1000000")
9
+
10
+ def self.calculate(definition, usage)
11
+ new(definition, usage).calculate
12
+ end
13
+
14
+ def initialize(definition, usage)
15
+ @definition = definition
16
+ @usage = usage.to_h.symbolize_keys
17
+ end
18
+
19
+ def calculate
20
+ return nil unless definition&.pricing
21
+
22
+ rates = definition.pricing.rates_for(input + cache_read + cache_write)
23
+ components = {
24
+ input: (rates.input * input) / TOKENS_PER_MILLION,
25
+ output: (rates.output * output) / TOKENS_PER_MILLION,
26
+ cache_read: (rates.cache_read * cache_read) / TOKENS_PER_MILLION,
27
+ cache_write: (rates.cache_write * cache_write) / TOKENS_PER_MILLION
28
+ }
29
+ components[:total] = components.values.sum
30
+ components.freeze
31
+ end
32
+
33
+ private
34
+
35
+ attr_reader :definition
36
+
37
+ def input = count(:input)
38
+ def output = count(:output)
39
+ def cache_read = count(:cache_read)
40
+ def cache_write = count(:cache_write)
41
+
42
+ def count(key)
43
+ Integer(@usage.fetch(key, 0))
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,325 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bigdecimal"
4
+ require "date"
5
+
6
+ module LlmGateway
7
+ module Models
8
+ class Definition
9
+ REASONING_LEVELS = %i[minimal low medium high max].freeze
10
+ REASONING_BLOCK_SIZE = 1_024
11
+ DEFAULT_REASONING_BUDGET_CEILING = 20_480
12
+
13
+ attr_reader :provider, :id, :name, :source, :release_date, :last_updated,
14
+ :context_window, :max_output_tokens, :input_modalities, :output_modalities,
15
+ :capabilities, :reasoning_controls, :pricing
16
+
17
+ def initialize(provider:, id:, name: nil, source: nil, release_date: nil, last_updated: nil,
18
+ context_window: nil, max_output_tokens: nil, input_modalities: [], output_modalities: [],
19
+ capabilities: {}, reasoning_controls: nil, pricing: nil)
20
+ @provider = non_empty_string(provider, :provider)
21
+ @id = non_empty_string(id, :id)
22
+ @name = (name || id).to_s.freeze
23
+ @source = source&.to_sym
24
+ @release_date = normalize_date(release_date, :release_date)
25
+ @last_updated = normalize_date(last_updated, :last_updated)
26
+ @context_window = non_negative_integer(context_window, :context_window)
27
+ @max_output_tokens = non_negative_integer(max_output_tokens, :max_output_tokens)
28
+ @input_modalities = normalize_modalities(input_modalities)
29
+ @output_modalities = normalize_modalities(output_modalities)
30
+ @capabilities = normalize_capabilities(capabilities)
31
+ @reasoning_controls = normalize_reasoning_controls(reasoning_controls)
32
+ @pricing = Pricing.new(pricing) if pricing
33
+ freeze
34
+ end
35
+
36
+ # Returns true, false, or nil when support for the capability is unknown.
37
+ def supports?(capability)
38
+ capabilities[capability.to_sym]
39
+ end
40
+
41
+ def supports_reasoning?
42
+ supports?(:reasoning)
43
+ end
44
+
45
+ def supports_input?(modality)
46
+ input_modalities.include?(modality.to_sym)
47
+ end
48
+
49
+ def supports_output?(modality)
50
+ output_modalities.include?(modality.to_sym)
51
+ end
52
+
53
+ # Canonical, UI-safe reasoning values supported by this definition.
54
+ # Provider-native controls remain available through #reasoning_controls.
55
+ def reasoning_options
56
+ return [].freeze unless supports?(:reasoning) == true
57
+
58
+ options = [ :default ]
59
+ control = preferred_reasoning_control
60
+ return options.freeze unless control
61
+
62
+ case control[:type]
63
+ when "effort"
64
+ options << :none if control[:values].include?("none")
65
+ options.concat(control[:values].filter_map { |value| canonical_positive_reasoning_value(value) })
66
+ when "budget_tokens"
67
+ options << :none
68
+ options.concat(REASONING_LEVELS)
69
+ when "toggle"
70
+ options.concat(%i[none high])
71
+ end
72
+
73
+ options.uniq.freeze
74
+ end
75
+
76
+ # Resolves a canonical reasoning option into a model control. Budget controls
77
+ # use the catalog model's output limit, or a conservative ceiling when absent.
78
+ def reasoning_control_for(option)
79
+ canonical = normalize_reasoning_option_name(option)
80
+ return { type: :none }.freeze if canonical == :none
81
+
82
+ raise ArgumentError, "Unsupported reasoning option #{option.inspect} for #{provider}/#{id}" unless reasoning_options.include?(canonical)
83
+
84
+ return nil if canonical == :default
85
+
86
+ control = preferred_reasoning_control
87
+ case control[:type]
88
+ when "effort"
89
+ { type: :effort, value: effort_for(control, canonical) }.freeze
90
+ when "budget_tokens"
91
+ { type: :budget_tokens, value: budget_for(control, canonical) }.freeze
92
+ when "toggle"
93
+ { type: :toggle, value: true }.freeze
94
+ end
95
+ end
96
+
97
+ private
98
+
99
+ def non_empty_string(value, name)
100
+ normalized = value.to_s
101
+ raise ArgumentError, "#{name} must not be empty" if normalized.strip.empty?
102
+
103
+ normalized.freeze
104
+ end
105
+
106
+ def non_negative_integer(value, name)
107
+ return nil if value.nil?
108
+
109
+ normalized = Integer(value)
110
+ if normalized.negative? || (value.is_a?(Numeric) && value != normalized)
111
+ raise ArgumentError
112
+ end
113
+
114
+ normalized
115
+ rescue TypeError, ArgumentError, RangeError
116
+ raise ArgumentError, "#{name} must be a non-negative integer"
117
+ end
118
+
119
+ def normalize_modalities(modalities)
120
+ Array(modalities).map(&:to_sym).uniq.freeze
121
+ end
122
+
123
+ def normalize_date(value, name)
124
+ return nil if value.nil?
125
+ return value if value.is_a?(Date)
126
+ raise ArgumentError, "#{name} must be an ISO-8601 date" unless value.is_a?(String)
127
+
128
+ Date.iso8601(value)
129
+ rescue Date::Error
130
+ raise ArgumentError, "#{name} must be an ISO-8601 date"
131
+ end
132
+
133
+ def normalize_reasoning_option_name(option)
134
+ normalized = option.to_sym
135
+ normalized == :xhigh ? :max : normalized
136
+ rescue NoMethodError
137
+ raise ArgumentError, "Invalid reasoning option #{option.inspect}"
138
+ end
139
+
140
+ def canonical_positive_reasoning_value(value)
141
+ return :max if value == "xhigh"
142
+
143
+ normalized = value.to_sym
144
+ normalized if REASONING_LEVELS.include?(normalized)
145
+ end
146
+
147
+ def positive_reasoning_value?(value)
148
+ !canonical_positive_reasoning_value(value).nil?
149
+ end
150
+
151
+ def preferred_reasoning_control
152
+ controls = reasoning_controls || []
153
+ controls.find { |control| control[:type] == "effort" && control[:values].any? { |value| positive_reasoning_value?(value) } } ||
154
+ controls.find { |control| control[:type] == "budget_tokens" } ||
155
+ controls.find { |control| control[:type] == "toggle" } ||
156
+ controls.find { |control| control[:type] == "effort" }
157
+ end
158
+
159
+ def effort_for(control, canonical)
160
+ control[:values].find { |value| canonical_positive_reasoning_value(value) == canonical }
161
+ end
162
+
163
+ def budget_for(control, canonical)
164
+ minimum = round_up_to_reasoning_block(control[:min] || REASONING_BLOCK_SIZE)
165
+ maximum = [ control[:max] || DEFAULT_REASONING_BUDGET_CEILING, max_output_tokens || DEFAULT_REASONING_BUDGET_CEILING ].min
166
+ maximum = round_down_to_reasoning_block(maximum)
167
+ raise ArgumentError, "No valid reasoning budget for #{provider}/#{id}" if maximum < minimum
168
+
169
+ minimum_blocks = minimum / REASONING_BLOCK_SIZE
170
+ maximum_blocks = maximum / REASONING_BLOCK_SIZE
171
+ level_index = REASONING_LEVELS.index(canonical)
172
+ blocks = minimum_blocks + ((maximum_blocks - minimum_blocks) * level_index.to_f / (REASONING_LEVELS.length - 1)).round
173
+ blocks * REASONING_BLOCK_SIZE
174
+ end
175
+
176
+ def round_up_to_reasoning_block(value)
177
+ ((value + REASONING_BLOCK_SIZE - 1) / REASONING_BLOCK_SIZE) * REASONING_BLOCK_SIZE
178
+ end
179
+
180
+ def round_down_to_reasoning_block(value)
181
+ (value / REASONING_BLOCK_SIZE) * REASONING_BLOCK_SIZE
182
+ end
183
+
184
+ def normalize_reasoning_controls(controls)
185
+ return nil if controls.nil?
186
+ raise ArgumentError, "reasoning_controls must be an array" unless controls.is_a?(Array)
187
+
188
+ controls.map.with_index do |option, index|
189
+ raise ArgumentError, "reasoning_controls[#{index}] must be an object" unless option.is_a?(Hash)
190
+
191
+ normalize_reasoning_option(option, index)
192
+ end.freeze
193
+ end
194
+
195
+ def normalize_reasoning_option(option, index)
196
+ normalized = normalize_source_value(option)
197
+ type = normalized[:type]
198
+ unless type.is_a?(String) && !type.empty?
199
+ raise ArgumentError, "reasoning_controls[#{index}].type must be a non-empty string"
200
+ end
201
+
202
+ case type
203
+ when "effort"
204
+ values = normalized[:values]
205
+ unless values.is_a?(Array) && values.all? { |value| value.is_a?(String) }
206
+ raise ArgumentError, "reasoning_controls[#{index}].values must contain strings"
207
+ end
208
+ normalized[:values] = values.uniq.freeze
209
+ when "budget_tokens"
210
+ %i[min max].each do |boundary|
211
+ next unless normalized.key?(boundary) && !normalized[boundary].nil?
212
+
213
+ normalized[boundary] = non_negative_integer(normalized[boundary], "reasoning_controls[#{index}].#{boundary}")
214
+ end
215
+ if normalized[:min] && normalized[:max] && normalized[:max] < normalized[:min]
216
+ raise ArgumentError, "reasoning_controls[#{index}].max must not be below min"
217
+ end
218
+ end
219
+
220
+ deep_freeze(normalized)
221
+ end
222
+
223
+ def normalize_source_value(value)
224
+ case value
225
+ when String, Numeric, TrueClass, FalseClass, NilClass then value
226
+ when Array then value.map { |item| normalize_source_value(item) }
227
+ when Hash
228
+ value.each_with_object({}) do |(key, item), normalized|
229
+ unless key.is_a?(String) || key.is_a?(Symbol)
230
+ raise ArgumentError, "reasoning option keys must be strings"
231
+ end
232
+
233
+ normalized[key.to_sym] = normalize_source_value(item)
234
+ end
235
+ else
236
+ raise ArgumentError, "reasoning option attributes must contain JSON values"
237
+ end
238
+ end
239
+
240
+ def deep_freeze(value)
241
+ case value
242
+ when Hash then value.each { |key, item| deep_freeze(key); deep_freeze(item) }
243
+ when Array then value.each { |item| deep_freeze(item) }
244
+ end
245
+ value.freeze
246
+ end
247
+
248
+ def normalize_capabilities(capabilities)
249
+ capabilities.to_h.each_with_object({}) do |(name, supported), normalized|
250
+ unless supported.nil? || supported == true || supported == false
251
+ raise ArgumentError, "Capability #{name.inspect} must be true, false, or nil"
252
+ end
253
+
254
+ normalized[name.to_sym] = supported
255
+ end.freeze
256
+ end
257
+
258
+ public
259
+
260
+ class Pricing
261
+ attr_reader :input, :output, :cache_read, :cache_write, :tiers
262
+
263
+ def initialize(attributes)
264
+ attributes = attributes.to_h.transform_keys(&:to_sym)
265
+ @input = decimal(attributes.fetch(:input))
266
+ @output = decimal(attributes.fetch(:output))
267
+ @cache_read = decimal(attributes.fetch(:cache_read, 0))
268
+ @cache_write = decimal(attributes.fetch(:cache_write, 0))
269
+ @tiers = Array(attributes[:tiers]).map { |tier| Tier.new(tier) }.freeze
270
+ freeze
271
+ end
272
+
273
+ def rates_for(input_tokens)
274
+ tiers.reduce(self) do |rates, tier|
275
+ tier.input_tokens_above < input_tokens && tier.input_tokens_above > rates.threshold ? tier : rates
276
+ end
277
+ end
278
+
279
+ def threshold
280
+ -1
281
+ end
282
+
283
+ private
284
+
285
+ def decimal(value)
286
+ decimal = BigDecimal(value.to_s)
287
+ raise ArgumentError, "Pricing rates must be finite and non-negative" unless decimal.finite? && !decimal.negative?
288
+
289
+ decimal
290
+ rescue TypeError, ArgumentError
291
+ raise ArgumentError, "Pricing rates must be finite and non-negative"
292
+ end
293
+
294
+ def non_negative_integer(value, name)
295
+ normalized = Integer(value)
296
+ if normalized.negative? || (value.is_a?(Numeric) && value != normalized)
297
+ raise ArgumentError
298
+ end
299
+
300
+ normalized
301
+ rescue TypeError, ArgumentError, RangeError
302
+ raise ArgumentError, "#{name} must be a non-negative integer"
303
+ end
304
+ end
305
+
306
+ class Tier < Pricing
307
+ attr_reader :input_tokens_above
308
+
309
+ def initialize(attributes)
310
+ attributes = attributes.to_h.transform_keys(&:to_sym)
311
+ @input_tokens_above = non_negative_integer(
312
+ attributes.fetch(:input_tokens_above),
313
+ "Tier input_tokens_above"
314
+ )
315
+
316
+ super
317
+ end
318
+
319
+ def threshold
320
+ input_tokens_above
321
+ end
322
+ end
323
+ end
324
+ end
325
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LlmGateway
4
+ module Models
5
+ module Explicit
6
+ # Legacy model IDs remain here because recorded streams still use them.
7
+ DEFINITIONS = [
8
+ {
9
+ provider: "anthropic",
10
+ id: "claude-sonnet-4-20250514",
11
+ name: "Claude Sonnet 4",
12
+ source: :explicit,
13
+ context_window: 200_000,
14
+ max_output_tokens: 64_000,
15
+ input_modalities: %i[text image],
16
+ output_modalities: %i[text],
17
+ capabilities: {
18
+ text_generation: true,
19
+ tool_calling: true,
20
+ structured_output: true,
21
+ reasoning: true
22
+ },
23
+ reasoning_controls: [ { type: "budget_tokens", min: 1_024, max: 13_312 } ],
24
+ pricing: { input: "3", output: "15", cache_read: "0.3", cache_write: "3.75" }
25
+ },
26
+ {
27
+ provider: "groq",
28
+ id: "meta-llama/llama-4-scout-17b-16e-instruct",
29
+ name: "Llama 4 Scout 17B 16E",
30
+ source: :explicit,
31
+ context_window: 131_072,
32
+ max_output_tokens: 8_192,
33
+ input_modalities: %i[text image],
34
+ output_modalities: %i[text],
35
+ capabilities: {
36
+ text_generation: true,
37
+ tool_calling: true,
38
+ structured_output: true,
39
+ reasoning: false
40
+ },
41
+ pricing: { input: "0.11", output: "0.34", cache_read: "0", cache_write: "0" }
42
+ }
43
+ ].freeze
44
+ end
45
+ end
46
+ end