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 }
191 changes: 191 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,191 @@
# 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
)
return yield unless transaction

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

Check warning 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 chat exceptions leave the root transaction status unset

When RubyLLM raises during a standalone chat, the root `gen_ai.chat` transaction is finished with no error status, so its trace status does not identify the operation as failed.
end
Comment thread
sentry-warden[bot] marked this conversation as resolved.
Resolved

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
85 changes: 85 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,85 @@
# 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|
{
type: "function",
name: tool.name.to_s,
description: tool.description,
parameters: tool.parameters_schema
}.compact
end

definitions + provider_tool_definitions(payload[:provider_tools])
end

def provider_tool_definitions(provider_tools)
Array(provider_tools).filter_map do |entry|
definition = entry[:raw] || entry
type = definition[:type]
name = definition[:name]

if type.to_s == "function" && (function = definition[:function])
{
type: "function",
name: function[:name],
description: function[:description],
parameters: function[:parameters]
}.compact
elsif name
{ type: (type || name).to_s, name: name.to_s }
end
end
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
Comment thread
sentry-warden[bot] marked this conversation as resolved.
Resolved
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