squishling 0.6.0 → 0.7.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1d16d5c74c4eb8fee390ba827002dee27418f0cc66694d1fc2762893b1c027fb
4
- data.tar.gz: 385bad5ba43f729d35260e7362955c35d5ffe7b4db731d1d6c0abe285e62d569
3
+ metadata.gz: 9f314a037f76cbb7f5537e24e772c2e943271263be0170c4d87a2216085cb5c0
4
+ data.tar.gz: b8898c499589a5a5a82673497eb424737bab2a63fc322c6b962af21f8ba72498
5
5
  SHA512:
6
- metadata.gz: 2a06a78caf781e12ea7dca4208bca5cc5bb008578cb3a26095b790477d82d2e0ebe5f574599b13acd36ffdfe83e0e269059e89b9f9c8285b61f55376f37e6002
7
- data.tar.gz: 940b86dfd9a8d612360fdc76e05532320dc65ac5f02bbfcf1f5600a863b399f569de650f373921fdb2ac8665edf1b039ec329b19e4ef6b5b662c135341bbca7b
6
+ metadata.gz: ac738f44d710e2b3e4e956eb4a04dac914e827aa3eaebb96e42ff14c5f2a122ec39ec6e6c68ad39397e033e1b61bb1f2cfa1e2793df0966de5b219118e836e33
7
+ data.tar.gz: e91629b891c59a9df7b2e3e1ee6bb4b7306d89ed31c4b537353221057e3d36fa1e61472d47e67d904f77991d7e10847c5974db2064191006bc45b5f173defa91
data/CHANGELOG.md CHANGED
@@ -7,6 +7,58 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.7.0] - 2026-11-23
11
+
12
+ Images as call inputs, mixing adapters in one escalation, and structured Ruby values that now reach the model as
13
+ structure. Read **Changed** before upgrading: a `Struct`, `Data`, `OpenStruct`, or `Set` argument is sent differently.
14
+
15
+ ### Added
16
+
17
+ - `Squishling::Image`: a squished method can read images. Build one from bytes (`Image.new(data:)`, the media type read
18
+ from the bytes), a file (`Image.from_path`), or a URL the provider fetches (`Image.from_url`), with an optional
19
+ `detail: :low | :high`, and pass it as an argument, inside a Hash or Array, or as a `squish_context` value. The JSON
20
+ input carries `{"attached_image": N}` in its place and the images go with each chat's first message, after the text;
21
+ the Ruby path gets the `Image` unchanged. A retry continues the chat, an escalation starts a fresh chat that carries
22
+ them again, samples and a `:chat` judge are sent them, and a `type: :judgment` judge can't see them, so that
23
+ combination raises `ConfigurationError`. PNG, JPEG, GIF, and WebP are supported. An image's `inspect`, `to_s`,
24
+ `as_json`, `to_json`, and YAML describe it (media type and size, or a URL without its query), and `Marshal` refuses
25
+ it, so its bytes don't reach logs, errors, or `squawk`. Known risk: with the RubyLLM adapter, RubyLLM may download an
26
+ image's URL from your process, from any host it can reach, so only build an `Image` from a URL or path you trust: see
27
+ [Images](docs/images.md#untrusted-urls-and-paths). (#110)
28
+ - `Adapter::Base#images?` (default `false`): an adapter that takes images sets it, and then receives a chat's first
29
+ message as content parts (`{ type: :text, ... }`, then `{ type: :image, image: Squishling::Image }`). A call with
30
+ images through an adapter without it, on any of its steps, raises `ConfigurationError` before the first request, so
31
+ existing custom adapters keep getting String content. The RubyLLM and OpenAI-compatible adapters take images, and
32
+ `Testing::Request#images` and `squishling_preview`'s `images:` show what was sent. See [Images](docs/images.md). (#110)
33
+ - `config.adapters`, a Hash of named adapters (each value takes anything `config.adapter` does, and is built when
34
+ assigned), and an `adapter:` key on escalation steps, so one escalation can run, say, Apple FM, Claude Code, and Ollama
35
+ in sequence. A step without `adapter:` keeps using `config.adapter`. `adapter:` also works on `squish!`'s
36
+ `escalation:`, on `default_escalation`, and on a harness's `judge:` step. An unknown adapter name raises
37
+ `ConfigurationError` before the call's first request (judge steps and custom-harness stages included), and
38
+ `Squishling.verify` reports it ahead of time. Error semantics are unchanged: an `LLMError` moves to the next step; a
39
+ `ConfigurationError` still ends the call. See [Mixing adapters](docs/adapters.md#mixing-adapters-in-one-escalation).
40
+ (#100)
41
+ - `Adapter::Request#adapter`, `Observer::Call#adapter`, and `Testing::Request#adapter` carry the step's adapter name
42
+ (`nil` for the default adapter). In tests, `step(adapter: :name)` selects a reply by it, and `Squishling::Testing`
43
+ routes every name in `config.adapters` to its scripted adapter. (#100)
44
+
45
+ ### Changed
46
+
47
+ - **Behavior change:** a `Struct`, `Data`, or `OpenStruct` argument or `squish_context` value now reaches the model as an
48
+ object of its members (its `to_h`), and a `Set` as an array, instead of Ruby's `inspect` text such as
49
+ `#<struct S a="secret">`. A model that was reading `#<struct S a="x">` now receives `{"a": "x"}`, and the class name is
50
+ no longer sent. All members are sent, so pass a Hash or define `to_h` to leave a field out. A value that contains
51
+ itself, or whose `to_h` doesn't return a Hash, raises `ConfigurationError`. `assert_sent_arguments` compares against what was actually sent. See
52
+ [Routing](docs/routing.md). (#95, #106)
53
+ - `Squishling.verify` checks the default adapter only for the steps that use it when `config.adapters` is set, and checks
54
+ every `adapter:` a step or judge names. (#100)
55
+
56
+ ### Internal
57
+
58
+ - Development dependencies: `ruby_llm` 2.2, `coolhand` 0.11, RuboCop 1.92.2, and `ostruct` (no longer a default gem on
59
+ Ruby 4.0); `ruby/setup-ruby` 1.338.0 in CI. (#103, #107, #108, #109, #106)
60
+ - The `prep-release` and `finish-release` skills credit outside and first-time contributors. (#105)
61
+
10
62
  ## [0.6.0] - 2026-11-01
11
63
 
12
64
  Prompt caching, on by default. Read **Changed** before upgrading: requests now ask the provider to cache the stable
data/README.md CHANGED
@@ -222,9 +222,10 @@ sees it right where the value goes, and the purpose stays short and about the go
222
222
  - [Explainer site](https://coolhand-labs.github.io/squishling/): interactive walkthrough, spectrum slider, and
223
223
  token-cost calculator
224
224
  - [Configuration](docs/configuration.md): options, models and escalation, providers, generation params, inheritance
225
- - [Adapters](docs/adapters.md): the RubyLLM and OpenAI-compatible adapters, and writing your own
225
+ - [Adapters](docs/adapters.md): the RubyLLM and OpenAI-compatible adapters, mixing them in one escalation, and your own
226
226
  - [Routing](docs/routing.md): when a call goes to the LLM, `squish!`, `append_to_purpose`, hardening a path,
227
227
  what the LLM sees
228
+ - [Images](docs/images.md): pass a `Squishling::Image` (bytes, a file, or a URL) for the model to read
228
229
  - [Output schemas](docs/schemas.md): schema forms, strict mode, typed results, optional vs. empty, contracts
229
230
  - [Failure handling](docs/failures.md): escalation, `squish_validate`, error classes, fallbacks
230
231
  - [Harnesses](docs/harnesses.md): escalation, squishsum, judges (chat or Jev), and custom harnesses
data/docs/adapters.md CHANGED
@@ -26,13 +26,71 @@ end
26
26
  ```
27
27
 
28
28
  An adapter is built when you assign it, so a missing gem or a bad option fails at boot, not on the first request.
29
- There is one adapter per process; every squishling class, method, and escalation step goes through it.
29
+ `config.adapter` is the default: every squishling class, method, and escalation step goes through it unless the step
30
+ picks another one (see [Mixing adapters](#mixing-adapters-in-one-escalation)).
30
31
 
31
32
  **When you set none**, Squishling uses the RubyLLM adapter if the `ruby_llm` gem is in your bundle, so apps that
32
33
  configured RubyLLM before adapters existed keep working. Squishling no longer requires `ruby_llm` when it loads, so an
33
34
  app that doesn't load its Gemfile with `Bundler.require` should `require "ruby_llm"` before `RubyLLM.configure`. Without the gem, the first squished call
34
35
  raises `Squishling::ConfigurationError` saying what to add.
35
36
 
37
+ ### Known risk: the RubyLLM adapter downloads some image URLs itself
38
+
39
+ When a call carries an [image given by URL](images.md#adapters), the RubyLLM adapter hands the URL to RubyLLM, which
40
+ downloads it from your process whenever it can't tell the image type from the URL's path (any path with no image
41
+ extension) or the provider can't fetch URLs itself. That download follows redirects and doesn't filter hosts, so a URL
42
+ that points at `localhost`, a private address, or a cloud metadata endpoint is fetched, and what comes back is sent to
43
+ the provider. If a user can choose an image URL, that is a server-side request forgery risk that comes with the RubyLLM
44
+ adapter: allow-list the URL's host and scheme before building the `Image`, or download it yourself and pass the bytes
45
+ with `Image.new(data:)`. The OpenAI-compatible adapter never downloads an image: it sends the URL on for the provider
46
+ to fetch.
47
+
48
+ ## Mixing adapters in one escalation
49
+
50
+ Give `config.adapters` a name for each extra adapter, and pick one per step with `adapter:`:
51
+
52
+ ```ruby
53
+ Squishling.configure do |config|
54
+ config.adapters = {
55
+ apple: :apple_fm, # squishling-apple_fm
56
+ claude: :claude_code, # squishling-claude_code
57
+ local: { type: :openai_compatible, base_url: "http://localhost:11434/v1" }
58
+ }
59
+ end
60
+
61
+ class Triage
62
+ include Squishling
63
+
64
+ squishling escalation: [
65
+ { model: "apple-fm", adapter: :apple },
66
+ { model: "sonnet", adapter: :claude },
67
+ { model: "llama3.2", adapter: :local, attempts: 2 },
68
+ "claude-opus-5-5" # no adapter: the default one (config.adapter, else RubyLLM)
69
+ ]
70
+ end
71
+ ```
72
+
73
+ Each value takes anything `config.adapter` does and is built when assigned. A step that names no adapter uses
74
+ `config.adapter`, so existing setups are unchanged; if every step names one, you need no default (and no `ruby_llm`).
75
+ `adapter:` works on any escalation step, on `squish!`'s `escalation:`, on `default_escalation`, and on a harness's
76
+ `judge:` step. A single `model:` takes a bare name only, so use a one-step `escalation:` to put it on an adapter.
77
+
78
+ - **The rest of the step is the adapter's to read.** `provider:` and `params:` mean what the chosen adapter makes of
79
+ them, so a step on `:local` doesn't need RubyLLM's `provider:`.
80
+ - **An unknown name is a `ConfigurationError`** (naming the configured ones), raised when a call starts (before its first
81
+ request), not when the class loads, since a class can load before `Squishling.configure` runs.
82
+ [`Squishling.verify`](verifying.md) finds it ahead of time.
83
+ - **Failures keep their meaning.** Each adapter classifies its own errors, then Squishling treats them as always: a
84
+ down Ollama is an `LLMError` and the call moves on to the next step, but a `ConfigurationError` (say, Claude Code
85
+ isn't logged in) ends the call and is never handed to the next adapter or to `squish_fallback`.
86
+ - **Rejected output crosses adapters.** The step after a failed one is shown the failed step's rejected output (see
87
+ [escalation](configuration.md#models-and-escalation)), so it goes to the next step's adapter, possibly a different
88
+ vendor. Set `forward_rejected: false` on a step that shouldn't see it.
89
+ - **A judge's adapter sees the full input**, like any judge's provider (see [the judge](harnesses.md#the-judge)).
90
+ `type: :judgment` judges need an adapter with judgments; the check is on the judge's own adapter.
91
+ - **Observers and tests** are told the name: `Observer::Call#adapter`, `Adapter::Request#adapter` (handed to your
92
+ adapter, `nil` for the default), and `Testing::Request#adapter`.
93
+
36
94
  ## `:ruby_llm`
37
95
 
38
96
  Everything works as it did before adapters: configure provider API keys with `RubyLLM.configure`, name models, and
@@ -174,8 +232,9 @@ Squishling.register_adapter(:acme, AcmeAdapter)
174
232
  |---|---|
175
233
  | `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). |
176
234
  | `model`, `provider` | The escalation step's, or `nil` when it names none (use your own default). What `provider:` means is up to you. |
235
+ | `adapter` | The name your adapter was configured under in `config.adapters`, or `nil` when it is the default adapter. |
177
236
  | `instructions` | The system prompt. |
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. |
237
+ | `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. Each `content` is a String, except a chat's first user message in a call with [images](#images). |
179
238
  | `schema` | `{ "name", "description", "schema", "strict" => true }`: the strict structured-output payload, without the conditional keywords providers can't take. |
180
239
  | `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
240
  | `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. |
@@ -238,6 +297,15 @@ exception propagates unwrapped and is never retried, so map your transport's err
238
297
  worker threads. `capture_context` runs on the caller's thread and returns whatever your tracing needs; `with_context`
239
298
  re-establishes it around each worker's request. The RubyLLM adapter uses this for its instrumentation workflow.
240
299
 
300
+ ### Images
301
+
302
+ A call can carry [images](images.md). To take them, return `true` from `images?`; then a chat's first user message has
303
+ an Array of content parts instead of a String: `{ type: :text, text: String }`, then `{ type: :image, image:
304
+ Squishling::Image }` per image. An `Image` gives you `data` (the bytes) with `media_type`, `data_uri`, and
305
+ `filename`, or, for `url?` images, the `url` for the provider to fetch, plus the `detail` asked for (`:low`, `:high`,
306
+ or `nil`). Without `images?`, a call with images raises `ConfigurationError` before any request, so adapters that
307
+ predate images keep getting Strings.
308
+
241
309
  ### Thread safety
242
310
 
243
311
  Adapters are called concurrently from worker threads when a harness takes samples. Keep no unsynchronized mutable
@@ -28,6 +28,7 @@ end
28
28
  | Option | Default | Description |
29
29
  |---|---|---|
30
30
  | `adapter` | `nil` (RubyLLM, when its gem is available) | How requests reach a model: `:ruby_llm`, `:openai_compatible`, a [registered](adapters.md#writing-your-own) name, a Hash with `type:` and that adapter's options, or an adapter instance. See [Adapters](adapters.md). |
31
+ | `adapters` | `{}` | More adapters by name, for escalation steps that pick one with `adapter:`. Each value takes what `adapter` does. See [Mixing adapters](adapters.md#mixing-adapters-in-one-escalation). |
31
32
  | `default_model` | `nil` | The universal model (a single attempt) for every squishling class that doesn't declare one. `nil` uses the adapter's own default (RubyLLM's `default_model`; the OpenAI-compatible adapter's `default_model:` option). |
32
33
  | `default_escalation` | `nil` | The universal [escalation](#models-and-escalation): models tried in order. Assigning it clears `default_model`, and vice versa. |
33
34
  | `default_provider` | `nil` | The provider for `default_model`/`default_escalation` steps that don't name one. What it means depends on the adapter: RubyLLM needs it only for models missing from its registry (see below); the OpenAI-compatible adapter ignores it. |
@@ -75,6 +76,7 @@ Each step is a model name, or a Hash with:
75
76
  | `rotate:` | `true` | Set `false` on a step to keep its tier in the order written instead of rotating it. |
76
77
  | `include_when:` | always | A Proc that leaves this step out of any call where it returns falsy (see [Excluding a model per call](#excluding-a-model-per-call)). |
77
78
  | `provider:` | the level's `provider:` | See [Providers](#providers-and-newly-released-models). |
79
+ | `adapter:` | `config.adapter` | The name of an adapter from `config.adapters` that makes this step's requests, so one escalation can mix adapters. See [Mixing adapters](adapters.md#mixing-adapters-in-one-escalation). |
78
80
  | `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`. |
79
81
  | `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). |
80
82
  | `params:` | `{}` | [Generation params](#generation-params) for this step, merged over the class and method params key by key. |
@@ -169,7 +171,7 @@ end
169
171
  Passing both `model:` and `escalation:` in one declaration raises `ConfigurationError`, and so does a list passed as
170
172
  `model:`. Across separate declarations (a reopened class, or two config assignments), the latest one wins.
171
173
 
172
- Consecutive attempts of the same step (same model, provider, params, `cache:`, `forward_rejected:`, and `retry_temperature:`, e.g. `attempts: 2`)
174
+ Consecutive attempts of the same step (same model, provider, adapter, params, `cache:`, `forward_rejected:`, and `retry_temperature:`, e.g. `attempts: 2`)
173
175
  continue one conversation. Moving to a different step starts a fresh chat with the original input plus the previous
174
176
  output and why it was rejected, so no provider-specific history crosses providers. That rejected output is
175
177
  model-generated and is sent to the next step's provider, even when it is a different one, truncated to 4,000
data/docs/images.md ADDED
@@ -0,0 +1,92 @@
1
+ # Images
2
+
3
+ A squished method can read images: pass a `Squishling::Image` as an argument, and the model gets it with the call's
4
+ input. Use it for receipts, screenshots, scanned forms, or anything you'd otherwise run through OCR first.
5
+
6
+ ```ruby
7
+ class ReceiptReader
8
+ include Squishling
9
+
10
+ squishling escalation: [{ model: "gpt-5-mini", attempts: 2 }, "gpt-5"]
11
+ purpose "Read the totals off this receipt."
12
+ output_schema do
13
+ optional(:total_cents, description: "The amount charged, tip included, in cents") { integer }
14
+ optional(:date, description: "The transaction date, YYYY-MM-DD") { string }
15
+ end
16
+ end
17
+
18
+ ReceiptReader.call(image: Squishling::Image.from_path("receipt.jpg"), note: "team lunch")
19
+ ```
20
+
21
+ ## Making an image
22
+
23
+ | | |
24
+ |---|---|
25
+ | `Squishling::Image.from_path(path)` | Reads the file. The media type comes from the bytes (or the extension). |
26
+ | `Squishling::Image.new(data: bytes)` | Bytes you already have (an upload, an ActiveStorage download). Pass `media_type:` if it can't be read from them. |
27
+ | `Squishling::Image.from_url(url)` | An http(s) URL the provider fetches itself. Nothing is downloaded here, so the URL has to be reachable from the provider (a signed URL works). |
28
+
29
+ PNG, JPEG, GIF, and WebP are supported. `detail: :low` or `:high` asks the provider to spend fewer or more tokens on
30
+ the image; providers without the setting ignore it. For a PDF, render its pages to images (one `Image` per page) and
31
+ pass them as an Array; text you can extract from the PDF can go alongside as a plain argument.
32
+
33
+ ## What the model sees
34
+
35
+ Each image is replaced in the JSON input by `{"attached_image": N}`, and the images go with the call's first message,
36
+ after the text, in that order. The system prompt gets one line explaining the placeholders. So for
37
+ `call(front: a, back: b)` the input is `{"arguments":{"front":{"attached_image":1},"back":{"attached_image":2}}}`, with
38
+ `a` and `b` attached. The same `Image` passed twice is attached once. Images can sit inside Hashes and Arrays, and in
39
+ `squish_context` values.
40
+
41
+ The Ruby path gets the `Image` objects as they were passed.
42
+
43
+ Every chat starts with the images: a retry continues the same chat (the model already has them), an escalation to a new
44
+ step starts a fresh chat that carries them again, and a sample harness sends them to every sample. A `:chat` judge is
45
+ sent them with the input it judges. A `type: :judgment` judge can't see images, so a call with images and such a judge
46
+ raises `ConfigurationError` before any request.
47
+
48
+ ## Adapters
49
+
50
+ The RubyLLM adapter sends images as RubyLLM attachments, and the OpenAI-compatible adapter as `image_url` content parts
51
+ (a `data:` URI, or the image's own URL); the model has to accept images. RubyLLM downloads a URL image itself when the
52
+ URL's path has no image extension (to tell its type) or when the provider can't fetch URLs, so with RubyLLM a URL has to
53
+ be reachable from your process too. A [custom adapter](adapters.md#images) opts
54
+ in with `images?`. A call with images through an adapter that doesn't take them raises `ConfigurationError` before any
55
+ request is made.
56
+
57
+ ## Untrusted URLs and paths
58
+
59
+ Build an `Image` only from sources you trust, or check them first. Squishling doesn't filter hosts or paths:
60
+
61
+ - **`Image.from_url` with the RubyLLM adapter is a known risk.** RubyLLM, not Squishling, may download the URL from your
62
+ own process (see [Adapters](#adapters)), following redirects, from any host it can reach, including `localhost`,
63
+ private addresses, and cloud metadata endpoints, and what it fetches is then sent to the provider. If a user can
64
+ choose the URL, allow-list its host and scheme before building the `Image`, or download it yourself and pass the
65
+ bytes with `Image.new(data:)`. See [the adapter note](adapters.md#known-risk-the-rubyllm-adapter-downloads-some-image-urls-itself).
66
+ The OpenAI-compatible adapter never downloads: the provider fetches the URL.
67
+ - **`Image.from_path`** reads whatever file the path names, so never pass it a path a user chose without confining it
68
+ to a directory you control.
69
+
70
+ ## Privacy and logs
71
+
72
+ An image is input, like any argument: it goes to the provider (and to a judge's provider). It never goes anywhere else.
73
+ `Image#inspect`, `#to_s`, `#as_json`, `#to_json`, and YAML describe the image (media type and size, or the URL without its
74
+ query or credentials), so an image that ends up in a log line, an error, or a serialized object carries no content. `Marshal.dump` of an
75
+ image raises `TypeError`: keep the bytes (or a URL) in your own storage and build the `Image` where the call is made.
76
+ `squawk` reports carry the JSON input with its placeholders, never the bytes, and observers never see input.
77
+
78
+ Images are billed as input tokens by the provider, and the [token budget](failures.md#capping-a-calls-cost-token-budgets)
79
+ counts them through the usage the provider reports. [Prompt caching](configuration.md#prompt-caching) still caches the
80
+ system prompt; the images are part of the message, not the cached prefix.
81
+
82
+ ## Testing
83
+
84
+ `Squishling::Testing::Request#images` lists the images a request was sent with, and `arguments` shows their
85
+ placeholders. `squishling_preview` returns them as `images:`.
86
+
87
+ ```ruby
88
+ fake = fake_squishling { |llm| llm.step(:any).reply({ "total_cents" => 1234 }) }
89
+ ReceiptReader.call(image:)
90
+ fake.requests.first.images # => [image]
91
+ fake.requests.first.arguments # => { "image" => { "attached_image" => 1 } }
92
+ ```
data/docs/observers.md CHANGED
@@ -68,6 +68,7 @@ Anything else raises `ConfigurationError` when you assign it.
68
68
  | `sample` | `"a"`, `"b"`, ... for a sample, else `nil` |
69
69
  | `attempt`, `attempts` | This request's 1-based position in the steps it was asked on, and how many there are: the escalation's expanded steps (or, for a custom harness, those passed to `run.escalate`), the sample's stage, or the judge's steps |
70
70
  | `model`, `provider` | The step's model and provider (`provider` is `nil` unless declared) |
71
+ | `adapter` | The name of the [adapter](adapters.md#mixing-adapters-in-one-escalation) the step picked (`nil` for the default one) |
71
72
  | `request` | `:chat`, or `:judgment` for a System One judge |
72
73
 
73
74
  It carries metadata, plus the rendered `purpose`. The method's inputs, its context, and the model's output never reach an
data/docs/routing.md CHANGED
@@ -232,6 +232,14 @@ Source is read with Ruby's own parser (Prism) the first time it's needed and cac
232
232
  `forward_rejected: false` on a step to start it from the original input only, without the rejected output or
233
233
  its errors. Don't put data in those messages that you wouldn't send as an argument.
234
234
 
235
+ Arguments and context are converted to JSON before they are sent. A `Struct`, `Data`, or `OpenStruct` goes as an
236
+ object of its members (its `to_h`, which must return a Hash, is the hook: a `to_json` on these types is not consulted,
237
+ and the class name is not sent), a `Set` as an array, and Hashes and Arrays are walked
238
+ recursively. An exception goes as its class and message. A value that contains itself raises a `ConfigurationError`.
239
+ All members are sent, so pass a Hash or define `to_h` to leave a field out. Any other object goes as the loaded JSON
240
+ library writes it (plain `JSON.generate` sends a `Range`, a `Time`, or a plain object as its `to_s`), so pass a Hash,
241
+ or an object whose `to_json` sends what you mean, when that text isn't what the model should see.
242
+
235
243
  `squish_context` names are read from a method of that name if there is one, otherwise from the instance
236
244
  variable. Only context you name is sent. Instance variables are never dumped wholesale, so API clients,
237
245
  database connections, and secrets stay out of the prompt.
data/docs/testing.md CHANGED
@@ -19,7 +19,8 @@ still hold what the helpers set), so the rest of your `Squishling.configure` sur
19
19
 
20
20
  The helpers change global state (`Squishling.config` and the stubbed classes), so tests that use them must not run
21
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
+ (routing every name in `config.adapters` to the guard too) for the block: a request another thread makes meanwhile is
23
+ forbidden too, and may be counted in the block's calls.
23
24
 
24
25
  ## Scripting the model
25
26
 
@@ -58,9 +59,11 @@ A reply is one of:
58
59
  | `:rate_limit`, `:server_error`, `:overloaded`, `:timeout`, `:context_length` | `LLMError` (the next attempt is tried) |
59
60
  | `:bad_request`, `:unauthorized`, `:forbidden` | `ConfigurationError` (never retried, never given to a fallback) |
60
61
 
61
- **Selecting what a rule answers.** `step(model)`, `step(provider: :vertexai)`, and `step(:any)` answer escalation
62
- attempts; `attempt: 2` narrows a step rule to one attempt of the escalation. Rules are matched most specific first
63
- (a sample or the judge, then the rule naming the most of model, provider and attempt, then `step(:any)`), and by
62
+ **Selecting what a rule answers.** `step(model)`, `step(provider: :vertexai)`, `step(adapter: :local)`, and `step(:any)`
63
+ answer escalation attempts; `attempt: 2` narrows a step rule to one attempt of the escalation. The scripted adapter
64
+ answers for every name in `config.adapters`, so `adapter:` selects on the name a step asked for. Rules are matched most
65
+ specific first (a sample or the judge, then the rule naming the most of model, provider, adapter and attempt, then
66
+ `step(:any)`), and by
64
67
  declaration order within that.
65
68
  Scripts are keyed by model, so a rotated tier (`priority:`) gets the same answers whichever model goes first. Which
66
69
  model goes first still depends on how many calls the class has had, so don't assert the order of `fake.models` for a
@@ -91,8 +94,9 @@ and `#verdict` are the real ones; rescue them as you would in production.
91
94
  | | |
92
95
  |---|---|
93
96
  | `arguments`, `context` | the method's arguments and the `squish_context` / `squish!` context the model was sent |
97
+ | `images` | the [`Squishling::Image`s](images.md) sent with the conversation's first message (`[]` when none were) |
94
98
  | `system_prompt`, `output_schema` | the purpose (with `append_to_purpose` sections) and the strict schema |
95
- | `model`, `provider`, `params`, `cache` | the step it went to (`cache` is `false` when [prompt caching](configuration.md#prompt-caching) was off for it) |
99
+ | `model`, `provider`, `adapter`, `params`, `cache` | the step it went to (`adapter` is its name from `config.adapters`, `nil` for the default; `cache` is `false` when [prompt caching](configuration.md#prompt-caching) was off for it) |
96
100
  | `role`, `sample`, `attempt`, `attempts` | `nil`/`:sample`/`:judge`, `"a"`, and where it is in the escalation |
97
101
  | `conversation` | the chat it belongs to |
98
102
  | `errors` | the validation messages a retry or escalation carried back to the model |
@@ -142,7 +146,7 @@ removed the stub (it is inert, but keeps the class alive), so stub the classes o
142
146
  squishling_validate(Klass, { "regex" => "[bad(" }, text: "x") # => ["regex is not a valid Ruby regex"]
143
147
  squishling_fallback_for(Klass, Squishling::LLMError.new("x"), text: "x") # the typed fallback result
144
148
  squishling_preview(Klass, text: "x")
145
- # => { system_prompt:, user_message:, output_schema:, step: } # for snapshot tests; makes no request
149
+ # => { system_prompt:, user_message:, images:, output_schema:, step: } # for snapshot tests; makes no request
146
150
  ```
147
151
 
148
152
  Arguments are keywords, or `args: [...]` for positional ones; `receiver:` supplies an instance for a class whose
@@ -181,7 +185,8 @@ can't tell which request is which.
181
185
 
182
186
  ## How it works
183
187
 
184
- `fake_squishling` assigns a `Squishling::Testing::Adapter` (a `Squishling::Adapter::Base`) as `config.adapter`, and an
185
- observer that tells it which role, sample, and attempt each request is. Because it sits behind the same interface as
186
- the real adapters, it needs no knowledge of RubyLLM or any provider, and it is covered by Squishling's own specs.
188
+ `fake_squishling` assigns a `Squishling::Testing::Adapter` (a `Squishling::Adapter::Base`) as `config.adapter`
189
+ (routing every name in `config.adapters` to it too), and an observer that tells it which role, sample, and attempt
190
+ each request is. Because it sits behind the same interface as the real adapters, it needs no knowledge of RubyLLM or
191
+ any provider, and it is covered by Squishling's own specs.
187
192
  Call `Squishling::Testing.install` and `.reset!` yourself if you use a test framework other than the two above.
data/docs/verifying.md CHANGED
@@ -40,7 +40,9 @@ For each squished method (inherited ones too, with the subclass's settings) it c
40
40
  keywords) can't take. Add `**` to accept any. A method that takes `**` or has no implementation can receive any
41
41
  keyword, so nothing is reported for it. `squish_fallback` and `squish_validate` are called with the inputs too, but
42
42
  aren't checked.
43
- - **The adapter** (once): that `config.adapter`, or RubyLLM's, can be built.
43
+ - **The adapter** (once): that `config.adapter`, or RubyLLM's, can be built. When `config.adapters` names others, that
44
+ check moves to each method: every `adapter:` a step or judge names must be configured, and the default adapter is
45
+ only checked for the steps that use it.
44
46
 
45
47
  A problem in an inherited method is reported once for each subclass, since each is checked with its own settings.
46
48
 
@@ -8,15 +8,21 @@ module Squishling
8
8
  # and registering it (Squishling.register_adapter) or assigning an instance to config.adapter. See docs/adapters.md.
9
9
  module Adapter
10
10
  # One completion to make. messages holds the conversation so far as { role: :user | :assistant, content: String }
11
- # Hashes, ending with the user message to answer; instructions is the system prompt. schema is the strict
12
- # structured-output payload ({ "name", "description", "schema", "strict" => true }). params is the resolved
13
- # generation params: the portable :temperature, :max_output_tokens, and :thinking, plus any provider-specific keys
11
+ # Hashes, ending with the user message to answer; instructions is the system prompt. When the call has images
12
+ # (see Image), a chat's first user message has an Array of content parts instead of a String: { type: :text,
13
+ # text: String } and then { type: :image, image: Squishling::Image } per image. Only adapters whose #images? is
14
+ # true are sent them. schema is the strict structured-output payload
15
+ # ({ "name", "description", "schema", "strict" => true }). params is the resolved generation params: the
16
+ # portable :temperature, :max_output_tokens, and :thinking, plus any provider-specific keys
14
17
  # (see Params). label ("Class#method") prefixes the adapter's error messages. model and provider are the step's
15
- # (nil when it names none). cache is the prompt caching to ask the provider for: false (none), or a Hash of options
18
+ # (nil when it names none). adapter is the name this adapter was configured under (config.adapters), nil for the
19
+ # default adapter. cache is the prompt caching to ask the provider for: false (none), or a Hash of options
16
20
  # ({} for the provider's default, { ttl: "1h" }), see Cache. An adapter whose provider has no prompt caching, or
17
21
  # 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)
22
+ Request = Data.define(:label, :model, :provider, :instructions, :messages, :schema, :params, :cache,
23
+ :adapter) do
24
+ def initialize(label:, model:, provider:, instructions:, messages:, schema:, params:, cache: false,
25
+ adapter: nil)
20
26
  super
21
27
  end
22
28
  end
@@ -115,6 +121,12 @@ module Squishling
115
121
  false
116
122
  end
117
123
 
124
+ # Whether #complete takes images: a message whose content is an Array of parts (see Request). A call with images
125
+ # through an adapter that doesn't is a ConfigurationError, made before any request.
126
+ def images?
127
+ false
128
+ end
129
+
118
130
  # A System One judgment: input (a Hash) and questions (a Hash of name => question), with the step's model and
119
131
  # params. Returns an object answering [name] with an answer that responds to choice and probabilities. label
120
132
  # ("Class#method") prefixes error messages. Called as judge(input, questions:, step:, label:).
@@ -20,7 +20,8 @@ module Squishling
20
20
  class OpenAICompatible < Adapter::Base
21
21
  Options = OpenAIOptions
22
22
  Transport = OpenAITransport
23
- private_constant :Options, :Transport
23
+ Content = OpenAIContent
24
+ private_constant :Options, :Transport, :Content
24
25
 
25
26
  DEFAULT_BASE_URL = "https://api.openai.com/v1"
26
27
  STRUCTURED_OUTPUT = %i[json_schema json_object none].freeze
@@ -76,6 +77,11 @@ module Squishling
76
77
  "default_model=#{@default_model.inspect} structured_output=#{@structured_output.inspect}>"
77
78
  end
78
79
 
80
+ # Images go out as image_url content parts (a data: URI, or the image's own URL).
81
+ def images?
82
+ true
83
+ end
84
+
79
85
  def complete(request)
80
86
  model = request.model || @default_model
81
87
  unless model
@@ -117,7 +123,9 @@ module Squishling
117
123
 
118
124
  def messages(request)
119
125
  system = system_prompt(request)
120
- turns = request.messages.map { |message| { "role" => message[:role].to_s, "content" => message[:content] } }
126
+ turns = request.messages.map do |message|
127
+ { "role" => message[:role].to_s, "content" => Content.of(message[:content]) }
128
+ end
121
129
  system ? [{ "role" => "system", "content" => system }] + turns : turns
122
130
  end
123
131
 
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Squishling
4
+ module Adapters
5
+ # A message's content as the Chat Completions API takes it: a String as is, or content parts (see
6
+ # Adapter::Request) as text and image_url parts, an image as a data: URI or its own URL.
7
+ module OpenAIContent
8
+ module_function
9
+
10
+ def of(value)
11
+ return value unless value.is_a?(Array)
12
+
13
+ value.map { |part| part[:type] == :image ? image(part[:image]) : { "type" => "text", "text" => part[:text] } }
14
+ end
15
+
16
+ def image(image)
17
+ url = { "url" => image.url || image.data_uri }
18
+ url["detail"] = image.detail.to_s if image.detail
19
+ { "type" => "image_url", "image_url" => url }
20
+ end
21
+ end
22
+ end
23
+ end
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "stringio"
4
+
3
5
  module Squishling
4
6
  module Adapters
5
7
  # Sends requests through RubyLLM (https://rubyllm.com): OpenAI, Anthropic Claude, Google Gemini, AWS Bedrock,
@@ -36,9 +38,7 @@ module Squishling
36
38
  # released ones) are only usable when a provider is named, so RubyLLM is told to assume they exist.
37
39
  def complete(request)
38
40
  chat = build_chat(request)
39
- *history, last = request.messages
40
- history.each { |message| chat.add_message(role: message[:role], content: message[:content]) }
41
- response = guarded(request) { ask(chat, request, last[:content]) }
41
+ response = guarded(request) { replay_and_ask(chat, request) }
42
42
  Adapter::Response.new(content: response.content, model: response.model, tokens: tokens_of(response),
43
43
  finish_reason: response.finish_reason)
44
44
  end
@@ -47,6 +47,11 @@ module Squishling
47
47
  true
48
48
  end
49
49
 
50
+ # Images go to RubyLLM as attachments: the bytes, or the image's URL.
51
+ def images?
52
+ true
53
+ end
54
+
50
55
  # A System One judgment (RubyLLM.judge) on one step. The step's params are sent as provider options.
51
56
  # RubyLLM raises ArgumentError for a judgment it can't build (e.g. a model on a provider that takes none, or
52
57
  # a provider option its protocol reserves), and a bare RubyLLM::Error without an HTTP response for a provider
@@ -82,10 +87,22 @@ module Squishling
82
87
 
83
88
  private
84
89
 
90
+ # The conversation so far added to the chat, then its last message asked. Building an attachment can fetch an
91
+ # image's URL (RubyLLM reads the media type from the response when the URL has no extension), so the history is
92
+ # guarded like the request itself.
93
+ def replay_and_ask(chat, request)
94
+ *history, last = request.messages
95
+ history.each do |message|
96
+ text, attachments = split(message[:content])
97
+ chat.add_message({ role: message[:role], content: text, attachments: }.compact)
98
+ end
99
+ ask(chat, request, *split(last[:content]))
100
+ end
101
+
85
102
  # RubyLLM checks a caching option against the provider when it renders the request, and raises ArgumentError for
86
103
  # one it can't use. That is the developer's setting, so it is a setup mistake rather than a failed request.
87
- def ask(chat, request, content)
88
- chat.ask(content)
104
+ def ask(chat, request, content, attachments = nil)
105
+ attachments ? chat.ask(content, with: attachments) : chat.ask(content)
89
106
  rescue ArgumentError => e
90
107
  raise unless request.cache && e.message.match?(/caching/i) && raised_by_ruby_llm?(e)
91
108
 
@@ -93,6 +110,20 @@ module Squishling
93
110
  "RubyLLM rejected the request, cache #{request.cache.inspect} (#{e.message})")
94
111
  end
95
112
 
113
+ # A message's text and its images as RubyLLM attachments (nil when it has none).
114
+ def split(content)
115
+ return [content, nil] unless content.is_a?(Array)
116
+
117
+ text = content.filter_map { |part| part[:text] if part[:type] == :text }.join("\n\n")
118
+ images = content.filter_map { |part| attachment(part[:image]) if part[:type] == :image }
119
+ [text, images]
120
+ end
121
+
122
+ def attachment(image)
123
+ source = image.url? ? image.url : StringIO.new(image.data)
124
+ ::RubyLLM::Attachment.new(source, filename: image.filename, resolution: image.detail)
125
+ end
126
+
96
127
  def tokens_of(response)
97
128
  response.tokens ? response.tokens.to_h : {}
98
129
  end