judgelint 0.1.10 → 0.2.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 +20 -0
- data/README.md +9 -11
- data/exe/judgelint +9 -9
- metadata +3 -25
- data/lib/judgelint/cache.rb +0 -344
- data/lib/judgelint/changes.rb +0 -87
- data/lib/judgelint/cli.rb +0 -252
- data/lib/judgelint/client.rb +0 -210
- data/lib/judgelint/config.rb +0 -162
- data/lib/judgelint/errors.rb +0 -14
- data/lib/judgelint/glob.rb +0 -77
- data/lib/judgelint/paint.rb +0 -46
- data/lib/judgelint/pool.rb +0 -44
- data/lib/judgelint/protocol.rb +0 -122
- data/lib/judgelint/providers.rb +0 -78
- data/lib/judgelint/question.rb +0 -159
- data/lib/judgelint/reporter.rb +0 -219
- data/lib/judgelint/rule.rb +0 -167
- data/lib/judgelint/runner.rb +0 -481
- data/lib/judgelint/scaffold.rb +0 -66
- data/lib/judgelint/source.rb +0 -105
- data/lib/judgelint/spec.rb +0 -240
- data/lib/judgelint/usage.rb +0 -53
- data/lib/judgelint/verdict.rb +0 -71
- data/lib/judgelint/version.rb +0 -5
- data/lib/judgelint.rb +0 -60
data/lib/judgelint/cli.rb
DELETED
|
@@ -1,252 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
module Judgelint
|
|
4
|
-
# Command line entry point. Exit codes: 0 clean, 1 violations (or missed
|
|
5
|
-
# examples for `test`), 2 usage or configuration error. Everything that can
|
|
6
|
-
# be checked is checked before the first paid request.
|
|
7
|
-
class CLI
|
|
8
|
-
COMMANDS = %w[check test rules providers init].freeze
|
|
9
|
-
|
|
10
|
-
HELP = <<~TEXT
|
|
11
|
-
Usage: judgelint [command] [options] [paths...]
|
|
12
|
-
|
|
13
|
-
Checks code against the conventions in your specs, like a CONVENTIONS.md
|
|
14
|
-
of bullets. For each file and each rule, it asks a decision model (Jev on
|
|
15
|
-
TypeSafe by default) whether the code breaks it.
|
|
16
|
-
|
|
17
|
-
Commands:
|
|
18
|
-
check [paths...] Check the files the specs govern, or these (default).
|
|
19
|
-
test [rule ids...] Judge each rule's examples (.judgelint/examples/<id>/pass
|
|
20
|
-
and fail) and report what the model gets wrong.
|
|
21
|
-
rules List the rules and how many files each governs.
|
|
22
|
-
providers List the decision-model providers judgelint knows.
|
|
23
|
-
init Write a CONVENTIONS.md to start from, with examples.
|
|
24
|
-
|
|
25
|
-
Options:
|
|
26
|
-
--base REF Check only what changed since the merge base with REF,
|
|
27
|
-
uncommitted work included
|
|
28
|
-
--pr --base the pull request's base branch, from CI variables
|
|
29
|
-
or the gh CLI
|
|
30
|
-
-f, --format FORMAT text, json, github (Actions annotations), or sarif
|
|
31
|
-
-m, --model MODEL Ask this model instead of the config's: a provider from
|
|
32
|
-
`judgelint providers`, optionally :model (cloudflare:clef)
|
|
33
|
-
-c, --config PATH Config file (default .judgelint.yml)
|
|
34
|
-
--no-cache Ask the models even when an answer is cached
|
|
35
|
-
-y, --yes Run even past max_cost_usd
|
|
36
|
-
-v, --version Print the version
|
|
37
|
-
-h, --help Print this help
|
|
38
|
-
|
|
39
|
-
Exit status: 0 clean, 1 violations or missed examples, 2 usage or config error.
|
|
40
|
-
TEXT
|
|
41
|
-
|
|
42
|
-
def initialize(argv, out: $stdout, err: $stderr)
|
|
43
|
-
@argv = argv.dup
|
|
44
|
-
@out = out
|
|
45
|
-
@err = err
|
|
46
|
-
@format = "text"
|
|
47
|
-
@config_path = nil
|
|
48
|
-
@base = nil
|
|
49
|
-
@pr = false
|
|
50
|
-
@yes = false
|
|
51
|
-
@overrides = {}
|
|
52
|
-
@usage = nil
|
|
53
|
-
@no_cache = false
|
|
54
|
-
@paint = Paint.for(out)
|
|
55
|
-
@err_paint = Paint.for(err)
|
|
56
|
-
end
|
|
57
|
-
|
|
58
|
-
def run
|
|
59
|
-
command = COMMANDS.include?(@argv.first) ? @argv.shift : "check"
|
|
60
|
-
@argv = parse_options(@argv)
|
|
61
|
-
return 0 if @done
|
|
62
|
-
|
|
63
|
-
case command
|
|
64
|
-
when "check" then check
|
|
65
|
-
when "test" then test
|
|
66
|
-
when "rules" then list_rules
|
|
67
|
-
when "providers" then list_providers
|
|
68
|
-
when "init" then init
|
|
69
|
-
end
|
|
70
|
-
rescue UsageError => e
|
|
71
|
-
@err.puts "#{@err_paint.call('judgelint:', Paint::BOLD_RED)} #{e.message}"
|
|
72
|
-
@err.puts @err_paint.call("Run `judgelint --help` for usage.", Paint::DIM)
|
|
73
|
-
2
|
|
74
|
-
rescue Error => e
|
|
75
|
-
@err.puts "#{@err_paint.call('judgelint:', Paint::BOLD_RED)} #{e.message}"
|
|
76
|
-
# Requests that succeeded before the failure are still billed.
|
|
77
|
-
cost_line if @usage && @usage.requests.positive?
|
|
78
|
-
2
|
|
79
|
-
end
|
|
80
|
-
|
|
81
|
-
private
|
|
82
|
-
|
|
83
|
-
# Spinel can't compile OptionParser, so the few options are parsed here.
|
|
84
|
-
VALUE_OPTIONS = {
|
|
85
|
-
"-c" => "config", "--config" => "config", "-f" => "format", "--format" => "format", "--base" => "base",
|
|
86
|
-
"-m" => "models", "--model" => "models"
|
|
87
|
-
}.freeze
|
|
88
|
-
|
|
89
|
-
def parse_options(argv)
|
|
90
|
-
rest = []
|
|
91
|
-
until argv.empty?
|
|
92
|
-
arg = argv.shift
|
|
93
|
-
name, inline = arg.start_with?("--") ? arg.split("=", 2) : [arg, nil]
|
|
94
|
-
if arg == "--"
|
|
95
|
-
rest.concat(argv)
|
|
96
|
-
argv = []
|
|
97
|
-
elsif VALUE_OPTIONS.key?(name)
|
|
98
|
-
value = inline || argv.shift
|
|
99
|
-
raise UsageError, "#{name} needs a value" if value.nil?
|
|
100
|
-
|
|
101
|
-
set_option(VALUE_OPTIONS.fetch(name), value)
|
|
102
|
-
elsif arg == "--no-cache"
|
|
103
|
-
@no_cache = true
|
|
104
|
-
elsif arg == "--pr"
|
|
105
|
-
@pr = true
|
|
106
|
-
elsif %w[-y --yes].include?(arg)
|
|
107
|
-
@yes = true
|
|
108
|
-
elsif %w[-v --version -h --help].include?(arg)
|
|
109
|
-
@out.puts(%w[-v --version].include?(arg) ? "judgelint #{VERSION}" : HELP)
|
|
110
|
-
@done = true
|
|
111
|
-
elsif arg.start_with?("-") && arg != "-"
|
|
112
|
-
raise UsageError, "unknown option #{arg}"
|
|
113
|
-
else
|
|
114
|
-
rest << arg
|
|
115
|
-
end
|
|
116
|
-
end
|
|
117
|
-
rest
|
|
118
|
-
end
|
|
119
|
-
|
|
120
|
-
def set_option(key, value)
|
|
121
|
-
case key
|
|
122
|
-
when "config" then @config_path = value
|
|
123
|
-
when "base" then @base = value
|
|
124
|
-
when "format"
|
|
125
|
-
raise UsageError, "--format is #{Reporter::FORMATS.join(', ')}, not #{value}" unless Reporter::FORMATS.include?(value)
|
|
126
|
-
|
|
127
|
-
@format = value
|
|
128
|
-
else @overrides[key] = value
|
|
129
|
-
end
|
|
130
|
-
end
|
|
131
|
-
|
|
132
|
-
def check
|
|
133
|
-
config, rules = load_rules
|
|
134
|
-
raise UsageError, "--base and --pr don't go together" if @base && @pr
|
|
135
|
-
|
|
136
|
-
base = @pr ? Changes.pr_base : @base
|
|
137
|
-
changes = base ? Changes.since(base) : nil
|
|
138
|
-
paths = check_paths(rules, changes).reject { |path| Glob.match_any?(config.ignore, path) }
|
|
139
|
-
directories = check_directories(rules).reject { |dir| Glob.match_any?(config.ignore, dir) }
|
|
140
|
-
units = paths.size + directories.size
|
|
141
|
-
runner = runner(config, rules)
|
|
142
|
-
jobs = runner.plan(paths, directories: directories, changes: changes)
|
|
143
|
-
runner.check_keys(jobs)
|
|
144
|
-
guard_cost(config, runner, jobs)
|
|
145
|
-
verdicts = runner.execute(jobs).flatten
|
|
146
|
-
Reporter.new(@out, format: @format, paint: @paint).check(verdicts, config: config, file_count: units, usage: @usage)
|
|
147
|
-
cost_line
|
|
148
|
-
verdicts.any?(&:failing?) ? 1 : 0
|
|
149
|
-
end
|
|
150
|
-
|
|
151
|
-
def check_paths(rules, changes)
|
|
152
|
-
if !@argv.empty?
|
|
153
|
-
paths = Glob.expand_arguments(@argv)
|
|
154
|
-
missing = paths.reject { |path| File.file?(path) }
|
|
155
|
-
raise ConfigError, "No such file: #{missing.join(', ')}" unless missing.empty?
|
|
156
|
-
|
|
157
|
-
paths = paths.select { |path| changes.key?(path) } if changes
|
|
158
|
-
elsif changes
|
|
159
|
-
paths = changes.keys.sort.select { |path| File.file?(path) }
|
|
160
|
-
else
|
|
161
|
-
paths = Glob.files(rules.flat_map(&:paths))
|
|
162
|
-
end
|
|
163
|
-
buffer = String.new(capacity: 8000)
|
|
164
|
-
paths.select { |path| rules.any? { |rule| !rule.directory? && rule.applies_to?(path) } }.reject { |path| Glob.binary?(path, buffer) }
|
|
165
|
-
end
|
|
166
|
-
|
|
167
|
-
# The directories directory rules govern; with paths named, those the
|
|
168
|
-
# paths are in or are. With a change, the runner keeps those it touched.
|
|
169
|
-
def check_directories(rules)
|
|
170
|
-
directories = rules.select(&:directory?).flat_map(&:directories).uniq.sort
|
|
171
|
-
return directories if @argv.empty?
|
|
172
|
-
|
|
173
|
-
named = @argv.map { |arg| arg.delete_prefix("./").delete_suffix("/") }
|
|
174
|
-
directories.select { |dir| named.any? { |path| path == dir || path.start_with?("#{dir}/") || dir.start_with?("#{path}/") } }
|
|
175
|
-
end
|
|
176
|
-
|
|
177
|
-
def test
|
|
178
|
-
config, rules = load_rules
|
|
179
|
-
unless @argv.empty?
|
|
180
|
-
unknown = @argv - rules.map(&:id)
|
|
181
|
-
raise ConfigError, "Unknown rules: #{unknown.join(', ')}" unless unknown.empty?
|
|
182
|
-
|
|
183
|
-
rules = rules.select { |rule| @argv.include?(rule.id) }
|
|
184
|
-
end
|
|
185
|
-
|
|
186
|
-
runner = runner(config, rules)
|
|
187
|
-
jobs = runner.plan_examples
|
|
188
|
-
untested = runner.untested
|
|
189
|
-
raise ConfigError, "No rule has examples yet. Add some under #{rules.first.examples_dir}/{pass,fail}/" if jobs.empty?
|
|
190
|
-
|
|
191
|
-
@err.puts "#{untested.size} #{untested.size == 1 ? 'rule has' : 'rules have'} no examples: #{untested.map(&:id).join(', ')}" unless untested.empty?
|
|
192
|
-
runner.check_keys(jobs)
|
|
193
|
-
guard_cost(config, runner, jobs)
|
|
194
|
-
examples = runner.execute(jobs).flatten
|
|
195
|
-
Reporter.new(@out, format: @format, paint: @paint).fixtures(examples, usage: @usage)
|
|
196
|
-
cost_line
|
|
197
|
-
examples.all?(&:correct?) ? 0 : 1
|
|
198
|
-
end
|
|
199
|
-
|
|
200
|
-
# Prices the planned requests and refuses a run over max_cost_usd.
|
|
201
|
-
def guard_cost(config, runner, jobs)
|
|
202
|
-
estimate = runner.estimated_cost(jobs)
|
|
203
|
-
return if estimate.nil? || estimate <= config.max_cost_usd || @yes
|
|
204
|
-
|
|
205
|
-
raise ConfigError, format("This run would send %d requests, about %s input tokens ($%.2f), over max_cost_usd " \
|
|
206
|
-
"($%.2f). Pass --yes to run it anyway.", runner.request_count(jobs),
|
|
207
|
-
Usage.delimit(runner.estimated_tokens(jobs)), estimate, config.max_cost_usd)
|
|
208
|
-
end
|
|
209
|
-
|
|
210
|
-
# What the run cost, and which models answered.
|
|
211
|
-
def cost_line
|
|
212
|
-
@err.puts @err_paint.call("#{@usage.line}, #{@models}", Paint::DIM)
|
|
213
|
-
end
|
|
214
|
-
|
|
215
|
-
def list_rules
|
|
216
|
-
_config, rules = load_rules
|
|
217
|
-
rules.each do |rule|
|
|
218
|
-
count = rule.directory? ? "#{rule.directories.size} dirs" : "#{Glob.files(rule.paths).count { |path| rule.applies_to?(path) }} files"
|
|
219
|
-
@out.puts format("%-24s %-8s %10s %s", rule.id, rule.severity, count, rule.question || rule.message)
|
|
220
|
-
end
|
|
221
|
-
0
|
|
222
|
-
end
|
|
223
|
-
|
|
224
|
-
def list_providers
|
|
225
|
-
PROVIDERS.each do |name, preset|
|
|
226
|
-
model = preset["model"] || "(you choose)"
|
|
227
|
-
key = preset["api_key_env"] || "no key"
|
|
228
|
-
@out.puts format("%-13s %-28s %-22s %s", name, model, key, preset["api_base"] || "(your endpoint)")
|
|
229
|
-
@out.puts " needs #{preset['needs']}" if preset["needs"]
|
|
230
|
-
end
|
|
231
|
-
0
|
|
232
|
-
end
|
|
233
|
-
|
|
234
|
-
def init
|
|
235
|
-
Scaffold.write(".", @out)
|
|
236
|
-
@err.puts "Next: set TYPESAFE_API_KEY, then run `judgelint test` to see the examples judged."
|
|
237
|
-
0
|
|
238
|
-
end
|
|
239
|
-
|
|
240
|
-
def load_rules
|
|
241
|
-
config = Config.load(path: @config_path, overrides: @overrides)
|
|
242
|
-
[config, Spec.discover(rules_dir: Config::RULES_DIR, default_threshold: config.threshold, ignore: config.ignore)]
|
|
243
|
-
end
|
|
244
|
-
|
|
245
|
-
def runner(config, rules)
|
|
246
|
-
@usage = Usage.new
|
|
247
|
-
@models = config.label
|
|
248
|
-
clients = config.models.map { |endpoint| Client.new(endpoint, usage: @usage) }
|
|
249
|
-
Runner.new(config: config, rules: rules, clients: clients, cache: Cache.new(@no_cache ? nil : Config::CACHE))
|
|
250
|
-
end
|
|
251
|
-
end
|
|
252
|
-
end
|
data/lib/judgelint/client.rb
DELETED
|
@@ -1,210 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
module Judgelint
|
|
4
|
-
# Asks one model (an Endpoint) the questions over Net::HTTP, in whichever
|
|
5
|
-
# protocol its provider speaks. Plain Net::HTTP rather than a gem keeps the
|
|
6
|
-
# same code compiling with Spinel.
|
|
7
|
-
class Client
|
|
8
|
-
RETRY_STATUSES = %w[408 429 500 502 503 504 529].freeze
|
|
9
|
-
# The native binary links OpenSSL statically, so it looks for certificates
|
|
10
|
-
# where OpenSSL was built. Unless SSL_CERT_FILE says otherwise, it uses the
|
|
11
|
-
# system's bundle: macOS and Alpine, Debian and Ubuntu, then Fedora and RHEL.
|
|
12
|
-
CA_BUNDLES = %w[/etc/ssl/cert.pem /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt].freeze
|
|
13
|
-
|
|
14
|
-
attr_reader :usage, :endpoint
|
|
15
|
-
|
|
16
|
-
def initialize(endpoint, usage: Usage.new, sleeper: ->(seconds) { sleep(seconds) })
|
|
17
|
-
if RUBY_ENGINE == "spinel" && ENV.fetch("SSL_CERT_FILE", "").empty?
|
|
18
|
-
bundle = CA_BUNDLES.find { |path| File.file?(path) }
|
|
19
|
-
ENV["SSL_CERT_FILE"] = bundle if bundle
|
|
20
|
-
end
|
|
21
|
-
@endpoint = endpoint
|
|
22
|
-
@protocol = Protocol::ALL.fetch(endpoint.protocol) do
|
|
23
|
-
raise ConfigError, "protocol is system_one or decisions, not #{endpoint.protocol}"
|
|
24
|
-
end
|
|
25
|
-
@usage = usage
|
|
26
|
-
@sleeper = sleeper
|
|
27
|
-
@question_tokens = {}
|
|
28
|
-
@connections = Queue.new # open, and not in use
|
|
29
|
-
@lock = Mutex.new
|
|
30
|
-
check_settings
|
|
31
|
-
end
|
|
32
|
-
|
|
33
|
-
# Returns the probability of "yes" for each question, keyed by its key,
|
|
34
|
-
# or nil for a question the model refused.
|
|
35
|
-
def judge(state, questions)
|
|
36
|
-
data = self.class.unwrap(post(JSON.generate(payload(state, questions))))
|
|
37
|
-
@usage.record(data, @endpoint.price_per_million)
|
|
38
|
-
@protocol.parse(data, questions)
|
|
39
|
-
end
|
|
40
|
-
|
|
41
|
-
def payload(state, questions)
|
|
42
|
-
@protocol.payload(@endpoint.model, state, questions).merge(@endpoint.provider_options)
|
|
43
|
-
end
|
|
44
|
-
|
|
45
|
-
# A conservative token count for code: three bytes a token.
|
|
46
|
-
def tokens(state, questions)
|
|
47
|
-
JSON.generate(payload(state, questions)).bytesize / 3
|
|
48
|
-
end
|
|
49
|
-
|
|
50
|
-
# What one more question adds to a request, without serializing the file
|
|
51
|
-
# again. Files share their questions, so each is measured once.
|
|
52
|
-
def question_tokens(question)
|
|
53
|
-
@question_tokens[question] ||= (JSON.generate(@protocol.render(question)).bytesize + question.key.bytesize + 6) / 3
|
|
54
|
-
end
|
|
55
|
-
|
|
56
|
-
def url
|
|
57
|
-
base = Config.expand(@endpoint.api_base)
|
|
58
|
-
path = Config.expand(@endpoint.path).gsub("{model}", @endpoint.model.to_s)
|
|
59
|
-
"#{base.delete_suffix('/')}/#{path.delete_prefix('/')}"
|
|
60
|
-
end
|
|
61
|
-
|
|
62
|
-
# Cloudflare wraps the answers as {result: {...}, success, errors}.
|
|
63
|
-
def self.unwrap(data)
|
|
64
|
-
raise ApiError, "Response is not a JSON object" unless data.is_a?(Hash)
|
|
65
|
-
|
|
66
|
-
result = data["result"]
|
|
67
|
-
!data.key?("answers") && result.is_a?(Hash) && result.key?("answers") ? result : data
|
|
68
|
-
end
|
|
69
|
-
|
|
70
|
-
# The error message, whichever of the shapes providers use: TypeSafe's
|
|
71
|
-
# detail (a string, {message}, or a validation list), OpenAI's
|
|
72
|
-
# {error: {message}}, Cloudflare's errors list, or a bare message.
|
|
73
|
-
def self.error_detail(body)
|
|
74
|
-
data = JSON.parse(body)
|
|
75
|
-
return body[0, 200] unless data.is_a?(Hash)
|
|
76
|
-
|
|
77
|
-
detail = data["detail"] || data["error"] || data["errors"] || data["message"]
|
|
78
|
-
message(detail) || body[0, 200]
|
|
79
|
-
rescue JSON::ParserError
|
|
80
|
-
body[0, 200]
|
|
81
|
-
end
|
|
82
|
-
|
|
83
|
-
def self.message(detail)
|
|
84
|
-
case detail
|
|
85
|
-
when String then detail.empty? ? nil : detail
|
|
86
|
-
when Hash then message(detail["message"] || detail["msg"])
|
|
87
|
-
when Array
|
|
88
|
-
messages = detail.map { |item| message(item) }.compact
|
|
89
|
-
messages.empty? ? nil : messages.join("; ")
|
|
90
|
-
end
|
|
91
|
-
end
|
|
92
|
-
|
|
93
|
-
# Called before the first request, so a run the cache answers needs no key.
|
|
94
|
-
def check_key
|
|
95
|
-
raise ConfigError, "Set #{@endpoint.api_key_env} to your #{@endpoint.provider} API key" if key_missing?
|
|
96
|
-
end
|
|
97
|
-
|
|
98
|
-
private
|
|
99
|
-
|
|
100
|
-
def check_settings
|
|
101
|
-
provider = @endpoint.provider
|
|
102
|
-
if @endpoint.api_base.to_s.empty?
|
|
103
|
-
raise ConfigError, "Provider #{provider} needs #{@endpoint.needs || 'api_base'} in .judgelint.yml"
|
|
104
|
-
end
|
|
105
|
-
raise ConfigError, "Provider #{provider} needs a model in .judgelint.yml" if model_needed?
|
|
106
|
-
|
|
107
|
-
unless %w[bearer basic none].include?(@endpoint.auth) || @endpoint.auth.start_with?("header:")
|
|
108
|
-
raise ConfigError, "auth is bearer, basic, none, or header:<name>, not #{@endpoint.auth}"
|
|
109
|
-
end
|
|
110
|
-
end
|
|
111
|
-
|
|
112
|
-
# llama.cpp serves one model and doesn't need its name; nothing else can guess it.
|
|
113
|
-
def model_needed?
|
|
114
|
-
@endpoint.model.to_s.empty? && @endpoint.provider != "llamacpp"
|
|
115
|
-
end
|
|
116
|
-
|
|
117
|
-
def key_missing?
|
|
118
|
-
@endpoint.auth != "none" && !@endpoint.api_key_env.to_s.empty? && @endpoint.api_key.to_s.empty?
|
|
119
|
-
end
|
|
120
|
-
|
|
121
|
-
def post(body)
|
|
122
|
-
attempt = 0
|
|
123
|
-
loop do
|
|
124
|
-
attempt += 1
|
|
125
|
-
response = request(body, attempt)
|
|
126
|
-
next if response.nil?
|
|
127
|
-
|
|
128
|
-
code = response.code
|
|
129
|
-
return parse_json(response.body.to_s) if code.start_with?("2")
|
|
130
|
-
|
|
131
|
-
detail = self.class.error_detail(response.body.to_s)
|
|
132
|
-
if RETRY_STATUSES.include?(code) && attempt <= Endpoint::RETRIES
|
|
133
|
-
@sleeper.call(retry_delay(response, attempt))
|
|
134
|
-
next
|
|
135
|
-
end
|
|
136
|
-
raise ApiError, "#{@endpoint.label} answered #{code}: #{detail}"
|
|
137
|
-
end
|
|
138
|
-
end
|
|
139
|
-
|
|
140
|
-
# Answers nil after a connection error that's worth another try. The
|
|
141
|
-
# HTTP stack loads with the first request, so a run the cache answers
|
|
142
|
-
# never loads it, and TLS only for an https endpoint. A connection is
|
|
143
|
-
# kept for the next request, from any thread, unless the request on it
|
|
144
|
-
# fails.
|
|
145
|
-
def request(body, attempt)
|
|
146
|
-
require "net/http"
|
|
147
|
-
uri = @lock.synchronize { @uri ||= URI(url) }
|
|
148
|
-
require "openssl" if uri.scheme == "https"
|
|
149
|
-
request = Net::HTTP::Post.new(uri.request_uri)
|
|
150
|
-
request["Content-Type"] = "application/json"
|
|
151
|
-
request["Accept"] = "application/json"
|
|
152
|
-
authorize(request)
|
|
153
|
-
@endpoint.headers.each { |name, value| request[name.to_s] = Config.expand(value.to_s) }
|
|
154
|
-
request.body = body
|
|
155
|
-
http = connection(uri)
|
|
156
|
-
begin
|
|
157
|
-
response = http.request(request)
|
|
158
|
-
rescue StandardError
|
|
159
|
-
http.finish if http.started?
|
|
160
|
-
raise
|
|
161
|
-
end
|
|
162
|
-
@connections << http
|
|
163
|
-
response
|
|
164
|
-
rescue Judgelint::Error
|
|
165
|
-
raise
|
|
166
|
-
rescue StandardError => e
|
|
167
|
-
# Nothing listening isn't going to change in a few seconds; a dropped or
|
|
168
|
-
# stalled connection might.
|
|
169
|
-
refused = e.is_a?(Errno::ECONNREFUSED) || e.message.include?("Connection refused")
|
|
170
|
-
raise ApiError, "Couldn't reach #{@endpoint.label} at #{url}: #{e.message}" if refused || attempt > Endpoint::RETRIES
|
|
171
|
-
|
|
172
|
-
@sleeper.call(2.0**attempt)
|
|
173
|
-
nil
|
|
174
|
-
end
|
|
175
|
-
|
|
176
|
-
# One kept from an earlier request, or a new one.
|
|
177
|
-
def connection(uri)
|
|
178
|
-
@connections.pop(true)
|
|
179
|
-
rescue ThreadError
|
|
180
|
-
http = Net::HTTP.new(uri.host, uri.port)
|
|
181
|
-
http.use_ssl = uri.scheme == "https"
|
|
182
|
-
http.open_timeout = Endpoint::TIMEOUT
|
|
183
|
-
http.read_timeout = Endpoint::TIMEOUT
|
|
184
|
-
http.start
|
|
185
|
-
end
|
|
186
|
-
|
|
187
|
-
def authorize(request)
|
|
188
|
-
key = @endpoint.api_key
|
|
189
|
-
return if key.to_s.empty?
|
|
190
|
-
|
|
191
|
-
case @endpoint.auth
|
|
192
|
-
when "bearer" then request["Authorization"] = "Bearer #{key}"
|
|
193
|
-
when "basic" then request["Authorization"] = "Basic #{["token:#{key}"].pack("m0")}"
|
|
194
|
-
when "none" then nil
|
|
195
|
-
else request[@endpoint.auth.delete_prefix("header:")] = key
|
|
196
|
-
end
|
|
197
|
-
end
|
|
198
|
-
|
|
199
|
-
def retry_delay(response, attempt)
|
|
200
|
-
after = Judgelint.number(response["Retry-After"])
|
|
201
|
-
after ? [after, 30.0].min : 0.5 * (2**(attempt - 1))
|
|
202
|
-
end
|
|
203
|
-
|
|
204
|
-
def parse_json(body)
|
|
205
|
-
JSON.parse(body)
|
|
206
|
-
rescue JSON::ParserError
|
|
207
|
-
raise ApiError, "#{@endpoint.label} answered with something other than JSON: #{body[0, 200]}"
|
|
208
|
-
end
|
|
209
|
-
end
|
|
210
|
-
end
|
data/lib/judgelint/config.rb
DELETED
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
module Judgelint
|
|
4
|
-
# .judgelint.yml, which is optional: which models to ask, the threshold,
|
|
5
|
-
# files to ignore, and a spending limit. Everything else has a fixed value.
|
|
6
|
-
#
|
|
7
|
-
# models: [typesafe, cloudflare:clef] # ask both and average
|
|
8
|
-
# threshold: 0.7
|
|
9
|
-
# ignore: ["vendor/**"]
|
|
10
|
-
# max_cost_usd: 1.00
|
|
11
|
-
class Config
|
|
12
|
-
FILE = ".judgelint.yml"
|
|
13
|
-
KEYS = %w[models threshold ignore max_cost_usd].freeze
|
|
14
|
-
RULES_DIR = ".judgelint/rules"
|
|
15
|
-
CACHE = ".judgelint/cache.json"
|
|
16
|
-
WINDOW_LINES = 40
|
|
17
|
-
THREADS = 8
|
|
18
|
-
# Answers this far below the threshold, or less, are uncertain: reported, never failing.
|
|
19
|
-
UNCERTAIN_BAND = 0.3
|
|
20
|
-
|
|
21
|
-
attr_reader :models, :threshold, :ignore, :max_cost_usd
|
|
22
|
-
|
|
23
|
-
# +overrides+ replaces the file's settings: --model replaces its models.
|
|
24
|
-
def self.load(path: nil, overrides: {})
|
|
25
|
-
new(Judgelint.read_yaml(path || FILE, required: !path.nil?).merge(overrides))
|
|
26
|
-
end
|
|
27
|
-
|
|
28
|
-
# ${VAR} reads the environment, so a URL can carry an account id. The
|
|
29
|
-
# client expands it when it sends, so commands that make no request don't
|
|
30
|
-
# need every variable set.
|
|
31
|
-
def self.expand(value)
|
|
32
|
-
value.gsub(/\$\{[A-Za-z_][A-Za-z0-9_]*\}/) do |reference|
|
|
33
|
-
name = reference[2..-2]
|
|
34
|
-
found = ENV.fetch(name, "")
|
|
35
|
-
raise ConfigError, "Set #{name} (used in #{value})" if found.empty?
|
|
36
|
-
|
|
37
|
-
found
|
|
38
|
-
end
|
|
39
|
-
end
|
|
40
|
-
|
|
41
|
-
def initialize(data)
|
|
42
|
-
unknown = data.keys - KEYS
|
|
43
|
-
raise ConfigError, "#{FILE}: unknown keys #{unknown.join(', ')} (it takes #{KEYS.join(', ')})" unless unknown.empty?
|
|
44
|
-
|
|
45
|
-
entries = data.fetch("models", "typesafe")
|
|
46
|
-
entries = [entries] unless entries.is_a?(Array)
|
|
47
|
-
raise ConfigError, "models needs at least one model" if entries.empty?
|
|
48
|
-
|
|
49
|
-
@models = entries.map { |entry| Endpoint.from(entry) }
|
|
50
|
-
@threshold = Judgelint.number(data.key?("threshold") ? data["threshold"] : 0.7)
|
|
51
|
-
raise ConfigError, "threshold must be a number between 0 and 1" unless @threshold&.between?(0.01, 1)
|
|
52
|
-
|
|
53
|
-
@ignore = list(data["ignore"])
|
|
54
|
-
@max_cost_usd = Judgelint.number(data.key?("max_cost_usd") ? data["max_cost_usd"] : 1)
|
|
55
|
-
raise ConfigError, "max_cost_usd must be a number" if @max_cost_usd.nil?
|
|
56
|
-
end
|
|
57
|
-
|
|
58
|
-
def warn_at
|
|
59
|
-
[threshold - UNCERTAIN_BAND, 0.0].max
|
|
60
|
-
end
|
|
61
|
-
|
|
62
|
-
def label
|
|
63
|
-
models.map(&:label).join(" + ")
|
|
64
|
-
end
|
|
65
|
-
|
|
66
|
-
private
|
|
67
|
-
|
|
68
|
-
def list(value)
|
|
69
|
-
return [] if value.nil?
|
|
70
|
-
|
|
71
|
-
value.is_a?(Array) ? value.map(&:to_s) : [value.to_s]
|
|
72
|
-
end
|
|
73
|
-
end
|
|
74
|
-
|
|
75
|
-
# One model to ask, and how to reach it: a provider preset and model id
|
|
76
|
-
# ("typesafe", "cloudflare:clef", "openrouter:typesafe/jev-1.13"), or a
|
|
77
|
-
# mapping for an endpoint judgelint has no preset for.
|
|
78
|
-
class Endpoint
|
|
79
|
-
KEYS = %w[
|
|
80
|
-
provider model api_base path protocol auth api_key_env headers provider_options
|
|
81
|
-
price_per_million batch_size max_state_tokens max_request_tokens
|
|
82
|
-
].freeze
|
|
83
|
-
TIMEOUT = 30
|
|
84
|
-
RETRIES = 3
|
|
85
|
-
|
|
86
|
-
attr_reader :provider, :model, :api_base, :path, :protocol, :auth, :api_key_env, :headers,
|
|
87
|
-
:provider_options, :price_per_million, :batch_size, :max_state_tokens, :max_request_tokens, :needs
|
|
88
|
-
|
|
89
|
-
def self.from(entry)
|
|
90
|
-
return new(entry) if entry.is_a?(Hash)
|
|
91
|
-
|
|
92
|
-
provider, model = entry.to_s.split(":", 2)
|
|
93
|
-
data = { "provider" => provider }
|
|
94
|
-
data["model"] = model if model && !model.empty?
|
|
95
|
-
new(data)
|
|
96
|
-
end
|
|
97
|
-
|
|
98
|
-
def initialize(data)
|
|
99
|
-
unknown = data.keys - KEYS
|
|
100
|
-
raise ConfigError, "models: unknown keys #{unknown.join(', ')}" unless unknown.empty?
|
|
101
|
-
|
|
102
|
-
@data = data
|
|
103
|
-
@provider = data.fetch("provider", "custom").to_s
|
|
104
|
-
@preset = PROVIDERS.fetch(@provider, {})
|
|
105
|
-
@model = setting("model")
|
|
106
|
-
@api_base = setting("api_base")
|
|
107
|
-
@path = setting("path") || "/v1/systemone"
|
|
108
|
-
@protocol = setting("protocol") || "system_one"
|
|
109
|
-
@auth = setting("auth") || "bearer"
|
|
110
|
-
@api_key_env = setting("api_key_env")
|
|
111
|
-
@headers = mapping("headers")
|
|
112
|
-
@provider_options = mapping("provider_options")
|
|
113
|
-
@price_per_million = price
|
|
114
|
-
@batch_size = count("batch_size", 32)
|
|
115
|
-
# A request's state plus its widest question, and a whole request: Jev's
|
|
116
|
-
# 32k and 64k token limits, with room for the estimate to be off.
|
|
117
|
-
@max_state_tokens = count("max_state_tokens", 30_000)
|
|
118
|
-
@max_request_tokens = count("max_request_tokens", 60_000)
|
|
119
|
-
@needs = @preset["needs"]
|
|
120
|
-
end
|
|
121
|
-
|
|
122
|
-
def label
|
|
123
|
-
"#{provider}:#{model}"
|
|
124
|
-
end
|
|
125
|
-
|
|
126
|
-
def api_key
|
|
127
|
-
api_key_env.to_s.empty? ? nil : ENV.fetch(api_key_env, nil)
|
|
128
|
-
end
|
|
129
|
-
|
|
130
|
-
private
|
|
131
|
-
|
|
132
|
-
def setting(key)
|
|
133
|
-
value = @data.key?(key) ? @data[key] : @preset[key]
|
|
134
|
-
value.nil? ? nil : value.to_s
|
|
135
|
-
end
|
|
136
|
-
|
|
137
|
-
def mapping(key)
|
|
138
|
-
value = @data.fetch(key, {})
|
|
139
|
-
raise ConfigError, "models: #{key} must be a mapping" unless value.is_a?(Hash)
|
|
140
|
-
|
|
141
|
-
value
|
|
142
|
-
end
|
|
143
|
-
|
|
144
|
-
# A preset's prices are per model; another model has no price unless the
|
|
145
|
-
# entry gives one, and its cost shows as unknown.
|
|
146
|
-
def price
|
|
147
|
-
return Judgelint.number(@data["price_per_million"]) if @data.key?("price_per_million")
|
|
148
|
-
|
|
149
|
-
prices = @preset["prices"] || {}
|
|
150
|
-
prices.key?(@model.to_s) ? Judgelint.number(prices[@model.to_s]) : nil
|
|
151
|
-
end
|
|
152
|
-
|
|
153
|
-
def count(key, default)
|
|
154
|
-
# Not fetch(key, default): Spinel miscompiles a Float default on a YAML hash.
|
|
155
|
-
value = @data.key?(key) ? @data[key] : @preset[key]
|
|
156
|
-
number = Judgelint.number(value.nil? ? default : value)
|
|
157
|
-
raise ConfigError, "models: #{key} must be a whole number of at least 1" if number.nil? || number < 1
|
|
158
|
-
|
|
159
|
-
number.to_i
|
|
160
|
-
end
|
|
161
|
-
end
|
|
162
|
-
end
|
data/lib/judgelint/errors.rb
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
module Judgelint
|
|
4
|
-
class Error < StandardError; end
|
|
5
|
-
|
|
6
|
-
# The command line doesn't parse.
|
|
7
|
-
class UsageError < Error; end
|
|
8
|
-
|
|
9
|
-
# A rule file or the config file can't be used as written.
|
|
10
|
-
class ConfigError < Error; end
|
|
11
|
-
|
|
12
|
-
# The decision model couldn't be reached or answered with something unusable.
|
|
13
|
-
class ApiError < Error; end
|
|
14
|
-
end
|