Repository navigation
feat(agents): Instrument RubyLLM agent runs #3186
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,194 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require "ruby_llm/agent" | ||
| require "ruby_llm/chat" | ||
|
|
||
| module Sentry | ||
| module Agents | ||
| module RubyLLM | ||
| module AgentRuns | ||
| AGENT_NAME_IVAR = :@sentry_agents_agent_name | ||
| DEPTH_IVAR = :@sentry_agents_agent_run_depth | ||
| OPERATION = "gen_ai.invoke_agent" | ||
| ORIGIN = "auto.ai.ruby_llm" | ||
|
|
||
| module AgentIdentityPatch | ||
| def apply_configuration(chat, input_values:, persist_instructions:, **options) | ||
| result = super(chat, input_values: input_values, persist_instructions: persist_instructions, **options) | ||
| chat.instance_variable_set(AGENT_NAME_IVAR, name.to_s) | ||
| result | ||
| end | ||
| end | ||
|
|
||
| module ChatPatch | ||
| def complete(*args, **kwargs, &block) | ||
| AgentRuns.with(self) { super(*args, **kwargs, &block) } | ||
| end | ||
|
|
||
| def generate(*args, **kwargs, &block) | ||
| AgentRuns.with(self) { super(*args, **kwargs, &block) } | ||
| end | ||
|
|
||
| def run_tools(*args, **kwargs, &block) | ||
| AgentRuns.with(self) { super(*args, **kwargs, &block) } | ||
| end | ||
|
|
||
| def step(*args, **kwargs, &block) | ||
| AgentRuns.with(self) { super(*args, **kwargs, &block) } | ||
| end | ||
| end | ||
|
|
||
| class << self | ||
| def install | ||
| install_agent_identity | ||
| install_chat_patch | ||
| end | ||
|
|
||
| def with(chat) | ||
| agent_name = chat.instance_variable_get(AGENT_NAME_IVAR) | ||
| return yield if agent_name.nil? || agent_name.empty? | ||
|
|
||
| depth = chat.instance_variable_get(DEPTH_IVAR).to_i | ||
| return yield if depth.positive? | ||
|
|
||
| chat.instance_variable_set(DEPTH_IVAR, depth + 1) | ||
| with_span(chat, agent_name) { yield } | ||
| ensure | ||
| if depth&.positive? | ||
| depth.zero? ? chat.remove_instance_variable(DEPTH_IVAR) : chat.instance_variable_set(DEPTH_IVAR, depth) | ||
| end | ||
| end | ||
|
|
||
| private | ||
|
|
||
| def install_agent_identity | ||
| target = ::RubyLLM::Agent.singleton_class | ||
| target.prepend(AgentIdentityPatch) unless target.ancestors.include?(AgentIdentityPatch) | ||
| end | ||
|
|
||
| def install_chat_patch | ||
| target = ::RubyLLM::Chat | ||
| target.prepend(ChatPatch) unless target.ancestors.include?(ChatPatch) | ||
| end | ||
|
|
||
| def with_span(chat, agent_name) | ||
| return yield unless Sentry.initialized? | ||
|
|
||
| scope = Sentry.get_current_scope | ||
| current_span = scope&.get_span | ||
| if current_span | ||
| with_child_span(scope, current_span, chat, agent_name) { yield } | ||
| else | ||
| with_root_transaction(chat, agent_name) { yield } | ||
| end | ||
| end | ||
|
|
||
| def with_child_span(scope, current_span, chat, agent_name) | ||
| span = nil | ||
| begin | ||
| span = current_span.start_child(op: OPERATION, description: description(agent_name), origin: ORIGIN) | ||
| scope.set_span(span) | ||
| rescue StandardError => error | ||
| safe_finish(span) | ||
| report(error) | ||
| return yield | ||
| end | ||
|
|
||
| execute_span(span, scope: scope, previous_span: current_span, chat: chat, agent_name: agent_name) { yield } | ||
| end | ||
|
|
||
| def with_root_transaction(chat, agent_name) | ||
| transaction = begin | ||
| Sentry.start_transaction(name: description(agent_name), op: OPERATION, origin: ORIGIN) | ||
| rescue StandardError => error | ||
| report(error) | ||
| nil | ||
| end | ||
| return yield unless transaction | ||
|
|
||
| application_called = false | ||
| begin | ||
| Sentry.with_scope do |scope| | ||
| scope.set_span(transaction) | ||
| execute_span(transaction, chat: chat, agent_name: agent_name) do | ||
| application_called = true | ||
| yield | ||
| end | ||
| end | ||
| rescue StandardError => error | ||
| raise if application_called | ||
|
|
||
| safe_finish(transaction) | ||
| report(error) | ||
| yield | ||
| end | ||
| end | ||
|
|
||
| def execute_span(span, chat:, agent_name:, scope: nil, previous_span: nil) | ||
| result = nil | ||
| begin | ||
| set_data(span, chat, agent_name) | ||
| result = yield | ||
| rescue StandardError => error | ||
| set_error(span, error) | ||
| raise | ||
| ensure | ||
| safe_restore_scope(scope, previous_span) if scope && previous_span | ||
| safe_finish(span) | ||
| end | ||
| result | ||
| end | ||
|
|
||
| def set_data(span, chat, agent_name) | ||
| span.set_data("gen_ai.operation.name", "invoke_agent") | ||
| span.set_data("gen_ai.agent.name", agent_name) | ||
| workflow = ::RubyLLM::Support::Instrumentation.current_workflow | ||
| pipeline = workflow && workflow[:workflow_name] | ||
| span.set_data("gen_ai.pipeline.name", pipeline) if pipeline | ||
| rescue StandardError => error | ||
| report(error) | ||
| end | ||
|
|
||
| def set_error(span, error) | ||
| safe_set_data(span, "error.type", error.class.name) | ||
| safe_set_status(span, "internal_error") | ||
| end | ||
|
|
||
| def safe_set_data(span, key, value) | ||
| span.set_data(key, value) | ||
| rescue StandardError => error | ||
| report(error) | ||
| end | ||
|
|
||
| def safe_set_status(span, status) | ||
| span.set_status(status) | ||
| rescue StandardError => error | ||
| report(error) | ||
| end | ||
|
|
||
| def safe_restore_scope(scope, span) | ||
| scope.set_span(span) | ||
| rescue StandardError => error | ||
| report(error) | ||
| end | ||
|
|
||
| def safe_finish(span) | ||
| span&.finish | ||
| rescue StandardError => error | ||
| report(error) | ||
| end | ||
|
|
||
| def report(error) | ||
| Sentry.configuration.sdk_logger.debug("sentry-agents instrumentation failed: #{error.class}: #{error.message}") | ||
| rescue StandardError | ||
| nil | ||
| end | ||
|
|
||
| def description(agent_name) | ||
| "invoke_agent #{agent_name}" | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
107 changes: 107 additions & 0 deletions
107
sentry-agents/spec/sentry/agents/ruby_llm/agent_runs_spec.rb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| # frozen_string_literal: true | ||
|
|
||
| require "spec_helper" | ||
|
|
||
| RSpec.describe Sentry::Agents::RubyLLM::AgentRuns do | ||
| before do | ||
| RubyLLM.config.instrumenter = nil | ||
| RubyLLM.configure { |config| config.openai_api_key = "test" } | ||
| 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 "creates one invoke_agent span with model and tool descendants" do | ||
| agent_class = agent_class("SupportAgent") | ||
| chat = agent_class.chat | ||
| adapter = Sentry::Agents::RubyLLM::Instrumenter.new(nil) | ||
|
|
||
| result = described_class.with(chat) do | ||
| adapter.instrument("chat.ruby_llm", chat_payload(chat)) { :model_result } | ||
| adapter.instrument("tool_call.ruby_llm", tool_payload(chat)) { :tool_result } | ||
| :agent_result | ||
| end | ||
|
|
||
| expect(result).to eq(:agent_result) | ||
| event = transaction_event | ||
| root_trace = event.contexts[:trace] | ||
| spans = event.spans | ||
|
|
||
| expect(root_trace[:op]).to eq("gen_ai.invoke_agent") | ||
| expect(root_trace[:data]["gen_ai.agent.name"]).to eq("SupportAgent") | ||
| expect(spans.map { |span| span[:op] }).to contain_exactly("gen_ai.chat", "gen_ai.execute_tool") | ||
| expect(spans.map { |span| span[:data]["gen_ai.agent.name"] }).to all(eq("SupportAgent")) | ||
| expect(spans.map { |span| span[:parent_span_id] }).to all(eq(root_trace[:span_id])) | ||
| end | ||
|
|
||
| it "suppresses duplicate wrappers for the same chat and keeps nested agents" do | ||
| outer_class = agent_class("OuterAgent") | ||
| inner_class = agent_class("InnerAgent") | ||
| outer_chat = outer_class.chat | ||
| inner_chat = inner_class.chat | ||
|
|
||
| described_class.with(outer_chat) do | ||
| described_class.with(outer_chat) { :same_chat } | ||
| described_class.with(inner_chat) { :nested_chat } | ||
| end | ||
|
|
||
| event = transaction_event | ||
| root_trace = event.contexts[:trace] | ||
| invoke_spans = event.spans.select { |span| span[:op] == "gen_ai.invoke_agent" } | ||
|
|
||
| expect(invoke_spans.size).to eq(1) | ||
| expect(invoke_spans.first[:data]["gen_ai.agent.name"]).to eq("InnerAgent") | ||
| expect(invoke_spans.first[:parent_span_id]).to eq(root_trace[:span_id]) | ||
| end | ||
|
|
||
| it "finishes the invoke_agent span when the operation raises" do | ||
| chat = agent_class("FailingAgent").chat | ||
|
|
||
| expect do | ||
| described_class.with(chat) { raise "agent failure" } | ||
| end.to raise_error(RuntimeError, "agent failure") | ||
|
|
||
| event = transaction_event | ||
| trace = event.contexts[:trace] | ||
| expect(trace[:status]).to eq("internal_error") | ||
| expect(trace[:data]["error.type"]).to eq("RuntimeError") | ||
| end | ||
|
|
||
| def agent_class(name) | ||
| stub_const(name, Class.new(RubyLLM::Agent)).tap do |klass| | ||
| klass.model "gpt-4o" | ||
| end | ||
| end | ||
|
|
||
| def chat_payload(chat) | ||
| { | ||
| chat: chat, | ||
| provider: "openai", | ||
| model: "gpt-4o", | ||
| input_messages: [] | ||
| } | ||
| end | ||
|
|
||
| def tool_payload(chat) | ||
| { | ||
| chat: chat, | ||
| tool_name: "weather", | ||
| tool_arguments: { city: "Paris" } | ||
| } | ||
| end | ||
|
|
||
| def transaction_event | ||
| Sentry.get_current_client.flush | ||
| sentry_events.find { |event| event.is_a?(Sentry::TransactionEvent) } | ||
| end | ||
| end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agent run depth never resets
High Severity
The
ensureinwithonly restores depth whendepthis already positive, so the outer wrapper never clears@sentry_agents_agent_run_depth. After the first run, later calls on the same chat skipgen_ai.invoke_agentspans, including follow-up turns on a reused agent chat.Reviewed by Cursor Bugbot for commit 18541b7. Configure here.