aireview 2.2.1 → 2.3.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +36 -0
- data/README.md +209 -79
- data/config/defaults.yml +6 -7
- data/lib/aireview/candidate_checker.rb +0 -1
- data/lib/aireview/cli.rb +91 -63
- data/lib/aireview/config.rb +42 -4
- data/lib/aireview/config_fallbacks.rb +8 -11
- data/lib/aireview/config_layers.rb +6 -4
- data/lib/aireview/config_loader.rb +31 -23
- data/lib/aireview/context_budget.rb +6 -2
- data/lib/aireview/context_builder.rb +1 -0
- data/lib/aireview/dry_run_report.rb +3 -0
- data/lib/aireview/github_client.rb +284 -0
- data/lib/aireview/jev_stage.rb +19 -2
- data/lib/aireview/llm_client.rb +8 -9
- data/lib/aireview/llm_router.rb +69 -90
- data/lib/aireview/model_candidate.rb +6 -3
- data/lib/aireview/model_pool.rb +6 -0
- data/lib/aireview/model_state.rb +5 -17
- data/lib/aireview/mr_parser.rb +44 -6
- data/lib/aireview/platform.rb +99 -0
- data/lib/aireview/publisher.rb +8 -7
- data/lib/aireview/review_comment_formatter.rb +158 -0
- data/lib/aireview/review_marker.rb +5 -1
- data/lib/aireview/review_pipeline.rb +24 -13
- data/lib/aireview/review_renderer.rb +33 -12
- data/lib/aireview/reviewer.rb +4 -5
- data/lib/aireview/stage_chains.rb +4 -0
- data/lib/aireview/version.rb +1 -1
- data/lib/aireview.rb +2 -1
- metadata +13 -14
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
require 'json'
|
|
3
|
+
require 'uri'
|
|
4
|
+
require_relative 'errors'
|
|
5
|
+
require_relative 'review_comment_formatter'
|
|
6
|
+
require_relative 'utils'
|
|
7
|
+
|
|
8
|
+
module Aireview
|
|
9
|
+
# GitHub pull requests in the shapes the rest of the review knows from
|
|
10
|
+
# GitLab: the merge request hash, change hashes with old/new paths and a
|
|
11
|
+
# diff, notes with an author id. Method names follow GitlabClient, so the
|
|
12
|
+
# CLI and the publisher do not care which platform answers.
|
|
13
|
+
class GithubClient
|
|
14
|
+
# A 403: for /user it means the token has no user to read.
|
|
15
|
+
class ForbiddenError < ApiError; end
|
|
16
|
+
|
|
17
|
+
OPEN_TIMEOUT = 10
|
|
18
|
+
READ_TIMEOUT = 30
|
|
19
|
+
PER_PAGE = 100
|
|
20
|
+
# The files endpoint stops at 3000 files (30 pages); comments have no
|
|
21
|
+
# such cap. Past the limit the walk fails instead of stopping: with an
|
|
22
|
+
# incomplete comment list the publisher would not find its own review
|
|
23
|
+
# and would post a second one.
|
|
24
|
+
PAGE_LIMIT = 100
|
|
25
|
+
REDIRECT_LIMIT = 5
|
|
26
|
+
REDIRECT_STATUSES = [301, 302, 307, 308].freeze
|
|
27
|
+
# GitHub limits issue and PR comment bodies to 65,536 characters.
|
|
28
|
+
MAX_COMMENT_LENGTH = 65_536
|
|
29
|
+
API_VERSION = '2022-11-28'
|
|
30
|
+
GITHUB_COM_API = 'https://api.github.com'
|
|
31
|
+
|
|
32
|
+
# github.com has its API on a separate host, GitHub Enterprise under /api/v3.
|
|
33
|
+
def self.api_url_for(base_url)
|
|
34
|
+
host = URI.parse(base_url).host
|
|
35
|
+
%w[github.com www.github.com].include?(host) ? GITHUB_COM_API : "#{base_url}/api/v3"
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def initialize(api_url:, token:, review_author: nil, logger: Logger.new($stderr), connection: nil)
|
|
39
|
+
require 'faraday'
|
|
40
|
+
|
|
41
|
+
raise ConfigError, 'GitHub API URL is required' if Aireview::Utils.blank?(api_url)
|
|
42
|
+
raise ConfigError, 'GitHub token is required' if Aireview::Utils.blank?(token)
|
|
43
|
+
|
|
44
|
+
@logger = logger
|
|
45
|
+
@token = token
|
|
46
|
+
@review_author = review_author
|
|
47
|
+
@base_uri = URI.parse("#{api_url.chomp('/')}/")
|
|
48
|
+
@connection = connection || build_connection(api_url)
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# diff_refs carries the merge base — the same meaning as GitLab's
|
|
52
|
+
# diff_refs.base_sha. The PR diff is taken against it, and it can move
|
|
53
|
+
# while the head stays: when the base branch takes in part of the PR's
|
|
54
|
+
# history. The compare goes against the base branch as it is now, not
|
|
55
|
+
# against base.sha.
|
|
56
|
+
def fetch_merge_request(repo, number)
|
|
57
|
+
pull = get_json("repos/#{repo}/pulls/#{number}")
|
|
58
|
+
validate_pull!(pull)
|
|
59
|
+
head_sha = pull.dig('head', 'sha')
|
|
60
|
+
base_ref = pull.dig('base', 'ref')
|
|
61
|
+
compare = get_json("repos/#{repo}/compare/#{escape_ref(base_ref)}...#{head_sha}", per_page: 1)
|
|
62
|
+
merge_base = compare.dig('merge_base_commit', 'sha') if compare.is_a?(Hash)
|
|
63
|
+
raise ApiError, 'GitHub did not return the merge base of the pull request' if Aireview::Utils.blank?(merge_base)
|
|
64
|
+
|
|
65
|
+
{
|
|
66
|
+
'title' => pull['title'],
|
|
67
|
+
'description' => pull['body'],
|
|
68
|
+
'author' => {'name' => pull.dig('user', 'login')},
|
|
69
|
+
'source_branch' => pull.dig('head', 'ref'),
|
|
70
|
+
'target_branch' => base_ref,
|
|
71
|
+
'sha' => head_sha,
|
|
72
|
+
'diff_refs' => {'base_sha' => merge_base, 'head_sha' => head_sha},
|
|
73
|
+
'changed_files' => pull['changed_files']
|
|
74
|
+
}
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def fetch_merge_request_changes(repo, number)
|
|
78
|
+
get_pages("repos/#{repo}/pulls/#{number}/files", 'files').map { |file| change(file) }
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# PR conversation comments are issue comments in the GitHub API. They
|
|
82
|
+
# come oldest first; the publisher expects newest first, like GitLab
|
|
83
|
+
# notes sorted by creation time descending.
|
|
84
|
+
def fetch_merge_request_notes(repo, number)
|
|
85
|
+
get_pages("repos/#{repo}/issues/#{number}/comments", 'comments').reverse.map do |comment|
|
|
86
|
+
{
|
|
87
|
+
'id' => comment['id'],
|
|
88
|
+
'body' => comment['body'],
|
|
89
|
+
'author' => {'id' => comment.dig('user', 'login')},
|
|
90
|
+
'system' => false
|
|
91
|
+
}
|
|
92
|
+
end
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def post_merge_request_note(repo, number, body)
|
|
96
|
+
send_json(:post, "repos/#{repo}/issues/#{number}/comments", body: fit_comment_body(body))
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def update_merge_request_note(repo, _number, comment_id, body)
|
|
100
|
+
send_json(:patch, "repos/#{repo}/issues/comments/#{comment_id}", body: fit_comment_body(body))
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# The login is the author id the publisher matches comments by. A token
|
|
104
|
+
# that cannot read /user (the Actions GITHUB_TOKEN, a GitHub App
|
|
105
|
+
# installation token) needs the login given explicitly: inside Actions a
|
|
106
|
+
# workflow may comment as its own App, so github-actions[bot] is not
|
|
107
|
+
# guessed — a wrong guess would miss the review and post a duplicate.
|
|
108
|
+
def fetch_current_user
|
|
109
|
+
return {'id' => @review_author} if Aireview::Utils.present?(@review_author)
|
|
110
|
+
|
|
111
|
+
{'id' => get_json('user')['login']}
|
|
112
|
+
rescue ForbiddenError => e
|
|
113
|
+
raise ApiError, 'GitHub token cannot read its user; set GITHUB_REVIEW_AUTHOR to the login that posts ' \
|
|
114
|
+
"the comments (github-actions[bot] for the Actions GITHUB_TOKEN). #{e.message}"
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
private
|
|
118
|
+
|
|
119
|
+
def validate_pull!(pull)
|
|
120
|
+
valid = pull.is_a?(Hash) && %w[head base].all? { |side| pull[side].is_a?(Hash) } &&
|
|
121
|
+
Aireview::Utils.present?(pull.dig('head', 'sha')) && Aireview::Utils.present?(pull.dig('base', 'ref'))
|
|
122
|
+
raise ApiError, 'GitHub API returned an invalid pull request payload' unless valid
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
# A file without a patch is a binary or a diff too large for GitHub; it
|
|
126
|
+
# has no mode fields either. Only a rename without changes explains an
|
|
127
|
+
# empty diff, everything else counts as unavailable — the report must not
|
|
128
|
+
# claim that a binary was reviewed. An empty new file ends up there too.
|
|
129
|
+
# Note: Git does not track line counts for binary files, so a binary file
|
|
130
|
+
# renamed with byte modifications also reports changes == 0 without a patch;
|
|
131
|
+
# without a base blob comparison this is indistinguishable from a pure rename.
|
|
132
|
+
def change(file)
|
|
133
|
+
status = file['status']
|
|
134
|
+
patch = file['patch'].to_s
|
|
135
|
+
pure_rename = status == 'renamed' && file['changes'].to_i.zero?
|
|
136
|
+
{
|
|
137
|
+
'old_path' => file['previous_filename'] || file['filename'],
|
|
138
|
+
'new_path' => file['filename'],
|
|
139
|
+
'diff' => patch,
|
|
140
|
+
'new_file' => status == 'added',
|
|
141
|
+
'deleted_file' => status == 'removed',
|
|
142
|
+
'renamed_file' => status == 'renamed',
|
|
143
|
+
'too_large' => patch.empty? && !pure_rename
|
|
144
|
+
}
|
|
145
|
+
end
|
|
146
|
+
|
|
147
|
+
# Pages are followed by the Link header, not counted: GitHub decides
|
|
148
|
+
# where the list ends.
|
|
149
|
+
def get_pages(path, what)
|
|
150
|
+
items = []
|
|
151
|
+
url = path
|
|
152
|
+
params = {per_page: PER_PAGE}
|
|
153
|
+
|
|
154
|
+
PAGE_LIMIT.times do
|
|
155
|
+
response = request(:get, url, params: params)
|
|
156
|
+
batch = parse_json(response)
|
|
157
|
+
raise ApiError, "GitHub API returned an invalid #{what} list" unless batch.is_a?(Array)
|
|
158
|
+
|
|
159
|
+
items.concat(batch)
|
|
160
|
+
url = next_page(response)
|
|
161
|
+
return items unless url
|
|
162
|
+
|
|
163
|
+
params = {}
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
raise ApiError, "Pull request has more than #{PAGE_LIMIT * PER_PAGE} #{what}"
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def next_page(response)
|
|
170
|
+
link = response.headers['link'].to_s
|
|
171
|
+
link.split(',').each do |part|
|
|
172
|
+
match = /<([^>]+)>\s*;\s*rel="next"/.match(part)
|
|
173
|
+
return match[1] if match
|
|
174
|
+
end
|
|
175
|
+
nil
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
# Branch names may hold characters that mean something in a URL; the
|
|
179
|
+
# slashes of a branch name stay, GitHub reads them as part of the ref.
|
|
180
|
+
def escape_ref(ref)
|
|
181
|
+
ref.split('/').map { |part| URI.encode_www_form_component(part).gsub('+', '%20') }.join('/')
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def build_connection(api_url)
|
|
185
|
+
Faraday.new(url: "#{api_url.chomp('/')}/") do |builder|
|
|
186
|
+
builder.request :json
|
|
187
|
+
builder.options.open_timeout = OPEN_TIMEOUT
|
|
188
|
+
builder.options.timeout = READ_TIMEOUT
|
|
189
|
+
builder.adapter Faraday.default_adapter
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def get_json(path, params = {})
|
|
194
|
+
parse_json(request(:get, path, params: params))
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
def request(method, path, params: nil, body: nil)
|
|
198
|
+
current_path = path
|
|
199
|
+
current_params = params
|
|
200
|
+
redirects = 0
|
|
201
|
+
|
|
202
|
+
loop do
|
|
203
|
+
response = execute_request(method, current_path, current_params, body)
|
|
204
|
+
return response unless REDIRECT_STATUSES.include?(response.status.to_i)
|
|
205
|
+
|
|
206
|
+
redirects += 1
|
|
207
|
+
raise ApiError, 'Too many redirects from GitHub API' if redirects > REDIRECT_LIMIT
|
|
208
|
+
|
|
209
|
+
current_path, current_params = follow_redirect(response, current_path, current_params)
|
|
210
|
+
end
|
|
211
|
+
rescue Faraday::Error => e
|
|
212
|
+
raise ApiError, "GitHub API request failed: #{e.message}"
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
def send_json(method, path, body)
|
|
216
|
+
parse_json(request(method, path, body: body))
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
def execute_request(method, path, params, body)
|
|
220
|
+
if body.nil?
|
|
221
|
+
@connection.public_send(method, path, params, headers)
|
|
222
|
+
else
|
|
223
|
+
@connection.public_send(method, path) do |request|
|
|
224
|
+
request.headers.update(headers)
|
|
225
|
+
request.body = JSON.generate(body)
|
|
226
|
+
end
|
|
227
|
+
end
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
def parse_json(response)
|
|
231
|
+
status = response.status.to_i
|
|
232
|
+
body = response.body.to_s
|
|
233
|
+
|
|
234
|
+
return JSON.parse(body) if status.between?(200, 299)
|
|
235
|
+
raise ForbiddenError, "GitHub API error #{status}: #{body}" if status == 403
|
|
236
|
+
|
|
237
|
+
raise ApiError, "GitHub API error #{status}: #{body}"
|
|
238
|
+
rescue JSON::ParserError
|
|
239
|
+
raise ApiError, "GitHub API returned invalid JSON: #{body}"
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def headers
|
|
243
|
+
{
|
|
244
|
+
'Accept' => 'application/vnd.github+json',
|
|
245
|
+
'Authorization' => "Bearer #{@token}",
|
|
246
|
+
'Content-Type' => 'application/json',
|
|
247
|
+
'X-GitHub-Api-Version' => API_VERSION
|
|
248
|
+
}
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
# Follow same-origin redirects (e.g. repo rename or transfer) without
|
|
252
|
+
# leaking authorization tokens to external hosts.
|
|
253
|
+
def follow_redirect(response, current_path, current_params)
|
|
254
|
+
location = response.headers['location'].to_s
|
|
255
|
+
if Aireview::Utils.blank?(location)
|
|
256
|
+
raise ApiError, "GitHub API redirected with status #{response.status} without a Location header"
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
current_url = URI.join(@base_uri.to_s, current_path)
|
|
260
|
+
target = URI.join(current_url.to_s, location)
|
|
261
|
+
unless same_origin?(target, @base_uri)
|
|
262
|
+
raise ApiError, "Refusing redirect from #{@base_uri.host} to #{target.host}"
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
[target.to_s, target.query ? {} : current_params]
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
def same_origin?(target, base)
|
|
269
|
+
target.scheme == base.scheme && target.host == base.host && target.port == base.port
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
# When an enormous review overflows GitHub's 65,536-char limit, findings
|
|
273
|
+
# and summary stay intact; only the files list in the not-reviewed block
|
|
274
|
+
# (or the summary if oversized) is shortened with a note. Never drops
|
|
275
|
+
# findings or result: a corrupted review must not be saved to GitHub.
|
|
276
|
+
def fit_comment_body(body, limit = MAX_COMMENT_LENGTH)
|
|
277
|
+
fitted = ReviewCommentFormatter.fit(body, limit: limit)
|
|
278
|
+
return fitted if fitted
|
|
279
|
+
|
|
280
|
+
raise ApiError, "Review comment exceeds GitHub limit of #{limit} characters " \
|
|
281
|
+
'and cannot be shortened without dropping findings'
|
|
282
|
+
end
|
|
283
|
+
end
|
|
284
|
+
end
|
data/lib/aireview/jev_stage.rb
CHANGED
|
@@ -13,7 +13,7 @@ module Aireview
|
|
|
13
13
|
class JevStage
|
|
14
14
|
# The report line: :jev (Jev decided everything), :jev_partial (some
|
|
15
15
|
# went to the LLM), :jev_failed (the LLM decided everything).
|
|
16
|
-
Outcome = Struct.new(:accepted, :note, keyword_init: true)
|
|
16
|
+
Outcome = Struct.new(:accepted, :note, :model, keyword_init: true)
|
|
17
17
|
|
|
18
18
|
def initialize(config:, critic:, logger: Logger.new($stderr))
|
|
19
19
|
@config = config
|
|
@@ -37,11 +37,28 @@ module Aireview
|
|
|
37
37
|
accepted = drop_duplicates(in_generate_order(accepted, candidates), result.answers)
|
|
38
38
|
@logger.info("Pipeline critique pass completed with #{accepted.size} kept candidate(s) (engine=jev, " \
|
|
39
39
|
"model=#{result.model}, requests=#{result.requests})")
|
|
40
|
-
Outcome.new(accepted: accepted, note: unverifiable
|
|
40
|
+
Outcome.new(accepted: accepted, note: outcome_note(unverifiable, candidates, result.model),
|
|
41
|
+
model: outcome_model(result.model))
|
|
41
42
|
end
|
|
42
43
|
|
|
43
44
|
private
|
|
44
45
|
|
|
46
|
+
def outcome_note(unverifiable, candidates, answered_model)
|
|
47
|
+
if unverifiable.empty? || fail?
|
|
48
|
+
Aireview::Utils.present?(answered_model) ? :jev : nil
|
|
49
|
+
elsif unverifiable.size == candidates.size && Aireview::Utils.blank?(answered_model)
|
|
50
|
+
:jev_failed
|
|
51
|
+
else
|
|
52
|
+
:jev_partial
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def outcome_model(answered_model)
|
|
57
|
+
return "jev/#{answered_model}" if Aireview::Utils.present?(answered_model)
|
|
58
|
+
|
|
59
|
+
:critique_no_verdicts if fail?
|
|
60
|
+
end
|
|
61
|
+
|
|
45
62
|
def fail?
|
|
46
63
|
@config.jev_fallback == 'fail'
|
|
47
64
|
end
|
data/lib/aireview/llm_client.rb
CHANGED
|
@@ -35,10 +35,10 @@ module Aireview
|
|
|
35
35
|
|
|
36
36
|
# Returns the RubyLLM answer; read it with LlmClient.content. A request
|
|
37
37
|
# error is re-raised as is — LlmFailure classifies it.
|
|
38
|
-
def request(prompt, candidate:, key:, timeout
|
|
38
|
+
def request(prompt, candidate:, key:, timeout:)
|
|
39
39
|
stage = prompt.stage.to_s
|
|
40
40
|
model = candidate.model
|
|
41
|
-
chat = prepare(prompt, candidate: candidate, key: key
|
|
41
|
+
chat = prepare(prompt, candidate: candidate, key: key)
|
|
42
42
|
@logger.info("LLM #{stage} request started (model=#{model}, temperature=#{chat.temperature || 'model default'})")
|
|
43
43
|
response = Timeout.timeout(timeout) { chat.ask(prompt.user) }
|
|
44
44
|
@logger.info("LLM #{stage} request completed (model=#{model}#{token_counts(response)})")
|
|
@@ -51,10 +51,10 @@ module Aireview
|
|
|
51
51
|
# The request as it will go, without sending it: the chat with the model,
|
|
52
52
|
# key, schema, instructions and temperature set. chat.render builds it —
|
|
53
53
|
# that is how the specs check the real request without the network.
|
|
54
|
-
def prepare(prompt, candidate:, key
|
|
54
|
+
def prepare(prompt, candidate:, key:)
|
|
55
55
|
load_ruby_llm
|
|
56
56
|
stage = prompt.stage.to_s
|
|
57
|
-
chat = build_chat(context: context(stage, candidate, key
|
|
57
|
+
chat = build_chat(context: context(stage, candidate, key), stage: stage,
|
|
58
58
|
model: candidate.model, provider: candidate.provider)
|
|
59
59
|
chat = configure_reasoning(chat: chat, model: candidate.model, provider: candidate.provider)
|
|
60
60
|
.with_temperature(temperature_for(chat, prompt, candidate))
|
|
@@ -126,11 +126,10 @@ module Aireview
|
|
|
126
126
|
context.chat(model: model, provider: provider.to_sym, assume_model_exists: true)
|
|
127
127
|
end
|
|
128
128
|
|
|
129
|
-
# A RubyLLM context per stage
|
|
130
|
-
# of your own)
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
@contexts[[stage, candidate.key_source, key_index]] ||= build_context(candidate, key)
|
|
129
|
+
# A RubyLLM context per stage and key source (a provider's API or a server
|
|
130
|
+
# of your own): isolated from the global config.
|
|
131
|
+
def context(stage, candidate, key)
|
|
132
|
+
@contexts[[stage, candidate.key_source]] ||= build_context(candidate, key)
|
|
134
133
|
end
|
|
135
134
|
|
|
136
135
|
def build_context(candidate, api_key)
|
data/lib/aireview/llm_router.rb
CHANGED
|
@@ -1,25 +1,22 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
|
-
require 'set'
|
|
3
2
|
require_relative 'errors'
|
|
4
3
|
require_relative 'llm_failure'
|
|
5
4
|
require_relative 'model_state'
|
|
6
5
|
|
|
7
6
|
module Aireview
|
|
8
|
-
# Walks the models
|
|
9
|
-
#
|
|
10
|
-
#
|
|
11
|
-
#
|
|
12
|
-
#
|
|
13
|
-
# expired. Two limits: the time budget of the run and the number of
|
|
14
|
-
# requests sent per model per stage (ModelState).
|
|
7
|
+
# Walks the models of a stage. An overloaded model goes into quarantine and
|
|
8
|
+
# is skipped until it expires; once the chain has been walked, the walk goes
|
|
9
|
+
# round again over the models whose quarantine has expired. Two limits: the
|
|
10
|
+
# time budget of the run and the number of requests sent per model per stage
|
|
11
|
+
# (ModelState).
|
|
15
12
|
class LlmRouter # rubocop:disable Metrics/ClassLength
|
|
16
|
-
Route = Struct.new(:candidate, :candidate_index, :key,
|
|
13
|
+
Route = Struct.new(:candidate, :candidate_index, :key, keyword_init: true) do
|
|
17
14
|
def fallback?
|
|
18
15
|
candidate_index.positive?
|
|
19
16
|
end
|
|
20
17
|
|
|
21
18
|
def to_s
|
|
22
|
-
|
|
19
|
+
candidate.to_s
|
|
23
20
|
end
|
|
24
21
|
end
|
|
25
22
|
|
|
@@ -33,8 +30,6 @@ module Aireview
|
|
|
33
30
|
end
|
|
34
31
|
|
|
35
32
|
Slot = Struct.new(:candidate, :index)
|
|
36
|
-
# The key the next model of the same provider continues from.
|
|
37
|
-
Carry = Struct.new(:key_source, :key_index)
|
|
38
33
|
Delay = Struct.new(:seconds, :source)
|
|
39
34
|
|
|
40
35
|
SWITCH_HINT = 'Try again later or switch model via --generate-model/--critique-model.'
|
|
@@ -74,30 +69,27 @@ module Aireview
|
|
|
74
69
|
|
|
75
70
|
# The block receives a route and a request timeout, makes the request and
|
|
76
71
|
# returns the answer. An error raised by the block is classified, then
|
|
77
|
-
# comes a retry, another
|
|
78
|
-
#
|
|
79
|
-
#
|
|
80
|
-
#
|
|
72
|
+
# comes a retry, another model, or ApiError once the routes are
|
|
73
|
+
# exhausted. pinned — only the model that answered last in this stage
|
|
74
|
+
# (the JSON repair): its failure is RouteExhaustedError, and the stage
|
|
75
|
+
# restarts on another model.
|
|
81
76
|
def call(stage:, request_chars:, pinned: false, &request)
|
|
82
77
|
@deadline ||= now + @config.llm_time_budget
|
|
83
78
|
visits = []
|
|
84
79
|
noted = Set.new
|
|
85
|
-
carry = nil
|
|
86
80
|
loop do
|
|
87
81
|
slots = available_slots(stage, request_chars, pinned, visits, noted)
|
|
88
82
|
slot = slots.empty? ? nil : ready_slot(stage, slots, visits)
|
|
89
83
|
raise exhausted_error(stage, visits, pinned) unless slot
|
|
90
84
|
|
|
91
|
-
status, value = try_candidate(stage, slot, visits,
|
|
85
|
+
status, value = try_candidate(stage, slot, visits, &request)
|
|
92
86
|
return value if status == :ok
|
|
93
|
-
|
|
94
|
-
carry = value
|
|
95
87
|
end
|
|
96
88
|
end
|
|
97
89
|
|
|
98
|
-
# Stages answered by
|
|
99
|
-
def
|
|
100
|
-
@used.
|
|
90
|
+
# Stages answered by any model, for the report.
|
|
91
|
+
def models
|
|
92
|
+
@used.transform_values { |route| route.candidate.display_name }
|
|
101
93
|
end
|
|
102
94
|
|
|
103
95
|
# The model that answered last in the stage and its place in the chain.
|
|
@@ -162,7 +154,7 @@ module Aireview
|
|
|
162
154
|
end
|
|
163
155
|
|
|
164
156
|
def bare_route(candidate, index)
|
|
165
|
-
Route.new(candidate: candidate, candidate_index: index
|
|
157
|
+
Route.new(candidate: candidate, candidate_index: index)
|
|
166
158
|
end
|
|
167
159
|
|
|
168
160
|
def skip_reason(stage, candidate, request_chars)
|
|
@@ -179,7 +171,7 @@ module Aireview
|
|
|
179
171
|
ensure_time_left!(stage, bare_route(slots.first.candidate, slots.first.index), visits)
|
|
180
172
|
moment = now
|
|
181
173
|
ready = slots.find { |slot| state(slot.candidate).quarantine_left(moment) <= 0 }
|
|
182
|
-
return ready if ready
|
|
174
|
+
return stronger_critic(stage, slots, ready, moment) || ready if ready
|
|
183
175
|
|
|
184
176
|
slot = slots.min_by { |item| state(item.candidate).quarantine_left(moment) }
|
|
185
177
|
wait = state(slot.candidate).quarantine_left(moment)
|
|
@@ -195,48 +187,50 @@ module Aireview
|
|
|
195
187
|
slot
|
|
196
188
|
end
|
|
197
189
|
|
|
198
|
-
#
|
|
199
|
-
#
|
|
200
|
-
#
|
|
201
|
-
#
|
|
202
|
-
#
|
|
203
|
-
#
|
|
204
|
-
#
|
|
205
|
-
#
|
|
206
|
-
def
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
#
|
|
224
|
-
#
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
key_index: key_index, key_count: keys.size)
|
|
231
|
-
end
|
|
232
|
-
routes.rotate(start_key(stage, slot, carry))
|
|
190
|
+
# A critique by the model that answered in Generate is the last resort
|
|
191
|
+
# of a ranked pool. When a model the critique chain puts before it is
|
|
192
|
+
# only quarantined and its release fits into the budget, wait for it:
|
|
193
|
+
# otherwise an overload in Generate turns the critique into a self-check
|
|
194
|
+
# (Generate and Critique on one model). Only the chain's own preference
|
|
195
|
+
# counts, so an explicit critique.start stays first; own chains and
|
|
196
|
+
# rank: any are not ranked and keep their order. Models out until the
|
|
197
|
+
# end of the run are not in slots. nil — nobody to wait for.
|
|
198
|
+
def stronger_critic(stage, slots, ready, moment)
|
|
199
|
+
generate = self_critique(stage, ready)
|
|
200
|
+
return nil unless generate
|
|
201
|
+
|
|
202
|
+
stronger = slots.select { |item| item.index < ready.index }
|
|
203
|
+
slot = stronger.min_by { |item| state(item.candidate).quarantine_left(moment) }
|
|
204
|
+
wait = slot && state(slot.candidate).quarantine_left(moment)
|
|
205
|
+
# The wait is optional: a full request must still fit after it, or a
|
|
206
|
+
# critique by the available model beats a failed review.
|
|
207
|
+
return nil if wait.nil? || wait + @config.llm_timeout.to_f > remaining_time
|
|
208
|
+
|
|
209
|
+
@logger.warn(format('LLM critique: waiting %<wait>.0fs for %<model>s instead of critiquing with %<same>s, ' \
|
|
210
|
+
'the model that answered in generate', wait: wait, model: slot.candidate, same: generate))
|
|
211
|
+
pause(wait)
|
|
212
|
+
slot
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
# The Generate model when it is the only one ready for a ranked
|
|
216
|
+
# Critique; else nil.
|
|
217
|
+
def self_critique(stage, ready)
|
|
218
|
+
generate = @used['generate']&.candidate
|
|
219
|
+
return nil unless stage == 'critique' && generate&.same_model?(ready.candidate)
|
|
220
|
+
|
|
221
|
+
generate if @routing.ranked_critique?(generate)
|
|
233
222
|
end
|
|
234
223
|
|
|
235
|
-
|
|
236
|
-
|
|
224
|
+
# Every visit either sends a request or excludes the model: otherwise the
|
|
225
|
+
# walk round the pool would never stop.
|
|
226
|
+
def try_candidate(stage, slot, visits, &)
|
|
227
|
+
key = @config.candidate_api_keys(slot.candidate).first
|
|
228
|
+
route = Route.new(candidate: slot.candidate, candidate_index: slot.index, key: key)
|
|
229
|
+
log_switch(stage, route, visits)
|
|
230
|
+
status, response = try_route(stage, route, visits, &)
|
|
231
|
+
return [:ok, remember(stage, route, response)] if status == :ok
|
|
237
232
|
|
|
238
|
-
|
|
239
|
-
cursor_candidate == slot.index ? cursor_key : 0
|
|
233
|
+
[:next_model, nil]
|
|
240
234
|
end
|
|
241
235
|
|
|
242
236
|
# A visit to a route: requests until an answer, a retry or a refusal. try
|
|
@@ -272,7 +266,7 @@ module Aireview
|
|
|
272
266
|
if decision == :retry
|
|
273
267
|
return :retry if requests_left?(stage, route) && waited_before_retry?(stage, route, delay)
|
|
274
268
|
|
|
275
|
-
decision =
|
|
269
|
+
decision = :next_model
|
|
276
270
|
end
|
|
277
271
|
record_failure(stage, route, kind, decision, error)
|
|
278
272
|
visits << Visit.new(route: route, kind: kind, tries: try, error: error)
|
|
@@ -286,29 +280,23 @@ module Aireview
|
|
|
286
280
|
false
|
|
287
281
|
end
|
|
288
282
|
|
|
289
|
-
# :retry with a delay, :
|
|
283
|
+
# :retry with a delay, :next_model or :fail.
|
|
290
284
|
def decide(kind, try, error)
|
|
291
285
|
case kind
|
|
292
286
|
when :fatal then [:fail]
|
|
293
|
-
when :unavailable then [:next_model]
|
|
294
|
-
when :
|
|
295
|
-
when :rate_limit then try == 1 ? [:retry, rate_limit_delay(error)] : [:next_key]
|
|
287
|
+
when :unavailable, :daily_quota then [:next_model]
|
|
288
|
+
when :rate_limit then try == 1 ? [:retry, rate_limit_delay(error)] : [:next_model]
|
|
296
289
|
else try == 1 ? [:retry, short_delay] : [:next_model]
|
|
297
290
|
end
|
|
298
291
|
end
|
|
299
292
|
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
# A daily quota marks the key of the model, a missing model marks the
|
|
305
|
-
# model for the whole run, an overload or a timeout quarantines it, a
|
|
306
|
-
# per-minute limit quarantines it for the provider's hint (the next key
|
|
307
|
-
# is tried at once; the quarantine only affects the next visit).
|
|
293
|
+
# A daily quota or a missing model excludes the model for the whole run,
|
|
294
|
+
# an overload or a timeout quarantines it, a per-minute limit quarantines
|
|
295
|
+
# it for the provider's hint.
|
|
308
296
|
def record_failure(stage, route, kind, decision, error)
|
|
309
297
|
model = state(route.candidate)
|
|
310
298
|
case kind
|
|
311
|
-
when :daily_quota then model.
|
|
299
|
+
when :daily_quota then model.exclude('daily quota exhausted earlier in this run')
|
|
312
300
|
when :unavailable then model.exclude('model unavailable earlier in this run')
|
|
313
301
|
when :rate_limit then quarantine(stage, route, rate_limit_delay(error).seconds)
|
|
314
302
|
when :overloaded, :timeout then quarantine(stage, route, @config.overloaded_quarantine) if decision == :next_model
|
|
@@ -368,18 +356,9 @@ module Aireview
|
|
|
368
356
|
[@config.llm_timeout.to_f, remaining_time].min
|
|
369
357
|
end
|
|
370
358
|
|
|
371
|
-
|
|
372
|
-
return false unless state(route.candidate).key_exhausted?(route.key_index)
|
|
373
|
-
|
|
374
|
-
@logger.info("LLM #{stage}: skipping #{route}, daily quota exhausted earlier in this run")
|
|
375
|
-
visits << Visit.new(route: route, note: 'daily quota exhausted earlier in this run')
|
|
376
|
-
true
|
|
377
|
-
end
|
|
378
|
-
|
|
379
|
-
# A model that answered is not overloaded, whichever key answered: a
|
|
380
|
-
# quarantine set through another key of the same model is lifted.
|
|
359
|
+
# A model that answered is not overloaded: its quarantine is lifted.
|
|
381
360
|
def remember(stage, route, response)
|
|
382
|
-
@cursor[stage] =
|
|
361
|
+
@cursor[stage] = route.candidate_index
|
|
383
362
|
@used[stage] = route
|
|
384
363
|
state(route.candidate).lift_quarantine
|
|
385
364
|
response
|
|
@@ -396,7 +375,7 @@ module Aireview
|
|
|
396
375
|
# The next request of the stage (the JSON repair, for instance) starts
|
|
397
376
|
# from the model that answered; the rest stay in reserve after it.
|
|
398
377
|
def ordered_chain(stage)
|
|
399
|
-
start_candidate
|
|
378
|
+
start_candidate = @cursor.fetch(stage, 0)
|
|
400
379
|
chain_for(stage).each_with_index.to_a.rotate(start_candidate)
|
|
401
380
|
end
|
|
402
381
|
|
|
@@ -14,16 +14,19 @@ module Aireview
|
|
|
14
14
|
# The address is part of the name, scheme included: two servers with the
|
|
15
15
|
# same model (http and https ones too) are two models for quarantine,
|
|
16
16
|
# reserves and the review key.
|
|
17
|
+
def display_name
|
|
18
|
+
"#{provider}/#{model}"
|
|
19
|
+
end
|
|
20
|
+
|
|
17
21
|
def to_s
|
|
18
|
-
|
|
19
|
-
api_base ? "#{name}@#{api_base.chomp('/')}" : name
|
|
22
|
+
api_base ? "#{display_name}@#{api_base.chomp('/')}" : display_name
|
|
20
23
|
end
|
|
21
24
|
|
|
22
25
|
# Every way a start or a CLI override may name this model: bare,
|
|
23
26
|
# "provider/name", or the full name with the address. One list for the
|
|
24
27
|
# config check and for picking the model, so they cannot disagree.
|
|
25
28
|
def names
|
|
26
|
-
[model.to_s,
|
|
29
|
+
[model.to_s, display_name, to_s].uniq
|
|
27
30
|
end
|
|
28
31
|
|
|
29
32
|
def same_model?(other)
|
data/lib/aireview/model_pool.rb
CHANGED
|
@@ -122,6 +122,12 @@ module Aireview
|
|
|
122
122
|
chain(stage).first
|
|
123
123
|
end
|
|
124
124
|
|
|
125
|
+
# Critique is ranked against the model that answered in Generate: both
|
|
126
|
+
# stages walk the pool and the rank is not_below_generate.
|
|
127
|
+
def ranked_critique?(after)
|
|
128
|
+
rank_applies?(after)
|
|
129
|
+
end
|
|
130
|
+
|
|
125
131
|
def weaker?(critique_candidate, generate_candidate)
|
|
126
132
|
return false unless pool_member?(critique_candidate) && pool_member?(generate_candidate)
|
|
127
133
|
|