code: def save_detector(
      detector: Union[Detector, ConfigurableDetector],
      filepath: Union[str, os.PathLike],
      legacy: bool = False,
  ) -> None:
      """
      Save outlier, drift or adversarial detector.
  
      Parameters
      ----------
      detector
          Detector object.
      filepath
          Save directory.
      legacy
          Whether to save in the legacy .dill format instead of via a config.toml file. Default is `False`.
          This option will be removed in a future version.
      """
      if legacy:
          warnings.warn(
              "The `legacy` option will be removed in a future version.",
              DeprecationWarning,
          )
  
      # TODO: Replace .__args__ w/ typing.get_args() once Python 3.7 dropped (and remove type ignore below)
      detector_name = detector.__class__.__name__
      if detector_name not in [
          detector for detector in VALID_DETECTORS
      ]:
          raise NotImplementedError(
              f"{detector_name} is not supported by `save_detector`."
          )
  
      # Saving is wrapped in a try, with cleanup in except. To prevent a half-saved detector remaining upon error.
      filepath = Path(filepath)
      try:
          # Create directory if it doesn't exist
          if not filepath.is_dir():
              logger.warning(
                  "Directory {} does not exist and is now created.".format(
                      filepath
                  )
              )
              filepath.mkdir(parents=True, exist_ok=True)
  
          # If a drift detector, wrap drift detector save method
          if isinstance(detector, ConfigurableDetector) and not legacy:
              _save_detector_config(detector, filepath)
  
          # Otherwise, save via the previous meta and state_dict approach
          else:
              save_detector_legacy(detector, filepath)
  
      except Exception as error:
          # Get a list of all existing files in `filepath` (so we know what not to cleanup if an error occurs)
          orig_files = set(filepath.iterdir())
          _cleanup_filepath(orig_files, filepath)
          raise RuntimeError(
              f"Saving failed. The save directory {filepath} has been cleaned."
          ) from error
  
      logger.info("finished saving.")
  
imports: import logging
  import os
  import shutil
  import warnings
  from functools import partial
  from pathlib import Path
  from typing import Callable, Optional, Tuple, Union, Any, Dict, TYPE_CHECKING
  import dill
  import numpy
  import toml
  from transformers import PreTrainedTokenizerBase
  from alibi_detect.saving._typing import VALID_DETECTORS
  from alibi_detect.saving.loading import _replace, validate_config, STATE_PATH
  from alibi_detect.saving.registry import registry
  from alibi_detect.utils._types import supported_models_all, supported_models_tf, supported_models_torch, supported_models_sklearn
  from alibi_detect.base import Detector, ConfigurableDetector, StatefulDetectorOnline
  from alibi_detect.saving._tensorflow import save_detector_legacy, save_model_config_tf, save_optimizer_config_tf
  from alibi_detect.saving._pytorch import save_model_config_pt, save_device_pt
  from alibi_detect.saving._sklearn import save_model_config_sk
label_desc: Use image node_id 1 for calling a global function with example usage: save_detector(detector, filepath, legacy) without return types