nitro_intelligence 4.1.1 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. checksums.yaml +4 -4
  2. data/docs/CHANGELOG.md +24 -0
  3. data/docs/README.md +152 -3
  4. data/lib/nitro_intelligence/client/base.rb +86 -0
  5. data/lib/nitro_intelligence/client/client.rb +2 -2
  6. data/lib/nitro_intelligence/client/handlers/embedding_handler.rb +95 -0
  7. data/lib/nitro_intelligence/client/handlers/observed/embedding_handler.rb +73 -0
  8. data/lib/nitro_intelligence/client/handlers/observed/rerank_handler.rb +78 -0
  9. data/lib/nitro_intelligence/client/handlers/rerank_handler.rb +82 -0
  10. data/lib/nitro_intelligence/client/observed.rb +19 -0
  11. data/lib/nitro_intelligence/client/observers/langfuse_observer.rb +41 -26
  12. data/lib/nitro_intelligence/embeddings.rb +39 -0
  13. data/lib/nitro_intelligence/langfuse_extension.rb +52 -0
  14. data/lib/nitro_intelligence/langfuse_tracer_provider.rb +11 -2
  15. data/lib/nitro_intelligence/media/image_generation.rb +6 -1
  16. data/lib/nitro_intelligence/models/model.rb +21 -0
  17. data/lib/nitro_intelligence/models/model_catalog.rb +4 -0
  18. data/lib/nitro_intelligence/models/model_factory.rb +2 -0
  19. data/lib/nitro_intelligence/observability/batch_span_processor.rb +200 -0
  20. data/lib/nitro_intelligence/observability/project.rb +26 -0
  21. data/lib/nitro_intelligence/observability/project_client.rb +23 -0
  22. data/lib/nitro_intelligence/observability/project_client_registry.rb +6 -2
  23. data/lib/nitro_intelligence/observability/prompt.rb +36 -5
  24. data/lib/nitro_intelligence/observation.rb +132 -0
  25. data/lib/nitro_intelligence/ranking.rb +47 -0
  26. data/lib/nitro_intelligence/reporter.rb +16 -4
  27. data/lib/nitro_intelligence/tracer.rb +87 -0
  28. data/lib/nitro_intelligence/version.rb +1 -1
  29. data/lib/nitro_intelligence.rb +9 -4
  30. metadata +30 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0e7cc3cbb0388e9001c106d00fddb60d6e1d7f2c3b9b54aa50d842e9ed719b8f
4
- data.tar.gz: c1fce6397a2b3bba37ac56531c27608f9e8503e11603c0d9d2634a77dc17937f
3
+ metadata.gz: 27f08824317caeb5e6b8de73db8cec8bbd9633a6dca72fc96d37977f7d4776e6
4
+ data.tar.gz: 2d751c4d40c30148d47bf75ac36b0b4a7024b7740b62985f79d2b2d581efd4c0
5
5
  SHA512:
6
- metadata.gz: 5c40c5f964e4e9c5441460f7c5113ea4e55d83e73ed9be8cc82c8021a0b8d69772ea8f29a3de6b9a3706557fb8260377bebac2231542cfcbd940ef3973156a6c
7
- data.tar.gz: ee972990ddda7041e3a756384022e46c68bc3e8af6e5188c545ad559e1c46618b7a1c0a5733940dd093c7a3d73aeb71a2012266de082776a3ec945b32c925067
6
+ metadata.gz: aae6508c9d5f23520d46acf912f9dcb4f18643e7950052a24c99f91acb0f99f8ef84156eea767733f1e50314b758dd10d982d8acab10de9c85e1cba0a0a4efa3
7
+ data.tar.gz: 637cb07fea164e376e4c6ca24ad1642bb98e9577c6cc6ea60429c1af5d58ca1f389a8113e71143b7eb96a292d54325758daa4a67af7bbe9f741295ffce233bb8
data/docs/CHANGELOG.md CHANGED
@@ -5,6 +5,30 @@ 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.3.0](https://github.com/powerhome/nitro-intelligence.rb/compare/v4.2.0...v4.3.0) (2026-11-11)
9
+
10
+
11
+ ### Added
12
+
13
+ * embed queries and documents with tracing and cost ([#199](https://github.com/powerhome/nitro-intelligence.rb/issues/199)) ([8136c50](https://github.com/powerhome/nitro-intelligence.rb/commit/8136c5076c0f39698bb2d93dd535aad6efbd343e))
14
+ * Expose Cerebro prompts ([#201](https://github.com/powerhome/nitro-intelligence.rb/issues/201)) ([b56cea8](https://github.com/powerhome/nitro-intelligence.rb/commit/b56cea839c7b32aeb6c490ff0c3316f5e7117b21))
15
+ * rerank documents against a query with tracing and cost ([#202](https://github.com/powerhome/nitro-intelligence.rb/issues/202)) ([4f59f4d](https://github.com/powerhome/nitro-intelligence.rb/commit/4f59f4d3458694e3ff45338a2decb973c6015e60))
16
+
17
+ ## [4.2.0](https://github.com/powerhome/nitro-intelligence.rb/compare/v4.1.1...v4.2.0) (2026-11-10)
18
+
19
+
20
+ ### Added
21
+
22
+ * let applications trace their own steps alongside the gem's requests ([#198](https://github.com/powerhome/nitro-intelligence.rb/issues/198)) ([dd45726](https://github.com/powerhome/nitro-intelligence.rb/commit/dd457262545752064030755591cd40b265b1cae3))
23
+ * let Reporter#score take observation_id, comment and metadata to ([dd45726](https://github.com/powerhome/nitro-intelligence.rb/commit/dd457262545752064030755591cd40b265b1cae3))
24
+ * **observability:** add project client flush ([#206](https://github.com/powerhome/nitro-intelligence.rb/issues/206)) ([0303034](https://github.com/powerhome/nitro-intelligence.rb/commit/0303034e5586e3fdfa0704be1899b93cbf8b90ce))
25
+
26
+
27
+ ### Fixed
28
+
29
+ * **observability:** share one project client registry and one client per ([0303034](https://github.com/powerhome/nitro-intelligence.rb/commit/0303034e5586e3fdfa0704be1899b93cbf8b90ce))
30
+ * use the final image when Gemini also returns thought images ([#205](https://github.com/powerhome/nitro-intelligence.rb/issues/205)) ([1ce6b50](https://github.com/powerhome/nitro-intelligence.rb/commit/1ce6b501e7d374de6b39a1d7cabe3314de69c01c))
31
+
8
32
  ## [4.1.1](https://github.com/powerhome/nitro-intelligence.rb/compare/v4.1.0...v4.1.1) (2026-11-05)
9
33
 
10
34
 
data/docs/README.md CHANGED
@@ -54,6 +54,8 @@ NitroIntelligence.configure do |config|
54
54
  "default_image_model" => "google/gemini-3.1-flash-image",
55
55
  "default_text_to_speech_model" => "openai/gpt-4o-mini-tts",
56
56
  "default_decision_model" => "typesafe/jev-1.14",
57
+ "default_embedding_model" => "Qwen/Qwen3-Embedding-0.6B",
58
+ "default_rerank_model" => "Qwen/Qwen3-Reranker-0.6B",
57
59
  "models" => [
58
60
  {
59
61
  "name" => "Qwen/Qwen3.6-35B-A3B",
@@ -81,6 +83,15 @@ NitroIntelligence.configure do |config|
81
83
  {
82
84
  "name" => "typesafe/jev-1.14",
83
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"
84
95
  }
85
96
  ]
86
97
  }
@@ -103,7 +114,7 @@ end
103
114
  | `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) |
104
115
  | `observability_user_id` | `String` | `""` | User ID recorded on observed traces when a request passes no `user_id` parameter — see [Users](#users) |
105
116
  | `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) |
106
- | `model_config` | `Hash` | `{}` | Model defaults and per-model settings. Top-level keys: `default_text_model`, `default_audio_transcription_model`, `default_image_model`, `default_text_to_speech_model`, `default_decision_model`, and `models` (array of per-model hashes keyed by `name` and `type`, with type-specific options like `aspect_ratios`/`resolutions` for images or `voices`/`response_formats` for TTS) |
117
+ | `model_config` | `Hash` | `{}` | Model defaults and per-model settings. Top-level keys: `default_text_model`, `default_audio_transcription_model`, `default_image_model`, `default_text_to_speech_model`, `default_decision_model`, `default_embedding_model`, `default_rerank_model`, and `models` (array of per-model hashes keyed by `name` and `type`, with type-specific options like `aspect_ratios`/`resolutions` for images or `voices`/`response_formats` for TTS, and for embeddings the optional, model-specific `query_prefix` and `document_prefix`: Qwen3-Embedding takes only `query_prefix`, E5 both, OpenAI's models neither, as [Embeddings](#embeddings) describes) |
107
118
 
108
119
  ## Basic Usage
109
120
 
@@ -262,6 +273,55 @@ The model defaults to `default_decision_model` and must be listed in `config.mod
262
273
 
263
274
  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`.
264
275
 
276
+ ### Embeddings
277
+
278
+ An embeddings model turns text into a vector, so text with similar meaning can be found by comparing vectors. Embeddings go through the gateway like any other request. The gateway must serve an embeddings model; see the [Inference Gateway docs](https://github.com/powerhome/nitro-intelligence/blob/main/docs/inference-gateway.md) for what it serves.
279
+
280
+ Many embeddings models are trained to embed a search query differently from the documents it is searched against, so the client has a method for each. `embed_documents` embeds the documents for an index, and `embed_query` the query to search it with. Both return a `NitroIntelligence::Embeddings` with one vector per input, in input order:
281
+
282
+ ```ruby
283
+ # Documents, such as an index rebuild
284
+ embeddings = client.embed_documents(documents: pages.map(&:description), parameters: { dimensions: 512 })
285
+ embeddings.vectors # => [[0.012, -0.034, ...], ...], one per page
286
+
287
+ # A query to search them with
288
+ client.embed_query(query: "How do I request time off?", parameters: { dimensions: 512 }).vector # => [0.021, 0.008, ...]
289
+ ```
290
+
291
+ `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
+
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 listed in `config.model_config` with the type `embedding`.
294
+
295
+ * **`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
+ * **`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
+
298
+ A model's `query_prefix` and `document_prefix` in `config.model_config` are what it expects before a query's text and before a document's, in the form it was trained on. Qwen3-Embedding takes an instruction before each query and nothing before a document, as in the configuration above; E5 takes `"query: "` and `"passage: "`. Leave both out for a model that embeds queries and documents the same way, such as OpenAI's. Switching to another embeddings model only means changing its `model_config` entry, but vectors from different models cannot be compared, so it also means embedding your stored documents again.
299
+
300
+ `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 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
+
302
+ Embeddings take no managed prompt: `prompt_name` and `prompt_variables` are ignored.
303
+
304
+ ### Reranking
305
+
306
+ A reranker scores how relevant each of a list of documents is to a query. It is more accurate than comparing vectors, and suits reordering the few dozen candidates a vector search returned. The gateway must serve a reranker; see the [Inference Gateway docs](https://github.com/powerhome/nitro-intelligence/blob/main/docs/inference-gateway.md) for what it serves.
307
+
308
+ `rerank` takes a query and a list of documents and returns a `NitroIntelligence::Ranking`, most relevant first:
309
+
310
+ ```ruby
311
+ ranking = client.rerank(
312
+ query: "How do I request time off?",
313
+ documents: candidates.map(&:description),
314
+ parameters: { top_n: 5 }
315
+ )
316
+ ranking.results.first.index # => 3, the position in `documents`
317
+ ranking.results.first.relevance_score # => 0.97, from 0 to 1
318
+ candidates.values_at(*ranking.results.map(&:index))
319
+ ```
320
+
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 listed in `config.model_config` with the type `rerank`. `ranking.meta` holds what the provider billed, and `ranking.last_response` the HTTP response, including the gateway's headers.
322
+
323
+ 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
+
265
325
  ### Image Editing and Generation
266
326
 
267
327
  Nitro Intelligence can be used for image editing and generation
@@ -275,7 +335,7 @@ client = NitroIntelligence::Client.new
275
335
  result = client.generate_image(message: "Create an image of a bear installing a window.")
276
336
  ```
277
337
 
278
- `result` is a `NitroIntelligence::ImageGeneration` object, and the generated image can be accessed via `result.generated_image` which returns a `NitroIntelligence::Image`.
338
+ `result` is a `NitroIntelligence::ImageGeneration` object, and the generated image can be accessed via `result.generated_image` which returns a `NitroIntelligence::Image`. Gemini image models that think can return their interim drafts alongside the final render; `generated_image` is always the final one.
279
339
 
280
340
  With observability enabled, `result.trace_id` and `result.observation_id` identify the trace and generation observation. Both are `nil` without observability.
281
341
 
@@ -343,6 +403,25 @@ client.chat(
343
403
 
344
404
  If no `prompt_label` or `prompt_version` is provided, the 'production' prompt is used by default.
345
405
 
406
+ ### Exporting Completed Observations
407
+
408
+ Observations are exported in the background. Use the same shared project client for tracing and flushing when a job needs to export completed observations before submitting their IDs for human review:
409
+
410
+ ```ruby
411
+ project_client = NitroIntelligence.project_client_registry.fetch("my-feature-project")
412
+ raise "Observation export failed or timed out" unless project_client.flush(timeout: 30)
413
+
414
+ # Submit the completed observations' IDs to the annotation queue here.
415
+ ```
416
+
417
+ `flush` waits only for this project's observations queued or in flight when called. Observations completed later do not extend the wait. The client remains usable, and active observations are not ended.
418
+
419
+ It returns `true` when those exports succeed or nothing needs exporting. It returns `false` if exporting fails or cannot start, an observation being flushed is dropped, the wait times out, or shutdown prevents completion. Calls made during or after shutdown return `false`. Earlier export failures are not reported.
420
+
421
+ The timeout defaults to 30 seconds; exports continue after a caller times out. With `timeout: 0`, a running client succeeds only if nothing is queued or in flight.
422
+
423
+ It does not flush queued scores or wait for evaluators, and successful export does not guarantee immediate visibility in Cerebro or annotation queues. Reserve `NitroIntelligence.project_client_registry.shutdown_all` for process teardown. See the [ProjectClient#flush API reference](https://www.rubydoc.info/gems/nitro_intelligence/NitroIntelligence/Observability/ProjectClient#flush-instance_method) for details.
424
+
346
425
  ### Prompt Fallbacks
347
426
 
348
427
  Pass `prompt_fallback_name` to name a second prompt to use when the one you asked for isn't there. The prompt in `prompt_name` is tried first; if it doesn't exist, or its lookup fails, the fallback is used instead:
@@ -507,7 +586,7 @@ success, so it records no input up front.
507
586
 
508
587
  A project can opt in to recording what happened without recording what was said. Set `"mask_content" => true` on its entry in `observability_projects`; projects that do not set it are unchanged.
509
588
 
510
- For a masked project, every observed request (chat, image generation, audio transcription, text-to-speech and decisions) is still traced, with its model, usage, cost, prompt link, tags, user, session, metadata and gateway call ID, but:
589
+ For a masked project, every observed request (chat, image generation, audio transcription, text-to-speech, decisions, embeddings and reranking) is still traced, with its model, usage, cost, prompt link, tags, user, session, metadata and gateway call ID, but:
511
590
 
512
591
  * The input and output of the generation and of the trace are recorded as `[masked]`. The whole value is replaced, so reasoning, tool calls and anything else in a response are masked however the provider shaped it.
513
592
  * A failed request records the error class (for example `OpenAI::Errors::BadRequestError`) as its status message, without the error's own message, which can quote the request or the response.
@@ -521,6 +600,46 @@ Two things this does not cover:
521
600
  * **The gateway's redaction is by field, and misses some.** It replaces the fields it knows about, such as `content` and `reasoning_content`, rather than the whole response, so a field a provider adds beyond those is still logged. Reasoning that a provider returns under `provider_specific_fields` is one such field today; see [powerhome/nitro-intelligence#704](https://github.com/powerhome/nitro-intelligence/issues/704).
522
601
  * **Prompts you fetch from Cerebro are unaffected.** Masking applies to traces, not to prompt management.
523
602
 
603
+ ### Tracing Application Steps
604
+
605
+ Each observed request is a trace of its own by default. A feature whose work is more than one model call, such as a search that embeds a question, queries an index, reranks the results and filters them by permission, can record that work as one trace with `NitroIntelligence::Tracer`: its own steps as observations, and the gem's requests nested among them.
606
+
607
+ ```ruby
608
+ tracer = NitroIntelligence::Tracer.new(observability_project_slug: "page-finder")
609
+ client = NitroIntelligence::Client.new(observability_project_slug: "page-finder")
610
+
611
+ pages = tracer.trace("Page Finder search", input: { question: }, user_id: current_user.id.to_s, session_id:) do |root_observation|
612
+ query = client.chat(message: question) # recorded inside the trace
613
+
614
+ hits = root_observation.observe("Elasticsearch", as_type: :retriever, input: { k: 50, boost: 2 }) do |step|
615
+ search(query).tap { |hits| step.output = hits.map { |hit| { id: hit.page_id, score: hit.score } } }
616
+ end
617
+
618
+ allowed = root_observation.observe("Permission filter", input: { candidates: hits.size }) do |step|
619
+ permitted(hits).tap { |pages| step.output = { allowed: pages.size } }
620
+ end
621
+
622
+ root_observation.output = allowed.map(&:page_id)
623
+ @trace_id = root_observation.trace_id # to score the search when the user clicks a result
624
+ allowed
625
+ end
626
+ ```
627
+
628
+ `Tracer#trace` records its block as a trace with the given name, user, session, tags and metadata, and the environment and release the gem's own requests record. `user_id` defaults to `observability_user_id`, as it does for a request. It yields the trace's root observation: the input and output set on it are the trace's input and output too, while metadata set on it is recorded on that observation only. `trace_seed:` gives the trace the ID `NitroIntelligence::Trace.create_id` gives for the seed; otherwise the ID is random, and `root_observation.trace_id` reads it.
629
+
630
+ `Observation#observe` records a step inside the trace, or inside another step, around a block. `as_type` is a Langfuse [observation type](https://langfuse.com/docs/observability/features/observation-types): `:span` by default, or `:retriever`, `:tool`, `:agent`, `:chain`, `:evaluator`, `:guardrail`, `:embedding` or `:generation`. `Observation#event` records a point in time, such as the results a user was shown. An exception raised inside a block is recorded on its step at level `ERROR`, and re-raised.
631
+
632
+ The gem's requests made inside the block are recorded as observations under the step that is open, not as traces of their own, when:
633
+
634
+ * the client records in the same Cerebro project as the tracer. A request recorded in another project is a trace of its own there, as it would be outside the block.
635
+ * the request passes no `trace_seed`. A seeded request is recorded in the seed's trace, as it is anywhere.
636
+
637
+ Such a request records its own observation only: the trace's name, input, output, user, session and tags are the ones the tracer was given, and the request's `trace_name`, `user_id`, `session_id` and `tags` are not recorded. Its `metadata` is still recorded on its observation and sent to the inference gateway.
638
+
639
+ A trace of its own started inside the block (a request to another project, a seeded request, or another `Tracer#trace`) neither takes the open trace's user, session, tags and metadata nor changes them. It takes only what the application propagated before opening the trace, such as with `Langfuse.propagate_attributes`, as it would outside the block.
640
+
641
+ A project that masks content records the input and output of every step and event as `[masked]`, and a failure's error class without its message, as it does for the gem's requests. Metadata, names, user, session and tags are not masked.
642
+
524
643
  ### Scoring
525
644
 
526
645
  You can use `NitroIntelligence::Reporter` to evaluate existing traces. Calling `NitroIntelligence::Reporter#score` lets you attach metrics to a trace in the observability platform.
@@ -543,6 +662,15 @@ trace_id = NitroIntelligence::Trace.create_id(seed: document_id)
543
662
  reporter.score(name: "precision", value: 0.5, trace_id:)
544
663
  ```
545
664
 
665
+ #### An Observation, Later
666
+
667
+ A score can be recorded from a later request than the one that made the trace, such as a click on a search result, given the trace's ID. Pass `observation_id:` to score one observation in the trace, as `Observation#id` gives it, rather than the trace as a whole. `comment:` and `metadata:` are recorded with the score.
668
+
669
+ ```ruby
670
+ reporter = NitroIntelligence::Reporter.new(observability_project_slug: "page-finder")
671
+ reporter.score(trace_id: params[:trace_id], name: "clicked", value: true, data_type: :boolean, metadata: { position: 3 })
672
+ ```
673
+
546
674
  #### Using different data types for scoring
547
675
 
548
676
  By default, scores submitted on a trace are numeric, but you can use the `data_type` keyword to change it to `:boolean` or `:categorical`. For example:
@@ -580,6 +708,8 @@ trace_url = "#{NitroIntelligence.config.observability_base_url}/project/#{projec
580
708
  request["Authorization"] = "Basic #{project.auth_token}"
581
709
  ```
582
710
 
711
+ `project.prompt(name, label:, version:)` fetches one of the project's prompts, as [`client.prompt`](#reading-a-prompt) does.
712
+
583
713
  `NitroIntelligence.project_client_registry.fetch(slug)` builds each project's client once per process, and raises `NitroIntelligence::Observability::Project::NotFoundError` for a slug `observability_projects` does not configure. `NitroIntelligence::Observability::Project.find_by_slug(slug:)` reads the same configuration without building a client, and returns `nil` instead. The gem never raises `NitroIntelligence::Observability::ProjectClient::NotFoundError`; it is public only because applications raise it themselves, and is to be retired ([#182](https://github.com/powerhome/nitro-intelligence.rb/issues/182)). Rescue `Project::NotFoundError` for a project that is not configured.
584
714
 
585
715
  Traces and scores are sent to Cerebro in the background. Fetch each project in an initializer to build its client at boot, and shut them all down as the process exits so that the last ones are sent:
@@ -720,6 +850,25 @@ client.chat(
720
850
  )
721
851
  ```
722
852
 
853
+ #### Reading a Prompt
854
+
855
+ To read a prompt without making a model call, for its config or to compile its text for a request of your own, fetch it from an observed client:
856
+
857
+ ```ruby
858
+ client = NitroIntelligence::Client.new(observability_project_slug: "page-finder")
859
+ prompt = client.prompt("Page Finder Search") # the production label
860
+ prompt = client.prompt("Page Finder Search", label: "staging")
861
+ prompt = client.prompt("Page Finder Search", version: 4)
862
+
863
+ prompt.name # => "Page Finder Search"
864
+ prompt.version # => 4
865
+ prompt.type # => "text", or "chat"
866
+ prompt.config # => { min_relevance: 0.1, candidates: 50 }, keys symbolized
867
+ prompt.compile(product: "Nitro") # the text, or the messages, with its variables filled in
868
+ ```
869
+
870
+ Code that holds a project rather than a client can call `project.prompt` with the same arguments (see [Reaching Cerebro Directly](#reaching-cerebro-directly)). Either uses the same cache as a request naming the prompt: five minutes for a label, indefinitely for a version, and the last prompt fetched for a label when Cerebro cannot be reached. To use one prompt's settings across several steps, fetch it once and keep the result, or pass its `version` to later lookups, so that a label moved in between cannot mix two versions. A missing prompt raises `ObservabilityPromptNotFoundError` and a failed lookup `ObservabilityPromptError`, as below. A client without observability has no project to fetch from, and raises `NitroIntelligence::Observability::Project::NotFoundError`.
871
+
723
872
  #### Prompt Errors
724
873
 
725
874
  A request naming a prompt raises when it cannot use one:
@@ -1,8 +1,11 @@
1
1
  require "nitro_intelligence/client/handlers/audio_transcription_handler"
2
2
  require "nitro_intelligence/client/handlers/chat_handler"
3
3
  require "nitro_intelligence/client/handlers/decision_handler"
4
+ require "nitro_intelligence/client/handlers/embedding_handler"
4
5
  require "nitro_intelligence/client/handlers/image_handler"
6
+ require "nitro_intelligence/client/handlers/rerank_handler"
5
7
  require "nitro_intelligence/client/handlers/text_to_speech_handler"
8
+ require "nitro_intelligence/observability/project"
6
9
 
7
10
  module NitroIntelligence
8
11
  module Client
@@ -60,6 +63,81 @@ module NitroIntelligence
60
63
  decision_handler.create(state:, questions:, parameters: parameters.dup)
61
64
  end
62
65
 
66
+ # Embeds a search query as a vector over the gateway's `/v1/embeddings` route, to compare
67
+ # with vectors from {#embed_documents}.
68
+ #
69
+ # @param query [String, Array<String>] the query, or several, such as an evaluation set
70
+ # @param parameters [Hash] `model`, `dimensions` (a shorter vector, for a model that supports
71
+ # one), `batch_size` (at most this many texts per request, 128 by default), `user`,
72
+ # `metadata` and `request_options`, and on an observed client `trace_name`, `trace_seed`,
73
+ # `user_id`, `session_id` and `tags`. It takes no managed prompt.
74
+ # @return [Embeddings] the query's vector in `vector`, or one per query in `vectors`
75
+ # @raise [ArgumentError] when the model is not one `model_config` lists with the type
76
+ # `embedding`, a query is empty or not text, or `batch_size` is not a positive integer
77
+ # @example
78
+ # client.embed_query(query: "How do I request time off?").vector
79
+ def embed_query(query:, parameters: {})
80
+ embedding_handler.create(input: query, input_type: :query, parameters: parameters.dup)
81
+ end
82
+
83
+ # Embeds documents as vectors over the gateway's `/v1/embeddings` route, for a search index.
84
+ #
85
+ # @param documents [Array<String>, String] the documents. A long list is sent in batches of
86
+ # `batch_size` and recorded as one observation.
87
+ # @param parameters [Hash] the same as {#embed_query}'s
88
+ # @return [Embeddings] one vector per document in `vectors`, in the order given
89
+ # @raise [ArgumentError] as {#embed_query} does
90
+ # @example
91
+ # client.embed_documents(documents: pages.map(&:description), parameters: { dimensions: 512 }).vectors
92
+ def embed_documents(documents:, parameters: {})
93
+ embedding_handler.create(input: documents, input_type: :document, parameters: parameters.dup)
94
+ end
95
+
96
+ # Ranks documents by their relevance to a query over the gateway's rerank route,
97
+ # `POST /v1/rerank`.
98
+ #
99
+ # @param query [String] what the documents are ranked against
100
+ # @param documents [Array<String>] the candidates
101
+ # @param parameters [Hash] `model`, `top_n` (return only the most relevant this many),
102
+ # `metadata` and `request_options`, and on an observed client `trace_name`, `trace_seed`,
103
+ # `user_id`, `session_id`, `tags` and `trace_documents` (false to record only how many
104
+ # documents there were, for a caller whose own trace already records them). It takes no
105
+ # managed prompt.
106
+ # @return [Ranking]
107
+ # @raise [ArgumentError] when the model is not one `model_config` lists with the type
108
+ # `rerank`, the query is empty, the documents are empty or not text, or `top_n` is not a
109
+ # positive integer
110
+ # @example
111
+ # client.rerank(query: "How do I request time off?", documents: pages.map(&:description),
112
+ # parameters: { top_n: 5 }).results.map(&:index)
113
+ def rerank(query:, documents:, parameters: {})
114
+ rerank_handler.create(query:, documents:, parameters: parameters.dup)
115
+ end
116
+
117
+ # Fetches a prompt from the client's Cerebro project without making a model call, as
118
+ # {Observability::Project#prompt} does.
119
+ #
120
+ # @param name [String] the prompt's name in Cerebro
121
+ # @param label [String, nil] the label to fetch, `"production"` when neither it nor `version`
122
+ # is given
123
+ # @param version [Integer, nil] the version to fetch, taking precedence over `label`
124
+ # @return [Observability::Prompt]
125
+ # @raise [Observability::Project::NotFoundError] when the client has no Cerebro project: it was
126
+ # built without an `observability_project_slug`, or with one `observability_projects` does
127
+ # not configure
128
+ # @raise [Observability::PromptStore::ObservabilityPromptNotFoundError] when the prompt, at that
129
+ # label or version, does not exist
130
+ # @raise [Observability::PromptStore::ObservabilityPromptError] when Cerebro fails to return
131
+ # the prompt
132
+ # @example
133
+ # client = NitroIntelligence::Client.new(observability_project_slug: "page-finder")
134
+ # client.prompt("Page Finder Search").config[:min_relevance] # => 0.1
135
+ def prompt(name, label: nil, version: nil) # rubocop:disable Lint/UnusedMethodArgument
136
+ raise Observability::Project::NotFoundError,
137
+ "This client has no Cerebro project to fetch #{name.inspect} from: build it with an " \
138
+ "observability_project_slug that observability_projects configures"
139
+ end
140
+
63
141
  # Generates an image, or edits `target_image`.
64
142
  #
65
143
  # @param message [String] what to generate, or how to edit the target
@@ -122,6 +200,10 @@ module NitroIntelligence
122
200
  @decision_handler ||= Handlers::DecisionHandler.new(client: @client)
123
201
  end
124
202
 
203
+ def embedding_handler
204
+ @embedding_handler ||= Handlers::EmbeddingHandler.new(client: @client)
205
+ end
206
+
125
207
  def image_handler
126
208
  @image_handler ||= Handlers::ImageHandler.new(client: @client)
127
209
  end
@@ -134,6 +216,10 @@ module NitroIntelligence
134
216
  @client.respond_to?(method_name, include_private) || super
135
217
  end
136
218
 
219
+ def rerank_handler
220
+ @rerank_handler ||= Handlers::RerankHandler.new(client: @client)
221
+ end
222
+
137
223
  def text_to_speech_handler
138
224
  @text_to_speech_handler ||= Handlers::TextToSpeechHandler.new(client: @client)
139
225
  end
@@ -1,8 +1,8 @@
1
1
  require "nitro_intelligence/client/factory"
2
2
 
3
3
  module NitroIntelligence
4
- # Inference through the inference gateway: chat, image generation and editing, audio
5
- # transcription and text-to-speech. See the README's "Basic Usage".
4
+ # Inference through the inference gateway: chat, decisions, embeddings, reranking, image
5
+ # generation and editing, audio transcription and text-to-speech. See the README's "Basic Usage".
6
6
  module Client
7
7
  # Builds a client, which records every request in Cerebro when given a project to report to.
8
8
  #
@@ -0,0 +1,95 @@
1
+ require "openai"
2
+ require "nitro_intelligence/client/handlers/base_handler"
3
+ require "nitro_intelligence/embeddings"
4
+
5
+ module NitroIntelligence
6
+ module Client
7
+ module Handlers
8
+ # Embeds text over the gateway's `/v1/embeddings` route, splitting a long list of inputs into
9
+ # batches of `batch_size` so an index rebuild of thousands of entries is one call.
10
+ #
11
+ # @api private
12
+ class EmbeddingHandler < BaseHandler
13
+ # Fields of openai-ruby's embedding request taken from `parameters`. The input is the
14
+ # handler's own argument, and the vectors are always requested as floats, the only
15
+ # encoding openai-ruby decodes into the response it returns.
16
+ ALLOWED_EXTRA_PARAMETERS =
17
+ (OpenAI::Models::EmbeddingCreateParams.fields.keys - %i[input encoding_format]).uniq.freeze
18
+
19
+ DEFAULT_BATCH_SIZE = 128
20
+
21
+ INPUT_TYPES = %i[query document].freeze
22
+
23
+ def create(input:, input_type:, parameters: {})
24
+ validate_and_resolve!(input, input_type, parameters)
25
+ perform_request(input:, input_type:, parameters:)
26
+ end
27
+
28
+ # Each batch's response is added to `responses` as it arrives, so a caller can still
29
+ # account for the batches already billed when a later one raises.
30
+ def perform_request(input:, input_type:, parameters: {}, correlation_trace_id: nil, mask_content: false,
31
+ responses: [])
32
+ add_gateway_headers(parameters, correlation_trace_id:, mask_content:)
33
+ texts(input, input_type, parameters).each_slice(parameters[:batch_size]) do |batch|
34
+ responses << @client.embeddings.create(
35
+ input: batch, encoding_format: :float, **parameters.slice(*ALLOWED_EXTRA_PARAMETERS)
36
+ )
37
+ end
38
+ Embeddings.new(responses)
39
+ end
40
+
41
+ def validate_and_resolve!(input, input_type, parameters)
42
+ default_parameters = {
43
+ metadata: {},
44
+ model: NitroIntelligence.model_catalog.default_embedding_model&.name,
45
+ batch_size: DEFAULT_BATCH_SIZE,
46
+ }
47
+
48
+ parameters.replace(default_parameters.merge(parameters))
49
+ Client.validate_model(parameters[:model], type: EmbeddingModel)
50
+ unless INPUT_TYPES.include?(input_type)
51
+ raise ArgumentError, "input_type must be one of #{INPUT_TYPES.inspect}"
52
+ end
53
+
54
+ validate_input!(input)
55
+ validate_batch_size!(parameters[:batch_size])
56
+ end
57
+
58
+ # 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.
60
+ def texts(input, input_type, parameters)
61
+ prefix = Client.validate_model(parameters[:model], type: EmbeddingModel).prefix_for(input_type)
62
+ Array(input).map { |text| "#{prefix}#{text}" }
63
+ end
64
+
65
+ # The cost of every batch, added up. A batch the gateway did not price leaves the whole call
66
+ # unpriced, because a sum that silently skips it would understate the spend.
67
+ def cost_details(embeddings)
68
+ costs = embeddings.responses.map { |response| super(response) }
69
+ return nil if costs.empty? || costs.any?(&:nil?)
70
+
71
+ %i[total input output].index_with do |component|
72
+ costs.sum { |cost| cost[component] } if costs.all? { |cost| cost.key?(component) }
73
+ end.compact
74
+ end
75
+
76
+ private
77
+
78
+ # Checked before any batch is sent, so a bad entry late in a long list cannot fail the call
79
+ # after the batches before it were billed.
80
+ def validate_input!(input)
81
+ texts = Array(input)
82
+ return if texts.any? && texts.all? { |text| text.is_a?(String) && text.present? }
83
+
84
+ raise ArgumentError, "input must be a non-empty string or a non-empty array of non-empty strings"
85
+ end
86
+
87
+ def validate_batch_size!(batch_size)
88
+ return if batch_size.is_a?(Integer) && batch_size.positive?
89
+
90
+ raise ArgumentError, "batch_size must be a positive integer, not #{batch_size.inspect}"
91
+ end
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,73 @@
1
+ require "nitro_intelligence/client/handlers/observed/base_handler"
2
+
3
+ module NitroIntelligence
4
+ module Client
5
+ module Handlers
6
+ module Observed
7
+ # Recorded as one embedding observation per call, however many batches the input was sent
8
+ # in, so an index rebuild is one observation rather than one for each entry.
9
+ #
10
+ # @api private
11
+ class EmbeddingHandler < BaseHandler
12
+ OBSERVATION_NAMES = { query: "embed-query", document: "embed-documents" }.freeze
13
+
14
+ def create(input:, input_type:, parameters: {})
15
+ @base_handler.validate_and_resolve!(input, input_type, parameters)
16
+
17
+ trace_name = parameters[:trace_name] || project.slug
18
+ texts = @base_handler.texts(input, input_type, parameters)
19
+
20
+ # The texts as the model received them, prefix included, since the prefix changes the
21
+ # vector as much as the text does.
22
+ @observer.observe(
23
+ OBSERVATION_NAMES.fetch(input_type),
24
+ type: :embedding,
25
+ parameters:,
26
+ trace_name:,
27
+ input: input.is_a?(Array) ? texts : texts.first
28
+ ) do |embedding|
29
+ workflow(embedding:, input:, input_type:, parameters:)
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ def workflow(embedding:, input:, input_type:, parameters:)
36
+ responses = []
37
+ embeddings = @base_handler.perform_request(
38
+ input:, input_type:, parameters:,
39
+ correlation_trace_id: embedding.trace_id, mask_content: project.mask_content?, responses:
40
+ )
41
+
42
+ # The vectors are never recorded: they are large, mean nothing to read, and are the
43
+ # caller's to store. Their count and size say whether the call did what was asked.
44
+ trace_attributes = {
45
+ model: embeddings.model,
46
+ output: { count: embeddings.vectors.size, dimensions: embeddings.vector&.size },
47
+ usage_details: embeddings.usage.to_h.symbolize_keys.presence,
48
+ cost_details: @base_handler.cost_details(embeddings),
49
+ }
50
+
51
+ [embeddings, trace_attributes]
52
+ rescue
53
+ record_billed_batches(embedding, responses)
54
+ raise
55
+ end
56
+
57
+ # A batch that fails after others succeeded leaves those billed, so the failed call still
58
+ # records what they used and cost, rather than nothing, before the error is raised.
59
+ def record_billed_batches(embedding, responses)
60
+ return if responses.empty?
61
+
62
+ billed = Embeddings.new(responses)
63
+ attributes = {
64
+ usage_details: billed.usage.to_h.symbolize_keys.presence,
65
+ cost_details: @base_handler.cost_details(billed),
66
+ }.compact
67
+ embedding.update(attributes) if attributes.any?
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end