judgeval 0.0.3__py3-none-any.whl → 0.0.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- judgeval/__init__.py +0 -71
- judgeval/common/tracer.py +57 -31
- judgeval/constants.py +1 -0
- judgeval/data/__init__.py +2 -1
- judgeval/data/scorer_data.py +2 -2
- judgeval/evaluation_run.py +16 -15
- judgeval/judges/__init__.py +2 -2
- judgeval/judges/base_judge.py +1 -1
- judgeval/judges/litellm_judge.py +2 -2
- judgeval/judges/mixture_of_judges.py +2 -2
- judgeval/judges/together_judge.py +2 -2
- judgeval/judges/utils.py +4 -4
- judgeval/judgment_client.py +67 -15
- judgeval/run_evaluation.py +79 -14
- judgeval/scorers/__init__.py +8 -4
- judgeval/scorers/api_scorer.py +64 -0
- judgeval/scorers/base_scorer.py +3 -2
- judgeval/scorers/exceptions.py +11 -0
- judgeval/scorers/{custom_scorer.py → judgeval_scorer.py} +9 -5
- judgeval/scorers/judgeval_scorers/__init__.py +132 -9
- judgeval/scorers/judgeval_scorers/api_scorers/__init__.py +23 -0
- judgeval/scorers/judgeval_scorers/api_scorers/answer_correctness.py +19 -0
- judgeval/scorers/judgeval_scorers/{answer_relevancy.py → api_scorers/answer_relevancy.py} +2 -2
- judgeval/scorers/judgeval_scorers/{contextual_precision.py → api_scorers/contextual_precision.py} +2 -2
- judgeval/scorers/judgeval_scorers/{contextual_recall.py → api_scorers/contextual_recall.py} +2 -2
- judgeval/scorers/judgeval_scorers/{contextual_relevancy.py → api_scorers/contextual_relevancy.py} +2 -2
- judgeval/scorers/judgeval_scorers/{faithfulness.py → api_scorers/faithfulness.py} +2 -2
- judgeval/scorers/judgeval_scorers/{hallucination.py → api_scorers/hallucination.py} +2 -2
- judgeval/scorers/judgeval_scorers/{json_correctness.py → api_scorers/json_correctness.py} +7 -7
- judgeval/scorers/judgeval_scorers/{summarization.py → api_scorers/summarization.py} +2 -2
- judgeval/scorers/judgeval_scorers/{tool_correctness.py → api_scorers/tool_correctness.py} +2 -2
- judgeval/scorers/judgeval_scorers/local_implementations/__init__.py +24 -0
- judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/__init__.py +4 -0
- judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/answer_correctness_scorer.py +272 -0
- judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/prompts.py +169 -0
- judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/__init__.py +4 -0
- judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/answer_relevancy_scorer.py +292 -0
- judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/prompts.py +174 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/__init__.py +3 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/contextual_precision_scorer.py +259 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/prompts.py +106 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/__init__.py +3 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/contextual_recall_scorer.py +249 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/prompts.py +142 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/__init__.py +3 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/contextual_relevancy_scorer.py +240 -0
- judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/prompts.py +121 -0
- judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/__init__.py +3 -0
- judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/faithfulness_scorer.py +318 -0
- judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/prompts.py +265 -0
- judgeval/scorers/judgeval_scorers/local_implementations/hallucination/__init__.py +3 -0
- judgeval/scorers/judgeval_scorers/local_implementations/hallucination/hallucination_scorer.py +258 -0
- judgeval/scorers/judgeval_scorers/local_implementations/hallucination/prompts.py +104 -0
- judgeval/scorers/judgeval_scorers/local_implementations/json_correctness/json_correctness_scorer.py +127 -0
- judgeval/scorers/judgeval_scorers/local_implementations/summarization/__init__.py +3 -0
- judgeval/scorers/judgeval_scorers/local_implementations/summarization/prompts.py +247 -0
- judgeval/scorers/judgeval_scorers/local_implementations/summarization/summarization_scorer.py +541 -0
- judgeval/scorers/judgeval_scorers/local_implementations/tool_correctness/__init__.py +3 -0
- judgeval/scorers/judgeval_scorers/local_implementations/tool_correctness/tool_correctness_scorer.py +151 -0
- judgeval/scorers/prompt_scorer.py +4 -4
- judgeval/scorers/score.py +14 -14
- judgeval/scorers/utils.py +40 -6
- {judgeval-0.0.3.dist-info → judgeval-0.0.4.dist-info}/METADATA +1 -1
- judgeval-0.0.4.dist-info/RECORD +78 -0
- judgeval-0.0.3.dist-info/RECORD +0 -46
- {judgeval-0.0.3.dist-info → judgeval-0.0.4.dist-info}/WHEEL +0 -0
- {judgeval-0.0.3.dist-info → judgeval-0.0.4.dist-info}/licenses/LICENSE.md +0 -0
@@ -0,0 +1,258 @@
|
|
1
|
+
"""
|
2
|
+
Metric that evaluates hallucinations in model outputs
|
3
|
+
|
4
|
+
The hallucination metric determines whether your LLM generates factually correct information by comparing
|
5
|
+
the actual_output to the provided context.
|
6
|
+
|
7
|
+
If you're looking to evaluate hallucination for a RAG system, refer to the faithfulness metric instead.
|
8
|
+
|
9
|
+
The HallucinationMetric uses an LLM to determine, for each context in contexts, whether there are any
|
10
|
+
contradictions to the actual_output.
|
11
|
+
|
12
|
+
Although extremely similar to the FaithfulnessMetric, the HallucinationMetric is calculated differently
|
13
|
+
since it uses contexts as the source of truth instead. Since contexts is the ideal segment of your
|
14
|
+
knowledge base relevant to a specific input, the degree of hallucination can be measured by the degree
|
15
|
+
of which the contexts is disagreed upon.
|
16
|
+
|
17
|
+
Faithfulness is measuring the number of statements in output that agree with contexts.
|
18
|
+
Hallucination is measuring the fraction of contexts that agree with output (do not contradict == agree)
|
19
|
+
"""
|
20
|
+
|
21
|
+
from typing import Optional, Union, List
|
22
|
+
|
23
|
+
from judgeval.scorers.utils import (get_or_create_event_loop,
|
24
|
+
scorer_progress_meter,
|
25
|
+
create_verbose_logs,
|
26
|
+
parse_response_json,
|
27
|
+
check_example_params,
|
28
|
+
)
|
29
|
+
from judgeval.scorers import JudgevalScorer
|
30
|
+
from judgeval.judges import JudgevalJudge
|
31
|
+
from judgeval.judges.utils import create_judge
|
32
|
+
from judgeval.data import Example, ExampleParams
|
33
|
+
from judgeval.scorers.judgeval_scorers.local_implementations.hallucination.prompts import *
|
34
|
+
|
35
|
+
|
36
|
+
required_params = [
|
37
|
+
ExampleParams.INPUT,
|
38
|
+
ExampleParams.ACTUAL_OUTPUT,
|
39
|
+
ExampleParams.CONTEXT,
|
40
|
+
]
|
41
|
+
|
42
|
+
|
43
|
+
class HallucinationScorer(JudgevalScorer):
|
44
|
+
def __init__(
|
45
|
+
self,
|
46
|
+
threshold: float = 0.5,
|
47
|
+
model: Optional[Union[str, JudgevalJudge]] = None,
|
48
|
+
include_reason: bool = True,
|
49
|
+
async_mode: bool = False,
|
50
|
+
strict_mode: bool = False,
|
51
|
+
verbose_mode: bool = False,
|
52
|
+
):
|
53
|
+
self.threshold = 1 if strict_mode else threshold
|
54
|
+
self.model, self.using_native_model = create_judge(model)
|
55
|
+
self.evaluation_model = self.model.get_model_name()
|
56
|
+
self.include_reason = include_reason
|
57
|
+
self.async_mode = async_mode
|
58
|
+
self.strict_mode = strict_mode
|
59
|
+
self.verbose_mode = verbose_mode
|
60
|
+
|
61
|
+
def score_example(
|
62
|
+
self,
|
63
|
+
example: Example,
|
64
|
+
_show_indicator: bool = True,
|
65
|
+
) -> float:
|
66
|
+
check_example_params(example, required_params, self)
|
67
|
+
|
68
|
+
with scorer_progress_meter(self, display_meter=_show_indicator):
|
69
|
+
if self.async_mode:
|
70
|
+
loop = get_or_create_event_loop()
|
71
|
+
loop.run_until_complete(
|
72
|
+
self.a_score_example(example, _show_indicator=False)
|
73
|
+
)
|
74
|
+
else:
|
75
|
+
self.verdicts: List[HallucinationVerdict] = (
|
76
|
+
self._generate_verdicts(
|
77
|
+
example.actual_output, example.context
|
78
|
+
)
|
79
|
+
)
|
80
|
+
self.score = self._calculate_score()
|
81
|
+
self.reason = self._generate_reason()
|
82
|
+
self.success = self.score <= self.threshold
|
83
|
+
self.verbose_logs = create_verbose_logs(
|
84
|
+
self,
|
85
|
+
steps=[
|
86
|
+
f"Verdicts:\n{[v.model_dump() for v in self.verdicts]}",
|
87
|
+
f"Score: {self.score}\nReason: {self.reason}",
|
88
|
+
],
|
89
|
+
)
|
90
|
+
|
91
|
+
return self.score
|
92
|
+
|
93
|
+
async def a_score_example(
|
94
|
+
self,
|
95
|
+
example: Example,
|
96
|
+
_show_indicator: bool = True,
|
97
|
+
) -> float:
|
98
|
+
check_example_params(example, required_params, self)
|
99
|
+
|
100
|
+
with scorer_progress_meter(
|
101
|
+
self, async_mode=True, display_meter=_show_indicator
|
102
|
+
):
|
103
|
+
self.verdicts: List[HallucinationVerdict] = (
|
104
|
+
await self._a_generate_verdicts(
|
105
|
+
example.actual_output, example.context
|
106
|
+
)
|
107
|
+
)
|
108
|
+
self.score = self._calculate_score()
|
109
|
+
self.reason = await self._a_generate_reason()
|
110
|
+
self.success = self.score <= self.threshold
|
111
|
+
self.verbose_logs = create_verbose_logs(
|
112
|
+
self,
|
113
|
+
steps=[
|
114
|
+
f"Verdicts:\n{[v.model_dump() for v in self.verdicts]}",
|
115
|
+
f"Score: {self.score}\nReason: {self.reason}",
|
116
|
+
],
|
117
|
+
)
|
118
|
+
|
119
|
+
return self.score
|
120
|
+
|
121
|
+
async def _a_generate_reason(self):
|
122
|
+
if self.include_reason is False:
|
123
|
+
return None
|
124
|
+
|
125
|
+
contradictions = []
|
126
|
+
for verdict in self.verdicts:
|
127
|
+
if verdict.verdict.strip().lower() == "no":
|
128
|
+
contradictions.append(verdict.reason)
|
129
|
+
|
130
|
+
prompt: dict = HallucinationTemplate.generate_reason(
|
131
|
+
contradictions=contradictions,
|
132
|
+
score=format(self.score, ".2f"),
|
133
|
+
)
|
134
|
+
|
135
|
+
if self.using_native_model:
|
136
|
+
res = await self.model.a_generate(prompt)
|
137
|
+
data = parse_response_json(res, self)
|
138
|
+
return data["reason"]
|
139
|
+
else:
|
140
|
+
try:
|
141
|
+
res: Reason = await self.model.a_generate(prompt, schema=Reason)
|
142
|
+
return res.reason
|
143
|
+
except TypeError:
|
144
|
+
res = await self.model.a_generate(prompt)
|
145
|
+
data = parse_response_json(res, self)
|
146
|
+
return data["reason"]
|
147
|
+
|
148
|
+
def _generate_reason(self):
|
149
|
+
if self.include_reason is False:
|
150
|
+
return None
|
151
|
+
|
152
|
+
factual_alignments = []
|
153
|
+
contradictions = []
|
154
|
+
for verdict in self.verdicts:
|
155
|
+
if verdict.verdict.strip().lower() == "no":
|
156
|
+
contradictions.append(verdict.reason)
|
157
|
+
|
158
|
+
prompt: dict = HallucinationTemplate.generate_reason(
|
159
|
+
factual_alignments=factual_alignments,
|
160
|
+
contradictions=contradictions,
|
161
|
+
score=format(self.score, ".2f"),
|
162
|
+
)
|
163
|
+
|
164
|
+
if self.using_native_model:
|
165
|
+
res = self.model.generate(prompt)
|
166
|
+
data = parse_response_json(res, self)
|
167
|
+
return data["reason"]
|
168
|
+
else:
|
169
|
+
try:
|
170
|
+
res: Reason = self.model.generate(prompt, schema=Reason)
|
171
|
+
return res.reason
|
172
|
+
except TypeError:
|
173
|
+
res = self.model.generate(prompt)
|
174
|
+
data = parse_response_json(res, self)
|
175
|
+
return data["reason"]
|
176
|
+
|
177
|
+
async def _a_generate_verdicts(
|
178
|
+
self, actual_output: str, contexts: List[str]
|
179
|
+
) -> List[HallucinationVerdict]:
|
180
|
+
verdicts: List[HallucinationVerdict] = []
|
181
|
+
prompt = HallucinationTemplate.generate_verdicts(
|
182
|
+
actual_output=actual_output, contexts=contexts
|
183
|
+
)
|
184
|
+
if self.using_native_model:
|
185
|
+
res = await self.model.a_generate(prompt)
|
186
|
+
data = parse_response_json(res, self)
|
187
|
+
verdicts = [
|
188
|
+
HallucinationVerdict(**item) for item in data["verdicts"]
|
189
|
+
]
|
190
|
+
return verdicts
|
191
|
+
else:
|
192
|
+
try:
|
193
|
+
res: Verdicts = await self.model.a_generate(
|
194
|
+
prompt, schema=Verdicts
|
195
|
+
)
|
196
|
+
verdicts = [item for item in res.verdicts]
|
197
|
+
return verdicts
|
198
|
+
except TypeError:
|
199
|
+
res = await self.model.a_generate(prompt)
|
200
|
+
data = parse_response_json(res, self)
|
201
|
+
verdicts = [
|
202
|
+
HallucinationVerdict(**item) for item in data["verdicts"]
|
203
|
+
]
|
204
|
+
return verdicts
|
205
|
+
|
206
|
+
def _generate_verdicts(
|
207
|
+
self, actual_output: str, contexts: List[str]
|
208
|
+
) -> List[HallucinationVerdict]:
|
209
|
+
verdicts: List[HallucinationVerdict] = []
|
210
|
+
prompt = HallucinationTemplate.generate_verdicts(
|
211
|
+
actual_output=actual_output, contexts=contexts
|
212
|
+
)
|
213
|
+
if self.using_native_model:
|
214
|
+
res = self.model.generate(prompt)
|
215
|
+
data = parse_response_json(res, self)
|
216
|
+
verdicts = [
|
217
|
+
HallucinationVerdict(**item) for item in data["verdicts"]
|
218
|
+
]
|
219
|
+
return verdicts
|
220
|
+
else:
|
221
|
+
try:
|
222
|
+
res: Verdicts = self.model.generate(prompt, schema=Verdicts)
|
223
|
+
verdicts = [item for item in res.verdicts]
|
224
|
+
return verdicts
|
225
|
+
except TypeError:
|
226
|
+
res = self.model.generate(prompt)
|
227
|
+
data = parse_response_json(res, self)
|
228
|
+
verdicts = [
|
229
|
+
HallucinationVerdict(**item) for item in data["verdicts"]
|
230
|
+
]
|
231
|
+
return verdicts
|
232
|
+
|
233
|
+
def _calculate_score(self) -> float:
|
234
|
+
number_of_verdicts = len(self.verdicts)
|
235
|
+
if number_of_verdicts == 0:
|
236
|
+
return 0
|
237
|
+
|
238
|
+
hallucination_count = 0
|
239
|
+
for verdict in self.verdicts:
|
240
|
+
if verdict.verdict.strip().lower() == "no":
|
241
|
+
hallucination_count += 1
|
242
|
+
|
243
|
+
score = hallucination_count / number_of_verdicts
|
244
|
+
return 1 if self.strict_mode and score > self.threshold else score
|
245
|
+
|
246
|
+
def _success_check(self) -> bool:
|
247
|
+
if self.error is not None:
|
248
|
+
self.success = False
|
249
|
+
else:
|
250
|
+
try:
|
251
|
+
self.success = self.score <= self.threshold
|
252
|
+
except:
|
253
|
+
self.success = False
|
254
|
+
return self.success
|
255
|
+
|
256
|
+
@property
|
257
|
+
def __name__(self):
|
258
|
+
return "Hallucination"
|
@@ -0,0 +1,104 @@
|
|
1
|
+
from typing import List, Optional
|
2
|
+
from pydantic import BaseModel, Field
|
3
|
+
|
4
|
+
|
5
|
+
class HallucinationVerdict(BaseModel):
|
6
|
+
verdict: str
|
7
|
+
reason: str
|
8
|
+
|
9
|
+
|
10
|
+
class Verdicts(BaseModel):
|
11
|
+
verdicts: List[HallucinationVerdict]
|
12
|
+
|
13
|
+
|
14
|
+
class Reason(BaseModel):
|
15
|
+
reason: str
|
16
|
+
|
17
|
+
|
18
|
+
class HallucinationTemplate:
|
19
|
+
@staticmethod
|
20
|
+
def generate_verdicts(actual_output, contexts):
|
21
|
+
return f"""==== TASK INSTRUCTIONS ====
|
22
|
+
You will be provided with an `actual output` (the response of an LLM to a particular query) and `contexts` (ground truth contextual information from a knowledge base).
|
23
|
+
Your task is to take each context in contexts and determine whether the `actual output` factually agrees with the context.
|
24
|
+
|
25
|
+
Additional notes:
|
26
|
+
You should NOT use any prior knowledge you have in your decision making process; take each context at face value.
|
27
|
+
Since you will determine a verdict for EACH context, the number of 'verdicts' is EXACTLY EQUAL TO the number of contexts.
|
28
|
+
You should be lenient in your judgment when the actual output lacks detail with respect to the context segment; you should ONLY provide a 'no' answer if the context contradicts the actual output.
|
29
|
+
|
30
|
+
==== FORMATTING INSTRUCTIONS ====
|
31
|
+
You should return a JSON object with a key 'verdicts', which is a list of JSON objects. Each JSON object corresponds to a context in `contexts`, and should have 2 fields: 'verdict' and 'reason'.
|
32
|
+
The 'verdict' key should be EXACTLY one of 'yes' or 'no', representing whether the `actual output` factually agrees with the context segment.
|
33
|
+
The 'reason' is the justification for the verdict. If your verdict is 'no', try to provide a correction in the reason.
|
34
|
+
|
35
|
+
==== EXAMPLE ====
|
36
|
+
Example contexts: ["Einstein won the Nobel Prize for his discovery of the photoelectric effect.", "Einstein won the Nobel Prize in 1968."]
|
37
|
+
Example actual output: "Einstein won the Nobel Prize in 1969 for his discovery of the photoelectric effect."
|
38
|
+
|
39
|
+
Example:
|
40
|
+
{{
|
41
|
+
"verdicts": [
|
42
|
+
{{
|
43
|
+
"verdict": "yes",
|
44
|
+
"reason": "The actual output agrees with the provided context which states that Einstein won the Nobel Prize for his discovery of the photoelectric effect."
|
45
|
+
}},
|
46
|
+
{{
|
47
|
+
"verdict": "no",
|
48
|
+
"reason": "The actual output contradicts the provided context which states that Einstein won the Nobel Prize in 1968, not 1969."
|
49
|
+
}}
|
50
|
+
]
|
51
|
+
}}
|
52
|
+
|
53
|
+
==== YOUR TURN ====
|
54
|
+
Contexts:
|
55
|
+
{contexts}
|
56
|
+
|
57
|
+
Actual Output:
|
58
|
+
{actual_output}
|
59
|
+
|
60
|
+
JSON:
|
61
|
+
"""
|
62
|
+
|
63
|
+
@staticmethod
|
64
|
+
def generate_reason(contradictions, score):
|
65
|
+
return f"""==== TASK INSTRUCTIONS ====
|
66
|
+
An LLM has been provided with a list of `contexts` (ground truth contextual information from a knowledge base) and `actual output` (the response of an LLM to a particular query).
|
67
|
+
You will be provided with a list of `contradictions`, which are factual discrepancies between the context segments and the actual output.
|
68
|
+
Additionally, you will be provided with a hallucination score, which is a float (0 - 1, where 0 is the best score) indicating the fraction of context segments that contradict the actual output.
|
69
|
+
|
70
|
+
Your task is to provide a CLEAR and CONCISE reason for the hallucination score.
|
71
|
+
If the hallucination score is 0 (no contradictions), you should instead respond with a positive remark with an upbeat encouraging tone (but don't overblow the kind attitude).
|
72
|
+
|
73
|
+
==== FORMATTING INSTRUCTIONS ====
|
74
|
+
Please make sure to only return in JSON format, with the 'reason' key providing the reason.
|
75
|
+
Example JSON:
|
76
|
+
{{
|
77
|
+
"reason": "The score is <hallucination_score> because <your_reason>."
|
78
|
+
}}
|
79
|
+
|
80
|
+
==== EXAMPLE ====
|
81
|
+
Example Contradictions:
|
82
|
+
[
|
83
|
+
"The actual output claims Einstein won the Nobel Prize in 1969, which contradicts the context stating he won it in 1968.",
|
84
|
+
"The actual output states Einstein was a chemist, but the context indicates he was a physicist.",
|
85
|
+
"The actual output claims Einstein was born in Switzerland, while the context states he was born in Germany."
|
86
|
+
]
|
87
|
+
|
88
|
+
Example Hallucination Score:
|
89
|
+
0.75
|
90
|
+
|
91
|
+
Example Response:
|
92
|
+
{{
|
93
|
+
"reason": "The score is 0.75 because the actual output made multiple factual errors: incorrectly stating Einstein's Nobel Prize year (1969 vs 1968), his profession (chemist vs physicist), and birthplace (Switzerland vs Germany)."
|
94
|
+
}}
|
95
|
+
|
96
|
+
==== YOUR TURN ====
|
97
|
+
Contradictions:
|
98
|
+
{contradictions}
|
99
|
+
|
100
|
+
Hallucination Score:
|
101
|
+
{score}
|
102
|
+
|
103
|
+
JSON:
|
104
|
+
"""
|
judgeval/scorers/judgeval_scorers/local_implementations/json_correctness/json_correctness_scorer.py
ADDED
@@ -0,0 +1,127 @@
|
|
1
|
+
from typing import List, Optional, Union, Any
|
2
|
+
from pydantic import BaseModel, ValidationError, create_model
|
3
|
+
|
4
|
+
from judgeval.judges import JudgevalJudge
|
5
|
+
from judgeval.scorers.utils import (get_or_create_event_loop,
|
6
|
+
scorer_progress_meter,
|
7
|
+
create_verbose_logs,
|
8
|
+
parse_response_json,
|
9
|
+
check_example_params
|
10
|
+
)
|
11
|
+
from judgeval.scorers import JudgevalScorer
|
12
|
+
from judgeval.data import Example, ExampleParams
|
13
|
+
|
14
|
+
|
15
|
+
required_params = [
|
16
|
+
ExampleParams.INPUT,
|
17
|
+
ExampleParams.ACTUAL_OUTPUT
|
18
|
+
]
|
19
|
+
|
20
|
+
|
21
|
+
class JsonCorrectnessScorer(JudgevalScorer):
|
22
|
+
|
23
|
+
def __init__(
|
24
|
+
self,
|
25
|
+
json_schema: Union[BaseModel, dict],
|
26
|
+
model: Optional[Union[str, JudgevalJudge]] = None,
|
27
|
+
threshold: float = 0.5,
|
28
|
+
async_mode: bool = True,
|
29
|
+
strict_mode: bool = False,
|
30
|
+
verbose_mode: bool = False,
|
31
|
+
user: Optional[str] = None
|
32
|
+
):
|
33
|
+
self.score_type = "json_correctness"
|
34
|
+
self.model = model
|
35
|
+
self.threshold = threshold
|
36
|
+
self.async_mode = async_mode
|
37
|
+
self.strict_mode = strict_mode
|
38
|
+
self.verbose_mode = verbose_mode
|
39
|
+
self.user = user
|
40
|
+
|
41
|
+
if isinstance(json_schema, dict):
|
42
|
+
# Convert to BaseModel
|
43
|
+
fields = {
|
44
|
+
key: (str if prop["type"] == "string" else Any, ...)
|
45
|
+
for key, prop in json_schema["properties"].items()
|
46
|
+
}
|
47
|
+
|
48
|
+
# Dynamically create the model
|
49
|
+
DynamicModel = create_model(json_schema["title"], **fields)
|
50
|
+
|
51
|
+
self.json_schema = DynamicModel
|
52
|
+
else:
|
53
|
+
self.json_schema = json_schema
|
54
|
+
|
55
|
+
def score_example(self, example: Example, _show_indicator: bool = True) -> float:
|
56
|
+
check_example_params(example, required_params, self)
|
57
|
+
with scorer_progress_meter(
|
58
|
+
self,
|
59
|
+
async_mode=self.async_mode,
|
60
|
+
display_meter=_show_indicator,
|
61
|
+
):
|
62
|
+
if self.async_mode:
|
63
|
+
loop = get_or_create_event_loop()
|
64
|
+
loop.run_until_complete(
|
65
|
+
self.a_measure(example, _show_indicator=False)
|
66
|
+
)
|
67
|
+
else:
|
68
|
+
valid_json = True
|
69
|
+
try:
|
70
|
+
self.json_schema.model_validate_json(
|
71
|
+
example.actual_output
|
72
|
+
)
|
73
|
+
except ValidationError as e:
|
74
|
+
valid_json = False
|
75
|
+
|
76
|
+
self.score = 1.0 if valid_json else 0
|
77
|
+
self.success = self.score >= self.threshold
|
78
|
+
self.verbose_logs = create_verbose_logs(
|
79
|
+
self,
|
80
|
+
steps=[
|
81
|
+
f"LLM outputed Json:\n{example.actual_output}",
|
82
|
+
f"Score: {self.score}",
|
83
|
+
],
|
84
|
+
)
|
85
|
+
|
86
|
+
return self.score
|
87
|
+
|
88
|
+
async def a_score_example(self, example: Example, _show_indicator: bool = True) -> float:
|
89
|
+
check_example_params(example, required_params, self)
|
90
|
+
with scorer_progress_meter(
|
91
|
+
self,
|
92
|
+
async_mode=self.async_mode,
|
93
|
+
display_meter=_show_indicator,
|
94
|
+
):
|
95
|
+
valid_json = True
|
96
|
+
try:
|
97
|
+
self.json_schema.model_validate_json(
|
98
|
+
example.actual_output
|
99
|
+
)
|
100
|
+
except ValidationError as e:
|
101
|
+
valid_json = False
|
102
|
+
|
103
|
+
self.score = 1.0 if valid_json else 0
|
104
|
+
self.success = self.score >= self.threshold
|
105
|
+
self.verbose_logs = create_verbose_logs(
|
106
|
+
self,
|
107
|
+
steps=[
|
108
|
+
f"LLM outputed Json:\n{example.actual_output}",
|
109
|
+
f"Score: {self.score}",
|
110
|
+
],
|
111
|
+
)
|
112
|
+
return self.score
|
113
|
+
|
114
|
+
def _success_check(self):
|
115
|
+
if self.error is not None:
|
116
|
+
self.success = False
|
117
|
+
else:
|
118
|
+
try:
|
119
|
+
self.success = self.score >= self.threshold
|
120
|
+
except:
|
121
|
+
self.success = False
|
122
|
+
return self.success
|
123
|
+
|
124
|
+
@property
|
125
|
+
def __name__(self):
|
126
|
+
return "JSON Correctness"
|
127
|
+
|