Source code for langchain.evaluation.regex_match.base
import re
from typing import Any, List
from langchain.evaluation.schema import StringEvaluator
[docs]class RegexMatchStringEvaluator(StringEvaluator):
"""计算预测值和参考值之间的正则表达式匹配。
示例
----------
>>> evaluator = RegexMatchStringEvaluator(flags=re.IGNORECASE)
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="^mindy.*cto$",
) # 由于IGNORECASE标志,将返回{'score': 1.0}
>>> evaluator = RegexMatchStringEvaluator()
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="^Mike.*CEO$",
) # 将返回{'score': 0.0}
>>> evaluator.evaluate_strings(
prediction="Mindy is the CTO",
reference="^Mike.*CEO$|^Mindy.*CTO$",
) # 由于预测值与并集中的第二个模式匹配,将返回{'score': 1.0}""" # noqa: E501
[docs] def __init__(self, *, flags: int = 0, **kwargs: Any): # Default is no flags
super().__init__()
self.flags = flags
@property
def requires_input(self) -> bool:
"""
这个评估器不需要输入。
"""
return False
@property
def requires_reference(self) -> bool:
"""
这个评估器需要一个参考。
"""
return True
@property
def input_keys(self) -> List[str]:
"""获取输入键。
返回:
List[str]:输入键。
"""
return ["reference", "prediction"]
@property
def evaluation_name(self) -> str:
"""获取评估名称。
返回:
str:评估名称。
"""
return "regex_match"
def _evaluate_strings( # type: ignore[arg-type,override]
self,
*,
prediction: str,
reference: str,
**kwargs: Any,
) -> dict:
"""评估预测值和参考值之间的正则表达式匹配。
参数:
prediction(str):预测字符串。
reference(Optional[str],可选):参考正则表达式模式。
返回:
dict:包含分数的评估结果。
"""
match = re.match(reference, prediction, flags=self.flags)
return {"score": int(bool(match))}