newrelic_rpm 9.7.1 → 9.8.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (33) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +30 -0
  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 +4 -4
  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/concurrent_ruby.rb +1 -0
  12. data/lib/new_relic/agent/instrumentation/net_http/instrumentation.rb +6 -0
  13. data/lib/new_relic/agent/instrumentation/ruby_openai/chain.rb +36 -0
  14. data/lib/new_relic/agent/instrumentation/ruby_openai/instrumentation.rb +197 -0
  15. data/lib/new_relic/agent/instrumentation/ruby_openai/prepend.rb +20 -0
  16. data/lib/new_relic/agent/instrumentation/ruby_openai.rb +35 -0
  17. data/lib/new_relic/agent/llm/chat_completion_message.rb +25 -0
  18. data/lib/new_relic/agent/llm/chat_completion_summary.rb +66 -0
  19. data/lib/new_relic/agent/llm/embedding.rb +60 -0
  20. data/lib/new_relic/agent/llm/llm_event.rb +95 -0
  21. data/lib/new_relic/agent/llm/response_headers.rb +80 -0
  22. data/lib/new_relic/agent/llm.rb +49 -0
  23. data/lib/new_relic/agent/threading/agent_thread.rb +1 -2
  24. data/lib/new_relic/agent/tracer.rb +5 -5
  25. data/lib/new_relic/agent/transaction/abstract_segment.rb +1 -1
  26. data/lib/new_relic/agent/transaction/tracing.rb +2 -2
  27. data/lib/new_relic/agent.rb +91 -0
  28. data/lib/new_relic/rack/browser_monitoring.rb +8 -4
  29. data/lib/new_relic/supportability_helper.rb +2 -0
  30. data/lib/new_relic/thread_local_storage.rb +31 -0
  31. data/lib/new_relic/version.rb +2 -2
  32. data/newrelic.yml +21 -1
  33. metadata +13 -2
@@ -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,8 +6,8 @@
6
6
  module NewRelic
7
7
  module VERSION # :nodoc:
8
8
  MAJOR = 9
9
- MINOR = 7
10
- TINY = 1
9
+ MINOR = 8
10
+ TINY = 0
11
11
 
12
12
  STRING = "#{MAJOR}.#{MINOR}.#{TINY}"
13
13
  end
data/newrelic.yml CHANGED
@@ -33,6 +33,18 @@ common: &default_settings
33
33
  # - a.third.event
34
34
  # active_support_custom_events_names: []
35
35
 
36
+ # If false, all LLM instrumentation (OpenAI only for now) will be disabled and no
37
+ # metrics, events, or spans will be sent. AI Monitoring is automatically disabled
38
+ # if high_security mode is enabled.
39
+ # ai_monitoring.enabled: false
40
+
41
+ # If false, LLM instrumentation (OpenAI only for now) will not capture input and
42
+ # output content on specific LLM events.
43
+ # The excluded attributes include:
44
+ # * content from LlmChatCompletionMessage events
45
+ # * input from LlmEmbedding events
46
+ # ai_monitoring.record_content.enabled: true
47
+
36
48
  # If true, enables capture of all HTTP request headers for all destinations.
37
49
  # allow_all_headers: false
38
50
 
@@ -324,7 +336,8 @@ common: &default_settings
324
336
  # error_collector.ignore_status_codes: ""
325
337
 
326
338
  # Defines the maximum number of frames in an error backtrace. Backtraces over this
327
- # amount are truncated at the beginning and end.
339
+ # amount are truncated in the middle, preserving the beginning and the end of the
340
+ # stack trace.
328
341
  # error_collector.max_backtrace_frames: 50
329
342
 
330
343
  # Defines the maximum number of TransactionError events reported per harvest
@@ -509,6 +522,10 @@ common: &default_settings
509
522
  # chain, disabled.
510
523
  # instrumentation.roda: auto
511
524
 
525
+ # Controls auto-instrumentation of the ruby-openai gem at start-up. May be one of:
526
+ # auto, prepend, chain, disabled.
527
+ # instrumentation.ruby_openai: auto
528
+
512
529
  # Controls auto-instrumentation of Sinatra at start-up. May be one of: auto,
513
530
  # prepend, chain, disabled.
514
531
  # instrumentation.sinatra: auto
@@ -704,6 +721,9 @@ common: &default_settings
704
721
  # the New Relic agent has time to report.
705
722
  # sync_startup: false
706
723
 
724
+ # If true, tracer state storage is thread-local, otherwise, fiber-local
725
+ # thread_local_tracer_state: false
726
+
707
727
  # If true, enables use of the thread profiler.
708
728
  # thread_profiler.enabled: false
709
729
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: newrelic_rpm
3
3
  version: !ruby/object:Gem::Version
4
- version: 9.7.1
4
+ version: 9.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tanna McClure
@@ -11,7 +11,7 @@ authors:
11
11
  autorequire:
12
12
  bindir: bin
13
13
  cert_chain: []
14
- date: 2024-01-25 00:00:00.000000000 Z
14
+ date: 2024-03-26 00:00:00.000000000 Z
15
15
  dependencies:
16
16
  - !ruby/object:Gem::Dependency
17
17
  name: bundler
@@ -480,6 +480,10 @@ files:
480
480
  - lib/new_relic/agent/instrumentation/roda/instrumentation.rb
481
481
  - lib/new_relic/agent/instrumentation/roda/prepend.rb
482
482
  - lib/new_relic/agent/instrumentation/roda/roda_transaction_namer.rb
483
+ - lib/new_relic/agent/instrumentation/ruby_openai.rb
484
+ - lib/new_relic/agent/instrumentation/ruby_openai/chain.rb
485
+ - lib/new_relic/agent/instrumentation/ruby_openai/instrumentation.rb
486
+ - lib/new_relic/agent/instrumentation/ruby_openai/prepend.rb
483
487
  - lib/new_relic/agent/instrumentation/sequel.rb
484
488
  - lib/new_relic/agent/instrumentation/sequel_helper.rb
485
489
  - lib/new_relic/agent/instrumentation/sidekiq.rb
@@ -513,6 +517,12 @@ files:
513
517
  - lib/new_relic/agent/internal_agent_error.rb
514
518
  - lib/new_relic/agent/javascript_instrumentor.rb
515
519
  - lib/new_relic/agent/linking_metadata.rb
520
+ - lib/new_relic/agent/llm.rb
521
+ - lib/new_relic/agent/llm/chat_completion_message.rb
522
+ - lib/new_relic/agent/llm/chat_completion_summary.rb
523
+ - lib/new_relic/agent/llm/embedding.rb
524
+ - lib/new_relic/agent/llm/llm_event.rb
525
+ - lib/new_relic/agent/llm/response_headers.rb
516
526
  - lib/new_relic/agent/local_log_decorator.rb
517
527
  - lib/new_relic/agent/log_event_aggregator.rb
518
528
  - lib/new_relic/agent/log_event_attributes.rb
@@ -644,6 +654,7 @@ files:
644
654
  - lib/new_relic/recipes/capistrano_legacy.rb
645
655
  - lib/new_relic/recipes/helpers/send_deployment.rb
646
656
  - lib/new_relic/supportability_helper.rb
657
+ - lib/new_relic/thread_local_storage.rb
647
658
  - lib/new_relic/traced_thread.rb
648
659
  - lib/new_relic/version.rb
649
660
  - lib/newrelic_rpm.rb