judgeval 0.0.32__py3-none-any.whl → 0.0.33__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.
Files changed (48) hide show
  1. judgeval/common/s3_storage.py +93 -0
  2. judgeval/common/tracer.py +612 -123
  3. judgeval/data/sequence.py +4 -10
  4. judgeval/judgment_client.py +25 -86
  5. judgeval/rules.py +4 -7
  6. judgeval/run_evaluation.py +1 -1
  7. judgeval/scorers/__init__.py +4 -4
  8. judgeval/scorers/judgeval_scorers/__init__.py +0 -176
  9. {judgeval-0.0.32.dist-info → judgeval-0.0.33.dist-info}/METADATA +15 -2
  10. judgeval-0.0.33.dist-info/RECORD +63 -0
  11. judgeval/scorers/base_scorer.py +0 -58
  12. judgeval/scorers/judgeval_scorers/local_implementations/__init__.py +0 -27
  13. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/__init__.py +0 -4
  14. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/answer_correctness_scorer.py +0 -276
  15. judgeval/scorers/judgeval_scorers/local_implementations/answer_correctness/prompts.py +0 -169
  16. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/__init__.py +0 -4
  17. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/answer_relevancy_scorer.py +0 -298
  18. judgeval/scorers/judgeval_scorers/local_implementations/answer_relevancy/prompts.py +0 -174
  19. judgeval/scorers/judgeval_scorers/local_implementations/comparison/__init__.py +0 -0
  20. judgeval/scorers/judgeval_scorers/local_implementations/comparison/comparison_scorer.py +0 -161
  21. judgeval/scorers/judgeval_scorers/local_implementations/comparison/prompts.py +0 -222
  22. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/__init__.py +0 -3
  23. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/contextual_precision_scorer.py +0 -264
  24. judgeval/scorers/judgeval_scorers/local_implementations/contextual_precision/prompts.py +0 -106
  25. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/__init__.py +0 -3
  26. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/contextual_recall_scorer.py +0 -254
  27. judgeval/scorers/judgeval_scorers/local_implementations/contextual_recall/prompts.py +0 -142
  28. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/__init__.py +0 -3
  29. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/contextual_relevancy_scorer.py +0 -245
  30. judgeval/scorers/judgeval_scorers/local_implementations/contextual_relevancy/prompts.py +0 -121
  31. judgeval/scorers/judgeval_scorers/local_implementations/execution_order/__init__.py +0 -3
  32. judgeval/scorers/judgeval_scorers/local_implementations/execution_order/execution_order.py +0 -156
  33. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/__init__.py +0 -3
  34. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/faithfulness_scorer.py +0 -318
  35. judgeval/scorers/judgeval_scorers/local_implementations/faithfulness/prompts.py +0 -268
  36. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/__init__.py +0 -3
  37. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/hallucination_scorer.py +0 -264
  38. judgeval/scorers/judgeval_scorers/local_implementations/hallucination/prompts.py +0 -104
  39. judgeval/scorers/judgeval_scorers/local_implementations/instruction_adherence/instruction_adherence.py +0 -232
  40. judgeval/scorers/judgeval_scorers/local_implementations/instruction_adherence/prompt.py +0 -102
  41. judgeval/scorers/judgeval_scorers/local_implementations/json_correctness/__init__.py +0 -5
  42. judgeval/scorers/judgeval_scorers/local_implementations/json_correctness/json_correctness_scorer.py +0 -134
  43. judgeval/scorers/judgeval_scorers/local_implementations/summarization/__init__.py +0 -3
  44. judgeval/scorers/judgeval_scorers/local_implementations/summarization/prompts.py +0 -247
  45. judgeval/scorers/judgeval_scorers/local_implementations/summarization/summarization_scorer.py +0 -551
  46. judgeval-0.0.32.dist-info/RECORD +0 -97
  47. {judgeval-0.0.32.dist-info → judgeval-0.0.33.dist-info}/WHEEL +0 -0
  48. {judgeval-0.0.32.dist-info → judgeval-0.0.33.dist-info}/licenses/LICENSE.md +0 -0
@@ -1,268 +0,0 @@
1
- from typing import List, Optional
2
- from pydantic import BaseModel, Field
3
-
4
-
5
- class FaithfulnessVerdict(BaseModel):
6
- verdict: str
7
- reason: Optional[str] = Field(default=None)
8
-
9
-
10
- class Verdicts(BaseModel):
11
- verdicts: List[FaithfulnessVerdict]
12
-
13
-
14
- class Truths(BaseModel):
15
- truths: List[str]
16
-
17
-
18
- class Claims(BaseModel):
19
- claims: List[str]
20
-
21
-
22
- class Reason(BaseModel):
23
- reason: str
24
-
25
-
26
- class FaithfulnessTemplate:
27
- @staticmethod
28
- def find_claims(text):
29
- return f"""==== TASK INSTRUCTIONS ====
30
- You will be provided with a passage of text. Based on the text, your task is to generate a comprehensive list of ALL CLAIMS that can be inferred from the text.
31
- For every claim that you derive from the text, provide the source of the claim via quoting the original text. Please try to extract EVERY CLAIM that is in the original text; priortize generating the most claims rather than being concise.
32
- You should NOT include any prior knowledge, and take the text at face value when extracting claims.
33
-
34
- ==== FORMATTING YOUR ANSWER ====
35
- Please return your answer in JSON format, with the "claims" key as a list of JSON objects with keys "claim" and "quote". No words or explanation beyond the output JSON is needed.
36
-
37
- ==== EXAMPLES ====
38
-
39
- ---- START OF EXAMPLE 1 ----
40
- Example Text:
41
- "Einstein won the nobel prize in 1968 for his discovery of the photoelectric effect."
42
-
43
- Example JSON:
44
- {{
45
- "claims": [
46
- {{
47
- "claim": "Einstein won the nobel prize for his discovery of the photoelectric effect.",
48
- "quote": "Einstein won the nobel prize in 1968 for his discovery of the photoelectric effect."
49
- }},
50
- {{
51
- "claim": "Einstein won the nobel prize in 1968.",
52
- "quote": "Einstein won the nobel prize in 1968 for his discovery of the photoelectric effect."
53
- }}
54
- ]
55
- }}
56
- ---- END OF EXAMPLE 1 ----
57
-
58
- ---- START OF EXAMPLE 2 ----
59
- Example Text: "The Wright brothers successfully flew the first powered airplane on December 17, 1903, in Kitty Hawk, North Carolina."
60
-
61
- {{
62
- "claims": [
63
- {{
64
- "claim": "The Wright brothers flew the first powered airplane.",
65
- "quote": "The Wright brothers successfully flew the first powered airplane on December 17, 1903, in Kitty Hawk, North Carolina."
66
- }},
67
- {{
68
- "claim": "The Wright brothers made their flight in Kitty Hawk, North Carolina.",
69
- "quote": "The Wright brothers successfully flew the first powered airplane on December 17, 1903, in Kitty Hawk, North Carolina."
70
- }},
71
- {{
72
- "claim": "The first powered airplane flight occurred on December 17, 1903.",
73
- "quote": "The Wright brothers successfully flew the first powered airplane on December 17, 1903, in Kitty Hawk, North Carolina."
74
- }}
75
- ]
76
- }}
77
- ---- END OF EXAMPLE 2 ----
78
-
79
- ---- START OF EXAMPLE 3 ----
80
- Example Text:
81
- "The Great Wall of China was built over many centuries by different Chinese dynasties. Construction began more than 2,000 years ago during the Warring States period. The most famous sections were built during the Ming Dynasty. The wall stretches for thousands of miles across northern China and was primarily built for military defense."
82
-
83
- Example JSON:
84
- {{
85
- "claims": [
86
- {{
87
- "claim": "The Great Wall of China was built by multiple Chinese dynasties",
88
- "quote": "The Great Wall of China was built over many centuries by different Chinese dynasties."
89
- }},
90
- {{
91
- "claim": "Construction of the Great Wall began over 2,000 years ago",
92
- "quote": "Construction began more than 2,000 years ago during the Warring States period."
93
- }},
94
- {{
95
- "claim": "Construction started during the Warring States period",
96
- "quote": "Construction began more than 2,000 years ago during the Warring States period."
97
- }},
98
- {{
99
- "claim": "The most well-known parts of the wall were constructed during the Ming Dynasty",
100
- "quote": "The most famous sections were built during the Ming Dynasty."
101
- }},
102
- {{
103
- "claim": "The Great Wall extends for thousands of miles",
104
- "quote": "The wall stretches for thousands of miles across northern China"
105
- }},
106
- {{
107
- "claim": "The wall is located in northern China",
108
- "quote": "The wall stretches for thousands of miles across northern China"
109
- }},
110
- {{
111
- "claim": "The Great Wall was constructed for defensive military purposes",
112
- "quote": "was primarily built for military defense."
113
- }}
114
- ]
115
- }}
116
- ---- END OF EXAMPLE 3 ----
117
-
118
- ==== END OF EXAMPLES ====
119
-
120
- ==== YOUR TURN ====
121
-
122
- Example Text:
123
- {text}
124
-
125
- JSON:
126
- """
127
-
128
- @staticmethod
129
- def create_verdicts(claims, retrieval_context):
130
- return f"""==== TASK INSTRUCTIONS ====
131
- You will be provided with a list of claims from an LLM's output text, accompanied by the retrieval documents that the LLM used to generate the output.
132
- I'm pretty sure that many of the claims are factually contradictory to the retrieval context, but I want you to double check that I'm right.
133
- For each claim, choose one of ("yes", "no", or "idk") to represent whether the claim is correct based on the retrieval context.
134
- YOU SHOULD be very scrutinous--if any part of the claim is contradicted by the retrieval context, you should choose "no". Think really hard about finding the contradictions, since they can be subtle!
135
-
136
- Choose 'no' if the retrieval context CONTRADICTS the claims. YOU SHOULD NEVER USE YOUR PRIOR KNOWLEDGE IN YOUR JUDGMENT.
137
- Claims made using vague, suggestive, or speculative language such as 'may have', 'possibility due to', do NOT count as a contradiction.
138
- Claims that are fuzzy based on lack of information MUST BE ANSWERED with 'idk'.
139
-
140
- ==== FORMATTING YOUR ANSWER ====
141
- Please return your answer in JSON format, with the 'verdicts' key as a list of JSON objects. Each JSON object should have 2 fields: 'verdict' and 'reason'.
142
- The 'verdict' key should be either 'yes', 'no', or 'idk', which states WHETHER THE CLAIM AGREES with the context.
143
- The 'reason' key should be a string explaining why the claim is 'yes', 'no', or 'idk'. Make specific reference to the retrieval context to justify your verdict.
144
-
145
- ==== EXAMPLES ====
146
- ---- START OF EXAMPLE 1 ----
147
- Example retrieval contexts: "Einstein won the Nobel Prize for his discovery of the photoelectric effect. Einstein won the Nobel Prize in 1968. Einstein is a German Scientist."
148
- Example claims: ["Barack Obama is a caucasian male.", "Zurich is a city in London", "Einstein won the Nobel Prize for the discovery of the photoelectric effect which may have contributed to his fame.", "Einstein won the Nobel Prize in 1969 for his discovery of the photoelectric effect.", "Einstein was a Germen chef."]
149
-
150
- Example JSON:
151
- {{
152
- "verdicts": [
153
- {{
154
- "verdict": "idk",
155
- "reason": "The claim about Barack Obama's ethnicity cannot be verified from the given retrieval context as it contains no information about Barack Obama."
156
- }},
157
- {{
158
- "verdict": "idk",
159
- "reason": "The claim about Zurich being a city in London cannot be verified from the given retrieval context as it contains no information about Zurich or London."
160
- }},
161
- {{
162
- "verdict": "yes",
163
- "reason": "The retrieval context confirms that Einstein won the Nobel Prize for discovering the photoelectric effect."
164
- }},
165
- {{
166
- "verdict": "no",
167
- "reason": "The actual output claims Einstein won the Nobel Prize in 1969, which is untrue as the retrieval context states it is 1968 instead."
168
- }},
169
- {{
170
- "verdict": "no",
171
- "reason": "The actual output claims Einstein is a Germen chef, which is not correct as the retrieval context states he was a German scientist instead."
172
- }}
173
- ]
174
- }}
175
- ---- END OF EXAMPLE 1 ----
176
- ---- START OF EXAMPLE 2 ----
177
- Example retrieval contexts: "The Great Wall of China was built over many centuries by different Chinese dynasties. Construction began more than 2,000 years ago. The wall stretches for thousands of miles across China's northern borders. Most of the existing wall was built during the Ming Dynasty."
178
- Example claims: ["The Great Wall was built in a single year.", "The Great Wall may have taken centuries to complete.", "The Great Wall was built by the Romans.", "The Great Wall is located in China's northern region.", "The Great Wall is 100 meters long."]
179
-
180
- Example JSON:
181
- {{
182
- "verdicts": [
183
- {{
184
- "verdict": "no",
185
- "reason": "The claim that the Great Wall was built in a single year directly contradicts the retrieval context, which states it was built over many centuries."
186
- }},
187
- {{
188
- "verdict": "yes",
189
- "reason": "The retrieval context confirms that the Great Wall was built over many centuries by different Chinese dynasties."
190
- }},
191
- {{
192
- "verdict": "no",
193
- "reason": "The claim states the Romans built the wall, which contradicts the retrieval context that specifies it was built by Chinese dynasties."
194
- }},
195
- {{
196
- "verdict": "yes",
197
- "reason": "The retrieval context explicitly states that the wall stretches across China's northern borders."
198
- }},
199
- {{
200
- "verdict": "no",
201
- "reason": "The claim that the wall is 100 meters long contradicts the retrieval context which states it stretches for thousands of miles."
202
- }}
203
- ]
204
- }}
205
- ---- END OF EXAMPLE 2 ----
206
- ==== END OF EXAMPLES ====
207
-
208
- ==== YOUR TURN ====
209
- Retrieval Contexts:
210
- {retrieval_context}
211
-
212
- Claims:
213
- {claims}
214
-
215
- JSON:
216
- """
217
-
218
- @staticmethod
219
- def justify_reason(score, contradictions):
220
- return f"""==== TASK INSTRUCTIONS ====
221
- You will be provided with a list of contradictions and a faithfulness score.
222
- The list of contradictions will be references to statements made by a RAG generator that contradicted one or more document(s) from the retrieval context.
223
- - To clarify, the LLM produced an `actual output` that contained claims that contradicted the `retrieval context` used to produce the output.
224
- The faithfulness score is a 0 - 1 float (1 is highest) indicating how factually consistent the RAG generator's output is to the retrieval context.
225
-
226
- Your task is to CLEARLY and CONCISELY summarize the contradictions to justify the score.
227
- If there are no contradictions, just say something positive with an upbeat encouraging tone (but don't overdo it otherwise it gets annoying).
228
- Your reason MUST use information from the contradictions in your reason.
229
-
230
-
231
- ==== FORMATTING YOUR ANSWER ====
232
- Please make sure to only return in JSON format, with the 'reason' key providing the reason.
233
-
234
- Example JSON:
235
- {{
236
- "reason": "The score is <faithfulness_score> because <your_reason>."
237
- }}
238
-
239
- ==== EXAMPLE ====
240
- Example Contradictions:
241
- [
242
- {{
243
- "verdict": "no",
244
- "reason": "The output claims Marie Curie was born in Russia, but the context clearly states she was born in Warsaw, Poland."
245
- }},
246
- {{
247
- "verdict": "no",
248
- "reason": "The output states Marie Curie discovered uranium, but the context indicates she discovered radium and polonium."
249
- }}
250
- ]
251
-
252
- Example Faithfulness Score:
253
- 0.60
254
-
255
- Example Response:
256
- {{
257
- "reason": "The score is 0.60 because the output made two significant factual errors: incorrectly stating Marie Curie was born in Russia instead of Poland, and wrongly attributing the discovery of uranium to her instead of radium and polonium."
258
- }}
259
-
260
- ==== YOUR TURN ====
261
- Faithfulness Score:
262
- {score}
263
-
264
- Contradictions:
265
- {contradictions}
266
-
267
- JSON:
268
- """
@@ -1,3 +0,0 @@
1
- from judgeval.scorers.judgeval_scorers.local_implementations.hallucination.hallucination_scorer import HallucinationScorer
2
-
3
- __all__ = ["HallucinationScorer"]
@@ -1,264 +0,0 @@
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.constants import APIScorer
24
- from judgeval.scorers.utils import (
25
- get_or_create_event_loop,
26
- scorer_progress_meter,
27
- create_verbose_logs,
28
- parse_response_json,
29
- check_example_params,
30
- )
31
- from judgeval.scorers import JudgevalScorer
32
- from judgeval.judges import JudgevalJudge
33
- from judgeval.judges.utils import create_judge
34
- from judgeval.data import Example, ExampleParams
35
- from judgeval.scorers.judgeval_scorers.local_implementations.hallucination.prompts import *
36
-
37
-
38
- required_params = [
39
- ExampleParams.INPUT,
40
- ExampleParams.ACTUAL_OUTPUT,
41
- ExampleParams.CONTEXT,
42
- ]
43
-
44
-
45
- class HallucinationScorer(JudgevalScorer):
46
- def __init__(
47
- self,
48
- threshold: float = 0.5,
49
- model: Optional[Union[str, JudgevalJudge]] = None,
50
- include_reason: bool = True,
51
- async_mode: bool = False,
52
- strict_mode: bool = False,
53
- verbose_mode: bool = False,
54
- ):
55
- super().__init__(
56
- score_type=APIScorer.HALLUCINATION,
57
- threshold=1 if strict_mode else threshold,
58
- evaluation_model=None,
59
- include_reason=include_reason,
60
- async_mode=async_mode,
61
- strict_mode=strict_mode,
62
- verbose_mode=verbose_mode
63
- )
64
- self.model, self.using_native_model = create_judge(model)
65
- self.evaluation_model = self.model.get_model_name()
66
-
67
- def score_example(
68
- self,
69
- example: Example,
70
- _show_indicator: bool = True,
71
- ) -> float:
72
- check_example_params(example, required_params, self)
73
-
74
- with scorer_progress_meter(self, display_meter=_show_indicator):
75
- if self.async_mode:
76
- loop = get_or_create_event_loop()
77
- loop.run_until_complete(
78
- self.a_score_example(example, _show_indicator=False)
79
- )
80
- else:
81
- self.verdicts: List[HallucinationVerdict] = (
82
- self._generate_verdicts(
83
- example.actual_output, example.context
84
- )
85
- )
86
- self.score = self._calculate_score()
87
- self.reason = self._generate_reason()
88
- self.success = self.score <= self.threshold
89
- self.verbose_logs = create_verbose_logs(
90
- self,
91
- steps=[
92
- f"Verdicts:\n{[v.model_dump() for v in self.verdicts]}",
93
- f"Score: {self.score}\nReason: {self.reason}",
94
- ],
95
- )
96
-
97
- return self.score
98
-
99
- async def a_score_example(
100
- self,
101
- example: Example,
102
- _show_indicator: bool = True,
103
- ) -> float:
104
- check_example_params(example, required_params, self)
105
-
106
- with scorer_progress_meter(
107
- self, async_mode=True, display_meter=_show_indicator
108
- ):
109
- self.verdicts: List[HallucinationVerdict] = (
110
- await self._a_generate_verdicts(
111
- example.actual_output, example.context
112
- )
113
- )
114
- self.score = self._calculate_score()
115
- self.reason = await self._a_generate_reason()
116
- self.success = self.score <= self.threshold
117
- self.verbose_logs = create_verbose_logs(
118
- self,
119
- steps=[
120
- f"Verdicts:\n{[v.model_dump() for v in self.verdicts]}",
121
- f"Score: {self.score}\nReason: {self.reason}",
122
- ],
123
- )
124
-
125
- return self.score
126
-
127
- async def _a_generate_reason(self):
128
- if self.include_reason is False:
129
- return None
130
-
131
- contradictions = []
132
- for verdict in self.verdicts:
133
- if verdict.verdict.strip().lower() == "no":
134
- contradictions.append(verdict.reason)
135
-
136
- prompt: dict = HallucinationTemplate.generate_reason(
137
- contradictions=contradictions,
138
- score=format(self.score, ".2f"),
139
- )
140
-
141
- if self.using_native_model:
142
- res = await self.model.a_generate(prompt)
143
- data = parse_response_json(res, self)
144
- return data["reason"]
145
- else:
146
- try:
147
- res: Reason = await self.model.a_generate(prompt, schema=Reason)
148
- return res.reason
149
- except TypeError:
150
- res = await self.model.a_generate(prompt)
151
- data = parse_response_json(res, self)
152
- return data["reason"]
153
-
154
- def _generate_reason(self):
155
- if self.include_reason is False:
156
- return None
157
-
158
- factual_alignments = []
159
- contradictions = []
160
- for verdict in self.verdicts:
161
- if verdict.verdict.strip().lower() == "no":
162
- contradictions.append(verdict.reason)
163
-
164
- prompt: dict = HallucinationTemplate.generate_reason(
165
- factual_alignments=factual_alignments,
166
- contradictions=contradictions,
167
- score=format(self.score, ".2f"),
168
- )
169
-
170
- if self.using_native_model:
171
- res = self.model.generate(prompt)
172
- data = parse_response_json(res, self)
173
- return data["reason"]
174
- else:
175
- try:
176
- res: Reason = self.model.generate(prompt, schema=Reason)
177
- return res.reason
178
- except TypeError:
179
- res = self.model.generate(prompt)
180
- data = parse_response_json(res, self)
181
- return data["reason"]
182
-
183
- async def _a_generate_verdicts(
184
- self, actual_output: str, contexts: List[str]
185
- ) -> List[HallucinationVerdict]:
186
- verdicts: List[HallucinationVerdict] = []
187
- prompt = HallucinationTemplate.generate_verdicts(
188
- actual_output=actual_output, contexts=contexts
189
- )
190
- if self.using_native_model:
191
- res = await self.model.a_generate(prompt)
192
- data = parse_response_json(res, self)
193
- verdicts = [
194
- HallucinationVerdict(**item) for item in data["verdicts"]
195
- ]
196
- return verdicts
197
- else:
198
- try:
199
- res: Verdicts = await self.model.a_generate(
200
- prompt, schema=Verdicts
201
- )
202
- verdicts = [item for item in res.verdicts]
203
- return verdicts
204
- except TypeError:
205
- res = await self.model.a_generate(prompt)
206
- data = parse_response_json(res, self)
207
- verdicts = [
208
- HallucinationVerdict(**item) for item in data["verdicts"]
209
- ]
210
- return verdicts
211
-
212
- def _generate_verdicts(
213
- self, actual_output: str, contexts: List[str]
214
- ) -> List[HallucinationVerdict]:
215
- verdicts: List[HallucinationVerdict] = []
216
- prompt = HallucinationTemplate.generate_verdicts(
217
- actual_output=actual_output, contexts=contexts
218
- )
219
- if self.using_native_model:
220
- res = self.model.generate(prompt)
221
- data = parse_response_json(res, self)
222
- verdicts = [
223
- HallucinationVerdict(**item) for item in data["verdicts"]
224
- ]
225
- return verdicts
226
- else:
227
- try:
228
- res: Verdicts = self.model.generate(prompt, schema=Verdicts)
229
- verdicts = [item for item in res.verdicts]
230
- return verdicts
231
- except TypeError:
232
- res = self.model.generate(prompt)
233
- data = parse_response_json(res, self)
234
- verdicts = [
235
- HallucinationVerdict(**item) for item in data["verdicts"]
236
- ]
237
- return verdicts
238
-
239
- def _calculate_score(self) -> float:
240
- number_of_verdicts = len(self.verdicts)
241
- if number_of_verdicts == 0:
242
- return 0
243
-
244
- hallucination_count = 0
245
- for verdict in self.verdicts:
246
- if verdict.verdict.strip().lower() == "no":
247
- hallucination_count += 1
248
-
249
- score = hallucination_count / number_of_verdicts
250
- return 1 if self.strict_mode and score > self.threshold else score
251
-
252
- def _success_check(self) -> bool:
253
- if self.error is not None:
254
- self.success = False
255
- else:
256
- try:
257
- self.success = self.score <= self.threshold
258
- except:
259
- self.success = False
260
- return self.success
261
-
262
- @property
263
- def __name__(self):
264
- return "Hallucination"
@@ -1,104 +0,0 @@
1
- from typing import List
2
- from pydantic import BaseModel
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
- """