newrelic_rpm 9.7.0 → 9.8.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +44 -2
  3. data/README.md +1 -1
  4. data/lib/new_relic/agent/configuration/default_source.rb +37 -1
  5. data/lib/new_relic/agent/configuration/high_security_source.rb +1 -0
  6. data/lib/new_relic/agent/configuration/manager.rb +6 -3
  7. data/lib/new_relic/agent/configuration/security_policy_source.rb +11 -0
  8. data/lib/new_relic/agent/custom_event_aggregator.rb +27 -1
  9. data/lib/new_relic/agent/error_collector.rb +2 -0
  10. data/lib/new_relic/agent/instrumentation/active_support_broadcast_logger/instrumentation.rb +7 -3
  11. data/lib/new_relic/agent/instrumentation/async_http.rb +3 -1
  12. data/lib/new_relic/agent/instrumentation/concurrent_ruby.rb +1 -0
  13. data/lib/new_relic/agent/instrumentation/grpc_server.rb +1 -1
  14. data/lib/new_relic/agent/instrumentation/net_http/instrumentation.rb +6 -0
  15. data/lib/new_relic/agent/instrumentation/ruby_openai/chain.rb +36 -0
  16. data/lib/new_relic/agent/instrumentation/ruby_openai/instrumentation.rb +197 -0
  17. data/lib/new_relic/agent/instrumentation/ruby_openai/prepend.rb +20 -0
  18. data/lib/new_relic/agent/instrumentation/ruby_openai.rb +35 -0
  19. data/lib/new_relic/agent/instrumentation/view_component/instrumentation.rb +2 -1
  20. data/lib/new_relic/agent/llm/chat_completion_message.rb +25 -0
  21. data/lib/new_relic/agent/llm/chat_completion_summary.rb +66 -0
  22. data/lib/new_relic/agent/llm/embedding.rb +60 -0
  23. data/lib/new_relic/agent/llm/llm_event.rb +95 -0
  24. data/lib/new_relic/agent/llm/response_headers.rb +80 -0
  25. data/lib/new_relic/agent/llm.rb +49 -0
  26. data/lib/new_relic/agent/threading/agent_thread.rb +1 -2
  27. data/lib/new_relic/agent/tracer.rb +5 -5
  28. data/lib/new_relic/agent/transaction/abstract_segment.rb +1 -1
  29. data/lib/new_relic/agent/transaction/tracing.rb +2 -2
  30. data/lib/new_relic/agent.rb +91 -0
  31. data/lib/new_relic/rack/browser_monitoring.rb +8 -4
  32. data/lib/new_relic/supportability_helper.rb +2 -0
  33. data/lib/new_relic/thread_local_storage.rb +31 -0
  34. data/lib/new_relic/version.rb +1 -1
  35. data/lib/tasks/instrumentation_generator/instrumentation.thor +1 -1
  36. data/lib/tasks/instrumentation_generator/templates/chain.tt +0 -1
  37. data/lib/tasks/instrumentation_generator/templates/chain_method.tt +0 -1
  38. data/newrelic.yml +21 -1
  39. metadata +13 -2
@@ -0,0 +1,66 @@
1
+ # This file is distributed under New Relic's license terms.
2
+ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
+ # frozen_string_literal: true
4
+
5
+ require_relative 'response_headers'
6
+
7
+ module NewRelic
8
+ module Agent
9
+ module Llm
10
+ class ChatCompletionSummary < LlmEvent
11
+ include ResponseHeaders
12
+
13
+ ATTRIBUTES = %i[request_max_tokens response_number_of_messages
14
+ request_model response_choices_finish_reason request_temperature
15
+ duration error]
16
+ ATTRIBUTE_NAME_EXCEPTIONS = {
17
+ response_number_of_messages: 'response.number_of_messages',
18
+ request_model: 'request.model',
19
+ response_choices_finish_reason: 'response.choices.finish_reason',
20
+ request_temperature: 'request.temperature'
21
+ }
22
+ ERROR_COMPLETION_ID = 'completion_id'
23
+ EVENT_NAME = 'LlmChatCompletionSummary'
24
+
25
+ attr_accessor(*ATTRIBUTES)
26
+
27
+ def attributes
28
+ LlmEvent::ATTRIBUTES + ResponseHeaders::ATTRIBUTES + ATTRIBUTES
29
+ end
30
+
31
+ def attribute_name_exceptions
32
+ # TODO: OLD RUBIES < 2.6
33
+ # Hash#merge accepts multiple arguments in 2.6
34
+ # Remove condition once support for Ruby <2.6 is dropped
35
+ if RUBY_VERSION >= '2.6.0'
36
+ LlmEvent::ATTRIBUTE_NAME_EXCEPTIONS.merge(ResponseHeaders::ATTRIBUTE_NAME_EXCEPTIONS, ATTRIBUTE_NAME_EXCEPTIONS)
37
+ else
38
+ LlmEvent::ATTRIBUTE_NAME_EXCEPTIONS.merge(ResponseHeaders::ATTRIBUTE_NAME_EXCEPTIONS).merge(ATTRIBUTE_NAME_EXCEPTIONS)
39
+ end
40
+ end
41
+
42
+ def event_name
43
+ EVENT_NAME
44
+ end
45
+
46
+ def error_attributes(exception)
47
+ attrs = {ERROR_COMPLETION_ID => id}
48
+
49
+ error_attributes_from_response(exception, attrs)
50
+ end
51
+
52
+ private
53
+
54
+ def error_attributes_from_response(exception, attrs)
55
+ return attrs unless exception.respond_to?(:response)
56
+
57
+ attrs[ERROR_ATTRIBUTE_STATUS_CODE] = exception.response.dig(:status)
58
+ attrs[ERROR_ATTRIBUTE_CODE] = exception.response.dig(:body, ERROR_STRING, CODE_STRING)
59
+ attrs[ERROR_ATTRIBUTE_PARAM] = exception.response.dig(:body, ERROR_STRING, PARAM_STRING)
60
+
61
+ attrs
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,60 @@
1
+ # This file is distributed under New Relic's license terms.
2
+ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
+ # frozen_string_literal: true
4
+
5
+ module NewRelic
6
+ module Agent
7
+ module Llm
8
+ class Embedding < LlmEvent
9
+ include ResponseHeaders
10
+
11
+ ATTRIBUTES = %i[input request_model token_count duration error].freeze
12
+ ATTRIBUTE_NAME_EXCEPTIONS = {
13
+ request_model: 'request.model'
14
+ }.freeze
15
+ ERROR_EMBEDDING_ID = 'embedding_id'
16
+ EVENT_NAME = 'LlmEmbedding'
17
+
18
+ attr_accessor(*ATTRIBUTES)
19
+
20
+ def attributes
21
+ LlmEvent::ATTRIBUTES + ResponseHeaders::ATTRIBUTES + ATTRIBUTES
22
+ end
23
+
24
+ def attribute_name_exceptions
25
+ # TODO: OLD RUBIES < 2.6
26
+ # Hash#merge accepts multiple arguments in 2.6
27
+ # Remove condition once support for Ruby <2.6 is dropped
28
+ if RUBY_VERSION >= '2.6.0'
29
+ LlmEvent::ATTRIBUTE_NAME_EXCEPTIONS.merge(ResponseHeaders::ATTRIBUTE_NAME_EXCEPTIONS, ATTRIBUTE_NAME_EXCEPTIONS)
30
+ else
31
+ LlmEvent::ATTRIBUTE_NAME_EXCEPTIONS.merge(ResponseHeaders::ATTRIBUTE_NAME_EXCEPTIONS).merge(ATTRIBUTE_NAME_EXCEPTIONS)
32
+ end
33
+ end
34
+
35
+ def event_name
36
+ EVENT_NAME
37
+ end
38
+
39
+ def error_attributes(exception)
40
+ attrs = {}
41
+ attrs[ERROR_EMBEDDING_ID] = id
42
+
43
+ error_attributes_from_response(exception, attrs)
44
+ end
45
+
46
+ private
47
+
48
+ def error_attributes_from_response(exception, attrs)
49
+ return attrs unless exception.respond_to?(:response)
50
+
51
+ attrs[ERROR_ATTRIBUTE_STATUS_CODE] = exception.response.dig(:status)
52
+ attrs[ERROR_ATTRIBUTE_CODE] = exception.response.dig(:body, ERROR_STRING, CODE_STRING)
53
+ attrs[ERROR_ATTRIBUTE_PARAM] = exception.response.dig(:body, ERROR_STRING, PARAM_STRING)
54
+
55
+ attrs
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,95 @@
1
+ # This file is distributed under New Relic's license terms.
2
+ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
+ # frozen_string_literal: true
4
+
5
+ module NewRelic
6
+ module Agent
7
+ module Llm
8
+ class LlmEvent
9
+ # Every subclass must define its own ATTRIBUTES constant, an array of symbols representing
10
+ # that class's unique attributes
11
+ ATTRIBUTES = %i[id request_id span_id trace_id response_model vendor
12
+ ingest_source metadata]
13
+ # These attributes should not be passed as arguments to initialize and will be set by the agent
14
+ AGENT_DEFINED_ATTRIBUTES = %i[span_id trace_id ingest_source]
15
+ # Some attributes have names that can't be written as symbols used for metaprogramming.
16
+ # The ATTRIBUTE_NAME_EXCEPTIONS hash should use the symbolized version of the name as the key
17
+ # and the string version expected by the UI as the value.
18
+ ATTRIBUTE_NAME_EXCEPTIONS = {response_model: 'response.model'}
19
+ INGEST_SOURCE = 'Ruby'
20
+ ERROR_ATTRIBUTE_STATUS_CODE = 'http.statusCode'
21
+ ERROR_ATTRIBUTE_CODE = 'error.code'
22
+ ERROR_ATTRIBUTE_PARAM = 'error.param'
23
+ ERROR_STRING = 'error'
24
+ CODE_STRING = 'code'
25
+ PARAM_STRING = 'param'
26
+
27
+ attr_accessor(*ATTRIBUTES)
28
+
29
+ def self.set_llm_agent_attribute_on_transaction
30
+ NewRelic::Agent::Transaction.add_agent_attribute(:llm, true, NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS)
31
+ end
32
+
33
+ # This initialize method is used for all subclasses.
34
+ # It leverages the subclass's `attributes` method to iterate through
35
+ # all the attributes for that subclass.
36
+ # It assigns instance variables for all arguments passed to the method.
37
+ # It also assigns agent-defined attributes.
38
+ def initialize(opts = {})
39
+ (attributes - AGENT_DEFINED_ATTRIBUTES).each do |attr|
40
+ instance_variable_set(:"@#{attr}", opts[attr]) if opts.key?(attr)
41
+ end
42
+
43
+ @id = id || NewRelic::Agent::GuidGenerator.generate_guid
44
+ @span_id = NewRelic::Agent::Tracer.current_span_id
45
+ @trace_id = NewRelic::Agent::Tracer.current_trace_id
46
+ @ingest_source = INGEST_SOURCE
47
+ end
48
+
49
+ # All subclasses use event_attributes to get a full hash of all
50
+ # attributes and their values
51
+ def event_attributes
52
+ attributes_hash = attributes.each_with_object({}) do |attr, hash|
53
+ hash[replace_attr_with_string(attr)] = instance_variable_get(:"@#{attr}")
54
+ end
55
+ attributes_hash.merge!(metadata) && attributes_hash.delete(:metadata) if !metadata.nil?
56
+
57
+ attributes_hash
58
+ end
59
+
60
+ # Subclasses define an attributes method to concatenate attributes
61
+ # defined across their ancestors and other modules
62
+ def attributes
63
+ ATTRIBUTES
64
+ end
65
+
66
+ # Subclasses that record events will override this method
67
+ def event_name
68
+ end
69
+
70
+ # Some attribute names include periods, which aren't valid values for
71
+ # Ruby method names. This method returns a Hash with the key as the
72
+ # Ruby symbolized version of the attribute and the value as the
73
+ # period-delimited string expected upstream.
74
+ def attribute_name_exceptions
75
+ ATTRIBUTE_NAME_EXCEPTIONS
76
+ end
77
+
78
+ def record
79
+ NewRelic::Agent.record_custom_event(event_name, event_attributes)
80
+ end
81
+
82
+ # Subclasses that add attributes to noticed errors will override this method
83
+ def error_attributes(exception)
84
+ NewRelic::EMPTY_HASH
85
+ end
86
+
87
+ private
88
+
89
+ def replace_attr_with_string(attr)
90
+ attribute_name_exceptions.fetch(attr, attr)
91
+ end
92
+ end
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,80 @@
1
+ # This file is distributed under New Relic's license terms.
2
+ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
+ # frozen_string_literal: true
4
+
5
+ module NewRelic
6
+ module Agent
7
+ module Llm
8
+ module ResponseHeaders
9
+ ATTRIBUTES = %i[response_organization llm_version ratelimit_limit_requests
10
+ ratelimit_limit_tokens ratelimit_remaining_requests
11
+ ratelimit_remaining_tokens ratelimit_reset_requests
12
+ ratelimit_reset_tokens ratelimit_limit_tokens_usage_based
13
+ ratelimit_reset_tokens_usage_based
14
+ ratelimit_remaining_tokens_usage_based].freeze
15
+
16
+ ATTRIBUTE_NAME_EXCEPTIONS = {
17
+ response_organization: 'response.organization',
18
+ llm_version: 'response.headers.llmVersion',
19
+ ratelimit_limit_requests: 'response.headers.ratelimitLimitRequests',
20
+ ratelimit_limit_tokens: 'response.headers.ratelimitLimitTokens',
21
+ ratelimit_remaining_requests: 'response.headers.ratelimitRemainingRequests',
22
+ ratelimit_remaining_tokens: 'response.headers.ratelimitRemainingTokens',
23
+ ratelimit_reset_requests: 'response.headers.ratelimitResetRequests',
24
+ ratelimit_reset_tokens: 'response.headers.ratelimitResetTokens',
25
+ ratelimit_limit_tokens_usage_based: 'response.headers.ratelimitLimitTokensUsageBased',
26
+ ratelimit_reset_tokens_usage_based: 'response.headers.ratelimitResetTokensUsageBased',
27
+ ratelimit_remaining_tokens_usage_based: 'response.headers.ratelimitRemainingTokensUsageBased'
28
+ }.freeze
29
+
30
+ OPENAI_ORGANIZATION = 'openai-organization'
31
+ OPENAI_VERSION = 'openai-version'
32
+ X_RATELIMIT_LIMIT_REQUESTS = 'x-ratelimit-limit-requests'
33
+ X_RATELIMIT_LIMIT_TOKENS = 'x-ratelimit-limit-tokens'
34
+ X_RATELIMIT_REMAINING_REQUESTS = 'x-ratelimit-remaining-requests'
35
+ X_RATELIMIT_REMAINING_TOKENS = 'x-ratelimit-remaining-tokens'
36
+ X_RATELIMIT_RESET_REQUESTS = 'x-ratelimit-reset-requests'
37
+ X_RATELIMIT_RESET_TOKENS = 'x-ratelimit-reset-tokens'
38
+ X_RATELIMIT_LIMIT_TOKENS_USAGE_BASED = 'x-ratelimit-limit-tokens-usage-based'
39
+ X_RATELIMIT_RESET_TOKENS_USAGE_BASED = 'x-ratelimit-reset-tokens-usage-based'
40
+ X_RATELIMIT_REMAINING_TOKENS_USAGE_BASED = 'x-ratelimit-remaining-tokens-usage-based'
41
+ X_REQUEST_ID = 'x-request-id'
42
+
43
+ attr_accessor(*ATTRIBUTES)
44
+
45
+ # Headers is a hash of Net::HTTP response headers
46
+ def populate_openai_response_headers(headers)
47
+ # Embedding, ChatCompletionSummary, and ChatCompletionMessage all need
48
+ # request_id, so it's defined in LlmEvent. ChatCompletionMessage
49
+ # adds the attribute via ChatCompletionSummary.
50
+ self.request_id = headers[X_REQUEST_ID]&.first
51
+ self.response_organization = headers[OPENAI_ORGANIZATION]&.first
52
+ self.llm_version = headers[OPENAI_VERSION]&.first
53
+ self.ratelimit_limit_requests = headers[X_RATELIMIT_LIMIT_REQUESTS]&.first.to_i
54
+ self.ratelimit_limit_tokens = headers[X_RATELIMIT_LIMIT_TOKENS]&.first.to_i
55
+ remaining_headers(headers)
56
+ reset_headers(headers)
57
+ tokens_usage_based_headers(headers)
58
+ end
59
+
60
+ private
61
+
62
+ def remaining_headers(headers)
63
+ self.ratelimit_remaining_requests = headers[X_RATELIMIT_REMAINING_REQUESTS]&.first.to_i
64
+ self.ratelimit_remaining_tokens = headers[X_RATELIMIT_REMAINING_TOKENS]&.first.to_i
65
+ end
66
+
67
+ def reset_headers(headers)
68
+ self.ratelimit_reset_requests = headers[X_RATELIMIT_RESET_REQUESTS]&.first
69
+ self.ratelimit_reset_tokens = headers[X_RATELIMIT_RESET_TOKENS]&.first
70
+ end
71
+
72
+ def tokens_usage_based_headers(headers)
73
+ self.ratelimit_limit_tokens_usage_based = headers[X_RATELIMIT_LIMIT_TOKENS_USAGE_BASED]&.first.to_i
74
+ self.ratelimit_reset_tokens_usage_based = headers[X_RATELIMIT_RESET_TOKENS_USAGE_BASED]&.first
75
+ self.ratelimit_remaining_tokens_usage_based = headers[X_RATELIMIT_REMAINING_TOKENS_USAGE_BASED]&.first.to_i
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,49 @@
1
+ # This file is distributed under New Relic's license terms.
2
+ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
+ # frozen_string_literal: true
4
+
5
+ require_relative 'llm/llm_event'
6
+ require_relative 'llm/chat_completion_message'
7
+ require_relative 'llm/chat_completion_summary'
8
+ require_relative 'llm/embedding'
9
+ require_relative 'llm/response_headers'
10
+
11
+ module NewRelic
12
+ module Agent
13
+ class LLM
14
+ INPUT = 'input'
15
+ CONTENT = 'content'
16
+ SEGMENT_PATTERN = %r{Llm/.+/OpenAI/.+}.freeze
17
+
18
+ def self.instrumentation_enabled?
19
+ NewRelic::Agent.config[:'ai_monitoring.enabled']
20
+ end
21
+
22
+ # LLM content-related attributes are exempt from the 4095 byte limit
23
+ def self.exempt_event_attribute?(type, key)
24
+ return false unless instrumentation_enabled?
25
+
26
+ (type == NewRelic::Agent::Llm::Embedding::EVENT_NAME && key == INPUT) ||
27
+ (type == NewRelic::Agent::Llm::ChatCompletionMessage::EVENT_NAME && key == CONTENT)
28
+ end
29
+
30
+ def self.openai?
31
+ @openai ||= %i[prepend chain].include?(NewRelic::Agent.config[:'instrumentation.ruby_openai']) &&
32
+ NewRelic::Agent.config[:'ai_monitoring.enabled']
33
+ end
34
+
35
+ # Used in NetHTTP instrumentation
36
+ def self.openai_parent?(segment)
37
+ return false unless openai?
38
+
39
+ segment&.parent&.name&.match?(SEGMENT_PATTERN)
40
+ end
41
+
42
+ def self.populate_openai_response_headers(response, parent)
43
+ return unless parent.instance_variable_defined?(:@llm_event)
44
+
45
+ parent.llm_event.populate_openai_response_headers(response.to_hash)
46
+ end
47
+ end
48
+ end
49
+ end
@@ -9,8 +9,7 @@ module NewRelic
9
9
  def self.create(label, &blk)
10
10
  ::NewRelic::Agent.logger.debug("Creating AgentThread: #{label}")
11
11
  wrapped_blk = proc do
12
- if ::Thread.current[:newrelic_tracer_state] && Thread.current[:newrelic_tracer_state].current_transaction
13
- txn = ::Thread.current[:newrelic_tracer_state].current_transaction
12
+ if (txn = ::NewRelic::ThreadLocalStorage[:newrelic_tracer_state]&.current_transaction)
14
13
  ::NewRelic::Agent.logger.warn("AgentThread created with current transaction #{txn.best_name}")
15
14
  end
16
15
  begin
@@ -392,11 +392,11 @@ module NewRelic
392
392
  #
393
393
  # If ever exposed, this requires additional synchronization
394
394
  def state_for(thread)
395
- state = thread[:newrelic_tracer_state]
395
+ state = ThreadLocalStorage.get(thread, :newrelic_tracer_state)
396
396
 
397
397
  if state.nil?
398
398
  state = Tracer::State.new
399
- thread[:newrelic_tracer_state] = state
399
+ ThreadLocalStorage.set(thread, :newrelic_tracer_state, state)
400
400
  end
401
401
 
402
402
  state
@@ -405,7 +405,7 @@ module NewRelic
405
405
  alias_method :tl_state_for, :state_for
406
406
 
407
407
  def clear_state
408
- Thread.current[:newrelic_tracer_state] = nil
408
+ ThreadLocalStorage[:newrelic_tracer_state] = nil
409
409
  end
410
410
 
411
411
  alias_method :tl_clear, :clear_state
@@ -420,12 +420,12 @@ module NewRelic
420
420
 
421
421
  def thread_block_with_current_transaction(segment_name: nil, parent: nil, &block)
422
422
  parent ||= current_segment
423
- current_txn = ::Thread.current[:newrelic_tracer_state]&.current_transaction if ::Thread.current[:newrelic_tracer_state]&.is_execution_traced?
423
+ current_txn = ThreadLocalStorage[:newrelic_tracer_state]&.current_transaction if ThreadLocalStorage[:newrelic_tracer_state]&.is_execution_traced?
424
424
  proc do |*args|
425
425
  begin
426
426
  if current_txn && !current_txn.finished?
427
427
  NewRelic::Agent::Tracer.state.current_transaction = current_txn
428
- ::Thread.current[:newrelic_thread_span_parent] = parent
428
+ ThreadLocalStorage[:newrelic_thread_span_parent] = parent
429
429
  current_txn.async = true
430
430
  segment_name = "#{segment_name}/Thread#{::Thread.current.object_id}/Fiber#{::Fiber.current.object_id}" if NewRelic::Agent.config[:'thread_ids_enabled']
431
431
  segment = NewRelic::Agent::Tracer.start_segment(name: segment_name, parent: parent) if segment_name
@@ -20,7 +20,7 @@ module NewRelic
20
20
  # calculation in all other cases.
21
21
  #
22
22
  attr_reader :start_time, :end_time, :duration, :exclusive_duration, :guid, :starting_segment_key
23
- attr_accessor :name, :parent, :children_time, :transaction, :transaction_name
23
+ attr_accessor :name, :parent, :children_time, :transaction, :transaction_name, :llm_event
24
24
  attr_writer :record_metrics, :record_scoped_metric, :record_on_finish
25
25
  attr_reader :noticed_error
26
26
 
@@ -41,11 +41,11 @@ module NewRelic
41
41
 
42
42
  def thread_starting_span
43
43
  # if the previous current segment was in another thread, use the thread local parent
44
- if ::Thread.current[:newrelic_thread_span_parent] &&
44
+ if ThreadLocalStorage[:newrelic_thread_span_parent] &&
45
45
  current_segment &&
46
46
  current_segment.starting_segment_key != NewRelic::Agent::Tracer.current_segment_key
47
47
 
48
- ::Thread.current[:newrelic_thread_span_parent]
48
+ ThreadLocalStorage[:newrelic_thread_span_parent]
49
49
  end
50
50
  end
51
51
 
@@ -31,6 +31,7 @@ module NewRelic
31
31
  require 'new_relic/noticed_error'
32
32
  require 'new_relic/agent/noticeable_error'
33
33
  require 'new_relic/supportability_helper'
34
+ require 'new_relic/thread_local_storage'
34
35
 
35
36
  require 'new_relic/agent/encoding_normalizer'
36
37
  require 'new_relic/agent/stats'
@@ -62,6 +63,7 @@ module NewRelic
62
63
  require 'new_relic/agent/attribute_processing'
63
64
  require 'new_relic/agent/linking_metadata'
64
65
  require 'new_relic/agent/local_log_decorator'
66
+ require 'new_relic/agent/llm'
65
67
 
66
68
  require 'new_relic/agent/instrumentation/controller_instrumentation'
67
69
 
@@ -105,11 +107,14 @@ module NewRelic
105
107
 
106
108
  # placeholder name used when we cannot determine a transaction's name
107
109
  UNKNOWN_METRIC = '(unknown)'.freeze
110
+ LLM_FEEDBACK_MESSAGE = 'LlmFeedbackMessage'
108
111
 
109
112
  attr_reader :error_group_callback
113
+ attr_reader :llm_token_count_callback
110
114
 
111
115
  @agent = nil
112
116
  @error_group_callback = nil
117
+ @llm_token_count_callback = nil
113
118
  @logger = nil
114
119
  @tracer_lock = Mutex.new
115
120
  @tracer_queue = []
@@ -387,6 +392,92 @@ module NewRelic
387
392
  nil
388
393
  end
389
394
 
395
+ # Records user feedback events for LLM applications. This API must pass
396
+ # the current trace id as a parameter, which can be obtained using:
397
+ #
398
+ # NewRelic::Agent::Tracer.current_trace_id
399
+ #
400
+ # @param [String] ID of the trace where the chat completion(s) related
401
+ # to the feedback occurred.
402
+ #
403
+ # @param [String or Integer] Rating provided by an end user
404
+ # (ex: “Good", "Bad”, 1, 2, 5, 8, 10).
405
+ #
406
+ # @param [optional, String] Category of the feedback as provided by the
407
+ # end user (ex: “informative”, “inaccurate”).
408
+ #
409
+ # @param start_time [optional, String] Freeform text feedback from an
410
+ # end user.
411
+ #
412
+ # @param [optional, Hash] Set of key-value pairs to store any other
413
+ # desired data to submit with the feedback event.
414
+ #
415
+ # @api public
416
+ #
417
+ def record_llm_feedback_event(trace_id:,
418
+ rating:,
419
+ category: nil,
420
+ message: nil,
421
+ metadata: NewRelic::EMPTY_HASH)
422
+
423
+ record_api_supportability_metric(:record_llm_feedback_event)
424
+ unless NewRelic::Agent.config[:'distributed_tracing.enabled']
425
+ return NewRelic::Agent.logger.error('Distributed tracing must be enabled to record LLM feedback')
426
+ end
427
+
428
+ feedback_message_event = {
429
+ 'trace_id': trace_id,
430
+ 'rating': rating,
431
+ 'category': category,
432
+ 'message': message,
433
+ 'id': NewRelic::Agent::GuidGenerator.generate_guid,
434
+ 'ingest_source': NewRelic::Agent::Llm::LlmEvent::INGEST_SOURCE
435
+ }
436
+ feedback_message_event.merge!(metadata) unless metadata.empty?
437
+
438
+ NewRelic::Agent.record_custom_event(LLM_FEEDBACK_MESSAGE, feedback_message_event)
439
+ rescue ArgumentError
440
+ raise
441
+ rescue => exception
442
+ NewRelic::Agent.logger.error('record_llm_feedback_event', exception)
443
+ end
444
+
445
+ # @!endgroup
446
+
447
+ # @!group LLM callbacks
448
+
449
+ # Set a callback proc for calculating `token_count` attributes for
450
+ # LlmEmbedding and LlmChatCompletionMessage events
451
+ #
452
+ # @param callback_proc [Proc] the callback proc
453
+ #
454
+ # This method should be called only once to set a callback for
455
+ # use with all LLM token calculations. If it is called multiple times, each
456
+ # new callback will replace the old one.
457
+ #
458
+ # The proc will be called with a single hash as its input argument and
459
+ # must return an Integer representing the number of tokens used for that
460
+ # particular prompt, completion message, or embedding. Values less than or
461
+ # equal to 0 will not be attached to an event.
462
+ #
463
+ # The hash has the following keys:
464
+ #
465
+ # :model => [String] The name of the LLM model
466
+ # :content => [String] The message content or prompt
467
+ #
468
+ # @api public
469
+ #
470
+ def set_llm_token_count_callback(callback_proc)
471
+ unless callback_proc.is_a?(Proc)
472
+ NewRelic::Agent.logger.error("#{self}.#{__method__}: expected an argument of type Proc, " \
473
+ "got #{callback_proc.class}")
474
+ return
475
+ end
476
+
477
+ record_api_supportability_metric(:set_llm_token_count_callback)
478
+ @llm_token_count_callback = callback_proc
479
+ end
480
+
390
481
  # @!endgroup
391
482
 
392
483
  # @!group Manual agent configuration and startup/shutdown
@@ -23,8 +23,8 @@ module NewRelic
23
23
  CONTENT_TYPE = 'Content-Type'.freeze
24
24
  CONTENT_DISPOSITION = 'Content-Disposition'.freeze
25
25
  CONTENT_LENGTH = 'Content-Length'.freeze
26
- ATTACHMENT = 'attachment'.freeze
27
- TEXT_HTML = 'text/html'.freeze
26
+ ATTACHMENT = /attachment/.freeze
27
+ TEXT_HTML = %r{text/html}.freeze
28
28
 
29
29
  BODY_START = '<body'.freeze
30
30
  HEAD_START = '<head'.freeze
@@ -65,6 +65,10 @@ module NewRelic
65
65
  html?(headers) &&
66
66
  !attachment?(headers) &&
67
67
  !streaming?(env, headers)
68
+ rescue StandardError => e
69
+ NewRelic::Agent.logger.error('RUM instrumentation applicability check failed on exception:' \
70
+ "#{e.class} - #{e.message}")
71
+ false
68
72
  end
69
73
 
70
74
  private
@@ -100,11 +104,11 @@ module NewRelic
100
104
 
101
105
  def html?(headers)
102
106
  # needs else branch coverage
103
- headers[CONTENT_TYPE] && headers[CONTENT_TYPE].include?(TEXT_HTML) # rubocop:disable Style/SafeNavigation
107
+ headers[CONTENT_TYPE]&.match?(TEXT_HTML)
104
108
  end
105
109
 
106
110
  def attachment?(headers)
107
- headers[CONTENT_DISPOSITION]&.include?(ATTACHMENT)
111
+ headers[CONTENT_DISPOSITION]&.match?(ATTACHMENT)
108
112
  end
109
113
 
110
114
  def streaming?(env, headers)
@@ -43,9 +43,11 @@ module NewRelic
43
43
  :process_response_metadata,
44
44
  :record_custom_event,
45
45
  :record_metric,
46
+ :record_llm_feedback_event,
46
47
  :recording_web_transaction?,
47
48
  :require_test_helper,
48
49
  :set_error_group_callback,
50
+ :set_llm_token_count_callback,
49
51
  :set_segment_callback,
50
52
  :set_sql_obfuscator,
51
53
  :set_transaction_name,
@@ -0,0 +1,31 @@
1
+ # This file is distributed under New Relic's license terms.
2
+ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
3
+ # frozen_string_literal: true
4
+
5
+ module NewRelic
6
+ module ThreadLocalStorage
7
+ def self.get(thread, key)
8
+ if Agent.config[:thread_local_tracer_state]
9
+ thread.thread_variable_get(key)
10
+ else
11
+ thread[key]
12
+ end
13
+ end
14
+
15
+ def self.set(thread, key, value)
16
+ if Agent.config[:thread_local_tracer_state]
17
+ thread.thread_variable_set(key, value)
18
+ else
19
+ thread[key] = value
20
+ end
21
+ end
22
+
23
+ def self.[](key)
24
+ get(::Thread.current, key)
25
+ end
26
+
27
+ def self.[]=(key, value)
28
+ set(::Thread.current, key, value)
29
+ end
30
+ end
31
+ end
@@ -6,7 +6,7 @@
6
6
  module NewRelic
7
7
  module VERSION # :nodoc:
8
8
  MAJOR = 9
9
- MINOR = 7
9
+ MINOR = 8
10
10
  TINY = 0
11
11
 
12
12
  STRING = "#{MAJOR}.#{MINOR}.#{TINY}"
@@ -82,7 +82,7 @@ class Instrumentation < Thor
82
82
  insert_into_file(
83
83
  DEFAULT_SOURCE_LOCATION,
84
84
  config_block(name.downcase),
85
- after: ":description => 'Controls auto-instrumentation of bunny at start-up. May be one of [auto|prepend|chain|disabled].'
85
+ after: ":description => 'Controls auto-instrumentation of bunny at start-up. May be one of: `auto`, `prepend`, `chain`, `disabled`.'
86
86
  },\n"
87
87
  )
88
88
  end
@@ -9,7 +9,6 @@ module NewRelic::Agent::Instrumentation
9
9
  include NewRelic::Agent::Instrumentation::<%= @class_name %>
10
10
 
11
11
  alias_method(:<%= @method.downcase %>_without_new_relic, :<%= @method.downcase %>)
12
- alias_method(:<%= @method.downcase %>, :<%= @method.downcase %>_with_new_relic)
13
12
 
14
13
  def <%= @method.downcase %><%= "(#{@args})" unless @args.empty? %>
15
14
  <%= @method.downcase %>_with_new_relic<%= "(#{@args})" unless @args.empty? %> do
@@ -1,5 +1,4 @@
1
1
  alias_method(:<%= @method.downcase %>_without_new_relic, :<%= @method.downcase %>)
2
- alias_method(:<%= @method.downcase %>, :<%= @method.downcase %>_with_new_relic)
3
2
 
4
3
  def <%= @method.downcase %><%= "(#{@args})" unless @args.empty? %>
5
4
  <%= @method.downcase %>_with_new_relic<%= "(#{@args})" unless @args.empty? %> do