cache_config.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. from typing import Any, Dict, Optional
  2. from embedchain.config.base_config import BaseConfig
  3. from embedchain.helpers.json_serializable import register_deserializable
  4. @register_deserializable
  5. class CacheSimilarityEvalConfig(BaseConfig):
  6. """
  7. This is the evaluator to compare two embeddings according to their distance computed in embedding retrieval stage.
  8. In the retrieval stage, `search_result` is the distance used for approximate nearest neighbor search and have been
  9. put into `cache_dict`. `max_distance` is used to bound this distance to make it between [0-`max_distance`].
  10. `positive` is used to indicate this distance is directly proportional to the similarity of two entites.
  11. If `positive` is set `False`, `max_distance` will be used to substract this distance to get the final score.
  12. :param max_distance: the bound of maximum distance.
  13. :type max_distance: float
  14. :param positive: if the larger distance indicates more similar of two entities, It is True. Otherwise it is False.
  15. :type positive: bool
  16. """
  17. def __init__(
  18. self,
  19. strategy: Optional[str] = "distance",
  20. max_distance: Optional[float] = 1.0,
  21. positive: Optional[bool] = False,
  22. ):
  23. self.strategy = strategy
  24. self.max_distance = max_distance
  25. self.positive = positive
  26. def from_config(config: Optional[Dict[str, Any]]):
  27. if config is None:
  28. return CacheSimilarityEvalConfig()
  29. else:
  30. return CacheSimilarityEvalConfig(
  31. strategy=config.get("strategy", "distance"),
  32. max_distance=config.get("max_distance", 1.0),
  33. positive=config.get("positive", False),
  34. )
  35. @register_deserializable
  36. class CacheInitConfig(BaseConfig):
  37. """
  38. This is a cache init config. Used to initialize a cache.
  39. :param similarity_threshold: a threshold ranged from 0 to 1 to filter search results with similarity score higher \
  40. than the threshold. When it is 0, there is no hits. When it is 1, all search results will be returned as hits.
  41. :type similarity_threshold: float
  42. :param auto_flush: it will be automatically flushed every time xx pieces of data are added, default to 20
  43. :type auto_flush: int
  44. """
  45. def __init__(
  46. self,
  47. similarity_threshold: Optional[float] = 0.8,
  48. auto_flush: Optional[int] = 20,
  49. ):
  50. if similarity_threshold < 0 or similarity_threshold > 1:
  51. raise ValueError(f"similarity_threshold {similarity_threshold} should be between 0 and 1")
  52. self.similarity_threshold = similarity_threshold
  53. self.auto_flush = auto_flush
  54. def from_config(config: Optional[Dict[str, Any]]):
  55. if config is None:
  56. return CacheInitConfig()
  57. else:
  58. return CacheInitConfig(
  59. similarity_threshold=config.get("similarity_threshold", 0.8),
  60. auto_flush=config.get("auto_flush", 20),
  61. )
  62. @register_deserializable
  63. class CacheConfig(BaseConfig):
  64. def __init__(
  65. self,
  66. similarity_eval_config: Optional[CacheSimilarityEvalConfig] = CacheSimilarityEvalConfig(),
  67. init_config: Optional[CacheInitConfig] = CacheInitConfig(),
  68. ):
  69. self.similarity_eval_config = similarity_eval_config
  70. self.init_config = init_config
  71. def from_config(config: Optional[Dict[str, Any]]):
  72. if config is None:
  73. return CacheConfig()
  74. else:
  75. return CacheConfig(
  76. similarity_eval_config=CacheSimilarityEvalConfig.from_config(config.get("similarity_evaluation", {})),
  77. init_config=CacheInitConfig.from_config(config.get("init_config", {})),
  78. )