nitro_intelligence 4.3.2 → 4.4.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/Rakefile +11 -0
- data/docs/CHANGELOG.md +13 -0
- data/docs/README.md +26 -52
- data/lib/nitro_intelligence/client/base.rb +24 -11
- data/lib/nitro_intelligence/client/handlers/audio_transcription_handler.rb +1 -1
- data/lib/nitro_intelligence/client/handlers/chat_handler.rb +1 -1
- data/lib/nitro_intelligence/client/handlers/decision_handler.rb +1 -1
- data/lib/nitro_intelligence/client/handlers/embedding_handler.rb +19 -4
- data/lib/nitro_intelligence/client/handlers/rerank_handler.rb +1 -1
- data/lib/nitro_intelligence/client/handlers/text_to_speech_handler.rb +1 -1
- data/lib/nitro_intelligence/client/observers/langfuse_observer.rb +22 -11
- data/lib/nitro_intelligence/configuration.rb +3 -2
- data/lib/nitro_intelligence/media/image_generation.rb +1 -2
- data/lib/nitro_intelligence/models/gateway_models.rb +87 -0
- data/lib/nitro_intelligence/models/model.rb +20 -3
- data/lib/nitro_intelligence/models/model_catalog.rb +138 -24
- data/lib/nitro_intelligence/version.rb +1 -1
- data/lib/nitro_intelligence.rb +1 -1
- metadata +10 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 6487f455691ffd262370d81066b51e5b4cf6dad688e6002a5f9b02c29253e2cc
|
|
4
|
+
data.tar.gz: 372209bb82930b56c163780e2ccc87371fbcbff21b3cb715d8d2acde2dca4d37
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 692009dc4963b15df7a749c7aa10cf15c6d959e3575abd1d7cd07f292300010a70b91fdaca7bf90d48463c7b30672243f94769b2473c807a27a280cf5fda91ac
|
|
7
|
+
data.tar.gz: 4181e4fa302350c9c1210d726bf880435f8c1205f92397cbfb55b83e8f8c9f6cde4e421f6dd95569eae19d35ae8f9d34b7eda92fbf7d84307ca1b684e800aec4
|
data/Rakefile
CHANGED
|
@@ -3,6 +3,17 @@ require "rspec/core/rake_task"
|
|
|
3
3
|
require "rubocop/rake_task"
|
|
4
4
|
|
|
5
5
|
RSpec::Core::RakeTask.new(:spec)
|
|
6
|
+
|
|
7
|
+
# The client against the real inference gateway, with nothing stubbed. Billable, so not part of the
|
|
8
|
+
# default task; needs NIP_E2E_INFERENCE_API_KEY and the Cerebro project's
|
|
9
|
+
# NIP_E2E_OBSERVABILITY_PROJECT_ID, NIP_E2E_OBSERVABILITY_PUBLIC_KEY and
|
|
10
|
+
# NIP_E2E_OBSERVABILITY_SECRET_KEY, and takes NIP_E2E_INFERENCE_BASE_URL to aim at a gateway other
|
|
11
|
+
# than the shared one.
|
|
12
|
+
desc "Run the end-to-end specs against the real inference gateway"
|
|
13
|
+
RSpec::Core::RakeTask.new(:e2e) do |task|
|
|
14
|
+
task.pattern = "spec/e2e/**/*_spec.rb"
|
|
15
|
+
task.rspec_opts = "--tag e2e"
|
|
16
|
+
end
|
|
6
17
|
RuboCop::RakeTask.new
|
|
7
18
|
|
|
8
19
|
# The public API is everything `.yardopts` does not hide as `@api private`, and every part of it
|
data/docs/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,19 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [4.4.0](https://github.com/powerhome/nitro-intelligence.rb/compare/v4.3.2...v4.4.0) (2026-12-02)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
* **embeddings:** take a per-request instruction on embed_query ([#241](https://github.com/powerhome/nitro-intelligence.rb/issues/241)) ([dadc251](https://github.com/powerhome/nitro-intelligence.rb/commit/dadc251ea2e0b58b48fe4ed4378fd9787e29474a))
|
|
14
|
+
* **models:** take models the app does not list from the gateway's model info ([#223](https://github.com/powerhome/nitro-intelligence.rb/issues/223)) ([25a4a11](https://github.com/powerhome/nitro-intelligence.rb/commit/25a4a11cb4d3bc9c40dba0f15702fed2dcc0e5ad))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
* **deps:** allow openai 0.86 through 1.x ([#267](https://github.com/powerhome/nitro-intelligence.rb/issues/267)) ([cdce0c2](https://github.com/powerhome/nitro-intelligence.rb/commit/cdce0c2b586d1c467e7701bf4d3325716f483f7d))
|
|
20
|
+
|
|
8
21
|
## [4.3.2](https://github.com/powerhome/nitro-intelligence.rb/compare/v4.3.1...v4.3.2) (2026-11-23)
|
|
9
22
|
|
|
10
23
|
|
data/docs/README.md
CHANGED
|
@@ -52,48 +52,10 @@ NitroIntelligence.configure do |config|
|
|
|
52
52
|
"default_audio_transcription_model" => "Qwen/Qwen3-ASR-1.7B",
|
|
53
53
|
"default_text_model" => "Qwen/Qwen3.6-35B-A3B",
|
|
54
54
|
"default_image_model" => "google/gemini-3.1-flash-image",
|
|
55
|
-
"default_text_to_speech_model" => "
|
|
55
|
+
"default_text_to_speech_model" => "google/gemini-3.8-flash-tts",
|
|
56
56
|
"default_decision_model" => "typesafe/jev-1.14",
|
|
57
57
|
"default_embedding_model" => "Qwen/Qwen3-Embedding-0.6B",
|
|
58
58
|
"default_rerank_model" => "Qwen/Qwen3-Reranker-0.6B",
|
|
59
|
-
"models" => [
|
|
60
|
-
{
|
|
61
|
-
"name" => "Qwen/Qwen3.6-35B-A3B",
|
|
62
|
-
"type" => "text"
|
|
63
|
-
},
|
|
64
|
-
{
|
|
65
|
-
"name" => "Qwen/Qwen3-ASR-1.7B",
|
|
66
|
-
"type" => "audio_transcription"
|
|
67
|
-
},
|
|
68
|
-
{
|
|
69
|
-
"name" => "google/gemini-3.1-flash-image",
|
|
70
|
-
"type" => "image",
|
|
71
|
-
"aspect_ratios" => ["1:1", "2:3", "3:2", "3:4", "4:3", "9:16", "16:9"],
|
|
72
|
-
"resolutions" => ["512", "1K", "2K"],
|
|
73
|
-
"omit_output_fields" => ["provider_specific_fields.thought_signatures"]
|
|
74
|
-
},
|
|
75
|
-
{
|
|
76
|
-
"name" => "openai/gpt-4o-mini-tts",
|
|
77
|
-
"type" => "text_to_speech",
|
|
78
|
-
"default_voice" => "marin",
|
|
79
|
-
"default_response_format" => "mp3",
|
|
80
|
-
"voices" => ["echo", "nova", "marin", "cedar"],
|
|
81
|
-
"response_formats" => ["mp3", "wav"]
|
|
82
|
-
},
|
|
83
|
-
{
|
|
84
|
-
"name" => "typesafe/jev-1.14",
|
|
85
|
-
"type" => "decision"
|
|
86
|
-
},
|
|
87
|
-
{
|
|
88
|
-
"name" => "Qwen/Qwen3-Embedding-0.6B",
|
|
89
|
-
"type" => "embedding",
|
|
90
|
-
"query_prefix" => "Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery:"
|
|
91
|
-
},
|
|
92
|
-
{
|
|
93
|
-
"name" => "Qwen/Qwen3-Reranker-0.6B",
|
|
94
|
-
"type" => "rerank"
|
|
95
|
-
}
|
|
96
|
-
]
|
|
97
59
|
}
|
|
98
60
|
end
|
|
99
61
|
```
|
|
@@ -114,7 +76,13 @@ end
|
|
|
114
76
|
| `observability_projects` | `Array<Hash>` | `[]` | Langfuse project credentials (slug, id, public_key, secret_key). Add `"mask_content" => true` to keep a project's prompts and responses out of Cerebro and the gateway logs, see [Masking Content](#masking-content) |
|
|
115
77
|
| `observability_user_id` | `String` | `""` | User ID recorded on observed traces when a request passes no `user_id` parameter — see [Users](#users) |
|
|
116
78
|
| `assistants_config` | `Hash` | `{}` | Assistants to make addressable by key. `base_url` (String, default: `"https://assistants.powerhome.ai"`) and `user_id` (String, default: `"default-user"`) are shared by every entry; `definitions` (Hash) holds one entry per assistant, keyed by what it is looked up with, each able to override a shared value. Without `definitions` the hash is read as credentials for a single `Assistants.new`, which takes the same two defaults — see [Assistants](#assistants) |
|
|
117
|
-
| `model_config` | `Hash` | `{}` |
|
|
79
|
+
| `model_config` | `Hash` | `{}` | The model each kind of request uses when it names none: `default_text_model`, `default_audio_transcription_model`, `default_image_model`, `default_text_to_speech_model`, `default_decision_model`, `default_embedding_model` and `default_rerank_model`. The models themselves, and their settings, come from the gateway — see [Models](#models) |
|
|
80
|
+
|
|
81
|
+
### Models
|
|
82
|
+
|
|
83
|
+
The gateway decides which models a request may name and how the client uses them. The first time a request names a model, the client fetches the gateway's model list (`GET /model/info`) for `inference_api_key`, which holds every model the key can reach. It takes each model's type from its `mode` (chat, image generation, audio transcription, speech, embedding, rerank or decision) and its settings from `model_info.nitro_intelligence`: an image model's aspect ratios and resolutions, a text-to-speech model's voices and formats and their defaults, an embedding model's query instruction template and query and document prefixes, and the output fields left out of traces. Configure nothing about a model beyond choosing the defaults in `model_config`.
|
|
84
|
+
|
|
85
|
+
The client keeps the list and fetches it again, at most every five minutes, when a request names a model that is not in it, so a model added to the gateway becomes usable without a restart. If the gateway cannot list its models, the client logs a warning and raises `ArgumentError` naming the model and the listing error, then asks again ten seconds later. A model whose settings the gateway does not publish, such as an image model with no aspect ratios or a text-to-speech model with no default voice, is unsupported until it does. Without an `inference_api_key` no model is available.
|
|
118
86
|
|
|
119
87
|
## Basic Usage
|
|
120
88
|
|
|
@@ -208,7 +176,7 @@ client = NitroIntelligence::Client.new
|
|
|
208
176
|
tts = client.text_to_speech(message: 'Hello, this is Power Home Remodeling Group.')
|
|
209
177
|
|
|
210
178
|
# tts is a StringIO object, we can write the file to disk
|
|
211
|
-
File.binwrite('tts.
|
|
179
|
+
File.binwrite('tts.wav', tts.string)
|
|
212
180
|
```
|
|
213
181
|
|
|
214
182
|
Supplying custom parameters:
|
|
@@ -218,18 +186,18 @@ client = NitroIntelligence::Client.new
|
|
|
218
186
|
tts = client.text_to_speech(
|
|
219
187
|
message: 'Hello, this is Power Home Remodeling Group.',
|
|
220
188
|
parameters: {
|
|
221
|
-
voice: '
|
|
222
|
-
response_format: '
|
|
189
|
+
voice: 'Kore',
|
|
190
|
+
response_format: 'wav',
|
|
223
191
|
instructions: 'Translate the English into Spanish before speaking.',
|
|
224
192
|
speed: 1.25
|
|
225
193
|
}
|
|
226
194
|
)
|
|
227
195
|
|
|
228
196
|
# tts is a StringIO object, we can write the file to disk
|
|
229
|
-
File.binwrite('tts.
|
|
197
|
+
File.binwrite('tts.wav', tts.string)
|
|
230
198
|
```
|
|
231
199
|
|
|
232
|
-
For a full list of supported parameters, see the [API reference here](https://developers.openai.com/api/reference/resources/audio/subresources/speech/methods/create ). Note that `voice` and `response_format` are further constrained to the
|
|
200
|
+
For a full list of supported parameters, see the [API reference here](https://developers.openai.com/api/reference/resources/audio/subresources/speech/methods/create ). Note that `voice` and `response_format` are further constrained to the voices and formats the gateway publishes for the chosen model, and default to the ones it marks as defaults.
|
|
233
201
|
|
|
234
202
|
### Decisions
|
|
235
203
|
|
|
@@ -269,7 +237,7 @@ decision.answers[:urgency].probabilities # => {0 => 0.1, 1 => 0.1, 2 => 0.8}
|
|
|
269
237
|
|
|
270
238
|
`answers` is keyed by question name and accepts strings or symbols. Each answer is a `NitroIntelligence::Decision::NoulAnswer`, `ChoiceAnswer` or `ScoreAnswer`; an answer of any other type is returned as the gateway sent it. `decision.usage` holds the token counts, also by string or symbol, and `decision.last_response` the HTTP response, including the gateway's headers.
|
|
271
239
|
|
|
272
|
-
The model defaults to `default_decision_model` and must be
|
|
240
|
+
The model defaults to `default_decision_model` and must be a decision model, one the gateway serves with mode `evaluation`. `parameters` takes `model`, `assets` (images that `state` and the questions refer to, see the [System One docs](https://docs.typesafe.ai/api/system-one.md); the gateway refuses assets for a model it reaches through OpenRouter, which includes `typesafe/jev-1.14`), `metadata`, `request_options` and, with observability, `trace_name`, `trace_seed`, `user_id`, `session_id` and `tags`, described under [Observability](#observability). Decisions take no managed prompt: `prompt_name` and `prompt_variables` are ignored, so put the instructions in `questions`. With observability enabled, each call is recorded in Cerebro as a generation with the state and questions as input, the answers as output, and the gateway's cost.
|
|
273
241
|
|
|
274
242
|
The client does not limit the request. To keep a feature portable to models NIP hosts itself, stay within the gateway's [portable subset](https://github.com/powerhome/nitro-intelligence/blob/main/docs/inference-gateway.md#stay-within-what-every-backend-supports): up to 64 questions, 26 options per `choice` question and 10 levels per `score` question, with text `state`.
|
|
275
243
|
|
|
@@ -284,18 +252,24 @@ Many embeddings models are trained to embed a search query differently from the
|
|
|
284
252
|
embeddings = client.embed_documents(documents: pages.map(&:description), parameters: { dimensions: 512 })
|
|
285
253
|
embeddings.vectors # => [[0.012, -0.034, ...], ...], one per page
|
|
286
254
|
|
|
287
|
-
# A query to search them with
|
|
288
|
-
client.embed_query(
|
|
255
|
+
# A query to search them with, and what the search is for
|
|
256
|
+
client.embed_query(
|
|
257
|
+
query: "How do I request time off?",
|
|
258
|
+
instruction: "Given an employee question, retrieve the HR policy that answers it",
|
|
259
|
+
parameters: { dimensions: 512 }
|
|
260
|
+
).vector # => [0.021, 0.008, ...]
|
|
289
261
|
```
|
|
290
262
|
|
|
291
263
|
`embed_query` also takes a list of queries, such as an evaluation set, and returns a vector for each in `vectors`. `embed_documents` also takes a single document.
|
|
292
264
|
|
|
293
|
-
`parameters` takes `model`, `dimensions`, `batch_size`, `user`, `metadata`, `request_options` and, with observability, `trace_name`, `trace_seed`, `user_id`, `session_id` and `tags`. The model defaults to `default_embedding_model` and must be
|
|
265
|
+
`parameters` takes `model`, `dimensions`, `batch_size`, `user`, `metadata`, `request_options` and, with observability, `trace_name`, `trace_seed`, `user_id`, `session_id` and `tags`. The model defaults to `default_embedding_model` and must be an embedding model, as [Models](#models) describes.
|
|
294
266
|
|
|
295
267
|
* **`dimensions`** shortens the vectors, for a model that supports it, as Qwen3-Embedding does. Embed queries and documents with the same model and the same `dimensions`, or the vectors cannot be compared.
|
|
296
268
|
* **`batch_size`** caps how many inputs go in one request, 128 by default. A longer list is sent in several requests and returned as one result, recorded as one observation, so an index rebuild of a few thousand entries is one call.
|
|
297
269
|
|
|
298
|
-
|
|
270
|
+
Some models are trained to read an instruction before each query, describing the task the embedding is for. Qwen3-Embedding is one, and its [model card](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B) recommends an instruction written for each use case; leaving it out costs a few percent in retrieval. Pass it as `embed_query`'s `instruction`: one sentence saying what the query should find, such as "Given a customer question, retrieve the help article that answers it". The client puts it into the `query_instruction_template` the gateway publishes for the model, at `{instruction}`, before each query; documents take no instruction. A model with no template refuses an instruction with `ArgumentError`. Use the same instruction for queries that perform the same retrieval task.
|
|
271
|
+
|
|
272
|
+
Without an instruction, the client puts the query and document prefixes the gateway publishes for a model before each query's text and each document's, in the form the model was trained on. E5 takes `"query: "` and `"passage: "`; OpenAI's models take neither. Switching to another embeddings model only means changing `default_embedding_model`, but vectors from different models cannot be compared, so it also means embedding your stored documents again.
|
|
299
273
|
|
|
300
274
|
`embeddings.usage` holds `prompt_tokens` and `total_tokens` summed over every request, and `embeddings.responses` the gateway's responses, one per batch, each with its `last_response`. With observability enabled, each call is recorded in Cerebro as an embedding observation named `embed-query` or `embed-documents`, with the input as the model received it, prefix included, the input tokens as usage, the gateway's cost added up over every batch, and the number and size of the vectors as output. The vectors themselves are never recorded. If the gateway did not price every batch, the cost is left unset rather than undercounted. If a batch fails after others succeeded, the failed call still records what those cost before the error is raised.
|
|
301
275
|
|
|
@@ -318,7 +292,7 @@ ranking.results.first.relevance_score # => 0.97, from 0 to 1
|
|
|
318
292
|
candidates.values_at(*ranking.results.map(&:index))
|
|
319
293
|
```
|
|
320
294
|
|
|
321
|
-
`parameters` takes `model`, `top_n` (return only the most relevant this many, a positive integer, applied after sorting even when the provider ignores it), `metadata`, `request_options` and, with observability, `trace_name`, `trace_seed`, `user_id`, `session_id`, `tags` and `trace_documents`. The model defaults to `default_rerank_model` and must be
|
|
295
|
+
`parameters` takes `model`, `top_n` (return only the most relevant this many, a positive integer, applied after sorting even when the provider ignores it), `metadata`, `request_options` and, with observability, `trace_name`, `trace_seed`, `user_id`, `session_id`, `tags` and `trace_documents`. The model defaults to `default_rerank_model` and must be a rerank model, as [Models](#models) describes. `ranking.meta` holds what the provider billed, and `ranking.last_response` the HTTP response, including the gateway's headers.
|
|
322
296
|
|
|
323
297
|
With observability enabled, each call is recorded in Cerebro as a generation, since Langfuse has no reranker type, with the query and documents as input, each document's index and score as output, the input tokens as usage, any search units the provider billed in the metadata, and the gateway's cost. Pass `trace_documents: false` when your own trace already records the candidates, such as an embedding call or a search step in the same trace, and only their number is recorded. Reranking takes no managed prompt: `prompt_name` and `prompt_variables` are ignored.
|
|
324
298
|
|
|
@@ -881,7 +855,7 @@ A request naming a prompt raises when it cannot use one:
|
|
|
881
855
|
| `NitroIntelligence::Client::Handlers::Observed::AudioTranscriptionHandler::ObservedAudioTranscriptionPromptError` | `#transcribe_audio` names a prompt that is not a text prompt |
|
|
882
856
|
| `NitroIntelligence::Client::Handlers::Observed::TextToSpeechHandler::ObservedTextToSpeechPromptError` | `#text_to_speech` names a prompt that is not a text prompt |
|
|
883
857
|
|
|
884
|
-
On an observed client whose project does not mask content, pass an open `File` as `audio_file` to `#transcribe_audio`. If `audio_file` has no path, as with a `StringIO`, the upload to Cerebro raises `NitroIntelligence::Audio::AudioFileFormatError`. By then, the gateway has already transcribed the audio and billed the request, but your app never receives the transcript. A masked project skips the upload, so the same input works there. Every method raises `ArgumentError` for a model, or a model setting such as a voice or aspect ratio
|
|
858
|
+
On an observed client whose project does not mask content, pass an open `File` as `audio_file` to `#transcribe_audio`. If `audio_file` has no path, as with a `StringIO`, the upload to Cerebro raises `NitroIntelligence::Audio::AudioFileFormatError`. By then, the gateway has already transcribed the audio and billed the request, but your app never receives the transcript. A masked project skips the upload, so the same input works there. Every method raises `ArgumentError` for a model the gateway does not provide, or a model setting such as a voice or aspect ratio that the gateway does not list for the model.
|
|
885
859
|
|
|
886
860
|
## Nitro Intelligence Assistants
|
|
887
861
|
|
|
@@ -31,7 +31,7 @@ module NitroIntelligence
|
|
|
31
31
|
# @param message [String] the user's message, used when `parameters` carries no `messages`
|
|
32
32
|
# @param parameters [Hash] openai-ruby's chat completion parameters, and this gem's own
|
|
33
33
|
# @return [OpenAI::Models::Chat::ChatCompletion]
|
|
34
|
-
# @raise [ArgumentError] when the model is not one
|
|
34
|
+
# @raise [ArgumentError] when the model is not one the gateway serves
|
|
35
35
|
# @raise [Handlers::Observed::ChatHandler::ObservedChatPromptError] on an observed client, when
|
|
36
36
|
# the request carries no user message for the model to answer
|
|
37
37
|
# @example
|
|
@@ -52,7 +52,7 @@ module NitroIntelligence
|
|
|
52
52
|
# `user_id`, `session_id` and `tags`. It takes no managed prompt: `prompt_name` and
|
|
53
53
|
# `prompt_variables` are ignored, so the instructions belong in `questions`.
|
|
54
54
|
# @return [Decision]
|
|
55
|
-
# @raise [ArgumentError] when the model is not one
|
|
55
|
+
# @raise [ArgumentError] when the model is not one the gateway serves with the type
|
|
56
56
|
# `decision`
|
|
57
57
|
# @example
|
|
58
58
|
# client.decide(
|
|
@@ -67,16 +67,29 @@ module NitroIntelligence
|
|
|
67
67
|
# with vectors from {#embed_documents}.
|
|
68
68
|
#
|
|
69
69
|
# @param query [String, Array<String>] the query, or several, such as an evaluation set
|
|
70
|
+
# @param instruction [String, nil] one sentence describing what the query's embedding is for,
|
|
71
|
+
# for a model trained on task instructions, such as Qwen3-Embedding. It goes into the
|
|
72
|
+
# model's `query_instruction_template` before each query; documents take none. Write it for
|
|
73
|
+
# your use case, such as "Given a customer question, retrieve the help article that answers
|
|
74
|
+
# it". Nil sends each query with the model's plain `query_prefix`, if it has one.
|
|
70
75
|
# @param parameters [Hash] `model`, `dimensions` (a shorter vector, for a model that supports
|
|
71
76
|
# one), `batch_size` (at most this many texts per request, 128 by default), `user`,
|
|
72
77
|
# `metadata` and `request_options`, and on an observed client `trace_name`, `trace_seed`,
|
|
73
78
|
# `user_id`, `session_id` and `tags`. It takes no managed prompt.
|
|
74
79
|
# @return [Embeddings] the query's vector in `vector`, or one per query in `vectors`
|
|
75
|
-
# @raise [ArgumentError] when the model is not one
|
|
76
|
-
# `embedding`, a query is empty or not text,
|
|
80
|
+
# @raise [ArgumentError] when the model is not one the gateway serves with the type
|
|
81
|
+
# `embedding`, a query is empty or not text, `batch_size` is not a positive integer, or
|
|
82
|
+
# `instruction` is given for a model with no `query_instruction_template` or is not a
|
|
83
|
+
# non-empty string
|
|
77
84
|
# @example
|
|
78
85
|
# client.embed_query(query: "How do I request time off?").vector
|
|
79
|
-
|
|
86
|
+
# @example With an instruction for the task
|
|
87
|
+
# client.embed_query(
|
|
88
|
+
# query: "How do I request time off?",
|
|
89
|
+
# instruction: "Given an employee question, retrieve the HR policy that answers it"
|
|
90
|
+
# ).vector
|
|
91
|
+
def embed_query(query:, instruction: nil, parameters: {})
|
|
92
|
+
parameters = parameters.merge(instruction:) unless instruction.nil?
|
|
80
93
|
embedding_handler.create(input: query, input_type: :query, parameters: parameters.dup)
|
|
81
94
|
end
|
|
82
95
|
|
|
@@ -104,7 +117,7 @@ module NitroIntelligence
|
|
|
104
117
|
# documents there were, for a caller whose own trace already records them). It takes no
|
|
105
118
|
# managed prompt.
|
|
106
119
|
# @return [Ranking]
|
|
107
|
-
# @raise [ArgumentError] when the model is not one
|
|
120
|
+
# @raise [ArgumentError] when the model is not one the gateway serves with the type
|
|
108
121
|
# `rerank`, the query is empty, the documents are empty or not text, or `top_n` is not a
|
|
109
122
|
# positive integer
|
|
110
123
|
# @example
|
|
@@ -143,10 +156,10 @@ module NitroIntelligence
|
|
|
143
156
|
# @param message [String] what to generate, or how to edit the target
|
|
144
157
|
# @param target_image [String, nil] the image to edit, as a byte string
|
|
145
158
|
# @param reference_images [Array<String>] further images to draw on, as byte strings
|
|
146
|
-
# @param parameters [Hash] `model`, `aspect_ratio` and `resolution`, among those
|
|
159
|
+
# @param parameters [Hash] `model`, `aspect_ratio` and `resolution`, among those the gateway
|
|
147
160
|
# lists for the model, and this gem's own
|
|
148
161
|
# @return [ImageGeneration]
|
|
149
|
-
# @raise [ArgumentError] when the model, aspect ratio or resolution is not one
|
|
162
|
+
# @raise [ArgumentError] when the model, aspect ratio or resolution is not one the gateway
|
|
150
163
|
# lists
|
|
151
164
|
# @example
|
|
152
165
|
# result = client.generate_image(message: "A bear installing a window")
|
|
@@ -166,7 +179,7 @@ module NitroIntelligence
|
|
|
166
179
|
# the `response_format`: a `Transcription` for `json`, the default, and the response body as a
|
|
167
180
|
# StringIO for `text`, `srt` and `vtt`. An observed client records the transcription's `text`,
|
|
168
181
|
# so it supports only the formats that return an object.
|
|
169
|
-
# @raise [ArgumentError] when the model is not one
|
|
182
|
+
# @raise [ArgumentError] when the model is not one the gateway serves
|
|
170
183
|
# @example
|
|
171
184
|
# client.transcribe_audio(audio_file: File.open("sample.m4a", "rb")).text
|
|
172
185
|
def transcribe_audio(message: +"", audio_file: nil, parameters: {})
|
|
@@ -177,9 +190,9 @@ module NitroIntelligence
|
|
|
177
190
|
#
|
|
178
191
|
# @param message [String] the text to speak
|
|
179
192
|
# @param parameters [Hash] openai-ruby's speech parameters, with `voice` and `response_format`
|
|
180
|
-
# among those
|
|
193
|
+
# among those the gateway lists for the model, and this gem's own
|
|
181
194
|
# @return [StringIO] the audio
|
|
182
|
-
# @raise [ArgumentError] when the model, voice or format is not one
|
|
195
|
+
# @raise [ArgumentError] when the model, voice or format is not one the gateway lists
|
|
183
196
|
# @example
|
|
184
197
|
# File.binwrite("hello.mp3", client.text_to_speech(message: "Hello").string)
|
|
185
198
|
def text_to_speech(message: "", parameters: {})
|
|
@@ -25,7 +25,7 @@ module NitroIntelligence
|
|
|
25
25
|
def validate_and_resolve!(parameters)
|
|
26
26
|
default_parameters = {
|
|
27
27
|
metadata: {},
|
|
28
|
-
model: NitroIntelligence.model_catalog.
|
|
28
|
+
model: NitroIntelligence.model_catalog.default_audio_transcription_model_name,
|
|
29
29
|
}
|
|
30
30
|
|
|
31
31
|
parameters.replace(default_parameters.merge(parameters))
|
|
@@ -27,7 +27,7 @@ module NitroIntelligence
|
|
|
27
27
|
default_parameters = {
|
|
28
28
|
metadata: {},
|
|
29
29
|
messages: [],
|
|
30
|
-
model: NitroIntelligence.model_catalog.
|
|
30
|
+
model: NitroIntelligence.model_catalog.default_text_model_name,
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
parameters.replace(default_parameters.merge(parameters))
|
|
@@ -48,7 +48,7 @@ module NitroIntelligence
|
|
|
48
48
|
def validate_and_resolve!(parameters)
|
|
49
49
|
default_parameters = {
|
|
50
50
|
metadata: {},
|
|
51
|
-
model: NitroIntelligence.model_catalog.
|
|
51
|
+
model: NitroIntelligence.model_catalog.default_decision_model_name,
|
|
52
52
|
}
|
|
53
53
|
|
|
54
54
|
parameters.replace(default_parameters.merge(parameters))
|
|
@@ -41,24 +41,30 @@ module NitroIntelligence
|
|
|
41
41
|
def validate_and_resolve!(input, input_type, parameters)
|
|
42
42
|
default_parameters = {
|
|
43
43
|
metadata: {},
|
|
44
|
-
model: NitroIntelligence.model_catalog.
|
|
44
|
+
model: NitroIntelligence.model_catalog.default_embedding_model_name,
|
|
45
45
|
batch_size: DEFAULT_BATCH_SIZE,
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
parameters.replace(default_parameters.merge(parameters))
|
|
49
|
-
Client.validate_model(parameters[:model], type: EmbeddingModel)
|
|
49
|
+
model = Client.validate_model(parameters[:model], type: EmbeddingModel)
|
|
50
50
|
unless INPUT_TYPES.include?(input_type)
|
|
51
51
|
raise ArgumentError, "input_type must be one of #{INPUT_TYPES.inspect}"
|
|
52
52
|
end
|
|
53
53
|
|
|
54
|
+
# Documents take no instruction, so one in a parameters hash shared with queries is ignored.
|
|
55
|
+
if input_type == :query && !parameters[:instruction].nil?
|
|
56
|
+
validate_instruction!(parameters[:instruction], model)
|
|
57
|
+
end
|
|
54
58
|
validate_input!(input)
|
|
55
59
|
validate_batch_size!(parameters[:batch_size])
|
|
56
60
|
end
|
|
57
61
|
|
|
58
62
|
# The texts as the model receives them: each after the model's prefix for queries or for
|
|
59
|
-
# documents, which is empty for a model that embeds both the same way
|
|
63
|
+
# documents, which is empty for a model that embeds both the same way, or after a query's
|
|
64
|
+
# `instruction` in the model's own form for one.
|
|
60
65
|
def texts(input, input_type, parameters)
|
|
61
|
-
|
|
66
|
+
model = Client.validate_model(parameters[:model], type: EmbeddingModel)
|
|
67
|
+
prefix = model.prefix_for(input_type, instruction: parameters[:instruction])
|
|
62
68
|
Array(input).map { |text| "#{prefix}#{text}" }
|
|
63
69
|
end
|
|
64
70
|
|
|
@@ -75,6 +81,15 @@ module NitroIntelligence
|
|
|
75
81
|
|
|
76
82
|
private
|
|
77
83
|
|
|
84
|
+
def validate_instruction!(instruction, model)
|
|
85
|
+
unless instruction.is_a?(String) && instruction.present?
|
|
86
|
+
raise ArgumentError, "instruction must be a non-empty string, not #{instruction.inspect}"
|
|
87
|
+
end
|
|
88
|
+
return if model.query_instruction_template.present?
|
|
89
|
+
|
|
90
|
+
raise ArgumentError, "Model '#{model.name}' takes no query instruction"
|
|
91
|
+
end
|
|
92
|
+
|
|
78
93
|
# Checked before any batch is sent, so a bad entry late in a long list cannot fail the call
|
|
79
94
|
# after the batches before it were billed.
|
|
80
95
|
def validate_input!(input)
|
|
@@ -45,7 +45,7 @@ module NitroIntelligence
|
|
|
45
45
|
def validate_and_resolve!(query, documents, parameters)
|
|
46
46
|
default_parameters = {
|
|
47
47
|
metadata: {},
|
|
48
|
-
model: NitroIntelligence.model_catalog.
|
|
48
|
+
model: NitroIntelligence.model_catalog.default_rerank_model_name,
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
parameters.replace(default_parameters.merge(parameters))
|
|
@@ -22,7 +22,7 @@ module NitroIntelligence
|
|
|
22
22
|
end
|
|
23
23
|
|
|
24
24
|
def validate_and_resolve!(parameters)
|
|
25
|
-
model_name = parameters[:model] || NitroIntelligence.model_catalog.
|
|
25
|
+
model_name = parameters[:model] || NitroIntelligence.model_catalog.default_text_to_speech_model_name
|
|
26
26
|
model = Client.validate_model(model_name, type: TextToSpeechModel)
|
|
27
27
|
|
|
28
28
|
default_parameters = {
|
|
@@ -65,7 +65,7 @@ module NitroIntelligence
|
|
|
65
65
|
record_input(generation, input)
|
|
66
66
|
|
|
67
67
|
result, trace_attributes = observe_failures(generation) { yield(generation) }
|
|
68
|
-
record_result(generation, trace_attributes)
|
|
68
|
+
record_result(generation, trace_attributes, requested_model: model)
|
|
69
69
|
|
|
70
70
|
result
|
|
71
71
|
end
|
|
@@ -78,14 +78,14 @@ module NitroIntelligence
|
|
|
78
78
|
# the gateway omits the header entirely for a deployment it has no price for,
|
|
79
79
|
# and writing a zero there would read as a free request rather than an
|
|
80
80
|
# unpriced one.
|
|
81
|
-
def record_result(generation, trace_attributes)
|
|
81
|
+
def record_result(generation, trace_attributes, requested_model: nil)
|
|
82
82
|
return unless trace_attributes
|
|
83
83
|
|
|
84
84
|
trace_attributes = masked(trace_attributes)
|
|
85
85
|
|
|
86
86
|
# Truncation trims fields out of an output that a masked project does not record.
|
|
87
87
|
unless project.mask_content?
|
|
88
|
-
handle_truncation(trace_attributes[:
|
|
88
|
+
handle_truncation(trace_attributes[:output], requested_model, trace_attributes[:model])
|
|
89
89
|
end
|
|
90
90
|
|
|
91
91
|
RECORDED_ATTRIBUTES.each do |name|
|
|
@@ -184,19 +184,30 @@ module NitroIntelligence
|
|
|
184
184
|
error.headers&.[](LITELLM_CALL_ID_HEADER)
|
|
185
185
|
end
|
|
186
186
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
187
|
+
# Omits the fields of both the model the request named, which the catalog already resolved
|
|
188
|
+
# before sending it, and the model the response names, which a provider may give in a dated
|
|
189
|
+
# form with fields of its own. Neither lookup asks the gateway, so recording a response never
|
|
190
|
+
# blocks or fails on it. A path the output cannot contain, such as any path into a
|
|
191
|
+
# transcript's plain text, is skipped.
|
|
192
|
+
def handle_truncation(output, *model_names)
|
|
193
|
+
catalog = NitroIntelligence.model_catalog
|
|
194
|
+
omit_output_fields = model_names.compact.uniq.flat_map do |name|
|
|
195
|
+
catalog.lookup_by_name(name, discover: false)&.omit_output_fields || []
|
|
196
|
+
end
|
|
191
197
|
|
|
192
|
-
|
|
198
|
+
omit_output_fields.uniq.each do |omit_output_field|
|
|
199
|
+
parent = omit_output_field[0...-1].reduce(output) { |node, key| child(node, key) }
|
|
193
200
|
last_key = omit_output_field.last
|
|
194
|
-
parent_keys = omit_output_field[0...-1]
|
|
195
|
-
parent = parent_keys.empty? ? output : output.dig(*parent_keys)
|
|
196
|
-
|
|
197
201
|
parent[last_key] = "[Truncated...]" if parent.is_a?(Hash) && parent.key?(last_key)
|
|
198
202
|
end
|
|
199
203
|
end
|
|
204
|
+
|
|
205
|
+
def child(node, key)
|
|
206
|
+
case node
|
|
207
|
+
when Hash then node[key]
|
|
208
|
+
when Array then node[key] if key.is_a?(Integer)
|
|
209
|
+
end
|
|
210
|
+
end
|
|
200
211
|
end
|
|
201
212
|
end
|
|
202
213
|
end
|
|
@@ -51,8 +51,9 @@ module NitroIntelligence
|
|
|
51
51
|
# @!attribute [rw] model_config
|
|
52
52
|
# @return [Hash] the default model for each modality (`default_text_model`,
|
|
53
53
|
# `default_audio_transcription_model`, `default_image_model`,
|
|
54
|
-
# `default_text_to_speech_model`
|
|
55
|
-
#
|
|
54
|
+
# `default_text_to_speech_model`, `default_decision_model`, `default_embedding_model`,
|
|
55
|
+
# `default_rerank_model`). The models and their settings come from the gateway. See the
|
|
56
|
+
# README's "Models".
|
|
56
57
|
config_accessor :model_config, default: {}
|
|
57
58
|
# @!attribute [rw] observability_base_url
|
|
58
59
|
# @return [String] Cerebro's base URL. Defaults to the shared deployment.
|
|
@@ -18,7 +18,7 @@ module NitroIntelligence
|
|
|
18
18
|
|
|
19
19
|
def initialize
|
|
20
20
|
@aspect_ratio = DEFAULT_ASPECT_RATIO
|
|
21
|
-
@model = NitroIntelligence.model_catalog.
|
|
21
|
+
@model = NitroIntelligence.model_catalog.default_image_model_name
|
|
22
22
|
@resolution = DEFAULT_RESOLUTION
|
|
23
23
|
end
|
|
24
24
|
end
|
|
@@ -41,7 +41,6 @@ module NitroIntelligence
|
|
|
41
41
|
)
|
|
42
42
|
@config = Config.new
|
|
43
43
|
@generated_image = nil
|
|
44
|
-
@model = NitroIntelligence.model_catalog.lookup_by_name(@config.model)
|
|
45
44
|
@reference_images = reference_images.map { |img| Image.new(img) }
|
|
46
45
|
@trace_id = nil
|
|
47
46
|
@observation_id = nil
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
require "net/http"
|
|
3
|
+
require "uri"
|
|
4
|
+
|
|
5
|
+
module NitroIntelligence
|
|
6
|
+
# The models the inference gateway serves to the configured key, as its `GET /model/info`
|
|
7
|
+
# describes them. The gateway gives each model's `mode`, which decides its type, and publishes
|
|
8
|
+
# what the client needs beyond that, such as an image model's aspect ratios, under
|
|
9
|
+
# `model_info.nitro_intelligence`, the same on every deployment of a model group.
|
|
10
|
+
#
|
|
11
|
+
# @api private
|
|
12
|
+
class GatewayModels
|
|
13
|
+
# Raised when the gateway does not answer with its model list.
|
|
14
|
+
class Error < StandardError; end
|
|
15
|
+
|
|
16
|
+
# The model type for each LiteLLM mode the client has a handler for. Models of any other mode
|
|
17
|
+
# are left out.
|
|
18
|
+
TYPES = {
|
|
19
|
+
"chat" => "text",
|
|
20
|
+
"audio_transcription" => "audio_transcription",
|
|
21
|
+
"audio_speech" => "text_to_speech",
|
|
22
|
+
"embedding" => "embedding",
|
|
23
|
+
"evaluation" => "decision",
|
|
24
|
+
"image_generation" => "image",
|
|
25
|
+
"rerank" => "rerank",
|
|
26
|
+
}.freeze
|
|
27
|
+
SETTINGS_KEY = "nitro_intelligence".freeze
|
|
28
|
+
TIMEOUT = 5
|
|
29
|
+
|
|
30
|
+
# @return [GatewayModels, nil] nil when there is no API key to ask the gateway with
|
|
31
|
+
def self.from_config(config)
|
|
32
|
+
return if config.inference_api_key.blank? || config.inference_base_url.blank?
|
|
33
|
+
|
|
34
|
+
new(base_url: config.inference_base_url, api_key: config.inference_api_key)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def initialize(base_url:, api_key:)
|
|
38
|
+
@uri = URI("#{base_url.to_s.chomp('/')}/model/info")
|
|
39
|
+
@api_key = api_key
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# @return [Array<Hash>] one entry per readable deployment, in the gateway's order, as
|
|
43
|
+
# {ModelFactory.build} takes it
|
|
44
|
+
# @raise [Error] when the gateway answers with anything but its model list
|
|
45
|
+
def fetch
|
|
46
|
+
response = Net::HTTP.start(@uri.host, @uri.port, use_ssl: @uri.scheme == "https",
|
|
47
|
+
open_timeout: TIMEOUT, read_timeout: TIMEOUT) do |http|
|
|
48
|
+
request = Net::HTTP::Get.new(@uri)
|
|
49
|
+
request["Authorization"] = "Bearer #{@api_key}"
|
|
50
|
+
http.request(request)
|
|
51
|
+
end
|
|
52
|
+
unless response.is_a?(Net::HTTPSuccess)
|
|
53
|
+
raise Error, "#{response.code} listing models: #{response.body.to_s.truncate(200)}"
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
parse(JSON.parse(response.body))
|
|
57
|
+
rescue JSON::ParserError => e
|
|
58
|
+
raise Error, "Unreadable model list: #{e.message}"
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
private
|
|
62
|
+
|
|
63
|
+
# The gateway lists every deployment of a group, in the order it tries them; the catalog keeps
|
|
64
|
+
# the first it can build. A setting published as null is treated as not published, so the model
|
|
65
|
+
# takes its default. A deployment whose entry, `model_info` or settings are not objects is left
|
|
66
|
+
# out, and the other models stay usable.
|
|
67
|
+
def parse(payload)
|
|
68
|
+
data = payload["data"] if payload.is_a?(Hash)
|
|
69
|
+
raise Error, "Unreadable model list: no data array" unless data.is_a?(Array)
|
|
70
|
+
|
|
71
|
+
data.grep(Hash).filter_map { |deployment| parse_deployment(deployment) }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def parse_deployment(deployment)
|
|
75
|
+
model_info = deployment["model_info"] || {}
|
|
76
|
+
settings = model_info[SETTINGS_KEY] || {} if model_info.is_a?(Hash)
|
|
77
|
+
unless settings.is_a?(Hash)
|
|
78
|
+
NitroIntelligence.logger.debug("Leaving out gateway model #{deployment['model_name']}: malformed model_info")
|
|
79
|
+
return
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
settings = settings.compact
|
|
83
|
+
type = settings["type"] || TYPES[model_info["mode"]]
|
|
84
|
+
settings.merge("name" => deployment["model_name"], "type" => type) if type
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
@@ -30,19 +30,36 @@ module NitroIntelligence
|
|
|
30
30
|
|
|
31
31
|
# @api private
|
|
32
32
|
class EmbeddingModel < Model
|
|
33
|
+
INSTRUCTION_PLACEHOLDER = "{instruction}".freeze
|
|
34
|
+
|
|
33
35
|
# What the model expects before a query's text and before a document's, for a model trained
|
|
34
36
|
# to embed the two differently. Empty for a model that embeds both the same way.
|
|
35
37
|
attr_reader :query_prefix, :document_prefix
|
|
38
|
+
# The model's form for a query that carries an instruction describing the task, with
|
|
39
|
+
# `{instruction}` where the instruction goes, such as Qwen3-Embedding's
|
|
40
|
+
# `"Instruct: {instruction}\nQuery:"`. Empty for a model that takes no instruction.
|
|
41
|
+
attr_reader :query_instruction_template
|
|
36
42
|
|
|
37
|
-
def initialize(
|
|
43
|
+
def initialize(
|
|
44
|
+
name:, omit_output_fields: [], query_prefix: "", document_prefix: "", query_instruction_template: "", **
|
|
45
|
+
)
|
|
38
46
|
super
|
|
39
47
|
@query_prefix = query_prefix.to_s
|
|
40
48
|
@document_prefix = document_prefix.to_s
|
|
49
|
+
@query_instruction_template = query_instruction_template.to_s
|
|
50
|
+
return if @query_instruction_template.empty? || @query_instruction_template.include?(INSTRUCTION_PLACEHOLDER)
|
|
51
|
+
|
|
52
|
+
raise ArgumentError, "query_instruction_template for #{name} has no #{INSTRUCTION_PLACEHOLDER}"
|
|
41
53
|
end
|
|
42
54
|
|
|
43
55
|
# @param input_type [Symbol] `:query` or `:document`
|
|
44
|
-
|
|
45
|
-
|
|
56
|
+
# @param instruction [String, nil] the task a query's embedding is for, in the model's own
|
|
57
|
+
# instruction form; nil for the model's plain query prefix
|
|
58
|
+
def prefix_for(input_type, instruction: nil)
|
|
59
|
+
return document_prefix unless input_type == :query
|
|
60
|
+
return query_prefix if instruction.nil?
|
|
61
|
+
|
|
62
|
+
query_instruction_template.gsub(INSTRUCTION_PLACEHOLDER) { instruction }
|
|
46
63
|
end
|
|
47
64
|
end
|
|
48
65
|
|
|
@@ -1,31 +1,69 @@
|
|
|
1
|
+
require "nitro_intelligence/models/gateway_models"
|
|
1
2
|
require "nitro_intelligence/models/model_factory"
|
|
2
3
|
|
|
3
4
|
module NitroIntelligence
|
|
5
|
+
# The models a request may name: those `model_config` lists under `models`, and every other model
|
|
6
|
+
# the gateway serves to the configured key. A model `models` lists is used exactly as listed,
|
|
7
|
+
# without asking the gateway. Any other name is looked up in the gateway's model list, fetched on
|
|
8
|
+
# the first such lookup and again, at most every {REFRESH_INTERVAL} seconds, when a name is not in
|
|
9
|
+
# it. After a failed listing, any use of the list asks again once {RETRY_INTERVAL} seconds have
|
|
10
|
+
# passed.
|
|
11
|
+
#
|
|
4
12
|
# @api private
|
|
5
13
|
class ModelCatalog
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
14
|
+
DEFAULTS = %i[
|
|
15
|
+
default_audio_transcription_model
|
|
16
|
+
default_decision_model
|
|
17
|
+
default_embedding_model
|
|
18
|
+
default_image_model
|
|
19
|
+
default_rerank_model
|
|
20
|
+
default_text_model
|
|
21
|
+
default_text_to_speech_model
|
|
22
|
+
].freeze
|
|
23
|
+
REFRESH_INTERVAL = 300
|
|
24
|
+
# How long to wait before asking again after the gateway failed to list its models.
|
|
25
|
+
RETRY_INTERVAL = 10
|
|
26
|
+
|
|
27
|
+
DEFAULTS.each do |default|
|
|
28
|
+
define_method(default) { lookup_by_name(@model_config[default]) }
|
|
29
|
+
# The name `model_config` gives, whether or not a model by that name is available, so that a
|
|
30
|
+
# request for the default names it when it is not.
|
|
31
|
+
define_method(:"#{default}_name") { @model_config[default].presence }
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# @param model_config [Hash] as {Configuration#model_config} takes it
|
|
35
|
+
# @param gateway_models [GatewayModels, nil] where to find models `model_config` does not list;
|
|
36
|
+
# nil to use only those it lists
|
|
37
|
+
def initialize(model_config, gateway_models = nil)
|
|
38
|
+
@model_config = model_config.symbolize_keys
|
|
39
|
+
@configured_models = (@model_config[:models] || []).map { |model_metadata| ModelFactory.build(model_metadata) }
|
|
40
|
+
@gateway_models = gateway_models
|
|
41
|
+
@discovered_models = []
|
|
42
|
+
@next_discovery_at = nil
|
|
43
|
+
@discovery_error = nil
|
|
44
|
+
@listed = false
|
|
45
|
+
@discovering = false
|
|
46
|
+
@mutex = Mutex.new
|
|
47
|
+
@discovered = ConditionVariable.new
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Every model, including what the gateway serves, which this may ask it for.
|
|
51
|
+
def models
|
|
52
|
+
configured_names = @configured_models.map(&:name)
|
|
53
|
+
@configured_models + discovered_models.reject { |model| configured_names.include?(model.name) }
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# @param discover [Boolean] false to look only at the configured models and the gateway's list
|
|
57
|
+
# as last fetched, never asking the gateway, for a lookup that must not block or fail on it
|
|
58
|
+
def lookup_by_name(name, discover: true)
|
|
59
|
+
return if name.blank?
|
|
60
|
+
|
|
61
|
+
found = @configured_models.find { |model| model.name == name }
|
|
62
|
+
return found if found || !@gateway_models
|
|
63
|
+
return @mutex.synchronize { @discovered_models }.find { |model| model.name == name } unless discover
|
|
64
|
+
|
|
65
|
+
discovered_models.find { |model| model.name == name } ||
|
|
66
|
+
discovered_models(refresh: true).find { |model| model.name == name }
|
|
29
67
|
end
|
|
30
68
|
|
|
31
69
|
# The named model, checked to be of the type a request needs. A model of another type
|
|
@@ -33,7 +71,7 @@ module NitroIntelligence
|
|
|
33
71
|
# does not say why.
|
|
34
72
|
def fetch(name, type: Model)
|
|
35
73
|
model = lookup_by_name(name)
|
|
36
|
-
raise ArgumentError,
|
|
74
|
+
raise ArgumentError, unsupported_message(name) unless model
|
|
37
75
|
|
|
38
76
|
return model if model.is_a?(type)
|
|
39
77
|
|
|
@@ -46,5 +84,81 @@ module NitroIntelligence
|
|
|
46
84
|
def exists?(name)
|
|
47
85
|
lookup_by_name(name).present?
|
|
48
86
|
end
|
|
87
|
+
|
|
88
|
+
private
|
|
89
|
+
|
|
90
|
+
def unsupported_message(name)
|
|
91
|
+
message = "Unsupported model: '#{name}'"
|
|
92
|
+
return message unless @discovery_error
|
|
93
|
+
|
|
94
|
+
"#{message} (the last attempt to list the inference gateway's models failed: #{@discovery_error})"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# The gateway's models, asking it for them the first time, and again when `refresh` is set and
|
|
98
|
+
# the last answer is old enough. One thread asks at a time, without holding the lock while it
|
|
99
|
+
# waits on the gateway. Another thread keeps using the list it has meanwhile; only one with no
|
|
100
|
+
# list yet waits for the answer, which it needs as much as the thread asking.
|
|
101
|
+
def discovered_models(refresh: false)
|
|
102
|
+
return [] unless @gateway_models
|
|
103
|
+
|
|
104
|
+
ask = @mutex.synchronize do
|
|
105
|
+
@discovered.wait(@mutex) while @discovering && !@listed
|
|
106
|
+
next false if @discovering || !discovery_due?(refresh)
|
|
107
|
+
|
|
108
|
+
@discovering = true
|
|
109
|
+
end
|
|
110
|
+
discover if ask
|
|
111
|
+
@mutex.synchronize { @discovered_models }
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def discovery_due?(refresh)
|
|
115
|
+
@next_discovery_at.nil? || ((refresh || @discovery_error) && now >= @next_discovery_at)
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def discover
|
|
119
|
+
# A group's deployments share their settings, so the first that builds stands for the group,
|
|
120
|
+
# and one published incompletely does not hide another that is usable.
|
|
121
|
+
models = @gateway_models.fetch.filter_map { |model_metadata| build_discovered(model_metadata) }.uniq(&:name)
|
|
122
|
+
@mutex.synchronize do
|
|
123
|
+
@discovered_models = models
|
|
124
|
+
@listed = true
|
|
125
|
+
@next_discovery_at = now + REFRESH_INTERVAL
|
|
126
|
+
@discovery_error = nil
|
|
127
|
+
end
|
|
128
|
+
rescue => e
|
|
129
|
+
# A gateway that cannot list its models cannot serve them either, so this only decides which
|
|
130
|
+
# error a request sees: "Unsupported model" now, or the gateway's own on the request.
|
|
131
|
+
error = "#{e.class}: #{e.message}"
|
|
132
|
+
NitroIntelligence.logger.warn("Could not list the inference gateway's models: #{error}")
|
|
133
|
+
@mutex.synchronize do
|
|
134
|
+
@discovery_error = error
|
|
135
|
+
@next_discovery_at = now + RETRY_INTERVAL
|
|
136
|
+
end
|
|
137
|
+
ensure
|
|
138
|
+
@mutex.synchronize do
|
|
139
|
+
@discovering = false
|
|
140
|
+
@discovered.broadcast
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
# A model the gateway does not publish enough about to use is left out, as if the gateway did
|
|
145
|
+
# not serve it: a text-to-speech model with no default voice, which cannot be built, an image
|
|
146
|
+
# model with no aspect ratios or resolutions, which would refuse every request, or a model whose
|
|
147
|
+
# settings are malformed. The other models stay usable.
|
|
148
|
+
def build_discovered(model_metadata)
|
|
149
|
+
model = ModelFactory.build(model_metadata)
|
|
150
|
+
if model.is_a?(ImageModel) && (model.aspect_ratios.blank? || model.resolutions.blank?)
|
|
151
|
+
raise ArgumentError, "no aspect_ratios or resolutions"
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
model
|
|
155
|
+
rescue => e
|
|
156
|
+
NitroIntelligence.logger.debug("Leaving out gateway model #{model_metadata['name']}: #{e.message}")
|
|
157
|
+
nil
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def now
|
|
161
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
162
|
+
end
|
|
49
163
|
end
|
|
50
164
|
end
|
data/lib/nitro_intelligence.rb
CHANGED
|
@@ -76,7 +76,7 @@ module NitroIntelligence
|
|
|
76
76
|
|
|
77
77
|
# @api private
|
|
78
78
|
def model_catalog
|
|
79
|
-
@model_catalog ||= ModelCatalog.new(configuration.model_config)
|
|
79
|
+
@model_catalog ||= ModelCatalog.new(configuration.model_config, GatewayModels.from_config(configuration))
|
|
80
80
|
end
|
|
81
81
|
|
|
82
82
|
# Each Cerebro project's client, through a registry shared by all threads.
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: nitro_intelligence
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 4.
|
|
4
|
+
version: 4.4.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Igor Artemenko
|
|
@@ -55,16 +55,22 @@ dependencies:
|
|
|
55
55
|
name: openai
|
|
56
56
|
requirement: !ruby/object:Gem::Requirement
|
|
57
57
|
requirements:
|
|
58
|
-
- - "
|
|
58
|
+
- - ">="
|
|
59
59
|
- !ruby/object:Gem::Version
|
|
60
60
|
version: '0.86'
|
|
61
|
+
- - "<"
|
|
62
|
+
- !ruby/object:Gem::Version
|
|
63
|
+
version: '2'
|
|
61
64
|
type: :runtime
|
|
62
65
|
prerelease: false
|
|
63
66
|
version_requirements: !ruby/object:Gem::Requirement
|
|
64
67
|
requirements:
|
|
65
|
-
- - "
|
|
68
|
+
- - ">="
|
|
66
69
|
- !ruby/object:Gem::Version
|
|
67
70
|
version: '0.86'
|
|
71
|
+
- - "<"
|
|
72
|
+
- !ruby/object:Gem::Version
|
|
73
|
+
version: '2'
|
|
68
74
|
- !ruby/object:Gem::Dependency
|
|
69
75
|
name: opentelemetry-sdk
|
|
70
76
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -132,6 +138,7 @@ files:
|
|
|
132
138
|
- lib/nitro_intelligence/media/image.rb
|
|
133
139
|
- lib/nitro_intelligence/media/image_generation.rb
|
|
134
140
|
- lib/nitro_intelligence/media/media.rb
|
|
141
|
+
- lib/nitro_intelligence/models/gateway_models.rb
|
|
135
142
|
- lib/nitro_intelligence/models/model.rb
|
|
136
143
|
- lib/nitro_intelligence/models/model_catalog.rb
|
|
137
144
|
- lib/nitro_intelligence/models/model_factory.rb
|