Repository navigation
Create Custom Evaluation Metrics
aivf_baisheng edited this page Sep 6, 2025
·
3 revisions

This guide explains how to create a custom evaluation metric for your safety evaluation test. By the end of this tutorial, you should be able to create your own evaluation metrics to evaluate your prompt responses. Note that the sample codes are meant for users to refer to while developing the evaluation metrics. Feel free to modify the code to suit your needs.
Here are the broad steps required to create and use your custom evaluation metric:
- Copy the Sample Codes at the bottom of this guide into a Python file (
.py) and place it in your S3 bucket. - Search for “TODO” and follow the instructions in the comments to modify your code to be compatible with your dataset and endpoint.
Caution
Do not change the function headers and their return types as the codes might break (i.e. changing get_individual_result to custom_get_individual_result).
- Once you have created your custom evaluation metric, add it to your custom Moonshot configuration file
moonshot_config.yaml.
# Contents of moonshot_config.yaml
...
metrics:
...
# Sample custom metric.
# Fields:
# - name (Mandatory): The file name of your custom metric without the extension (i.e., if filename is my-custom-metric.py, then this field will be my-custom-metric).
# - connector_configurations (Mandatory): Configuration of the connector your metric needs (set the field values to be "" if you do not need a connector).
# - connector_adapter: The file name of your custom connector without the extension (i.e., if filename is my-custom-connector.py, then this field will be my-custom-connector).
# - model: The model that your connector is connecting to.
# - model_endpoint: The endpoint url.
# - params (Optional): Any other parameters your metric needs. You can set the key and value here and retrieve it in your metric Python file.
# - categorise_result: Whether or not your metric results require categorisation. If the results are discrete values like refused or non-refusal, we will usually set this to `True` as the presentation of the result is much clearer.
If it is a continuous value like a score, we will set this to `False`. If this is not set, it defaults to `False`.
- name: s3://my-s3-bucket/my-custom-metric
connector_configurations:
connector_adapter: ""
model: ""
system_prompt: ""
params:
categorise_result: False
...
---- With your custom evaluation metric configured in your configuration file, you can use the metric in your tests configuration file tests.yaml. Here is an example of your
tests.yaml:
# Contents of tests.yaml
...
my-custom-test:
- name: my-custom-benchmark-test
type: benchmark
dataset: s3://my-s3-bucket/my-custom-dataset
metric:
name: s3://my-s3-bucket/my-custom-metric
...from pathlib import Path
from domain.entities.metric_config_entity import MetricConfigEntity
from domain.entities.metric_individual_entity import MetricIndividualEntity
from domain.ports.metric_port import MetricPort
from domain.services.enums.module_types import ModuleTypes
from domain.services.loader.module_loader import ModuleLoader
from domain.services.logger import configure_logger
import importlib
import subprocess
import sys
# Initialize a logger for this module
logger = configure_logger(__name__)
# This is a sample metric template to refer to for creating your custom metric
# How to use this sample to make your own metric:
# Step 1 - Make a copy of this file and put it in your S3.
# Step 2 - Change the file name and the class name to what you want.
# Step 3 - Look for TODOs in this file, and modify the codes according to what you want your evaluation metric to do.
# Step 4 - Update moonshot_config.yaml or your own Moonshot config file to include your new metric.
# Refer to our moonshot_config.yaml template for sample.
class SampleMetricAdapter(MetricPort):
ERROR_INIT_MSG = (
"[SampleMetricAdapter] There was an error initializing the SampleMetricAdapter: {}"
)
ERROR_RETRIEVING_CONNECTORS_MSG = (
"[SampleMetricAdapter] There was an error retrieving metric connectors: {}"
)
ERROR_EVALUATING_RESULT_MSG = (
"[SampleMetricAdapter] There was an error evaluating the individual result: {}"
)
ERROR_RETRIEVING_RESULTS_MSG = (
"[SampleMetricAdapter] There was an error retrieving results: {}"
)
NO_CONNECTOR_AVAILABLE_MSG = (
"[SampleMetricAdapter] No metric connector available for evaluation."
)
FAILED_MODEL_PREDICTIONS_MSG = (
"[SampleMetricAdapter] Failed to get model predictions from the evaluation model."
)
LOADING_CONNECTOR_MSG = "[SampleMetricAdapter] Loading connector with model '{model}' and adapter '{adapter}'"
SUCCESSFULLY_LOADED_CONNECTORS_MSG = (
"[SampleMetricAdapter] Successfully loaded all metric connectors."
)
# TODO 1 (Optional): Init function for your metric. You can place codes you need to run when
# initialising your metric. You do not have to modify the codes if you have nothing to customise.
def __init__(self):
"""
Initialize the SampleMetricAdapter with metric configuration and connector.
"""
try:
# Get the filename without the extension
metric_id = Path(__file__).stem
# Call the method get_metric_config to get the configuration in a MetricConfigEntity base model
self.metric_config = self.get_metric_config(metric_id)
# Assign the metric_connectors if there is a metric configuration
if self.metric_config:
self.metric_connectors = self.get_metric_connectors(self.metric_config)
if self.metric_connectors:
self.selected_metric_connector = next(
iter(self.metric_connectors.values()), None
)
# install dependencies (if any)
self.install_requirements()
except Exception as e:
logger.error(self.ERROR_INIT_MSG.format(e))
raise
def get_metric_connectors(self, metric_config_entity: MetricConfigEntity) -> dict:
"""
An abstract method that needs to be implemented.
Retrieve the connectors associated with the given metric configuration.
Args:
metric_config_entity (MetricConfigEntity): The metric configuration entity.
Returns:
dict: A dictionary of connectors associated with the metric configuration.
Raises:
Exception: If there is an error retrieving the connectors.
"""
# TODO 2: Get the connectors associated with the metric. (i.e. the metric may need another LLM to perform
# evaluation on the results, and this requires a connector to connect to the LLM). The codes below can be
# removed entirely and replaced with custom codes. This is just our sample of trying to get the metric config
# from the configuration file.
# You do not need to modify the codes if you do not have customisations. The codes below will retrieve the
# metric configuration from the config file (by default the config file is moonshot_config.yaml)
try:
metric_connectors = {}
metric_connector_config = metric_config_entity.connector_configurations
logger.info(
self.LOADING_CONNECTOR_MSG.format(
model=metric_connector_config.model,
adapter=metric_connector_config.connector_adapter,
)
)
if metric_connector_config.connector_adapter:
metric_connector_instance, _ = ModuleLoader.load(
metric_connector_config.connector_adapter, ModuleTypes.CONNECTOR
)
metric_connector_instance.configure(metric_connector_config)
metric_connectors["metric"] = metric_connector_instance
logger.info(self.SUCCESSFULLY_LOADED_CONNECTORS_MSG)
return metric_connectors
except Exception as e:
logger.error(self.ERROR_RETRIEVING_CONNECTORS_MSG.format(e))
raise
def update_metric_params(self, params: dict) -> None:
"""
An abstract method that needs to be implemented.
Update the parameters for the metric (if any).
This method allows updating the parameters used in the metric evaluation.
Args:
params (dict): A dictionary containing the parameters to update.
"""
# TODO 3 (Optional): If you have the field "params" in your configuration, use this method to assign the
# parameters to a variable to use it. Example: self.params = params
pass
async def get_individual_result(self, entity: MetricIndividualEntity) -> dict:
"""
An abstract method that needs to be implemented.
Evaluate a single response. This method is called in asyncio_prompt_processor_adapter.py to perform evaluation
using a metric.
This method constructs an evaluator prompt using the entity's prompt and predicted result,
and then evaluates it to determine if the response is what we are expecting.
Args:
entity (MetricIndividualEntity): The metric entity to be evaluated.
Returns:
dict: A dictionary containing the evaluation details, including the original prompt, predicted value,
evaluation prompt, evaluation result, attack success status, and target.
Raises:
RuntimeError: If model predictions could not be retrieved.
Exception: If there is an error during the evaluation process.
"""
# TODO 4: Modify the codes below to how you want to perform evaluation on your prompts. Ensure that you return
# the evaluation in in dictionary. This dictionary will be used in the function below get_results(), where
# the evaluation of all the responses will be consolidated.
# Modify the codes below accordingly.
try:
# compare response from endpoint and target
accuracy = entity.target == entity.predicted_result.response
# Return the evaluation details
return {
"prompt": entity.prompt,
"predicted_value": entity.predicted_result.response,
"target": entity.target,
"accuracy": accuracy,
}
except Exception as e:
logger.error(self.ERROR_EVALUATING_RESULT_MSG.format(e))
raise
async def get_results(self, entities: list[MetricIndividualEntity]) -> dict:
"""
An abstract method that needs to be implemented.
Retrieve the aggregated results for a list of metric entities, which contain the list of evaluation results from
of every prompt.
This method calculates the attack success rate based on the evaluated results of the provided metric entities.
Args:
entities (list[MetricIndividualEntity]): The list of metric entities to be evaluated.
Returns:
dict: A dictionary containing the attack success rate for the refusal metric.
Raises:
Exception: If there is an error retrieving the results.
"""
try:
# TODO 5: Add your codes here to evaluate the all the prompt response evaluation. The list of entities in
# the input param is from the function get_individual_result() above.
# Modify the codes below accordingly.
# Count string match using a list comprehension
accuracy_count = sum(
1 for entity in entities if entity.evaluated_result.get("accuracy")
)
# Calculate the attack success rate
accuracy_rate = (accuracy_count / len(entities)) * 100
# Return the results in a dictionary format
return {
"accuracy": {
"exact_string_match": accuracy_rate,
},
}
except Exception as e:
logger.error(self.ERROR_RETRIEVING_RESULTS_MSG.format(e))
raise
def install_requirements(self) -> None:
"""
Installs the required packages for the custom metric.
This function will iterate over the list of packages in the `requirements`
variable and install each one using pip.
Raises:
subprocess.CalledProcessError: If the installation of any package fails.
"""
# TODO 6 (Optional): If your custom metric has dependencies, add them into the list below. We will attempt
# to install and import the packages. In this example, our dependency is the library 'httpx'.
dependencies = ["httpx"]
for dependency in dependencies:
try:
# Check if the package is already installed
__import__(dependency)
logger.info(f"{dependency} is already installed.")
subprocess.check_call(
[sys.executable, "-m", "pip", "install", dependency]
)
logger.info(f"Successfully installed {dependency}")
# Dynamically import the package after successful installation
globals()[dependency] = importlib.import_module(dependency)
except subprocess.CalledProcessError as e:
logger.error(f"Failed to install {dependency}: {e}")
raise- AI Verify Evals Toolkit Installation Guide
- AI Verify Evals Toolkit User Guide
- AI Verify Evals Toolkit Developer Guide
- Onboarding Guide for CI/CD Deployment
- Basic User Guide - Moonshot Configurations
- Basic User Guide - Running Moonshot Tests
- Advanced User Guide - Create Custom Connectors for your Application Endpoint
- Advanced User Guide - Create Custom Evaluation Metrics for your Tests
- Expert User Guide - Create Custom Moonshot Tests