squishling 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +115 -0
  3. data/README.md +4 -4
  4. data/docs/adapters.md +94 -22
  5. data/docs/configuration.md +53 -6
  6. data/docs/failures.md +59 -13
  7. data/docs/harnesses.md +15 -1
  8. data/docs/measuring-tokens.md +6 -1
  9. data/docs/observers.md +5 -4
  10. data/docs/routing.md +11 -4
  11. data/docs/schemas.md +13 -0
  12. data/docs/testing.md +8 -4
  13. data/docs/verifying.md +4 -2
  14. data/lib/squishling/adapter/error_body.rb +9 -2
  15. data/lib/squishling/adapter.rb +73 -13
  16. data/lib/squishling/adapters/openai_compatible.rb +71 -53
  17. data/lib/squishling/adapters/openai_options.rb +45 -3
  18. data/lib/squishling/adapters/openai_transport.rb +123 -0
  19. data/lib/squishling/adapters/ruby_llm.rb +70 -16
  20. data/lib/squishling/budget.rb +11 -3
  21. data/lib/squishling/cache.rb +33 -0
  22. data/lib/squishling/class_methods.rb +23 -8
  23. data/lib/squishling/configuration.rb +27 -1
  24. data/lib/squishling/definition.rb +22 -7
  25. data/lib/squishling/errors.rb +7 -5
  26. data/lib/squishling/invoker.rb +24 -6
  27. data/lib/squishling/judge.rb +8 -2
  28. data/lib/squishling/llm_client.rb +3 -2
  29. data/lib/squishling/model_path.rb +12 -9
  30. data/lib/squishling/observer.rb +11 -4
  31. data/lib/squishling/params.rb +2 -2
  32. data/lib/squishling/result.rb +13 -0
  33. data/lib/squishling/router.rb +3 -2
  34. data/lib/squishling/run/reports.rb +63 -0
  35. data/lib/squishling/run.rb +6 -23
  36. data/lib/squishling/schema.rb +44 -4
  37. data/lib/squishling/secret.rb +45 -0
  38. data/lib/squishling/squawk.rb +7 -4
  39. data/lib/squishling/testing/adapter.rb +5 -3
  40. data/lib/squishling/testing/request.rb +7 -2
  41. data/lib/squishling/testing/state.rb +2 -1
  42. data/lib/squishling/version.rb +1 -1
  43. data/lib/squishling/wrapper.rb +19 -1
  44. data/lib/squishling.rb +8 -3
  45. metadata +5 -1
data/docs/failures.md CHANGED
@@ -8,9 +8,9 @@ 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 the original exception as its `cause` (when the adapter has one: the RubyLLM adapter always does; the OpenAI-compatible adapter for transport errors, not for HTTP statuses). |
12
- | Bad API key, unknown model, missing provider config | Raises `Squishling::ConfigurationError`. Never escalated, never sent to the fallback. |
13
- | Provider rejects the request (400 Bad Request), 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 on `cause` when the adapter has one (RubyLLM's does; with the OpenAI-compatible adapter `cause` carries only the status). It is never retried, so if you know a given code means "this input was bad", rescue it and decide for yourself. Never escalated, never sent to the fallback, so a setup mistake can't be silently covered up on every call. |
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. |
12
+ | 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
+ | 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
14
  | 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. |
15
15
  | Malformed or truncated JSON | Moves to the next attempt, then raises `InvalidOutputError`. JSON wrapped in a markdown code fence is accepted. |
16
16
  | JSON that doesn't match the schema (wrong types, missing or extra keys, `null` in a non-`optional` field, a broken [conditional rule](schemas.md#contracts-beyond-the-schema), root not an object) | Moves to the next attempt with the validation errors, then raises `InvalidOutputError` |
@@ -65,9 +65,10 @@ Model output can echo sensitive input, so the raw response is kept in one place:
65
65
  the message, the logger, and the next attempt's prompt.
66
66
  - A fixed message when a response contains a value JSON can't represent (`1e400` parses to `Infinity`, or a string
67
67
  with invalid UTF-8).
68
- - For a failed provider request (`LLMError`, and the `ConfigurationError` for a 400, bad credentials, or a forbidden
69
- key), only the error class and HTTP status, plus a 400's provider status and code when they are plain tokens. The provider's own message can echo request content or part of an API
70
- key, so it stays on `cause` (`error.cause.message`) for you to read or log deliberately.
68
+ - For a failed provider request (`LLMError`, and the `ConfigurationError` for a rejected request, bad credentials, or a forbidden
69
+ key), only the error class and HTTP status, plus a rejection's provider status and code when they are plain tokens. The provider's own message can echo request content or part of an API
70
+ key, and error trackers report the whole `cause` chain, so it is not on `cause` either unless you
71
+ [opt in](#the-cause-of-a-provider-failure).
71
72
  - At most the first 20 of these errors, plus a count of the rest, so a very large malformed response can't flood
72
73
  the retry message or the log.
73
74
  - For a [`DisagreementError`](harnesses.md#when-the-harness-fails), only what Squishling wrote: a `:judgment` judge's
@@ -99,6 +100,26 @@ The same applies to anything you log yourself, such as `error.message` in a [fal
99
100
  only where you are willing to store model output. To send the output of every attempt somewhere on purpose, use
100
101
  [`squawk`](#observing-every-attempt-squawk).
101
102
 
103
+ ### The cause of a provider failure
104
+
105
+ A provider's own exception (RubyLLM's, say) carries the provider's response body in its message and `response`, and the
106
+ body can echo your request. Error trackers such as Sentry report the whole `cause` chain, so an `LLMError`,
107
+ `ConfigurationError`, or `RequestRejectedError` raised for a failed request does not carry that exception as its
108
+ `cause`. The [RubyLLM adapter](adapters.md#ruby_llm) puts a `Squishling::Adapter::ProviderFailure` there instead: its
109
+ message is the original's class and HTTP status (`RubyLLM::RateLimitError, HTTP 429`), and it has the original's
110
+ backtrace, but none of its message, response, or other state. Transport errors that carry no body (the OpenAI-compatible
111
+ adapter's timeouts and connection failures) are passed through as they are.
112
+
113
+ To get the original back for debugging, accept that it reaches your tracker and set `keep_cause: true`:
114
+
115
+ ```ruby
116
+ Squishling.configure do |config|
117
+ config.adapter = { type: :ruby_llm, keep_cause: true }
118
+ end
119
+ ```
120
+
121
+ Then `error.cause` is the `RubyLLM::Error` itself, with its message and `response`.
122
+
102
123
  ## Capping a call's cost (token budgets)
103
124
 
104
125
  `attempts:` limits retries per step, but a call that fails every attempt still pays for all of them, and with
@@ -134,7 +155,10 @@ Things to know:
134
155
  limit by one request (for the squishsum harnesses, one round of samples).
135
156
  - Tokens are the counts the [adapter](adapters.md) reports (`output_tokens` includes a reasoning model's thinking
136
157
  tokens for providers that count them that way). A request that failed reports none, and a provider that reports no
137
- usage never exhausts a budget.
158
+ usage never exhausts a budget. The input total includes the tokens written to the prompt cache
159
+ (`cache_write_tokens`) but not those read from it (`cache_read_tokens`), which adapters report apart from
160
+ `input_tokens`: with [prompt caching](configuration.md#prompt-caching) on, a hit on a long cached prompt doesn't spend
161
+ the budget. Set `config.budget_counts_cache_reads = true` in `Squishling.configure` to count reads too.
138
162
  - The limits are positive Integers. Set them with `Squishling.configure` (`default_max_total_output_tokens`,
139
163
  `default_max_total_input_tokens`), `squishling`, `squish :method, ...`, or a [`squish!`](routing.md#handing-off-to-the-llm-with-squish) call.
140
164
  The more specific level wins, limit by limit, and `false` lifts a limit set at a wider level.
@@ -143,8 +167,8 @@ Things to know:
143
167
  ## Observing every attempt (`squawk`)
144
168
 
145
169
  `squawk` is an opt-in hook for sending what the model returned to an error tracker or tracing tool. It runs after
146
- every LLM attempt, accepted or rejected (unless you narrow it with `squawk_on:`, below), and does nothing unless you
147
- set it:
170
+ every LLM attempt, accepted or rejected (unless you narrow it with `squawk_on:`, below), and once more when a token
171
+ budget or a disagreement stops the call. It does nothing unless you set it:
148
172
 
149
173
  ```ruby
150
174
  Squishling.configure do |config|
@@ -157,8 +181,8 @@ end
157
181
  | Keyword | Value |
158
182
  |---|---|
159
183
  | `output` | The raw response: a Hash or String, or `nil` when the provider call itself failed |
160
- | `error` | `nil` for an accepted attempt. Otherwise the `InvalidOutputError` (with `errors` and `raw`) or `LLMError` that ended the attempt |
161
- | `metadata` | `label` (`"Class#method"`), `attempt`, `attempts` (the escalation's length; `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`) |
184
+ | `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 |
185
+ | `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)) |
162
186
 
163
187
  - Set it globally with `config.squawk`, per class with `squishling squawk: ...`, or per method with
164
188
  `squish :triage, squawk: ...`. The method's hook wins over the class's, which wins over the configured one;
@@ -191,6 +215,28 @@ end
191
215
  - It isn't called for a `ConfigurationError`, for deterministic and fallback returns, or for an attempt where your own
192
216
  `squish_validate` raises (that exception propagates first).
193
217
 
218
+ ### A call that is stopped
219
+
220
+ A call that a [token budget](#capping-a-calls-cost-token-budgets) or a
221
+ [disagreement](harnesses.md#when-the-harness-fails) stops has no attempt of its own to report: the attempt before a
222
+ budget stop was reported as not final, and a disagreement's samples were both accepted. So the call gets one more
223
+ report, whatever `squawk_on:` is set to:
224
+
225
+ - `error` is the `BudgetExhaustedError` or `DisagreementError`, `output` is `nil` (nothing was sent), `metadata[:final]`
226
+ is `true`, and `metadata[:stopped]` is `:budget` or `:disagreement` (it is `nil` for every attempt's report).
227
+ - `attempt` and `attempts` are `error.attempts`, or `0` when that is `nil` (a disagreement, or a budget that ran out
228
+ before a sample or judge made its first attempt); a stop before a retry counts the attempts already made. `model` is
229
+ the last of `error.models`, and `provider`, `params`, `usage`, `role`, and `sample` are `nil`.
230
+ - It is sent once, after the attempts that led to it and before `squish_fallback` runs, for the built-in harnesses and
231
+ for a [custom one](harnesses.md#reporting-to-squawk) that raises either error. A call to another squished method
232
+ from your own code (a `squish_validate`, say) reports its own stop, and the outer call does not report that error
233
+ again. The attempts before it keep `final: false`, so `squawk_on: :final` sees a budget or disagreement ending only
234
+ through this report.
235
+ - Like any attempt's report, it runs your hook inline: an exception the hook raises propagates in place of the
236
+ `BudgetExhaustedError` or `DisagreementError` (which stays on `cause`), so `squish_fallback` does not run.
237
+ - `squawk: false`, or no hook, sends nothing. Ending on the last invalid attempt is not a stop: that attempt already
238
+ carried `final: true`.
239
+
194
240
  ## Output checks (`squish_validate`)
195
241
 
196
242
  The schema covers shape and types. For rules it can't express, such as cross-field arithmetic or a lookup against
@@ -224,11 +270,11 @@ end
224
270
  | Error | Raised when |
225
271
  |---|---|
226
272
  | `Squishling::Error` | Base class for everything below. Raised directly for misuse at call time, e.g. `result` or `squish!` called outside a squished method |
227
- | `Squishling::ConfigurationError` | Missing purpose or schema, a non-strict schema, 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 (400, as `RequestRejectedError`, with `provider_status` and `provider_code`) |
273
+ | `Squishling::ConfigurationError` | Missing purpose or schema, a non-strict schema, 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`) |
228
274
  | `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 |
229
275
  | `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 |
230
276
  | `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 |
231
- | `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 the original, when the adapter has one) |
277
+ | `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) |
232
278
 
233
279
  Errors raised by your own Ruby code are not wrapped.
234
280
 
data/docs/harnesses.md CHANGED
@@ -91,6 +91,13 @@ A judged harness with neither raises `ConfigurationError` before any sample is r
91
91
  step uses only its own `provider:`; it doesn't inherit the class or method `provider:`, which belongs to their models
92
92
  (a chat judge's params, though, do merge over the method's).
93
93
 
94
+ **What the judge is sent.** The judge's provider receives the operation's purpose, the call's full input (the same
95
+ method arguments and named context the samples saw), and **both candidate outputs**, whatever they hold. None of it is
96
+ capped or filtered, and there is no opt-out short of not using a judged harness. When the judge is a different
97
+ provider than the sampled model (a `judge:` step with its own `provider:`, or an escalation's next step on another
98
+ provider), the input and both outputs go to that provider as well, so only name a judge you would trust with the
99
+ input itself.
100
+
94
101
  ### Chat judges
95
102
 
96
103
  By default the judge is a chat model, asked for a strict `{ "verdict": "a" | "b" | "neither", "reason": "..." }`.
@@ -299,7 +306,10 @@ results, the same type the deterministic path returns.
299
306
  | `run.log(message)` | A warning to `config.logger`, prefixed with `"[Squishling] Class#method"` |
300
307
 
301
308
  `call` returns the accepted result: one a primitive of this run returned. Returning anything else (a Hash, `nil`, a
302
- result you built or copied with `with`) raises `ConfigurationError`, so a harness can't skip validation.
309
+ result you built or copied with `with`) raises `ConfigurationError`, so a harness can't skip validation. The check is
310
+ by object identity, which suits the typed results of an object schema. When the schema isn't an object, a result is a
311
+ bare JSON value, and an immediate such as `1` or `true` counts as produced whatever its source, so there the check can't
312
+ catch a hand-built value.
303
313
 
304
314
  ### When a custom harness fails
305
315
 
@@ -328,6 +338,10 @@ and `attempts` count within that sample, judge, or escalation. `metadata[:repeat
328
338
  sent back the reply it was just rejected for; the primitive then skips the rest of that step's attempts (the next
329
339
  step's `attempt` jumps past them, and a sample ends with its `InvalidOutputError`).
330
340
 
341
+ A call that ends on the token budget or on a `DisagreementError` (the built-in squishsum harnesses', or one your
342
+ `call` raises) is reported once more, as [a stopped call](failures.md#a-call-that-is-stopped), with `metadata[:stopped]`
343
+ set and no output. Squishling does it around your `call`, so a custom harness needs no code for it.
344
+
331
345
  ### Threads
332
346
 
333
347
  Only the provider requests inside `run.samples` run on worker threads. Your `call`, parsing, validation,
@@ -72,6 +72,10 @@ Squishling.configure do |config|
72
72
  end
73
73
  ```
74
74
 
75
+ A call that stops on its [token budget](failures.md#capping-a-calls-cost-token-budgets) or a disagreement is also
76
+ reported once, with `metadata[:stopped]` set (`:budget` or `:disagreement`) and no `usage`, so the hook above logs
77
+ it with empty counts; check `metadata[:stopped]` to count it apart from an attempt.
78
+
75
79
  Each line carries the `"Class#method"` that made the call, so grouping by label gives you tokens per squishling. A call
76
80
  that stays in Ruby makes no LLM request and never reaches the hook, so a label that stops appearing is a path that has
77
81
  been hardened. You can also set the hook per class (`squishling squawk: ...`) or per method. See
@@ -89,7 +93,8 @@ can meter spend knowing which method, escalation level, sample, or judge made th
89
93
  ```ruby
90
94
  class SpendObserver
91
95
  def around(call)
92
- usage = yield # input_tokens, output_tokens (nil if unreported), and model; never the content
96
+ usage = yield # input_tokens (not counting cached ones), output_tokens, cache_read_tokens, cache_write_tokens
97
+ # (each nil if unreported), and model; never the content
93
98
  tags = ["label:#{call.label}", "role:#{call.role || 'squish'}", "model:#{usage.model}"]
94
99
  Metrics.increment("squishling.tokens.in", usage.input_tokens.to_i, tags:)
95
100
  Metrics.increment("squishling.tokens.out", usage.output_tokens.to_i, tags:)
data/docs/observers.md CHANGED
@@ -26,7 +26,8 @@ raises `ConfigurationError`.
26
26
 
27
27
  ## What `yield` returns
28
28
 
29
- The block returns a `Squishling::Observer::Usage`: the request's `input_tokens` and `output_tokens` (nil when the
29
+ The block returns a `Squishling::Observer::Usage`: the request's `input_tokens` and `output_tokens`, the
30
+ `cache_read_tokens` and `cache_write_tokens` of [prompt caching](configuration.md#prompt-caching) (each nil when the
30
31
  provider didn't report them) and the `model` that answered. That is enough to meter spend:
31
32
 
32
33
  ```ruby
@@ -60,7 +61,7 @@ Anything else raises `ConfigurationError` when you assign it.
60
61
  | Field | |
61
62
  |---|---|
62
63
  | `label` | `"Class#method"` |
63
- | `purpose` | The purpose text sent as the system prompt (after `purpose` procs and `append_to_purpose` sections are resolved) |
64
+ | `purpose` | The purpose text sent as the system prompt (after `purpose` procs and `append_to_purpose` sections are resolved). It is the whole prompt, including any source you pass to `append_to_purpose` and whatever your `purpose` procs return, so treat it as sensitive: don't log it to a place the prompt itself shouldn't go |
64
65
  | `handed_off` | `true` when a `squish!` call sent the call to the LLM (typically from a `rescue`), `false` when `squish_when` or a missing implementation did |
65
66
  | `harness` | The harness type (`:escalation`, `:squishsum`, `:judged_squishsum`, or a [custom one](harnesses.md#custom-harnesses)) |
66
67
  | `role` | `nil` for an escalation attempt, `:sample` or `:judge`, as in `squawk`'s `metadata` |
@@ -69,8 +70,8 @@ Anything else raises `ConfigurationError` when you assign it.
69
70
  | `model`, `provider` | The step's model and provider (`provider` is `nil` unless declared) |
70
71
  | `request` | `:chat`, or `:judgment` for a System One judge |
71
72
 
72
- It carries metadata only. The method's inputs, its context, and the model's output never reach an observer: it gets
73
- the request's token [`Usage`](#what-yield-returns) back, and `squawk` is the route for output.
73
+ It carries metadata, plus the rendered `purpose`. The method's inputs, its context, and the model's output never reach an
74
+ observer: it gets the request's token [`Usage`](#what-yield-returns) back, and `squawk` is the route for output.
74
75
 
75
76
  ## Errors
76
77
 
data/docs/routing.md CHANGED
@@ -17,7 +17,7 @@ A squished call runs its Ruby implementation unless one of these sends it to the
17
17
  | Trigger | Declared where | Decided |
18
18
  |---|---|---|
19
19
  | `squish_when` (or `when:`) predicate is truthy | class, or per method | before Ruby runs |
20
- | The method has no implementation: it isn't defined, or it raises `NotImplementedError` | the method body | when Ruby gives up |
20
+ | The method has no implementation: it isn't defined, or its own body raises `NotImplementedError` | the method body | when Ruby gives up |
21
21
  | `squish!` | inside the method, e.g. in a `rescue` | after Ruby has partly run, see [Handing off to the LLM](#handing-off-to-the-llm-with-squish) |
22
22
 
23
23
  With no predicate and a working implementation, every call runs Ruby.
@@ -41,8 +41,14 @@ is validated against the schema and turned into the same typed result the LLM pa
41
41
  already has a `result` (see [Naming and collisions](naming.md)). Invalid deterministic output raises
42
42
  `Squishling::InvalidOutputError` too, so a hardened path can't silently drift from the contract.
43
43
 
44
- A `NotImplementedError` raised anywhere inside the method, including from code it calls, also routes to the
45
- LLM.
44
+ Only the method's own stub routes: a `NotImplementedError` raised directly in the method body (`raise
45
+ NotImplementedError` in a `def` or a `define_method` block, including one in a module prepended before
46
+ `include Squishling`, or in a squished parent reached through `super`). One raised by code the method calls
47
+ (a helper, another object, a block, or a `super` into a parent that isn't squished) is a bug in that code, not a
48
+ missing implementation, so it propagates and nothing is sent to the provider. Keep the `raise` in the method body:
49
+ a shared `not_implemented!` helper, or a decorator prepended before `include Squishling` that wraps the method with
50
+ its own `super` frame, hides the stub and the error propagates (use `squish_when { true }` or `squish!` to
51
+ send those calls to the LLM).
46
52
 
47
53
  Each call is routed on its own, including a squished method that calls itself on smaller inputs (those
48
54
  recursive calls must return schema-valid values too). A subclass
@@ -92,7 +98,7 @@ end
92
98
  - `purpose:` (replaces the class's)
93
99
  - `append_to_purpose:` (added to the class's, see [Appending to the purpose](#appending-to-the-purpose))
94
100
  - `output_schema:` (or a schema block)
95
- - `model:` or `escalation:`, `provider:`, and `params:` (generation params; see [Configuration](configuration.md))
101
+ - `model:` or `escalation:`, `provider:`, `params:` (generation params), and `cache:` (prompt caching); see [Configuration](configuration.md)
96
102
  - `harness:` (see [Harnesses](harnesses.md), including your own)
97
103
  - `max_total_output_tokens:` and `max_total_input_tokens:` (see [Capping a call's cost](failures.md#capping-a-calls-cost-token-budgets))
98
104
  - `when:`, a predicate proc
@@ -137,6 +143,7 @@ end
137
143
  | `append_to_purpose:` | Added to the declared sections; `false` (alone or first in an Array) drops them for this call |
138
144
  | `purpose:` | Replaces the purpose |
139
145
  | `model:` or `escalation:`, `provider:`, `params:` | E.g. send this call to a stronger model, or a whole [escalation](configuration.md#models-and-escalation), when Ruby fails. A `provider:` needs a `model:` or `escalation:`; `params:` merge key by key over the declared ones. |
146
+ | `cache:` | Replaces the declared [prompt caching](configuration.md#prompt-caching) setting; `false` turns it off for this call |
140
147
  | `harness:` | Replaces the declared [harness](harnesses.md), e.g. `harness: :judged_squishsum` to double-check a hand-off |
141
148
  | `max_total_output_tokens:`, `max_total_input_tokens:` | Cap what this call may spend, e.g. a tighter budget for a hand-off; `false` lifts a declared cap. See [Capping a call's cost](failures.md#capping-a-calls-cost-token-budgets). |
142
149
 
data/docs/schemas.md CHANGED
@@ -30,6 +30,11 @@ output_schema(
30
30
  )
31
31
  ```
32
32
 
33
+ A raw schema's `$ref`s must point inside the schema (`"#/$defs/address"`). Squishling resolves them when it builds the
34
+ schema, so one that points nowhere (a remote URI, which is never fetched, or a `$defs` entry that doesn't exist)
35
+ raises `Squishling::ConfigurationError` then, and [`Squishling.verify`](verifying.md) reports it, instead of failing on
36
+ the first response.
37
+
33
38
  ## Describing fields
34
39
 
35
40
  Every DSL type, and `optional`, takes a `description:`. It is sent to the provider as guidance for that field
@@ -84,6 +89,14 @@ fields; rename them (`class` to `ticket_class`). The reserved names are `class`,
84
89
  `deconstruct_keys`, and a few Ruby and Squishling internals (`initialize*`, `__send__`, `squishling_squished`).
85
90
  Other names, such as `method`, `format`, or `type`, work as usual. This applies to nested objects and array items too.
86
91
 
92
+ With a hand-written Hash schema, every object schema that becomes a result (and so a nested result) must also say
93
+ `type: "object"`; `allOf` parts and unions with several non-null branches aren't typed, so they are exempt. A schema with
94
+ `properties` alone accepts a String or Array too (JSON Schema applies `properties` only to objects), which would end
95
+ up in the typed result where a nested result belongs. Squishling raises `ConfigurationError` when the schema is built
96
+ (and `Squishling.verify` reports it) for the root, a nested property, array `items`, the object branch of an
97
+ `optional`, or a `$ref` target. A union that includes it, like `["object", "null"]`, is fine. The DSL always sets
98
+ the type for you.
99
+
87
100
  On the deterministic path, return a `Hash` or build the result with `result(...)`. Either way it's validated
88
101
  against the schema, and so is anything else you return (`nil`, a string, another schema's result), which raises
89
102
  `Squishling::InvalidOutputError` unless it matches.
data/docs/testing.md CHANGED
@@ -18,7 +18,8 @@ Both give your tests the helpers below and put back, after each test, whatever t
18
18
  still hold what the helpers set), so the rest of your `Squishling.configure` survives.
19
19
 
20
20
  The helpers change global state (`Squishling.config` and the stubbed classes), so tests that use them must not run
21
- in parallel threads.
21
+ in parallel threads. That includes `no_llm_call` / `assert_no_llm_call`, which swap the process-wide `config.adapter`
22
+ for the block: a request another thread makes meanwhile is forbidden too, and may be counted in the block's calls.
22
23
 
23
24
  ## Scripting the model
24
25
 
@@ -91,7 +92,7 @@ and `#verdict` are the real ones; rescue them as you would in production.
91
92
  |---|---|
92
93
  | `arguments`, `context` | the method's arguments and the `squish_context` / `squish!` context the model was sent |
93
94
  | `system_prompt`, `output_schema` | the purpose (with `append_to_purpose` sections) and the strict schema |
94
- | `model`, `provider`, `params` | the step it went to |
95
+ | `model`, `provider`, `params`, `cache` | the step it went to (`cache` is `false` when [prompt caching](configuration.md#prompt-caching) was off for it) |
95
96
  | `role`, `sample`, `attempt`, `attempts` | `nil`/`:sample`/`:judge`, `"a"`, and where it is in the escalation |
96
97
  | `conversation` | the chat it belongs to |
97
98
  | `errors` | the validation messages a retry or escalation carried back to the model |
@@ -132,8 +133,8 @@ stub_squishling_error(PatternGenerator, :llm_error) # also :configurat
132
133
  Attributes that don't satisfy the method's `output_schema` raise `Squishling::Testing::SetupError` when you stub, so a
133
134
  stand-in can't drift from the real result type. Pass `method: :triage` for another squished method. The stubs are
134
135
  removed after each test. A stub applies to that class only, not to its subclasses, which keep their own behavior. The
135
- hook that makes a stub possible stays on the class for the life of the process, so stub the classes of your suite, not
136
- one per test.
136
+ hook that makes a stub possible stays on the class for the life of the process, even after `Testing.reset!` has
137
+ removed the stub (it is inert, but keeps the class alive), so stub the classes of your suite, not one per test.
137
138
 
138
139
  ## Running parts of a method without a model
139
140
 
@@ -171,6 +172,9 @@ capture.calls.map { |call| call.metadata[:attempt] } # output:, error:, and m
171
172
  `with_squawk` swaps `config.squawk` for the block and puts the previous hook back, so an app-wide hook that enqueues
172
173
  a job isn't run in tests. A `squawk:` set on a class or method still takes precedence over the configured one.
173
174
 
175
+ The capture also records the [report of a stopped call](failures.md#a-call-that-is-stopped) (`metadata[:stopped]` is
176
+ `:budget` or `:disagreement`). `stub_error` replaces the method without running Squishling, so it reports nothing.
177
+
174
178
  An observer you configured *before* `fake_squishling` keeps working while the fake is installed (it is chained behind
175
179
  the fake's own). Configure it first: one assigned afterwards replaces the fake's, and then sample and judge scripts
176
180
  can't tell which request is which.
data/docs/verifying.md CHANGED
@@ -27,8 +27,10 @@ Squishling.verify(Triage, Invoice) # just these classes
27
27
  For each squished method (inherited ones too, with the subclass's settings) it checks:
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
- property name that can't be a result member (`total=`) is reported. A method with no output schema or no purpose is reported, because its LLM path
31
- would raise. The default `call` method is skipped when you don't implement or configure it.
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.
32
34
  - **What the layers resolve to:** the escalation, generation params and `squawk` that the method, its class and
33
35
  `Squishling.config` add up to.
34
36
  - **The harness:** that it is still registered (not removed or replaced since the class declared it), and that a
@@ -11,7 +11,8 @@ module Squishling
11
11
  # repeated.
12
12
  WORD = /\A[A-Za-z0-9][\w.]{0,39}\z/
13
13
  PATH = /\A[\w.\-\[\]]{1,64}\z/
14
- private_constant :WORD, :PATH
14
+ CONTEXT_LENGTH_EXCEEDED = "context_length_exceeded"
15
+ private_constant :WORD, :PATH, :CONTEXT_LENGTH_EXCEEDED
15
16
 
16
17
  module_function
17
18
 
@@ -38,9 +39,15 @@ module Squishling
38
39
  nil
39
40
  end
40
41
 
42
+ # Whether the body's code or type is the structured "context_length_exceeded" (what OpenAI sends for a prompt too
43
+ # long for the model). Only that field is read, never the message.
44
+ def context_length?(body)
45
+ (error(body)&.values_at("code", "type") || []).include?(CONTEXT_LENGTH_EXCEEDED)
46
+ end
47
+
41
48
  def token(value, pattern)
42
49
  value = value.to_s if value.is_a?(Integer)
43
- value if value.is_a?(String) && value.match?(pattern)
50
+ value if value.is_a?(String) && value.valid_encoding? && value.match?(pattern)
44
51
  end
45
52
  end
46
53
  end
@@ -12,15 +12,22 @@ module Squishling
12
12
  # structured-output payload ({ "name", "description", "schema", "strict" => true }). params is the resolved
13
13
  # generation params: the portable :temperature, :max_output_tokens, and :thinking, plus any provider-specific keys
14
14
  # (see Params). label ("Class#method") prefixes the adapter's error messages. model and provider are the step's
15
- # (nil when it names none).
16
- Request = Data.define(:label, :model, :provider, :instructions, :messages, :schema, :params)
15
+ # (nil when it names none). cache is the prompt caching to ask the provider for: false (none), or a Hash of options
16
+ # ({} for the provider's default, { ttl: "1h" }), see Cache. An adapter whose provider has no prompt caching, or
17
+ # caches on its own, ignores it.
18
+ Request = Data.define(:label, :model, :provider, :instructions, :messages, :schema, :params, :cache) do
19
+ def initialize(label:, model:, provider:, instructions:, messages:, schema:, params:, cache: false)
20
+ super
21
+ end
22
+ end
17
23
 
18
24
  # Stands in for an empty reply when the conversation is replayed: some servers reject an empty assistant message.
19
25
  EMPTY_REPLY = "(no output)"
20
26
 
21
27
  # What a completion returns. content is the model's output: the raw String, or a Hash the adapter already parsed.
22
- # model is the model id the provider reports. tokens is a Hash of counts (:input_tokens, :output_tokens, and
23
- # whatever else the provider reports, such as :cache_read_tokens and :thinking_tokens), empty when unknown.
28
+ # model is the model id the provider reports. tokens is a Hash of counts (:input_tokens, the input not read from or
29
+ # written to the prompt cache, :output_tokens, and whatever else the provider reports, such as :cache_read_tokens,
30
+ # :cache_write_tokens and :thinking_tokens), empty when unknown.
24
31
  # finish_reason is why the provider stopped, as a Symbol: :stop, :max_tokens (the output cap cut the reply off),
25
32
  # :content_filter, :tool_calls, or the provider's own spelling; nil when it reported none.
26
33
  Response = Data.define(:content, :model, :tokens, :finish_reason) do
@@ -69,6 +76,11 @@ module Squishling
69
76
  end
70
77
  end
71
78
 
79
+ # What an adapter puts on a Squishling error's #cause in place of a provider's own exception (see
80
+ # Base#sanitized_cause): the original's class name and HTTP status in its message, and its backtrace, but none of
81
+ # its message, response, or other state. Not a Squishling::Error: it is never raised, only carried.
82
+ class ProviderFailure < StandardError; end
83
+
72
84
  # The adapter contract. Subclass it, implement #complete, and raise Squishling's errors:
73
85
  #
74
86
  # class MyAdapter < Squishling::Adapter::Base
@@ -78,15 +90,20 @@ module Squishling
78
90
  # rescue MyClient::Unauthorized
79
91
  # raise configuration_error(request, "MyClient rejected the credentials")
80
92
  # rescue MyClient::Error => e
81
- # raise llm_error(request, "MyClient failed (#{e.class})")
93
+ # raise llm_error(request, "MyClient failed (#{e.class})"), cause: sanitized_cause(e, status: e.status)
82
94
  # end
83
95
  # end
84
96
  #
85
97
  # ConfigurationError is for setup mistakes (bad credentials, an invalid request, an unknown model): it is never
86
98
  # retried or escalated. LLMError is for failures worth another attempt (rate limits, 5xx, timeouts, connection
87
- # errors): the next attempt, or the last one's caller, sees it. Keep the provider's own message out of both: it can
88
- # echo request content or part of a key. Any other exception propagates unwrapped. Adapters are called from worker
89
- # threads when a harness takes samples, so they must not share unsynchronized state.
99
+ # errors, a prompt too long for the model): the next attempt, or the last one's caller, sees it. Keep the provider's
100
+ # own message out of both: it can echo request content or part of a key. The same goes for the exception it came
101
+ # from, which error trackers report as the error's #cause: pass `cause: sanitized_cause(e, status:)` rather than
102
+ # letting a raise inside a rescue set a provider exception that carries a response body. Any other exception
103
+ # propagates unwrapped.
104
+ # Which of the two a provider failure is, is the adapter's call (#http_failure maps HTTP statuses, and
105
+ # #context_length? is where an adapter recognizes an overlong prompt); what happens next is Squishling's.
106
+ # Adapters are called from worker threads when a harness takes samples, so they must not share unsynchronized state.
90
107
  class Base
91
108
  # One completion. Returns an Adapter::Response.
92
109
  def complete(_request)
@@ -126,10 +143,53 @@ module Squishling
126
143
  LLMError.new("#{request.label}: #{message}")
127
144
  end
128
145
 
129
- # A RequestRejectedError for a request the provider rejected (a 400). via names how it failed (the error class,
130
- # the HTTP status); body is the provider's error body (a JSON String, or a Hash with String keys), of which only
131
- # the status and code tokens are repeated, never its message. http_status, when given, drops a code that only
132
- # repeats it. The params are pointed at only when the provider named one of them.
146
+ # What to pass as `cause:` when raising a Squishling error for a provider's exception: a ProviderFailure naming
147
+ # the original's class and the HTTP status (when given), with the original's backtrace. A provider exception's
148
+ # message and response usually hold the provider's response body, which can echo request content, and error
149
+ # trackers (Sentry, say) report the whole cause chain. Built fresh, never a copy of the original, so none of
150
+ # its state (a Faraday response, say) comes along. Transport errors that carry no body can be passed as they are.
151
+ def sanitized_cause(error, status: nil)
152
+ ProviderFailure.new([error.class, ("HTTP #{status}" if status)].compact.join(", "))
153
+ .tap { |failure| failure.set_backtrace(error.backtrace) }
154
+ end
155
+
156
+ # Classifies a provider's HTTP failure, so adapters sort the same status the same way: 408, 413, 429, and 5xx are
157
+ # LLMErrors; 401, 402, 403, 404, and a redirect are ConfigurationErrors (credentials, billing, model or endpoint:
158
+ # nothing a retry fixes); every other 4xx is a RequestRejectedError, unless #context_length? says the input
159
+ # outgrew the model, which is an LLMError too (a bigger model may take it). via names how it failed (the error
160
+ # class, the HTTP status) and is all of the failure that is repeated, with a rejection's status and code tokens.
161
+ # body is the provider's error body, as for #rejected_request_error. A nil status (no HTTP response) or a
162
+ # success status (a reply that was unusable) is an LLMError.
163
+ def http_failure(request, status:, body:, via:)
164
+ case status
165
+ when nil, 100..299, 408, 413, 429, 500.. then llm_error(request, via)
166
+ when 401, 403 then configuration_error(request, "the provider refused the credentials (#{via})")
167
+ when 402 then configuration_error(request, "#{via}: the provider reports a billing or quota problem")
168
+ when 404 then configuration_error(request, "#{via}: check the model name and the endpoint")
169
+ when 300..399 then configuration_error(request, "#{via}: redirects aren't followed; check the endpoint")
170
+ else rejected_or_overlong(request, status:, body:, via:)
171
+ end
172
+ end
173
+
174
+ # Whether a rejected request (a 400, or another 4xx not otherwise classified) means the input was too long for the
175
+ # model, which makes it an LLMError rather than a RequestRejectedError. The adapter decides: only it knows how its
176
+ # provider says so. The default recognizes a 400 whose structured error code or type is "context_length_exceeded",
177
+ # never reading the message. Override it to recognize more (and call super); when an adapter can't tell, the
178
+ # failure stays a rejection. status and body are those given to #http_failure.
179
+ def context_length?(status:, body:)
180
+ status == 400 && ErrorBody.context_length?(body)
181
+ end
182
+
183
+ def rejected_or_overlong(request, status:, body:, via:)
184
+ return llm_error(request, via) if context_length?(status:, body:)
185
+
186
+ rejected_request_error(request, via:, body:, http_status: status)
187
+ end
188
+
189
+ # A RequestRejectedError for a request the provider rejected (a 400, or another 4xx). via names how it failed
190
+ # (the error class, the HTTP status); body is the provider's error body (a JSON String, or a Hash with String
191
+ # keys), of which only the status and code tokens are repeated, never its message. http_status, when given, drops
192
+ # a code that only repeats it. The params are pointed at only when the provider named one of them.
133
193
  def rejected_request_error(request, via:, body:, http_status: nil)
134
194
  found = ErrorBody.read(body, http_status:)
135
195
  tokens = found.values_at(:status, :code).compact
@@ -219,7 +279,7 @@ module Squishling
219
279
  return value if value.respond_to?(:complete)
220
280
 
221
281
  raise ConfigurationError, "#{where} adapter must be an adapter (responding to complete), one of " \
222
- "#{type_list}, or a Hash with type:, got #{value.inspect}"
282
+ "#{type_list}, or a Hash with type:, got #{Appendices.describe(value)}"
223
283
  end
224
284
  end
225
285