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
data/docs/inputs.md CHANGED
@@ -55,8 +55,9 @@ every object except a `String` (a String subclass is sent as its own text), `Ima
55
55
  as containers (their members, elements, or message), before any file shape is considered.
56
56
 
57
57
  A file that is empty, can't be read, or is over a limit raises `InputRejectedError` before any request, naming where it
58
- was (`arguments.scan`) but never the file. A Hash key that isn't a plain identifier (a name, an MRN) appears as `[key]` in
59
- that path. A binary String that is neither a known file nor UTF-8 text is refused too.
58
+ was (`arguments.scan`) but never the file. Only an identifier-shaped Symbol Hash key (a name you chose in code)
59
+ appears in that path; every String key, identifier-shaped or not (`"MRN12345"`, `"jane_doe"`), appears as `[key]`. A
60
+ binary String that is neither a known file nor UTF-8 text is refused too.
60
61
 
61
62
  ### Arrays of files
62
63
 
@@ -70,12 +71,19 @@ call's final files are counted once more. Filter your own Array first to send on
70
71
 
71
72
  ### Limits
72
73
 
73
- `config.max_files` (20) and `config.max_file_bytes` (20 MB, per file) bound a call, explicit `Squishling::Image`s and
74
- `Squishling::Document`s included; set either to `nil` to lift it. A file's size is checked before it is read when it is
75
- known (a blob's `byte_size`, a `File`'s size), and a stream of unknown size is read no further than one byte past the
76
- limit, so an oversized file is refused without being loaded whole. A file always goes inline with the request: the
77
- RubyLLM adapter turns off RubyLLM's automatic upload of large files to a provider's Files API. Text isn't capped by
78
- these: bound it in a sanitizer, or with a [token budget](failures.md#capping-a-calls-cost-token-budgets).
74
+ `config.max_files` (20), `config.max_file_bytes` (20 MB, per file), and `config.max_total_file_bytes` (100 MB, all of a
75
+ call's files together) bound a call, explicit `Squishling::Image`s and `Squishling::Document`s included; set any to
76
+ `nil` to lift it. A file's size is checked before it is read when it is known (a blob's `byte_size`, a `File`'s size),
77
+ and a stream of unknown size is read no further than one byte past the limit, so an oversized file is refused without
78
+ being loaded whole. A file always goes inline with the request: the RubyLLM adapter turns off RubyLLM's automatic upload
79
+ of large files to a provider's Files API. For `max_total_file_bytes`, a file that wouldn't fit in what the files already
80
+ read leave is refused the same way, unread, and the total is checked once more over the files the call sends (an
81
+ explicit `Image` or `Document` passed twice counts once, as it is sent once; a file read from a blob, path, or stream
82
+ counts each time it is read). Each file is held in memory several times over (its bytes, its base64 data URI, the JSON
83
+ body), and concurrent [samples](harnesses.md) multiply that, so lower the total if your calls run in small processes;
84
+ the default is in line with what providers' request limits allow. `Squishling::Image.from_path` holds a file to
85
+ `max_file_bytes` as well, raising `InputRejectedError` before reading it. Text isn't capped by these: bound it in a
86
+ sanitizer, or with a [token budget](failures.md#capping-a-calls-cost-token-budgets).
79
87
 
80
88
  ## Sanitizing inputs
81
89
 
@@ -131,8 +139,13 @@ process as input. The squawk report's `input`, a judge, and escalation all build
131
139
  - The purpose and `append_to_purpose` (your own text and source).
132
140
  - The Ruby path, `squish_when`, and `squish_fallback`, which get the input as it was passed. An
133
141
  [apprentice](apprentice.md) therefore compares the Ruby result on the raw input with the model's on the sanitized one.
134
- - Hash keys, which are never offered: don't put values in them. (They are masked in an error's path, not in what
135
- is sent.)
142
+ - Hash keys. A sanitizer is offered every value, never a key, so it can neither redact nor reject one, and a key is
143
+ sent to the model as it is. Squishling treats keys as schema (field names you chose), not data, and a sanitizer is
144
+ about data, so don't put an identifier (a name, an MRN, an email) in a key: key the Hash by a field name and put the
145
+ identifier in a value, where a sanitizer can reach it. The same rule keeps keys out of error messages: an
146
+ `InputRejectedError` path quotes a Symbol key and masks every String key as `[key]`, since a String key may be data
147
+ and error trackers collect messages. (A Symbol key can't be told from a name you chose, so it is quoted: don't build
148
+ Symbols from data either, as `JSON.parse(symbolize_names: true)`, `symbolize_keys`, or `OpenStruct.new(hash)` would.)
136
149
  - What the model returns: a rejected output is forwarded to the next escalation step as the model wrote it.
137
150
  - Your own `squish_validate` and field `validate:` code, which get the raw input as keywords. A message they return goes
138
151
  back to the model in the re-ask, into `InvalidOutputError#message`, and to any outer-loop agent that defines
@@ -104,7 +104,7 @@ end
104
104
  Squishling.configure { |config| config.outer_loop_agent = SpendAgent.new }
105
105
  ```
106
106
 
107
- An outer-loop agent sees usage, never the model's output or your inputs. See [Outer-loop agents](outer-loop-agents.md) for the `call` fields
107
+ Through `around`, an outer-loop agent sees usage, never the model's output or your inputs (only one that defines [`report`](outer-loop-agents.md#reports-and-output-report) is sent `squawk`'s reports). See [Outer-loop agents](outer-loop-agents.md) for the `call` fields
108
108
  and the rules.
109
109
 
110
110
  ### OpenTelemetry
@@ -140,10 +140,10 @@ route out of your process, and they see both sides:
140
140
  model's responses. Coolhand sends them to coolhandlabs.com unless you point `config.base_url` at an endpoint of your
141
141
  own.
142
142
  - **A `squawk` hook that forwards `output:` or `metadata[:input]`** sends model output and your inputs wherever you
143
- send them. That is the sanctioned route for model output; see
143
+ send them. That is a sanctioned route for model output (an [outer-loop agent's `report`](outer-loop-agents.md#reports-and-output-report) is the other); see
144
144
  [Observing every attempt](failures.md#observing-every-attempt-squawk). The examples above log only metadata.
145
145
  - **OpenTelemetry** with RubyLLM's tracer records usage and request settings, not message text.
146
146
  - **An outer-loop agent** sees timing, token usage, and the call's metadata (method, model, level), never the model's output or
147
- your inputs.
147
+ your inputs, unless it defines [`report`](outer-loop-agents.md#reports-and-output-report).
148
148
 
149
149
  Check what your tool stores before pointing it at inputs that contain personal data.
@@ -25,8 +25,10 @@ outer-loop agent are visible to the HTTP call. What `around` returns is ignored.
25
25
  raises `ConfigurationError`.
26
26
 
27
27
  An outer-loop agent *observes* the loop; it does not steer it. It sees the request's metadata, its token usage, and (if it
28
- asks for them) the failure messages of rejected responses. It never sees the method's inputs, its context, or the model's
29
- output. What it returns is ignored, and it can't change the request, the retries, or the result.
28
+ asks for them) the failure messages of rejected responses. Through `around` it never sees the method's inputs, its context,
29
+ or the model's output; it sees the model's output (and the sanitized `input`, as `squawk` does) only if it defines a
30
+ [`report`](#reports-and-output-report) method on purpose. What it returns is
31
+ ignored, and it can't change the request, the retries, or the result.
30
32
 
31
33
  > **Renamed from "observer".** Before this rename it was `config.observer`, `Squishling::Observer`,
32
34
  > `Squishling::Observers::Coolhand`, and `Squishling::Testing::Observer`. The old names are gone, with no aliases:
@@ -50,7 +52,7 @@ class SpendAgent
50
52
  end
51
53
  ```
52
54
 
53
- Usage never includes the model's output; Squishling returns the real response to its own caller, whatever `around`
55
+ Neither `Usage` nor the `call` includes the model's output; Squishling returns the real response to its own caller, whatever `around`
54
56
  returns. If the request fails, the error is raised through `yield`, so a `begin/ensure` in `around` still runs.
55
57
 
56
58
  ## `config.outer_loop_agent`
@@ -84,11 +86,11 @@ Anything else raises `ConfigurationError` when you assign it.
84
86
  | `request_id` | This request: `"<call_id>.<n>"`, numbered in the order the call's requests start |
85
87
  | `apprentice` | `true` for the requests of an [apprentice's](apprentice.md) shadow run, else `false` |
86
88
 
87
- It carries metadata, plus the rendered `purpose`. The method's inputs, its context, and the model's output never reach an
88
- outer-loop agent (the two exceptions are an apprentice's Ruby result, which `apprentice(review)` gets, and the failure messages
89
- `invalid_output(rejection)` gets, which can quote a key name the model chose or a value your own validators put in
90
- their messages; see below): it gets the request's token [`Usage`](#what-yield-returns) back, and `squawk` is the route
91
- for output.
89
+ It carries metadata, plus the rendered `purpose`. The method's inputs, its context, and the model's output never reach
90
+ `around`: it gets the request's token [`Usage`](#what-yield-returns) back, and output comes only through
91
+ [`report`](#reports-and-output-report) (or [`squawk`](failures.md#observing-every-attempt-squawk)). (The other exceptions
92
+ are an apprentice's Ruby result, which `apprentice(review)` gets, and the failure messages `invalid_output(rejection)`
93
+ gets, which can quote a key name the model chose or a value your own validators put in their messages; see below.)
92
94
 
93
95
  ## Supplying your own call id
94
96
 
@@ -196,9 +198,54 @@ your own messages to the field and the constraint, never the value.
196
198
  It carries messages, never the response. The [Coolhand outer-loop agent](coolhand.md#validation-feedback) uses it to send each
197
199
  message as feedback on the request. An exception it raises propagates, like any outer-loop agent's.
198
200
 
201
+ ## Reports and output (`report`)
202
+
203
+ An outer-loop agent that defines `report(output:, metadata:, error:)` is sent the same reports [`squawk`](failures.md#observing-every-attempt-squawk)
204
+ makes, so one object can both wrap the request and record what came back, instead of also configuring a `squawk` hook:
205
+
206
+ ```ruby
207
+ class TracingAgent
208
+ def around(call, &) = Tracer.in_span("squishling #{call.label}", &)
209
+
210
+ def report(output:, metadata:, error:)
211
+ Tracer.current_span.add_event("attempt", attributes: { "attempt" => metadata[:attempt], "ok" => error.nil? })
212
+ ErrorTracker.capture(error, extra: { output: }) if error
213
+ end
214
+ end
215
+ ```
216
+
217
+ The keywords, and every `metadata` key (`attempt`, `final`, `repeated`, `role`, `sample`, `stopped`, `call_id`,
218
+ `apprentice`, ...), are those of `squawk`: see its [table](failures.md#observing-every-attempt-squawk). `report` takes
219
+ only the keywords it declares, or all of them with `**`; it is checked when you assign the agent, so a `report` that takes
220
+ positional arguments, or requires an unknown keyword, raises `ConfigurationError` at setup.
221
+
222
+ This is the one place output reaches an outer-loop agent, and it only does if the agent defines `report`. An agent
223
+ with only `around` (or `apprentice`, or `invalid_output`) is never sent output, so output can't reach an agent by
224
+ accident. Like `apprentice` and `invalid_output`, it is called only when the agent defines it, an exception it raises
225
+ propagates unchanged, and it runs on the thread that makes the report: the caller's, for samples too, since only a
226
+ sample's request runs on a worker. The Coolhand outer-loop agent doesn't define `report`.
227
+
228
+ **It follows squawk's scoping.** `report` is another destination for squawk's reports, not a second mechanism with its
229
+ own rules:
230
+
231
+ - `squawk_on:` (config, class, method) narrows what `report` receives exactly as it does the `squawk` hook, and a
232
+ [stopped call](failures.md#a-call-that-is-stopped) is reported to it once, with no output.
233
+ - `squawk: false` (on a method, a class, or `config.squawk`) silences `report` too. That is the per-class and
234
+ per-method off switch for output leaving the process, so a class that handles sensitive data can still opt out, and
235
+ an agent can't route around it.
236
+ - Nothing else is needed: `report` is called whether or not a `squawk` hook is also set. With both, the `squawk` hook
237
+ runs first, and an exception it raises propagates before `report` is called for that attempt.
238
+
239
+ A method named `report` on an outer-loop agent is taken as this hook, so an agent that already had an unrelated
240
+ `report` needs it renamed (one with positional arguments raises `ConfigurationError` when assigned).
241
+
242
+ `squawk` itself is unchanged and stays the way to send output somewhere for one class or method, with a hook of its
243
+ own. Use `squawk` for a per-class sink (this class's rejections to an error tracker), and `report` when the tool that
244
+ wraps your requests should also get what came back.
245
+
199
246
  ## Errors
200
247
 
201
- An outer-loop agent is your code: an exception it raises propagates unchanged, and is never retried, escalated, or handed to
248
+ An outer-loop agent is your code: an exception it raises (from `around`, `report`, or any optional method) propagates unchanged, and is never retried, escalated, or handed to
202
249
  `squish_fallback`. Squishling maps a failed request onto `LLMError` or `ConfigurationError` inside the block, so `around` sees those and
203
250
  can rescue them or let them pass. If `around` rescues one and returns normally, Squishling raises it again: an
204
251
  outer-loop agent can watch a failure, not swallow it.
data/docs/schemas.md CHANGED
@@ -33,7 +33,9 @@ output_schema(
33
33
  A raw schema's `$ref`s must point inside the schema (`"#/$defs/address"`). Squishling resolves them when it builds the
34
34
  schema, so one that points nowhere (a remote URI, which is never fetched, or a `$defs` entry that doesn't exist)
35
35
  raises `Squishling::ConfigurationError` then, and [`Squishling.verify`](verifying.md) reports it, instead of failing on
36
- the first response.
36
+ the first response. So does one that leads back to itself while still describing the same value (an alias of itself, or a
37
+ union that includes itself), since no output could ever be checked against it. Recursion through an object's
38
+ `properties` or an array's `items` is fine.
37
39
 
38
40
  ## Describing fields
39
41
 
data/docs/testing.md CHANGED
@@ -59,7 +59,8 @@ A reply is one of:
59
59
 
60
60
  | Intent | Raises |
61
61
  |---|---|
62
- | `:rate_limit`, `:server_error`, `:overloaded`, `:timeout`, `:context_length` | `LLMError` (the next attempt is tried) |
62
+ | `:server_error`, `:overloaded`, `:timeout`, `:context_length` | `LLMError` (the next attempt is tried) |
63
+ | `:rate_limit` (with `retry_after:` seconds, e.g. `.fail(:rate_limit, retry_after: 30)`) | `RateLimitError`, an `LLMError` (the next step is tried, not the same model again) |
63
64
  | `:bad_request`, `:unauthorized`, `:forbidden` | `ConfigurationError` (never retried, never given to a fallback) |
64
65
 
65
66
  **Selecting what a rule answers.** `step(model)`, `step(provider: :vertexai)`, `step(adapter: :local)`, and `step(:any)`
@@ -135,7 +136,7 @@ stub_squishling_result(PatternGenerator, regex: "x") { ... } #
135
136
  stub_squishling_result(IsUrgent, false) # a boolean or nullable schema: any one value
136
137
 
137
138
  stub_squishling_error(PatternGenerator, :invalid_output, errors: ["bad"], raw: "{}", attempts: 2, models: %w[a b])
138
- stub_squishling_error(PatternGenerator, :llm_error) # also :configuration, :disagreement (candidates:, verdict:, reason:)
139
+ stub_squishling_error(PatternGenerator, :llm_error) # also :rate_limit (retry_after:), :configuration, :disagreement (candidates:, verdict:, reason:)
139
140
  ```
140
141
 
141
142
  Attributes that don't satisfy the method's `output_schema` raise `Squishling::Testing::SetupError` when you stub, so a
@@ -185,7 +186,9 @@ The capture also records the [report of a stopped call](failures.md#a-call-that-
185
186
 
186
187
  An outer-loop agent you configured *before* `fake_squishling` keeps working while the fake is installed (it is chained behind
187
188
  the fake's own). Configure it first: one assigned afterwards replaces the fake's, and then sample and judge scripts
188
- can't tell which request is which.
189
+ can't tell which request is which. If that agent defines [`report`](outer-loop-agents.md#reports-and-output-report), it is
190
+ sent the scripted replies as output like any reports (`with_squawk` doesn't stop it); the fake's agent passes `report`
191
+ on only when yours defines one.
189
192
 
190
193
  ## Apprentice mode
191
194
 
data/docs/verifying.md CHANGED
@@ -28,13 +28,14 @@ For each squished method (inherited ones too, with the subclass's settings) it c
28
28
 
29
29
  - **The output schema:** that it builds (and is strict), is valid JSON Schema, and produces a typed result, so a
30
30
  property name that can't be a result member (`total=`), an object with `properties` but no `type: "object"`, or a
31
- `$ref` that doesn't resolve within the schema (a remote URI is never fetched; a missing `$defs` entry) is reported.
32
- A method with no output schema or no purpose is reported, because its LLM path would raise. The default `call`
33
- method is skipped when you don't implement or configure it.
31
+ `$ref` that doesn't resolve within the schema (a remote URI is never fetched; a missing `$defs` entry) or leads back
32
+ to itself without reaching a property or an item is reported. A method with no output schema or no purpose is
33
+ reported, because its LLM path would raise. The default `call` method is skipped when you don't implement or
34
+ configure it.
34
35
  - **What the layers resolve to:** the escalation, generation params and `squawk` that the method, its class and
35
36
  `Squishling.config` add up to.
36
- - **Each `squish_rescue`:** the escalation, params, adapters and harness a rescue's options resolve to, reported
37
- under `Class#method squish_rescue`.
37
+ - **Each `squish_rescue`:** the escalation (including each step's `include_when:` keywords), params, adapters and
38
+ harness a rescue's options resolve to, reported under `Class#method squish_rescue`.
38
39
  - **The harness:** that it is still registered (not removed or replaced since the class declared it), and that a
39
40
  `type: :judgment` judge has an adapter that supports judgments.
40
41
  - **Keywords:** that each `include_when:` and the `squish_when` block can be called with the method's inputs as keywords
@@ -49,7 +50,11 @@ For each squished method (inherited ones too, with the subclass's settings) it c
49
50
  - **`squish_sanitize`:** that each sanitizer, at every level, is a callable that takes keywords only.
50
51
  - **Field rules:** that each [`validate:`](schemas.md#rules-for-one-field-validate) rule responds to `call`, and that a
51
52
  Proc rule takes the value, has no required keyword that isn't an input, and (as a lambda) accepts every input.
52
- - **The adapter** (once): that `config.adapter`, or RubyLLM's, can be built. When `config.adapters` names others, that
53
+ - **The adapter** (once): that `config.adapter`, or RubyLLM's, can be built; for a [list of candidates](adapters.md#choosing-from-candidates-and-squishling_adapter),
54
+ that at least one is registered, has its gem, and is `available?`; and, when set, that
55
+ `SQUISHLING_ADAPTER` names a registered or configured adapter and isn't ambiguous (more than one configured adapter of
56
+ that type; checked once even when `config.adapters` names others, since it replaces the default adapter for every
57
+ step). Only adapters are built and `available?` asked; no request is made. When `config.adapters` names others, that
53
58
  check moves to each method: every `adapter:` a step or judge names must be configured, and the default adapter is
54
59
  only checked for the steps that use it.
55
60
 
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Squishling
4
+ module Adapter
5
+ # An ordered list of adapters for config.adapter, tried first to last (see Candidates.build): the first one that is
6
+ # registered, whose gem is available, and that says it is #available? is the adapter requests go through. Which
7
+ # entry is usable is decided each time it is asked (#select), never cached, and the list is shared across threads.
8
+ class Candidates
9
+ # One entry of the list. type is its registered name (nil for an instance), label what messages call it, adapter
10
+ # the adapter built when the list was assigned, and skipped why there is none. An entry that wasn't registered
11
+ # then keeps its value (source, a Secret, since it may hold an API key) and where it came from, to be built once
12
+ # it is registered. Its inspect is the label only.
13
+ Entry = Data.define(:type, :label, :adapter, :skipped, :source, :where) do
14
+ def inspect
15
+ "#<entry #{label}>"
16
+ end
17
+ alias_method :to_s, :inspect
18
+ end
19
+
20
+ UNREGISTERED = "not registered; is its gem in the bundle and loaded?"
21
+ MISSING_GEM = "its gem isn't available"
22
+ UNAVAILABLE = "it reports it can't run here (available? is false)"
23
+ private_constant :UNREGISTERED, :MISSING_GEM, :UNAVAILABLE
24
+
25
+ class << self
26
+ # The list for an Array of config.adapter values (anything Adapter.build takes). A registered type is built now,
27
+ # so a bad option fails at setup. One that isn't registered, or whose gem is missing (an
28
+ # Adapter::MissingGemError), is skipped, not an error, since a candidate is expected to be absent somewhere (a
29
+ # dev-only gem in production); an unregistered one is built when it is registered later, whenever that happens.
30
+ # An empty list, or an entry that is none of the kinds, is a ConfigurationError.
31
+ def build(list, where)
32
+ raise ConfigurationError, "#{where} adapter: a list of adapters can't be empty" if list.empty?
33
+
34
+ new(list.each_with_index.map { |value, index| entry(value, "#{where} entry #{index}") })
35
+ end
36
+
37
+ private
38
+
39
+ def entry(value, where)
40
+ type = type_of(value)
41
+ return built(type, value, where) if type.nil? || Registry.fetch(type)
42
+
43
+ Entry.new(type:, label: type.inspect, adapter: nil, skipped: UNREGISTERED, source: Secret.new(value), where:)
44
+ rescue MissingGemError
45
+ Entry.new(type:, label: type.inspect, adapter: nil, skipped: MISSING_GEM, source: nil, where:)
46
+ end
47
+
48
+ def built(type, value, where)
49
+ adapter = Adapter.build(value, where)
50
+ label = type ? type.inspect : "an instance of #{adapter.class}"
51
+ Entry.new(type:, label:, adapter:, skipped: nil, source: nil, where:)
52
+ end
53
+
54
+ # The registered name a Symbol, String or Hash value names; nil for an instance (or anything Adapter.build
55
+ # rejects, which then reports it).
56
+ def type_of(value)
57
+ name = value.is_a?(Hash) ? value.transform_keys(&:to_sym)[:type] : value
58
+ name.to_s.to_sym if name.is_a?(Symbol) || name.is_a?(String)
59
+ end
60
+ end
61
+
62
+ def initialize(entries)
63
+ @entries = entries.freeze
64
+ @late = {}.compare_by_identity
65
+ @lock = Mutex.new
66
+ end
67
+
68
+ # The first usable adapter. Raises ConfigurationError, naming each candidate and why it was skipped, when none is.
69
+ # An adapter's own #available? that raises propagates.
70
+ def select
71
+ skipped = @entries.filter_map do |entry|
72
+ adapter, reason = resolve(entry)
73
+ reason ||= (UNAVAILABLE unless available?(adapter))
74
+ return adapter unless reason
75
+
76
+ "#{entry.label} (#{reason})"
77
+ end
78
+ raise ConfigurationError, "config.adapter has no usable adapter; skipped #{skipped.join(', ')}. " \
79
+ "End the list with an adapter that is always there, such as :ruby_llm with its gem"
80
+ end
81
+
82
+ # The built adapter of the entry of this registered name, whether or not it is #available?; nil if there is none.
83
+ def named(name)
84
+ @entries.filter_map { |entry| resolve(entry).first if entry.type == name }.first
85
+ end
86
+
87
+ # ["entry N (label)", adapter] for each entry of klass (or a subclass) that has an adapter now (built, or
88
+ # registered since), usable or not. An entry that isn't of klass is never built here.
89
+ def built(klass)
90
+ @entries.each_with_index.filter_map do |entry, index|
91
+ adapter = resolve(entry).first if of?(entry, klass)
92
+ ["entry #{index} (#{entry.label})", adapter] if adapter
93
+ end
94
+ end
95
+
96
+ # The registered names of the entries (not instances).
97
+ def types
98
+ @entries.filter_map(&:type)
99
+ end
100
+
101
+ def labels
102
+ @entries.map(&:label)
103
+ end
104
+
105
+ # The entries' labels only: never an adapter's own state.
106
+ def inspect
107
+ "#<#{self.class.name} #{labels.join(', ')}>"
108
+ end
109
+
110
+ private
111
+
112
+ # [the entry's adapter, why there is none]: the one built when the list was assigned, else (for an entry that
113
+ # wasn't registered then) one built from its kept value as soon as its name is registered, once for each
114
+ # registered class. Built outside the lock, since a constructor may load a gem.
115
+ def resolve(entry)
116
+ return [entry.adapter, nil] if entry.adapter
117
+ return [nil, entry.skipped] unless entry.source && (klass = Registry.fetch(entry.type))
118
+
119
+ cached = @lock.synchronize { @late[entry] }
120
+ [cached.instance_of?(klass) ? cached : build_late(entry, klass), nil]
121
+ rescue MissingGemError
122
+ [nil, MISSING_GEM]
123
+ end
124
+
125
+ def build_late(entry, klass)
126
+ built = Adapter.build(entry.source.reveal, entry.where)
127
+ @lock.synchronize { @late[entry] = @late[entry].instance_of?(klass) ? @late[entry] : built }
128
+ end
129
+
130
+ # Whether the entry is, or will be once built, of klass: judged without building one that isn't built yet (a
131
+ # registered name is always a Class: Registry.register checks).
132
+ def of?(entry, klass)
133
+ return entry.adapter.is_a?(klass) if entry.adapter
134
+
135
+ registered = Registry.fetch(entry.type) if entry.type
136
+ registered ? registered <= klass : false
137
+ end
138
+
139
+ def available?(adapter)
140
+ !adapter.respond_to?(:available?) || adapter.available?
141
+ end
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Squishling
4
+ module Adapter
5
+ # SQUISHLING_ADAPTER: the name of a registered adapter, or of one in config.adapters or in config.adapter's list,
6
+ # that Squishling uses for every request whose step doesn't pick an adapter itself, ahead of config.adapter. Read
7
+ # each time the adapter is resolved, never at load, so a process (or a test) can set it late. Unset or blank
8
+ # changes nothing. An instance holds the adapters it built from a bare registered name, so each is built once.
9
+ class Override
10
+ ENV_VAR = "SQUISHLING_ADAPTER"
11
+
12
+ # The name asked for as a Symbol, nil when the variable is unset or blank.
13
+ def self.requested
14
+ value = ENV.fetch(ENV_VAR, nil).to_s.strip
15
+ value.to_sym unless value.empty?
16
+ end
17
+
18
+ def initialize
19
+ @built = {}
20
+ @lock = Mutex.new
21
+ end
22
+
23
+ # The adapter the name asks for, given config.adapters (a Hash), config.adapter as set (current) and the
24
+ # adapter auto-detected so far (detected), in order:
25
+ # 1. one from adapters;
26
+ # 2. a candidate of current's list of that name (with the options it was given, and whether or not it is
27
+ # #available?: asking for it is the point);
28
+ # 3. the adapter the developer configured that is of that registered class (see #configured);
29
+ # 4. detected, when it is of that class: it was never configured, so it is only a bare build already made, and
30
+ # can't make a name ambiguous;
31
+ # 5. the registered adapter built with no options, outside the lock (a constructor may load a gem), once for each
32
+ # registered class.
33
+ # Raises ConfigurationError for a name that is none of these, and for a class more than one adapter is of.
34
+ def adapter(name, adapters:, current:, detected:)
35
+ adapters[name] || (current.is_a?(Candidates) && current.named(name)) ||
36
+ registered(name, adapters, current, detected)
37
+ end
38
+
39
+ private
40
+
41
+ def registered(name, adapters, current, detected)
42
+ klass = Registry.fetch(name)
43
+ raise unknown(adapters, current) unless klass
44
+
45
+ configured(name, klass, adapters, current) || (detected if detected.instance_of?(klass)) || bare(name, klass)
46
+ end
47
+
48
+ # The one adapter the developer configured (in config.adapters, the candidate list, or config.adapter) that is of
49
+ # klass, so naming a type picks the adapter they set up, options and all, not a bare one pointed at the provider's
50
+ # default host. A single config.adapter of exactly klass wins, as the default adapter the name is about (it has no
51
+ # name of its own for an error to ask the operator to use). Otherwise an adapter of exactly klass is preferred; an
52
+ # instance of a subclass (a customised adapter) counts only when there is none. One instance configured in two
53
+ # places is one adapter. More than one is a ConfigurationError (see #ambiguous); none is nil.
54
+ def configured(name, klass, adapters, current)
55
+ return current if current.instance_of?(klass)
56
+
57
+ pool = configured_adapters(adapters, current, klass)
58
+ found = pool.select { |_, adapter| adapter.instance_of?(klass) }
59
+ found = pool if found.empty?
60
+ raise ambiguous(name, found.map(&:first)) if found.size > 1
61
+
62
+ found.dig(0, 1)
63
+ end
64
+
65
+ # [where it is configured, adapter] for each adapter set up that is a klass (or a subclass of it). The places are
66
+ # names, never an adapter's options.
67
+ def configured_adapters(adapters, current, klass)
68
+ found = adapters.map { |key, adapter| ["config.adapters[#{key.inspect}]", adapter] }
69
+ found << ["config.adapter", current] if current && !current.is_a?(Candidates)
70
+ found = found.select { |_, adapter| adapter.is_a?(klass) }
71
+ found += candidate_adapters(current, klass)
72
+ found.uniq { |_, adapter| adapter.__id__ }
73
+ end
74
+
75
+ def candidate_adapters(current, klass)
76
+ return [] unless current.is_a?(Candidates)
77
+
78
+ current.built(klass).map { |place, adapter| ["config.adapter's #{place}", adapter] }
79
+ end
80
+
81
+ def bare(name, klass)
82
+ cached = @lock.synchronize { @built[name] }
83
+ return cached if cached.instance_of?(klass)
84
+
85
+ built = Adapter.build(name, ENV_VAR)
86
+ @lock.synchronize { @built[name] = @built[name].instance_of?(klass) ? @built[name] : built }
87
+ end
88
+
89
+ # The ConfigurationError for a registered name that more than one configured adapter is of. It lists where they
90
+ # are configured (names, never options or credentials) so the variable can name one of them.
91
+ def ambiguous(name, places)
92
+ ConfigurationError.new("#{ENV_VAR} names #{name.inspect}, which #{places.size} configured adapters are of " \
93
+ "(#{places.join(', ')}); set #{ENV_VAR} to the config.adapters name (or the " \
94
+ "candidate's registered name) of the one to use; one with no name must first be given " \
95
+ "one in config.adapters")
96
+ end
97
+
98
+ # The ConfigurationError for a name that is neither configured nor registered, listing the names that would
99
+ # work. The value is never repeated: a variable set to something else (a key pasted into the wrong place) never
100
+ # reaches an error message or a log.
101
+ def unknown(adapters, current)
102
+ configured = adapters.keys + (current.is_a?(Candidates) ? current.types : [])
103
+ named = configured.empty? ? "" : "; configured: #{configured.uniq.map(&:inspect).join(', ')}"
104
+ ConfigurationError.new("#{ENV_VAR} names an adapter that isn't registered or configured " \
105
+ "(registered: #{Adapter.type_list}#{named})")
106
+ end
107
+ end
108
+ end
109
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Squishling
6
+ module Adapter
7
+ # Reads a Retry-After header (RFC 9110): a number of seconds, or an HTTP date, which becomes the seconds from now
8
+ # until it. Anything else (a blank, a negative number, text) is nil, since a provider's header is not ours to trust.
9
+ # A longer wait than MAX is capped to it, so a malformed or hostile value can't park a background job for days.
10
+ module RetryAfter
11
+ MAX = 3600
12
+ SECONDS = /\A\d+(?:\.\d+)?\z/
13
+ private_constant :SECONDS
14
+
15
+ module_function
16
+
17
+ # value is the header's String (or a number); returns seconds as an Integer or Float, or nil. now is injectable.
18
+ def parse(value, now: Time.now)
19
+ seconds = seconds_of(value.is_a?(Numeric) ? value : value.to_s.scrub("?").strip, now)
20
+ [seconds, MAX].min unless seconds.nil? || seconds.to_f.nan? || seconds.negative?
21
+ end
22
+
23
+ def seconds_of(value, now)
24
+ return (value if value.real?) if value.is_a?(Numeric)
25
+ return value.include?(".") ? value.to_f : value.to_i if value.match?(SECONDS)
26
+
27
+ [(Time.httpdate(value) - now).ceil, 0].max
28
+ rescue ArgumentError
29
+ nil
30
+ end
31
+ private_class_method :seconds_of
32
+ end
33
+ end
34
+ end
@@ -103,12 +103,13 @@ module Squishling
103
103
  # end
104
104
  #
105
105
  # ConfigurationError is for setup mistakes (bad credentials, an invalid request, an unknown model): it is never
106
- # retried or escalated. LLMError is for failures worth another attempt (rate limits, 5xx, timeouts, connection
107
- # errors, a prompt too long for the model): the next attempt, or the last one's caller, sees it. Keep the provider's
108
- # own message out of both: it can echo request content or part of a key. The same goes for the exception it came
109
- # from, which error trackers report as the error's #cause: pass `cause: sanitized_cause(e, status:)` rather than
110
- # letting a raise inside a rescue set a provider exception that carries a response body. Any other exception
111
- # propagates unwrapped.
106
+ # retried or escalated. LLMError is for failures worth another attempt (5xx, timeouts, connection errors, a prompt
107
+ # too long for the model): the next attempt, or the last one's caller, sees it. Its RateLimitError subclass is for
108
+ # a rate limit (429), which the escalation answers with the next step, not a retry. Keep the provider's own
109
+ # message out of both: it can echo request content or part of a key. The same goes for the exception it came from,
110
+ # which error trackers report as the error's #cause: pass `cause: sanitized_cause(e, status:)` rather than letting
111
+ # a raise inside a rescue set a provider exception that carries a response body. Any other exception propagates
112
+ # unwrapped.
112
113
  # Which of the two a provider failure is, is the adapter's call (#http_failure maps HTTP statuses, and
113
114
  # #context_length? is where an adapter recognizes an overlong prompt); what happens next is Squishling's.
114
115
  # Adapters are called from worker threads when a harness takes samples, so they must not share unsynchronized state.
@@ -118,6 +119,14 @@ module Squishling
118
119
  raise NotImplementedError, "#{self.class} must implement #complete(request)"
119
120
  end
120
121
 
122
+ # Whether this adapter can run here, which a list of config.adapter candidates asks to pick the first usable one
123
+ # (see Candidates): an adapter for a device or OS feature returns false where the feature is missing. Local and
124
+ # cheap: no request, no credentials check, no raise. Asked each time the adapter is resolved, so don't memoize
125
+ # what can change.
126
+ def available?
127
+ true
128
+ end
129
+
121
130
  # Whether #judge is supported (judges with type: :judgment).
122
131
  def judgments?
123
132
  false
@@ -168,6 +177,11 @@ module Squishling
168
177
  LLMError.new("#{request.label}: #{message}")
169
178
  end
170
179
 
180
+ # retry_after: seconds, already parsed (see RetryAfter.parse), or nil.
181
+ def rate_limit_error(request, message, retry_after: nil)
182
+ RateLimitError.new("#{request.label}: #{message}", retry_after:)
183
+ end
184
+
171
185
  # What to pass as `cause:` when raising a Squishling error for a provider's exception: a ProviderFailure naming
172
186
  # the original's class and the HTTP status (when given), with the original's backtrace. A provider exception's
173
187
  # message and response usually hold the provider's response body, which can echo request content, and error
@@ -178,16 +192,18 @@ module Squishling
178
192
  .tap { |failure| failure.set_backtrace(error.backtrace) }
179
193
  end
180
194
 
181
- # Classifies a provider's HTTP failure, so adapters sort the same status the same way: 408, 413, 429, and 5xx are
182
- # LLMErrors; 401, 402, 403, 404, and a redirect are ConfigurationErrors (credentials, billing, model or endpoint:
183
- # nothing a retry fixes); every other 4xx is a RequestRejectedError, unless #context_length? says the input
184
- # outgrew the model, which is an LLMError too (a bigger model may take it). via names how it failed (the error
185
- # class, the HTTP status) and is all of the failure that is repeated, with a rejection's status and code tokens.
186
- # body is the provider's error body, as for #rejected_request_error. A nil status (no HTTP response) or a
187
- # success status (a reply that was unusable) is an LLMError.
188
- def http_failure(request, status:, body:, via:)
195
+ # Classifies a provider's HTTP failure, so adapters sort the same status the same way: 429 is a RateLimitError
196
+ # (carrying retry_after, the Retry-After header's value when the adapter read one: seconds or an HTTP date, see
197
+ # RetryAfter.parse); 408, 413, and 5xx are LLMErrors; 401, 402, 403, 404, and a redirect are ConfigurationErrors
198
+ # (credentials, billing, model or endpoint: nothing a retry fixes); every other 4xx is a RequestRejectedError,
199
+ # unless #context_length? says the input outgrew the model, which is an LLMError too (a bigger model may take
200
+ # it). via names how it failed (the error class, the HTTP status) and is all of the failure that is repeated,
201
+ # with a rejection's status and code tokens. body is the provider's error body, as for #rejected_request_error.
202
+ # A nil status (no HTTP response) or a success status (a reply that was unusable) is an LLMError.
203
+ def http_failure(request, status:, body:, via:, retry_after: nil)
189
204
  case status
190
- when nil, 100..299, 408, 413, 429, 500.. then llm_error(request, via)
205
+ when 429 then rate_limit_error(request, via, retry_after: RetryAfter.parse(retry_after))
206
+ when nil, 100..299, 408, 413, 500.. then llm_error(request, via)
191
207
  when 401, 403 then configuration_error(request, "the provider refused the credentials (#{via})")
192
208
  when 402 then configuration_error(request, "#{via}: the provider reports a billing or quota problem")
193
209
  when 404 then configuration_error(request, "#{via}: check the model name and the endpoint")