squishling 0.8.0 → 0.8.1

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 +105 -0
  3. data/README.md +2 -2
  4. data/docs/adapters.md +95 -9
  5. data/docs/apprentice.md +6 -0
  6. data/docs/configuration.md +10 -8
  7. data/docs/failures.md +44 -7
  8. data/docs/harnesses.md +9 -5
  9. data/docs/images.md +2 -2
  10. data/docs/inputs.md +23 -10
  11. data/docs/measuring-tokens.md +3 -3
  12. data/docs/outer-loop-agents.md +56 -9
  13. data/docs/schemas.md +3 -1
  14. data/docs/testing.md +6 -3
  15. data/docs/verifying.md +11 -6
  16. data/lib/squishling/adapter/candidates.rb +144 -0
  17. data/lib/squishling/adapter/override.rb +109 -0
  18. data/lib/squishling/adapter/retry_after.rb +34 -0
  19. data/lib/squishling/adapter.rb +31 -15
  20. data/lib/squishling/adapters/openai_compatible.rb +10 -9
  21. data/lib/squishling/adapters/openai_options.rb +2 -1
  22. data/lib/squishling/adapters/ruby_llm.rb +14 -5
  23. data/lib/squishling/apprentice/shadow.rb +45 -4
  24. data/lib/squishling/attachment.rb +60 -28
  25. data/lib/squishling/configuration.rb +42 -12
  26. data/lib/squishling/definition.rb +8 -3
  27. data/lib/squishling/errors.rb +41 -8
  28. data/lib/squishling/image.rb +6 -3
  29. data/lib/squishling/judge.rb +19 -8
  30. data/lib/squishling/llm_client.rb +3 -2
  31. data/lib/squishling/outer_loop_agent.rb +33 -6
  32. data/lib/squishling/params.rb +3 -1
  33. data/lib/squishling/payload/normalizer.rb +24 -9
  34. data/lib/squishling/payload.rb +32 -8
  35. data/lib/squishling/result.rb +87 -34
  36. data/lib/squishling/run/rejections.rb +64 -6
  37. data/lib/squishling/run/reports.rb +23 -8
  38. data/lib/squishling/run.rb +36 -51
  39. data/lib/squishling/sanitizer.rb +5 -3
  40. data/lib/squishling/schema.rb +55 -4
  41. data/lib/squishling/squawk.rb +4 -3
  42. data/lib/squishling/testing/adapter.rb +1 -1
  43. data/lib/squishling/testing/outer_loop_agent.rb +11 -0
  44. data/lib/squishling/testing/reply.rb +23 -10
  45. data/lib/squishling/testing/script.rb +7 -7
  46. data/lib/squishling/testing/stubs.rb +8 -2
  47. data/lib/squishling/verifier.rb +41 -15
  48. data/lib/squishling/version.rb +1 -1
  49. data/lib/squishling.rb +3 -0
  50. metadata +4 -1
@@ -46,12 +46,13 @@ module Squishling
46
46
  # endpoint gets only the key you give it, so an OpenAI key can't reach another host. None is sent when the key
47
47
  # is blank (local servers). headers: extra request headers. default_model: used for steps that name no model.
48
48
  # max_retries: how often a timeout, connection failure, HTTP 408, 429, or 5xx is retried here (honoring
49
- # Retry-After) before it surfaces as an LLMError. max_tokens_param: the body key for max_output_tokens
50
- # (:max_completion_tokens, or :max_tokens for older servers). structured_output: :json_schema, :json_object,
51
- # or :none. allow_insecure_http: lets a credential (api_key, or a header such as Authorization or api-key) go
52
- # over plain http to a host that isn't loopback; without it that is a ConfigurationError. max_response_bytes:
53
- # the most a response (an error body too) may hold, 8 MiB by default. total_timeout: the most seconds one
54
- # attempt may take (read_timeout restarts at every read); it defaults to open_timeout + 2 * read_timeout.
49
+ # Retry-After) before it surfaces as an LLMError (a RateLimitError for a 429, whose retry_after is that header).
50
+ # max_tokens_param: the body key for max_output_tokens (:max_completion_tokens, or :max_tokens for older
51
+ # servers). structured_output: :json_schema, :json_object, or :none. allow_insecure_http: lets a credential
52
+ # (api_key, or a header such as Authorization or api-key) go over plain http to a host that isn't loopback;
53
+ # without it that is a ConfigurationError. max_response_bytes: the most a response (an error body too) may
54
+ # hold, 8 MiB by default. total_timeout: the most seconds one attempt may take (read_timeout restarts at every
55
+ # read); it defaults to open_timeout + 2 * read_timeout.
55
56
  # media_types: the types the server takes (the four image types by default, and application/pdf for OpenAI's
56
57
  # own endpoint); a call with another is refused before any request.
57
58
  # Responses are requested and accepted uncompressed only. Raises ConfigurationError for a bad option.
@@ -257,7 +258,8 @@ module Squishling
257
258
  return transport_failure(request, error) if error
258
259
 
259
260
  status = response.code.to_i
260
- http_failure(request, status:, body: response.body.to_s, via: "HTTP #{status}")
261
+ http_failure(request, status:, body: response.body.to_s, via: "HTTP #{status}",
262
+ retry_after: response.retry_after)
261
263
  end
262
264
 
263
265
  # A certificate that doesn't verify is a setup mistake (base_url, CA store) that a retry can't fix.
@@ -280,8 +282,7 @@ module Squishling
280
282
  end
281
283
 
282
284
  def retry_delay(response, attempt)
283
- after = response&.retry_after.to_s
284
- seconds = after.match?(/\A\d+\z/) ? after.to_i : (0.5 * (2**(attempt - 1))) + (rand * 0.25)
285
+ seconds = Adapter::RetryAfter.parse(response&.retry_after) || ((0.5 * (2**(attempt - 1))) + (rand * 0.25))
285
286
  [seconds, MAX_RETRY_DELAY].min
286
287
  end
287
288
 
@@ -29,7 +29,8 @@ module Squishling
29
29
 
30
30
  URI.parse("#{uri}/chat/completions")
31
31
  rescue URI::InvalidURIError
32
- raise ConfigurationError, INVALID_BASE_URL
32
+ # cause: nil, since the parser's message quotes the whole URL, which may carry credentials.
33
+ raise ConfigurationError, INVALID_BASE_URL, cause: nil
33
34
  end
34
35
 
35
36
  # The media types the server takes (some of Image::MEDIA_TYPES and Document::MEDIA_TYPES): the given list, or
@@ -10,7 +10,7 @@ module Squishling
10
10
  MINIMUM_VERSION = Gem::Version.new("2.2")
11
11
 
12
12
  # The ruby_llm gem isn't installed (Adapter.detect tells that apart from a gem that is, but too old).
13
- class MissingGemError < ConfigurationError; end
13
+ class MissingGemError < Adapter::MissingGemError; end
14
14
 
15
15
  # Raises ConfigurationError when the ruby_llm gem is missing. keep_cause: true keeps RubyLLM's original exception
16
16
  # as the #cause of the errors raised for a failed request (its message and response hold the provider's response
@@ -206,9 +206,10 @@ module Squishling
206
206
  end
207
207
 
208
208
  # Transient HTTP failures are already retried by RubyLLM; anything that still fails is surfaced as an
209
- # LLMError, which moves on to the next attempt of the escalation (or propagates from the last one), or as a
210
- # ConfigurationError for a setup mistake (see #http_failure for which statuses are which): escalating or a
211
- # fallback would otherwise hide it on every call.
209
+ # LLMError (a RateLimitError for a 429, with the response's Retry-After as retry_after), which moves on to the
210
+ # next attempt of the escalation (or propagates from the last one), or as a ConfigurationError for a setup
211
+ # mistake (see #http_failure for which statuses are which): escalating or a fallback would otherwise hide it on
212
+ # every call.
212
213
  # A provider's or transport's own message never goes into ours: a provider can echo request content or part of
213
214
  # an API key in it, and ours reach logs and error trackers.
214
215
  # Error trackers report the whole cause chain, and RubyLLM's error message and response hold the provider's
@@ -233,7 +234,14 @@ module Squishling
233
234
  return llm_error(request, via) if error.is_a?(::RubyLLM::ContextLengthExceededError)
234
235
 
235
236
  status = response_field(error.response, :status) || class_status(error)
236
- http_failure(request, status:, body: response_field(error.response, :body), via:)
237
+ http_failure(request, status:, body: response_field(error.response, :body), via:,
238
+ retry_after: retry_after_of(error.response))
239
+ end
240
+
241
+ # The value of the response's Retry-After header (any capitalization), which RubyLLM has already normalized from
242
+ # a provider's other hints (retry-after-ms), or nil. Only the header is read, never the body.
243
+ def retry_after_of(response)
244
+ response_field(response, :headers).to_h.find { |name, _| name.to_s.casecmp?("retry-after") }&.last
237
245
  end
238
246
 
239
247
  # The status RubyLLM's classes stand for, for an error raised without a response.
@@ -243,6 +251,7 @@ module Squishling
243
251
  when ::RubyLLM::PaymentRequiredError then 402
244
252
  when ::RubyLLM::ForbiddenError then 403
245
253
  when ::RubyLLM::BadRequestError then 400
254
+ when ::RubyLLM::RateLimitError then 429
246
255
  end
247
256
  end
248
257
 
@@ -4,8 +4,10 @@ module Squishling
4
4
  module Apprentice
5
5
  # One shadow run: the LLM path of a call whose Ruby result the caller already has. Starts on the caller's thread
6
6
  # (when:, then the request is built, so the instance's state is read before the caller moves on; on a background
7
- # runner the Ruby result is copied too, since the caller may change it), and the rest (the requests, validation,
8
- # compare:, the report) runs as a job on the configured runner.
7
+ # runner the Ruby result and the inputs are copied too, since the caller may change them), and the rest (the
8
+ # requests, validation, compare:, the report) runs as a job on the configured runner. The receiver is the
9
+ # caller's own object, so the job reads it live (as it reads its state in include_when:, compare:, and
10
+ # squish_validate).
9
11
  class Shadow
10
12
  # What a shadow run absorbs and reports: errors, and a NotImplementedError (a ScriptError) from the developer's
11
13
  # callbacks. Not the rest of Exception (an Interrupt, a SignalException, an exit), which still ends the process.
@@ -31,8 +33,9 @@ module Squishling
31
33
  begin
32
34
  return unless chosen?
33
35
 
34
- # Copied first, so that whatever fails after it is reported on the copy, never the caller's live result.
35
- @ruby = snapshot(@ruby) unless @runner.equal?(INLINE)
36
+ # Copied first, so that whatever fails after it is reported on the copies, not the caller's live objects
37
+ # (unless the copy itself fails: an object whose own #dup raises).
38
+ snapshot! unless @runner.equal?(INLINE)
36
39
  @call_id = @definition.call_id_for(@receiver, @inputs, @frame.call_id)
37
40
  invoker = Invoker.new(@definition, @receiver, @inputs, call_id: @call_id)
38
41
  built = invoker.prepare
@@ -48,6 +51,11 @@ module Squishling
48
51
 
49
52
  private
50
53
 
54
+ def snapshot!
55
+ @ruby = snapshot(@ruby)
56
+ @inputs = copy(@inputs, {}.compare_by_identity, 0)
57
+ end
58
+
51
59
  # A copy of the Ruby result the caller can't reach: a typed result's nested arrays and hashes stay mutable, and a
52
60
  # background job reads it after the call returned. Built like the original (a typed result of the schema).
53
61
  def snapshot(ruby)
@@ -55,6 +63,39 @@ module Squishling
55
63
  schema ? schema.build(Schema.plain(ruby), squished: false) : ruby
56
64
  end
57
65
 
66
+ # A copy of an input with its Hashes, Arrays, Sets, and Strings copied all the way down (a cycle stays a cycle),
67
+ # so that the caller changing one after the call returned is not seen by compare:, squish_validate,
68
+ # include_when:, or the report. What isn't plain data (a model, a Struct, an Image, an IO) can't be copied
69
+ # without running its code, and is shared: an Image is immutable, and the others are the caller's own objects.
70
+ # An input nested past JSON's own limit is refused here (as the pipeline would), not left to overflow the stack.
71
+ def copy(value, seen, depth)
72
+ return seen[value] if seen.key?(value)
73
+
74
+ if depth > Payload::Normalizer::MAX_DEPTH
75
+ raise InputRejectedError.single(Payload::TOO_DEEP, label: @definition.label)
76
+ end
77
+
78
+ case value
79
+ when Hash then copy_hash(value, seen, depth)
80
+ when Array, Set then copy_collection(value, seen, depth)
81
+ when String then value.frozen? ? value : value.dup
82
+ else value
83
+ end
84
+ end
85
+
86
+ # Each container is recorded before its contents are copied, so one that holds itself reaches its own copy.
87
+ def copy_hash(hash, seen, depth)
88
+ copied = seen[hash] = hash.dup.clear
89
+ hash.each { |key, item| copied[key] = copy(item, seen, depth + 1) }
90
+ copied
91
+ end
92
+
93
+ def copy_collection(collection, seen, depth)
94
+ copied = seen[collection] = collection.dup.clear
95
+ collection.each { |item| copied << copy(item, seen, depth + 1) }
96
+ copied
97
+ end
98
+
58
99
  def chosen?
59
100
  condition = @settings[:when]
60
101
  condition.nil? || @receiver.instance_exec(**@inputs, &condition)
@@ -60,12 +60,23 @@ module Squishling
60
60
  # of attachments), nil (an attachment slot with nothing in it), or NOT_A_FILE (including a slot or collection that
61
61
  # holds something other than files). label names the call in an InputRejectedError, raised for a file that is
62
62
  # empty, too large (see max_file_bytes, checked before it is read where its size is known), or unreadable. The
63
- # message never carries a path or a name.
64
- def read(value, label)
63
+ # message never carries a path or a name. room is how many bytes the call's files may still take before
64
+ # max_total_file_bytes (nil for no limit): a file that wouldn't fit is refused the same way, before it is read
65
+ # where its size is known, and a stream of unknown size is read no further than one byte past it.
66
+ def read(value, label, room: nil)
65
67
  return NOT_A_FILE if PLAIN.any? { |plain| value.is_a?(plain) }
66
68
 
67
69
  reader = reader_for(value)
68
- reader ? send(reader, value, label) : NOT_A_FILE
70
+ reader ? send(reader, value, label, room:) : NOT_A_FILE
71
+ end
72
+
73
+ # The bytes a node from #read holds: the file's (an Image given by URL holds none), or the sum for a collection.
74
+ def bytes_of(node)
75
+ case node
76
+ when Array then node.sum { |item| bytes_of(item) }
77
+ when String, Image, Document then node.bytesize.to_i
78
+ else 0
79
+ end
69
80
  end
70
81
 
71
82
  # A String as a node: a binary one (what #download and File.binread return) that starts with a known file
@@ -95,8 +106,8 @@ module Squishling
95
106
  raise InputRejectedError.single("a file couldn't be read", label:), cause: nil
96
107
  end
97
108
 
98
- def read_slot(value, label)
99
- value.attached? ? read(value.attachment, label) : nil
109
+ def read_slot(value, label, room: nil)
110
+ value.attached? ? read(value.attachment, label, room:) : nil
100
111
  end
101
112
 
102
113
  # ActiveStorage's blob surface (blobs, and attachments, which delegate to theirs). Looser than that would call
@@ -127,7 +138,7 @@ module Squishling
127
138
  true
128
139
  end
129
140
 
130
- def from_url(value, _label)
141
+ def from_url(value, _label, **)
131
142
  Image.from_url(value.to_s)
132
143
  end
133
144
 
@@ -145,7 +156,7 @@ module Squishling
145
156
  value.is_a?(URI::HTTP) && !Image.extension_type(value.path).nil?
146
157
  end
147
158
 
148
- def read_many(value, label)
159
+ def read_many(value, label, room: nil)
149
160
  files = value.attachments.to_a
150
161
  max = Squishling.config.max_files
151
162
  if max && files.size > max
@@ -153,56 +164,77 @@ module Squishling
153
164
  end
154
165
  return NOT_A_FILE unless files.all? { |file| reader_for(file) }
155
166
 
156
- files.map { |file| read(file, label) }
167
+ files.map do |file|
168
+ read(file, label, room:).tap { |node| room -= bytes_of(node) if room }
169
+ end
157
170
  end
158
171
 
159
- def stored(value, label)
160
- check_size(value.byte_size, label)
172
+ def stored(value, label, room: nil)
173
+ check_size(value.byte_size, label, room)
161
174
  build(value.download, value.content_type, extension_of(value), label)
162
175
  end
163
176
 
164
- def upload(value, label)
165
- from_io(value.tempfile, label, value.content_type, value.original_filename)
177
+ def upload(value, label, room: nil)
178
+ from_io(value.tempfile, label, value.content_type, value.original_filename, room:)
166
179
  end
167
180
 
168
- def from_path(path, label)
181
+ def from_path(path, label, room: nil)
169
182
  reading(label) do
170
- check_size(File.size(path), label)
171
- build(File.binread(path, read_limit), nil, path.to_s, label)
183
+ build(read_file(path, label, room), nil, path.to_s, label)
172
184
  end
173
185
  end
174
186
 
175
- def from_io(io, label, declared = nil, name = io.respond_to?(:path) ? io.path : nil)
187
+ # The bytes of the file at path, read no further than one byte past the limit: refused before the read when its
188
+ # size is already over one (label is nil for a caller outside the input pipeline, such as Image.from_path).
189
+ def read_file(path, label, room = nil)
190
+ check_size(File.size(path), label, room)
191
+ File.binread(path, read_limit(room))
192
+ end
193
+
194
+ def from_io(io, label, declared = nil, name = io.respond_to?(:path) ? io.path : nil, room: nil)
176
195
  reading(label) do
177
- check_size(size_of(io), label)
178
- build(read_stream(io), declared, name, label)
196
+ check_size(size_of(io), label, room)
197
+ build(read_stream(io, room), declared, name, label)
179
198
  end
180
199
  end
181
200
 
182
- # One byte past the limit, so a file whose size wasn't known (or changed) is still caught without reading it all.
183
- def read_limit
184
- max = Squishling.config.max_file_bytes
185
- max && (max + 1)
201
+ # One byte past the smaller of max_file_bytes and room, so a file whose size wasn't known (or changed) is still
202
+ # caught (by the checks after it, see Payload::Normalizer) without reading it all.
203
+ def read_limit(room = nil)
204
+ max = [Squishling.config.max_file_bytes, room].compact.min
205
+ max && ([max, 0].max + 1)
186
206
  end
187
207
 
188
208
  def size_of(io)
189
209
  io.size if io.respond_to?(:size)
190
210
  end
191
211
 
192
- # Refuses a file over max_file_bytes before it is read (size is nil when unknown).
193
- def check_size(size, label)
212
+ # Refuses a file over max_file_bytes, or one that wouldn't fit in room, before it is read (size is nil when
213
+ # unknown).
214
+ def check_size(size, label, room = nil)
215
+ return unless size
216
+
194
217
  max = Squishling.config.max_file_bytes
195
- return unless max && size && size > max
218
+ if max && size > max
219
+ raise InputRejectedError.single("a file of #{size} bytes is over max_file_bytes (#{max})", label:)
220
+ end
221
+ return unless room && size > room
222
+
223
+ raise InputRejectedError.single(total_message("a file of #{size} bytes would take the call's files"), label:)
224
+ end
196
225
 
197
- raise InputRejectedError.single("a file of #{size} bytes is over max_file_bytes (#{max})", label:)
226
+ # The refusal for files over max_total_file_bytes; subject says what went over ("the call's files are", which
227
+ # names no size: a stream is read only to one byte past the limit, so the sum isn't known).
228
+ def total_message(subject)
229
+ "#{subject} over max_total_file_bytes (#{Squishling.config.max_total_file_bytes})"
198
230
  end
199
231
 
200
232
  # The whole stream, whatever position the caller left it at, and the position put back (even when the read
201
233
  # fails) so the Ruby path (or the caller) reads it as before. A stream that can't seek is read from where it is.
202
- def read_stream(io)
234
+ def read_stream(io, room = nil)
203
235
  position = seekable_position(io)
204
236
  io.rewind if position
205
- io.read(read_limit)
237
+ io.read(read_limit(room))
206
238
  ensure
207
239
  io.seek(position) if position
208
240
  end
@@ -56,9 +56,10 @@ module Squishling
56
56
  attr_reader :squawk
57
57
 
58
58
  # The sanitizers every squished method runs before any of its class's or its own (see
59
- # ClassMethods#squish_sanitize), and the most files, and the most bytes in one file, a call may send (nil lifts a
60
- # limit). A call over one raises InputRejectedError before any request.
61
- attr_reader :sanitizers, :max_files, :max_file_bytes
59
+ # ClassMethods#squish_sanitize), and the most files, the most bytes in one file, and the most bytes in all of a
60
+ # call's files together, a call may send (nil lifts a limit). A call over one raises InputRejectedError before any
61
+ # request.
62
+ attr_reader :sanitizers, :max_files, :max_file_bytes, :max_total_file_bytes
62
63
 
63
64
  # Which attempts reach the squawk hook: :all (the default), :rejections (attempts that errored), :retries (those
64
65
  # plus any accepted attempt after the first), :final (the last attempt the escalation allows), or a list of
@@ -95,11 +96,18 @@ module Squishling
95
96
  # How Squishling reaches a model (see Adapter): :ruby_llm, :openai_compatible, an adapter you registered, a Hash
96
97
  # with type: and that adapter's options, or an adapter instance. nil (the default) uses RubyLLM when the ruby_llm
97
98
  # gem is available. Built when assigned, so a mistake fails at setup rather than on the first request.
99
+ # An Array of those is a list of candidates (see Adapter::Candidates), e.g.
100
+ # config.adapter = [{ type: :apple_fm, ignore_unsupported_params: true }, :ruby_llm]
101
+ # of which the first that is registered, has its gem, and is #available? is used; one that isn't is skipped, and a
102
+ # list with none usable is a ConfigurationError when the adapter is first needed (an empty list, or a bad entry, is
103
+ # one when assigned). The SQUISHLING_ADAPTER environment variable (see Adapter::Override) names an adapter that
104
+ # replaces whatever this resolves to.
98
105
  attr_reader :adapter
99
106
 
100
107
  # More adapters, by name, for escalation steps that pick one with adapter: (see ModelPath), e.g.
101
108
  # config.adapters = { local: { type: :openai_compatible, base_url: "http://localhost:11434/v1" }, claude: :claude_code }
102
- # Each value is anything config.adapter takes. A step without adapter: uses config.adapter. Built when assigned.
109
+ # Each value is an adapter, a registered name, or a Hash with type: (not a list of candidates). A step without
110
+ # adapter: uses config.adapter (or the adapter SQUISHLING_ADAPTER names). Built when assigned.
103
111
  attr_reader :adapters
104
112
 
105
113
  # Squishling::Testing only: when set, every adapter name resolves to this adapter, so a scripted adapter answers
@@ -118,6 +126,7 @@ module Squishling
118
126
  @adapters = {}.freeze
119
127
  @adapter_override = nil
120
128
  @detected_adapter = nil
129
+ @override = Adapter::Override.new
121
130
  @adapter_lock = Mutex.new
122
131
  @outer_loop_agent = nil
123
132
  @default_model = nil
@@ -134,6 +143,7 @@ module Squishling
134
143
  @sanitizers = [].freeze
135
144
  @max_files = 20
136
145
  @max_file_bytes = 20_000_000
146
+ @max_total_file_bytes = 100_000_000
137
147
  @apprentice_report = nil
138
148
  @apprentice_runner = :inline
139
149
  @apprentice_enabled = true
@@ -154,7 +164,7 @@ module Squishling
154
164
  end
155
165
 
156
166
  def adapter=(adapter)
157
- built = adapter.nil? ? nil : Adapter.build(adapter, "Squishling.configure")
167
+ built = build_adapter(adapter)
158
168
  @adapter_lock.synchronize do
159
169
  @adapter = built
160
170
  @detected_adapter = nil
@@ -175,11 +185,10 @@ module Squishling
175
185
  end
176
186
 
177
187
  # The adapter a step's adapter: names (nil is the default one, see #resolved_adapter). Raises ConfigurationError
178
- # for a name that isn't configured.
188
+ # for a name that isn't configured. Squishling::Testing's adapter_override answers for every name, the
189
+ # SQUISHLING_ADAPTER override included; otherwise a step that names an adapter gets it, whatever the variable says.
179
190
  def adapter_for(name)
180
- return resolved_adapter if name.nil?
181
-
182
- @adapter_override || named_adapter(name)
191
+ @adapter_override || (name.nil? ? resolved_adapter : named_adapter(name))
183
192
  end
184
193
 
185
194
  # The adapter configured under a name, whatever Squishling::Testing routes to. Raises ConfigurationError for a name
@@ -192,10 +201,18 @@ module Squishling
192
201
  end
193
202
  end
194
203
 
195
- # The adapter requests go through: the configured one, else RubyLLM's (when its gem is available) built on first
196
- # use. Raises ConfigurationError when there is neither.
204
+ # The adapter requests go through: the one SQUISHLING_ADAPTER names, else the configured one (the first usable of a
205
+ # list of candidates), else RubyLLM's (when its gem is available) built on first use. Raises ConfigurationError when
206
+ # there is none, naming why.
197
207
  def resolved_adapter
198
- @adapter_lock.synchronize { @adapter || (@detected_adapter ||= Adapter.detect) }
208
+ override = Adapter::Override.requested
209
+ if override
210
+ adapters, current, detected = @adapter_lock.synchronize { [@adapters, @adapter, @detected_adapter] }
211
+ return @override.adapter(override, adapters:, current:, detected:)
212
+ end
213
+
214
+ chosen = @adapter_lock.synchronize { @adapter || (@detected_adapter ||= Adapter.detect) }
215
+ chosen.is_a?(Adapter::Candidates) ? chosen.select : chosen
199
216
  end
200
217
 
201
218
  def default_max_total_output_tokens=(tokens)
@@ -228,6 +245,10 @@ module Squishling
228
245
  @max_file_bytes = positive_or_nil(limit, "max_file_bytes")
229
246
  end
230
247
 
248
+ def max_total_file_bytes=(limit)
249
+ @max_total_file_bytes = positive_or_nil(limit, "max_total_file_bytes")
250
+ end
251
+
231
252
  def squawk_on=(on)
232
253
  @squawk_on = Squawk.validate_on(on, "Squishling.configure") || :all
233
254
  end
@@ -289,6 +310,15 @@ module Squishling
289
310
 
290
311
  private
291
312
 
313
+ # What config.adapter= takes: nil, a list of candidates (or one built already), or one adapter.
314
+ def build_adapter(value)
315
+ case value
316
+ when nil, Adapter::Candidates then value
317
+ when Array then Adapter::Candidates.build(value, "Squishling.configure")
318
+ else Adapter.build(value, "Squishling.configure")
319
+ end
320
+ end
321
+
292
322
  # A limit: a positive Integer, or nil for none.
293
323
  def positive_or_nil(value, name)
294
324
  return value if value.nil? || (value.is_a?(Integer) && value.positive?)
@@ -190,9 +190,11 @@ module Squishling
190
190
 
191
191
  # The observability hook: the method's, else the class's, else the configured one. `false` at a level
192
192
  # silences the levels above it.
193
- def squawk
194
- [@squawk, klass.squishling_squawk, Squishling.config.squawk].find { |hook| !hook.nil? } || nil
195
- end
193
+ def squawk = squawk_setting || nil
194
+
195
+ # Whether `squawk: false` (the method's, else the class's, else the configuration's) silences reports for this
196
+ # method. It also keeps them from an outer-loop agent's report (see OuterLoopAgent.reporter).
197
+ def squawk_silenced? = squawk_setting == false
196
198
 
197
199
  # Which attempts reach the hook (see Squawk): the method's, else the class's, else the configured one.
198
200
  def squawk_on
@@ -292,6 +294,9 @@ module Squishling
292
294
 
293
295
  private
294
296
 
297
+ # The first level that sets squawk (a hook, or false to silence), nil when none does.
298
+ def squawk_setting = [@squawk, klass.squishling_squawk, Squishling.config.squawk].find { |hook| !hook.nil? }
299
+
295
300
  def check_context!(context)
296
301
  return if context.nil? || (context.is_a?(Hash) && context.each_key.all?(NAME_KEY))
297
302
 
@@ -37,8 +37,9 @@ module Squishling
37
37
  end
38
38
 
39
39
  # An input the call would send was refused before any request was made: the sanitizer (squish_sanitize) rejected it
40
- # (reject.call), a file is over max_files or max_file_bytes, empty or unreadable, or its type isn't one an adapter
41
- # can send (a fax's TIFF nobody converted). Never retried or escalated, and not passed to squish_fallback: the
40
+ # (reject.call), the files are over max_files, max_file_bytes, or max_total_file_bytes, a file is empty or
41
+ # unreadable, or its type isn't one an adapter can send (a fax's TIFF nobody converted). Never retried or
42
+ # escalated, and not passed to squish_fallback: the
42
43
  # input is what's wrong, so the caller decides what to do about it. rejections holds every problem found, each with
43
44
  # the path of the input in the call ("arguments.pages[1]", nil when it isn't one input's), never the value, the
44
45
  # bytes, a file name, or a URL (a rejection message you wrote with reject.call is your own: don't put values in it).
@@ -92,9 +93,9 @@ module Squishling
92
93
  end
93
94
  Detail::SOURCES = %i[schema validator parse squishling].freeze
94
95
 
95
- # models: the model ids tried, one per attempt (nil entries mean the adapter's default model). finish_reason: why
96
- # the provider stopped on the last attempt (a Symbol such as :stop or :max_tokens; nil when unknown or not from
97
- # an LLM).
96
+ # models: the model ids tried, one per attempt (nil entries mean the adapter's default model; a budget stop in
97
+ # Run#samples lists each round's distinct models instead). finish_reason: why the provider stopped on the last
98
+ # attempt (a Symbol such as :stop or :max_tokens; nil when unknown or not from an LLM).
98
99
  # errors: Strings, or Details; a String counts as :squishling text.
99
100
  attr_reader :errors, :error_details, :raw, :attempts, :models, :finish_reason
100
101
 
@@ -159,8 +160,40 @@ module Squishling
159
160
  end
160
161
  end
161
162
 
162
- # The LLM call itself failed (rate limit, server error, timeout, connection) after the
163
- # adapter's own HTTP retries. #cause is the adapter's: a sanitized stand-in (Adapter::ProviderFailure) for a provider
164
- # exception that carries a response body, or the transport error itself when it carries none.
163
+ # The LLM call itself failed (server error, timeout, connection; a rate limit is the RateLimitError subclass) after
164
+ # the adapter's own HTTP retries. #cause is the adapter's: a sanitized stand-in (Adapter::ProviderFailure) for a
165
+ # provider exception that carries a response body, or the transport error itself when it carries none.
165
166
  class LLMError < Error; end
167
+
168
+ # The provider rate limited the request (HTTP 429) after the adapter's own HTTP retries. An LLMError, so a
169
+ # rescue of that (or squish_fallback) still catches it, but one that doesn't spend the rest of its step's attempts:
170
+ # another request to the same model would land in the same quota window, so the escalation moves on to its next
171
+ # step instead, and the error is raised when there is none. retry_after is the provider's own wait in seconds (a
172
+ # Numeric, capped at an hour) when it sent a Retry-After header, otherwise nil, so a background job can requeue
173
+ # with it.
174
+ class RateLimitError < LLMError
175
+ attr_reader :retry_after
176
+
177
+ def initialize(message = nil, retry_after: nil)
178
+ unless retry_after.nil? || seconds?(retry_after)
179
+ raise ArgumentError, "retry_after must be nil or a non-negative number of seconds, got #{retry_after.inspect}"
180
+ end
181
+
182
+ @retry_after = retry_after
183
+ super(message)
184
+ end
185
+
186
+ private
187
+
188
+ # A finite, non-negative real number (not NaN, infinite, or a Complex).
189
+ def seconds?(value)
190
+ value.is_a?(Numeric) && value.real? && value.to_f.finite? && !value.negative?
191
+ end
192
+ end
193
+
194
+ module Adapter
195
+ # Raised when an adapter is built and the gem it needs isn't installed. A ConfigurationError like any setup mistake,
196
+ # except that a config.adapter list of candidates skips an entry that raises it (see Adapter::Candidates).
197
+ class MissingGemError < ConfigurationError; end
198
+ end
166
199
  end
@@ -30,9 +30,11 @@ module Squishling
30
30
  attr_reader :media_type, :detail, :url
31
31
 
32
32
  class << self
33
- # An image read from a file. The media type comes from the bytes, or the extension when given none.
33
+ # An image read from a file. The media type comes from the bytes, or the extension when given none. A file over
34
+ # config.max_file_bytes raises InputRejectedError before it is read (the limit every file is held to).
34
35
  def from_path(path, media_type: nil, detail: nil)
35
- data = File.binread(path)
36
+ data = Attachment.read_file(path, nil)
37
+ Attachment.check_size(data.bytesize, nil)
36
38
  new(data:, media_type: media_type || sniff(data) || extension_type(path), detail:)
37
39
  end
38
40
 
@@ -130,7 +132,8 @@ module Squishling
130
132
 
131
133
  raise ConfigurationError, "Squishling::Image url: must be an http or https URL"
132
134
  rescue URI::InvalidURIError
133
- raise ConfigurationError, "Squishling::Image url: must be an http or https URL"
135
+ # cause: nil, since the parser's message quotes the whole URL, query and credentials included.
136
+ raise ConfigurationError, "Squishling::Image url: must be an http or https URL", cause: nil
134
137
  end
135
138
 
136
139
  def checked_detail(detail)
@@ -46,7 +46,7 @@ module Squishling
46
46
  # files: the call's Images and Documents, which a chat judge is sent with the input; a :judgment judge can't take
47
47
  # them.
48
48
  def initialize(definition:, receiver:, client:, judge:, instructions:, path:, purpose:, payload:, escalate:,
49
- log_failure:, guard:, budget_check:, harness_type:, files: [])
49
+ log_failure:, guard:, budget_check:, harness_type:, next_attempt:, files: [])
50
50
  @definition = definition
51
51
  @receiver = receiver
52
52
  @client = client
@@ -57,6 +57,7 @@ module Squishling
57
57
  check_judgments!
58
58
  @guard = guard
59
59
  @budget_check = budget_check
60
+ @next_attempt = next_attempt
60
61
  @harness_type = harness_type
61
62
  @purpose = purpose
62
63
  @payload = payload
@@ -153,12 +154,16 @@ module Squishling
153
154
  prompt = Invoker::Prompt.new(
154
155
  instructions: "#{judge_instructions}\n\nThe operation's purpose:\n<purpose>\n#{@purpose}\n" \
155
156
  "</purpose>\n\n#{INPUT_NOTE}#{Invoker.file_notes(@files)}",
156
- schema: Schema.for(VERDICT_SCHEMA), input: JSON.generate(state(candidates)), role: :judge, files: @files
157
+ schema: Schema.for(VERDICT_SCHEMA), input: candidates_json(candidates), role: :judge, files: @files
157
158
  )
158
159
  result = @escalate.call(@steps, prompt)
159
160
  Verdict.new(choice: result[:verdict].to_sym, reason: result[:reason], detail: nil)
160
161
  end
161
162
 
163
+ # A candidate may sit at JSON's own nesting limit (a reply is parsed up to it), and the wrapper around it goes two
164
+ # levels past, so generating has no limit of its own: the depth is already bounded by what was parsed.
165
+ def candidates_json(candidates) = JSON.generate(state(candidates), max_nesting: false)
166
+
162
167
  def judgment(candidates)
163
168
  input = { purpose: @purpose, **state(candidates) }
164
169
  questions = { winner: { type: :choice, instructions: judge_instructions, options: CHOICES } }
@@ -189,15 +194,21 @@ module Squishling
189
194
  Verdict.new(choice: :neither, reason: text, detail: text)
190
195
  end
191
196
 
192
- # A judgment always matches its questions, so only a failed request (LLMError) moves on to the next attempt.
197
+ # A judgment always matches its questions, so only a failed request (LLMError) moves on to the next attempt, and a
198
+ # rate limit skips the rest of its step's attempts, as in an escalation.
193
199
  def judge_with_retries(input, questions)
194
- @steps.each.with_index(1) do |step, attempt|
195
- @budget_check.call(attempts: attempt - 1)
196
- return @client.wrapped_judgment(input, questions:, step:, attempt:, attempts: @steps.size)
200
+ attempt = 1
201
+ made = 0
202
+ loop do
203
+ @budget_check.call(attempts: made)
204
+ made += 1
205
+ return @client.wrapped_judgment(input, questions:, step: @steps[attempt - 1], attempt:, attempts: @steps.size)
197
206
  rescue LLMError => e
198
- raise if attempt == @steps.size
207
+ following = @next_attempt.call(@steps, attempt, e.is_a?(RateLimitError))
208
+ raise unless following
199
209
 
200
- @log_failure.call(:judge, attempt, @steps, e.message)
210
+ @log_failure.call(:judge, attempt, @steps, e.message, following:)
211
+ attempt = following
201
212
  end
202
213
  end
203
214
 
@@ -58,10 +58,11 @@ module Squishling
58
58
 
59
59
  adapters = steps.map { |step| adapter_for(step) }
60
60
  contexts = captured_contexts(adapters)
61
- threads = jobs.zip(adapters).map do |job, adapter|
61
+ threads = []
62
+ jobs.zip(adapters).each do |job, adapter|
62
63
  thread = Thread.new { with_context(adapter, contexts.fetch(adapter)) { capture(job) } }
63
64
  thread.report_on_exception = false
64
- thread
65
+ threads << thread # one at a time, so the ensure can stop the started ones if a later Thread.new raises
65
66
  end
66
67
  threads.map(&:value)
67
68
  ensure