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
@@ -0,0 +1,200 @@
1
+ module NitroIntelligence
2
+ module Observability
3
+ # Coordinates flush with the existing export worker instead of exporting a separate
4
+ # queue snapshot. OpenTelemetry Ruby 1.13.1's force_flush misses in-flight batches
5
+ # and waits for export locks without a deadline. Keep its queue, exporter and metrics;
6
+ # wake its worker and wait for the work captured at the call's start with a deadline.
7
+ # The OTLP exporter sends synchronously and its force_flush is a no-op, so finishing
8
+ # the worker's export also finishes that batch's delivery attempt.
9
+ #
10
+ # Upstream fix requested in https://github.com/open-telemetry/opentelemetry-ruby/issues/2497;
11
+ # once it ships, this subclass can be replaced by the SDK's own force_flush.
12
+ #
13
+ # @api private
14
+ class BatchSpanProcessor < OpenTelemetry::SDK::Trace::Export::BatchSpanProcessor
15
+ # Each call captures a prefix of the FIFO queue and the current export, if any.
16
+ # Counts shrink on dequeue or overflow; later spans never extend a call's work.
17
+ #
18
+ # @api private
19
+ FlushWaiter = Struct.new(:queued, :exporting, :result) do
20
+ def pending?
21
+ queued.positive? || exporting
22
+ end
23
+ end
24
+
25
+ # Shutdown needs the upstream synchronous drain after stopping the worker.
26
+ # Public flush calls must never take that path, which ignores in-flight batches.
27
+ alias flush_at_shutdown force_flush
28
+ private :flush_at_shutdown
29
+
30
+ def force_flush(timeout: nil)
31
+ start_time = OpenTelemetry::Common::Utilities.timeout_timestamp
32
+ startup_error = nil
33
+
34
+ result = lock do
35
+ return OpenTelemetry::SDK::Trace::Export::FAILURE unless @keep_running
36
+
37
+ remaining = OpenTelemetry::Common::Utilities.maybe_timeout(timeout, start_time)
38
+ if remaining&.zero?
39
+ return OpenTelemetry::SDK::Trace::Export::SUCCESS if spans.empty? && !@exporting
40
+
41
+ return OpenTelemetry::SDK::Trace::Export::TIMEOUT
42
+ end
43
+
44
+ reset_on_fork(restart_thread: false)
45
+ begin
46
+ start_worker
47
+ rescue ThreadError => e
48
+ startup_error = e
49
+ next OpenTelemetry::SDK::Trace::Export::FAILURE
50
+ end
51
+
52
+ wait_for_exports(timeout, start_time)
53
+ end
54
+ # Reporting can block; release the queue lock before invoking either callback.
55
+ report_startup_error(startup_error) if startup_error
56
+ result
57
+ end
58
+
59
+ # Preserve the SDK's teardown, but wake waiting flush callers and use the
60
+ # private upstream drain instead of dispatching back to public force_flush.
61
+ def shutdown(timeout: nil)
62
+ start_time = OpenTelemetry::Common::Utilities.timeout_timestamp
63
+ thread = lock do
64
+ return OpenTelemetry::SDK::Trace::Export::FAILURE unless @keep_running
65
+
66
+ @keep_running = false
67
+ @condition.signal
68
+ @flush_condition.broadcast
69
+ @thread
70
+ end
71
+
72
+ thread&.join(timeout)
73
+ flush_at_shutdown(timeout: OpenTelemetry::Common::Utilities.maybe_timeout(timeout, start_time))
74
+ dropped_spans = lock { spans.shift(spans.length) }
75
+ report_dropped_spans(dropped_spans, reason: "terminating") if dropped_spans.any?
76
+ @exporter.shutdown(timeout: OpenTelemetry::Common::Utilities.maybe_timeout(timeout, start_time))
77
+ end
78
+
79
+ private
80
+
81
+ def start_worker
82
+ return @thread if @thread&.alive?
83
+
84
+ @thread = Thread.new { work }
85
+ end
86
+
87
+ def report_startup_error(error)
88
+ @metrics_reporter.add_to_counter("otel.bsp.error", labels: { "reason" => "ThreadError" })
89
+ OpenTelemetry.handle_error(exception: error, message: "unexpected error in BatchSpanProcessor#start_worker")
90
+ end
91
+
92
+ def wait_for_exports(timeout, start_time)
93
+ waiter = FlushWaiter.new(spans.size, @exporting, OpenTelemetry::SDK::Trace::Export::SUCCESS)
94
+ @flush_waiters.add(waiter)
95
+ @condition.signal
96
+
97
+ loop do
98
+ return waiter.result unless waiter.pending?
99
+ return OpenTelemetry::SDK::Trace::Export::FAILURE unless @keep_running
100
+
101
+ remaining = OpenTelemetry::Common::Utilities.maybe_timeout(timeout, start_time)
102
+ return OpenTelemetry::SDK::Trace::Export::TIMEOUT if remaining&.zero?
103
+
104
+ @flush_condition.wait(@mutex, remaining)
105
+ end
106
+ ensure
107
+ @flush_waiters.delete(waiter)
108
+ end
109
+
110
+ # Find the batch limit while collecting waiters; Set iteration order is unspecified.
111
+ def queued_flushes
112
+ waiters = []
113
+ limit = batch_size
114
+ @flush_waiters.each do |waiter|
115
+ next unless waiter.queued.positive?
116
+
117
+ waiters << waiter
118
+ limit = waiter.queued if waiter.queued < limit
119
+ end
120
+ [waiters, limit]
121
+ end
122
+
123
+ # Unlike the upstream worker, a waiting flush bypasses the scheduled delay for
124
+ # its remaining batches. @exporting covers dequeue through result reporting.
125
+ def work
126
+ loop do
127
+ batch = lock do
128
+ waiters, limit = queued_flushes
129
+ if spans.size < batch_size && @keep_running && waiters.empty?
130
+ @condition.wait(@mutex, @delay_seconds)
131
+ @condition.wait(@mutex, @delay_seconds) while spans.empty? && @keep_running
132
+ # Waiting releases the lock; callers may register or time out before we resume.
133
+ waiters, limit = queued_flushes
134
+ end
135
+ return unless @keep_running
136
+
137
+ take_batch(waiters, limit)
138
+ end
139
+
140
+ export_and_notify(batch)
141
+ end
142
+ end
143
+
144
+ # Split at the earliest flush boundary so a batch never mixes that call's
145
+ # captured observations with later work. This runs under the queue lock.
146
+ def take_batch(waiters, limit)
147
+ batch = spans.shift(limit)
148
+ waiters.each do |waiter|
149
+ waiter.queued -= batch.size
150
+ waiter.exporting = true
151
+ end
152
+ @exporting = true
153
+ batch
154
+ end
155
+
156
+ def export_and_notify(batch)
157
+ result = OpenTelemetry::SDK::Trace::Export::FAILURE
158
+ @metrics_reporter.observe_value("otel.bsp.buffer_utilization", value: spans.size / max_queue_size.to_f)
159
+ result = export_batch(batch)
160
+ ensure
161
+ lock do
162
+ @flush_waiters.each do |waiter|
163
+ next unless waiter.exporting
164
+
165
+ unless result == OpenTelemetry::SDK::Trace::Export::SUCCESS
166
+ waiter.result = OpenTelemetry::SDK::Trace::Export::FAILURE
167
+ end
168
+ waiter.exporting = false
169
+ end
170
+ @exporting = false
171
+ @flush_condition.broadcast
172
+ end
173
+ end
174
+
175
+ # Queue overflow is reported inside the queue lock. Export failures are
176
+ # reported outside it, and are delivered to waiters by export_and_notify.
177
+ def report_dropped_spans(dropped_spans, reason:, **kwargs)
178
+ if reason == "buffer-full" && dropped_spans.any?
179
+ @flush_waiters.each do |waiter|
180
+ next unless waiter.queued.positive?
181
+
182
+ waiter.queued = [waiter.queued - dropped_spans.size, 0].max
183
+ waiter.result = OpenTelemetry::SDK::Trace::Export::FAILURE
184
+ end
185
+ @flush_condition.broadcast
186
+ end
187
+ super
188
+ end
189
+
190
+ def reset_on_fork(restart_thread: true)
191
+ return if @pid == Process.pid
192
+
193
+ @flush_condition = ConditionVariable.new
194
+ @flush_waiters = Set.new.compare_by_identity
195
+ @exporting = false
196
+ super
197
+ end
198
+ end
199
+ end
200
+ end
@@ -39,6 +39,32 @@ module NitroIntelligence
39
39
  )
40
40
  end
41
41
 
42
+ # Fetches one of the project's prompts, without making a model call: to read its `config`, or to
43
+ # compile its text for a request of your own.
44
+ #
45
+ # A prompt fetched by label is cached for five minutes, and by version indefinitely. If Cerebro
46
+ # cannot be reached, a label lookup falls back to the last prompt fetched for that label, however
47
+ # old. To use the same prompt for several steps, fetch it once and ask for its `version` in the
48
+ # requests that follow, so that a label moved in between cannot mix two versions.
49
+ #
50
+ # @param name [String] the prompt's name in Cerebro
51
+ # @param label [String, nil] the label to fetch, `"production"` when neither it nor `version`
52
+ # is given
53
+ # @param version [Integer, nil] the version to fetch, taking precedence over `label`
54
+ # @return [Prompt]
55
+ # @raise [PromptStore::ObservabilityPromptNotFoundError] when the prompt, at that label or
56
+ # version, does not exist
57
+ # @raise [PromptStore::ObservabilityPromptError] when Cerebro fails to return the prompt
58
+ # @example
59
+ # prompt = project.prompt("Page Finder Search")
60
+ # prompt.config[:candidates] # => 50
61
+ def prompt(name, label: nil, version: nil)
62
+ prompt = prompt_store.get_prompt(prompt_name: name, prompt_label: label, prompt_version: version)
63
+ raise PromptStore::ObservabilityPromptNotFoundError, "Prompt: #{name} Not Found" if prompt.nil?
64
+
65
+ prompt
66
+ end
67
+
42
68
  # @api private
43
69
  def mask_content?
44
70
  @mask_content
@@ -18,6 +18,29 @@ module NitroIntelligence
18
18
  @observability_client = observability_client
19
19
  end
20
20
 
21
+ # Wait for this project's observation exports queued or in flight when called.
22
+ #
23
+ # Observations completed later are excluded from this call's wait and result. The client
24
+ # remains usable, and active observations are not ended. Queued scores and evaluator
25
+ # results are not covered. Success does not guarantee immediate visibility in Cerebro.
26
+ #
27
+ # Earlier export failures are not reported, and discarded observations are not retried.
28
+ # Concurrent calls have independent timeouts. Completed results take precedence over
29
+ # timeout or shutdown.
30
+ #
31
+ # @param timeout [Numeric] maximum wait in seconds (default: 30). Exports continue after
32
+ # timeout. With zero, succeeds only for a running client with no pending exports.
33
+ # @return [Boolean] true if this call's exports succeed or none are pending; false if
34
+ # exporting fails or cannot start, an observation being flushed is dropped, the wait
35
+ # times out, or shutdown interrupts pending work. Calls made while the client is
36
+ # stopping or stopped return false.
37
+ # @example Export before submitting observation IDs for review
38
+ # client = NitroIntelligence.project_client_registry.fetch("my-feature-project")
39
+ # raise "Observation export failed or timed out" unless client.flush(timeout: 30)
40
+ def flush(timeout: 30) # rubocop:disable Naming/PredicateMethod
41
+ @observability_client.flush(timeout:) == OpenTelemetry::SDK::Trace::Export::SUCCESS
42
+ end
43
+
21
44
  # @api private
22
45
  def shutdown
23
46
  @observability_client.shutdown
@@ -17,15 +17,17 @@ module NitroIntelligence
17
17
  def initialize(base_url:)
18
18
  @base_url = base_url
19
19
  @project_clients = {}
20
+ @mutex = Mutex.new
20
21
  end
21
22
 
22
23
  # The client for the project configured under `slug`, built on first use.
24
+ # Concurrent fetches for the same project share one client.
23
25
  #
24
26
  # @param slug [String]
25
27
  # @return [ProjectClient]
26
28
  # @raise [Project::NotFoundError] when `observability_projects` does not configure the project
27
29
  def fetch(slug)
28
- @project_clients[slug] ||= build_project_client(slug)
30
+ @mutex.synchronize { @project_clients[slug] ||= build_project_client(slug) }
29
31
  end
30
32
 
31
33
  # Sends what each client still holds to Cerebro, and stops it. Call it as the process exits, or
@@ -33,7 +35,8 @@ module NitroIntelligence
33
35
  #
34
36
  # @return [void]
35
37
  def shutdown_all
36
- @project_clients.values.each(&:shutdown)
38
+ clients = @mutex.synchronize { @project_clients.values }
39
+ clients.each(&:shutdown)
37
40
  end
38
41
 
39
42
  private
@@ -50,6 +53,7 @@ module NitroIntelligence
50
53
  config.public_key = project.public_key
51
54
  config.secret_key = project.secret_key
52
55
  config.base_url = @base_url
56
+ config.release = NitroIntelligence.configuration.current_revision
53
57
  # Default flush of 60 seconds can be too quick when
54
58
  # dealing with longer responses like image gen
55
59
  config.flush_interval = 120
@@ -1,11 +1,32 @@
1
1
  module NitroIntelligence
2
2
  module Observability
3
- # @api private
3
+ # A prompt managed in Cerebro, as {Project#prompt} and {Client::Base#prompt} return it. A request
4
+ # that names a prompt with `prompt_name` uses one of these, but an application can also read one
5
+ # itself, for its text or its `config`, without making a model call.
4
6
  class Prompt
5
- attr_reader :name, :type, :prompt, :version, :config, :labels, :tags
7
+ # @return [String] the prompt's name in Cerebro
8
+ attr_reader :name
9
+ # @return [String] `"text"` for a single string, or `"chat"` for a list of role-tagged messages
10
+ attr_reader :type
11
+ # @return [String, Array<Hash>] the prompt's content as Cerebro stores it, variables
12
+ # uncompiled: a string for a text prompt, or messages with `:role` and `:content` for a chat
13
+ # prompt. {#compile} fills in the variables.
14
+ attr_reader :prompt
15
+ # @return [Integer] the version Cerebro returned, which a later lookup can ask for to get the
16
+ # same prompt again
17
+ attr_reader :version
18
+ # @return [Hash{Symbol => Object}] the prompt's config, keys symbolized at every level, and
19
+ # empty when it has none
20
+ attr_reader :config
21
+ # @return [Array<String>] the labels this version carries, such as `"production"`
22
+ attr_reader :labels
23
+ # @return [Array<String>]
24
+ attr_reader :tags
6
25
 
26
+ # @api private
7
27
  VARIABLE_REGEX = /\{\{([a-zA-Z0-9_]+)\}\}/
8
28
 
29
+ # @api private
9
30
  def initialize(name:, type:, prompt:, version:, **extra_args)
10
31
  @name = name
11
32
  @type = type
@@ -16,9 +37,14 @@ module NitroIntelligence
16
37
  @tags = extra_args[:tags] || []
17
38
  end
18
39
 
19
- # Returns prompt "content" from API with prompt variables replaced
20
- # Prompt "content" will either be a string or an array of hashes
21
- # based on prompt "type" ("text" or "chat")
40
+ # The prompt's content with its `{{variables}}` filled in. A variable with no replacement is
41
+ # left as it is.
42
+ #
43
+ # @param replacements [Hash{Symbol => #to_s}] each variable's value, by name
44
+ # @return [String, Array<Hash>] a string for a text prompt, or new messages for a chat prompt,
45
+ # leaving this prompt's own uncompiled
46
+ # @example
47
+ # client.prompt("Page Finder Search").compile(product: "Nitro")
22
48
  def compile(**replacements)
23
49
  return replace_variables(@prompt, **replacements) if @type == "text"
24
50
 
@@ -28,6 +54,8 @@ module NitroIntelligence
28
54
  end
29
55
  end
30
56
 
57
+ # @api private
58
+ #
31
59
  # Takes provided chat messages and inserts the compiled prompt
32
60
  # into the correct position based on prompt "type" ("text" or "chat")
33
61
  def interpolate(messages:, variables:)
@@ -38,6 +66,9 @@ module NitroIntelligence
38
66
  end
39
67
  end
40
68
 
69
+ # The names of the `{{variables}}` the prompt's content uses, in order of appearance.
70
+ #
71
+ # @return [Array<Symbol>]
41
72
  def variables
42
73
  messages = @type == "text" ? [@prompt] : @prompt.pluck(:content)
43
74
 
@@ -0,0 +1,132 @@
1
+ module NitroIntelligence
2
+ # A step of application code recorded in Cerebro, as {Tracer#trace} and {#observe} yield it.
3
+ #
4
+ # A project that masks content records the input and output given here as `[masked]`, as it does
5
+ # for the gem's own requests. Metadata is recorded as given, so keep content out of it.
6
+ class Observation
7
+ # The Langfuse observation types {#observe} accepts.
8
+ TYPES = (Langfuse::OBSERVATION_TYPES.keys - [:event]).freeze
9
+
10
+ # @api private
11
+ MAX_STATUS_MESSAGE_LENGTH = 2000
12
+
13
+ # @api private
14
+ def initialize(langfuse_observation, observability_client:, project:)
15
+ @observation = langfuse_observation
16
+ @observability_client = observability_client
17
+ @project = project
18
+ end
19
+
20
+ # @return [String] the observation's ID, for scoring it with {Reporter#score}
21
+ def id
22
+ @observation.id
23
+ end
24
+
25
+ # @return [String] the ID of the trace the observation is in, for scoring it with {Reporter#score}
26
+ def trace_id
27
+ @observation.trace_id
28
+ end
29
+
30
+ # Records what the step was given. On the observation {Tracer#trace} yields, this is the
31
+ # trace's input too.
32
+ #
33
+ # @param value [Object] anything that serializes to JSON
34
+ def input=(value)
35
+ @observation.input = @project.mask(value)
36
+ end
37
+
38
+ # Records what the step produced. On the observation {Tracer#trace} yields, this is the
39
+ # trace's output too.
40
+ #
41
+ # @param value [Object] anything that serializes to JSON
42
+ def output=(value)
43
+ @observation.output = @project.mask(value)
44
+ end
45
+
46
+ # Records metadata on the observation. It is not masked.
47
+ #
48
+ # @param value [Hash]
49
+ def metadata=(value)
50
+ @observation.metadata = value
51
+ end
52
+
53
+ # Records a step inside this one, around a block. The gem's requests made inside the block nest
54
+ # under the step. An exception the block raises is recorded on the step at level `ERROR`, and
55
+ # re-raised.
56
+ #
57
+ # @param name [String] what the step does
58
+ # @param as_type [Symbol] one of {TYPES}, such as `:span`, `:retriever` or `:tool`
59
+ # @param input [Object, nil] what the step is given
60
+ # @param metadata [Hash, nil]
61
+ # @yieldparam observation [Observation] the step, to record its output on
62
+ # @return [Object] the block's value
63
+ # @raise [ArgumentError] when `as_type` is not one of {TYPES}, or no block is given
64
+ # @example
65
+ # hits = root_observation.observe("Elasticsearch", as_type: :retriever, input: { k: 50 }) do |step|
66
+ # search(question).tap { |hits| step.output = hits.map(&:page_id) }
67
+ # end
68
+ def observe(name, as_type: :span, input: nil, metadata: nil, &)
69
+ raise ArgumentError, "a block is required" unless block_given?
70
+ unless TYPES.include?(as_type)
71
+ raise ArgumentError, "as_type must be one of #{TYPES.join(', ')}, not #{as_type.inspect}"
72
+ end
73
+
74
+ child = @observability_client.start_observation(
75
+ name,
76
+ attributes(input:, metadata:),
77
+ as_type:,
78
+ parent_span_context: @observation.otel_span.context
79
+ )
80
+ Observation.new(child, observability_client: @observability_client, project: @project).run(&)
81
+ end
82
+
83
+ # Records something that happened at a point in time inside this step, such as a user's choice.
84
+ #
85
+ # @param name [String] what happened
86
+ # @param input [Object, nil]
87
+ # @param output [Object, nil]
88
+ # @param metadata [Hash, nil]
89
+ # @return [void]
90
+ def event(name, input: nil, output: nil, metadata: nil)
91
+ @observability_client.start_observation(
92
+ name,
93
+ attributes(input:, output:, metadata:),
94
+ as_type: :event,
95
+ parent_span_context: @observation.otel_span.context
96
+ )
97
+ nil
98
+ end
99
+
100
+ # @api private
101
+ #
102
+ # Runs the block with this observation active, records an exception it raises, and ends the
103
+ # observation.
104
+ def run
105
+ @observability_client.within(@observation) { yield self }
106
+ rescue => e
107
+ @observation.update(level: "ERROR", status_message: failure_message(e))
108
+ raise
109
+ ensure
110
+ @observation.end
111
+ end
112
+
113
+ private
114
+
115
+ def attributes(input: nil, output: nil, metadata: nil)
116
+ {
117
+ input: @project.mask(input),
118
+ output: @project.mask(output),
119
+ metadata:,
120
+ environment: NitroIntelligence.environment.to_s,
121
+ }.compact
122
+ end
123
+
124
+ # The message of an exception can quote what the step was given, so a masked project records
125
+ # which exception it was and nothing it said.
126
+ def failure_message(error)
127
+ return error.class.to_s if @project.mask_content?
128
+
129
+ "#{error.class}: #{error.message}".truncate(MAX_STATUS_MESSAGE_LENGTH)
130
+ end
131
+ end
132
+ end
@@ -0,0 +1,47 @@
1
+ module NitroIntelligence
2
+ # What {Client::Base#rerank} returns: the documents' relevance to the query, most relevant first.
3
+ class Ranking
4
+ # One document's place in the ranking.
5
+ #
6
+ # @!attribute [r] index
7
+ # @return [Integer] the document's position in the `documents` given to {Client::Base#rerank}
8
+ # @!attribute [r] relevance_score
9
+ # @return [Float, nil] how relevant the document is to the query, from 0 to 1, or nil when the
10
+ # provider sent no score, which ranks the document last
11
+ Result = Data.define(:index, :relevance_score)
12
+
13
+ # @return [String, nil] the gateway's identifier for the request
14
+ attr_reader :id
15
+ # @return [Array<Result>] the documents ranked, most relevant first, limited to `top_n` when
16
+ # that was given
17
+ attr_reader :results
18
+ # @return [ActiveSupport::HashWithIndifferentAccess] what the gateway reported as billed:
19
+ # `tokens` (`input_tokens`) and `billed_units` (`search_units`, `total_tokens`), each where the
20
+ # provider sent them
21
+ attr_reader :meta
22
+ # @api private
23
+ attr_reader :response
24
+
25
+ # @!method last_response
26
+ # @return [OpenAI::ResponseMetadata, nil] the HTTP response, including the
27
+ # gateway's headers
28
+ delegate :last_response, to: :response
29
+
30
+ # @api private
31
+ # @param top_n [Integer, nil] how many results to keep, applied here because not every
32
+ # provider honours it
33
+ def initialize(response, top_n: nil)
34
+ @response = response
35
+ @id = response[:id]
36
+ @results = response[:results].to_a.map do |result|
37
+ Result.new(index: result[:index], relevance_score: Float(result[:relevance_score], exception: false))
38
+ end
39
+ # Ties keep the order the provider gave them, since sort_by alone is not stable.
40
+ @results = @results.each_with_index.sort_by do |result, index|
41
+ [-(result.relevance_score || -Float::INFINITY), index]
42
+ end.map(&:first)
43
+ @results = @results.first(top_n) if top_n
44
+ @meta = response[:meta].to_h.deep_dup.with_indifferent_access
45
+ end
46
+ end
47
+ end
@@ -53,24 +53,36 @@ module NitroIntelligence
53
53
  response
54
54
  end
55
55
 
56
- # Scores a trace. Scoring it again under the same `id` replaces the score.
56
+ # Scores a trace, or an observation in it. Scoring it again under the same `id` replaces the
57
+ # score.
57
58
  #
58
- # @param trace_id [String] the trace, such as {Trace.create_id} gives for a seed
59
+ # @param trace_id [String] the trace, such as {Trace.create_id} gives for a seed, or
60
+ # {Observation#trace_id}
59
61
  # @param name [String] what the score measures
60
62
  # @param value [Numeric, String, Boolean] the score: a number, `true` or `false` for `:boolean`,
61
63
  # or the category's name for `:categorical`
64
+ # @param observation_id [String, nil] the observation in the trace to score, as
65
+ # {Observation#id} gives it, rather than the trace as a whole
62
66
  # @param id [String] identifies the score, so that recording it again replaces it. Defaults to
63
- # one per trace and name.
67
+ # one per trace, observation and name.
64
68
  # @param data_type [Symbol] `:numeric`, `:boolean` or `:categorical`
69
+ # @param comment [String, nil]
70
+ # @param metadata [Hash, nil]
65
71
  # @return [void]
66
72
  # @raise [ArgumentError] when `value` does not suit `data_type`
67
- def score(trace_id:, name:, value:, id: "#{trace_id}-#{name}", data_type: :numeric)
73
+ # @example Scoring a search result the user clicked, from the request that records the click
74
+ # reporter.score(trace_id: params[:trace_id], name: "clicked", value: 1, metadata: { position: 3 })
75
+ def score(trace_id:, name:, value:, observation_id: nil, id: [trace_id, observation_id, name].compact.join("-"), # rubocop:disable Metrics/ParameterLists
76
+ data_type: :numeric, comment: nil, metadata: nil)
68
77
  @project_client.observability_client.create_score(
69
78
  id:,
70
79
  trace_id:,
80
+ observation_id:,
71
81
  name:,
72
82
  value:,
73
83
  data_type:,
84
+ comment:,
85
+ metadata:,
74
86
  environment: NitroIntelligence.environment
75
87
  )
76
88
  end
@@ -0,0 +1,87 @@
1
+ require "nitro_intelligence/observation"
2
+ require "nitro_intelligence/trace"
3
+
4
+ module NitroIntelligence
5
+ # Records application code in Cerebro as a trace, with the gem's requests made inside it nested
6
+ # under it, for a feature whose work is more than one model call.
7
+ #
8
+ # @example
9
+ # tracer = NitroIntelligence::Tracer.new(observability_project_slug: "page-finder")
10
+ # client = NitroIntelligence::Client.new(observability_project_slug: "page-finder")
11
+ #
12
+ # tracer.trace("Page Finder search", input: { question: }, user_id: current_user.id.to_s) do |root_observation|
13
+ # query = client.chat(message: question) # recorded inside the trace
14
+ # hits = root_observation.observe("Elasticsearch", as_type: :retriever, input: { k: 50 }) do |step|
15
+ # search(query).tap { |hits| step.output = hits.map(&:page_id) }
16
+ # end
17
+ # root_observation.output = hits.map(&:page_id)
18
+ # end
19
+ class Tracer
20
+ # @param observability_project_slug [String] the Cerebro project to record in. The gem's
21
+ # requests nest under the trace only when their client records in the same project.
22
+ # @raise [Observability::Project::NotFoundError] when `observability_projects` does not configure
23
+ # the project
24
+ def initialize(observability_project_slug:)
25
+ @project_client = NitroIntelligence.project_client_registry.fetch(observability_project_slug)
26
+ end
27
+
28
+ # Records the block as a trace of its own, even inside another trace, with its environment and
29
+ # release set as the gem's requests set them. The gem's requests made inside the block, through a
30
+ # client for the same project and without a `trace_seed`, are recorded as observations in this
31
+ # trace instead of traces of their own: the trace's name, input, output, user, session and tags are
32
+ # the ones given here, and the request's `trace_name`, `user_id`, `session_id` and `tags` are not
33
+ # recorded. An exception the block raises is recorded on the trace at level `ERROR`, and re-raised.
34
+ #
35
+ # @param name [String] the trace's name
36
+ # @param as_type [Symbol] the type of the trace's root observation, one of {Observation::TYPES}
37
+ # @param input [Object, nil] the trace's input. Set it later with {Observation#input=}.
38
+ # @param metadata [Hash] recorded on the trace and every observation in it, with each value
39
+ # converted to a String. It is not masked.
40
+ # @param user_id [String, nil] the application's user, defaulting to `observability_user_id`
41
+ # @param session_id [String, nil] groups related traces
42
+ # @param tags [Array<String>, nil] labels the trace for filtering
43
+ # @param trace_seed [String, nil] gives the trace the ID {Trace.create_id} gives for the seed,
44
+ # rather than a random one
45
+ # @yieldparam root_observation [Observation] the trace's root observation
46
+ # @return [Object] the block's value
47
+ # @raise [ArgumentError] when `as_type` is not one of {Observation::TYPES}, or no block is given
48
+ def trace(name, as_type: :span, input: nil, metadata: {}, user_id: nil, session_id: nil, tags: nil, # rubocop:disable Metrics/ParameterLists
49
+ trace_seed: nil, &)
50
+ raise ArgumentError, "a block is required" unless block_given?
51
+ unless Observation::TYPES.include?(as_type)
52
+ raise ArgumentError, "as_type must be one of #{Observation::TYPES.join(', ')}, not #{as_type.inspect}"
53
+ end
54
+
55
+ propagated = propagated_attributes(metadata:, user_id:, session_id:, tags:)
56
+ LangfuseExtension.in_new_trace do
57
+ Langfuse.propagate_attributes(**propagated) { start(name, as_type:, input:, trace_seed:).run(&) }
58
+ end
59
+ end
60
+
61
+ private
62
+
63
+ def start(name, as_type:, input:, trace_seed:)
64
+ observability_client = @project_client.observability_client
65
+ trace_id = trace_seed.present? ? Trace.create_id(seed: trace_seed) : Langfuse.create_trace_id
66
+
67
+ langfuse_observation = observability_client.start_observation(
68
+ name, { environment: NitroIntelligence.environment.to_s }, as_type:, trace_id:
69
+ )
70
+ langfuse_observation.update_trace(name:)
71
+
72
+ Observation.new(
73
+ langfuse_observation, observability_client:, project: @project_client.project
74
+ ).tap { |observation| observation.input = input unless input.nil? }
75
+ end
76
+
77
+ def propagated_attributes(metadata:, user_id:, session_id:, tags:)
78
+ attributes = {
79
+ user_id: user_id || NitroIntelligence.configuration.observability_user_id,
80
+ metadata: metadata.to_h.transform_values(&:to_s),
81
+ }
82
+ attributes[:session_id] = session_id if session_id.present?
83
+ attributes[:tags] = tags if tags.present?
84
+ attributes
85
+ end
86
+ end
87
+ end