def _track_costs(
        __func: asynchro_utils.CallableMaybeAwaitable[A, T],
        *args,
        with_endpoints: Optional[List[Endpoint]] = None,
        **kwargs,
    ) -> Tuple[T, Sequence[EndpointCallback]]:
        """Root of all cost tracking methods.

        Runs the given `thunk`, tracking costs using each of the provided
        endpoints' callbacks.
        """

        if (
            with_endpoints is not None
            and len(with_endpoints) > 0
            and not Endpoint._have_context()
        ):
            # If we cannot access the context vars, we cannot track costs, the
            # last condition issues a warning with more info.
            return __func(*args, **kwargs), []

        # Check to see if this call is within another _track_costs call:
        endpoints = dict(Endpoint._context_endpoints.get())  # copy

        # Collect any new endpoints requested of us.
        with_endpoints = with_endpoints or []

        # Keep track of the new callback objects we create here for returning
        # later.
        callbacks = []

        # Create the callbacks for the new requested endpoints only. Existing
        # endpoints from other frames will keep their callbacks.
        for endpoint in with_endpoints:
            callback_class = endpoint.callback_class
            callback = callback_class(endpoint=endpoint)

            if callback_class not in endpoints:
                endpoints[callback_class] = []

            # And add them to the endpoints dict.
            endpoints[callback_class].append((endpoint, callback))

            callbacks.append(callback)

        # Push the endpoints into the contextvars for wrappers inside the
        # following call to retrieve.
        endpoints_token = Endpoint._context_endpoints.set(endpoints)  # noqa: F841

        try:
            # context_vars = contextvars.copy_context()
            context_vars = {
                Endpoint._context_endpoints: Endpoint._context_endpoints.get()
            }

            # Call the function.
            result: T = __func(*args, **kwargs)

            def rewrap(result):
                if python_utils.is_lazy(result):
                    return python_utils.wrap_lazy(
                        result,
                        wrap=rewrap,
                        context_vars=context_vars,
                    )

                return result

            result = rewrap(result)
        finally:
            # Pop the endpoints from the contextvars.
            # Optionally disable to debug context issues. See App._set_context_vars.
            Endpoint._context_endpoints.reset(endpoints_token)

        # Return result and only the callbacks created here. Outer thunks might
        # return others.
        return result, callbacks
Root of all cost tracking methods.

        Runs the given `thunk`, tracking costs using each of the provided
        endpoints' callbacks.
        
src/core/trulens/core/feedback/endpoint.py