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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2c50560e08f93a644589fb8ab529a41eca9ae201b81b9dd9233ecc9ea86873c5
4
- data.tar.gz: f8e2e5bca400137917567449ce299b59a05b40af787631154144f6b986ba8dbb
3
+ metadata.gz: 1d16d5c74c4eb8fee390ba827002dee27418f0cc66694d1fc2762893b1c027fb
4
+ data.tar.gz: 385bad5ba43f729d35260e7362955c35d5ffe7b4db731d1d6c0abe285e62d569
5
5
  SHA512:
6
- metadata.gz: fa16bccb992c1a7b040254e6c909bb1a36588c4e9fa068ce8eb7d6b5bcf4f2e0394429c15b5d4ab7e90ac39f2cf286367eb44475b7abfce9b9a2f177e1388b3f
7
- data.tar.gz: 97998785808aae5c1182fa6e0780990f512e2ea653856b853e89fbb330e09621f653355aabc6be2e294d2a13c031df5f94143e3bad85fa3f2315609d445bda0d
6
+ metadata.gz: 2a06a78caf781e12ea7dca4208bca5cc5bb008578cb3a26095b790477d82d2e0ebe5f574599b13acd36ffdfe83e0e269059e89b9f9c8285b61f55376f37e6002
7
+ data.tar.gz: 940b86dfd9a8d612360fdc76e05532320dc65ac5f02bbfcf1f5600a863b399f569de650f373921fdb2ac8665edf1b039ec329b19e4ef6b5b662c135341bbca7b
data/CHANGELOG.md CHANGED
@@ -7,6 +7,121 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.6.0] - 2026-11-01
11
+
12
+ Prompt caching, on by default. Read **Changed** before upgrading: requests now ask the provider to cache the stable
13
+ prompt, which can bill a cache write on providers that charge for one.
14
+
15
+ ### Added
16
+
17
+ - Prompt caching: a `cache` setting that asks the provider to cache the stable prompt (the purpose and the input note in
18
+ the system prompt), so a repeated call can read it back instead of paying for it again. It is `true`, `false`, or a
19
+ Hash of options such as `{ ttl: "1h" }`, set with `config.default_cache`, `squishling cache:`, `squish :method,
20
+ cache:`, `squish!(cache:)`, or an escalation step's `cache:`; the more specific level wins. There is no class-level
21
+ `cache false` macro, since it would collide with `ActiveRecord::Base.cache`: use `squishling cache: false`. The RubyLLM
22
+ adapter asks for it with `Chat#with_caching` and sends no cache controls when it is off; a System One judgment is never
23
+ cached. See [Prompt caching](docs/configuration.md#prompt-caching). (#79, #80)
24
+ - `Observer::Usage` gains `cache_read_tokens` and `cache_write_tokens`, and `Adapter::Request`, `ModelPath::Step`, and
25
+ `Testing::Request` gain a `cache` member (defaulting to `false`, so existing constructors keep working). Adapters that
26
+ report cache usage put `:cache_read_tokens` and `:cache_write_tokens` in `Adapter::Response#tokens`. (#79, #80)
27
+ - `config.budget_counts_cache_reads` (default `false`, `true` or `false` only): whether the tokens a request reads from the
28
+ provider's prompt cache count toward `max_total_input_tokens`. (#97)
29
+
30
+ ### Changed
31
+
32
+ - **Behavior change:** prompt caching is on by default (`config.default_cache` is `true`). With the RubyLLM adapter, a
33
+ provider that bills for cache writes (such as Anthropic Claude) may charge a write premium on the first call. Set
34
+ `config.default_cache = false`, or `cache: false` on a class, method, or step, to opt out. A model that can't take
35
+ cache controls may reject the request, which raises `ConfigurationError`: set `cache: false` for that model. The
36
+ OpenAI-compatible adapter ignores the setting. (#79, #80)
37
+ - **Behavior change:** `max_total_input_tokens` now counts the tokens written to the prompt cache, which RubyLLM
38
+ reports apart from `input_tokens`, so a call that writes a large cached prompt can reach the budget sooner than before.
39
+ Tokens read from the cache are left out unless `budget_counts_cache_reads` is `true`. Output tokens are unchanged.
40
+ (#79, #80, #97)
41
+ - **Behavior change:** the OpenAI-compatible adapter reports `input_tokens` net of cached tokens, as every adapter
42
+ does (the cached reads go to `cache_read_tokens`, and a server's cache writes to `cache_write_tokens`). A custom
43
+ adapter's `input_tokens` should likewise exclude cached tokens. Code that read `input_tokens` from `squawk` usage or an
44
+ observer for this adapter will see a smaller number on cache hits. (#79, #80)
45
+
46
+ ### Documented
47
+
48
+ - The adapter docs list the separate [`squishling-apple_fm`](https://github.com/Coolhand-Labs/squishling-apple-fm-adapter)
49
+ and [`squishling-claude_code`](https://github.com/Coolhand-Labs/squishling-claude-code-adapter) adapter gems. (#94)
50
+
51
+ ## [0.5.1] - 2026-10-31
52
+
53
+ The v0.5.0 red-team follow-ups (#70): data-egress, secret-leakage, and misclassification fixes. Several of them change
54
+ behavior that used to work, so read **Changed** before upgrading.
55
+
56
+ ### Added
57
+
58
+ - The OpenAI-compatible adapter takes `allow_insecure_http:` (default `false`), `max_response_bytes:` (default 8 MiB), and
59
+ `total_timeout:` (default `open_timeout + 2 * read_timeout`, per attempt). See **Changed** for what they guard.
60
+ (#74, #86)
61
+ - `keep_cause: true` on the RubyLLM adapter keeps the provider's original exception as `cause`. (#76, #84)
62
+ - `Adapter::Base#http_failure(request, status:, body:, via:)`, an overridable `context_length?(status:, body:)` hook, and
63
+ `sanitized_cause(error, status:)` for custom adapters: one shared mapping from an HTTP status to `LLMError`,
64
+ `ConfigurationError`, or `RequestRejectedError`, and a body-free `cause`. See [Adapters](docs/adapters.md). (#72, #76,
65
+ #84, #88)
66
+ - `squawk` metadata gains `stopped:` (`:budget`, `:disagreement`, or `nil` for an ordinary attempt). (#73, #87)
67
+
68
+ ### Changed
69
+
70
+ - **Behavior change:** a `NotImplementedError` raised by code a squished method calls (an abstract method on another
71
+ object, a helper, a block) now propagates instead of sending the method's arguments to the provider. Only the
72
+ method's own stub routes to the LLM: `def x = raise NotImplementedError`, `define_method`, a prepended module, and an
73
+ undefined method. To use the LLM from a rescue deeper in the stack, call `squish!` in the method. (#71, #83)
74
+ - **Behavior change:** `error.cause` from the RubyLLM adapter is now an `Adapter::ProviderFailure` that names only the
75
+ original's class and HTTP status (`RubyLLM::RateLimitError, HTTP 429`) and keeps its backtrace, because the original's
76
+ message is the provider's response body, which can echo request content and which error trackers such as Sentry report
77
+ from the cause chain. This reverses 0.4.0's choice to keep the original: code that read `e.cause.message` or
78
+ `e.cause.is_a?(RubyLLM::...)` needs `keep_cause: true`. The OpenAI-compatible adapter's transport causes carry no body
79
+ and are unchanged. (#76, #84)
80
+ - **Behavior change:** a provider failure is classified by the adapter from its HTTP status and structured error
81
+ `code`/`type`, no longer from the provider's message text. Both adapters now agree: 408, 413, 429, and 5xx are
82
+ `LLMError`; 401, 402, 403, 404, and 3xx are `ConfigurationError`; every other 4xx is a `RequestRejectedError`. On
83
+ RubyLLM, 402, 404, and 422 were retryable `LLMError`s. A context overflow is an `LLMError` (so it retries and
84
+ escalates) only when the body's `code`/`type` is `context_length_exceeded`, the adapter recognizes it (the
85
+ OpenAI-compatible adapter still matches the usual wordings, no longer a bare "maximum ... tokens"), or RubyLLM raised
86
+ its `ContextLengthExceededError`; one that is only in the message text now raises `RequestRejectedError`. (#72, #88)
87
+ - **Behavior change:** the OpenAI-compatible adapter refuses to send an `api_key` or `Authorization` header over
88
+ `http://` to a host that isn't loopback (`localhost`, `*.localhost`, `127.0.0.0/8`, `::1`), raising
89
+ `ConfigurationError`. A LAN or Docker setup such as `http://ollama:11434/v1` needs `allow_insecure_http: true`.
90
+ Successful responses over `max_response_bytes` raise `LLMError`, requests send `Accept-Encoding: identity` and a
91
+ compressed successful reply is refused, and `total_timeout:` bounds a whole attempt, not each read. None of those is
92
+ retried by the adapter. A failure status (4xx, 5xx, redirect) is classified by its status even when its body is
93
+ compressed or over the cap. (#74, #86)
94
+ - **Behavior change:** a hand-written Hash `output_schema` with `properties` but no `type: "object"`, at the root or
95
+ nested (a property, array `items`, an `optional` branch, a `$ref` target), now raises `ConfigurationError` when the
96
+ schema is built, and `Squishling.verify` reports it. Add `type: "object"` (or a union that includes it). Schematist
97
+ schemas are unaffected. (#77, #81)
98
+ - **Behavior change:** a schema with a remote or unresolvable `$ref` now raises `ConfigurationError` when it is built
99
+ (and in `verify`), not a raw `JSONSchemer::UnknownRef` on the first reply. A Hash or Array argument that contains
100
+ itself raises `ConfigurationError`, not `SystemStackError`. `cached_content` joins the reserved `params` keys. (#78,
101
+ #85)
102
+ - **Behavior change:** the `squawk` hook now also runs once when a call ends on `BudgetExhaustedError` or
103
+ `DisagreementError`, with `output: nil`, `final: true`, and `stopped:` set, so `squawk_on: :final` and `:rejections`
104
+ see those endings. A hook that assumes every call has output or usage should skip calls where `metadata[:stopped]` is
105
+ set. (#73, #87)
106
+ - `Marshal.dump` of an `OpenAICompatible` adapter (or a config holding one) now raises `TypeError`, and its API key and
107
+ header values show as `[REDACTED]` in `to_yaml` and `as_json`, as they already did in `inspect`. Rebuild the adapter
108
+ from its options instead of caching a dump. (#75, #82)
109
+
110
+ ### Fixed
111
+
112
+ - A provider 400 whose error `message`, `code`, or `type` is not valid UTF-8 (for example an echo cut mid-character) now
113
+ raises `RequestRejectedError` like any other 400, instead of a bare `ArgumentError` that is not a Squishling error.
114
+ - A `ConfigurationError` for a rejected `config.adapter`, `observer`, or `squawk` now names the object's class instead of
115
+ its `inspect` output, which could print an instance variable such as an access token.
116
+ - `Schema::CACHE` holds its keys weakly, so schema classes replaced by a Rails code reload can be collected. Two equal
117
+ Hash schemas now share one cached `Schema`. (#78, #85)
118
+
119
+ ### Documented
120
+
121
+ - `Observer::Call#purpose` is the fully rendered system prompt, including `append_to_purpose` source and procs: treat it
122
+ as sensitive. `Testing::Stubs` hooks persist after `Testing.reset!`; `Testing.no_llm_call` swaps the process-wide
123
+ adapter, so it is not safe under parallel test threads; `Run#produced?` compares by identity. (#78, #85)
124
+
10
125
  ## [0.5.0] - 2026-10-28
11
126
 
12
127
  ### Added
data/README.md CHANGED
@@ -151,7 +151,7 @@ A squishling class needs a **purpose** (the system prompt) and an **output schem
151
151
  validated on both paths). A squished call goes to the LLM when:
152
152
 
153
153
  - its `squish_when` predicate is truthy for these inputs,
154
- - the method has no implementation (it isn't defined, or raises `NotImplementedError`), or
154
+ - the method has no implementation (it isn't defined, or its own body raises `NotImplementedError`), or
155
155
  - the Ruby implementation calls `squish!`.
156
156
 
157
157
  Otherwise the Ruby runs, and whatever it returns is validated and typed like LLM output.
@@ -172,7 +172,7 @@ sees it right where the value goes, and the purpose stays short and about the go
172
172
  the OpenAI-compatible adapter (OpenAI, Ollama, vLLM, LM Studio, Together, Groq, … over plain HTTP), or write your
173
173
  own in one method.
174
174
  - **Any provider and model**: set a universal, per-class, per-method, or per-call model, plus layered generation params (temperature,
175
- reasoning effort, top_p, …).
175
+ reasoning effort, top_p, …) and [prompt caching](docs/configuration.md#prompt-caching) (on by default, opt out per class, method, or call).
176
176
  - **Model escalation**: declare an `escalation:` instead of a `model:`, with per-step `attempts:`, `priority:` (models tied on priority take turns going first), provider,
177
177
  params, `forward_rejected:`, `retry_temperature:`, and `include_when:` (leave a model out of calls where a Proc is falsy). Invalid output (with its errors fed back) or a provider failure moves on to the next attempt. Steps can
178
178
  cross providers, e.g. a local Qwen model on Ollama, then Anthropic Claude Haiku on AWS Bedrock, then Claude Opus:
@@ -210,8 +210,8 @@ sees it right where the value goes, and the purpose stays short and about the go
210
210
  - **Defined failure behavior**: provider errors become `Squishling::LLMError`, and `squish_fallback` lets you decide
211
211
  what to return when every attempt fails.
212
212
  - **Observability**: the opt-in [`squawk`](docs/failures.md#observing-every-attempt-squawk) hook sends each attempt's
213
- raw output (or only the rejected and retried ones) to your error tracker. Model output stays out of
214
- error messages and logs otherwise.
213
+ raw output (or only the rejected and retried ones), and the end of a call that a token budget or a disagreement
214
+ stopped, to your error tracker. Model output stays out of error messages and logs otherwise.
215
215
  - **Opt-in context**: only method arguments, the instance state you name with `squish_context`, the `context:` you
216
216
  pass to `squish!`, and the source you choose to append are sent to the provider. The one addition: when
217
217
  [escalation](docs/configuration.md#models-and-escalation) moves to the next step, that step also sees the previous
data/docs/adapters.md CHANGED
@@ -3,12 +3,14 @@
3
3
  An **adapter** is how Squishling reaches a model. Squishling builds the request (system prompt, conversation so far,
4
4
  strict output schema, generation params), the adapter makes one completion and returns the model's output, and
5
5
  Squishling does the rest: validation, `squish_validate`, retries and escalation, harnesses, `squawk`, and fallbacks.
6
- Two adapters ship, and you can write your own.
6
+ Two adapters ship, separate gems add more (below), and you can write your own.
7
7
 
8
8
  | Adapter | Reaches | Needs |
9
9
  |---|---|---|
10
10
  | [`:ruby_llm`](#ruby_llm) | OpenAI, Anthropic Claude, Google Gemini, AWS Bedrock, OpenRouter, and every provider [RubyLLM](https://rubyllm.com) supports | `gem "ruby_llm"` |
11
11
  | [`:openai_compatible`](#openai-compatible-endpoints) | Any server that speaks OpenAI's Chat Completions API: OpenAI, Ollama, vLLM, LM Studio, llama.cpp, Together, Groq, … | nothing (Ruby's `Net::HTTP`) |
12
+ | [`squishling-apple_fm`](https://github.com/Coolhand-Labs/squishling-apple-fm-adapter) (separate gem) | The on-device model built into macOS (Apple Intelligence): free and offline, for development | `gem "squishling-apple_fm"`, macOS 26+ on Apple Silicon |
13
+ | [`squishling-claude_code`](https://github.com/Coolhand-Labs/squishling-claude-code-adapter) (separate gem) | Your local Claude Code CLI (`claude -p`), on your own Claude subscription instead of API billing, for development | `gem "squishling-claude_code"`, Claude Code installed and logged in |
12
14
  | [Your own](#writing-your-own) | Anything | a class with one method |
13
15
 
14
16
  Squishling itself depends on neither RubyLLM nor any provider SDK.
@@ -37,6 +39,19 @@ Everything works as it did before adapters: configure provider API keys with `Ru
37
39
  use `provider:` for models missing from RubyLLM's registry. See [Configuration](configuration.md). Transport-level
38
40
  retries are RubyLLM's (`RubyLLM.config.max_retries`, `request_timeout`).
39
41
 
42
+ | Option | Default | Description |
43
+ |---|---|---|
44
+ | `keep_cause` | `false` | RubyLLM's exception holds the provider's response body, which can echo your request, and error trackers report the whole `cause` chain. By default the errors the adapter raises carry a sanitized `cause` (the class and HTTP status only). `true` keeps RubyLLM's original exception there. See [the cause of a provider failure](failures.md#the-cause-of-a-provider-failure). |
45
+
46
+ **Failures** are sorted by the HTTP status of the error's response, the same way as for the OpenAI-compatible adapter
47
+ below (an error with no response, such as a timeout, is sorted by its class). RubyLLM's own error classes are not what
48
+ decides: on a 400 its middleware picks a class from the provider's message text, so a bad parameter whose message says
49
+ "per day" would otherwise look like a rate limit. The one RubyLLM class that is honored over the status is
50
+ `RubyLLM::ContextLengthExceededError`, an `LLMError`, since RubyLLM is where each provider's wording for an overlong
51
+ prompt is known. RubyLLM picks that class from the message on a 400, with wording broader than the OpenAI-compatible
52
+ adapter's, so a bad parameter whose message happens to match is retried as an overflow rather than rejected. Each of
53
+ these errors carries a sanitized `cause` (see `keep_cause` above).
54
+
40
55
  This is the only built-in adapter that supports `type: :judgment` judges ([System One decision models](harnesses.md#the-judge)).
41
56
 
42
57
  ## OpenAI-compatible endpoints
@@ -56,28 +71,52 @@ end
56
71
  | Option | Default | Description |
57
72
  |---|---|---|
58
73
  | `base_url` | `https://api.openai.com/v1` | The API root. Requests go to `{base_url}/chat/completions`. Must be `http(s)` and carry no credentials, query, or fragment. |
59
- | `api_key` | `ENV["OPENAI_API_KEY"]` for OpenAI's own endpoint, else none | A String, or a callable returning one (called once per completion, outside the adapter's retry handling, so rotating keys work and its exceptions reach you unchanged). Sent as a bearer token; omitted when blank. The key is sent as-is, so use `https://` for anything off your machine or trusted network. `OPENAI_API_KEY` is read only for OpenAI's own `https://api.openai.com`, so it can never go to another host: pass `api_key:` for any other endpoint that needs one. |
74
+ | `api_key` | `ENV["OPENAI_API_KEY"]` for OpenAI's own endpoint, else none | A String, or a callable returning one (called once per completion, outside the adapter's retry handling, so rotating keys work and its exceptions reach you unchanged). Sent as a bearer token; omitted when blank. The key is sent as-is, and not over plain `http://` to another machine unless `allow_insecure_http: true` (below). `OPENAI_API_KEY` is read only for OpenAI's own `https://api.openai.com`, so it can never go to another host: pass `api_key:` for any other endpoint that needs one. |
60
75
  | `headers` | `{}` | Extra request headers, e.g. `{ "OpenAI-Organization" => "org-…" }` or a gateway's own. |
61
76
  | `default_model` | `nil` | The model for steps that don't name one. Without it, a step with no model raises `ConfigurationError`. |
62
- | `open_timeout` / `read_timeout` | `10` / `120` | Seconds. |
77
+ | `allow_insecure_http` | `false` | A credential (the `api_key`, or a header named `Authorization`, `Proxy-Authorization`, `api-key`, or `X-Api-Key`; other headers aren't inspected) is never sent over plain `http://` to a host that isn't this machine: building the adapter (or, for a callable key, making the request) raises `ConfigurationError`. Loopback hosts (`localhost`, `*.localhost`, `127.0.0.0/8`, `::1`) are exempt, judged by the name as written and never resolved, so a `*.localhost` name counts even on a resolver that doesn't map it to loopback (use the bare `localhost`, or an IP, if you can't rely on that). Set `true` to send it anyway, for a trusted LAN or container network. With no credential, `http://` to any host is fine. |
78
+ | `open_timeout` / `read_timeout` | `10` / `120` | Seconds. `read_timeout` restarts at every read, so it alone doesn't bound a request. |
79
+ | `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. |
80
+ | `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. |
63
81
  | `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. |
64
82
  | `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. |
65
83
  | `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. |
66
84
 
85
+ **Credentials stay out of serializers.** The adapter holds the `api_key` and the `headers` (which may carry an
86
+ `api-key` or `Authorization` value) in an opaque wrapper, not in plain instance variables, so logging or caching the
87
+ adapter or `Squishling.config` can't write them out: `inspect`, `to_s`, `pp`, `to_yaml`, `as_json` (including
88
+ ActiveSupport's `instance_values` walk) and `to_json` show `[REDACTED]`, and `Marshal.dump` raises a `TypeError`
89
+ instead of dumping the key. This guards against accidental serialization (a logged config, an error tracker, a cache
90
+ dump), not against code running in your process, which can still reach the value. If you write your own adapter,
91
+ keep credentials out of plain instance variables the same way, or define `encode_with`, `as_json`, and
92
+ `marshal_dump` to omit them.
93
+
67
94
  **How params map.** `temperature` → `temperature`; `max_output_tokens` → `max_tokens_param`; `thinking: { effort: }` →
68
95
  `reasoning_effort` (`true`/`false` leave the model's default, and a `budget:` or `display:` raises
69
96
  `ConfigurationError`, since Chat Completions has no field for them). Any other param (`top_p`, `seed`, …) goes into
70
97
  the request body as given. Squishling's own keys (`model`, `messages`, `response_format`, `n`, `stream`) always win.
71
98
  `provider:` has no meaning here and is ignored.
72
99
 
73
- **Failures.** Every HTTP status of 300 or above except 408, 429, and 5xx (401, 403, 404, 400, 422, a redirect, …) raises `ConfigurationError`, a `RequestRejectedError` for a 400 or other rejected request (never retried or escalated; a 400 that
74
- reports an overlong context, and a 413, are `LLMError`s, since they depend on the input; a 400 counts as an overlong
75
- context when its error code is `context_length_exceeded` or its message uses the usual wording ("context length", "too many
76
- tokens", …), which the message is only matched against, never repeated). 408, 429, 5xx, timeouts, and
77
- connection errors raise `LLMError` once the adapter's own retries are used up. Messages carry the status or error
78
- class only; a rejected request (400) also carries the server's error status and code when they are plain tokens (as
79
- `provider_status` and `provider_code`). The server's message, the response body, and the API key never appear in an error or log. Redirects
80
- aren't followed, so the key can't be sent to another host.
100
+ **Failures.** The HTTP status decides (see [the status mapping](#the-error-contract)): 408, 413, 429, 5xx, timeouts, and
101
+ connection errors raise `LLMError` once the adapter's own retries are used up; 401, 402, 403, 404, and a redirect raise
102
+ `ConfigurationError`; any other 4xx (400, 409, 422, …) raises `RequestRejectedError`, never retried or escalated. The
103
+ one exception is a 400 that reports an overlong context, which is an `LLMError` too, since it depends on the input (a
104
+ bigger model may take it). This adapter recognizes one when the error's `code` or `type` is `context_length_exceeded`, or,
105
+ for servers that send neither (vLLM, Ollama, llama.cpp), when its message uses the usual wording ("context length",
106
+ "context window", "context size", "too many tokens", "prompt is too long"). The message is only matched against that
107
+ wording, never repeated; the match is deliberately narrow, so a wording it doesn't know is a rejected request, not a
108
+ retry. Messages carry the status or error class only; a rejected request also carries the server's error status and code
109
+ when they are plain tokens (as `provider_status` and `provider_code`). The server's message, the response body, and the
110
+ API key never appear in an error or log. Redirects aren't followed, so the key can't be sent to another host.
111
+
112
+ **Response limits.** The adapter sends `Accept-Encoding: identity` (it replaces any `Accept-Encoding` header you set)
113
+ and reads the body in chunks. A successful (2xx) response that is compressed anyway, one over `max_response_bytes`,
114
+ and any response that takes longer than `total_timeout` each raise an `LLMError` naming the limit (never the URL or
115
+ any of the response) and are not retried by the adapter, since the same request would meet the same limit;
116
+ escalation and `squish_fallback` handle it like any other `LLMError`. A failure status (4xx, 5xx, or a redirect) is
117
+ classified by its status alone even when its body is compressed or over the cap: the body is dropped unread, so a
118
+ gateway's gzipped 401 is still a `ConfigurationError`, not a transport failure that `squish_fallback` would absorb,
119
+ and a 503 is still retried.
81
120
 
82
121
  ## Writing your own
83
122
 
@@ -105,12 +144,21 @@ class AcmeAdapter < Squishling::Adapter::Base
105
144
  )
106
145
  rescue Acme::AuthError
107
146
  raise configuration_error(request, "Acme rejected the credentials")
108
- rescue Acme::BadRequest => e
109
- # a 400: repeats only the body's status and code, and points at a param only if the provider named one
110
- raise rejected_request_error(request, via: "Acme, HTTP 400", body: e.response_body, http_status: 400)
147
+ rescue Acme::HTTPError => e
148
+ # sorted by status like the built-in adapters; only the status and a rejection's status/code tokens are repeated
149
+ raise http_failure(request, status: e.status, body: e.response_body, via: "Acme, HTTP #{e.status}")
111
150
  rescue Acme::Error => e
112
151
  raise llm_error(request, "Acme failed (#{e.class})")
113
152
  end
153
+
154
+ private
155
+
156
+ # Optional: what an overlong prompt looks like for Acme. The default (super) already recognizes a 400 whose error
157
+ # code or type is "context_length_exceeded"; add whatever else Acme's errors tell you, without reading its message.
158
+ # body is the provider's error body, a JSON String or a Hash (or nil); ErrorBody.error reads either safely.
159
+ def context_length?(status:, body:)
160
+ super || (status == 400 && Squishling::Adapter::ErrorBody.error(body)&.[]("code") == "prompt_too_long")
161
+ end
114
162
  end
115
163
 
116
164
  Squishling.configure { |config| config.adapter = AcmeAdapter.new }
@@ -124,21 +172,23 @@ Squishling.register_adapter(:acme, AcmeAdapter)
124
172
 
125
173
  | Field | |
126
174
  |---|---|
127
- | `label` | `"Class#method"`, to prefix your error messages (the `configuration_error` / `llm_error` helpers do; `rejected_request_error(request, via:, body:, http_status:)` builds the error for a rejected request, from a JSON String or String-keyed Hash body). |
175
+ | `label` | `"Class#method"`, to prefix your error messages (the `configuration_error` / `llm_error` helpers do; `http_failure(request, status:, body:, via:)` sorts an HTTP failure; `rejected_request_error(request, via:, body:, http_status:)` builds the error for a rejected request, from a JSON String or String-keyed Hash body). |
128
176
  | `model`, `provider` | The escalation step's, or `nil` when it names none (use your own default). What `provider:` means is up to you. |
129
177
  | `instructions` | The system prompt. |
130
178
  | `messages` | The conversation so far, ending with the user message to answer. After invalid output, Squishling appends your previous answer and a retry message; you never keep history. |
131
179
  | `schema` | `{ "name", "description", "schema", "strict" => true }`: the strict structured-output payload, without the conditional keywords providers can't take. |
132
180
  | `params` | The resolved [generation params](configuration.md#generation-params): the portable `:temperature`, `:max_output_tokens`, `:thinking`, plus provider-specific keys. Squishling has already rejected the keys it owns. Translate the portable ones for your provider; pass the rest through if it takes them. |
181
+ | `cache` | The [prompt caching](configuration.md#prompt-caching) to ask for: `false` (none), or a Hash of options (`{}` for the provider's default, `{ ttl: "1h" }`). Ignore it if your provider has no prompt caching or caches on its own. |
133
182
 
134
183
  ### The response
135
184
 
136
185
  `Squishling::Adapter::Response.new(content:, model:, tokens:, finish_reason:)`. `content` is the model's output as a
137
186
  String, or a Hash if you parsed it; `nil` or empty counts as invalid output and is retried. `model` is the id the
138
- provider reports. `tokens` is a Hash (`:input_tokens`, `:output_tokens`, and anything else you have); `{}` when
187
+ provider reports. `tokens` is a Hash (`:input_tokens`, which leaves out the tokens read from or written to the prompt cache, `:output_tokens`, `:cache_read_tokens`, `:cache_write_tokens`, and anything else you have); `{}` when
139
188
  unknown. These feed [`squawk`'s `usage`](failures.md#observing-every-attempt-squawk), the [observer](observers.md)'s `Usage`, and the
140
- [token budget](failures.md#capping-a-calls-cost-token-budgets), which counts `:input_tokens` and `:output_tokens`
141
- (a response with none never exhausts a budget).
189
+ [token budget](failures.md#capping-a-calls-cost-token-budgets), which counts `:input_tokens`, `:cache_write_tokens` and
190
+ `:output_tokens`, and `:cache_read_tokens` only with `budget_counts_cache_reads` (a response with none never exhausts a
191
+ budget).
142
192
  `finish_reason` is why the provider stopped, as a Symbol: `:stop`, `:max_tokens` (the output cap cut the reply off),
143
193
  `:content_filter`, `:tool_calls`, or the provider's own spelling; leave it out (`nil`) when unknown. Map your
144
194
  provider's "length" reason to `:max_tokens`, so Squishling can [tell a cutoff from a wrong
@@ -146,14 +196,36 @@ answer](failures.md#a-cutoff-or-a-wrong-answer).
146
196
 
147
197
  ### The error contract
148
198
 
199
+ Classifying a provider failure is the adapter's job; what happens next is Squishling's.
200
+
201
+ **An adapter defines** which error a failure is. Only the adapter knows its provider's status codes, error bodies, and
202
+ how it says a prompt is too long:
203
+
149
204
  | Raise | When | What Squishling does |
150
205
  |---|---|---|
151
- | `Squishling::ConfigurationError` | Bad credentials, a request the provider rejects, an unknown model: anything a retry can't fix | Raised at once. Never retried, escalated, or sent to `squish_fallback`. |
206
+ | `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`. |
207
+ | `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. |
152
208
  | `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`). |
153
209
 
154
- Keep the provider's own message out of both: it can echo request content or part of a key, and ours reach logs and
155
- error trackers. Put the original on `cause` (raising inside a `rescue` does that for you). Any other exception
156
- propagates unwrapped and is never retried, so map your transport's errors. Return anything but an
210
+ **Squishling manages** everything that follows from the class: retries, escalation, the fallback, the token budget, and
211
+ `squawk`. It never looks at a provider's status, code, or message; it sees only the error class your adapter raised.
212
+
213
+ For an HTTP provider, `http_failure(request, status:, body:, via:)` does the sorting, so every adapter treats a status
214
+ the same way: 408, 413, 429, 5xx, no status at all (a timeout), and a success status (a reply that was unusable) are
215
+ `LLMError`s; 401, 402, 403, 404, and a redirect are `ConfigurationError`s;
216
+ every other 4xx is a `RequestRejectedError`. `via` ("Acme, HTTP 400") is the only text repeated, plus the status and
217
+ code tokens of a rejection. Between those, one case depends on the provider: a rejected request whose input was too
218
+ long for the model should be an `LLMError`, since a bigger model may take it. `http_failure` asks the
219
+ `context_length?(status:, body:)` hook. Its default recognizes a 400 whose error `code` or `type` is
220
+ `context_length_exceeded` and never reads the message; override it (calling `super`) to recognize what your provider
221
+ sends. Where the adapter can't tell, leave it: the failure stays a `RequestRejectedError`, which is never absorbed.
222
+
223
+ Keep the provider's own message out of every error you raise: it can echo request content or part of a key, and ours
224
+ reach logs and error trackers, and so do trackers that walk the `cause` chain. If the provider's exception carries a
225
+ response body (an HTTP client error), don't leave it as the `cause` that raising inside a `rescue` sets: pass
226
+ `cause: sanitized_cause(error, status: …)`, which builds a stand-in with only the class, the status, and the
227
+ backtrace. An exception that carries no body (a timeout, a refused connection) can stay as the `cause`. Any other
228
+ exception propagates unwrapped and is never retried, so map your transport's errors. Return anything but an
157
229
  `Adapter::Response` and Squishling raises `ConfigurationError`.
158
230
 
159
231
  ### Optional hooks
@@ -32,9 +32,11 @@ end
32
32
  | `default_escalation` | `nil` | The universal [escalation](#models-and-escalation): models tried in order. Assigning it clears `default_model`, and vice versa. |
33
33
  | `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. |
34
34
  | `default_params` | `{}` | Generation params for every call (temperature, reasoning effort, top_p, …), overridable per class, per method, and per escalation step. See [Generation params](#generation-params). |
35
+ | `default_cache` | `true` | Asks the provider to cache the stable prompt on every request: `true`, `false`, or a Hash of options such as `{ ttl: "1h" }`. Overridable per class, per method, per escalation step, and per `squish!` call. See [Prompt caching](#prompt-caching). |
35
36
  | `default_max_total_output_tokens`, `default_max_total_input_tokens` | `nil` (no limit) | The most output (or input) tokens one call may use across all its requests; once reached, the call raises `BudgetExhaustedError` instead of making another attempt. Overridable per class (`squishling max_total_output_tokens: ...`), per method, and per `squish!` call. See [Capping a call's cost](failures.md#capping-a-calls-cost-token-budgets). |
36
- | `squawk` | `nil` | A callable run after every LLM attempt (see `squawk_on`) 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). |
37
- | `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). Also settable per class and per method. |
37
+ | `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). |
38
+ | `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). |
39
+ | `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. |
38
40
  | `observer` | `nil` | An around-style hook for every provider request: `:coolhand`, any object responding to `around(call)`, or `false` for none. `nil` uses the [Coolhand observer](coolhand.md) when the `coolhand` gem is configured. See [Observers](observers.md). |
39
41
  | `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). |
40
42
  | `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). |
@@ -76,6 +78,7 @@ Each step is a model name, or a Hash with:
76
78
  | `retry_temperature:` | none | A Numeric `temperature` for this step's retries in the same chat (not its first attempt), to nudge a model that keeps sending the same rejected reply. Don't use it on a step that sets `thinking`, since reasoning models reject `temperature`. |
77
79
  | `forward_rejected:` | `true` | Set `false` to start this step from the original input alone, without the previous step's rejected output and its errors (see below). |
78
80
  | `params:` | `{}` | [Generation params](#generation-params) for this step, merged over the class and method params key by key. |
81
+ | `cache:` | the level's `cache:` | [Prompt caching](#prompt-caching) for this step: `false`, `true`, or a Hash of options. It replaces the level's value, since caching behaves differently per model and provider. |
79
82
 
80
83
  Without `priority:`, steps run in the order written. With it, the order is explicit and doesn't depend on position:
81
84
 
@@ -166,7 +169,7 @@ end
166
169
  Passing both `model:` and `escalation:` in one declaration raises `ConfigurationError`, and so does a list passed as
167
170
  `model:`. Across separate declarations (a reopened class, or two config assignments), the latest one wins.
168
171
 
169
- Consecutive attempts of the same step (same model, provider, params, `forward_rejected:`, and `retry_temperature:`, e.g. `attempts: 2`)
172
+ Consecutive attempts of the same step (same model, provider, params, `cache:`, `forward_rejected:`, and `retry_temperature:`, e.g. `attempts: 2`)
170
173
  continue one conversation. Moving to a different step starts a fresh chat with the original input plus the previous
171
174
  output and why it was rejected, so no provider-specific history crosses providers. That rejected output is
172
175
  model-generated and is sent to the next step's provider, even when it is a different one, truncated to 4,000
@@ -242,7 +245,7 @@ end
242
245
 
243
246
  - Keys that Squishling or the adapter control (`model`, `messages`, `input`, `instructions`, `system`, `stream`,
244
247
  `response_format`, `text`, `output_config`, `tools`, `tool_choice`, `functions`, `function_call`, `schema`, and the camelCase and plural
245
- spellings other providers use, such as `systemInstruction`, `toolConfig`/`tool_config`, `outputConfig`, `inputs`, …)
248
+ spellings other providers use, such as `systemInstruction`, `cachedContent`/`cached_content`, `toolConfig`/`tool_config`, `outputConfig`, `inputs`, …)
246
249
  raise `ConfigurationError`, because they would override the model, the conversation, or the strict output format.
247
250
  - **Nested containers** such as Gemini's `generationConfig` (and `generation_config` for Gemini Interactions) and
248
251
  Mistral Conversations' `completion_args` accept ordinary settings, but reject the keys inside them that carry the
@@ -257,9 +260,53 @@ end
257
260
  - If a provider rejects a param, the call raises `Squishling::ConfigurationError` naming the params. It isn't
258
261
  retried or sent to `squish_fallback`. See [Failure handling](failures.md).
259
262
 
263
+ ## Prompt caching
264
+
265
+ Squishling puts the stable text (the purpose and the note on the inputs) in the system prompt and the
266
+ per-call data in the user message, which is the order provider prompt caches want. With the RubyLLM adapter, caching is
267
+ on by default: each request goes out with RubyLLM's `with_caching`, so Anthropic Claude (whose caching is opt-in) caches
268
+ the prompt, and a call's retries within one escalation step reuse it. The cache point RubyLLM sets covers the request up
269
+ to its last message, so the per-call data is written to the cache too, and only a later request that shares that prefix
270
+ reads it back. The OpenAI-compatible adapter ignores the setting, and providers that cache on their own (OpenAI, Google
271
+ Gemini) still do.
272
+
273
+ `cache` is `true`, `false`, or a Hash of options for the provider (`{ ttl: "1h" }`). Each level overrides the one above
274
+ it, and `nil` inherits; a Hash replaces the level above's rather than merging into it:
275
+
276
+ ```ruby
277
+ Squishling.configure { |c| c.default_cache = false } # every call (default: true)
278
+
279
+ class Triager
280
+ include Squishling
281
+ squishling cache: false # this class (and subclasses)
282
+
283
+ squish :triage, cache: { ttl: "1h" } do # one method
284
+ string :priority
285
+ end
286
+ end
287
+
288
+ squish!(cache: false, escalation: ["claude-opus-5-5"]) # one hand-off
289
+ # escalation: [{ model: "claude-haiku-4-5", cache: false }, "claude-sonnet-5-5"] # one step
290
+ ```
291
+
292
+ - **Writing a cache entry costs extra.** Anthropic charges a premium for the write (about 1.25x the input price for the
293
+ 5-minute lifetime, more for `ttl: "1h"`) and pays it back only when a later request reads the entry. A class with a
294
+ long prompt that is called once and never again costs slightly more with caching on; set `cache: false` for it.
295
+ - **Not every model takes cache controls.** A model that can't cache may reject them (a provider 400, which is a
296
+ `ConfigurationError`, never retried); set `cache: false` for it, per class, method, or escalation step.
297
+ - **A prefix below the model's minimum is not cached.** Providers ignore caching under a model-specific minimum, so a
298
+ short prompt is a harmless no-op, not an error.
299
+ - **An option the provider doesn't take raises `ConfigurationError`** when the request is made (Anthropic accepts `ttl`,
300
+ for instance). Explicit Gemini content caches (`id:`) are not supported.
301
+ - **Judgments** (`type: :judgment` judges) don't use a chat, so they are never cached.
302
+ - **Token budgets** count the tokens written to the cache but not those read back, so a hit doesn't spend
303
+ `max_total_input_tokens`; `budget_counts_cache_reads = true` counts reads too.
304
+ - **See whether it hits** in `cache_read_tokens` and `cache_write_tokens`: they are in `squawk`'s `usage` and on the
305
+ [observer](observers.md#what-yield-returns)'s `Usage` (nil when the provider reports none).
306
+
260
307
  ## Inheritance
261
308
 
262
- Subclasses inherit the model or escalation and its provider (as a pair), harness, generation params (merged key by key), token budgets (limit by limit), purpose, output schema,
309
+ Subclasses inherit the model or escalation and its provider (as a pair), harness, generation params (merged key by key), prompt caching, token budgets (limit by limit), purpose, output schema,
263
310
  `squish_when` predicate, `squish_context` names, `squish_validate`, `squish_fallback`, and every `squish` declaration. Overrides in a subclass, including
264
311
  overridden methods, are routed the same way.
265
312
 
@@ -269,6 +316,6 @@ overridden methods, are routed the same way.
269
316
  ## Per-call overrides
270
317
 
271
318
  Inside a squished method, `squish!` sends the call to the LLM with its own `purpose:`,
272
- `append_to_purpose:`, `context:`, `model:` or `escalation:` (with `provider:`), `params:`, `harness:`, and
319
+ `append_to_purpose:`, `context:`, `model:` or `escalation:` (with `provider:`), `params:`, `cache:`, `harness:`, and
273
320
  `max_total_output_tokens:`/`max_total_input_tokens:`. Each layers over the method and class
274
321
  settings the same way they layer over each other. See [Handing off to the LLM](routing.md#handing-off-to-the-llm-with-squish).