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 +4 -4
- data/CHANGELOG.md +4 -0
- data/README.md +187 -31
- data/lib/inquirex/llm/anthropic_adapter.rb +6 -4
- data/lib/inquirex/llm/configuration.rb +85 -2
- data/lib/inquirex/llm/dsl/llm_step_builder.rb +50 -0
- data/lib/inquirex/llm/errors.rb +8 -0
- data/lib/inquirex/llm/evals/adapter.rb +8 -8
- data/lib/inquirex/llm/evals/model_adapter.rb +3 -3
- data/lib/inquirex/llm/evals/scorer.rb +14 -14
- data/lib/inquirex/llm/jev_adapter.rb +7 -6
- data/lib/inquirex/llm/node.rb +5 -1
- data/lib/inquirex/llm/null_adapter.rb +2 -2
- data/lib/inquirex/llm/openai_adapter.rb +19 -14
- data/lib/inquirex/llm/routing/catalog.rb +74 -0
- data/lib/inquirex/llm/routing/console.rb +34 -0
- data/lib/inquirex/llm/routing/model_id.rb +65 -0
- data/lib/inquirex/llm/routing/registry.rb +162 -0
- data/lib/inquirex/llm/routing/route.rb +21 -0
- data/lib/inquirex/llm/routing/router.rb +79 -0
- data/lib/inquirex/llm/routing.rb +26 -0
- data/lib/inquirex/llm/safe_source.rb +1 -0
- data/lib/inquirex/llm/version.rb +1 -1
- data/lib/inquirex/llm.rb +51 -0
- metadata +74 -68
|
@@ -4,7 +4,7 @@ module Inquirex
|
|
|
4
4
|
module LLM
|
|
5
5
|
module Evals
|
|
6
6
|
# The gem's {OpenAIAdapter} with its transport swapped for an
|
|
7
|
-
# llm-evals {LLM::Evals::Model}. Everything the model sees and
|
|
7
|
+
# llm-evals {LLM::Evals::Models::Model}. Everything the model sees and
|
|
8
8
|
# everything done to its answer is production's: the system prompt,
|
|
9
9
|
# the schema contract, the user prompt built from the step's `from`
|
|
10
10
|
# answers, fence stripping, JSON parsing and the canonicalization of
|
|
@@ -18,13 +18,13 @@ module Inquirex
|
|
|
18
18
|
# OpenAIAdapter insists on a key; the eval model holds the real one.
|
|
19
19
|
NO_KEY = "(unused: the eval model carries its own key)"
|
|
20
20
|
|
|
21
|
-
# @return [LLM::Evals::
|
|
21
|
+
# @return [LLM::Evals::Results::ProviderResponse, nil] what the model answered, once asked
|
|
22
22
|
attr_reader :completion
|
|
23
23
|
|
|
24
24
|
# @return [Hash{Symbol => String}, nil] the system and user prompts, once sent
|
|
25
25
|
attr_reader :prompt
|
|
26
26
|
|
|
27
|
-
# @param model [LLM::Evals::Model]
|
|
27
|
+
# @param model [LLM::Evals::Models::Model]
|
|
28
28
|
def initialize(model)
|
|
29
29
|
super(api_key: NO_KEY, model: model.id)
|
|
30
30
|
@model = model
|
|
@@ -13,36 +13,36 @@ module Inquirex
|
|
|
13
13
|
# share the model answered anyway; it is nil when the truth has no
|
|
14
14
|
# null, so a dataset of complete texts neither earns nor loses by it.
|
|
15
15
|
# `invalid_rate` is the share of fields the schema would reject.
|
|
16
|
-
class Scorer < ::LLM::Evals::Scorer
|
|
16
|
+
class Scorer < ::LLM::Evals::Scoring::Scorer
|
|
17
17
|
METRICS = [
|
|
18
|
-
::LLM::Evals::Metric.new(name: "score",
|
|
18
|
+
::LLM::Evals::Scoring::Metric.new(name: "score",
|
|
19
19
|
primary: true,
|
|
20
20
|
description: "Mean field value: correct 1.0, missed 0.2, hallucinated 0.15, incorrect 0.1, invalid 0; " \
|
|
21
21
|
"a multi_enum is the mean of its elements."),
|
|
22
|
-
::LLM::Evals::Metric.new(name: "exact", description: "1 when every field is correct."),
|
|
23
|
-
::LLM::Evals::Metric.new(name: "hallucinated_rate",
|
|
22
|
+
::LLM::Evals::Scoring::Metric.new(name: "exact", description: "1 when every field is correct."),
|
|
23
|
+
::LLM::Evals::Scoring::Metric.new(name: "hallucinated_rate",
|
|
24
24
|
description: "Of the fields the text never answers (truth null), the share the model answered anyway; " \
|
|
25
25
|
"nothing recorded when the truth has no null."),
|
|
26
|
-
::LLM::Evals::Metric.new(name: "invalid_rate",
|
|
26
|
+
::LLM::Evals::Scoring::Metric.new(name: "invalid_rate",
|
|
27
27
|
description: "Share of fields whose value the schema does not allow: off the list, wrong type.")
|
|
28
28
|
].freeze
|
|
29
29
|
|
|
30
|
-
# How the gem's field types read to {LLM::Evals::SchemaValidator}.
|
|
30
|
+
# How the gem's field types read to {LLM::Evals::Scoring::SchemaValidator}.
|
|
31
31
|
VALIDATOR_TYPES = { enum: :enum, multi_enum: :multi_enum, integer: :integer, boolean: :boolean,
|
|
32
32
|
decimal: :number, currency: :number }.freeze
|
|
33
33
|
|
|
34
|
-
# @return [Array<LLM::Evals::Metric>]
|
|
34
|
+
# @return [Array<LLM::Evals::Scoring::Metric>]
|
|
35
35
|
def metrics = METRICS
|
|
36
36
|
|
|
37
|
-
# @param kase [LLM::Evals::Case]
|
|
38
|
-
# @param reply [LLM::Evals::Reply]
|
|
37
|
+
# @param kase [LLM::Evals::Datasets::Case]
|
|
38
|
+
# @param reply [LLM::Evals::Results::Reply]
|
|
39
39
|
# @param context [Hash] `:schema`, the {Inquirex::LLM::Schema} the dataset extracts
|
|
40
|
-
# @return [LLM::Evals::Score]
|
|
40
|
+
# @return [LLM::Evals::Results::Score]
|
|
41
41
|
def call(kase, reply, context:)
|
|
42
42
|
schema = context.fetch(:schema)
|
|
43
43
|
fields = field_scores(schema, kase.expected, reply.raw)
|
|
44
44
|
open = fields.select { kase.expected[it.field].nil? }
|
|
45
|
-
::LLM::Evals::Score.new(
|
|
45
|
+
::LLM::Evals::Results::Score.new(
|
|
46
46
|
value: mean(fields.map(&:value)),
|
|
47
47
|
metrics: { "score" => mean(fields.map(&:value)),
|
|
48
48
|
"exact" => fields.all?(&:correct?) ? 1.0 : 0.0,
|
|
@@ -74,7 +74,7 @@ module Inquirex
|
|
|
74
74
|
# Checks expected.json against the schema, every field nullable: a
|
|
75
75
|
# null is how the truth says the text never answers it.
|
|
76
76
|
#
|
|
77
|
-
# @param kase [LLM::Evals::Case]
|
|
77
|
+
# @param kase [LLM::Evals::Datasets::Case]
|
|
78
78
|
# @param context [Hash]
|
|
79
79
|
# @return [Array<String>] unknown keys, missing keys, off-list values, wrong types
|
|
80
80
|
def verify(kase, context:)
|
|
@@ -82,10 +82,10 @@ module Inquirex
|
|
|
82
82
|
fields = schema.field_specs.to_h do |name, spec|
|
|
83
83
|
[name.to_s, { type: VALIDATOR_TYPES.fetch(spec.type, :string), enum: spec.values, nullable: true }]
|
|
84
84
|
end
|
|
85
|
-
::LLM::Evals::SchemaValidator.new(fields).problems(kase.expected)
|
|
85
|
+
::LLM::Evals::Scoring::SchemaValidator.new(fields).problems(kase.expected)
|
|
86
86
|
end
|
|
87
87
|
|
|
88
|
-
# @param kase [LLM::Evals::Case]
|
|
88
|
+
# @param kase [LLM::Evals::Datasets::Case]
|
|
89
89
|
# @return [String] "answered 7/10"
|
|
90
90
|
def summary(kase)
|
|
91
91
|
return nil unless kase.expected.is_a?(Hash)
|
|
@@ -85,9 +85,10 @@ module Inquirex
|
|
|
85
85
|
#
|
|
86
86
|
# @param node [Inquirex::LLM::Node] the current extract step
|
|
87
87
|
# @param answers [Hash] all collected answers so far
|
|
88
|
+
# @param model [String, nil] Jev model to use instead of the configured one (set by routing)
|
|
88
89
|
# @return [Extraction] usage is { input_tokens:, output_tokens: }
|
|
89
90
|
# @raise [Errors::AdapterError] on API failures, or a field Jev cannot answer
|
|
90
|
-
def call(node, answers = {})
|
|
91
|
+
def call(node, answers = {}, model: nil)
|
|
91
92
|
raise Errors::AdapterError, "#{node.id.inspect} has no schema; Jev can only answer a schema" unless node.schema
|
|
92
93
|
|
|
93
94
|
unsupported = self.class.unsupported_fields(node.schema)
|
|
@@ -101,7 +102,7 @@ module Inquirex
|
|
|
101
102
|
readers = node.schema.field_specs.to_h do |field, spec|
|
|
102
103
|
[field, ask(questions, node, field, spec, source.values.join("\n"))]
|
|
103
104
|
end
|
|
104
|
-
result = post(state: { "answers" => source }, questions: questions)
|
|
105
|
+
result = post(state: { "answers" => source }, questions: questions, model: model || self.model)
|
|
105
106
|
|
|
106
107
|
confidence = {}
|
|
107
108
|
values = readers.to_h { |field, reader| [field, reader.call(result.fetch("answers"), confidence)] }
|
|
@@ -113,7 +114,7 @@ module Inquirex
|
|
|
113
114
|
# Jev cannot write prose.
|
|
114
115
|
#
|
|
115
116
|
# @raise [Errors::AdapterError] always
|
|
116
|
-
def summarize(node, _transcript, _answers = {})
|
|
117
|
+
def summarize(node, _transcript, _answers = {}, model: nil) # rubocop:disable Lint/UnusedMethodArgument
|
|
117
118
|
raise Errors::AdapterError, "Jev cannot summarize (#{node.id.inspect}): route summarize to a text model"
|
|
118
119
|
end
|
|
119
120
|
|
|
@@ -210,10 +211,10 @@ module Inquirex
|
|
|
210
211
|
|
|
211
212
|
# @return [Hash] the parsed response
|
|
212
213
|
# @raise [Errors::AdapterError] on a non-2xx after retries, or a body that is not JSON
|
|
213
|
-
def post(state:, questions:)
|
|
214
|
+
def post(state:, questions:, model: self.model)
|
|
214
215
|
attempt = 0
|
|
215
216
|
loop do
|
|
216
|
-
response = request(JSON.generate("state" => state, "questions" => questions, "model" => model))
|
|
217
|
+
response = request(JSON.generate("state" => state, "questions" => questions, "model" => model), model)
|
|
217
218
|
return JSON.parse(response.body) if response.is_a?(Net::HTTPSuccess)
|
|
218
219
|
|
|
219
220
|
if RETRY_STATUSES.include?(response.code) && attempt < MAX_RETRIES
|
|
@@ -227,7 +228,7 @@ module Inquirex
|
|
|
227
228
|
raise Errors::AdapterError, "TypeSafe returned a body that is not JSON: #{e.message}"
|
|
228
229
|
end
|
|
229
230
|
|
|
230
|
-
def request(body)
|
|
231
|
+
def request(body, model = self.model)
|
|
231
232
|
uri = URI(API_URL)
|
|
232
233
|
http = Net::HTTP.new(uri.host, uri.port)
|
|
233
234
|
http.use_ssl = true
|
data/lib/inquirex/llm/node.rb
CHANGED
|
@@ -24,6 +24,8 @@ module Inquirex
|
|
|
24
24
|
# @attr_reader from_steps [Array<Symbol>] source step ids whose answers feed the LLM
|
|
25
25
|
# @attr_reader from_all [Boolean] whether to pass all collected answers to the LLM
|
|
26
26
|
# @attr_reader model [Symbol, nil] optional model hint (e.g. :claude_sonnet)
|
|
27
|
+
# @attr_reader models [Array<String>] "vendor/model" names from `use_first_available_model`,
|
|
28
|
+
# by preference; server-side only, never serialized (see docs/decisions/prioritized-model-selection.md)
|
|
27
29
|
# @attr_reader temperature [Float, nil] optional sampling temperature
|
|
28
30
|
# @attr_reader max_tokens [Integer, nil] optional max output tokens
|
|
29
31
|
# @attr_reader fallback [Proc, nil] server-side fallback (stripped from JSON)
|
|
@@ -40,17 +42,19 @@ module Inquirex
|
|
|
40
42
|
:from_steps,
|
|
41
43
|
:from_all,
|
|
42
44
|
:model,
|
|
45
|
+
:models,
|
|
43
46
|
:temperature,
|
|
44
47
|
:max_tokens,
|
|
45
48
|
:fallback
|
|
46
49
|
|
|
47
50
|
def initialize(prompt:, schema: nil, from_steps: [], from_all: false,
|
|
48
|
-
model: nil, temperature: nil, max_tokens: nil, fallback: nil, **)
|
|
51
|
+
model: nil, models: [], temperature: nil, max_tokens: nil, fallback: nil, **)
|
|
49
52
|
@prompt = prompt
|
|
50
53
|
@schema = schema
|
|
51
54
|
@from_steps = Array(from_steps).map(&:to_sym).freeze
|
|
52
55
|
@from_all = !!from_all
|
|
53
56
|
@model = model&.to_sym
|
|
57
|
+
@models = Array(models).map(&:to_s).freeze
|
|
54
58
|
@temperature = temperature&.to_f
|
|
55
59
|
@max_tokens = max_tokens&.to_i
|
|
56
60
|
@fallback = fallback
|
|
@@ -37,7 +37,7 @@ module Inquirex
|
|
|
37
37
|
# @param node [LLM::Node]
|
|
38
38
|
# @param _answers [Hash] ignored
|
|
39
39
|
# @return [Hash, String]
|
|
40
|
-
def call(node, _answers = {})
|
|
40
|
+
def call(node, _answers = {}, model: nil) # rubocop:disable Lint/UnusedMethodArgument
|
|
41
41
|
if node.schema
|
|
42
42
|
node.schema.fields.each_with_object({}) do |(name, type), acc|
|
|
43
43
|
acc[name] = placeholder_for(node.schema, name, type)
|
|
@@ -55,7 +55,7 @@ module Inquirex
|
|
|
55
55
|
# @param transcript [String] the session transcript
|
|
56
56
|
# @param _answers [Hash] ignored
|
|
57
57
|
# @return [String] markdown
|
|
58
|
-
def summarize(node, transcript, _answers = {})
|
|
58
|
+
def summarize(node, transcript, _answers = {}, model: nil) # rubocop:disable Lint/UnusedMethodArgument
|
|
59
59
|
<<~MARKDOWN.strip
|
|
60
60
|
This is a placeholder summary for #{node.id}. No language model was called.
|
|
61
61
|
|
|
@@ -44,12 +44,13 @@ module Inquirex
|
|
|
44
44
|
|
|
45
45
|
# @param node [Inquirex::LLM::Node] the current LLM step
|
|
46
46
|
# @param answers [Hash] all collected answers so far
|
|
47
|
+
# @param model [String, nil] model id to use instead of the node's hint (set by routing)
|
|
47
48
|
# @return [Extraction] the schema-shaped values, with the model's raw JSON and the usage
|
|
48
49
|
# @raise [Errors::AdapterError] on API / parse failures
|
|
49
50
|
# @raise [Errors::SchemaViolationError] when the LLM output misses schema fields
|
|
50
|
-
def call(node, answers = {})
|
|
51
|
+
def call(node, answers = {}, model: nil)
|
|
51
52
|
source = source_answers(node, answers)
|
|
52
|
-
model
|
|
53
|
+
model ||= resolve_model(node)
|
|
53
54
|
temperature = node.respond_to?(:temperature) ? (node.temperature || config.temperature) : config.temperature
|
|
54
55
|
max_tokens = node.respond_to?(:max_tokens) ? (node.max_tokens || config.max_tokens) : config.max_tokens
|
|
55
56
|
|
|
@@ -76,15 +77,17 @@ module Inquirex
|
|
|
76
77
|
# @param node [Inquirex::LLM::Node] the summarize step
|
|
77
78
|
# @param transcript [String] the session transcript
|
|
78
79
|
# @param answers [Hash] unused; accepted for interface symmetry
|
|
80
|
+
# @param model [String, nil] model id to use instead of the node's hint (set by routing)
|
|
79
81
|
# @return [String] markdown summary
|
|
80
82
|
# @raise [Errors::AdapterError] on API / parse failures
|
|
81
|
-
def summarize(node, transcript, _answers = {})
|
|
83
|
+
def summarize(node, transcript, _answers = {}, model: nil)
|
|
82
84
|
response = call_api(
|
|
83
|
-
model: resolve_model(node),
|
|
85
|
+
model: model || resolve_model(node),
|
|
84
86
|
system: Prompts::SUMMARIZE,
|
|
85
87
|
user: summary_input(transcript),
|
|
86
88
|
temperature: node.respond_to?(:temperature) ? (node.temperature || config.summary_temperature) : config.summary_temperature,
|
|
87
|
-
max_tokens: node.respond_to?(:max_tokens) ? (node.max_tokens || config.summary_max_tokens) : config.summary_max_tokens
|
|
89
|
+
max_tokens: node.respond_to?(:max_tokens) ? (node.max_tokens || config.summary_max_tokens) : config.summary_max_tokens,
|
|
90
|
+
json: false
|
|
88
91
|
)
|
|
89
92
|
parse_text_response(response)
|
|
90
93
|
end
|
|
@@ -152,21 +155,23 @@ module Inquirex
|
|
|
152
155
|
|
|
153
156
|
# The request body. Subclasses add provider-specific fields here.
|
|
154
157
|
#
|
|
158
|
+
# @param json [Boolean] ask for a JSON object; false for prose, since
|
|
159
|
+
# OpenAI rejects json_object when the messages never mention JSON
|
|
155
160
|
# @return [Hash]
|
|
156
|
-
def request_body(model:, system:, user:, temperature:, max_tokens:)
|
|
157
|
-
{
|
|
158
|
-
model:
|
|
159
|
-
max_tokens:
|
|
160
|
-
temperature:
|
|
161
|
-
|
|
162
|
-
messages: [
|
|
161
|
+
def request_body(model:, system:, user:, temperature:, max_tokens:, json: true)
|
|
162
|
+
body = {
|
|
163
|
+
model: model,
|
|
164
|
+
max_tokens: max_tokens,
|
|
165
|
+
temperature: temperature,
|
|
166
|
+
messages: [
|
|
163
167
|
{ role: "system", content: system },
|
|
164
168
|
{ role: "user", content: user }
|
|
165
169
|
]
|
|
166
170
|
}
|
|
171
|
+
json ? body.merge(response_format: { type: "json_object" }) : body
|
|
167
172
|
end
|
|
168
173
|
|
|
169
|
-
def call_api(model:, system:, user:, temperature:, max_tokens:)
|
|
174
|
+
def call_api(model:, system:, user:, temperature:, max_tokens:, json: true)
|
|
170
175
|
uri = URI(api_url)
|
|
171
176
|
http = Net::HTTP.new(uri.host, uri.port)
|
|
172
177
|
http.use_ssl = true
|
|
@@ -177,7 +182,7 @@ module Inquirex
|
|
|
177
182
|
request["Content-Type"] = "application/json"
|
|
178
183
|
request["Authorization"] = "Bearer #{@api_key}"
|
|
179
184
|
request.body = JSON.generate(
|
|
180
|
-
request_body(model
|
|
185
|
+
request_body(model:, system:, user:, temperature:, max_tokens:, json:)
|
|
181
186
|
)
|
|
182
187
|
|
|
183
188
|
warn "[inquirex-llm] Calling #{provider_name} #{model}..." if config.debug?
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "net/http"
|
|
5
|
+
require "uri"
|
|
6
|
+
|
|
7
|
+
module Inquirex
|
|
8
|
+
module LLM
|
|
9
|
+
module Routing
|
|
10
|
+
# Downloads the model ids each provider serves, so a model is accepted
|
|
11
|
+
# only when its provider really lists it. One GET per provider; every
|
|
12
|
+
# failure (no answer in time, non-2xx, unreadable body) raises
|
|
13
|
+
# {Errors::AdapterError}, and the caller drops that provider.
|
|
14
|
+
class Catalog
|
|
15
|
+
# Seconds to wait for a catalog, connecting and reading.
|
|
16
|
+
TIMEOUT = 5
|
|
17
|
+
|
|
18
|
+
# Each provider's model list.
|
|
19
|
+
ENDPOINTS = {
|
|
20
|
+
openrouter: "https://openrouter.ai/api/v1/models",
|
|
21
|
+
openai: "https://api.openai.com/v1/models",
|
|
22
|
+
anthropic: "https://api.anthropic.com/v1/models?limit=1000",
|
|
23
|
+
typesafe: "https://api.typesafe.ai/v1/models"
|
|
24
|
+
}.freeze
|
|
25
|
+
|
|
26
|
+
# @param timeout [Numeric] seconds per request
|
|
27
|
+
def initialize(timeout: TIMEOUT)
|
|
28
|
+
@timeout = timeout
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# @param provider [Symbol] a key of {ENDPOINTS}
|
|
32
|
+
# @param api_key [String]
|
|
33
|
+
# @return [Set<String>] the model ids the provider lists
|
|
34
|
+
# @raise [Errors::AdapterError] when the catalog cannot be read
|
|
35
|
+
def fetch(provider, api_key)
|
|
36
|
+
uri = URI(ENDPOINTS.fetch(provider))
|
|
37
|
+
response = get(uri, headers(provider, api_key))
|
|
38
|
+
raise Errors::AdapterError, "#{provider} catalog: HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
|
|
39
|
+
|
|
40
|
+
ids(JSON.parse(response.body))
|
|
41
|
+
rescue JSON::ParserError, SystemCallError, IOError, Timeout::Error, OpenSSL::SSL::SSLError => e
|
|
42
|
+
raise Errors::AdapterError, "#{provider} catalog: #{e.class}: #{e.message}"
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
private
|
|
46
|
+
|
|
47
|
+
def get(uri, headers)
|
|
48
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
49
|
+
http.use_ssl = true
|
|
50
|
+
http.open_timeout = @timeout
|
|
51
|
+
http.read_timeout = @timeout
|
|
52
|
+
request = Net::HTTP::Get.new(uri)
|
|
53
|
+
headers.each { |name, value| request[name] = value }
|
|
54
|
+
http.request(request)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def headers(provider, api_key)
|
|
58
|
+
case provider
|
|
59
|
+
when :anthropic then { "x-api-key" => api_key, "anthropic-version" => "2023-06-01" }
|
|
60
|
+
else { "Authorization" => "Bearer #{api_key}" }
|
|
61
|
+
end
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Every provider here answers `{ "data": [{ "id": ... }, ...] }`.
|
|
65
|
+
def ids(body)
|
|
66
|
+
data = body.is_a?(Hash) ? body["data"] : nil
|
|
67
|
+
raise Errors::AdapterError, "catalog has no \"data\" list" unless data.is_a?(Array)
|
|
68
|
+
|
|
69
|
+
data.filter_map { |entry| entry["id"].to_s if entry.is_a?(Hash) && entry["id"] }.to_set
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
end
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Inquirex
|
|
4
|
+
module LLM
|
|
5
|
+
module Routing
|
|
6
|
+
# Coloured notices on stderr: yellow for something removed, green for
|
|
7
|
+
# what is left. Colour only when stderr is a terminal, so logs stay clean.
|
|
8
|
+
class Console
|
|
9
|
+
YELLOW = "\e[33m"
|
|
10
|
+
GREEN = "\e[32m"
|
|
11
|
+
RESET = "\e[0m"
|
|
12
|
+
|
|
13
|
+
# @param io [IO] where notices go
|
|
14
|
+
def initialize(io = $stderr)
|
|
15
|
+
@io = io
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# @param message [String]
|
|
19
|
+
# @return [void]
|
|
20
|
+
def warn(message) = say(YELLOW, "[inquirex-llm] WARNING: #{message}")
|
|
21
|
+
|
|
22
|
+
# @param message [String]
|
|
23
|
+
# @return [void]
|
|
24
|
+
def info(message) = say(GREEN, "[inquirex-llm] #{message}")
|
|
25
|
+
|
|
26
|
+
private
|
|
27
|
+
|
|
28
|
+
def say(color, message)
|
|
29
|
+
@io.puts(@io.respond_to?(:tty?) && @io.tty? ? "#{color}#{message}#{RESET}" : message)
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Inquirex
|
|
4
|
+
module LLM
|
|
5
|
+
module Routing
|
|
6
|
+
# An OpenRouter-style model name, "vendor/model", and the id each
|
|
7
|
+
# vendor's own API knows it by.
|
|
8
|
+
#
|
|
9
|
+
# @example
|
|
10
|
+
# id = ModelId.parse("anthropic/claude-haiku-5.5")
|
|
11
|
+
# id.vendor # => :anthropic
|
|
12
|
+
# id.native_id # => "claude-haiku-5-5"
|
|
13
|
+
# id.native_provider # => :anthropic
|
|
14
|
+
class ModelId < Data.define(:vendor, :name)
|
|
15
|
+
# "vendor/model": a lowercase vendor, then any model name without spaces.
|
|
16
|
+
FORMAT = %r{\A[a-z0-9][a-z0-9_.-]*/[^\s/][^\s]*\z}
|
|
17
|
+
|
|
18
|
+
# Vendors with an adapter of their own. Every other vendor is reached
|
|
19
|
+
# only through OpenRouter.
|
|
20
|
+
NATIVE = %i[anthropic openai typesafe].freeze
|
|
21
|
+
|
|
22
|
+
class << self
|
|
23
|
+
# @param value [String, Symbol]
|
|
24
|
+
# @return [Boolean] whether the value is a "vendor/model" name
|
|
25
|
+
def valid?(value) = FORMAT.match?(value.to_s)
|
|
26
|
+
|
|
27
|
+
# @param value [String, Symbol] "vendor/model"
|
|
28
|
+
# @return [ModelId]
|
|
29
|
+
# @raise [ArgumentError] when the value is not "vendor/model"
|
|
30
|
+
def parse(value)
|
|
31
|
+
raise ArgumentError, "#{value.inspect} is not a \"vendor/model\" name" unless valid?(value)
|
|
32
|
+
|
|
33
|
+
vendor, name = value.to_s.split("/", 2)
|
|
34
|
+
new(vendor: vendor.to_sym, name: name)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# The "vendor/model" name an old-style DSL model hint stands for:
|
|
38
|
+
# `:claude_sonnet` => "anthropic/claude-sonnet-5.5". A hint that is
|
|
39
|
+
# already "vendor/model" passes through.
|
|
40
|
+
#
|
|
41
|
+
# @param hint [Symbol, String, nil]
|
|
42
|
+
# @return [String, nil] nil when the hint names nothing routable
|
|
43
|
+
def from_hint(hint)
|
|
44
|
+
return nil if hint.nil?
|
|
45
|
+
return hint.to_s if valid?(hint)
|
|
46
|
+
|
|
47
|
+
Models::OPENROUTER_ALIASES[hint.to_sym]
|
|
48
|
+
end
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# @return [String] "vendor/model", as OpenRouter names it
|
|
52
|
+
def to_s = "#{vendor}/#{name}"
|
|
53
|
+
|
|
54
|
+
# @return [Symbol, nil] the vendor's own provider, nil when only OpenRouter serves it
|
|
55
|
+
def native_provider = NATIVE.include?(vendor) ? vendor : nil
|
|
56
|
+
|
|
57
|
+
# The id the vendor's own API uses. Anthropic writes versions with
|
|
58
|
+
# dashes ("claude-haiku-5-5") where OpenRouter uses dots ("5.5").
|
|
59
|
+
#
|
|
60
|
+
# @return [String]
|
|
61
|
+
def native_id = vendor == :anthropic ? name.tr(".", "-") : name
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Inquirex
|
|
4
|
+
module LLM
|
|
5
|
+
module Routing
|
|
6
|
+
# The vendors and models this Ruby process can actually use, settled
|
|
7
|
+
# once by {#ensure!}: a vendor needs its API key and a catalog that
|
|
8
|
+
# downloads; a model needs a surviving vendor that lists it. What is
|
|
9
|
+
# removed stays removed for the life of the process.
|
|
10
|
+
class Registry
|
|
11
|
+
# The environment variable each vendor's key comes from, for messages.
|
|
12
|
+
KEY_VARIABLES = {
|
|
13
|
+
openrouter: "OPENROUTER_API_KEY",
|
|
14
|
+
openai: "OPENAI_API_KEY",
|
|
15
|
+
anthropic: "ANTHROPIC_API_KEY",
|
|
16
|
+
typesafe: "TYPESAFE_API_KEY"
|
|
17
|
+
}.freeze
|
|
18
|
+
|
|
19
|
+
# @return [Array<Symbol>] usable vendors, in priority order
|
|
20
|
+
attr_reader :vendors
|
|
21
|
+
# @return [Array<String>] usable "vendor/model" names, in priority order
|
|
22
|
+
attr_reader :models
|
|
23
|
+
|
|
24
|
+
# @param config [Configuration]
|
|
25
|
+
# @param catalog [#fetch] downloads one provider's model ids
|
|
26
|
+
# @param console [Console]
|
|
27
|
+
def initialize(config, catalog: Catalog.new, console: Console.new)
|
|
28
|
+
@config = config
|
|
29
|
+
@catalog = catalog
|
|
30
|
+
@console = console
|
|
31
|
+
@catalogs = {}
|
|
32
|
+
@adapters = {}
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# @return [self]
|
|
36
|
+
# @raise [Errors::MissingProviderAPIKeysError] when no vendor is usable
|
|
37
|
+
# @raise [Errors::NoAvailableModelsError] when no model is servable
|
|
38
|
+
def ensure!
|
|
39
|
+
@vendors = usable_vendors
|
|
40
|
+
@adapters = @vendors.to_h { |vendor| [vendor, build_adapter(vendor)] }
|
|
41
|
+
@models = servable_models
|
|
42
|
+
self
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# The route for one model, or nil when no usable vendor serves it.
|
|
46
|
+
#
|
|
47
|
+
# @param model [String] "vendor/model"
|
|
48
|
+
# @param verb [Symbol] :extract or :summarize
|
|
49
|
+
# @param node [Node, nil] the step, which decides whether Jev can answer it
|
|
50
|
+
# @return [Route, nil]
|
|
51
|
+
def route_for(model, verb: :extract, node: nil)
|
|
52
|
+
id = ModelId.parse(model)
|
|
53
|
+
@vendors.each do |vendor|
|
|
54
|
+
route = route_via(vendor, id, verb, node)
|
|
55
|
+
return route if route
|
|
56
|
+
end
|
|
57
|
+
nil
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
private
|
|
61
|
+
|
|
62
|
+
def route_via(vendor, id, verb, node)
|
|
63
|
+
if vendor == :openrouter
|
|
64
|
+
return unless @catalogs[:openrouter].include?(id.to_s)
|
|
65
|
+
|
|
66
|
+
Route.new(model: id.to_s, provider: :openrouter, native_id: id.to_s, adapter: @adapters[:openrouter])
|
|
67
|
+
elsif vendor == id.native_provider
|
|
68
|
+
return unless listed?(vendor, id.native_id)
|
|
69
|
+
return if vendor == :typesafe && !jev_can_answer?(verb, node)
|
|
70
|
+
|
|
71
|
+
Route.new(model: id.to_s, provider: vendor, native_id: id.native_id, adapter: @adapters[vendor])
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Anthropic also lists dated snapshots ("claude-haiku-5-5-20261001").
|
|
76
|
+
def listed?(vendor, native_id)
|
|
77
|
+
ids = @catalogs[vendor]
|
|
78
|
+
ids.include?(native_id) || ids.any? { |id| id.start_with?("#{native_id}-") }
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# Jev chooses and cannot write: only an extract whose every field it can answer.
|
|
82
|
+
def jev_can_answer?(verb, node)
|
|
83
|
+
return false unless verb == :extract
|
|
84
|
+
return true if node.nil? # checking availability, not a specific step
|
|
85
|
+
|
|
86
|
+
node.respond_to?(:schema) && node.schema && JevAdapter.unsupported_fields(node.schema).empty?
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def usable_vendors
|
|
90
|
+
listed = @config.llm_vendors_priority
|
|
91
|
+
keyed = listed.select { |vendor| key?(vendor) }
|
|
92
|
+
fetched = download_catalogs(keyed)
|
|
93
|
+
usable = keyed.select { |vendor| fetched.include?(vendor) }
|
|
94
|
+
raise Errors::MissingProviderAPIKeysError, no_vendors_message(listed) if usable.empty?
|
|
95
|
+
|
|
96
|
+
@console.info("LLM vendors in use, by priority: #{usable.join(", ")}") if usable != listed
|
|
97
|
+
usable
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def key?(vendor)
|
|
101
|
+
return true if api_key(vendor)
|
|
102
|
+
|
|
103
|
+
@console.warn("#{vendor} is in llm_vendors_priority, but #{KEY_VARIABLES.fetch(vendor)} is not set; skipping it")
|
|
104
|
+
false
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# All catalogs at once, so boot waits for the slowest, not the sum.
|
|
108
|
+
def download_catalogs(vendors)
|
|
109
|
+
threads = vendors.to_h do |vendor|
|
|
110
|
+
thread = Thread.new do
|
|
111
|
+
Thread.current.report_on_exception = false # the error is reported below, as a warning
|
|
112
|
+
@catalog.fetch(vendor, api_key(vendor))
|
|
113
|
+
end
|
|
114
|
+
[vendor, thread]
|
|
115
|
+
end
|
|
116
|
+
threads.each_with_object([]) do |(vendor, thread), ok|
|
|
117
|
+
@catalogs[vendor] = thread.value
|
|
118
|
+
ok << vendor
|
|
119
|
+
rescue StandardError => e
|
|
120
|
+
@console.warn("#{vendor}'s model catalog could not be downloaded (#{e.message}); " \
|
|
121
|
+
"skipping #{vendor} until this process restarts")
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def servable_models
|
|
126
|
+
servable = @config.llm_models_priority.select do |model|
|
|
127
|
+
next true if route_for(model)
|
|
128
|
+
|
|
129
|
+
@console.warn("#{model} is in llm_models_priority, but no usable vendor serves it; skipping it")
|
|
130
|
+
false
|
|
131
|
+
end
|
|
132
|
+
raise Errors::NoAvailableModelsError, no_models_message if servable.empty?
|
|
133
|
+
|
|
134
|
+
servable
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def api_key(vendor) = @config.public_send(:"#{vendor}_api_key")
|
|
138
|
+
|
|
139
|
+
def build_adapter(vendor)
|
|
140
|
+
key = api_key(vendor)
|
|
141
|
+
case vendor
|
|
142
|
+
when :openrouter then OpenRouterAdapter.new(api_key: key)
|
|
143
|
+
when :openai then OpenAIAdapter.new(api_key: key)
|
|
144
|
+
when :anthropic then AnthropicAdapter.new(api_key: key)
|
|
145
|
+
when :typesafe then JevAdapter.new(api_key: key)
|
|
146
|
+
end
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def no_vendors_message(listed)
|
|
150
|
+
"None of llm_vendors_priority (#{listed.join(", ")}) is usable: set at least one of " \
|
|
151
|
+
"#{listed.map { |vendor| KEY_VARIABLES.fetch(vendor) }.join(", ")}, and make sure its model catalog is reachable"
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
def no_models_message
|
|
155
|
+
models = @config.llm_models_priority
|
|
156
|
+
listed = models.empty? ? "llm_models_priority is empty" : "none of #{models.join(", ")}"
|
|
157
|
+
"No model is available: #{listed} is served by the usable vendors (#{@vendors.join(", ")})"
|
|
158
|
+
end
|
|
159
|
+
end
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
end
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Inquirex
|
|
4
|
+
module LLM
|
|
5
|
+
module Routing
|
|
6
|
+
# Where one LLM step's call goes: the chosen "vendor/model", the
|
|
7
|
+
# provider serving it, the id that provider knows it by, and the
|
|
8
|
+
# adapter to call.
|
|
9
|
+
#
|
|
10
|
+
# @!attribute [r] model
|
|
11
|
+
# @return [String, nil] "vendor/model"; nil on the legacy path, where the adapter picks
|
|
12
|
+
# @!attribute [r] provider
|
|
13
|
+
# @return [Symbol, nil] :openrouter, :openai, :anthropic or :typesafe
|
|
14
|
+
# @!attribute [r] native_id
|
|
15
|
+
# @return [String, nil] the model id sent to the provider
|
|
16
|
+
# @!attribute [r] adapter
|
|
17
|
+
# @return [Adapter]
|
|
18
|
+
Route = Data.define(:model, :provider, :native_id, :adapter)
|
|
19
|
+
end
|
|
20
|
+
end
|
|
21
|
+
end
|