您可以使用 Agent Platform SDK for Python 的 生成式 AI Evaluation 模組,透過 Gen AI Evaluation Service API,以程式輔助方式評估生成式語言模型和應用程式。本頁面說明如何使用 Agent Platform SDK 執行評估。請注意,大規模評估只能透過 REST API 進行。
事前準備
如要開始執行評估,請先完成下列必要條件。
安裝 Agent Platform SDK
如要從 Agent Platform SDK for Python 安裝生成式 AI Evaluation 模組,請執行下列指令:
!pip install -q google-cloud-aiplatform[evaluation]
詳情請參閱「安裝 Agent Platform SDK for Python」。
驗證 Agent Platform SDK
安裝 Agent Platform SDK for Python 後,您需要進行驗證。下列主題說明在本機和 Colaboratory 中,如何使用 Agent Platform SDK 進行驗證:
如果您在本機開發,請在本機環境中設定應用程式預設憑證 (ADC):
安裝 Google Cloud CLI,然後執行下列指令初始化:
gcloud init為 Google 帳戶建立本機驗證憑證:
gcloud auth application-default login系統會顯示登入畫面。登入後,您的憑證會儲存在 ADC 使用的本機憑證檔案中。詳情請參閱「為本機開發環境設定 ADC」。
如果您是在 Colaboratory 中作業,請在 Colab 儲存格中執行下列指令,進行驗證:
from google.colab import auth auth.authenticate_user()這個指令會開啟視窗,供您完成驗證。
瞭解服務帳戶
Gen AI Evaluation Service 會使用服務帳戶,從 Gemini Enterprise Agent Platform 的 Gemini API 取得預測結果,用於模型式評估指標。首次向 Gen AI Evaluation Service 提出要求時,系統會自動佈建這個服務帳戶。
| 名稱 | 說明 | 電子郵件地址 | 角色 |
|---|---|---|---|
| Agent Platform 快速評估服務代理 | 用於取得模型評估預測結果的服務帳戶。 | service-PROJECT_NUMBER@gcp-sa-vertex-eval. |
roles/aiplatform.rapidevalServiceAgent |
快速評估服務代理的相關權限如下:
| 角色 | 權限 |
|---|---|
| Agent Platform 快速評估服務代理 (roles/aiplatform.rapidevalServiceAgent) | aiplatform.endpoints.predict |
執行評估
使用 EvalTask 類別,針對下列用途執行評估:
EvalTask 類別
EvalTask 類別可協助您根據特定任務評估模型和應用程式。如要公平比較生成模型,通常需要使用特定指標,根據固定的評估資料集,反覆評估各種模型和提示詞範本。此外,在單次評估作業中同時評估多項指標也很重要。
EvalTask 也與 Gemini Enterprise Agent Platform 的實驗功能整合,可協助您追蹤每次評估執行的設定和結果。Gemini Enterprise Agent Platform 的實驗功能可協助您管理及解讀評估結果,做出明智決策。
以下範例說明如何將 EvalTask 類別例項化,並執行評估:
from vertexai.evaluation import (
EvalTask,
PairwiseMetric,
PairwiseMetricPromptTemplate,
PointwiseMetric,
PointwiseMetricPromptTemplate,
MetricPromptTemplateExamples,
)
eval_task = EvalTask(
dataset=DATASET,
metrics=[METRIC_1, METRIC_2, METRIC_3],
experiment=EXPERIMENT_NAME,
)
eval_result = eval_task.evaluate(
model=MODEL,
prompt_template=PROMPT_TEMPLATE,
experiment_run=EXPERIMENT_RUN,
)
使用模型式指標執行評估
如果是以模型為基礎的指標,請使用 PointwiseMetric 和 PairwiseMetric 類別,根據特定條件定義指標。使用下列選項執行評估:
使用以模型為基準的指標範例
您可以直接在 Agent Platform SDK 中使用內建常數 Metric Prompt Template Examples。或者,您也可以在任意形式指標定義介面中修改並整合這些指標。
如需涵蓋多數重要用途的指標提示詞範本範例完整清單,請參閱「指標提示詞範本」。
控制台
在 Colab Enterprise 筆記本中執行評估時,您可以直接從 Google Cloud 控制台存取指標提示詞範本。
按一下偏好的 Gen AI Evaluation Service 筆記本連結。
筆記本會在 GitHub 中開啟。按一下「在 Colab Enterprise 中開啟」。如果對話方塊要求您啟用 API,請按一下「啟用」。
按一下側欄中的「生成式 AI 評估」圖示。「預先建立的指標範本」面板隨即開啟。
選取「Pointwise」或「Pairwise」指標。
按一下要使用的指標,例如「流暢度」。系統會顯示指標的程式碼範例。
按一下「複製」即可複製程式碼範例。(選用) 按一下「自訂」,變更指標的預設欄位。
將程式碼範例貼到筆記本中。
Agent Platform SDK
以下 Agent Platform SDK 範例說明如何使用 MetricPromptTemplateExamples 類別定義指標:
# View all the available examples of model-based metrics
MetricPromptTemplateExamples.list_example_metric_names()
# Display the metric prompt template of a specific example metric
print(MetricPromptTemplateExamples.get_prompt_template('fluency'))
# Use the pre-defined model-based metrics directly
eval_task = EvalTask(
dataset=EVAL_DATASET,
metrics=[MetricPromptTemplateExamples.Pointwise.FLUENCY],
)
eval_result = eval_task.evaluate(
model=MODEL,
)
使用以模型為基準的指標範本介面
使用 Agent Platform SDK 中的 PointwiseMetricPromptTemplate 和 PairwiseMetricPromptTemplate 類別,填入 Criteria 和 Rating Rubrics 等欄位,即可自訂指標。如果您未提供輸入內容,某些欄位 (例如 Instruction) 會指派預設值。
您也可以視需要指定 input_variables,這是指標提示詞範本使用的輸入欄位清單,用於生成模型評估結果。根據預設,逐點指標會包含模型的 response 欄,成對指標則會包含候選模型的 response 和 baseline_model_response 欄。
詳情請參閱「指標提示詞範本」中的「建構指標提示詞範本」一節。
# Define a pointwise metric with two custom criteria
custom_text_quality = PointwiseMetric(
metric="custom_text_quality",
metric_prompt_template=PointwiseMetricPromptTemplate(
criteria={
"fluency": "Sentences flow smoothly and are easy to read, avoiding awkward phrasing or run-on sentences. Ideas and sentences connect logically, using transitions effectively where needed.",
"entertaining": "Short, amusing text that incorporates emojis, exclamations and questions to convey quick and spontaneous communication and diversion.",
},
rating_rubric={
"1": "The response performs well on both criteria.",
"0": "The response is somewhat aligned with both criteria",
"-1": "The response falls short on both criteria",
},
input_variables=["prompt"],
),
)
# Display the serialized metric prompt template
print(custom_text_quality.metric_prompt_template)
# Run evaluation using the custom_text_quality metric
eval_task = EvalTask(
dataset=EVAL_DATASET,
metrics=[custom_text_quality],
)
eval_result = eval_task.evaluate(
model=MODEL,
)
使用模型指標任意形式 SDK 介面
如要更靈活地自訂指標提示詞範本,可以直接使用任意形式介面定義指標,該介面接受直接輸入字串。
# Define a pointwise multi-turn chat quality metric
pointwise_chat_quality_metric_prompt = """Evaluate the AI's contribution to a meaningful conversation, considering coherence, fluency, groundedness, and conciseness.
Review the chat history for context. Rate the response on a 1-5 scale, with explanations for each criterion and its overall impact.
# Conversation History
{history}
# Current User Prompt
{prompt}
# AI-generated Response
{response}
"""
freeform_multi_turn_chat_quality_metric = PointwiseMetric(
metric="multi_turn_chat_quality_metric",
metric_prompt_template=pointwise_chat_quality_metric_prompt,
)
# Run evaluation using the freeform_multi_turn_chat_quality_metric metric
eval_task = EvalTask(
dataset=EVAL_DATASET,
metrics=[freeform_multi_turn_chat_quality_metric],
)
eval_result = eval_task.evaluate(
model=MODEL,
)
評估翻譯模型
使用 Agent Platform SDK 時,您可以指定 BLEU、MetricX 或 COMET 做為評估指標,評估翻譯模型。
#Prepare the dataset for evaluation.
sources = [
"Dem Feuer konnte Einhalt geboten werden",
"Schulen und Kindergärten wurden eröffnet.",
]
responses = [
"The fire could be stopped",
"Schools and kindergartens were open",
]
references = [
"They were able to control the fire.",
"Schools and kindergartens opened",
]
eval_dataset = pd.DataFrame({
"source": sources,
"response": responses,
"reference": references,
})
# Set the metrics.
metrics = [
"bleu",
pointwise_metric.Comet(),
pointwise_metric.MetricX(),
]
eval_task = evaluation.EvalTask(
dataset=eval_dataset,
metrics=metrics,
)
eval_result = eval_task.evaluate()
使用以運算為基礎的指標執行評估
您可以單獨使用以運算為基礎的指標,或與以模型為基礎的指標搭配使用。
# Combine computation-based metrics "ROUGE" and "BLEU" with model-based metrics
eval_task = EvalTask(
dataset=EVAL_DATASET,
metrics=["rouge_l_sum", "bleu", custom_text_quality],
)
eval_result = eval_task.evaluate(
model=MODEL,
)
大規模執行評估
如果您有大型評估資料集,或定期在正式環境中執行評估,可以使用 Gen AI Evaluation Service 的 EvaluateDataset API 大規模執行評估。
使用任何要求資料之前,請先修改下列項目的值:
- PROJECT_NUMBER:您的專案編號。
- DATASET_URI:JSONL 檔案的 Cloud Storage 路徑,內含評估執行個體。檔案中的每一行都應代表一個例項,其鍵對應至
metric_prompt_template中使用者定義的輸入欄位 (適用於以模型為基礎的指標),或必要的輸入參數 (適用於以運算為基礎的指標)。您只能指定一個 JSONL 檔案。以下是逐點評估例項的一行範例:{"response": "The Roman Senate was filled with exuberance due to Pompey's defeat in Asia."} - METRIC_SPEC:用於評估的一或多個指標規格。執行大規模評估時,您可以使用下列指標規格:
"pointwise_metric_spec"、"pairwise_metric_spec"、"exact_match_spec"、"bleu_spec"和"rouge_spec"。 - METRIC_SPEC_FIELD_NAME:所選指標規格的必填欄位,例如
"metric_prompt_template" - METRIC_SPEC_FIELD_CONTENT:所選指標規格的欄位內容。舉例來說,您可以使用下列欄位內容進行逐點評估:
"Evaluate the fluency of this sentence: {response}. Give score from 0 to 1. 0 - not fluent at all. 1 - very fluent." - OUTPUT_BUCKET:要儲存評估結果的 Cloud Storage bucket 名稱。
HTTP 方法和網址:
POST https://us-central1-aiplatform.googleapis.com/v1beta1/projects/PROJECT_NUMBER/locations/us-central1/evaluateDataset
JSON 要求內文:
{
"dataset": {
"gcs_source": {
"uris": "DATASET_URI"
}
},
"metrics": [
{
METRIC_SPEC: {
METRIC_SPEC_FIELD_NAME: METRIC_SPEC_FIELD_CONTENT
}
}
],
"output_config": {
"gcs_destination": {
"output_uri_prefix": "OUTPUT_BUCKET"
}
}
}
如要傳送要求,請選擇以下其中一個選項:
curl
將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://us-central1-aiplatform.googleapis.com/v1beta1/projects/PROJECT_NUMBER/locations/us-central1/evaluateDataset"
PowerShell
將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/PROJECT_NUMBER/locations/us-central1/evaluateDataset" | Select-Object -Expand Content
您應該會收到如下的 JSON 回覆。
您可以使用回應中收到的 OPERATION_ID,要求評估狀態:
curl -X GET \ -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \ -H "Content-Type: application/json; charset=utf-8" \ "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/PROJECT_NUMBER/locations/us-central1/operations/OPERATION_ID"
其他指標自訂選項
如要進一步自訂指標,例如為以模型為基礎的指標選擇不同的評估模型,或定義新的以運算為基礎的指標,可以使用 Agent Platform SDK 中的 CustomMetric 類別。詳情請參閱下列筆記本:
執行模型式評估,享有更高的頻率限制和配額
單一模型指標評估要求會產生多個基礎要求,傳送至 Agent Platform 的 Gemini API,並耗用判斷模型的配額。在下列用途中,建議您提高評估服務頻率限制:
資料量增加:如果使用模型型指標處理的資料量大幅增加,可能會達到預設的每分鐘要求數 (RPM) 配額。提高配額後,您就能處理更大量的資料,不會降低效能或中斷服務。
加快評估速度:如果應用程式需要更快的評估作業時間,可能需要提高 RPM 配額。這對時效性應用程式或即時互動應用程式來說尤其重要,因為評估延遲可能會影響使用者體驗。
複雜的評估工作:較高的 RPM 配額可確保您有足夠的容量,處理複雜工作或大量文字的資源密集型評估。
高使用者並行:如果預期專案中會有大量使用者同時要求模型評估和模型推論,則必須提高模型 RPM 限制,以免發生瓶頸並維持回應速度。
如果您使用的是預設評估模型 Gemini 2.5 Flash 或更新的模型,建議您使用佈建輸送量管理配額。
如要使用新配額執行評估,請按照下列方式設定 evaluation_service_qps 參數:
from vertexai.evaluation import EvalTask
# GEMINI_RPM is the requests per minute (RPM) quota for gemini-2.0-flash-001 in your region
# Evaluation Service QPS limit is equal to (gemini-2.0-flash-001 RPM / 60 sec / default number of samples)
CUSTOM_EVAL_SERVICE_QPS_LIMIT = GEMINI_RPM / 60 / 4
eval_task = EvalTask(
dataset=DATASET,
metrics=[METRIC_1, METRIC_2, METRIC_3],
)
eval_result = eval_task.evaluate(
evaluation_service_qps=CUSTOM_EVAL_SERVICE_QPS_LIMIT,
# Specify a retry_timeout limit for a more responsive evaluation run
# the default value is 600 (in seconds, or 10 minutes)
retry_timeout=RETRY_TIMEOUT,
)
如要進一步瞭解配額和限制,請參閱「Gen AI Evaluation 服務配額」和「Gen AI Evaluation 服務 API」。
後續步驟
找出以模型為基準的指標範本。
試用評估範例筆記本。