inquirex-llm 0.12.2 β†’ 0.13.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: 1261cf90cb18c935731001fc135e896e271d63e64f84aba6fc5b45105bfcaa8c
4
- data.tar.gz: 74ddcc8813674ae65e5979a3becc1c9ecbd7bdf4b0e64e71161a6ddc15c86a01
3
+ metadata.gz: 51e6068f0bba8baab7870c047a9409f86d311c7a5883ea84edd1d69aa9f7d62e
4
+ data.tar.gz: b4baf400d30ee4035601b6faf990e0351c710466d6fbebddedbf1c3071078963
5
5
  SHA512:
6
- metadata.gz: 1eda2a5ae132b1027700dc058f90ff47fe3a29e5e8804669b5ad4c9c1771f76b8c01484963e8f3d63d5e3fc9f3311e568d67d73b0f35f7e3cff9c1723a4d723c
7
- data.tar.gz: 7af624fbd2546c4cf1404f3ac51aecc72c670e013888fb7fdb654be5f2f3ee455023e08737dfea510295bdfa9fd783c4ffe801f2e383004f8491ed463ad02955
6
+ metadata.gz: 8f085f0d856c9e219960c2b84cd3ed1a0ffeb42fa3739c6b3469048959921ff3cb27c3f37f829cfb1939dfb9f7765f3500b6c9b69635bb6dc40faa167233f840
7
+ data.tar.gz: 89390898cd1b2de4513bbce4755e205317799cc20bfbfef217fab6ba2fc09c28cd7e0756330d5f762f253b2bb267e64dc40d7590a2bf6d8eca892546fa171c22
data/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.3
4
+
5
+ - Use the module-scoped constants of llm-evals 0.5.0 (`LLM::Evals::Actions::Adapter`, `Scoring::Scorer` and so on). The suite needs llm-evals `~> 0.5.0`.
6
+
3
7
  ## 0.12.2 (unreleased)
4
8
 
5
9
  - **The eval suite now runs on llm-evals.** `inquirex/llm/evals` requires `llm/evals` and subclasses `::LLM::Evals`, because `agent-evals` was renamed and is no longer on RubyGems. The config file is `evals/.llm-evals.config.yml` and the executable is `evals`. Inside `Inquirex::LLM`, a bare `LLM` means this gem, so the leading `::` is required.
data/README.md CHANGED
@@ -1,22 +1,50 @@
1
1
  [![Gem Version](https://badge.fury.io/rb/inquirex-llm.svg)](https://badge.fury.io/rb/inquirex-llm) [![Ruby](https://github.com/inquirex/inquirex-llm/actions/workflows/main.yml/badge.svg)](https://github.com/inquirex/inquirex-llm/actions/workflows/main.yml) ![Coverage](docs/badges/coverage_badge.svg)
2
2
 
3
- # inquirex-llm
3
+ > [!CAUTION]
4
+ >
5
+ > If you have not read the README for the [inquirex](https://github.com/inquirex/inquirex) Ruby gem, which constitutes the basis for this gem and a few others, please stop reading here, and head over there and read the README, or have Claude or your favorite model summarize it for you, but beware that **this README** assumes **full understanding of what `inquirex` does**, how it works, and what it's for.
4
6
 
5
- LLM integration verbs for the [Inquirex](https://github.com/inquirex/inquirex) questionnaire engine.
7
+ ---
6
8
 
7
- Extends the core DSL with two server-side verbs: `extract` (alias: `clarify`), which turns free-text answers into structured data, and `summarize`, which closes a flow with a prose summary of the whole session. Ships with a pluggable adapter interface and a `NullAdapter` for testing. (`describe` and `detour` are temporarily parked.)
9
+ # `inquirex-llm` β€” "Making Forms... Less Clueless Since 2026 πŸ˜‚"
8
10
 
9
- `inquirex` is a pure Ruby, declarative, rules-driven questionnaire engine for building conditional intake forms, qualification wizards, and branching surveys.
11
+ This Ruby gem is meant to be used with its parent `inquirex` gem. It enriches `inquirex` 's DSL with additional keywords you can use in your form descriptions.
12
+
13
+ > [!NOTE]
14
+ >
15
+ > If you use inquirex to show the forms inside a web copilot, similar to how they are done on the site [Qualified.At](https://qualified.at) and especially on their [ten separate demos](https://qualified.at/demos) β€” which is, they generate a floating Copilot with form questions as widgets inside entirely via JavaScript package [inquirex-widget](https://www.npmjs.com/package/inquirex-widget) and run the user through the questions without any round-trips to the server, as the entire DSL is passed at once in the beginning as JSON; and so until the user (a lead) finishes the form, there are no server trips necessary.
16
+ >
17
+ > However, for the keywords added by this gem to work, they must be sent to some sort of backend API server, because pure client-side calling of LLM APIs would expose the API key.
18
+ >
19
+ > When used within the context of a Terminal GUI (ie., [`inquirex-tty`](https://github.com/inquirex/inquirex-tty), the form is rendered and run through by the same Ruby VM process, and therefore you just need your API keys set in your environment.
20
+ >
21
+ > And if you ever want to encrypt your development keys and commit them with your repo, there is no tool like [**sopsy**](https://sopsy-cli.dev), GitHub: <https://github.com/kigster/sopsy>. Sopsy is a Rust-based encryption tool that stores private keys inside your MacBook's secure enclave chip, or on a YubiKey.
22
+
23
+ ---
24
+
25
+ ## The New Keywords
26
+
27
+ This gem extends the core DSL with two server-side verbs:
28
+
29
+ * `extract` (alias: `clarify`), which turns free-text answers into structured data, and
30
+
31
+ * `summarize`, which closes a flow with a prose summary of the whole session.
32
+
33
+ Ships with a pluggable adapter interface and a `NullAdapter` for testing.
10
34
 
11
35
  > [!IMPORTANT]
12
- > Note that `inquirex-llm` is part of an entire ecosystem that contains:
13
36
  >
14
- > - [`inquirex`](https://github.com/inquirex/inquirex)
15
- > - [`inquirex-llm`](https://github.com/inquirex/inquirex-llm)
16
- > - [`inquirex-tty`](https://github.com/inquirex/inquirex-tty)
17
- > - [`inquirex-widget`](https://github.com/inquirex/inquirex-widget) (`npmjs` module [`inquirex-widget`](https://www.npmjs.com/package/inquirex-widget), formerly `@kigster/inquirex-js`)
37
+ > As we mentioned above, `inquirex-llm` is part of an entire ecosystem that comprises:
38
+ >
39
+ > - [`inquirex`](https://github.com/inquirex/inquirex) β€” the base gem that defines the core DSL and validation rules.
40
+ > - [`inquirex-llm`](https://github.com/inquirex/inquirex-llm) β€”Β this gem extends it with AI-enabled features
41
+ > - [`inquirex-tty`](https://github.com/inquirex/inquirex-tty) β€”Β a TUI user interface gem that converts the form DSLs into a proper terminal screen wizard/questionaire, and could be combined with the LLM gem to offer AI-enabled form features.
18
42
  >
19
- > For a presentation about these gems and what they do please watch the [RubySF presentation](https://www.youtube.com/watch?v=iaoKW7Ap3_M&t=1s) and you can also [view the slides from the presentation](https://reinvent.one/images/talks/pdfs/2026.inquirex.pdf).
43
+ > In addition to the Ruby Gems, there is an NPM JavaScript module that also converts DSLs into a Copilot-style questionnaire for use in a web application.
44
+ >
45
+ > - [`inquirex-widget`](https://github.com/inquirex/inquirex-widget), and it's npmjs module [`inquirex-widget`](https://www.npmjs.com/package/inquirex-widget)
46
+ >
47
+ > For a presentation about these gems and what they collectively do, please check out the [Slides from the RubySF presentation](https://kig.re/speaking/2026.inquirex) (or the [video](https://www.youtube.com/watch?v=iaoKW7Ap3_M&t=1s) if you prefer.
20
48
  >
21
49
  > Finally, the SaaS application [qualified.at](https://qualified.at) allows users to leverage the ecosystem by creating their own custom lead intake flows and integrating them on their own sites.
22
50
 
@@ -46,7 +74,8 @@ definition = Inquirex.define id: "tax-intake-2026", version: "1.0.0" do
46
74
  entity_type: :string,
47
75
  employee_count: :integer,
48
76
  estimated_revenue: :currency
49
- model :claude_sonnet
77
+ use_first_available_model "deepseek/deepseek-v4.1-flash",
78
+ "anthropic/claude-haiku-5.5"
50
79
  temperature 0.2
51
80
  transition to: :done
52
81
  end
@@ -61,7 +90,7 @@ All core verbs (`ask`, `say`, `header`, `btw`, `warning`, `confirm`) and widget
61
90
 
62
91
  ### Loading stored flows
63
92
 
64
- Since inquirex 0.7.0, `Inquirex.load_dsl` validates source against a **default-deny** allowlist before evaluating it β€” a word nobody declared is a violation, not an oversight. Requiring this gem registers its own vocabulary (`extract`, `clarify`, `summarize`, and the methods legal inside their blocks), so a flow stored in a database or authored in a visual builder loads normally:
93
+ Since Inquirex 0.7.0, `Inquirex.load_dsl` validates source against a **default-deny** allowlist before evaluating it β€” a word nobody declared is a violation, not an oversight. Requiring this gem registers its own vocabulary (`extract`, `clarify`, `summarize`, and the methods legal inside their blocks), so a flow stored in a database or authored in a visual builder loads normally:
65
94
 
66
95
  ```ruby
67
96
  Inquirex.load_dsl(customer.flow_dsl) # validates, then evaluates
@@ -69,7 +98,7 @@ Inquirex.load_dsl(customer.flow_dsl) # validates, then evaluates
69
98
 
70
99
  `fallback` is the one deliberate exception: it takes a Ruby block, which is exactly what static validation cannot vet, so it is excluded from the allowlist rather than permitted. Flows that need it must be loaded from your own source with `unsafe: true`.
71
100
 
72
- Registration is skipped on inquirex versions predating the allowlist, so the gem still works against them.
101
+ Registration is skipped on Inquirex versions predating the allowlist, so the gem still works against them.
73
102
 
74
103
  ## Currently Supported LLM Verbs
75
104
 
@@ -82,7 +111,8 @@ extract :business_extracted do
82
111
  from :business_description
83
112
  prompt "Extract structured business information."
84
113
  schema industry: :string, employee_count: :integer, revenue: :currency
85
- model :claude_sonnet
114
+ use_first_available_model "deepseek/deepseek-v4.1-flash",
115
+ "anthropic/claude-haiku-5.5"
86
116
  temperature 0.2
87
117
  max_tokens 1024
88
118
  transition to: :next_step
@@ -102,6 +132,8 @@ Inquirex.define id: "depreciation-help" do
102
132
 
103
133
  summarize :wrap_up do
104
134
  temperature 0.4
135
+ use_first_available_model "anthropic/claude-sonnet-5.5",
136
+ "anthropic/claude-haiku-5.5"
105
137
  end
106
138
  end
107
139
  ```
@@ -126,7 +158,12 @@ The prompt constrains the model to what the transcript establishes, and to the m
126
158
 
127
159
  Each raises `Errors::DefinitionError` naming the reason.
128
160
 
129
- `temperature`, `model`, and `max_tokens` remain available: they change how the summary is generated, not what it is allowed to say.
161
+ - `temperature(float between 0..1)`
162
+ - `model(symbol)` (deprecated, but still works until 1.0.0)
163
+ - `use_first_available_model(array of strings)` is the replacement for `model` allowing the choice of a model best suited for a specific question or a task.
164
+ - `max_tokens(integer)`
165
+
166
+ These parameters change how the summary is generated, not what it can say.
130
167
 
131
168
  #### Calling it
132
169
 
@@ -193,19 +230,20 @@ Write the prompt by hand when you need domain framing the questions don't carry
193
230
 
194
231
  ## DSL Methods (inside LLM verb blocks)
195
232
 
196
- | Method | Purpose | Required |
197
- | ------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------- |
198
- | `prompt "..."` / `prompt :auto` | LLM prompt template, or generated from question refs | `extract`; **rejected** on `summarize` |
199
- | `schema :question_id, ...` | Fields resolved from questions (types + options) | `extract` (this or keywords); **rejected** on `summarize` |
200
- | `schema key: :type, ...` | Explicit field => type pairs | `extract` (this or refs); **rejected** on `summarize` |
201
- | `from :step_id` | Source step(s) whose answers feed the LLM | `extract` (or use `from_all`); **rejected** on `summarize` |
202
- | `from_all` | Pass all collected answers to the LLM | Alternative to `from`; **rejected** on `summarize` |
203
- | `model :claude_sonnet` | Optional model hint for the adapter | No |
204
- | `temperature 0.3` | Optional sampling temperature | No |
205
- | `max_tokens 1024` | Optional max output tokens | No |
206
- | `fallback { \|answers\| ... }` | Server-side fallback (stripped from JSON) | No |
207
- | `transition to: :step` | Conditional transition (same as core) | No; **rejected** on `summarize` |
208
- | `skip_if rule` | Skip step when condition is true | No |
233
+ | Method | Purpose | Required |
234
+ | ----------------------------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- |
235
+ | `prompt "..."` / `prompt :auto` | LLM prompt template, or generated from question refs | `extract`; **rejected** on `summarize` |
236
+ | `schema :question_id, ...` | Fields resolved from questions (types + options) | `extract` (this or keywords); **rejected** on `summarize` |
237
+ | `schema key: :type, ...` | Explicit field => type pairs | `extract` (this or refs); **rejected** on `summarize` |
238
+ | `from :step_id` | Source step(s) whose answers feed the LLM | `extract` (or use `from_all`); **rejected** on `summarize` |
239
+ | `from_all` | Pass all collected answers to the LLM | Alternative to `from`; **rejected** on `summarize` |
240
+ | `model :claude_sonnet` | ~~Optional model hint for the adapter~~ | No, Deprecated |
241
+ | `use_first_available_model "vendor/model", ...` | Models this step prefers, best first; the first one a usable vendor serves is used. Overrides `model`. Server-side only | No |
242
+ | `temperature 0.3` | Optional sampling temperature | No |
243
+ | `max_tokens 1024` | Optional max output tokens | No |
244
+ | `fallback { \|answers\| ... }` | Server-side fallback (stripped from JSON) | No |
245
+ | `transition to: :step` | Conditional transition (same as core) | No; **rejected** on `summarize` |
246
+ | `skip_if rule` | Skip step when condition is true | No |
209
247
 
210
248
  `summarize` rejects the content-shaping methods rather than ignoring them β€” see [`summarize`](#summarize) for each refusal and its reason.
211
249
 
@@ -238,6 +276,59 @@ result = adapter.call(engine.current_step)
238
276
  # => { industry: "", employee_count: 0, revenue: 0.0 }
239
277
  ```
240
278
 
279
+ ## Model routing (0.13.0+)
280
+
281
+ > [!NOTE]
282
+ >
283
+ > For a fun read on how this feature came to be, please read the blog post [Home-made Evals Taste Better](https://kig.re/2026/11/02/llm-evals-is-a-ruby-gem-for-testing-probabilistic-assumptions-in-your-AI-datasets.html)
284
+
285
+ Different steps want different models: an eval run (see [Evals](#evals)) may show that DeepSeek wins one dataset and Claude Haiku another. Routing lets the host list the vendors and models it prefers once, and lets each LLM step name its own ordered list. The full reasoning is in [docs/decisions/prioritized-model-selection.md](docs/decisions/prioritized-model-selection.md).
286
+
287
+ Models are always named the OpenRouter way, `"vendor/model"`: `"openai/gpt-4.1-mini"`, `"anthropic/claude-haiku-5.5"`, `"deepseek/deepseek-v4.1-flash"`.
288
+
289
+ ```ruby
290
+ Inquirex::LLM.configure do |c|
291
+ c.llm_vendors_priority = %i[openrouter openai anthropic typesafe]
292
+ c.llm_models_priority = %w[deepseek/deepseek-v4.1-flash
293
+ anthropic/claude-haiku-5.5]
294
+ c.dsl_can_reprioritize = true # default: a step's own order wins
295
+ c.dsl_can_use_unlisted_models = true # default: a step may name models not listed above
296
+ end.ensure_provider_models!
297
+ ```
298
+
299
+ `ensure_provider_models!` runs once per process (it also runs lazily on the first routed call):
300
+
301
+ 1. Drops every vendor whose API key is not set, warning in yellow on stderr.
302
+ 1. Downloads each remaining vendor's model catalog, all at once. A vendor whose catalog fails is dropped for the life of the process.
303
+ 1. If anything was dropped, prints the surviving vendors in green. If none survive, raises `Errors::MissingProviderAPIKeysError`.
304
+ 1. Drops every model in `llm_models_priority` that no surviving vendor serves. If none is left, raises `Errors::NoAvailableModelsError`.
305
+
306
+ Who serves a model: OpenRouter serves anything its catalog lists; OpenAI and Anthropic serve their own models natively (`anthropic/claude-haiku-5.5` is sent to Anthropic as `claude-haiku-5-5`); TypeSafe serves `typesafe/jev-*` for `extract` steps whose every field Jev can answer. When several vendors could serve a model, `llm_vendors_priority` decides.
307
+
308
+ A step names its own models with `use_first_available_model`:
309
+
310
+ ```ruby
311
+ extract :facts do
312
+ from :situation
313
+ prompt "Extract the filing details."
314
+ schema filing_status: :string, dependents: :integer
315
+ use_first_available_model "deepseek/deepseek-v4.1-flash",
316
+ "anthropic/claude-haiku-5.5"
317
+ end
318
+ ```
319
+
320
+ At call time the first model a usable vendor serves is used; if none is, the step falls back to `llm_models_priority` with one warning. A step with no list uses `llm_models_priority`; an old `model :claude_sonnet` hint counts as a one-entry list. The list never appears in the JSON wire format: the server reads it from the definition it loaded.
321
+
322
+ Call the step through the routing facade:
323
+
324
+ ```ruby
325
+ Inquirex::LLM.route(node) # => Routing::Route(model:, provider:, native_id:, adapter:)
326
+ Inquirex::LLM.extract(node, engine.answers) # => Extraction
327
+ Inquirex::LLM.summarize(node, transcript, answers) # => markdown String
328
+ ```
329
+
330
+ Without `llm_vendors_priority`, routing is off and these three use `Inquirex::LLM.adapter`, exactly as before.
331
+
241
332
  ## Configuration
242
333
 
243
334
  Model ids, the provider and its credentials are set in one place, `Inquirex::LLM.configuration`. Each setting is read from its environment variable when that variable is set and not blank, and otherwise takes the default below. The adapters fall back on it whenever no `api_key:` or `model:` is passed and a node sets no `max_tokens` or `temperature` of its own.
@@ -261,6 +352,8 @@ Model ids, the provider and its credentials are set in one place, `Inquirex::LLM
261
352
 
262
353
  An invalid value (an unknown provider, a token count that is not a positive integer, a temperature outside 0 to 2) raises `Inquirex::LLM::Errors::ConfigurationError` naming the variable. `to_h` and `inspect` print every `*_api_key` as `[REDACTED]`.
263
354
 
355
+ The single-provider settings (`provider`, the `*_model` settings and `Inquirex::LLM.adapter`) are **deprecated** since 0.13.0 in favour of [Model routing](#model-routing-0130); they keep working unchanged.
356
+
264
357
  ENV is read once, on first use. Code can override any setting afterwards; `nil` restores the default:
265
358
 
266
359
  ```ruby
@@ -369,7 +462,7 @@ definition = Inquirex.define id: "tax-intake" do
369
462
  dependents: :integer,
370
463
  income_types: :multi_enum,
371
464
  state_filing: :string
372
- model :claude_sonnet
465
+
373
466
  transition to: :filing_status
374
467
  end
375
468
 
@@ -403,7 +496,69 @@ engine.prefill!(result) # splats into top-level answers
403
496
  # whichever field the LLM couldn't fill in.
404
497
  ```
405
498
 
406
- `Engine#prefill!` is non-destructive (won't clobber an answer the user already gave), ignores `nil`/empty values so they don't spuriously trigger `not_empty`, and auto-advances past any step whose `skip_if` now evaluates true. See [examples/09_tax_preparer_llm.rb](../inquirex-tty/examples/09_tax_preparer_llm.rb) for a complete runnable flow, or the repo-level `demo_llm_intake.rb` for a scripted end-to-end walkthrough.
499
+ `Engine#prefill!` is non-destructive (won't clobber an answer the user already gave), ignores `nil`/empty values so they don't spuriously trigger `not_empty`, and auto-advances past any step whose `skip_if` now evaluates true. See [examples](./examples) folder for a couple of complete runnable flows, or the repo-level `demo_llm_intake.rb` for a scripted end-to-end walkthrough.
500
+
501
+ ### Running Examples
502
+
503
+ > [!NOTE]
504
+ >
505
+ > To get the full benefit from these examples, we recommend that you set in your environment all of the following variables:
506
+ >
507
+ > - `OPENAI_API_KEY`
508
+ > - `OPENROUTER_API_KEY`
509
+ > - `ANTHROPIC_API_KEY`
510
+
511
+ Then you can run the two examples via `bundle exec` (so make sure to run `bundle install` first)
512
+
513
+ ```bash
514
+ $ bundle exec examples/llm-intake.rb
515
+
516
+ ========================================================================
517
+ INQUIREX + LLM DEMO β€” Tax Intake
518
+ Powered by: OpenAI GPT
519
+ ========================================================================
520
+
521
+ Step 1 β€” Tell us about your tax situation in a few sentences.
522
+ ------------------------------------------------------------------------
523
+
524
+ > I'm married filing jointly, we have two kids. I work at Google on a W-2 but my wife runs a consulting LLC and she also has a rental property in Oakland. We have a Coinbase account with some crypto trades. We live in California.
525
+
526
+ # and so on.... we don't want to spoil the surprise.
527
+ ```
528
+
529
+ But a much more interesting way to run this example is with the `--interactive` flag:
530
+
531
+ Here is one extreme example where the form punishes the silly or the joker:
532
+
533
+ ```bash
534
+ $ be examples/llm-intake.rb --interactive
535
+
536
+ ========================================================================
537
+ INQUIREX + LLM DEMO β€” Tax Intake
538
+ Powered by: OpenAI GPT
539
+ ========================================================================
540
+
541
+ Step 1 β€” Tell us about your tax situation in a few sentences.
542
+ ------------------------------------------------------------------------
543
+
544
+ > I have no clue. Never done taxes.
545
+
546
+ # ..... Try it! :)
547
+ ```
548
+
549
+ The above script is a self contained Ruby executable. You might not even need `bundle exec` to run it.
550
+
551
+ The second example is a deliberate pure DSL example that you must run via some sort of renderer.
552
+
553
+ If you ran `bundle install` in this repo, you can then run the following command:
554
+
555
+ ```bash
556
+ bundle exec inquirex-tty run examples/tax-preparation-estimator.rb
557
+ ```
558
+
559
+ What's happening here? The gem `inquirex-tty` is not a formal dependency for `inquirex-llm`, so it's not declared in the `gemspec`. It's only declared in the `Gemfile`, which isn't even distributed with the gem file.
560
+
561
+ That gem provides the terminal commands and the interface to interprete the DSL in that example file. We recommend that you play around with this, and report any issues to the Github Issues board.
407
562
 
408
563
  ## JSON Serialization
409
564
 
@@ -426,7 +581,8 @@ LLM steps serialize with `"requires_server": true` so the JS widget knows to rou
426
581
  }
427
582
  },
428
583
  "from_steps": ["business_description"],
429
- "model": "claude_sonnet",
584
+ "use_first_available_model": ["deepseek/deepseek-v4.1-flash",
585
+ "anthropic/claude-haiku-5.5"],
430
586
  "temperature": 0.2,
431
587
  "max_tokens": 1024
432
588
  }
@@ -50,12 +50,13 @@ module Inquirex
50
50
 
51
51
  # @param node [Inquirex::LLM::Node] the current LLM step
52
52
  # @param answers [Hash] all collected answers so far
53
+ # @param model [String, nil] model id to use instead of the node's hint (set by routing)
53
54
  # @return [Extraction] the schema-shaped values, with the model's raw JSON and the usage
54
55
  # @raise [Errors::AdapterError] on API / parse failures
55
56
  # @raise [Errors::SchemaViolationError] when the LLM output misses schema fields
56
- def call(node, answers = {})
57
+ def call(node, answers = {}, model: nil)
57
58
  source = source_answers(node, answers)
58
- model = resolve_model(node)
59
+ model ||= resolve_model(node)
59
60
  temperature = node.respond_to?(:temperature) ? (node.temperature || config.temperature) : config.temperature
60
61
  max_tokens = node.respond_to?(:max_tokens) ? (node.max_tokens || config.max_tokens) : config.max_tokens
61
62
 
@@ -83,11 +84,12 @@ module Inquirex
83
84
  # @param node [Inquirex::LLM::Node] the summarize step
84
85
  # @param transcript [String] the session transcript
85
86
  # @param answers [Hash] unused; accepted for interface symmetry
87
+ # @param model [String, nil] model id to use instead of the node's hint (set by routing)
86
88
  # @return [String] markdown summary
87
89
  # @raise [Errors::AdapterError] on API / parse failures
88
- def summarize(node, transcript, _answers = {})
90
+ def summarize(node, transcript, _answers = {}, model: nil)
89
91
  response = call_api(
90
- model: resolve_model(node),
92
+ model: model || resolve_model(node),
91
93
  system: Prompts::SUMMARIZE,
92
94
  user: summary_input(transcript),
93
95
  temperature: node.respond_to?(:temperature) ? (node.temperature || config.summary_temperature) : config.summary_temperature,
@@ -20,11 +20,23 @@ module Inquirex
20
20
  # typo in INQUIREX_LLM_ADAPTER fails loudly instead of silently falling
21
21
  # through to auto-detection.
22
22
  #
23
- # @example
23
+ # Model routing ({Routing}) is configured with four more attributes that
24
+ # have no environment variables: {#llm_vendors_priority},
25
+ # {#llm_models_priority}, {#dsl_can_reprioritize} and
26
+ # {#dsl_can_use_unlisted_models}. Setting {#llm_vendors_priority} turns
27
+ # routing on; until then the deprecated single-provider settings apply.
28
+ #
29
+ # @example Routing (0.13.0+)
30
+ # Inquirex::LLM.configure do |c|
31
+ # c.llm_vendors_priority = %i[openrouter anthropic]
32
+ # c.llm_models_priority = %w[deepseek/deepseek-v4.1-flash anthropic/claude-haiku-5.5]
33
+ # c.max_tokens = 4096
34
+ # end.ensure_provider_models!
35
+ #
36
+ # @example Single provider (deprecated)
24
37
  # Inquirex::LLM.configure do |c|
25
38
  # c.provider = :anthropic
26
39
  # c.anthropic_model = "claude-opus-5-5"
27
- # c.max_tokens = 4096
28
40
  # end
29
41
  class Configuration
30
42
  # The providers {LLM.adapter} can build. nil means auto-detect.
@@ -78,12 +90,83 @@ module Inquirex
78
90
  end
79
91
  end
80
92
 
93
+ # @return [Array<Symbol>, nil] vendors to route through, by priority; nil leaves routing off
94
+ attr_reader :llm_vendors_priority
95
+ # @return [Array<String>] "vendor/model" names, by priority: what a step without its own list uses
96
+ attr_reader :llm_models_priority
97
+ # @return [Boolean] whether a step's own model order beats llm_models_priority (default true)
98
+ attr_accessor :dsl_can_reprioritize
99
+ # @return [Boolean] whether a step may name models absent from llm_models_priority (default true)
100
+ attr_accessor :dsl_can_use_unlisted_models
101
+
81
102
  # @param env [#[]] the environment to read; ENV unless a spec says otherwise
82
103
  # @raise [Errors::ConfigurationError] when a variable holds an invalid value
83
104
  def initialize(env = ENV)
84
105
  SETTINGS.each do |name, setting|
85
106
  instance_variable_set(:"@#{name}", resolve(name, env[setting.env], setting.env))
86
107
  end
108
+ @llm_vendors_priority = nil
109
+ @llm_models_priority = []
110
+ @dsl_can_reprioritize = true
111
+ @dsl_can_use_unlisted_models = true
112
+ @routing_lock = Mutex.new
113
+ end
114
+
115
+ # @param vendors [Array<Symbol, String>, nil] from {Routing::VENDORS}; nil turns routing off
116
+ # @raise [Errors::ConfigurationError] on an unknown vendor
117
+ def llm_vendors_priority=(vendors)
118
+ @router = nil
119
+ if vendors.nil?
120
+ @llm_vendors_priority = nil
121
+ return
122
+ end
123
+
124
+ list = Array(vendors).map { |vendor| vendor.to_s.strip.downcase.to_sym }.uniq
125
+ unknown = list - Routing::VENDORS
126
+ invalid!("Inquirex::LLM.configuration.llm_vendors_priority", unknown, "a list of #{Routing::VENDORS.join(", ")}") if unknown.any?
127
+ @llm_vendors_priority = list.freeze
128
+ end
129
+
130
+ # @param models [Array<String, Symbol>] "vendor/model" names
131
+ # @raise [Errors::ConfigurationError] on a name that is not "vendor/model"
132
+ def llm_models_priority=(models)
133
+ @router = nil
134
+ list = Array(models).map(&:to_s).uniq
135
+ bad = list.reject { |model| Routing::ModelId.valid?(model) }
136
+ invalid!("Inquirex::LLM.configuration.llm_models_priority", bad, "a list of \"vendor/model\" names") if bad.any?
137
+ @llm_models_priority = list.freeze
138
+ end
139
+
140
+ # @return [Boolean] whether per-step model routing is on
141
+ def routing? = !@llm_vendors_priority.nil?
142
+
143
+ # Settles which vendors and models this process can use: drops each
144
+ # vendor without an API key or a reachable model catalog, then each
145
+ # model no remaining vendor serves, warning on stderr for each. Runs
146
+ # once; a later call is a no-op until the routing settings change.
147
+ #
148
+ # @param catalog [#fetch] downloads a provider's model ids (a spec passes a fake)
149
+ # @param console [Routing::Console]
150
+ # @return [self]
151
+ # @raise [Errors::ConfigurationError] when llm_vendors_priority is not set
152
+ # @raise [Errors::MissingProviderAPIKeysError] when no vendor is usable
153
+ # @raise [Errors::NoAvailableModelsError] when no model is servable
154
+ def ensure_provider_models!(catalog: Routing::Catalog.new, console: Routing::Console.new)
155
+ raise Errors::ConfigurationError, "set llm_vendors_priority before ensure_provider_models!" unless routing?
156
+
157
+ @routing_lock.synchronize do
158
+ @router ||= Routing::Router.new(self, Routing::Registry.new(self, catalog:, console:).ensure!, console:)
159
+ end
160
+ self
161
+ end
162
+
163
+ # @return [Boolean] whether {#ensure_provider_models!} has already settled the vendors
164
+ def routing_ready? = !@router.nil?
165
+
166
+ # @return [Routing::Router] the router, running {#ensure_provider_models!} first if nothing has
167
+ def router
168
+ ensure_provider_models! unless @router
169
+ @router
87
170
  end
88
171
 
89
172
  # @return [Boolean] whether debug logging is on
@@ -35,6 +35,7 @@ module Inquirex
35
35
  @from_steps = []
36
36
  @from_all = false
37
37
  @model = nil
38
+ @models = []
38
39
  @temperature = nil
39
40
  @max_tokens = nil
40
41
  @fallback = nil
@@ -98,6 +99,19 @@ module Inquirex
98
99
  @model = name.to_sym
99
100
  end
100
101
 
102
+ # The models this step prefers, best first, as OpenRouter-style
103
+ # "vendor/model" names. The first one a usable vendor serves is used
104
+ # (see {LLM.route}); it overrides {#model}. The list never reaches
105
+ # the wire format: the server reads it from the definition it loaded.
106
+ #
107
+ # @example
108
+ # use_first_available_model "deepseek/deepseek-v4.1-flash", "anthropic/claude-haiku-5.5"
109
+ #
110
+ # @param names [Array<String, Symbol, Array>] one or more "vendor/model" names, or one array
111
+ def use_first_available_model(*names)
112
+ @models.concat(names.flatten.map(&:to_s))
113
+ end
114
+
101
115
  # Optional sampling temperature.
102
116
  #
103
117
  # @param value [Float]
@@ -164,6 +178,7 @@ module Inquirex
164
178
  # reference does not resolve to an ask/confirm question
165
179
  def build(id, nodes: nil)
166
180
  validate!(id)
181
+ validate_models!(id)
167
182
 
168
183
  field_map = resolve_schema_refs(id, nodes).merge(@schema_fields)
169
184
  schema_obj = field_map.empty? ? nil : Schema.new(**field_map)
@@ -177,6 +192,7 @@ module Inquirex
177
192
  from_steps: @from_steps,
178
193
  from_all: @from_all,
179
194
  model: @model,
195
+ models: @models.uniq,
180
196
  temperature: @temperature,
181
197
  max_tokens: @max_tokens,
182
198
  fallback: @fallback,
@@ -283,6 +299,40 @@ module Inquirex
283
299
  spec
284
300
  end
285
301
 
302
+ # `use_first_available_model` entries must be "vendor/model"; with
303
+ # dsl_can_use_unlisted_models off, also in llm_models_priority.
304
+ # Declaring `model` as well is legal but pointless, so it warns.
305
+ def validate_models!(id)
306
+ return if @models.empty?
307
+
308
+ bad = @models.reject { |name| Routing::ModelId.valid?(name) }
309
+ unless bad.empty?
310
+ raise Errors::DefinitionError,
311
+ "LLM step #{id.inspect} use_first_available_model needs \"vendor/model\" names " \
312
+ "(e.g. \"anthropic/claude-haiku-5.5\"), got #{bad.map(&:inspect).join(", ")}"
313
+ end
314
+
315
+ config = LLM.configuration
316
+ unless config.dsl_can_use_unlisted_models
317
+ unlisted = @models - config.llm_models_priority
318
+ unless unlisted.empty?
319
+ raise Errors::DefinitionError,
320
+ "LLM step #{id.inspect} names #{unlisted.join(", ")}, which llm_models_priority does not list, " \
321
+ "and dsl_can_use_unlisted_models is false"
322
+ end
323
+ end
324
+
325
+ if config.routing_ready? && @models.none? { config.router.registry.route_for(it, verb: @verb) }
326
+ warn "[inquirex-llm] LLM step #{id.inspect}: no usable vendor serves #{@models.join(", ")}; " \
327
+ "its calls will fall back to llm_models_priority"
328
+ end
329
+
330
+ return unless @model
331
+
332
+ warn "[inquirex-llm] LLM step #{id.inspect} declares both `model` and `use_first_available_model`; " \
333
+ "`model #{@model.inspect}` is ignored"
334
+ end
335
+
286
336
  def validate!(id)
287
337
  return validate_summarize!(id) if @verb == :summarize
288
338
 
@@ -18,6 +18,14 @@ module Inquirex
18
18
  # Raised when a configuration value, from ENV or a writer, is invalid.
19
19
  # The message names the variable or attribute that carried it.
20
20
  class ConfigurationError < Error; end
21
+
22
+ # Raised by {LLM.ensure_provider_models!} when no vendor in
23
+ # llm_vendors_priority has its API key set and a reachable catalog.
24
+ class MissingProviderAPIKeysError < ConfigurationError; end
25
+
26
+ # Raised when no model in llm_models_priority is served by a usable
27
+ # vendor, or when no model at all can serve a given step.
28
+ class NoAvailableModelsError < ConfigurationError; end
21
29
  end
22
30
  end
23
31
  end
@@ -9,9 +9,9 @@ module Inquirex
9
9
  # canonicalized by the gem. It never scores; {Scorer} does that.
10
10
  #
11
11
  # A reply that is not a JSON object is the model's failure and comes
12
- # back as a {LLM::Evals::Reply} with `error` set. A transport failure
12
+ # back as a {LLM::Evals::Results::Reply} with `error` set. A transport failure
13
13
  # raises, and the run counts it as an error rather than a wrong answer.
14
- class Adapter < ::LLM::Evals::Adapter
14
+ class Adapter < ::LLM::Evals::Actions::Adapter
15
15
  # Recorded with every experiment: which prompt the models saw.
16
16
  PROMPT = "Inquirex::LLM::OpenAIAdapter"
17
17
 
@@ -36,14 +36,14 @@ module Inquirex
36
36
  set.schema
37
37
  end
38
38
 
39
- # @param kase [LLM::Evals::Case]
40
- # @param model [LLM::Evals::Model]
41
- # @return [LLM::Evals::Reply]
39
+ # @param kase [LLM::Evals::Datasets::Case]
40
+ # @param model [LLM::Evals::Models::Model]
41
+ # @return [LLM::Evals::Results::Reply]
42
42
  def call(kase, model:)
43
43
  set = dataset(kase.dataset)
44
44
  adapter = ModelAdapter.new(model)
45
45
  extraction = adapter.call(set.node, { set.source_step => kase.input })
46
- ::LLM::Evals::Reply.new(
46
+ ::LLM::Evals::Results::Reply.new(
47
47
  output: extraction.output.transform_keys(&:to_s),
48
48
  raw: extraction.raw.transform_keys(&:to_s),
49
49
  usage: adapter.completion.usage,
@@ -52,13 +52,13 @@ module Inquirex
52
52
  rescue Errors::AdapterError => e
53
53
  raise if adapter.completion.nil? # nothing was asked: not the model's doing
54
54
 
55
- ::LLM::Evals::Reply.new(error: e.message.lines.first.strip,
55
+ ::LLM::Evals::Results::Reply.new(error: e.message.lines.first.strip,
56
56
  raw: adapter.completion.text,
57
57
  usage: adapter.completion.usage,
58
58
  metadata: { prompt: adapter.prompt })
59
59
  end
60
60
 
61
- # @param kase [LLM::Evals::Case]
61
+ # @param kase [LLM::Evals::Datasets::Case]
62
62
  # @return [Hash] the schema the scorer grades against
63
63
  def context(kase) = { schema: dataset(kase.dataset).schema }
64
64