def _flox_reduce(
        self,
        dim: Dims,
        keep_attrs: bool | None = None,
        **kwargs: Any,
    ) -> T_Xarray:
        """Adaptor function that translates our groupby API to that of flox."""
        import flox
        from flox.xarray import xarray_reduce

        from xarray.core.dataset import Dataset

        obj = self._original_obj
        variables = (
            {k: v.variable for k, v in obj.data_vars.items()}
            if isinstance(obj, Dataset)  # type: ignore[redundant-expr]  # seems to be a mypy bug
            else obj._coords
        )

        if keep_attrs is None:
            keep_attrs = _get_keep_attrs(default=True)

        if Version(flox.__version__) < Version("0.9") and not self._by_chunked:
            # preserve current strategy (approximately) for dask groupby
            # on older flox versions to prevent surprises.
            # flox >=0.9 will choose this on its own.
            kwargs.setdefault("method", "cohorts")

        midx_grouping_vars: tuple[Hashable, ...] = ()
        for grouper in self.groupers:
            name = grouper.name
            maybe_midx = obj._indexes.get(name, None)
            if isinstance(maybe_midx, PandasMultiIndex):
                midx_grouping_vars += tuple(maybe_midx.index.names) + (name,)

        # For datasets, running a numeric-only reduction on non-numeric
        # variable will just drop it.
        non_numeric: dict[Hashable, Variable]
        if kwargs.pop("numeric_only", None):
            non_numeric = {
                name: var
                for name, var in variables.items()
                if (
                    not (np.issubdtype(var.dtype, np.number) or (var.dtype == np.bool_))
                    # this avoids dropping any levels of a MultiIndex, which raises
                    # a warning
                    and name not in midx_grouping_vars
                    and name not in obj.dims
                )
            }
        else:
            non_numeric = {}

        if "min_count" in kwargs:
            if kwargs["func"] not in ["sum", "prod"]:
                raise TypeError("Received an unexpected keyword argument 'min_count'")
            elif kwargs["min_count"] is None:
                # set explicitly to avoid unnecessarily accumulating count
                kwargs["min_count"] = 0

        parsed_dim: tuple[Hashable, ...]
        if isinstance(dim, str):
            parsed_dim = (dim,)
        elif dim is None:
            parsed_dim_list = list()
            # preserve order
            for dim_ in itertools.chain(
                *(grouper.codes.dims for grouper in self.groupers)
            ):
                if dim_ not in parsed_dim_list:
                    parsed_dim_list.append(dim_)
            parsed_dim = tuple(parsed_dim_list)
        elif dim is ...:
            parsed_dim = tuple(obj.dims)
        else:
            parsed_dim = tuple(dim)

        # Do this so we raise the same error message whether flox is present or not.
        # Better to control it here than in flox.
        for grouper in self.groupers:
            if any(
                d not in grouper.codes.dims and d not in obj.dims for d in parsed_dim
            ):
                raise ValueError(f"cannot reduce over dimensions {dim}.")

        has_missing_groups = (
            self.encoded.unique_coord.size != self.encoded.full_index.size
        )
        if self._by_chunked or has_missing_groups or kwargs.get("min_count", 0) > 0:
            # Xarray *always* returns np.nan when there are no observations in a group,
            # We can fake that here by forcing min_count=1 when it is not set.
            # This handles boolean reductions, and count
            # See GH8090, GH9398
            # Note that `has_missing_groups=False` when `self._by_chunked is True`.
            # We *choose* to always do the masking, so that behaviour is predictable
            # in some way. The real solution is to expose fill_value as a kwarg,
            # and set appropriate defaults :/.
            kwargs.setdefault("fill_value", np.nan)
            kwargs.setdefault("min_count", 1)

        # pass RangeIndex as a hint to flox that `by` is already factorized
        expected_groups = tuple(
            pd.RangeIndex(len(grouper)) for grouper in self.groupers
        )

        codes = tuple(g.codes for g in self.groupers)
        result = xarray_reduce(
            obj.drop_vars(non_numeric.keys()),
            *codes,
            dim=parsed_dim,
            expected_groups=expected_groups,
            isbin=False,
            keep_attrs=keep_attrs,
            **kwargs,
        )

        # we did end up reducing over dimension(s) that are
        # in the grouped variable
        group_dims = set(grouper.group.dims)
        new_coords = []
        to_drop = []
        if group_dims & set(parsed_dim):
            for grouper in self.groupers:
                output_index = grouper.full_index
                if isinstance(output_index, pd.RangeIndex):
                    # flox always assigns an index so we must drop it here if we don't need it.
                    to_drop.append(grouper.name)
                    continue
                # TODO: We can't simply use `self.encoded.coords` here because it corresponds to `unique_coord`,
                # NOT `full_index`. We would need to construct a new Coordinates object, that corresponds to `full_index`.
                new_coords.append(
                    # Using IndexVariable here ensures we reconstruct PandasMultiIndex with
                    # all associated levels properly.
                    coordinates_from_variable(
                        IndexVariable(
                            dims=grouper.name,
                            data=output_index,
                            attrs=grouper.codes.attrs,
                        )
                    )
                )
            result = result.assign_coords(
                Coordinates._construct_direct(*merge_coords(new_coords))
            ).drop_vars(to_drop)

        # broadcast any non-dim coord variables that don't
        # share all dimensions with the grouper
        result_variables = (
            result._variables if isinstance(result, Dataset) else result._coords
        )
        to_broadcast: dict[Hashable, Variable] = {}
        for name, var in variables.items():
            dims_set = set(var.dims)
            if (
                dims_set <= set(parsed_dim)
                and (dims_set & set(result.dims))
                and name not in result_variables
            ):
                to_broadcast[name] = var
        for name, var in to_broadcast.items():
            if new_dims := tuple(d for d in parsed_dim if d not in var.dims):
                new_sizes = tuple(
                    result.sizes.get(dim, obj.sizes.get(dim)) for dim in new_dims
                )
                result[name] = var.set_dims(
                    new_dims + var.dims, new_sizes + var.shape
                ).transpose(..., *result.dims)

        if not isinstance(result, Dataset):
            # only restore dimension order for arrays
            result = self._restore_dim_order(result)

        return result
Adaptor function that translates our groupby API to that of flox.
xarray/core/groupby.py