-
Notifications
You must be signed in to change notification settings - Fork 292
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Config Loading from YAML & README Update #778
Open
deval-shah
wants to merge
3
commits into
confident-ai:main
Choose a base branch
from
deval-shah:evaluation-config-loading
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
metrics: | ||
answer_relevancy: | ||
threshold: 0.7 | ||
model: gpt-4-turbo | ||
include_reason: true | ||
faithfulness: | ||
threshold: 0.7 | ||
model: gpt-4-turbo | ||
include_reason: true | ||
contextual_precision: | ||
threshold: 0.7 | ||
model: gpt-4-turbo | ||
include_reason: true | ||
contextual_recall: | ||
threshold: 0.7 | ||
model: gpt-4-turbo | ||
include_reason: true | ||
contextual_relevancy: | ||
threshold: 0.7 | ||
model: gpt-4-turbo | ||
include_reason: true | ||
geval: | ||
name: geval | ||
threshold: 0.5 | ||
model: gpt-4-turbo | ||
criteria: "Coherence - determine if the actual output is coherent with the input." | ||
evaluation_params: | ||
- input | ||
- actual_output |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,127 @@ | ||
from deepeval.test_case import LLMTestCaseParams, LLMTestCase | ||
from .registry import metric_class_mapping | ||
from .utils import ConfigLoader | ||
from .base_metric import BaseMetric | ||
from typing import List | ||
|
||
class MetricsLoader: | ||
def __init__(self, config_path=None, metrics=None): | ||
""" | ||
Initialize MetricsLoader instance | ||
|
||
Args: | ||
config_path (str, optional): Path to a YAML config file. | ||
metrics (list, optional): List of metrics to evaluate. | ||
|
||
Raises: | ||
ValueError: If neither config_path nor metrics are provided. | ||
""" | ||
if config_path is None and metrics is None: | ||
raise ValueError("Either config_path or metrics must be provided") | ||
|
||
self.config_loader = None | ||
self.metrics = None | ||
|
||
if config_path is not None: | ||
self.config_loader = ConfigLoader(config_path) | ||
self.metrics = self.initialize_metrics() | ||
elif metrics is not None: | ||
self.metrics = metrics | ||
|
||
if self.config_loader is None: | ||
raise ValueError("Config file is not provided") | ||
if self.metrics is None: | ||
raise ValueError("Metrics are not provided") | ||
|
||
def initialize_metrics( | ||
self, | ||
) -> dict: | ||
""" | ||
Initialize metrics from config file. | ||
|
||
Initializes metrics for evaluation based on the configuration | ||
provided in the config file. The configuration is expected to be a dictionary | ||
where the keys are the names of the metrics and the values are dictionaries | ||
containing the configuration for the metric. | ||
|
||
Returns: | ||
dict: A dictionary containing the initialized metrics `{metric_name: metric object}`. | ||
""" | ||
metrics_config = self.config_loader.get_metrics_config() | ||
metrics = {} | ||
for metric_name, config in metrics_config.items(): | ||
# Map evaluation_params from config to LLMTestCaseParams | ||
evaluation_params = config.pop("evaluation_params", []) | ||
if not isinstance(evaluation_params, list): | ||
raise ValueError( | ||
f"Invalid configuration for metric '{metric_name}'. " | ||
f"'evaluation_params' must be a list. Check the metric registry for valid configuration." | ||
) | ||
# For handling multiple evaluation_params provided for some metrics (i.e. geval) | ||
mapped_params = [] | ||
for param in evaluation_params: | ||
try: | ||
# Convert the string param to the corresponding LLMTestCaseParams enum | ||
mapped_param = getattr(LLMTestCaseParams, param.upper(), None) | ||
if mapped_param is None: | ||
raise ValueError( | ||
f"Invalid evaluation param '{param}' for metric '{metric_name}'. " | ||
f"Check the LLMTestCaseParams enum for valid values." | ||
) | ||
mapped_params.append(mapped_param) | ||
except AttributeError: | ||
raise ValueError( | ||
f"Invalid evaluation param '{param}' for metric '{metric_name}'. " | ||
f"Check the LLMTestCaseParams enum for valid values." | ||
) | ||
if mapped_params: | ||
config["evaluation_params"] = mapped_params | ||
if metric_name in metric_class_mapping: | ||
MetricClass = metric_class_mapping[metric_name] | ||
try: | ||
metrics[metric_name] = MetricClass(**config) | ||
except TypeError: | ||
raise ValueError( | ||
f"Invalid configuration for metric '{metric_name}'. " | ||
f"Check the metric registry for valid configuration." | ||
) | ||
else: | ||
raise ValueError(f"No metric class found for '{metric_name}'. Check the metric registry.") | ||
|
||
return metrics | ||
|
||
def evaluate( | ||
self, | ||
test_case: LLMTestCase | ||
) -> dict: | ||
""" | ||
Evaluates the given test case using all the metrics in the metrics dictionary. | ||
|
||
Returns: | ||
dict[str, dict[str, Union[str, bool]]]: A dictionary containing the results of the evaluation for each metric. | ||
""" | ||
results = {} | ||
for metric_name, metric in self.metrics.items(): | ||
try: | ||
result = metric.measure(test_case) | ||
results[metric_name] = result | ||
except Exception as e: | ||
results[metric_name] = { | ||
'error': str(e), | ||
'success': False | ||
} | ||
return results | ||
|
||
def get_metrics_list( | ||
self, | ||
) -> List[BaseMetric]: | ||
""" | ||
Retrieves a list of metric objects from the MetricsEvaluator instance. | ||
|
||
Args: | ||
self (MetricsEvaluator): An instance of MetricsEvaluator. | ||
|
||
Returns: | ||
list: A list of metric objects. | ||
""" | ||
return list(self.metrics.values()) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
# Import metric classes from their respective modules | ||
from .answer_relevancy.answer_relevancy import AnswerRelevancyMetric | ||
from .faithfulness.faithfulness import FaithfulnessMetric | ||
from .contextual_recall.contextual_recall import ContextualRecallMetric | ||
from .contextual_relevancy.contextual_relevancy import ContextualRelevancyMetric | ||
from .contextual_precision.contextual_precision import ContextualPrecisionMetric | ||
from .g_eval.g_eval import GEval | ||
from .bias.bias import BiasMetric | ||
from .toxicity.toxicity import ToxicityMetric | ||
from .hallucination.hallucination import HallucinationMetric | ||
from .knowledge_retention.knowledge_retention import KnowledgeRetentionMetric | ||
from .summarization.summarization import SummarizationMetric | ||
|
||
# Define a dictionary mapping from metric names to metric classes | ||
metric_class_mapping = { | ||
'answer_relevancy': AnswerRelevancyMetric, | ||
'faithfulness': FaithfulnessMetric, | ||
'contextual_recall': ContextualRecallMetric, | ||
'contextual_relevancy': ContextualRelevancyMetric, | ||
'contextual_precision': ContextualPrecisionMetric, | ||
'geval': GEval, | ||
'bias': BiasMetric, | ||
'toxicity': ToxicityMetric, | ||
'hallucination': HallucinationMetric, | ||
'knowledge_retention': KnowledgeRetentionMetric, | ||
'summarization': SummarizationMetric, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Isn't
deepeval
using gpt4o by default?