<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css"
        integrity="sha512-SzlrxWUlpfuzQ+pcUCosxcglQRNAq/DZjVsC0lE40xsADsfeQoEypE+enwcOiGjk/bSuGGKHEyjSoQ1zVisanQ=="
        crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
</html>
from functools import wraps
from typing import TYPE_CHECKING

import sentry_sdk
from sentry_sdk.consts import SPANSTATUS

if TYPE_CHECKING:
    from typing import Any


def _patch_error_tracing() -> None:
    """
    Patches agents error tracing function to inject our span error logic
    when a tool execution fails.

    In newer versions, the function is at: agents.util._error_tracing.attach_error_to_current_span
    In older versions, it was at: agents._utils.attach_error_to_current_span

    This works even when the module or function doesn't exist.
    """
    error_tracing_module = None

    # Try newer location first (agents.util._error_tracing)
    try:
        from agents.util import _error_tracing

        error_tracing_module = _error_tracing
    except (ImportError, AttributeError):
        pass

    # Try older location (agents._utils)
    if error_tracing_module is None:
        try:
            import agents._utils

            error_tracing_module = agents._utils
        except (ImportError, AttributeError):
            # Module doesn't exist in either location, nothing to patch
            return

    # Check if the function exists
    if not hasattr(error_tracing_module, "attach_error_to_current_span"):
        return

    original_attach_error = error_tracing_module.attach_error_to_current_span

    @wraps(original_attach_error)
    def sentry_attach_error_to_current_span(
        error: "Any", *args: "Any", **kwargs: "Any"
    ) -> "Any":
        """
        Wraps agents' error attachment to also set Sentry span status to error.
        This allows us to properly track tool execution errors even though
        the agents library swallows exceptions.
        """
        # Set the current Sentry span to errored
        current_span = sentry_sdk.get_current_span()
        if current_span is not None:
            current_span.set_status(SPANSTATUS.INTERNAL_ERROR)

        # Call the original function
        return original_attach_error(error, *args, **kwargs)

    error_tracing_module.attach_error_to_current_span = (
        sentry_attach_error_to_current_span
    )
