diff --git a/sentry-agents/README.md b/sentry-agents/README.md index 658634cf4..cf8f8aa1a 100644 --- a/sentry-agents/README.md +++ b/sentry-agents/README.md @@ -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 @@ -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. diff --git a/sentry-agents/lib/sentry-agents.rb b/sentry-agents/lib/sentry-agents.rb index 6a0804189..2bbaf7b51 100644 --- a/sentry-agents/lib/sentry-agents.rb +++ b/sentry-agents/lib/sentry-agents.rb @@ -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 } diff --git a/sentry-agents/lib/sentry/agents/ruby_llm/instrumenter.rb b/sentry-agents/lib/sentry/agents/ruby_llm/instrumenter.rb new file mode 100644 index 000000000..483f5a914 --- /dev/null +++ b/sentry-agents/lib/sentry/agents/ruby_llm/instrumenter.rb @@ -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 + + 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 diff --git a/sentry-agents/lib/sentry/agents/ruby_llm/serializer.rb b/sentry-agents/lib/sentry/agents/ruby_llm/serializer.rb new file mode 100644 index 000000000..b6bb308d3 --- /dev/null +++ b/sentry-agents/lib/sentry/agents/ruby_llm/serializer.rb @@ -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 + 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 diff --git a/sentry-agents/lib/sentry/span/data_conventions.rb b/sentry-agents/lib/sentry/span/data_conventions.rb new file mode 100644 index 000000000..92b83e5d1 --- /dev/null +++ b/sentry-agents/lib/sentry/span/data_conventions.rb @@ -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 diff --git a/sentry-agents/spec/sentry/agents/ruby_llm/instrumenter_spec.rb b/sentry-agents/spec/sentry/agents/ruby_llm/instrumenter_spec.rb new file mode 100644 index 000000000..08f530958 --- /dev/null +++ b/sentry-agents/spec/sentry/agents/ruby_llm/instrumenter_spec.rb @@ -0,0 +1,192 @@ +# frozen_string_literal: true + +require "spec_helper" +require "json" + +RSpec.describe Sentry::Agents::RubyLLM::Instrumenter do + before do + RubyLLM.config.instrumenter = nil + Sentry.init do |config| + config.dsn = Sentry::TestHelper::DUMMY_DSN + config.sdk_logger = Logger.new(nil) + config.background_worker_threads = 0 + config.transport.transport_class = Sentry::DummyTransport + config.traces_sample_rate = 1.0 + config.data_collection.gen_ai.inputs = true + config.data_collection.gen_ai.outputs = true + end + end + + after do + RubyLLM.config.instrumenter = nil + end + + it "installs idempotently during Sentry initialization" do + instrumenter = RubyLLM.config.instrumenter + + expect(instrumenter).to be_a(described_class) + end + + it "installs on an isolated RubyLLM context" do + context = RubyLLM.context + context.config.instrumenter = nil + + Sentry::Agents::RubyLLM.install(context.config) + + expect(context.config.instrumenter).to be_a(described_class) + end + + it "creates a standalone chat transaction and serializes content" do + response = message(role: :assistant, content: "Paris", model: "gpt-4o", finish_reason: :stop) + payload = chat_payload + + result = instrument(described_class.new, "chat.ruby_llm", payload) do |event| + event[:response] = response + "result" + end + + expect(result).to eq("result") + + event = transaction_event + data = model_data(event) + expect(event.transaction).to eq("chat gpt-4o") + expect(model_op(event)).to eq("gen_ai.chat") + expect(model_description(event)).to eq("chat gpt-4o") + expect(data["gen_ai.operation.name"]).to eq("chat") + expect(data["gen_ai.provider.name"]).to eq("openai") + expect(data["gen_ai.request.model"]).to eq("gpt-4o") + expect(data["gen_ai.request.temperature"]).to eq(0.2) + expect(data["gen_ai.request.max_tokens"]).to eq(20) + expect(JSON.parse(data["gen_ai.input.messages"])).to eq( + [{ "role" => "user", "parts" => [{ "type" => "text", "content" => "hello" }] }] + ) + expect(JSON.parse(data["gen_ai.system_instructions"])).to eq( + [{ "type" => "text", "content" => "Be concise" }] + ) + expect(JSON.parse(data["gen_ai.output.messages"])).to eq( + [{ "role" => "assistant", "parts" => [{ "type" => "text", "content" => "Paris" }] }] + ) + expect(data["gen_ai.response.model"]).to eq("gpt-4o") + expect(data["gen_ai.response.finish_reasons"]).to eq(["stop"]) + end + + it "records semantic provider, streaming, and reasoning attributes" do + payload = chat_payload( + provider: "bedrock", + streaming: true, + thinking: RubyLLM::Thinking::Config.new(effort: :high) + ) + + instrument(described_class.new, "chat.ruby_llm", payload) { |event| event[:response] = message } + + data = model_data(transaction_event) + expect(data["gen_ai.provider.name"]).to eq("aws.bedrock") + expect(data["gen_ai.request.stream"]).to be(true) + expect(data["gen_ai.request.reasoning.level"]).to eq("high") + end + + it "keeps model spans as children of an existing transaction and restores scope" do + parent = Sentry.start_transaction(name: "parent", op: "test") + Sentry.get_current_scope.set_span(parent) + + instrument(described_class.new, "chat.ruby_llm", chat_payload) { :result } + + expect(Sentry.get_current_scope.get_span).to eq(parent) + parent.finish + + event = transaction_event + expect(event.transaction).to eq("parent") + expect(event.spans.size).to eq(1) + expect(event.spans.first[:op]).to eq("gen_ai.chat") + end + + it "records usage attempts without using response tokens" do + response = message(role: :assistant, content: "done", tokens: RubyLLM::Tokens.new(input: 999, output: 999)) + adapter = described_class.new + + instrument(adapter, "chat.ruby_llm", chat_payload) do |event| + instrument(adapter, "usage.ruby_llm", tokens: RubyLLM::Tokens.new(input: 10, output: 4, cache_read: 2, cache_write: 3, thinking: 1)) + instrument(adapter, "usage.ruby_llm", tokens: RubyLLM::Tokens.new(input: 0, output: 2, cache_read: 0, cache_write: 0, thinking: 0)) + event[:response] = response + end + + data = model_data(transaction_event) + expect(data["gen_ai.usage.input_tokens"]).to eq(15) + expect(data["gen_ai.usage.output_tokens"]).to eq(6) + expect(data["gen_ai.usage.cache_read.input_tokens"]).to eq(2) + expect(data["gen_ai.usage.cache_creation.input_tokens"]).to eq(3) + expect(data["gen_ai.usage.reasoning.output_tokens"]).to eq(1) + end + + it "gates input and output content independently" do + Sentry.configuration.data_collection.gen_ai.inputs = false + Sentry.configuration.data_collection.gen_ai.outputs = false + response = message(role: :assistant, content: "secret") + + instrument(described_class.new, "chat.ruby_llm", chat_payload) do |event| + event[:response] = response + end + + data = model_data(transaction_event) + expect(data).not_to have_key("gen_ai.input.messages") + expect(data).not_to have_key("gen_ai.system_instructions") + expect(data).not_to have_key("gen_ai.output.messages") + expect(data["gen_ai.request.model"]).to eq("gpt-4o") + end + + it "passes through uninstrumented events and application exceptions" do + adapter = described_class.new + + expect(instrument(adapter, "request.ruby_llm", {}) { :result }).to eq(:result) + + expect do + instrument(adapter, "chat.ruby_llm", chat_payload) { raise "boom" } + end.to raise_error(RuntimeError, "boom") + + expect(transaction_event.transaction).to eq("chat gpt-4o") + end + + def instrument(adapter, name, payload, &block) + return adapter.instrument(name, payload) unless block + + adapter.instrument(name, payload) { block.call(payload) } + end + + def model_data(event) + event.spans.first&.fetch(:data) || event.contexts[:trace][:data] + end + + def model_op(event) + event.spans.first&.fetch(:op) || event.contexts[:trace][:op] + end + + def model_description(event) + event.spans.first&.fetch(:description) || event.transaction + end + + def transaction_event + Sentry.get_current_client.flush + sentry_events.find { |event| event.is_a?(Sentry::TransactionEvent) } + end + + def chat_payload(provider: "openai", streaming: false, thinking: nil) + { + chat: Struct.new(:tools).new({}), + provider_tools: [], + provider: provider, + model: "gpt-4o", + input_messages: [ + message(role: :system, content: "Be concise"), + message(role: :user, content: "hello") + ], + temperature: 0.2, + max_output_tokens: 20, + streaming: streaming, + thinking: thinking + } + end + + def message(**attributes) + RubyLLM::Message.new({ role: :user, content: "message" }.merge(attributes)) + end +end