oceansweep commited on
Commit
0ba7261
·
verified ·
1 Parent(s): b3d35a8

Delete App_Function_Libraries/ms_g_eval.py

Browse files
Files changed (1) hide show
  1. App_Function_Libraries/ms_g_eval.py +0 -473
App_Function_Libraries/ms_g_eval.py DELETED
@@ -1,473 +0,0 @@
1
- #######################################################################################################################
2
- #
3
- # geval.py
4
- #
5
- # Description: This file contains the code to evaluate the generated text using G-Eval metric.
6
- #
7
- # Scripts taken from https://github.com/microsoft/promptflow/tree/main/examples/flows/evaluation/eval-summarization and modified.
8
- #
9
- import configparser
10
- import inspect
11
- import json
12
- import logging
13
- import re
14
- from typing import Dict, Callable, List, Any
15
-
16
- import gradio as gr
17
- from tenacity import (
18
- RetryError,
19
- Retrying,
20
- after_log,
21
- before_sleep_log,
22
- stop_after_attempt,
23
- wait_random_exponential,
24
- )
25
-
26
- from App_Function_Libraries.Chat import chat_api_call
27
-
28
- #
29
- #######################################################################################################################
30
- #
31
- # Start of G-Eval.py
32
-
33
- logger = logging.getLogger(__name__)
34
- config = configparser.ConfigParser()
35
- config.read('config.txt')
36
-
37
- def aggregate(
38
- fluency_list: List[float],
39
- consistency_list: List[float],
40
- relevance_list: List[float],
41
- coherence_list: List[float],
42
- ) -> Dict[str, float]:
43
- """
44
- Takes list of scores for 4 dims and outputs average for them.
45
-
46
- Args:
47
- fluency_list (List(float)): list of fluency scores
48
- consistency_list (List(float)): list of consistency scores
49
- relevance_list (List(float)): list of relevance scores
50
- coherence_list (List(float)): list of coherence scores
51
-
52
- Returns:
53
- Dict[str, float]: Returns average scores
54
- """
55
- average_fluency = sum(fluency_list) / len(fluency_list)
56
- average_consistency = sum(consistency_list) / len(consistency_list)
57
- average_relevance = sum(relevance_list) / len(relevance_list)
58
- average_coherence = sum(coherence_list) / len(coherence_list)
59
-
60
- log_metric("average_fluency", average_fluency)
61
- log_metric("average_consistency", average_consistency)
62
- log_metric("average_relevance", average_relevance)
63
- log_metric("average_coherence", average_coherence)
64
-
65
- return {
66
- "average_fluency": average_fluency,
67
- "average_consistency": average_consistency,
68
- "average_relevance": average_relevance,
69
- "average_coherence": average_coherence,
70
- }
71
-
72
- def run_geval(document, summary, api_key, api_name=None, save=False):
73
- prompts = {
74
- "coherence": """You will be given one summary written for a source document.
75
-
76
- Your task is to rate the summary on one metric.
77
-
78
- Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed.
79
-
80
- Evaluation Criteria:
81
-
82
- Coherence (1-5) - the collective quality of all sentences. We align this dimension with the DUC quality question of structure and coherence whereby "the summary should be well-structured and well-organized. The summary should not just be a heap of related information, but should build from sentence to a coherent body of information about a topic."
83
-
84
- Evaluation Steps:
85
-
86
- 1. Read the source document carefully and identify the main topic and key points.
87
- 2. Read the summary and compare it to the source document. Check if the summary covers the main topic and key points of the source document, and if it presents them in a clear and logical order.
88
- 3. Assign a score for coherence on a scale of 1 to 5, where 1 is the lowest and 5 is the highest based on the Evaluation Criteria.
89
-
90
-
91
- Example:
92
-
93
-
94
- Source Document:
95
-
96
- {{Document}}
97
-
98
- Summary:
99
-
100
- {{Summary}}
101
-
102
-
103
- Evaluation Form (scores ONLY):
104
-
105
- - Coherence:""",
106
- "consistency": """You will be given a source document. You will then be given one summary written for this source document.
107
-
108
- Your task is to rate the summary on one metric.
109
-
110
- Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed.
111
-
112
-
113
- Evaluation Criteria:
114
-
115
- Consistency (1-5) - the factual alignment between the summary and the summarized source. A factually consistent summary contains only statements that are entailed by the source document. Annotators were also asked to penalize summaries that contained hallucinated facts.
116
-
117
- Evaluation Steps:
118
-
119
- 1. Read the source document carefully and identify the main facts and details it presents.
120
- 2. Read the summary and compare it to the source document. Check if the summary contains any factual errors that are not supported by the source document.
121
- 3. Assign a score for consistency based on the Evaluation Criteria.
122
-
123
-
124
- Example:
125
-
126
-
127
- Source Document:
128
-
129
- {{Document}}
130
-
131
- Summary:
132
-
133
- {{Summary}}
134
-
135
-
136
- Evaluation Form (scores ONLY):
137
-
138
- - Consistency:""",
139
- "fluency": """You will be given one summary written for a source document.
140
-
141
- Your task is to rate the summary on one metric.
142
-
143
- Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed.
144
-
145
-
146
- Evaluation Criteria:
147
-
148
- Fluency (1-3): the quality of the summary in terms of grammar, spelling, punctuation, word choice, and sentence structure.
149
-
150
- - 1: Poor. The summary has many errors that make it hard to understand or sound unnatural.
151
- - 2: Fair. The summary has some errors that affect the clarity or smoothness of the text, but the main points are still comprehensible.
152
- - 3: Good. The summary has few or no errors and is easy to read and follow.
153
-
154
-
155
- Example:
156
-
157
- Summary:
158
-
159
- {{Summary}}
160
-
161
-
162
- Evaluation Form (scores ONLY):
163
-
164
- - Fluency (1-3):""",
165
- "relevance": """You will be given one summary written for a source document.
166
-
167
- Your task is to rate the summary on one metric.
168
-
169
- Please make sure you read and understand these instructions carefully. Please keep this document open while reviewing, and refer to it as needed.
170
-
171
- Evaluation Criteria:
172
-
173
- Relevance (1-5) - selection of important content from the source. The summary should include only important information from the source document. Annotators were instructed to penalize summaries which contained redundancies and excess information.
174
-
175
- Evaluation Steps:
176
-
177
- 1. Read the summary and the source document carefully.
178
- 2. Compare the summary to the source document and identify the main points of the source document.
179
- 3. Assess how well the summary covers the main points of the source document, and how much irrelevant or redundant information it contains.
180
- 4. Assign a relevance score from 1 to 5.
181
-
182
-
183
- Example:
184
-
185
-
186
- Source Document:
187
-
188
- {{Document}}
189
-
190
- Summary:
191
-
192
- {{Summary}}
193
-
194
-
195
- Evaluation Form (scores ONLY):
196
-
197
- - Relevance:"""
198
- }
199
-
200
- scores = {}
201
- for metric, prompt in prompts.items():
202
- full_prompt = prompt.replace("{{Document}}", document).replace("{{Summary}}", summary)
203
- try:
204
- score = geval_summarization(full_prompt, 5 if metric != "fluency" else 3, api_name, api_key)
205
- scores[metric] = score
206
- except Exception as e:
207
- error_message = detailed_api_error(api_name, e)
208
- return error_message
209
-
210
- avg_scores = aggregate([scores['fluency']], [scores['consistency']],
211
- [scores['relevance']], [scores['coherence']])
212
-
213
- results = {
214
- "scores": scores,
215
- "average_scores": avg_scores
216
- }
217
- logging.debug("Results: %s", results)
218
-
219
- if save:
220
- logging.debug("Saving results to geval_results.json")
221
- save_eval_results(results)
222
- logging.debug("Results saved to geval_results.json")
223
-
224
- return (f"Coherence: {scores['coherence']:.2f}\n"
225
- f"Consistency: {scores['consistency']:.2f}\n"
226
- f"Fluency: {scores['fluency']:.2f}\n"
227
- f"Relevance: {scores['relevance']:.2f}\n"
228
- f"Average Scores:\n"
229
- f" Fluency: {avg_scores['average_fluency']:.2f}\n"
230
- f" Consistency: {avg_scores['average_consistency']:.2f}\n"
231
- f" Relevance: {avg_scores['average_relevance']:.2f}\n"
232
- f" Coherence: {avg_scores['average_coherence']:.2f}\n"
233
- f"Results saved to geval_results.json")
234
-
235
-
236
- def create_geval_tab():
237
- with gr.Tab("G-Eval"):
238
- gr.Markdown("# G-Eval Summarization Evaluation")
239
- with gr.Row():
240
- with gr.Column():
241
- document_input = gr.Textbox(label="Source Document", lines=10)
242
- summary_input = gr.Textbox(label="Summary", lines=5)
243
- api_name_input = gr.Dropdown(
244
- choices=["OpenAI", "Anthropic", "Cohere", "Groq", "OpenRouter", "DeepSeek", "HuggingFace", "Mistral", "Llama.cpp", "Kobold", "Ooba", "Tabbyapi", "VLLM", "Local-LLM", "Ollama"],
245
- label="Select API"
246
- )
247
- api_key_input = gr.Textbox(label="API Key (if required)", type="password")
248
- save_value = gr.Checkbox(label="Save Results to a JSON file(geval_results.json)")
249
- evaluate_button = gr.Button("Evaluate Summary")
250
- with gr.Column():
251
- output = gr.Textbox(label="Evaluation Results", lines=10)
252
-
253
- evaluate_button.click(
254
- fn=run_geval,
255
- inputs=[document_input, summary_input, api_name_input, api_key_input, save_value],
256
- outputs=output
257
- )
258
-
259
- return document_input, summary_input, api_name_input, api_key_input, evaluate_button, output
260
-
261
-
262
- def parse_output(output: str, max: float) -> float:
263
- """
264
- Function that extracts numerical score from the beginning of string
265
-
266
- Args:
267
- output (str): String to search
268
- max (float): Maximum score allowed
269
-
270
- Returns:
271
- float: The extracted score
272
- """
273
- matched: List[str] = re.findall(r"(?<!\S)\d+(?:\.\d+)?", output)
274
- if matched:
275
- if len(matched) == 1:
276
- score = float(matched[0])
277
- if score > max:
278
- raise ValueError(f"Parsed number: {score} was larger than max score: {max}")
279
- else:
280
- raise ValueError(f"More than one number detected in input. Input to parser was: {output}")
281
- else:
282
- raise ValueError(f'No number detected in input. Input to parser was "{output}". ')
283
- return score
284
-
285
- def geval_summarization(
286
- prompt_with_src_and_gen: str,
287
- max_score: float,
288
- api_endpoint: str,
289
- api_key: str,
290
- ) -> float:
291
- model = get_model_from_config(api_endpoint)
292
-
293
- try:
294
- for attempt in Retrying(
295
- reraise=True,
296
- before_sleep=before_sleep_log(logger, logging.INFO),
297
- after=after_log(logger, logging.INFO),
298
- wait=wait_random_exponential(multiplier=1, min=1, max=120),
299
- stop=stop_after_attempt(10),
300
- ):
301
- with attempt:
302
- system_message="You are a helpful AI assistant"
303
- # TEMP setting for Confabulation check
304
- temp = 0.7
305
- logging.info(f"Debug - geval_summarization Function - API Endpoint: {api_endpoint}")
306
- try:
307
- response = chat_api_call(api_endpoint, api_key, prompt_with_src_and_gen, "", temp, system_message)
308
- except Exception as e:
309
- raise ValueError(f"Unsupported API endpoint: {api_endpoint}")
310
- except RetryError:
311
- logger.exception(f"geval {api_endpoint} call failed\nInput prompt was: {prompt_with_src_and_gen}")
312
- raise
313
-
314
- try:
315
- score = parse_output(response, max_score)
316
- except ValueError as e:
317
- logger.warning(f"Error parsing output: {e}")
318
- score = 0
319
-
320
- return score
321
-
322
-
323
- def get_model_from_config(api_name: str) -> str:
324
- model = config.get('models', api_name)
325
- if isinstance(model, dict):
326
- # If the model is a dictionary, return a specific key or a default value
327
- return model.get('name', str(model)) # Adjust 'name' to the appropriate key if needed
328
- return str(model) if model is not None else ""
329
-
330
- def aggregate_llm_scores(llm_responses: List[str], max_score: float) -> float:
331
- """Parse and average valid scores from the generated responses of
332
- the G-Eval LLM call.
333
-
334
- Args:
335
- llm_responses (List[str]): List of scores from multiple LLMs
336
- max_score (float): The maximum score allowed.
337
-
338
- Returns:
339
- float: The average of all the valid scores
340
- """
341
- all_scores = []
342
- error_count = 0
343
- for generated in llm_responses:
344
- try:
345
- parsed = parse_output(generated, max_score)
346
- all_scores.append(parsed)
347
- except ValueError as e:
348
- logger.warning(e)
349
- error_count += 1
350
- if error_count:
351
- logger.warning(f"{error_count} out of 20 scores were discarded due to corrupt g-eval generation")
352
- score = sum(all_scores) / len(all_scores)
353
- return score
354
-
355
-
356
- def validate_inputs(document: str, summary: str, api_name: str, api_key: str) -> None:
357
- """
358
- Validate inputs for the G-Eval function.
359
-
360
- Args:
361
- document (str): The source document
362
- summary (str): The summary to evaluate
363
- api_name (str): The name of the API to use
364
- api_key (str): The API key
365
-
366
- Raises:
367
- ValueError: If any of the inputs are invalid
368
- """
369
- if not document.strip():
370
- raise ValueError("Source document cannot be empty")
371
- if not summary.strip():
372
- raise ValueError("Summary cannot be empty")
373
- if api_name.lower() not in ["openai", "anthropic", "cohere", "groq", "openrouter", "deepseek", "huggingface",
374
- "mistral", "llama.cpp", "kobold", "ooba", "tabbyapi", "vllm", "local-llm", "ollama"]:
375
- raise ValueError(f"Unsupported API: {api_name}")
376
-
377
-
378
- def detailed_api_error(api_name: str, error: Exception) -> str:
379
- """
380
- Generate a detailed error message for API failures.
381
-
382
- Args:
383
- api_name (str): The name of the API that failed
384
- error (Exception): The exception that was raised
385
-
386
- Returns:
387
- str: A detailed error message
388
- """
389
- error_type = type(error).__name__
390
- error_message = str(error)
391
- return f"API Failure: {api_name}\nError Type: {error_type}\nError Message: {error_message}\nPlease check your API key and network connection, and try again."
392
-
393
-
394
- def save_eval_results(results: Dict[str, Any], filename: str = "geval_results.json") -> None:
395
- """
396
- Save evaluation results to a JSON file.
397
-
398
- Args:
399
- results (Dict[str, Any]): The evaluation results
400
- filename (str): The name of the file to save results to
401
- """
402
- with open(filename, 'w') as f:
403
- json.dump(results, f, indent=2)
404
- print(f"Results saved to {filename}")
405
-
406
-
407
-
408
-
409
- #
410
- #
411
- #######################################################################################################################
412
- #
413
- # Taken from: https://github.com/microsoft/promptflow/blob/b5a68f45e4c3818a29e2f79a76f2e73b8ea6be44/src/promptflow-core/promptflow/_core/metric_logger.py
414
-
415
- class MetricLoggerManager:
416
- _instance = None
417
-
418
- def __init__(self):
419
- self._metric_loggers = []
420
-
421
- @staticmethod
422
- def get_instance() -> "MetricLoggerManager":
423
- if MetricLoggerManager._instance is None:
424
- MetricLoggerManager._instance = MetricLoggerManager()
425
- return MetricLoggerManager._instance
426
-
427
- def log_metric(self, key, value, variant_id=None):
428
- for logger in self._metric_loggers:
429
- if len(inspect.signature(logger).parameters) == 2:
430
- logger(key, value) # If the logger only accepts two parameters, we don't pass variant_id
431
- else:
432
- logger(key, value, variant_id)
433
-
434
- def add_metric_logger(self, logger_func: Callable):
435
- existing_logger = next((logger for logger in self._metric_loggers if logger is logger_func), None)
436
- if existing_logger:
437
- return
438
- if not callable(logger_func):
439
- return
440
- sign = inspect.signature(logger_func)
441
- # We accept two kinds of metric loggers:
442
- # def log_metric(k, v)
443
- # def log_metric(k, v, variant_id)
444
- if len(sign.parameters) not in [2, 3]:
445
- return
446
- self._metric_loggers.append(logger_func)
447
-
448
- def remove_metric_logger(self, logger_func: Callable):
449
- self._metric_loggers.remove(logger_func)
450
-
451
-
452
- def log_metric(key, value, variant_id=None):
453
- """Log a metric for current promptflow run.
454
-
455
- :param key: Metric name.
456
- :type key: str
457
- :param value: Metric value.
458
- :type value: float
459
- :param variant_id: Variant id for the metric.
460
- :type variant_id: str
461
- """
462
- MetricLoggerManager.get_instance().log_metric(key, value, variant_id)
463
-
464
-
465
- def add_metric_logger(logger_func: Callable):
466
- MetricLoggerManager.get_instance().add_metric_logger(logger_func)
467
-
468
-
469
- def remove_metric_logger(logger_func: Callable):
470
- MetricLoggerManager.get_instance().remove_metric_logger(logger_func)
471
- #
472
- # End of G-Eval.py
473
- #######################################################################################################################