Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions sentry-agents/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@

[![Build Status](https://github.com/getsentry/sentry-ruby/actions/workflows/tests.yml/badge.svg)](https://github.com/getsentry/sentry-ruby/actions/workflows/tests.yml)

`sentry-agents` integrates [RubyLLM](https://github.com/crmne/ruby_llm) with Sentry.
`sentry-agents` integrates [RubyLLM](https://github.com/crmne/ruby_llm) with Sentry. Loading the gem instruments the global RubyLLM configuration when Sentry is initialized.

For an isolated RubyLLM context, install the adapter explicitly:

```ruby
context = RubyLLM.context
Sentry::Agents::RubyLLM.install(context.config)
```

## Requirements

Expand All @@ -28,4 +35,4 @@ Sentry.init do |config|
end
```

These settings only control GenAI content. HTTP body, breadcrumb, and exception-local collection have separate controls; disabling GenAI content is not a blanket redaction switch.
These settings only control GenAI content. HTTP body, breadcrumb, and exception-local collection have separate controls; disabling GenAI content is not a blanket redaction switch. With RubyLLM 2.2+, also set `RubyLLM.config.redact_error_messages = true` when inputs are disabled so provider errors do not include prompts.
10 changes: 10 additions & 0 deletions sentry-agents/lib/sentry-agents.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,21 @@
require "sentry-ruby"
require "sentry/integrable"
require "sentry/agents/version"
require "sentry/span/data_conventions"
require "sentry/agents/ruby_llm/instrumenter"

module Sentry
module Agents
extend Sentry::Integrable

register_integration name: "agents", version: Sentry::Agents::VERSION

module RubyLLM
def self.install(ruby_llm_config = ::RubyLLM.config)
Instrumenter.install(ruby_llm_config)
end
end
end
end

Sentry::Configuration.after(:configured) { Sentry::Agents::RubyLLM.install }
190 changes: 190 additions & 0 deletions sentry-agents/lib/sentry/agents/ruby_llm/instrumenter.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
# frozen_string_literal: true

require "json"
require "sentry/agents/ruby_llm/serializer"

module Sentry
module Agents
module RubyLLM
class Instrumenter
CHAT_EVENT = "chat.ruby_llm"
USAGE_EVENT = "usage.ruby_llm"
OPERATION = "gen_ai.chat"
ORIGIN = "auto.ai.ruby_llm"

def self.install(config)
config.instrumenter = new
end

def instrument(name, payload)
case name.to_s
when CHAT_EVENT
with_chat_span(payload) { yield } if block_given?
when USAGE_EVENT
update_usage(payload)
yield if block_given?
else
yield if block_given?
end
end

private

def with_chat_span(payload)
return yield unless Sentry.initialized?

if Sentry.get_current_scope.get_span
with_child_span(payload) { yield }
else
with_root_transaction(payload) { yield }
end
end

def with_child_span(payload)
Sentry.with_child_span(
op: OPERATION,
description: span_description(payload),
origin: ORIGIN
) do |span|
execute_span(span, payload) { yield }
end
end

def with_root_transaction(payload)
transaction = Sentry.start_transaction(
name: span_description(payload),
op: OPERATION,
origin: ORIGIN
)

begin
Sentry.with_scope do |scope|
scope.set_span(transaction)
execute_span(transaction, payload) { yield }
end
ensure
transaction.finish
end
end

Check failure on line 68 in sentry-agents/lib/sentry/agents/ruby_llm/instrumenter.rb

View check run for this annotation

@sentry/warden / warden: code-review

Standalone RubyLLM chats crash when tracing is disabled or another instrumenter is configured

With Sentry initialized but tracing disabled (the default) or a non-Sentry instrumenter configured, standalone RubyLLM chat calls raise instead of reaching the application block, breaking every chat operation in that configuration.
Comment on lines +53 to +68

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Standalone RubyLLM chats crash when tracing is disabled or another instrumenter is configured

With Sentry initialized but tracing disabled (the default) or a non-Sentry instrumenter configured, standalone RubyLLM chat calls raise instead of reaching the application block, breaking every chat operation in that configuration.

Evidence
  • with_chat_span calls with_root_transaction for an initialized Sentry scope with no current span; it does not guard against Sentry.start_transaction returning nil.
  • start_transaction returns nil when tracing is disabled or its instrumenter argument (:sentry by default) does not match the configured instrumenter. Tracing is disabled when no valid traces sample rate or sampler is configured.
  • scope.set_span(transaction) rejects nil, and the ensure then calls transaction.finish; the RubyLLM application block is never yielded. The tests configure a traces sample rate of 1.0, so they do not cover this path.
Also found at 1 additional location
  • sentry-agents/spec/sentry/agents/ruby_llm/instrumenter_spec.rb:39-71

Identified by Warden · code-review · 7XS-59X


def execute_span(span, payload)
set_request_data(span, payload)
yield
ensure
set_response_data(span, payload)
end

def set_request_data(span, payload)
span.set_data(Sentry::Span::DataConventions::GEN_AI_OPERATION_NAME, "chat")

if provider = provider_name(payload[:provider])
span.set_data(Sentry::Span::DataConventions::GEN_AI_PROVIDER_NAME, provider)
end

if model = payload[:model]&.to_s
span.set_data(Sentry::Span::DataConventions::GEN_AI_REQUEST_MODEL, model)
end

if temperature = payload[:temperature]
span.set_data(Sentry::Span::DataConventions::GEN_AI_REQUEST_TEMPERATURE, temperature)
end

if max_tokens = payload[:max_output_tokens]
span.set_data(Sentry::Span::DataConventions::GEN_AI_REQUEST_MAX_TOKENS, max_tokens)
end

if stream = !!payload[:streaming]
span.set_data(Sentry::Span::DataConventions::GEN_AI_REQUEST_STREAM, stream)
end

if reasoning_level = payload[:thinking]&.effort&.to_s
span.set_data(Sentry::Span::DataConventions::GEN_AI_REQUEST_REASONING_LEVEL, reasoning_level)
end

return unless collect_inputs?

system, non_system = Serializer.messages(payload[:input_messages])
if non_system.any?
span.set_data(Sentry::Span::DataConventions::GEN_AI_INPUT_MESSAGES, JSON.generate(non_system))
end
if system.any?
span.set_data(Sentry::Span::DataConventions::GEN_AI_SYSTEM_INSTRUCTIONS, JSON.generate(system))
end

definitions = Serializer.tool_definitions(payload)
if definitions.any?
span.set_data(Sentry::Span::DataConventions::GEN_AI_TOOL_DEFINITIONS, JSON.generate(definitions))
end
rescue => e
Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Failed to set RubyLLM request data: #{e}" }
end

def set_response_data(span, payload)
response = payload[:response]
response_model = payload[:response_model] || response&.model
finish_reason = response&.finish_reason

if response_model = response_model&.to_s
span.set_data(Sentry::Span::DataConventions::GEN_AI_RESPONSE_MODEL, response_model)
end

if finish_reasons = (Array(finish_reason).map(&:to_s) if finish_reason)
span.set_data(Sentry::Span::DataConventions::GEN_AI_RESPONSE_FINISH_REASONS, finish_reasons)
end

return unless collect_outputs? && response

messages = [Serializer.normalize_message(response)]
if messages.any?
span.set_data(Sentry::Span::DataConventions::GEN_AI_OUTPUT_MESSAGES, JSON.generate(messages))
end
rescue => e
Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Failed to set RubyLLM response data: #{e}" }
end

def update_usage(payload)
return unless Sentry.initialized?

span = Sentry.get_current_scope&.get_span
return unless span&.op == OPERATION

tokens = payload[:tokens]
return unless tokens

input_tokens = [tokens.input, tokens.cache_read, tokens.cache_write].compact
add_usage(span, Sentry::Span::DataConventions::GEN_AI_USAGE_INPUT_TOKENS, input_tokens.sum) unless input_tokens.empty?
add_usage(span, Sentry::Span::DataConventions::GEN_AI_USAGE_OUTPUT_TOKENS, tokens.output)
add_usage(span, Sentry::Span::DataConventions::GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, tokens.cache_read)
add_usage(span, Sentry::Span::DataConventions::GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, tokens.cache_write)
add_usage(span, Sentry::Span::DataConventions::GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, tokens.thinking)
rescue => e
Sentry.sdk_logger.debug(Sentry::LOGGER_PROGNAME) { "Failed to update RubyLLM usage: #{e}" }
end

def add_usage(span, key, value)
return if value.nil?

previous = span.data[key]
span.set_data(key, previous.nil? ? value : previous + value)
end

def span_description(payload)
model = payload[:model]
model ? "chat #{model}" : "chat"
end

def provider_name(provider)
::RubyLLM::OpenTelemetry::Attributes.provider_name(provider)
end

def collect_inputs?
Sentry.configuration.data_collection.gen_ai.inputs
end

def collect_outputs?
Sentry.configuration.data_collection.gen_ai.outputs
end
end
end
end
end
65 changes: 65 additions & 0 deletions sentry-agents/lib/sentry/agents/ruby_llm/serializer.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# frozen_string_literal: true

module Sentry
module Agents
module RubyLLM
module Serializer
module_function

def messages(messages)
system, non_system = Array(messages).partition { |message| message.role == :system }

[
system.flat_map { |message| parts(message) },
non_system.map { |message| normalize_message(message) }
]
end

def tool_definitions(payload)
definitions = payload[:chat].tools.values.map do |tool|
{
name: tool.name,
description: tool.description,
parameters: tool.parameters_schema
}.compact
end

definitions + payload[:provider_tools]
end

def normalize_message(message)
role = normalize_role(message.role)
{ role: role, parts: parts(message) }
end

def parts(message)
case normalize_role(message.role)
when "tool"
[{ type: "tool_call_response", id: message.tool_call_id, response: message.content }]
else
result = []
result << { type: "text", content: message.content } unless message.content.nil?
message.tool_calls.each do |tool_call|
result << {
type: "tool_call",
id: tool_call.id,
name: tool_call.name,
arguments: tool_call.arguments
}.compact
end

Check warning on line 49 in sentry-agents/lib/sentry/agents/ruby_llm/serializer.rb

View check run for this annotation

@sentry/warden / warden: code-review

parts iterates tool_calls Hash as ToolCall objects

Non-empty `message.tool_calls` are a Hash of id=&gt;ToolCall, so one-arg `each` yields `[id, tool_call]` arrays and `.id`/`.name` raise; request/response message attributes are then dropped by the instrumenter rescue.
Comment on lines +42 to +49

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parts iterates tool_calls Hash as ToolCall objects

Non-empty message.tool_calls are a Hash of id=>ToolCall, so one-arg each yields [id, tool_call] arrays and .id/.name raise; request/response message attributes are then dropped by the instrumenter rescue.

Evidence
  • parts does message.tool_calls.each do |tool_call| then reads tool_call.id/name/arguments.
  • RubyLLM stores tool_calls as a Hash (default {}); Hash #each with one block arg yields [key, value], not the ToolCall.
  • The same serializer correctly uses payload[:chat].tools.values for the tools Hash, showing the intended pattern.
  • Instrumenter#set_request_data / #set_response_data call Serializer.messages / normalize_message inside rescue, so a tool-call message drops gen_ai.input.messages / gen_ai.output.messages instead of recording them.
  • Specs only exercise empty tool_calls, so this path is untested.

Identified by Warden · code-review · W8J-BVU

result
end
end

def normalize_role(role)
case role.to_s
when "human" then "user"
when "ai" then "assistant"
when "function" then "tool"
else role.to_s
end
end
end
end
end
end
26 changes: 26 additions & 0 deletions sentry-agents/lib/sentry/span/data_conventions.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# frozen_string_literal: true

module Sentry
class Span
module DataConventions
GEN_AI_OPERATION_NAME = "gen_ai.operation.name"
GEN_AI_PROVIDER_NAME = "gen_ai.provider.name"
GEN_AI_REQUEST_MODEL = "gen_ai.request.model"
GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"
GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"
GEN_AI_REQUEST_STREAM = "gen_ai.request.stream"
GEN_AI_REQUEST_REASONING_LEVEL = "gen_ai.request.reasoning.level"
GEN_AI_INPUT_MESSAGES = "gen_ai.input.messages"
GEN_AI_SYSTEM_INSTRUCTIONS = "gen_ai.system_instructions"
GEN_AI_TOOL_DEFINITIONS = "gen_ai.tool.definitions"
GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"
GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"
GEN_AI_OUTPUT_MESSAGES = "gen_ai.output.messages"
GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"
GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"
GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS = "gen_ai.usage.cache_read.input_tokens"
GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS = "gen_ai.usage.cache_creation.input_tokens"
GEN_AI_USAGE_REASONING_OUTPUT_TOKENS = "gen_ai.usage.reasoning.output_tokens"
end
end
end
Loading
Loading