aireview 0.2.1 → 2.0.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.
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
  require_relative 'utils'
3
3
  require_relative 'errors'
4
+ require_relative 'stages'
4
5
  require_relative 'secret_scrubber'
5
6
  require_relative 'diff_fetcher'
6
7
  require_relative 'context_budget'
@@ -15,15 +16,14 @@ module Aireview
15
16
  }.freeze
16
17
  CHANGES_HEADER = "Changes:\n"
17
18
  CANDIDATES_HEADER = "\n\nCandidates JSON from Generate:\n"
18
- # Резерв под кандидатов в промпте критика: три кандидата по ~1 500
19
- # символов. Оценка, не гарантия; фактический размер проверяется перед
20
- # отправкой.
19
+ # Room for the candidates in the Critique prompt: three candidates of
20
+ # ~1,500 characters. An estimate, not a guarantee; the actual size is
21
+ # checked before sending.
21
22
  CANDIDATES_RESERVE_CHARS = 4_500
22
- STAGES = %i[generate critique].freeze
23
23
 
24
- # Контекст одного прогона: обе стадии получают одинаковые MR, Jira и дифф,
25
- # усечённые один раз под самую тесную из стадий.
26
- Context = Struct.new(:user_prompt, :coverage, :sizes, keyword_init: true)
24
+ # The context of one run: both stages get the same MR, Jira and diff,
25
+ # truncated once for the tightest of the stages.
26
+ Context = Struct.new(:user_prompt, :diff_text, :coverage, :sizes, keyword_init: true)
27
27
 
28
28
  def initialize(config:, logger: Logger.new($stderr))
29
29
  @config = config
@@ -49,20 +49,20 @@ module Aireview
49
49
 
50
50
  sizes = context_sizes(fixed: fixed, packed: packed, budget: budget, diff_budget: diff_budget, critique: critique)
51
51
  log_sizes(sizes)
52
- Context.new(user_prompt: fixed + packed.text, coverage: coverage, sizes: sizes)
52
+ Context.new(user_prompt: fixed + packed.text, diff_text: packed.text, coverage: coverage, sizes: sizes)
53
53
  end
54
54
 
55
55
  def build_generate_prompt(context)
56
- check_stage_size!(:generate, system_prompt(:generate), context.user_prompt)
56
+ check_stage_size!('generate', system_prompt('generate'), context.user_prompt)
57
57
  end
58
58
 
59
59
  def build_critique_prompt(context, candidates_json:)
60
60
  user = "#{context.user_prompt}#{CANDIDATES_HEADER}#{scrub_text(candidates_json)}"
61
- check_stage_size!(:critique, system_prompt(:critique), user)
61
+ check_stage_size!('critique', system_prompt('critique'), user)
62
62
  end
63
63
 
64
64
  def system_prompt(stage)
65
- template = stage.to_sym == :critique ? CRITIQUE_PROMPT_TEMPLATE : GENERATE_PROMPT_TEMPLATE
65
+ template = stage.to_s == 'critique' ? CRITIQUE_PROMPT_TEMPLATE : GENERATE_PROMPT_TEMPLATE
66
66
  extras = []
67
67
  if Aireview::Utils.present?(@config.review_instructions)
68
68
  extras << "Additional project instructions:\n#{scrub_text(@config.review_instructions.strip)}"
@@ -72,10 +72,11 @@ module Aireview
72
72
  [template, *extras].join("\n\n")
73
73
  end
74
74
 
75
- # Проверка перед отправкой: если кандидаты вышли за резерв и запрос не
76
- # помещается, это ошибка, а не повод молча резать контекст, который
77
- # генератор уже видел.
75
+ # A check before sending: when the candidates exceed the reserve and the
76
+ # request does not fit, that is an error, not a reason to silently cut
77
+ # the context Generate has already seen.
78
78
  def check_stage_size!(stage, system, user)
79
+ stage = stage.to_s
79
80
  limit = @config.max_prompt_chars(stage)
80
81
  total = system.length + user.length
81
82
  if total > limit
@@ -89,10 +90,10 @@ module Aireview
89
90
 
90
91
  private
91
92
 
92
- # Минимум по стадиям: контекст один на прогон, поэтому он должен
93
- # помещаться в каждую из них вместе с её системным промптом и резервом.
93
+ # The minimum over the stages: the context is one per run, so it must fit
94
+ # into each of them together with its system prompt and reserve.
94
95
  def context_budget(critique:)
95
- stages = critique ? STAGES : [:generate]
96
+ stages = critique ? STAGES : ['generate']
96
97
  budgets = stages.to_h { |stage| [stage, stage_budget(stage)] }
97
98
  stage, budget = budgets.min_by { |_, value| value }
98
99
  return budget if budget.positive?
@@ -104,7 +105,7 @@ module Aireview
104
105
  end
105
106
 
106
107
  def stage_budget(stage)
107
- reserve = stage == :critique ? CANDIDATES_RESERVE_CHARS + CANDIDATES_HEADER.length : 0
108
+ reserve = stage == 'critique' ? CANDIDATES_RESERVE_CHARS + CANDIDATES_HEADER.length : 0
108
109
  @config.max_prompt_chars(stage) - system_prompt(stage).length - reserve
109
110
  end
110
111
 
@@ -152,7 +153,7 @@ module Aireview
152
153
  end
153
154
 
154
155
  def context_sizes(fixed:, packed:, budget:, diff_budget:, critique:)
155
- stages = critique ? STAGES : [:generate]
156
+ stages = critique ? STAGES : ['generate']
156
157
  {
157
158
  context_budget: budget,
158
159
  diff_budget: diff_budget,
@@ -7,13 +7,14 @@ module Aireview
7
7
  DIFF_UNAVAILABLE = '[diff not available]'
8
8
  BINARY_DIFF = /\ABinary files .* differ/
9
9
 
10
- # Один файл из ответа GitLab: заголовок, хунки и что с ним можно делать.
10
+ # One file from the GitLab answer: the header, the hunks and what can be done with it.
11
11
  # kind:
12
- # :text есть хунки, код можно проверить;
13
- # :no_text_changes переименование, смена режима, пустой файл: проверять
14
- # нечего;
15
- # :unavailable GitLab не отдал дифф (too_large, бинарник, пустой
16
- # дифф без причины): код есть, но проверить его не удалось.
12
+ # :text there are hunks, the code can be checked;
13
+ # :no_text_changes a rename, a mode change, an empty file: nothing to
14
+ # check;
15
+ # :unavailable GitLab did not return the diff (too_large, a binary,
16
+ # an empty diff without a reason): the code exists,
17
+ # but could not be checked.
17
18
  class Entry
18
19
  attr_reader :path, :kind, :header, :hunks
19
20
 
@@ -49,9 +50,9 @@ module Aireview
49
50
 
50
51
  private
51
52
 
52
- # Пустой дифф без объяснимой причины (переименование, смена режима,
53
- # пустой новый или удалённый файл) считаем недоступным: код есть, но
54
- # GitLab его не отдал.
53
+ # An empty diff without an explainable reason (a rename, a mode change,
54
+ # an empty new or deleted file) counts as unavailable: the code exists,
55
+ # but GitLab did not return it.
55
56
  def classify(change, diff)
56
57
  return :unavailable if change['too_large']
57
58
  return :unavailable if diff.match?(BINARY_DIFF)
@@ -67,8 +68,8 @@ module Aireview
67
68
  modes.none?(&:nil?) && modes.uniq.size == 2
68
69
  end
69
70
 
70
- # Хунки режем по заголовкам @@; текст до первого @@ (или дифф без них,
71
- # например заглушка про секретный файл) считается одним хунком.
71
+ # Hunks are split at the @@ headers; the text before the first @@ (or a
72
+ # diff without any, such as the secret-file placeholder) counts as one hunk.
72
73
  def split_hunks(diff)
73
74
  diff = "#{diff}\n" unless diff.end_with?("\n")
74
75
  pieces = diff.split(/^(?=@@ )/)
@@ -1,20 +1,14 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Aireview
4
- # Вывод --dry-run: настройки, сводка контекста и промпты обеих стадий.
4
+ # The --dry-run output: settings, the context summary and the prompts of both stages.
5
5
  class DryRunReport
6
6
  def initialize(out)
7
7
  @out = out
8
8
  end
9
9
 
10
10
  def render(dry_run)
11
- @out.puts('=== LLM SETTINGS ===')
12
- @out.puts("Generate: #{dry_run[:generate_model]} temperature=#{dry_run[:generate_temperature]}")
13
- if dry_run[:critique_prompt]
14
- @out.puts("Critique: #{dry_run[:critique_model]} temperature=#{dry_run[:critique_temperature]}")
15
- else
16
- @out.puts('Critique: disabled')
17
- end
11
+ render_settings(dry_run)
18
12
  @out.puts
19
13
  @out.puts('=== CONTEXT ===')
20
14
  render_context_sizes(dry_run[:sizes])
@@ -37,6 +31,41 @@ module Aireview
37
31
 
38
32
  private
39
33
 
34
+ def render_settings(dry_run)
35
+ @out.puts('=== LLM SETTINGS ===')
36
+ render_config_paths(dry_run[:config_paths])
37
+ render_stage(dry_run, :generate)
38
+ if dry_run[:critique_prompt]
39
+ render_stage(dry_run, :critique)
40
+ else
41
+ @out.puts('Critique: disabled')
42
+ end
43
+ @out.puts("Critique rule: #{dry_run[:critique_rule]}") if dry_run[:critique_rule]
44
+ render_reserves(dry_run)
45
+ list('warnings', dry_run[:warnings], separator: "\n ")
46
+ end
47
+
48
+ def render_config_paths(paths)
49
+ return if paths.nil? || paths.empty?
50
+
51
+ @out.puts("Config: #{paths.map { |name, path| "#{name} #{path}" }.join(', ')}")
52
+ end
53
+
54
+ # The source of every setting is the layer it came from: built-in, image
55
+ # defaults, .aireview.yml, env or cli.
56
+ def render_stage(dry_run, stage)
57
+ sources = dry_run.dig(:sources, stage) || {}
58
+ @out.puts("#{stage.capitalize}: #{dry_run[:"#{stage}_model"]} " \
59
+ "temperature=#{dry_run[:"#{stage}_temperature"]}#{origin(sources, :model, :provider)}")
60
+ fallbacks = dry_run[:"#{stage}_fallbacks"]
61
+ list('fallbacks', fallbacks, separator: ' -> ', suffix: origin(sources, :fallbacks))
62
+ end
63
+
64
+ def origin(sources, *keys)
65
+ parts = keys.filter_map { |key| "#{key} from #{sources[key]}" if sources[key] }
66
+ parts.empty? ? '' : " (#{parts.join(', ')})"
67
+ end
68
+
40
69
  def render_context_sizes(sizes)
41
70
  @out.puts("Sections: #{sizes[:sections]} chars, diff: #{sizes[:diff]} chars " \
42
71
  "(budget #{sizes[:diff_budget]}, hunks #{sizes[:hunks_shown]}/#{sizes[:hunks_total]})")
@@ -57,8 +86,18 @@ module Aireview
57
86
  list('diff not available', coverage.files_unavailable)
58
87
  end
59
88
 
60
- def list(title, items)
61
- @out.puts(" #{title}: #{items.join(', ')}") unless items.empty?
89
+ def render_reserves(dry_run)
90
+ keys = Array(dry_run[:api_keys]).map { |provider, count| "#{provider} #{count}" }
91
+ @out.puts("API keys: #{keys.join(', ')}") unless keys.empty?
92
+ return unless dry_run[:time_budget]
93
+
94
+ quarantine = dry_run[:overloaded_quarantine]
95
+ @out.puts("Time budget: #{dry_run[:time_budget]}s#{", overloaded quarantine: #{quarantine}s" if quarantine}")
96
+ end
97
+
98
+ def list(title, items, separator: ', ', suffix: '')
99
+ items = Array(items)
100
+ @out.puts(" #{title}: #{items.join(separator)}#{suffix}") unless items.empty?
62
101
  end
63
102
  end
64
103
  end
@@ -3,7 +3,15 @@ module Aireview
3
3
  class Error < StandardError; end
4
4
  class ConfigError < Error; end
5
5
  class ParseError < Error; end
6
+ # Repairing invalid JSON is impossible: the model that answered is out of
7
+ # attempts or quarantined with no budget to wait. For the pipeline it is
8
+ # the same as an invalid result — the stage restarts on another model.
9
+ class RepairImpossibleError < ParseError; end
6
10
  class ApiError < Error; end
11
+ # A pinned route (the JSON repair by the same model) could not answer: out
12
+ # of attempts, excluded, or quarantined with no budget to wait. Not fatal
13
+ # for the run — the stage restarts on another model.
14
+ class RouteExhaustedError < ApiError; end
7
15
  class ContextBudgetError < Error; end
8
16
  class HelpRequested < Error; end
9
17
  end
@@ -35,8 +35,9 @@ module Aireview
35
35
  get_json('user')
36
36
  end
37
37
 
38
- # Retry создаёт новый job в том же pipeline. Старые попытки видны только
39
- # с include_retried; один лишь новый CI_JOB_ID бывает и после обычного push.
38
+ # A Retry creates a new job in the same pipeline. Earlier attempts are
39
+ # visible only with include_retried; a new CI_JOB_ID alone happens after an
40
+ # ordinary push too.
40
41
  def retried_job?(project_id, job_id)
41
42
  current = get_json("projects/#{project_id}/jobs/#{job_id}")
42
43
  validate_retry_job!(current, pipeline: true)
@@ -54,13 +55,13 @@ module Aireview
54
55
  raise ApiError, 'Too many pipeline jobs to determine whether this job is a retry'
55
56
  end
56
57
 
57
- # Заметки отдаются страницами и сортируются по времени создания, а
58
- # обновление комментария в этом порядке его не поднимает: на длинном MR
59
- # своё ревью оказывается далеко не на первой странице. Обрывать обход молча
60
- # нельзя — по неполному списку ревью решит, что заметки нет, и создаст
61
- # вторую, поэтому упираемся в предел с ошибкой. Порядок задаётся явно: от
62
- # него зависит, какую из старых заметок без метки подхватит ревью, и
63
- # полагаться тут на дефолт API не стоит.
58
+ # Notes come in pages sorted by creation time, and updating a comment
59
+ # does not move it up in that order: on a long MR our review is far from
60
+ # the first page. Stopping the walk silently is not an option — with an
61
+ # incomplete list the review would decide the note is missing and create
62
+ # a second one, so the limit fails with an error. The order is explicit:
63
+ # it decides which old unmarked note the review picks up, and the API
64
+ # default is not to be relied on here.
64
65
  def fetch_merge_request_notes(project_id, iid)
65
66
  notes = []
66
67
  page = 1
@@ -0,0 +1,113 @@
1
+ # frozen_string_literal: true
2
+ require 'timeout'
3
+ require_relative 'errors'
4
+ require_relative 'utils'
5
+
6
+ module Aireview
7
+ # One request to one model with one key through RubyLLM. Retries, keys and
8
+ # reserves belong to LlmRouter: the built-in RubyLLM/Faraday retries (3 by
9
+ # default) are off, otherwise every router attempt would turn into four
10
+ # HTTP requests and burn quota before the error reaches the classifier.
11
+ class LlmClient
12
+ # What a stage sends to the model; the same for every route of the stage.
13
+ Prompt = Struct.new(:stage, :system, :user, :temperature, :schema, keyword_init: true) do
14
+ def chars
15
+ system.length + user.length
16
+ end
17
+ end
18
+
19
+ def initialize(config:, logger: Logger.new($stderr))
20
+ @config = config
21
+ @logger = logger
22
+ @contexts = {}
23
+ end
24
+
25
+ # Returns the RubyLLM answer (content is text or a structure by the
26
+ # schema). A request error is re-raised as is — LlmFailure classifies it.
27
+ def request(prompt, candidate:, key:, timeout:, key_index: 0)
28
+ load_ruby_llm
29
+ stage = prompt.stage.to_s
30
+ model = candidate.model
31
+ @logger.info("LLM #{stage} request started (model=#{model}, temperature=#{prompt.temperature})")
32
+ chat = build_chat(context: context(stage, candidate.provider, key, key_index), stage: stage,
33
+ model: model, provider: candidate.provider)
34
+ chat = configure_reasoning(chat: chat, model: model, provider: candidate.provider)
35
+ .with_temperature(prompt.temperature.to_f)
36
+ .with_schema(prompt.schema)
37
+ chat.with_instructions(prompt.system)
38
+ response = Timeout.timeout(timeout) { chat.ask(prompt.user) }
39
+ @logger.info("LLM #{stage} request completed (model=#{model})")
40
+ response
41
+ rescue Timeout::Error
42
+ @logger.warn("LLM #{stage} request timed out after #{timeout.round} seconds (model=#{model})")
43
+ raise
44
+ end
45
+
46
+ private
47
+
48
+ def load_ruby_llm
49
+ require 'ruby_llm'
50
+ rescue LoadError => e
51
+ @logger.error("LLM setup failed: #{e.message}")
52
+ raise ConfigError, "Missing dependency: #{e.message}"
53
+ end
54
+
55
+ def configure_reasoning(chat:, model:, provider:)
56
+ return chat unless provider == 'ollama' && model.start_with?('gpt-oss:')
57
+
58
+ chat.with_thinking(effort: :low)
59
+ end
60
+
61
+ def build_chat(context:, stage:, model:, provider:)
62
+ context.chat(model: model, provider: provider.to_sym)
63
+ rescue RubyLLM::ModelNotFoundError
64
+ @logger.warn(
65
+ "LLM #{stage}: model not found in RubyLLM registry; " \
66
+ "using fallback with incomplete model metadata " \
67
+ "(model=#{model}, provider=#{provider})"
68
+ )
69
+ context.chat(model: model, provider: provider.to_sym, assume_model_exists: true)
70
+ end
71
+
72
+ # A RubyLLM context per stage, provider and key index: switching the key
73
+ # is another context, not an edit of the global config.
74
+ def context(stage, provider, key, key_index)
75
+ @contexts[[stage, provider, key_index]] ||= build_context(provider.to_s, key)
76
+ end
77
+
78
+ def build_context(provider, api_key)
79
+ RubyLLM.context do |ruby_config|
80
+ configure_http_proxy(ruby_config)
81
+ ruby_config.request_timeout = @config.llm_timeout.to_f
82
+ ruby_config.max_retries = 0
83
+ configure_provider(ruby_config, provider, api_key)
84
+ end
85
+ end
86
+
87
+ def configure_http_proxy(ruby_config)
88
+ return unless Aireview::Utils.present?(@config.llm_http_proxy)
89
+
90
+ ruby_config.http_proxy = @config.llm_http_proxy
91
+ end
92
+
93
+ def configure_provider(ruby_config, provider, api_key)
94
+ case provider
95
+ when 'gemini', 'openai', 'openrouter'
96
+ configure_remote_provider(ruby_config, provider, api_key)
97
+ when 'anthropic'
98
+ ruby_config.anthropic_api_key = api_key
99
+ when 'ollama'
100
+ ruby_config.ollama_api_base = @config.ollama_api_base
101
+ else
102
+ raise ConfigError, "Unsupported LLM provider: #{provider.inspect}"
103
+ end
104
+ end
105
+
106
+ def configure_remote_provider(ruby_config, provider, api_key)
107
+ ruby_config.public_send("#{provider}_api_key=", api_key)
108
+ return unless Aireview::Utils.present?(@config.llm_api_base)
109
+
110
+ ruby_config.public_send("#{provider}_api_base=", @config.llm_api_base)
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,107 @@
1
+ # frozen_string_literal: true
2
+ require 'json'
3
+ require 'timeout'
4
+
5
+ module Aireview
6
+ # Classifies an LLM request error. Answers only "what is it"; the decision
7
+ # to retry, switch the key or the model belongs to LlmRouter.
8
+ #
9
+ # :daily_quota — the project's daily quota for the model, retries are useless;
10
+ # :rate_limit — a per-minute limit, passes after the hinted time;
11
+ # :overloaded — 503 / "high demand" on the model;
12
+ # :timeout — no answer for longer than LLM_TIMEOUT;
13
+ # :unavailable — the provider has no such model: retired, a typo, not pulled into Ollama;
14
+ # :fatal — an API error that reserves do not cure;
15
+ # :unhandled — not a provider error, re-raised as is.
16
+ module LlmFailure
17
+ KINDS = %i[daily_quota rate_limit overloaded timeout unavailable fatal unhandled].freeze
18
+ # Only by the provider's text about the model: a bare 404 is also what a
19
+ # wrong LLM_API_BASE or proxy answers, and the next model will not help.
20
+ # Ollama: `model 'x' not found` (through /v1) and `model "x" not found,
21
+ # try pulling it first` (older versions and /api).
22
+ UNAVAILABLE_MODEL_TEXT = Regexp.union(
23
+ /\bmodels?\/[\w.:-]+ is not found\b/i,
24
+ /\bis not supported for generateContent\b/i,
25
+ /\bmodel ['"][^'"]+['"] not found\b/i
26
+ )
27
+ QUOTA_FAILURE_TYPE = 'type.googleapis.com/google.rpc.QuotaFailure'
28
+ DAILY_QUOTA_ID = /PerDay/i
29
+ DAILY_QUOTA_TEXT = /\bper\s+day\b|\bdaily\b/i
30
+ RETRY_AFTER = /retry\s+(?:in|after)\s+(\d+(?:\.\d+)?)\s*(?:s|sec|secs|second|seconds)\b/i
31
+
32
+ module_function
33
+
34
+ # Quota details are checked before the exception class: RubyLLM turns a
35
+ # 429 mentioning input_token into ContextLengthExceededError, although
36
+ # it is an exhausted token quota, not an oversized request.
37
+ def classify(error)
38
+ return :timeout if transport_timeout?(error)
39
+ return :unhandled unless ruby_llm_error?(error)
40
+
41
+ quota_kind(error) || model_kind(error) || (overloaded?(error) ? :overloaded : :fatal)
42
+ end
43
+
44
+ def model_kind(error)
45
+ :unavailable if error.message.to_s.match?(UNAVAILABLE_MODEL_TEXT)
46
+ end
47
+
48
+ # The outer Timeout.timeout and Faraday's transport timeouts: the latter
49
+ # inherit neither Timeout::Error nor RubyLLM::Error.
50
+ def transport_timeout?(error)
51
+ return true if error.is_a?(Timeout::Error) || error.is_a?(Errno::ETIMEDOUT)
52
+
53
+ defined?(Faraday::TimeoutError) && error.is_a?(Faraday::TimeoutError)
54
+ end
55
+
56
+ def overloaded?(error)
57
+ error.is_a?(RubyLLM::ServiceUnavailableError) || error.is_a?(RubyLLM::OverloadedError)
58
+ end
59
+
60
+ def ruby_llm_error?(error)
61
+ defined?(RubyLLM::Error) && error.is_a?(RubyLLM::Error)
62
+ end
63
+
64
+ # Google puts the kind of quota into QuotaFailure.violations[].quotaId
65
+ # (GenerateRequestsPerDay… / …PerMinute…). The free_tier_requests metric
66
+ # is the same for both, it cannot tell them apart. The message text is
67
+ # the fallback signal when there is no response body.
68
+ def quota_kind(error)
69
+ ids = quota_ids(error)
70
+ return daily_quota_id?(ids) ? :daily_quota : :rate_limit unless ids.empty?
71
+ return unless error.is_a?(RubyLLM::RateLimitError)
72
+
73
+ error.message.to_s.match?(DAILY_QUOTA_TEXT) ? :daily_quota : :rate_limit
74
+ end
75
+
76
+ def daily_quota_id?(ids)
77
+ ids.any? { |id| id.match?(DAILY_QUOTA_ID) }
78
+ end
79
+
80
+ def quota_ids(error)
81
+ body = response_body(error)
82
+ details = body.is_a?(Hash) ? Array(body.dig('error', 'details')) : []
83
+ details.flat_map do |detail|
84
+ next [] unless detail.is_a?(Hash) && detail['@type'] == QUOTA_FAILURE_TYPE
85
+
86
+ Array(detail['violations']).filter_map { |violation| violation['quotaId'] if violation.is_a?(Hash) }
87
+ end
88
+ end
89
+
90
+ def response_body(error)
91
+ body = error.respond_to?(:response) && error.response.respond_to?(:body) ? error.response.body : nil
92
+ return body unless body.is_a?(String)
93
+
94
+ JSON.parse(body)
95
+ rescue JSON::ParserError
96
+ nil
97
+ end
98
+
99
+ def retry_after_seconds(message)
100
+ match = message.to_s.match(RETRY_AFTER)
101
+ match[1].to_f if match
102
+ end
103
+
104
+ private_class_method :model_kind, :transport_timeout?, :overloaded?, :ruby_llm_error?, :quota_kind,
105
+ :daily_quota_id?, :quota_ids, :response_body
106
+ end
107
+ end