3
3
from enum import Enum
4
4
5
5
from langchain_core .callbacks import Callbacks
6
- from rapidfuzz import distance
7
6
8
7
from ragas .dataset_schema import SingleTurnSample
9
8
from ragas .metrics .base import MetricType , SingleTurnMetric
@@ -16,13 +15,6 @@ class DistanceMeasure(Enum):
16
15
JARO = "jaro"
17
16
18
17
19
- DISTANCE_MEASURE_MAP = {
20
- DistanceMeasure .LEVENSHTEIN : distance .Levenshtein ,
21
- DistanceMeasure .HAMMING : distance .Hamming ,
22
- DistanceMeasure .JARO : distance .Jaro ,
23
- }
24
-
25
-
26
18
@dataclass
27
19
class ExactMatch (SingleTurnMetric ):
28
20
name : str = "exact_match" # type: ignore
@@ -42,6 +34,7 @@ async def _ascore(self, row: t.Dict, callbacks: Callbacks) -> float:
42
34
return await self ._single_turn_ascore (SingleTurnSample (** row ), callbacks )
43
35
44
36
37
+ @dataclass
45
38
class StringPresent (SingleTurnMetric ):
46
39
name : str = "string_present" # type: ignore
47
40
_required_columns : t .Dict [MetricType , t .Set [str ]] = field (
@@ -64,13 +57,28 @@ async def _ascore(self, row: t.Dict, callbacks: Callbacks) -> float:
64
57
return await self ._single_turn_ascore (SingleTurnSample (** row ), callbacks )
65
58
66
59
67
- class StringDistance (SingleTurnMetric ):
68
- name : str = "string_distance" # type: ignore
60
+ @dataclass
61
+ class NonLLMStringSimilarity (SingleTurnMetric ):
62
+ name : str = "non_llm_string_similarity" # type: ignore
69
63
_required_columns : t .Dict [MetricType , t .Set [str ]] = field (
70
64
default_factory = lambda : {MetricType .SINGLE_TURN : {"reference" , "response" }}
71
65
)
72
66
distance_measure : DistanceMeasure = DistanceMeasure .LEVENSHTEIN
73
67
68
+ def __post_init__ (self ):
69
+ try :
70
+ from rapidfuzz import distance
71
+ except ImportError :
72
+ raise ImportError (
73
+ "rapidfuzz is required for string distance. Please install it using `pip install rapidfuzz`"
74
+ )
75
+
76
+ self .distance_measure_map = {
77
+ DistanceMeasure .LEVENSHTEIN : distance .Levenshtein ,
78
+ DistanceMeasure .HAMMING : distance .Hamming ,
79
+ DistanceMeasure .JARO : distance .Jaro ,
80
+ }
81
+
74
82
def init (self , run_config : RunConfig ):
75
83
pass
76
84
@@ -81,7 +89,7 @@ async def _single_turn_ascore(
81
89
response = sample .response
82
90
assert isinstance (reference , str ), "Expecting a string"
83
91
assert isinstance (response , str ), "Expecting a string"
84
- return 1 - DISTANCE_MEASURE_MAP [self .distance_measure ].normalized_distance (
92
+ return 1 - self . distance_measure_map [self .distance_measure ].normalized_distance (
85
93
reference , response
86
94
)
87
95
0 commit comments