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