|
| 1 | +"""LLM evaluated metric based on the GEval framework: https://arxiv.org/pdf/2303.16634.pdf""" |
| 2 | + |
| 3 | +from typing import Optional, List, Tuple, Union |
| 4 | +from deepeval.models import DeepEvalBaseMLLM |
| 5 | +from deepeval.metrics import BaseMultimodalMetric |
| 6 | +from deepeval.test_case import ( |
| 7 | + MLLMTestCaseParams, |
| 8 | + MLLMTestCase, |
| 9 | +) |
| 10 | +from deepeval.metrics.multimodal_metrics.multimodal_g_eval.template import MultimodalGEvalTemplate |
| 11 | +from deepeval.metrics.multimodal_metrics.multimodal_g_eval.schema import * |
| 12 | +from deepeval.utils import get_or_create_event_loop, prettify_list |
| 13 | +from deepeval.metrics.indicator import metric_progress_indicator |
| 14 | +from deepeval.metrics.utils import ( |
| 15 | + initialize_multimodal_model, |
| 16 | + check_mllm_test_case_params, |
| 17 | + construct_verbose_logs, |
| 18 | + trimAndLoadJson, |
| 19 | +) |
| 20 | +from deepeval.metrics.multimodal_metrics.multimodal_g_eval.utils import ( |
| 21 | + construct_test_case_list, |
| 22 | + no_multimodal_log_prob_support, |
| 23 | + construct_g_eval_params_string, |
| 24 | +) |
| 25 | +from deepeval.metrics.g_eval.utils import ( |
| 26 | + Rubric, |
| 27 | + format_rubrics, |
| 28 | + calculate_weighted_summed_score, |
| 29 | + validate_and_sort_rubrics, |
| 30 | + validate_criteria_and_evaluation_steps, |
| 31 | + number_evaluation_steps, |
| 32 | + get_score_range, |
| 33 | +) |
| 34 | + |
| 35 | + |
| 36 | +class MultimodalGEval(BaseMultimodalMetric): |
| 37 | + def __init__( |
| 38 | + self, |
| 39 | + name: str, |
| 40 | + evaluation_params: List[MLLMTestCaseParams], |
| 41 | + criteria: Optional[str] = None, |
| 42 | + evaluation_steps: Optional[List[str]] = None, |
| 43 | + rubric: Optional[List[Rubric]] = None, |
| 44 | + model: Optional[Union[str, DeepEvalBaseMLLM]] = None, |
| 45 | + threshold: float = 0.5, |
| 46 | + top_logprobs: int = 20, |
| 47 | + async_mode: bool = True, |
| 48 | + strict_mode: bool = False, |
| 49 | + verbose_mode: bool = False, |
| 50 | + _include_g_eval_suffix: bool = True, |
| 51 | + ): |
| 52 | + validate_criteria_and_evaluation_steps(criteria, evaluation_steps) |
| 53 | + self.name = name |
| 54 | + self.evaluation_params = evaluation_params |
| 55 | + self.criteria = criteria |
| 56 | + self.rubric = validate_and_sort_rubrics(rubric) |
| 57 | + self.model, self.using_native_model = initialize_multimodal_model(model) |
| 58 | + self.evaluation_model = self.model.get_model_name() |
| 59 | + self.evaluation_steps = evaluation_steps |
| 60 | + self.threshold = 1 if strict_mode else threshold |
| 61 | + self.top_logprobs = top_logprobs |
| 62 | + self.strict_mode = strict_mode |
| 63 | + self.async_mode = async_mode |
| 64 | + self.verbose_mode = verbose_mode |
| 65 | + self._include_g_eval_suffix = _include_g_eval_suffix |
| 66 | + |
| 67 | + def measure( |
| 68 | + self, |
| 69 | + test_case: MLLMTestCase, |
| 70 | + _show_indicator: bool = True, |
| 71 | + _in_component: bool = False, |
| 72 | + _additional_context: Optional[str] = None, |
| 73 | + ) -> float: |
| 74 | + |
| 75 | + check_mllm_test_case_params(test_case, self.evaluation_params, None, None, self) |
| 76 | + |
| 77 | + self.evaluation_cost = 0 if self.using_native_model else None |
| 78 | + with metric_progress_indicator( |
| 79 | + self, _show_indicator=_show_indicator, _in_component=_in_component |
| 80 | + ): |
| 81 | + if self.async_mode: |
| 82 | + loop = get_or_create_event_loop() |
| 83 | + loop.run_until_complete( |
| 84 | + self.a_measure( |
| 85 | + test_case, |
| 86 | + _show_indicator=False, |
| 87 | + _in_component=_in_component, |
| 88 | + _additional_context=_additional_context, |
| 89 | + ) |
| 90 | + ) |
| 91 | + else: |
| 92 | + self.evaluation_steps: List[str] = ( |
| 93 | + self._generate_evaluation_steps() |
| 94 | + ) |
| 95 | + g_score, reason = self._evaluate( |
| 96 | + test_case, _additional_context=_additional_context |
| 97 | + ) |
| 98 | + self.reason = reason |
| 99 | + self.score = float(g_score) / 10 |
| 100 | + self.score = ( |
| 101 | + 0 |
| 102 | + if self.strict_mode and self.score < self.threshold |
| 103 | + else self.score |
| 104 | + ) |
| 105 | + self.success = self.score >= self.threshold |
| 106 | + self.verbose_logs = construct_verbose_logs( |
| 107 | + self, |
| 108 | + steps=[ |
| 109 | + f"Criteria:\n{self.criteria}", |
| 110 | + f"Evaluation Steps:\n{prettify_list(self.evaluation_steps)}", |
| 111 | + f"Rubric:\n{format_rubrics(self.rubric)}", |
| 112 | + f"Score: {self.score}\nReason: {self.reason}", |
| 113 | + ], |
| 114 | + ) |
| 115 | + |
| 116 | + return self.score |
| 117 | + |
| 118 | + async def a_measure( |
| 119 | + self, |
| 120 | + test_case: MLLMTestCase, |
| 121 | + _show_indicator: bool = True, |
| 122 | + _in_component: bool = False, |
| 123 | + _additional_context: Optional[str] = None, |
| 124 | + ) -> float: |
| 125 | + |
| 126 | + check_mllm_test_case_params(test_case, self.evaluation_params, None, None, self) |
| 127 | + |
| 128 | + self.evaluation_cost = 0 if self.using_native_model else None |
| 129 | + with metric_progress_indicator( |
| 130 | + self, |
| 131 | + async_mode=True, |
| 132 | + _show_indicator=_show_indicator, |
| 133 | + _in_component=_in_component, |
| 134 | + ): |
| 135 | + self.evaluation_steps: List[str] = ( |
| 136 | + await self._a_generate_evaluation_steps() |
| 137 | + ) |
| 138 | + g_score, reason = await self._a_evaluate( |
| 139 | + test_case, _additional_context=_additional_context |
| 140 | + ) |
| 141 | + self.reason = reason |
| 142 | + self.score = ( |
| 143 | + float(g_score) / 10 if not self.strict_mode else int(g_score) |
| 144 | + ) |
| 145 | + self.success = self.score >= self.threshold |
| 146 | + self.verbose_logs = construct_verbose_logs( |
| 147 | + self, |
| 148 | + steps=[ |
| 149 | + f"Criteria:\n{self.criteria}", |
| 150 | + f"Evaluation Steps:\n{prettify_list(self.evaluation_steps)}", |
| 151 | + f"Rubric:\n{format_rubrics(self.rubric)}", |
| 152 | + f"Score: {self.score}\nReason: {self.reason}", |
| 153 | + ], |
| 154 | + ) |
| 155 | + return self.score |
| 156 | + |
| 157 | + async def _a_generate_evaluation_steps(self) -> List[str]: |
| 158 | + if self.evaluation_steps: |
| 159 | + return self.evaluation_steps |
| 160 | + |
| 161 | + g_eval_params_str = construct_g_eval_params_string( |
| 162 | + self.evaluation_params |
| 163 | + ) |
| 164 | + prompt = MultimodalGEvalTemplate.generate_evaluation_steps( |
| 165 | + criteria=self.criteria, parameters=g_eval_params_str |
| 166 | + ) |
| 167 | + if self.using_native_model: |
| 168 | + res, cost = await self.model.a_generate([prompt], schema=Steps) |
| 169 | + self.evaluation_cost += cost |
| 170 | + return res.steps |
| 171 | + else: |
| 172 | + try: |
| 173 | + res: Steps = await self.model.a_generate([prompt], schema=Steps) |
| 174 | + return res.steps |
| 175 | + except TypeError: |
| 176 | + res = await self.model.a_generate([prompt]) |
| 177 | + data = trimAndLoadJson(res, self) |
| 178 | + return data["steps"] |
| 179 | + |
| 180 | + def _generate_evaluation_steps(self) -> List[str]: |
| 181 | + if self.evaluation_steps: |
| 182 | + return self.evaluation_steps |
| 183 | + |
| 184 | + g_eval_params_str = construct_g_eval_params_string( |
| 185 | + self.evaluation_params |
| 186 | + ) |
| 187 | + prompt = MultimodalGEvalTemplate.generate_evaluation_steps( |
| 188 | + criteria=self.criteria, parameters=g_eval_params_str |
| 189 | + ) |
| 190 | + if self.using_native_model: |
| 191 | + res, cost = self.model.generate([prompt], schema=Steps) |
| 192 | + self.evaluation_cost += cost |
| 193 | + return res.steps |
| 194 | + else: |
| 195 | + try: |
| 196 | + res: Steps = self.model.generate([prompt], schema=Steps) |
| 197 | + return res.steps |
| 198 | + except TypeError: |
| 199 | + res = self.model.generate([prompt]) |
| 200 | + data = trimAndLoadJson(res, self) |
| 201 | + return data["steps"] |
| 202 | + |
| 203 | + async def _a_evaluate( |
| 204 | + self, test_case: MLLMTestCase, _additional_context: Optional[str] = None |
| 205 | + ) -> Tuple[Union[int, float], str]: |
| 206 | + test_case_list= construct_test_case_list(self.evaluation_params, test_case) |
| 207 | + g_eval_params_str = construct_g_eval_params_string(self.evaluation_params) |
| 208 | + |
| 209 | + if not self.strict_mode: |
| 210 | + rubric_str = format_rubrics(self.rubric) if self.rubric else None |
| 211 | + prompt = MultimodalGEvalTemplate.generate_evaluation_results( |
| 212 | + evaluation_steps=number_evaluation_steps(self.evaluation_steps), |
| 213 | + test_case_list=test_case_list, |
| 214 | + parameters=g_eval_params_str, |
| 215 | + rubric=rubric_str, |
| 216 | + score_range=get_score_range(self.rubric), |
| 217 | + _additional_context=_additional_context, |
| 218 | + ) |
| 219 | + else: |
| 220 | + prompt = MultimodalGEvalTemplate.generate_strict_evaluation_results( |
| 221 | + evaluation_steps=number_evaluation_steps(self.evaluation_steps), |
| 222 | + test_case_list=test_case_list, |
| 223 | + parameters=g_eval_params_str, |
| 224 | + _additional_context=_additional_context, |
| 225 | + ) |
| 226 | + try: |
| 227 | + # don't use log probabilities for unsupported gpt models |
| 228 | + if no_multimodal_log_prob_support(self.model): |
| 229 | + raise AttributeError("log_probs unsupported.") |
| 230 | + |
| 231 | + # Don't have to check for using native model |
| 232 | + # since generate raw response only exist for deepeval's native model |
| 233 | + res, cost = await self.model.a_generate_raw_response( |
| 234 | + prompt, top_logprobs=self.top_logprobs |
| 235 | + ) |
| 236 | + self.evaluation_cost += cost |
| 237 | + data = trimAndLoadJson(res.choices[0].message.content, self) |
| 238 | + |
| 239 | + reason = data["reason"] |
| 240 | + score = data["score"] |
| 241 | + if self.strict_mode: |
| 242 | + return score, reason |
| 243 | + |
| 244 | + try: |
| 245 | + weighted_summed_score = calculate_weighted_summed_score( |
| 246 | + score, res |
| 247 | + ) |
| 248 | + return weighted_summed_score, reason |
| 249 | + except: |
| 250 | + return score, reason |
| 251 | + except ( |
| 252 | + AttributeError |
| 253 | + ): # This catches the case where a_generate_raw_response doesn't exist. |
| 254 | + if self.using_native_model: |
| 255 | + res, cost = await self.model.a_generate(prompt) |
| 256 | + self.evaluation_cost += cost |
| 257 | + data = trimAndLoadJson(res, self) |
| 258 | + return data["score"], data["reason"] |
| 259 | + else: |
| 260 | + try: |
| 261 | + res: ReasonScore = await self.model.a_generate( |
| 262 | + prompt, schema=ReasonScore |
| 263 | + ) |
| 264 | + return res.score, res.reason |
| 265 | + except TypeError: |
| 266 | + res = await self.model.a_generate(prompt) |
| 267 | + data = trimAndLoadJson(res, self) |
| 268 | + return data["score"], data["reason"] |
| 269 | + |
| 270 | + def _evaluate( |
| 271 | + self, test_case: MLLMTestCase, _additional_context: Optional[str] = None |
| 272 | + ) -> Tuple[Union[int, float], str]: |
| 273 | + test_case_list = construct_test_case_list(self.evaluation_params, test_case) |
| 274 | + g_eval_params_str = construct_g_eval_params_string(self.evaluation_params) |
| 275 | + |
| 276 | + if not self.strict_mode: |
| 277 | + rubric_str = format_rubrics(self.rubric) if self.rubric else None |
| 278 | + prompt = MultimodalGEvalTemplate.generate_evaluation_results( |
| 279 | + evaluation_steps=number_evaluation_steps(self.evaluation_steps), |
| 280 | + test_case_list=test_case_list, |
| 281 | + parameters=g_eval_params_str, |
| 282 | + rubric=rubric_str, |
| 283 | + score_range=get_score_range(self.rubric), |
| 284 | + _additional_context=_additional_context, |
| 285 | + ) |
| 286 | + else: |
| 287 | + prompt = MultimodalGEvalTemplate.generate_strict_evaluation_results( |
| 288 | + evaluation_steps=number_evaluation_steps(self.evaluation_steps), |
| 289 | + test_case_list=test_case_list, |
| 290 | + parameters=g_eval_params_str, |
| 291 | + _additional_context=_additional_context, |
| 292 | + ) |
| 293 | + |
| 294 | + try: |
| 295 | + # don't use log probabilities for unsupported gpt models |
| 296 | + if no_multimodal_log_prob_support(self.model): |
| 297 | + raise AttributeError("log_probs unsupported.") |
| 298 | + |
| 299 | + res, cost = self.model.generate_raw_response( |
| 300 | + prompt, top_logprobs=self.top_logprobs |
| 301 | + ) |
| 302 | + self.evaluation_cost += cost |
| 303 | + data = trimAndLoadJson(res.choices[0].message.content, self) |
| 304 | + |
| 305 | + reason = data["reason"] |
| 306 | + score = data["score"] |
| 307 | + if self.strict_mode: |
| 308 | + return score, reason |
| 309 | + |
| 310 | + try: |
| 311 | + weighted_summed_score = calculate_weighted_summed_score( |
| 312 | + score, res |
| 313 | + ) |
| 314 | + return weighted_summed_score, reason |
| 315 | + except: |
| 316 | + return score, reason |
| 317 | + except AttributeError: |
| 318 | + # This catches the case where a_generate_raw_response doesn't exist. |
| 319 | + if self.using_native_model: |
| 320 | + res, cost = self.model.generate(prompt) |
| 321 | + self.evaluation_cost += cost |
| 322 | + data = trimAndLoadJson(res, self) |
| 323 | + return data["score"], data["reason"] |
| 324 | + else: |
| 325 | + try: |
| 326 | + res: ReasonScore = self.model.generate( |
| 327 | + prompt, schema=ReasonScore |
| 328 | + ) |
| 329 | + return res.score, res.reason |
| 330 | + except TypeError: |
| 331 | + res = self.model.generate(prompt) |
| 332 | + data = trimAndLoadJson(res, self) |
| 333 | + return data["score"], data["reason"] |
| 334 | + |
| 335 | + def is_successful(self) -> bool: |
| 336 | + if self.error is not None: |
| 337 | + self.success = False |
| 338 | + else: |
| 339 | + try: |
| 340 | + self.success = self.score >= self.threshold |
| 341 | + except: |
| 342 | + self.success = False |
| 343 | + return self.success |
| 344 | + |
| 345 | + @property |
| 346 | + def __name__(self): |
| 347 | + if self._include_g_eval_suffix: |
| 348 | + return f"{self.name} (GEval)" |
| 349 | + else: |
| 350 | + return self.name |
0 commit comments