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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c0f88fd9fc72def835f2a7c05494e95dc8bbb318f2a531e5437f978c90d4bf8a
4
- data.tar.gz: e75de810c1fc839857b44c15f456c37467245ac55df13a2d2110e807f9af3bdb
3
+ metadata.gz: 904d5beb642a5f4950d439b8917f26790504bf327529309ca91da868f5028154
4
+ data.tar.gz: 6cdbf5ad28b5f9ef21ac286f3f919bfe6f9b9d6767eb8ab16d2fe3a5904c17fe
5
5
  SHA512:
6
- metadata.gz: 491b5298f335886c5f2e77fc06004b60ec9e256a58ac380c37cec0d25d95c05440e8705c5e1dbd49e1580673e6116fd954b9d3ca0317e55fdebea933e2fbc272
7
- data.tar.gz: 6007c5c10002519a38a7e0a9c3e4ab5d55caeaa18c92ccc856823e8e8c22de6bc4a90bbd9cad72786280f40fd9fb51c3461045b3d8b83d5c7a4a774a03fa982f
6
+ metadata.gz: 8a6b74d34188e8dffbd626d5638e75c1ee45aa229eb5abf16300f9d123505ad66588185681bb8a80d2967b1becbeaf75c07f67b7532777d1f63f4ed7a557d93e
7
+ data.tar.gz: f64791882c20936316ef09bfecf37c1b30af1c5dc4d476466b42faae12e9b64a75d8a0887a3da5ef3ea030f549e81d393283dfa8b9d674e277c0bf36c68c1619
data/CHANGELOG.md CHANGED
@@ -7,6 +7,111 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.8.1] - 2026-11-30
11
+
12
+ A typed error for rate limits that moves on to the next model instead of retrying the same one, an adapter chosen from a
13
+ list of candidates or by `SQUISHLING_ADAPTER`, an outer-loop agent that can take `squawk`'s reports, and fixes from the
14
+ 0.8.0 red-team: a cap on the files of one call, Hash keys that no longer show up in input errors, results typed through
15
+ chained and recursive `$ref`s, and every sample of a round reaching `squawk`. Read **Changed** before upgrading: a 429 no
16
+ longer spends a step's remaining attempts, a call sending more than 100 MB of files is refused, and a schema that loops
17
+ back on itself is now a `ConfigurationError`.
18
+
19
+ ### Added
20
+
21
+ - `Squishling::RateLimitError`, a subclass of `LLMError` raised for an HTTP 429 once the adapter's own retries are used
22
+ up, with `retry_after` (the provider's `Retry-After` in seconds, capped at an hour, or `nil`) so a background job can
23
+ requeue itself. A `rescue LLMError` and `squish_fallback` still catch it. Both built-in adapters raise it; a custom
24
+ adapter gets it through `http_failure(status, retry_after:)`. The OpenAI-compatible adapter's own backoff now honors an
25
+ HTTP-date `Retry-After` too. Squishling never sleeps. `Squishling::Testing` scripts it with `fail(:rate_limit,
26
+ retry_after: 30)` and `stub_squishling_error(klass, :rate_limit, retry_after:)`. See
27
+ [Failures](docs/failures.md#rate-limits). (#147)
28
+ - `config.adapter` takes a list of candidates, such as `[{ type: :apple_fm }, :ruby_llm]`, and uses the first that is
29
+ registered, has its gem, and answers `available?` (a new optional `Adapter::Base` hook, `true` by default). A custom
30
+ adapter that raises `Adapter::MissingGemError` is skipped the same way, and the RubyLLM one now does. With no usable
31
+ entry the first call, and `Squishling.verify`, raises a `ConfigurationError` naming each skipped candidate, never its
32
+ options. See [Adapters](docs/adapters.md#choosing-from-candidates-and-squishling_adapter). (#148)
33
+ - `SQUISHLING_ADAPTER=<name>` replaces the default adapter ahead of `config.adapter`, so a developer or a deploy can pick
34
+ another one without a code change. The name is a `config.adapters` entry or candidate, else the adapter you configured
35
+ of that class (so `SQUISHLING_ADAPTER=openai_compatible` uses your `base_url`, not OpenAI's), else a registered adapter
36
+ built with no options; two configured adapters of one class is a `ConfigurationError` asking you to name one. An
37
+ escalation step's own `adapter:` and `Squishling::Testing` still win, an unknown name is a `ConfigurationError` that
38
+ never repeats the value, and unset or blank changes nothing. `Squishling.verify` checks it. (#148, #167)
39
+ - An outer-loop agent can define an optional `report(output:, metadata:, error:)` and be sent the reports `squawk` gets:
40
+ same keywords, same `squawk_on:` gate, the stopped call's final report once. It is the deliberate opt-in to output
41
+ reaching an agent: `around` and an agent without `report` (the Coolhand one among them) still never see it, and
42
+ `squawk: false` silences `report` too. See [Outer-loop agents](docs/outer-loop-agents.md#reports-and-output-report).
43
+ (#145)
44
+ - `config.max_total_file_bytes` (100 MB), a cap on the bytes of all the files one call sends together, enforced before
45
+ each read where the size is known so the file that would cross it is refused unread. See **Changed** and
46
+ [Inputs](docs/inputs.md#limits). (#146)
47
+
48
+ ### Changed
49
+
50
+ - **Behavior change:** after a `RateLimitError`, an escalation step's remaining same-model attempts are skipped and the
51
+ next step is used; with no next step the error is raised (or handed to `squish_fallback`). A sample raises it at once,
52
+ and a judge skips the same way. `squawk` reports `final: true` on the attempt that ends the call. Before, a 429 was a
53
+ plain `LLMError` and was retried on the same model. A test that scripted `fail(:rate_limit)` and relied on that retry
54
+ now moves to the next step: use `:server_error` for a retryable failure. (#147)
55
+ - **Behavior change:** a call that sends more than 100 MB of files in total now raises `InputRejectedError` before any
56
+ request. That is above what any provider takes in one request, so such a call was already failing, after the bytes had
57
+ been read and encoded. Set `config.max_total_file_bytes = nil` to restore the old behavior. `Image.from_path` now holds
58
+ a file to `max_file_bytes` as well, checking its size before reading it. (#146)
59
+ - **Behavior change:** an `InputRejectedError` path quotes only a Symbol Hash key shaped like an identifier (a name you
60
+ chose). Every String key is masked as `[key]`, including ones like `"jane_doe"` or `"MRN12345"` that are data, not
61
+ schema. Sanitizers were never offered Hash keys, and that is now stated in [Inputs](docs/inputs.md). (#144)
62
+ - **Behavior change:** in a sample round (`:squishsum`, `:judged_squishsum`, a custom harness), every sample that was
63
+ asked is now reported to `squawk` and the outer-loop agent before the first terminal error is raised, where before
64
+ the later samples were paid for and never seen. A sample that could still retry reports `final: true` when another
65
+ sample's last attempt or repeated reply ends the call, and the log no longer says "retrying" for it. The error the
66
+ caller gets is the same, but a sibling's output is now checked after another sample has failed for good: an exception
67
+ from `squish_validate`, a field's `validate:`, the `squawk` hook or an outer-loop agent raised there replaces the
68
+ sample's error, so a `squish_fallback` that would have run before doesn't. (#153, thanks @yorzi, and #156)
69
+ - A `BudgetExhaustedError` raised before a sample round lists each completed round's distinct models in `models`, not
70
+ only the first sample's. (#153, thanks @yorzi)
71
+ - A schema whose reference leads back to itself while still describing the same value (a `$ref` to itself, or through
72
+ nothing but `allOf`, `anyOf`, `oneOf`, `not` or `if`) is now a `ConfigurationError` when the schema is built, and
73
+ `Squishling.verify` reports it, instead of overflowing the validator's stack after a request was paid for. Recursion
74
+ through `properties` or `items` is fine. To migrate, remove the self-reference. A schema first reached through a longer
75
+ `$ref` chain now gets the checks an inline one gets, so `properties` without `type: "object"`, or a reserved property
76
+ name, raises there too. Set `type: "object"` or rename the field. (#152, thanks @yorzi)
77
+ - An outer-loop agent that already has an unrelated method named `report` is now treated as this hook, and positional
78
+ arguments raise `ConfigurationError` when it is assigned. Rename the method. (#145)
79
+ - `Data.define(:"a=")`'s `ArgumentError` while building a result class is now a `ConfigurationError`, so
80
+ `Squishling.verify` collects it. Perplexity's `preset` is a reserved `params:` key. (#146)
81
+
82
+ ### Fixed
83
+
84
+ - A result that was typed through a `$ref` chain longer than two hops, an escaped name, or an array index, or through a
85
+ recursive schema, lost its fields and came back as a plain Hash (or raised). The builder now follows json_schemer's
86
+ resolved references for as long as nothing typed it, and a result that was typed before is typed the same. (#152,
87
+ thanks @yorzi)
88
+ - A result is produced only once `Run#samples` returns, so a custom harness that escalates after a sample failed can't
89
+ have `accepted_request_id` name the dropped sample, and two agreeing boolean samples name the request of the sample
90
+ that is returned. (#153, thanks @yorzi)
91
+ - An apprentice running on a non-inline runner now gets a copy of the call's inputs (Hashes, Arrays, Sets and Strings,
92
+ all the way down), so a caller changing them after returning can't alter what `compare:`, `squish_validate`,
93
+ `include_when:` or the report's `inputs:` see. Non-plain objects are still shared. (#146)
94
+ - `Squishling.verify` checks the `include_when:` keywords of an escalation step declared on a `squish_rescue`, which
95
+ it skipped, so a mismatched one failed with an `ArgumentError` at runtime once the rescue fired. (#136, thanks @yorzi)
96
+
97
+ - A URL that `Image.from_url` refuses, or an OpenAI-compatible `base_url` the parser refuses, no longer stays on the
98
+ error as its `cause`: the parser's message quotes the whole URL, query string and credentials included, and error
99
+ trackers walk the cause chain.
100
+ - A judged harness no longer raises a bare `JSON::NestingError` when a candidate reply sits at JSON's own nesting limit
101
+ (100) and the judge's wrapper around it goes past it.
102
+ - Concurrent sample requests are stopped, rather than left running unobserved, when a later request thread can't be
103
+ created.
104
+
105
+ ### Internal
106
+
107
+ - The Pages workflow is split into build and deploy jobs, so the deploy no longer races the artifact upload and a failed
108
+ deploy can be retried alone. (#155)
109
+
110
+ ### Thanks
111
+
112
+ - Thank you to @yorzi for #136 (`include_when:` checks for `squish_rescue` escalations), #152 (results typed through
113
+ chained and recursive schema references) and #153 (every completed sample reaching `squawk`).
114
+
10
115
  ## [0.8.0] - 2026-11-28
11
116
 
12
117
  Files and PDFs as plain inputs, a sanitizer over everything sent, a way to declare which Ruby errors the LLM recovers,
data/README.md CHANGED
@@ -213,11 +213,11 @@ sees it right where the value goes, and the purpose stays short and about the go
213
213
  spending without limit (see [Capping a call's cost](docs/failures.md#capping-a-calls-cost-token-budgets)).
214
214
  - **Output contracts**: beyond the strict schema, conditional rules (`given`) and Ruby checks (`squish_validate`)
215
215
  reject bad output and trigger the next attempt.
216
- - **Defined failure behavior**: provider errors become `Squishling::LLMError`, and `squish_fallback` lets you decide
216
+ - **Defined failure behavior**: provider errors become `Squishling::LLMError` (a rate limit is a `RateLimitError` carrying `retry_after`), and `squish_fallback` lets you decide
217
217
  what to return when every attempt fails.
218
218
  - **Observability**: the opt-in [`squawk`](docs/failures.md#observing-every-attempt-squawk) hook sends each attempt's
219
219
  raw output (or only the rejected and retried ones), and the end of a call that a token budget or a disagreement
220
- stopped, to your error tracker. Model output stays out of error messages and logs otherwise.
220
+ stopped, to your error tracker (or to your outer-loop agent, if it defines `report`). Model output stays out of error messages and logs otherwise.
221
221
  - **Opt-in context**: only method arguments, the instance state you name with `squish_context`, the `context:` you
222
222
  pass to `squish!`, and the source you choose to append are sent to the provider. The one addition: when
223
223
  [escalation](docs/configuration.md#models-and-escalation) moves to the next step, that step also sees the previous
data/docs/adapters.md CHANGED
@@ -51,6 +51,75 @@ The RubyLLM adapter builds each chat in a copy of RubyLLM's configuration with `
51
51
  image or PDF always goes with the request and never to a provider's Files API; RubyLLM's global configuration is not
52
52
  changed.
53
53
 
54
+ ## Choosing from candidates, and `SQUISHLING_ADAPTER`
55
+
56
+ An app that uses a local or dev-only adapter in one environment and RubyLLM elsewhere can say so in one line. Give
57
+ `config.adapter` a list, and Squishling uses the first entry that is registered and usable:
58
+
59
+ ```ruby
60
+ Squishling.configure do |config|
61
+ config.adapter = [{ type: :apple_fm, ignore_unsupported_params: true }, :ruby_llm]
62
+ end
63
+ ```
64
+
65
+ Each entry takes what a single `config.adapter` does (a name, a Hash with `type:` and options, or an instance). An entry
66
+ is **skipped**, not an error, when
67
+
68
+ - its name isn't registered (its gem isn't in the bundle, such as a development-group gem in production, or isn't loaded
69
+ yet: an entry is used as soon as it is registered, even after the list was assigned),
70
+ - its adapter's gem is missing (for an entry registered when the list is assigned, that is final: installing the gem
71
+ later doesn't revive it): building it raised `Squishling::Adapter::MissingGemError` (the RubyLLM adapter does this
72
+ without the `ruby_llm` gem; raise it from your own adapter's `initialize` for the same), or
73
+ - its adapter's [`available?`](#optional-hooks) returns `false`: it can't run on this machine (an adapter for an Apple
74
+ Silicon feature on a Linux server).
75
+
76
+ An entry that is registered is built when you assign the list, so a bad option still fails at boot (one registered later
77
+ is built, and its options checked, when it is first needed). `available?` is asked each
78
+ time the adapter is resolved (at the start of a call), so the answer can change while the process runs.
79
+
80
+ **When no entry is usable**, the first squished call (and `Squishling.verify`) raises `Squishling::ConfigurationError`
81
+ naming each candidate and why it was skipped, e.g. `config.adapter has no usable adapter; skipped :apple_fm (not
82
+ registered; is its gem in the bundle and loaded?), :ruby_llm (its gem isn't available)`. A list never falls back to the
83
+ RubyLLM auto-detection used when `config.adapter` is unset, and an empty list is rejected when you assign it: end the
84
+ list with the adapter that is always there. The message holds names and reasons only, never an adapter's options or
85
+ credentials.
86
+
87
+ ### Overriding the choice with `SQUISHLING_ADAPTER`
88
+
89
+ Squishling reads the `SQUISHLING_ADAPTER` environment variable itself, so a developer or a deploy can pick another
90
+ adapter without a code change. When it is set, the adapter it names is the default adapter, ahead of `config.adapter`
91
+ (a single adapter, a candidate list, or the RubyLLM auto-detection):
92
+
93
+ ```sh
94
+ SQUISHLING_ADAPTER=ruby_llm bin/rails test # opt out of the dev-only adapter
95
+ ```
96
+
97
+ - **Unset, or blank, changes nothing.** It is read each time the adapter is resolved, never at load.
98
+ - **The name** is looked up in `config.adapters` first, then among the entries of the `config.adapter` list (so it keeps the
99
+ options it was given there, and is used even if its `available?` says `false`: asking for it by name is the point), then
100
+ the adapter you already configured that is of that registered type, then the registered adapter built with no
101
+ options. Surrounding whitespace is ignored.
102
+ - **Naming a type uses the adapter you configured of it.** With
103
+ `config.adapters = { local: { type: :openai_compatible, base_url: "http://localhost:11434/v1" } }`,
104
+ `SQUISHLING_ADAPTER=openai_compatible` uses `local` (its `base_url` and all), not a bare adapter pointed at OpenAI's
105
+ host. It looks through `config.adapters`, the entries of the `config.adapter` list, and `config.adapter` itself, and
106
+ takes an adapter of exactly that class, or, when there is none, an instance of a subclass of it. A single
107
+ `config.adapter` of exactly that class wins over the others, since it is the default the name is about. Only when
108
+ nothing configured is of that type is the registered adapter built with no options.
109
+ - **More than one configured adapter of that type is a `ConfigurationError`** naming where they are configured (such as
110
+ `config.adapters[:local]` and `config.adapters[:other]`; never their options or credentials). Set the variable to the
111
+ `config.adapters` name (or the candidate's registered name) of the one to use; one that has no name (an instance in the
112
+ candidate list) must first be given one in `config.adapters`. The same instance configured in two places counts once.
113
+ - **An unknown name** is a `ConfigurationError` listing the registered and configured names. It never repeats the
114
+ value, so one set by mistake (a key pasted into the wrong variable) is never echoed.
115
+ - **An escalation step with `adapter:` still wins for that step**: the variable replaces only the default adapter (a
116
+ step with no `adapter:`, and a judge with none). Steps that name an adapter from `config.adapters` keep it.
117
+ - **[`Squishling::Testing`](testing.md)** still wins over all of it: the scripted adapter answers for every step, so a
118
+ test run is never redirected by the variable.
119
+
120
+ `Squishling.verify` checks both at no cost: it reports a candidate list with no usable entry, and a `SQUISHLING_ADAPTER` that
121
+ names nothing or is ambiguous, once for the run. It builds adapters and calls `available?`, and makes no request.
122
+
54
123
  ## Mixing adapters in one escalation
55
124
 
56
125
  Give `config.adapters` a name for each extra adapter, and pick one per step with `adapter:`:
@@ -101,7 +170,12 @@ Each value takes anything `config.adapter` does and is built when assigned. A st
101
170
 
102
171
  Everything works as it did before adapters: configure provider API keys with `RubyLLM.configure`, name models, and
103
172
  use `provider:` for models missing from RubyLLM's registry. See [Configuration](configuration.md). Transport-level
104
- retries are RubyLLM's (`RubyLLM.config.max_retries`, `request_timeout`).
173
+ retries are RubyLLM's, so they are global, not per adapter or per step: `RubyLLM.config.max_retries` (default 3),
174
+ `retry_interval` (0.1 seconds), `retry_backoff_factor` (2), `retry_interval_randomness` (0.5), `retry_max_interval`
175
+ (30 seconds), and `request_timeout`. RubyLLM waits out a short `Retry-After` itself, but its default backoff retries a
176
+ rate limit three times inside about a second, so raise `retry_interval` (or lower `max_retries`) if a per-minute quota
177
+ is what you hit. When the provider asks for more than `retry_max_interval`, RubyLLM stops retrying at once and the
178
+ `RateLimitError` below carries that wait as `retry_after`.
105
179
 
106
180
  | Option | Default | Description |
107
181
  |---|---|---|
@@ -114,7 +188,8 @@ decides: on a 400 its middleware picks a class from the provider's message text,
114
188
  `RubyLLM::ContextLengthExceededError`, an `LLMError`, since RubyLLM is where each provider's wording for an overlong
115
189
  prompt is known. RubyLLM picks that class from the message on a 400, with wording broader than the OpenAI-compatible
116
190
  adapter's, so a bad parameter whose message happens to match is retried as an overflow rather than rejected. Each of
117
- these errors carries a sanitized `cause` (see `keep_cause` above).
191
+ these errors carries a sanitized `cause` (see `keep_cause` above). A 429 is a `Squishling::RateLimitError`, whose
192
+ `retry_after` is the response's `Retry-After` header in seconds (nil when it has none).
118
193
 
119
194
  This is the only built-in adapter that supports `type: :judgment` judges ([System One decision models](harnesses.md#the-judge)).
120
195
 
@@ -142,7 +217,7 @@ end
142
217
  | `open_timeout` / `read_timeout` | `10` / `120` | Seconds. `read_timeout` restarts at every read, so it alone doesn't bound a request. |
143
218
  | `total_timeout` | `open_timeout + 2 * read_timeout` | Seconds one attempt (each retry gets its own) may take from connecting to the last byte of the response. Past it the call fails with an `LLMError` that isn't retried by the adapter. |
144
219
  | `max_response_bytes` | `8388608` (8 MiB) | The most a response body may hold, an error body included, checked against `Content-Length` and the bytes actually read. Over it, a successful response fails with an `LLMError` that isn't retried by the adapter; a failure status drops the body and is classified by its status. Raise it only if you expect very large completions. |
145
- | `max_retries` | `2` | Timeouts, connection and protocol failures, HTTP 408, 429, and 5xx are retried this many times with exponential backoff (honoring `Retry-After`, up to 30 seconds) before they surface as an `LLMError`. A timed-out request may still have been processed by the server, so a retry can be billed twice; set `max_retries: 0` if that matters more than resilience. |
220
+ | `max_retries` | `2` | Timeouts, connection and protocol failures, HTTP 408, 429, and 5xx are retried this many times with exponential backoff (honoring `Retry-After`, up to 30 seconds) before they surface as an `LLMError` (a `RateLimitError` for a 429). A timed-out request may still have been processed by the server, so a retry can be billed twice; set `max_retries: 0` if that matters more than resilience. |
146
221
  | `max_tokens_param` | `:max_completion_tokens` | The body key for `max_output_tokens`. Use `:max_tokens` for servers that don't know the newer name. |
147
222
  | `media_types` | the four image types, plus `application/pdf` for `api.openai.com` | The [file types](inputs.md) the server takes, some of `image/png`, `image/jpeg`, `image/gif`, `image/webp`, `application/pdf`. A call with a file of another type is refused before any request; an empty list or an unknown type raises `ConfigurationError`. |
148
223
  | `structured_output` | `:json_schema` | `:json_schema` asks for strict structured output. For servers without it use `:json_object`, or `:none`: the schema then goes into the system prompt in words. Squishling validates every answer itself either way. |
@@ -162,8 +237,10 @@ keep credentials out of plain instance variables the same way, or define `encode
162
237
  the request body as given. Squishling's own keys (`model`, `messages`, `response_format`, `n`, `stream`) always win.
163
238
  `provider:` has no meaning here and is ignored.
164
239
 
165
- **Failures.** The HTTP status decides (see [the status mapping](#the-error-contract)): 408, 413, 429, 5xx, timeouts, and
166
- connection errors raise `LLMError` once the adapter's own retries are used up; 401, 402, 403, 404, and a redirect raise
240
+ **Failures.** The HTTP status decides (see [the status mapping](#the-error-contract)): 408, 413, 5xx, timeouts, and
241
+ connection errors raise `LLMError` once the adapter's own retries are used up, and a 429 raises `RateLimitError` (an
242
+ `LLMError`) whose `retry_after` is the last response's `Retry-After` header in seconds (a number of seconds or an HTTP
243
+ date; capped at an hour; nil when absent or unreadable); 401, 402, 403, 404, and a redirect raise
167
244
  `ConfigurationError`; any other 4xx (400, 409, 422, …) raises `RequestRejectedError`, never retried or escalated. The
168
245
  one exception is a 400 that reports an overlong context, which is an `LLMError` too, since it depends on the input (a
169
246
  bigger model may take it). This adapter recognizes one when the error's `code` or `type` is `context_length_exceeded`, or,
@@ -271,14 +348,16 @@ how it says a prompt is too long:
271
348
  |---|---|---|
272
349
  | `Squishling::ConfigurationError` | Bad credentials, billing, an unknown model or endpoint: anything a retry can't fix | Raised at once. Never retried, escalated, or sent to `squish_fallback`. |
273
350
  | `Squishling::RequestRejectedError` (a `ConfigurationError`) | The provider refused the request itself: a 400 or another 4xx for a bad param or schema | Same as `ConfigurationError`, so a setup mistake can't be hidden by a fallback on every call. |
274
- | `Squishling::LLMError` | Rate limit, 5xx, timeout, connection failure, an overlong context: anything worth another go | Moves to the next attempt; raised from the last one (and goes to `squish_fallback`). |
351
+ | `Squishling::LLMError` | 5xx, timeout, connection failure, an overlong context: anything worth another go | Moves to the next attempt; raised from the last one (and goes to `squish_fallback`). |
352
+ | `Squishling::RateLimitError` (an `LLMError`, with `retry_after:`) | A rate limit (HTTP 429), with the provider's `Retry-After` in seconds when it sent one | Skips the rest of its step's attempts, since the same model would hit the same quota window, and moves to the next step; raised when there is none (and goes to `squish_fallback`). |
275
353
 
276
354
  **Squishling manages** everything that follows from the class: retries, escalation, the fallback, the token budget, and
277
355
  `squawk`. It never looks at a provider's status, code, or message; it sees only the error class your adapter raised.
278
356
 
279
- For an HTTP provider, `http_failure(request, status:, body:, via:)` does the sorting, so every adapter treats a status
280
- the same way: 408, 413, 429, 5xx, no status at all (a timeout), and a success status (a reply that was unusable) are
281
- `LLMError`s; 401, 402, 403, 404, and a redirect are `ConfigurationError`s;
357
+ For an HTTP provider, `http_failure(request, status:, body:, via:, retry_after: nil)` does the sorting (pass the
358
+ `Retry-After` header's value as `retry_after:`; a 429 carries it, parsed into seconds), so every adapter treats a status
359
+ the same way: 429 is a `RateLimitError`; 408, 413, 5xx, no status at all (a timeout), and a success status (a reply
360
+ that was unusable) are `LLMError`s; 401, 402, 403, 404, and a redirect are `ConfigurationError`s;
282
361
  every other 4xx is a `RequestRejectedError`. `via` ("Acme, HTTP 400") is the only text repeated, plus the status and
283
362
  code tokens of a rejection. Between those, one case depends on the provider: a rejected request whose input was too
284
363
  long for the model should be an `LLMError`, since a bigger model may take it. `http_failure` asks the
@@ -296,6 +375,13 @@ exception propagates unwrapped and is never retried, so map your transport's err
296
375
 
297
376
  ### Optional hooks
298
377
 
378
+ - **`available?`**: whether the adapter can run here (default `true`). A list of [candidates](#choosing-from-candidates-and-squishling_adapter)
379
+ skips an adapter that returns `false`, e.g. `RUBY_PLATFORM.include?("darwin") && macos_version >= 26` for an adapter that
380
+ needs an OS feature. Keep it local and cheap: no request, no credentials check, and it must not raise (an exception
381
+ propagates out of the call, and out of `Squishling.verify`). It is called each time the adapter is resolved, from any
382
+ thread, so don't cache what can change.
383
+ - **`Squishling::Adapter::MissingGemError`**: raise it from `initialize` when the gem your adapter needs isn't installed.
384
+ It is a `ConfigurationError`, except that a list of candidates skips the entry.
299
385
  - **`judgments?` and `judge(input, questions:, step:, label:)`**: System One decision models for `type: :judgment` judges.
300
386
  `judge` returns an object answering `[:winner]` with something that responds to `choice` and `probabilities`.
301
387
  Without `judgments?`, such a judge raises `ConfigurationError` before any request. If the object has `tokens` (with
data/docs/apprentice.md CHANGED
@@ -142,6 +142,12 @@ there, and the arguments and `squish_context` values are read there, so later ch
142
142
  The rest runs in the job, against the same instance: the escalation (with any `include_when:`), `squish_validate`,
143
143
  `compare:` and the report. Keep those free of state the caller goes on to change, or use the inline runner.
144
144
 
145
+ On a background runner the Ruby result and the inputs are also copied before the call returns, so a caller that changes
146
+ either afterwards isn't seen by `compare:`, `squish_validate`, `include_when:`, or the report (`inputs:`). The inputs
147
+ are copied all the way down through their Hashes, Arrays, Sets, and Strings; anything else (a model, a Struct, an IO)
148
+ can't be copied without running its code, so it is shared, and so is the instance. On the inline runner nothing is
149
+ copied, because the call waits for the run.
150
+
145
151
  ## Identifying the request
146
152
 
147
153
  Every squished call that reaches the LLM gets a `call_id` (a UUID, or your own, from
@@ -27,8 +27,8 @@ end
27
27
 
28
28
  | Option | Default | Description |
29
29
  |---|---|---|
30
- | `adapter` | `nil` (RubyLLM, when its gem is available) | How requests reach a model: `:ruby_llm`, `:openai_compatible`, a [registered](adapters.md#writing-your-own) name, a Hash with `type:` and that adapter's options, or an adapter instance. See [Adapters](adapters.md). |
31
- | `adapters` | `{}` | More adapters by name, for escalation steps that pick one with `adapter:`. Each value takes what `adapter` does. See [Mixing adapters](adapters.md#mixing-adapters-in-one-escalation). |
30
+ | `adapter` | `nil` (RubyLLM, when its gem is available) | How requests reach a model: `:ruby_llm`, `:openai_compatible`, a [registered](adapters.md#writing-your-own) name, a Hash with `type:` and that adapter's options, or an adapter instance. A list of those, e.g. `[{ type: :apple_fm }, :ruby_llm]`, uses the first that is registered and `available?`; none usable is a `ConfigurationError` at the first call. The `SQUISHLING_ADAPTER` environment variable overrides all of it. See [Adapters](adapters.md) and [Choosing from candidates](adapters.md#choosing-from-candidates-and-squishling_adapter). |
31
+ | `adapters` | `{}` | More adapters by name, for escalation steps that pick one with `adapter:`. Each value is an adapter, a registered name, or a Hash with `type:` (not a list). See [Mixing adapters](adapters.md#mixing-adapters-in-one-escalation). |
32
32
  | `default_model` | `nil` | The universal model (a single attempt) for every squishling class that doesn't declare one. `nil` uses the adapter's own default (RubyLLM's `default_model`; the OpenAI-compatible adapter's `default_model:` option). |
33
33
  | `default_escalation` | `nil` | The universal [escalation](#models-and-escalation): models tried in order. Assigning it clears `default_model`, and vice versa. |
34
34
  | `default_provider` | `nil` | The provider for `default_model`/`default_escalation` steps that don't name one. What it means depends on the adapter: RubyLLM needs it only for models missing from its registry (see below); the OpenAI-compatible adapter ignores it. |
@@ -38,14 +38,14 @@ end
38
38
  | `budget_counts_cache_reads` | `false` | Whether the input tokens a request reads from the provider's prompt cache count toward `max_total_input_tokens`. Off by default, since reads are cheap; tokens written to the cache always count. Global only. See [Capping a call's cost](failures.md#capping-a-calls-cost-token-budgets). |
39
39
  | `squawk` | `nil` | A callable run after every LLM attempt (see `squawk_on`), and once more when a token budget or a disagreement stops the call, with the raw output, for sending it to an error tracker or tracing tool. Also settable per class and per method. See [Observing every attempt](failures.md#observing-every-attempt-squawk). |
40
40
  | `squawk_on` | `:all` | Which attempts reach the `squawk` hook: `:all`, `:rejections` (errors only), `:retries` (errors plus any accepted attempt after the first), `:final` (the last attempt the escalation allows), or a list of them (any one holding runs the hook). A call [stopped](failures.md#a-call-that-is-stopped) by a token budget or a disagreement is always reported. Also settable per class and per method. |
41
- | `outer_loop_agent` | `nil` | An around-style hook for every provider request: `:coolhand`, any object responding to `around(call)`, or `false` for none. `nil` uses the [Coolhand outer-loop agent](coolhand.md) when the `coolhand` gem is configured. See [Outer-loop agents](outer-loop-agents.md). |
41
+ | `outer_loop_agent` | `nil` | An around-style hook for every provider request: `:coolhand`, any object responding to `around(call)`, or `false` for none. `nil` uses the [Coolhand outer-loop agent](coolhand.md) when the `coolhand` gem is configured. An agent that also defines `report(output:, metadata:, error:)` is sent `squawk`'s reports (and only then sees output). See [Outer-loop agents](outer-loop-agents.md). |
42
42
  | `apprentice_report` | `nil` | The report hook of every [apprentice](apprentice.md) that doesn't declare its own `report:`: a callable taking keywords (`ruby:`, `llm:`, `match:`, `error:`, `inputs:`, `metadata:`). |
43
43
  | `apprentice_runner` | `:inline` | Where an [apprentice's](apprentice.md#running-it-in-the-background) shadow run happens: `:inline` (on the caller's thread, after the Ruby result), `:thread` (the built-in background pool), a `Squishling::Apprentice::ThreadRunner`, or any callable that takes the job and calls it. |
44
44
  | `apprentice_enabled` | `true` | Set `false` to stop every [apprentice](apprentice.md#turning-it-off) shadow run, whatever the classes declare (a kill switch). |
45
45
  | `coolhand_rejection_feedback` | `true` | Whether the [Coolhand outer-loop agent](coolhand.md#validation-feedback) sends a `dislike` feedback for each message of every rejected response. Set `false` to leave rejections out of Coolhand. Global only. |
46
46
  | `default_harness` | `nil` (`:escalation`) | How every squishling class that doesn't declare its own uses its escalation: `:escalation`, `:squishsum`, `:judged_squishsum`, a [registered custom harness](harnesses.md#custom-harnesses), or a Hash with `type:` and options. See [Harnesses](harnesses.md). |
47
47
  | `sanitizer` | `[]` | A callable, or a list of them, run over everything every squished call sends, before any class's or method's own: filter, redact, or convert inputs. Keywords `value:`, `path:`, `reject:`. None can be switched off. See [Sanitizing inputs](inputs.md#sanitizing-inputs). |
48
- | `max_files`, `max_file_bytes` | `20`, `20_000_000` | The most files one call may send, and the most bytes in one; `nil` lifts a limit. A call over one raises `InputRejectedError` before any request. See [Limits](inputs.md#limits). |
48
+ | `max_files`, `max_file_bytes`, `max_total_file_bytes` | `20`, `20_000_000`, `100_000_000` | The most files one call may send, the most bytes in one, and the most bytes in all of a call's files together; `nil` lifts a limit. A call over one raises `InputRejectedError` before any request. `Image.from_path` holds a file to `max_file_bytes` too. See [Limits](inputs.md#limits). |
49
49
  | `logger` | `nil` | Any `Logger`. Debug lines when a call routes to the LLM, warnings on each escalation and when a fallback is used. Never includes the raw model response; see [what ends up in errors and logs](failures.md#what-ends-up-in-errors-and-logs). |
50
50
 
51
51
  Transport-level retries (rate limits, 5xx, timeouts) belong to the adapter: RubyLLM's own
@@ -184,7 +184,7 @@ model-generated and is sent to the next step's provider, even when it is a diffe
184
184
  characters. If you don't want a step to see it (say, because the next step is a different provider), set
185
185
  `forward_rejected: false` on that step and it starts from the original input only. Configuration errors (bad
186
186
  credentials, an unknown model, a request the provider rejects) never move to the next attempt. A retry that returns
187
- exactly the reply the step was just told was invalid skips the step's remaining attempts and moves to the next step. See [Failure handling](failures.md).
187
+ exactly the reply the step was just told was invalid skips the step's remaining attempts and moves to the next step, and so does a rate limit (a `RateLimitError`, HTTP 429), since the same model would hit it again. See [Failure handling](failures.md).
188
188
 
189
189
  ## Providers and newly released models
190
190
 
@@ -252,9 +252,11 @@ end
252
252
  ```
253
253
 
254
254
  - Keys that Squishling or the adapter control (`model`, `messages`, `input`, `instructions`, `system`, `stream`,
255
- `response_format`, `text`, `output_config`, `tools`, `tool_choice`, `functions`, `function_call`, `schema`, and the camelCase and plural
256
- spellings other providers use, such as `systemInstruction`, `cachedContent`/`cached_content`, `toolConfig`/`tool_config`, `outputConfig`, `inputs`, …)
257
- raise `ConfigurationError`, because they would override the model, the conversation, or the strict output format.
255
+ `response_format`, `text`, `output_config`, `tools`, `tool_choice`, `functions`, `function_call`, `schema`, `preset`
256
+ (Perplexity's, which swaps the model and its instructions), and the camelCase and plural spellings
257
+ other providers use, such as `systemInstruction`, `cachedContent`/`cached_content`, `toolConfig`/`tool_config`,
258
+ `outputConfig`, `inputs`, …) raise `ConfigurationError`, because they would override the model, the conversation, or
259
+ the strict output format.
258
260
  - **Nested containers** such as Gemini's `generationConfig` (and `generation_config` for Gemini Interactions) and
259
261
  Mistral Conversations' `completion_args` accept ordinary settings, but reject the keys inside them that carry the
260
262
  output format or tools (`responseMimeType`, `responseSchema`, `responseJsonSchema`, `response_format`, `tools`,
data/docs/failures.md CHANGED
@@ -8,7 +8,8 @@ A failed attempt moves on to the next one; once the last fails, the error is rai
8
8
 
9
9
  | Failure | What Squishling does |
10
10
  |---|---|
11
- | Rate limit, 5xx, overload, timeout, connection error | The [adapter](adapters.md) retries at the HTTP level first (RubyLLM: `RubyLLM.config.max_retries`, default 3; OpenAI-compatible: `max_retries:`, default 2). If it still fails, moves to the next attempt in a fresh chat; on the last attempt, raises `Squishling::LLMError` with a `cause` when the adapter has one: the RubyLLM adapter always does, a [sanitized stand-in](#the-cause-of-a-provider-failure); the OpenAI-compatible adapter only for transport errors (the error itself, which carries no response body), not for HTTP statuses. |
11
+ | 5xx, overload, timeout, connection error | The [adapter](adapters.md) retries at the HTTP level first (RubyLLM: `RubyLLM.config.max_retries`, default 3; OpenAI-compatible: `max_retries:`, default 2). If it still fails, moves to the next attempt in a fresh chat; on the last attempt, raises `Squishling::LLMError` with a `cause` when the adapter has one: the RubyLLM adapter always does, a [sanitized stand-in](#the-cause-of-a-provider-failure); the OpenAI-compatible adapter only for transport errors (the error itself, which carries no response body), not for HTTP statuses. |
12
+ | Rate limit (HTTP 429) | The [adapter](adapters.md) retries at the HTTP level first, as above. If it still fails, the escalation does not spend the rest of that step's attempts on the same model, since another request would land in the same quota window: it moves to the next *step* in a fresh chat, and raises `Squishling::RateLimitError` (an `LLMError`, so a fallback or `rescue Squishling::LLMError` still catches it) when there is none, whatever `attempts:` the last step has. A sample or a judge that is rate limited raises it at once, and a step skipped over makes no request, so nothing is added to the token budget. See [Rate limits](#rate-limits). |
12
13
  | Bad API key, billing or quota problem (402), unknown model or endpoint (404), missing provider config | Raises `Squishling::ConfigurationError`. Never escalated, never sent to the fallback. |
13
14
  | Provider rejects the request (400 Bad Request, or another 4xx such as 409 or 422), e.g. an unsupported `temperature` or a schema it won't accept | Raises `Squishling::RequestRejectedError` (a `ConfigurationError`) naming the error class, the HTTP status, and the provider's error status/code when its body carries one (`INVALID_ARGUMENT`, `invalid_request_error`). They are also on `error.provider_status` and `error.provider_code` (nil when absent); only plain tokens are kept, never the provider's message. The message points at a param only when the provider named it, and otherwise says the params, output schema, or input may be invalid. The provider's own message is not on `cause` either unless you opt in (see [the cause of a provider failure](#the-cause-of-a-provider-failure)). It is never retried, so if you know a given code means "this input was bad", rescue it and decide for yourself. A 400 that reports an overlong input is the exception: the adapter raises an `LLMError` for it (the built-in adapters recognize the structured `context_length_exceeded` code; RubyLLM's own `ContextLengthExceededError` is honored too, and the OpenAI-compatible adapter also recognizes the usual wording of servers that send none), since a bigger model may take it. Which of the two a failure is, is the adapter's call (see [the error contract](adapters.md#the-error-contract)); a wording it doesn't recognize stays a rejected request. Never escalated, never sent to the fallback, so a setup mistake can't be silently covered up on every call. |
14
15
  | Empty or `nil` response (e.g. a refusal or a max-tokens cutoff) | Moves to the next attempt, then raises `Squishling::InvalidOutputError`. When the provider reported a max-tokens cutoff, the error says so and [`truncated?`](#a-cutoff-or-a-wrong-answer) is true. |
@@ -53,7 +54,8 @@ budget is cut off before any JSON is written.
53
54
  ### What ends up in errors and logs
54
55
 
55
56
  Model output can echo sensitive input, so the raw response is kept in one place: `InvalidOutputError#raw` (plus the
56
- opt-in `squawk` hook below, and an [apprentice's](apprentice.md) `report:` hook, which gets the LLM's typed result).
57
+ opt-in `squawk` hook below, an [outer-loop agent's `report`](outer-loop-agents.md#reports-and-output-report), which gets
58
+ the same reports, and an [apprentice's](apprentice.md) `report:` hook, which gets the LLM's typed result).
57
59
  `InvalidOutputError#message`, `#errors`, and `config.logger` warnings are built from these:
58
60
 
59
61
  - For unparseable JSON, only the position (`response was not valid JSON (at line 1 column 7)`), never the parser's
@@ -147,7 +149,9 @@ requests and raises `Squishling::BudgetExhaustedError`. It is an `InvalidOutputE
147
149
  so far (`{ input_tokens:, output_tokens: }`).
148
150
  - `errors` starts with the budget line, followed by the validation errors of the last rejected output, which is in
149
151
  `raw` (`nil` when no output was rejected, e.g. the samples were valid but there was no budget left for the judge);
150
- `attempts` and `models` are the requests made.
152
+ `attempts` and `models` describe the attempts already made. For a budget stop before a sample round, `attempts`
153
+ counts completed rounds, and each round adds its distinct models to `models` in sample order, so a retried model
154
+ appears again.
151
155
  - Like any other error message, it carries no model output.
152
156
 
153
157
  Things to know:
@@ -183,7 +187,7 @@ end
183
187
  |---|---|
184
188
  | `output` | The raw response: a Hash or String, or `nil` when the provider call itself failed |
185
189
  | `error` | `nil` for an accepted attempt. Otherwise the `InvalidOutputError` (with `errors` and `raw`) or `LLMError` that ended the attempt, or the `BudgetExhaustedError` or `DisagreementError` that stopped the call |
186
- | `metadata` | `label` (`"Class#method"`), `attempt`, `attempts` (the escalation's length, or for a [stopped call](#a-call-that-is-stopped) the attempts made; `attempt` jumps past the attempts a repeated reply skips; under a harness, the sample's or judge's own attempts), `final` (the last attempt, or a rejection after which none follows), `repeated` (`true` when the attempt returned the same reply as the one before it, in the same chat, which skips the step's remaining attempts), `model`, `provider`, `params`, `input` (the JSON sent: arguments and named context only), `usage` (token counts, when the adapter reports them), `finish_reason` (why the provider stopped, e.g. `:stop` or `:max_tokens`; `nil` when unknown or the call failed), `role` (`nil` for an escalation attempt, `:sample`, or `:judge`), `sample` (`"a"`, `"b"`, ... for a sample's attempt, else `nil`), `stopped` (`nil` for an attempt; `:budget` or `:disagreement` for the [stopped call's report](#a-call-that-is-stopped)), `call_id` (the call's id, shared by its attempts: a UUID, or your own from [`with_call_id` or `call_id:`](outer-loop-agents.md#supplying-your-own-call-id); see [Identifying the request](apprentice.md#identifying-the-request)), `apprentice` (`true` for an [apprentice's](apprentice.md) shadow run) |
190
+ | `metadata` | `label` (`"Class#method"`), `attempt`, `attempts` (the escalation's length, or for a [stopped call](#a-call-that-is-stopped) the attempts made; `attempt` jumps past the attempts a repeated reply skips; under a harness, the sample's or judge's own attempts), `final` (the last attempt, a rejection after which none follows, or, under a harness, a sample of a round that another sample's failure ends the call: the hook won't see it again, though `attempt` and `attempts` show it had attempts left), `repeated` (`true` when the attempt returned the same reply as the one before it, in the same chat, which skips the step's remaining attempts), `model`, `provider`, `params`, `input` (the JSON sent: arguments and named context only), `usage` (token counts, when the adapter reports them), `finish_reason` (why the provider stopped, e.g. `:stop` or `:max_tokens`; `nil` when unknown or the call failed), `role` (`nil` for an escalation attempt, `:sample`, or `:judge`), `sample` (`"a"`, `"b"`, ... for a sample's attempt, else `nil`), `stopped` (`nil` for an attempt; `:budget` or `:disagreement` for the [stopped call's report](#a-call-that-is-stopped)), `call_id` (the call's id, shared by its attempts: a UUID, or your own from [`with_call_id` or `call_id:`](outer-loop-agents.md#supplying-your-own-call-id); see [Identifying the request](apprentice.md#identifying-the-request)), `apprentice` (`true` for an [apprentice's](apprentice.md) shadow run) |
187
191
 
188
192
  - Set it globally with `config.squawk`, per class with `squishling squawk: ...`, or per method with
189
193
  `squish :triage, squawk: ...`. The method's hook wins over the class's, which wins over the configured one;
@@ -205,14 +209,24 @@ end
205
209
  `squish :triage, squawk_on: ...`. It resolves on its own, method then class then configured, so
206
210
  `config.squawk_on = :retries` filters every hook, including a class's own, unless that class or method overrides it.
207
211
  Under a [harness](harnesses.md), `attempt`, `attempts` and `final` count per sample or judge, so a sample's
208
- first-attempt success is skipped even while another sample retries, and `:final` fires once per sample and judge.
212
+ first-attempt success is skipped even while another sample retries, and `:final` fires once per sample and judge,
213
+ including a sample with attempts left when another sample's failure ends the call.
209
214
  - Any object that responds to `call` works. The hook receives only the keywords it declares, unless it takes `**`,
210
215
  so a lambda that wants just `error:` is fine and new metadata fields won't break it.
211
216
  - It runs inline, so keep it quick. Exceptions it raises propagate unchanged and fail the call, like any of your own
212
217
  code, so rescue inside the hook if an outage in your tracing tool shouldn't.
213
218
  - `output` is the same object the result is built from, so treat it as read-only.
219
+ - An [outer-loop agent](outer-loop-agents.md#reports-and-output-report) that defines `report(output:, metadata:, error:)`
220
+ is sent the same reports, under the same `squawk_on:` and `squawk: false` rules, after the hook. It is the only way an
221
+ outer-loop agent receives output, and only by defining that method.
214
222
  - Under a [harness](harnesses.md), it runs for every sample and judge attempt too, each with its own `input`, and
215
223
  `role`/`sample` say which one it was. A [custom harness](harnesses.md#reporting-to-squawk) reports the same way.
224
+ A round checks every sample (`squish_validate`, a field's `validate:`) before it reports any, so the squawk hook and
225
+ the outer-loop agent's rejection reports hear nothing from a round in which your own check raises. When a sample
226
+ fails for good (on its last attempt, or with a repeated reply), the other samples of that round are still reported
227
+ before its error is raised; those that failed or were rejected, with attempts left or not, carry `final: true`,
228
+ since the call is ending. An exception your own code raises for one of them (in `squish_validate`, a field's
229
+ `validate:`, the hook, or an outer-loop agent) propagates in place of that error.
216
230
  - It isn't called for a `ConfigurationError`, for deterministic and fallback returns, or for an attempt where your own
217
231
  `squish_validate` raises (that exception propagates first).
218
232
 
@@ -272,18 +286,41 @@ end
272
286
  |---|---|
273
287
  | `Squishling::Error` | Base class for everything below. Raised directly for misuse at call time, e.g. `result` or `squish!` called outside a squished method |
274
288
  | `Squishling::ConfigurationError` | Missing purpose or schema, a non-strict schema, an argument that isn't plain data and has no `to_squishling`, invalid or reserved params, an invalid `model:`/`escalation:` declaration, an invalid `append_to_purpose` item or unavailable source, bad credentials, an unknown model, a request the provider rejects (a 400 or other rejected 4xx, as `RequestRejectedError`, with `provider_status` and `provider_code`) |
275
- | `Squishling::InputRejectedError` | An input was refused before any request: a sanitizer's `reject`, a file over `max_files`/`max_file_bytes`, empty, unreadable, or of a type no adapter sends. `rejections` lists each problem with the input's `path`, never its value. Not a `ConfigurationError`: never retried, escalated, or absorbed by `squish_fallback`. See [Inputs](inputs.md) |
289
+ | `Squishling::InputRejectedError` | An input was refused before any request: a sanitizer's `reject`, a file over `max_files`/`max_file_bytes`/`max_total_file_bytes`, empty, unreadable, or of a type no adapter sends. `rejections` lists each problem with the input's `path`, never its value. Not a `ConfigurationError`: never retried, escalated, or absorbed by `squish_fallback`. See [Inputs](inputs.md) |
276
290
  | `Squishling::InvalidOutputError` | LLM output still invalid (schema or `squish_validate`) after every attempt in the escalation, or a deterministic/fallback return that doesn't match the schema |
277
291
  | `Squishling::DisagreementError` | A subclass of `InvalidOutputError`: a [squishsum harness](harnesses.md#when-the-harness-fails)'s samples disagreed and no judge accepted either. `candidates`, `verdict`, and `reason` describe what happened |
278
292
  | `Squishling::BudgetExhaustedError` | A subclass of `InvalidOutputError`: the call used up its [token budget](#capping-a-calls-cost-token-budgets) before an attempt was accepted. `limit`, `max`, and `used` describe the budget |
279
293
  | `Squishling::LLMError` | The provider call failed on the last attempt in the escalation, after the adapter's own retries, including context-length errors (`cause` holds a [sanitized stand-in](#the-cause-of-a-provider-failure), when the adapter has one) |
294
+ | `Squishling::RateLimitError` | A subclass of `LLMError`: the provider rate limited the request (HTTP 429) after the adapter's own retries. `retry_after` is the provider's wait in seconds (nil when it sent no `Retry-After`), see [Rate limits](#rate-limits) |
280
295
 
281
296
  Errors raised by your own Ruby code are not wrapped.
282
297
 
298
+ ## Rate limits
299
+
300
+ A 429 raises `Squishling::RateLimitError`, an `LLMError` that carries `retry_after`: the provider's `Retry-After`
301
+ header in seconds (a number of seconds or an HTTP date, capped at an hour), or `nil` when it sent none or the value
302
+ isn't readable. Matching the error's message is never needed:
303
+
304
+ ```ruby
305
+ begin
306
+ TicketTriager.new.call(text: body)
307
+ rescue Squishling::RateLimitError => e
308
+ RetryJob.set(wait: e.retry_after || 60).perform_later(body) # requeue with the provider's own delay
309
+ end
310
+ ```
311
+
312
+ Both adapters retry a 429 themselves first (the OpenAI-compatible adapter honoring `Retry-After`, RubyLLM with its
313
+ global `retry_*` settings: see [the adapters](adapters.md#ruby_llm)). What is left is quota that a retry within the next
314
+ second or two won't clear, so Squishling doesn't spend another same-model attempt on it: the rest of that step's
315
+ `attempts:` are skipped and the escalation continues with the next step (a different model or provider, which has
316
+ its own quota). With no next step the `RateLimitError` is raised, or handed to `squish_fallback` like any
317
+ `LLMError`. `squawk` still reports each failed attempt, with `final: true` on the one that ends the call; the skipped
318
+ attempts make no request and report nothing. Squishling never sleeps: waiting is yours to do with `retry_after`.
319
+
283
320
  ## Fallbacks
284
321
 
285
322
  Use `squish_fallback` to decide what happens when the LLM path fails with `InvalidOutputError` (including a
286
- `DisagreementError` or `BudgetExhaustedError`) or `LLMError`. It's the one fallback for every [harness](harnesses.md).
323
+ `DisagreementError` or `BudgetExhaustedError`) or `LLMError` (a `RateLimitError` too). It's the one fallback for every [harness](harnesses.md).
287
324
  It receives the error plus the method's inputs as keywords, and runs against the instance:
288
325
 
289
326
  ```ruby
data/docs/harnesses.md CHANGED
@@ -62,7 +62,8 @@ Both samples run on the escalation's first step, with its model, provider, and p
62
62
  `chat.ruby_llm`) do see each sample's request on its worker thread, outside the Rails executor, so keep them thread-safe.
63
63
  - **Each one is retried like an escalation step.** A sample with invalid output is re-asked in its own chat, up to
64
64
  the first step's `attempts:`, while a sample that already passed keeps its result. A failed request gets a fresh
65
- chat. A sample still failing after its attempts fails the call with `InvalidOutputError` or `LLMError`, as
65
+ chat, except after a rate limit, which fails the call with `RateLimitError` at once (the same model would hit it
66
+ again). A sample still failing after its attempts fails the call with `InvalidOutputError` or `LLMError`, as
66
67
  usual. Later escalation steps are never used for samples (a judge may use the next one, see
67
68
  [The judge](#the-judge)).
68
69
  - **Agreement is exact by default.** Free-text fields seldom match word for word, so pass `compare:` to decide
@@ -131,8 +132,9 @@ Squishling asks one `choice` question (`a`, `b`, or `neither`), with the judge p
131
132
  operation's purpose, input, output schema, and candidates as the judgment input. A pick of `a` or `b` is
132
133
  accepted only when its probability is at least `min_confidence:` (default `0.8`). Otherwise, as with `neither`,
133
134
  `DisagreementError` is raised with the choice and its probability in its `reason`. A judgment judge sends only its own
134
- `params:` (as RubyLLM `provider_options:`). `attempts:` retries a failed request. Judgments are a RubyLLM feature, so
135
- they need the `:ruby_llm` adapter, with the provider's credentials configured in RubyLLM as usual.
135
+ `params:` (as RubyLLM `provider_options:`). `attempts:` retries a failed request (not a rate limit, which raises
136
+ `RateLimitError` at once). Judgments are a RubyLLM feature, so they need the `:ruby_llm` adapter, with the provider's
137
+ credentials configured in RubyLLM as usual.
136
138
 
137
139
  ### The default judge prompt
138
140
 
@@ -180,7 +182,8 @@ and the judge's included. When it is spent before the next round of retries or b
180
182
  `BudgetExhaustedError` (also an `InvalidOutputError`, and also sent to the fallback) instead of a `DisagreementError`.
181
183
 
182
184
  Other failures are unchanged. A sample or judge that never produces valid output raises `InvalidOutputError`, a
183
- failed request on the last attempt raises `LLMError`, and setup mistakes (including a provider 400 on either
185
+ failed request on the last attempt raises `LLMError` (a rate limit raises `RateLimitError` at once, since the same
186
+ model would hit it again), and setup mistakes (including a provider 400 on either
184
187
  sample) raise `ConfigurationError`, which is never sent to the fallback.
185
188
 
186
189
  ## Custom harnesses
@@ -316,7 +319,8 @@ catch a hand-built value.
316
319
  A harness fails the way the built-ins do, so `squish_fallback` and the error classes behave predictably:
317
320
 
318
321
  - **Attempts run out.** `run.escalate` and `run.samples` raise `InvalidOutputError` (invalid output after the last
319
- attempt) or `LLMError` (a failed request on the last attempt) themselves, with the same attributes as always.
322
+ attempt) or `LLMError` (a failed request on the last attempt, or a `RateLimitError` at once) themselves, with the
323
+ same attributes as always.
320
324
  - **Your rule rejects.** Raise one of those errors yourself. `Squishling::DisagreementError.new(candidates:,
321
325
  models:)` is the one for samples that don't agree, and `Squishling::InvalidOutputError.new(errors: [...],
322
326
  source: "Harness")` for anything else. Both go to [`squish_fallback`](failures.md#fallbacks). A String error is
data/docs/images.md CHANGED
@@ -28,7 +28,7 @@ Which files are recognized, and how, is on [Inputs](inputs.md#passing-files-dire
28
28
 
29
29
  | | |
30
30
  |---|---|
31
- | `Squishling::Image.from_path(path)` | Reads the file. The media type comes from the bytes (or the extension). |
31
+ | `Squishling::Image.from_path(path)` | Reads the file. The media type comes from the bytes (or the extension). A file over `max_file_bytes` raises `InputRejectedError` before it is read. |
32
32
  | `Squishling::Image.new(data: bytes)` | Bytes you already have (an upload, an ActiveStorage download). Pass `media_type:` if it can't be read from them. |
33
33
  | `Squishling::Image.from_url(url, media_type: nil)` | An http(s) URL the provider fetches itself. Nothing is downloaded here, so the URL has to be reachable from the provider (a signed URL works). The media type is the one you give, or the one the path's extension says (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`); a URL with neither (`/files/123?sig=...`) needs `media_type:` with the RubyLLM adapter. |
34
34
 
@@ -87,7 +87,7 @@ An image is input, like any argument: it goes to the provider (and to a judge's
87
87
  `Image#inspect`, `#to_s`, `#as_json`, `#to_json`, and YAML describe the image (media type and size, or the URL without its
88
88
  query or credentials), so an image that ends up in a log line, an error, or a serialized object carries no content. `Marshal.dump` of an
89
89
  image raises `TypeError`: keep the bytes (or a URL) in your own storage and build the `Image` where the call is made.
90
- `squawk` reports carry the JSON input with its placeholders, never the bytes, and outer-loop agents never see input.
90
+ `squawk` reports carry the JSON input with its placeholders, never the bytes. Outer-loop agents never see input through `around`; one that defines [`report`](outer-loop-agents.md#reports-and-output-report) gets the same report (and so the same `input`) as `squawk`.
91
91
 
92
92
  Images are billed as input tokens by the provider, and the [token budget](failures.md#capping-a-calls-cost-token-budgets)
93
93
  counts them through the usage the provider reports. [Prompt caching](configuration.md#prompt-caching) still caches the