Chapter 85
Bring-Your-Own-Autorater using CustomMetric
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.Bring-Your-Own-Autorater using CustomMetric
Share to:
| Author(s) | Jason Dai |
Overview
Use the Vertex AI Python SDK for Gen AI Evaluation Service to evaluate generative AI models with your locally-defined CustomMetric, and use your own autorater model to perform model-based metric evaluation.
Getting Started
Install Vertex AI Python SDK for Gen AI Evaluation Service
%pip install --upgrade --user --quiet google-cloud-aiplatform[evaluation] google-genaiRestart runtime
To use the newly installed packages in this Jupyter runtime, you must restart the runtime. You can do this by running the cell below, which restarts the current kernel.
The restart might take a minute or longer. After it's restarted, continue to the next step.
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)Authenticate your notebook environment (Colab only)
import sys
if "google.colab" in sys.modules:
from google.colab import auth
auth.authenticate_user()Set Google Cloud project information and initialize Vertex AI SDK"
PROJECT_ID = "[your-project-id]" # @param {type:"string"}
LOCATION = "us-central1" # @param {type:"string"}
if not PROJECT_ID or PROJECT_ID == "[your-project-id]":
raise ValueError("Please set your PROJECT_ID")
import vertexai
vertexai.init(project=PROJECT_ID, location=LOCATION)Import libraries
import inspect
import pandas as pd
from google import genai
from google.genai import types
from vertexai.evaluation import CustomMetric, EvalTask
from vertexai.preview.evaluation import notebook_utilsUsing locally-defined CustomMetric class
Documentation
print(f"{CustomMetric.__name__}:\n{inspect.getdoc(CustomMetric)}\n")Define a CustomMetric and "Bring-Your-Own-Autorater"
Define a custom model-based metric and "Bring-Your-Own-Autorater". The custom model-based metric can contain multiple fields such as an autorater-graded score, explanations for the score, and more. The score field must match the name of the metric, other fields can be freeform strings.
# Bring-Your-Own-Autorater and define your autorater inference function
def get_autorater_response(metric_prompt: str) -> dict:
client = genai.Client(vertexai=True, project=PROJECT_ID, location=LOCATION)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=metric_prompt,
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_schema={
"type": "OBJECT",
"properties": {
"score": {"type": "NUMBER"},
"explanation": {"type": "STRING"},
},
"required": ["score", "explanation"],
},
safety_settings=[
types.SafetySetting(
category="HARM_CATEGORY_HATE_SPEECH",
threshold="BLOCK_NONE",
),
types.SafetySetting(
category="HARM_CATEGORY_DANGEROUS_CONTENT",
threshold="BLOCK_NONE",
),
types.SafetySetting(
category="HARM_CATEGORY_SEXUALLY_EXPLICIT",
threshold="BLOCK_NONE",
),
types.SafetySetting(
category="HARM_CATEGORY_HARASSMENT",
threshold="BLOCK_NONE",
),
],
),
)
return response.parsed# Define your metric computation function
def linguistic_acceptability_fn(instance: dict) -> dict:
metric_prompt_template = """
# Instruction
You are an expert evaluator. Your task is to evaluate the quality of the responses generated by AI models. We will provide you with the user prompt and an AI-generated responses.
You should first read the user input carefully for analyzing the task, and then evaluate the quality of the responses based on the Criteria provided in the Evaluation section below.
You will assign the response a rating following the Rating Rubric and Evaluation Steps. Give step by step explanations for your rating, and only choose ratings from the Rating Rubric.
# Evaluation
## Criteria
Appropriate word choice: Words chosen are appropriate and purposeful given their relative context and positioning in the text. Vocabulary demonstrates prompt understanding.
Proper Grammar: The language's grammar rules are correctly followed, including but not limited to sentence structures, verb tenses, subject-verb agreement, proper punctuation, and capitalization.
Reference Alignment: The response is consistent and aligned with the reference.
## Rating Rubric
1: Poor: The writing is riddled with grammatical errors, uses highly inappropriate vocabulary, is completely unrelated to the reference.
2: Unsatisfactory: The writing has significant grammatical errors, uses inappropriate vocabulary, deviates significantly from the reference.
3: Satisfactory: The writing may have minor grammatical errors or use less-appropriate vocabulary, but it aligns reasonably well with the reference.
4: Good: The writing is generally grammatically correct, uses appropriate vocabulary and aligns well with the reference.
5: Excellent: The writing is grammatically correct, uses appropriate vocabulary and aligns perfectly with the reference.
## Evaluation Steps
Step 1: Assess the response in aspects of all criteria provided. Provide assessment according to each criterion.
Step 2: Score based on the rating rubric. Give a brief rationale to explain your evaluation considering each individual criterion.
# User Inputs and AI-generated Response
## User Inputs
### prompt
{prompt}
## AI-generated Response
{response}
"""
prompt = instance["prompt"]
response = instance["response"]
metric_prompt = metric_prompt_template.format(prompt=prompt, response=response)
response_dict = get_autorater_response(metric_prompt)
return {
"linguistic_acceptability": response_dict["score"],
"explanation": response_dict["explanation"],
}# Define a CustomMetric
linguistic_acceptability_metric = CustomMetric(
name="linguistic_acceptability",
metric_function=linguistic_acceptability_fn,
)Run Evaluations with CustomMetric
-
The registered custom metrics are computed on the client side, without using Vertex Gen AI Evaluation Service APIs.
-
Mixing CustomMetric instances and other types of metrics is supported.
-
You can handle rate limiting of your own autorater with Eval SDK's RateLimiter utils function based on your autorater's capacity and QPS limit.
Define an evaluation dataset
instruction = "Summarize the following article"
context = [
"To make a classic spaghetti carbonara, start by bringing a large pot of salted water to a boil. While the water is heating up, cook pancetta or guanciale in a skillet with olive oil over medium heat until it's crispy and golden brown. Once the pancetta is done, remove it from the skillet and set it aside. In the same skillet, whisk together eggs, grated Parmesan cheese, and black pepper to make the sauce. When the pasta is cooked al dente, drain it and immediately toss it in the skillet with the egg mixture, adding a splash of the pasta cooking water to create a creamy sauce.",
"Preparing a perfect risotto requires patience and attention to detail. Begin by heating butter in a large, heavy-bottomed pot over medium heat. Add finely chopped onions and minced garlic to the pot, and cook until they're soft and translucent, about 5 minutes. Next, add Arborio rice to the pot and cook, stirring constantly, until the grains are coated with the butter and begin to toast slightly. Pour in a splash of white wine and cook until it's absorbed. From there, gradually add hot chicken or vegetable broth to the rice, stirring frequently, until the risotto is creamy and the rice is tender with a slight bite.",
"For a flavorful grilled steak, start by choosing a well-marbled cut of beef like ribeye or New York strip. Season the steak generously with kosher salt and freshly ground black pepper on both sides, pressing the seasoning into the meat. Preheat a grill to high heat and brush the grates with oil to prevent sticking. Place the seasoned steak on the grill and cook for about 4-5 minutes on each side for medium-rare, or adjust the cooking time to your desired level of doneness. Let the steak rest for a few minutes before slicing against the grain and serving.",
"Creating a creamy homemade tomato soup is a comforting and simple process. Begin by heating olive oil in a large pot over medium heat. Add diced onions and minced garlic to the pot and cook until they're soft and fragrant. Next, add chopped fresh tomatoes, chicken or vegetable broth, and a sprig of fresh basil to the pot. Simmer the soup for about 20-30 minutes, or until the tomatoes are tender and falling apart. Remove the basil sprig and use an immersion blender to puree the soup until smooth. Season with salt and pepper to taste before serving.",
"To bake a decadent chocolate cake from scratch, start by preheating your oven to 350°F (175°C) and greasing and flouring two 9-inch round cake pans. In a large mixing bowl, cream together softened butter and granulated sugar until light and fluffy. Beat in eggs one at a time, making sure each egg is fully incorporated before adding the next. In a separate bowl, sift together all-purpose flour, cocoa powder, baking powder, baking soda, and salt. Divide the batter evenly between the prepared cake pans and bake for 25-30 minutes, or until a toothpick inserted into the center comes out clean.",
]
reference = [
"The process of making spaghetti carbonara involves boiling pasta, crisping pancetta or guanciale, whisking together eggs and Parmesan cheese, and tossing everything together to create a creamy sauce.",
"Preparing risotto entails sautéing onions and garlic, toasting Arborio rice, adding wine and broth gradually, and stirring until creamy and tender.",
"Grilling a flavorful steak involves seasoning generously, preheating the grill, cooking to desired doneness, and letting it rest before slicing.",
"Creating homemade tomato soup includes sautéing onions and garlic, simmering with tomatoes and broth, pureeing until smooth, and seasoning to taste.",
"Baking a decadent chocolate cake requires creaming butter and sugar, beating in eggs and alternating dry ingredients with buttermilk before baking until done.",
]
eval_dataset = pd.DataFrame(
{
"context": context,
"instruction": [instruction] * len(context),
"reference": reference,
}
)Define prompt templates to compare
prompt_templates = [
"Instruction: {instruction}. Article: {context}. Summary:",
"Article: {context}. Complete this task: {instruction}, in three sentence. Summary:",
"Goal: {instruction} and give me a TLDR. Here's a news article: {context}. Summary:",
]Define metrics
metrics = ["rouge_l_sum", "fluency", "coherence", linguistic_acceptability_metric]Define an EvalTask
experiment_name = "eval-custom-metric" # @param {type:"string"}
eval_task = EvalTask(
dataset=eval_dataset,
metrics=metrics,
experiment=experiment_name,
)Run an Evaluation
eval_results = []
for i, prompt_template in enumerate(prompt_templates):
eval_result = eval_task.evaluate(
model="gemini-2.5-flash",
prompt_template=prompt_template,
)
eval_results.append((f"Prompt #{i}", eval_result))Display Evaluation result and explanations
for title, eval_result in eval_results:
notebook_utils.display_eval_result(title=title, eval_result=eval_result)for title, eval_result in eval_results:
notebook_utils.display_explanations(
eval_result, metrics=["linguistic_acceptability"]
)Compare Eval Results
notebook_utils.display_radar_plot(
eval_results,
metrics=["fluency", "coherence", "linguistic_acceptability"],
)notebook_utils.display_bar_plot(eval_results, metrics=["rouge_l_sum"])eval_task.display_runs()