|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from functools import wraps |
| 4 | + |
| 5 | +from sentry_sdk.integrations import DidNotEnable |
| 6 | + |
| 7 | +from ..spans import invoke_agent_span, update_invoke_agent_span, handoff_span |
| 8 | + |
| 9 | +from typing import TYPE_CHECKING |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from typing import Any, Optional |
| 13 | + |
| 14 | + |
| 15 | +try: |
| 16 | + import agents |
| 17 | +except ImportError: |
| 18 | + raise DidNotEnable("OpenAI Agents not installed") |
| 19 | + |
| 20 | + |
| 21 | +def _patch_agent_run() -> None: |
| 22 | + """ |
| 23 | + Patches AgentRunner methods to create agent invocation spans. |
| 24 | + This directly patches the execution flow to track when agents start and stop. |
| 25 | + """ |
| 26 | + |
| 27 | + # Store original methods |
| 28 | + original_run_single_turn = agents.run.AgentRunner._run_single_turn |
| 29 | + original_execute_handoffs = agents._run_impl.RunImpl.execute_handoffs |
| 30 | + original_execute_final_output = agents._run_impl.RunImpl.execute_final_output |
| 31 | + |
| 32 | + def _start_invoke_agent_span( |
| 33 | + context_wrapper: agents.RunContextWrapper, agent: agents.Agent |
| 34 | + ) -> None: |
| 35 | + """Start an agent invocation span""" |
| 36 | + # Store the agent on the context wrapper so we can access it later |
| 37 | + context_wrapper._sentry_current_agent = agent |
| 38 | + invoke_agent_span(context_wrapper, agent) |
| 39 | + |
| 40 | + def _end_invoke_agent_span( |
| 41 | + context_wrapper: agents.RunContextWrapper, |
| 42 | + agent: agents.Agent, |
| 43 | + output: Optional[Any] = None, |
| 44 | + ) -> None: |
| 45 | + """End the agent invocation span""" |
| 46 | + # Clear the stored agent |
| 47 | + if hasattr(context_wrapper, "_sentry_current_agent"): |
| 48 | + delattr(context_wrapper, "_sentry_current_agent") |
| 49 | + |
| 50 | + update_invoke_agent_span(context_wrapper, agent, output) |
| 51 | + |
| 52 | + def _has_active_agent_span(context_wrapper: agents.RunContextWrapper) -> bool: |
| 53 | + """Check if there's an active agent span for this context""" |
| 54 | + return getattr(context_wrapper, "_sentry_current_agent", None) is not None |
| 55 | + |
| 56 | + def _get_current_agent( |
| 57 | + context_wrapper: agents.RunContextWrapper, |
| 58 | + ) -> Optional[agents.Agent]: |
| 59 | + """Get the current agent from context wrapper""" |
| 60 | + return getattr(context_wrapper, "_sentry_current_agent", None) |
| 61 | + |
| 62 | + @wraps( |
| 63 | + original_run_single_turn.__func__ |
| 64 | + if hasattr(original_run_single_turn, "__func__") |
| 65 | + else original_run_single_turn |
| 66 | + ) |
| 67 | + async def patched_run_single_turn( |
| 68 | + cls: agents.Runner, *args: Any, **kwargs: Any |
| 69 | + ) -> Any: |
| 70 | + """Patched _run_single_turn that creates agent invocation spans""" |
| 71 | + agent = kwargs.get("agent") |
| 72 | + context_wrapper = kwargs.get("context_wrapper") |
| 73 | + should_run_agent_start_hooks = kwargs.get("should_run_agent_start_hooks") |
| 74 | + |
| 75 | + # Start agent span when agent starts (but only once per agent) |
| 76 | + if should_run_agent_start_hooks and agent and context_wrapper: |
| 77 | + # End any existing span for a different agent |
| 78 | + if _has_active_agent_span(context_wrapper): |
| 79 | + current_agent = _get_current_agent(context_wrapper) |
| 80 | + if current_agent and current_agent != agent: |
| 81 | + _end_invoke_agent_span(context_wrapper, current_agent) |
| 82 | + |
| 83 | + _start_invoke_agent_span(context_wrapper, agent) |
| 84 | + |
| 85 | + # Call original method with all the correct parameters |
| 86 | + try: |
| 87 | + result = await original_run_single_turn(*args, **kwargs) |
| 88 | + finally: |
| 89 | + if agent and context_wrapper and _has_active_agent_span(context_wrapper): |
| 90 | + _end_invoke_agent_span(context_wrapper, agent) |
| 91 | + |
| 92 | + return result |
| 93 | + |
| 94 | + @wraps( |
| 95 | + original_execute_handoffs.__func__ |
| 96 | + if hasattr(original_execute_handoffs, "__func__") |
| 97 | + else original_execute_handoffs |
| 98 | + ) |
| 99 | + async def patched_execute_handoffs( |
| 100 | + cls: agents.Runner, *args: Any, **kwargs: Any |
| 101 | + ) -> Any: |
| 102 | + """Patched execute_handoffs that creates handoff spans and ends agent span for handoffs""" |
| 103 | + context_wrapper = kwargs.get("context_wrapper") |
| 104 | + run_handoffs = kwargs.get("run_handoffs") |
| 105 | + agent = kwargs.get("agent") |
| 106 | + |
| 107 | + # Create Sentry handoff span for the first handoff (agents library only processes the first one) |
| 108 | + if run_handoffs: |
| 109 | + first_handoff = run_handoffs[0] |
| 110 | + handoff_agent_name = first_handoff.handoff.agent_name |
| 111 | + handoff_span(context_wrapper, agent, handoff_agent_name) |
| 112 | + |
| 113 | + # Call original method with all parameters |
| 114 | + try: |
| 115 | + result = await original_execute_handoffs(*args, **kwargs) |
| 116 | + |
| 117 | + finally: |
| 118 | + # End span for current agent after handoff processing is complete |
| 119 | + if agent and context_wrapper and _has_active_agent_span(context_wrapper): |
| 120 | + _end_invoke_agent_span(context_wrapper, agent) |
| 121 | + |
| 122 | + return result |
| 123 | + |
| 124 | + @wraps( |
| 125 | + original_execute_final_output.__func__ |
| 126 | + if hasattr(original_execute_final_output, "__func__") |
| 127 | + else original_execute_final_output |
| 128 | + ) |
| 129 | + async def patched_execute_final_output( |
| 130 | + cls: agents.Runner, *args: Any, **kwargs: Any |
| 131 | + ) -> Any: |
| 132 | + """Patched execute_final_output that ends agent span for final outputs""" |
| 133 | + agent = kwargs.get("agent") |
| 134 | + context_wrapper = kwargs.get("context_wrapper") |
| 135 | + final_output = kwargs.get("final_output") |
| 136 | + |
| 137 | + # Call original method with all parameters |
| 138 | + try: |
| 139 | + result = await original_execute_final_output(*args, **kwargs) |
| 140 | + finally: |
| 141 | + # End span for current agent after final output processing is complete |
| 142 | + if agent and context_wrapper and _has_active_agent_span(context_wrapper): |
| 143 | + _end_invoke_agent_span(context_wrapper, agent, final_output) |
| 144 | + |
| 145 | + return result |
| 146 | + |
| 147 | + # Apply patches |
| 148 | + agents.run.AgentRunner._run_single_turn = classmethod(patched_run_single_turn) |
| 149 | + agents._run_impl.RunImpl.execute_handoffs = classmethod(patched_execute_handoffs) |
| 150 | + agents._run_impl.RunImpl.execute_final_output = classmethod( |
| 151 | + patched_execute_final_output |
| 152 | + ) |
0 commit comments