執行評估作業

您可以使用 Vertex AI SDK for PythonGen AI Evaluation 模組,透過 Gen AI Evaluation Service API 以程式輔助方式評估生成式語言模型和應用程式。本頁說明如何使用 Vertex AI SDK 執行評估。請注意,大規模評估只能透過 REST API 進行。

事前準備

安裝 Vertex AI SDK

如要從 Python 適用的 Vertex AI SDK 安裝 Gen AI 評估模組,請執行下列指令:

!pip install -q google-cloud-aiplatform[evaluation]

詳情請參閱「安裝 Python 適用的 Vertex AI SDK」。

驗證 Vertex AI SDK

安裝 Python 適用的 Vertex AI SDK 後,您需要進行驗證。下列主題說明如何透過 Vertex AI SDK 進行驗證 (如果您在本機或 Colaboratory 中工作):

  • 如果您在本機開發,請在本機環境中設定應用程式預設憑證 (ADC)

    1. 安裝 Google Cloud CLI,然後執行下列指令初始化

      gcloud init
      
    2. 為 Google 帳戶建立本機驗證憑證:

      gcloud auth application-default login
      

      畫面上會顯示登入畫面。登入後,ADC 會將您的憑證儲存在本機憑證檔案中。詳情請參閱「為本機開發環境設定 ADC」。

  • 如果您在 Colaboratory 中工作,請在 Colab 儲存格中執行下列指令進行驗證:

    from google.colab import auth
    auth.authenticate_user()
    

    這個指令會開啟視窗,讓您完成驗證。

瞭解服務帳戶

Gen AI 評估服務會使用服務帳戶,從 Vertex AI 中的 Gemini API 取得預測結果,以評估模型。首次要求 Gen AI Evaluation Service 時,系統會自動佈建這個服務帳戶。

名稱 說明 電子郵件地址 角色
Vertex AI Rapid Eval 服務代理 用於取得模型評估預測結果的服務帳戶。 service-PROJECT_NUMBER@gcp-sa-vertex-eval.iam.gserviceaccount.com roles/aiplatform.rapidevalServiceAgent

與快速評估服務代理相關聯的權限如下:

角色 權限
Vertex AI Rapid Eval 服務代理 (roles/aiplatform.rapidevalServiceAgent) aiplatform.endpoints.predict

執行評估作業

使用 EvalTask 類別,針對下列用途執行評估:

EvalTask 類別

EvalTask 類別可協助您根據特定工作評估模型和應用程式。如要公平比較生成模型,通常需要使用特定指標,針對固定評估資料集重複評估各種模型和提示範本。此外,在單次評估作業中,同時評估多項指標也很重要。

EvalTask 也會與 Vertex AI Experiments 整合,協助您追蹤每次評估執行的設定和結果。Vertex AI Experiments 可協助您管理及解讀評估結果,做出明智決策。

以下範例說明如何例項化 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,
)

使用模型式指標執行評估

如要使用以模型為準的指標,請使用 PointwiseMetricPairwiseMetric 類別,定義符合特定條件的指標。使用下列選項執行評估:

使用以模型為基準的指標範例

您可以在 Vertex AI SDK 中直接使用內建常數 Metric Prompt Template Examples。或者,您也可以在任意形式指標定義介面中修改並納入這些指標。

如要查看涵蓋大多數重要用途的指標提示範本完整清單,請參閱「指標提示範本」。

控制台

在 Colab Enterprise 筆記本中執行評估時,您可以直接在 Google Cloud 控制台中存取指標提示範本。

  1. 按一下偏好的 Gen AI Evaluation Service 筆記本連結。

  2. 筆記本會在 GitHub 中開啟。按一下「在 Colab Enterprise 中開啟」。如果對話方塊要求您啟用 API,請按一下「啟用」

  3. 按一下側欄中的「Gen AI Evaluation」圖示。「預先建立的指標範本」面板隨即開啟。

  4. 選取「逐點」或「成對」指標。

  5. 按一下要使用的指標,例如「流暢度」。系統會顯示指標的程式碼範例。

  6. 按一下「複製」即可複製程式碼範例。(選用) 按一下「自訂」,變更指標的預設欄位。

  7. 將程式碼範例貼到筆記本中。

Vertex AI SDK

下列 Vertex AI 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,
)

使用以模型為基準的指標範本介面

如要自訂指標,請使用 Vertex AI SDK 中的 PointwiseMetricPromptTemplatePairwiseMetricPromptTemplate 類別,填入 CriteriaRating Rubrics 等欄位。如果您未提供輸入內容,系統會為特定欄位 (例如 Instruction) 指派預設值。

您可以選擇指定 input_variables,這是指標提示範本使用的輸入欄位清單,可產生以模型為準的評估結果。根據預設,系統會為逐點指標納入模型的 response 欄,並為成對指標納入候選模型的 responsebaseline_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,
)

評估翻譯模型

如要評估翻譯模型,使用 Vertex AI SDK 時,可以指定 BLEUMetricXCOMET 做為評估指標。

#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 評估服務中的 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"

其他指標自訂項目

如要進一步自訂指標,例如為以模型為基礎的指標選擇其他評估模型,或定義新的以運算為基礎的指標,可以使用 Vertex AI SDK 中的 CustomMetric 類別。詳情請參閱下列筆記本:

以更高的速率限制和配額執行模型式評估

針對以模型為準的指標發出單一評估要求時,系統會對 Vertex AI 中的 Gemini API 發出多項基礎要求,並耗用評估模型配額。在下列情況中,您應設定較高的評估服務速率限制:

  • 資料量增加:如果您使用以模型為準的指標處理大量資料,可能會達到每分鐘預設請求數 (RPM) 配額。提高配額後,您就能處理更多資料量,不會發生效能降低或中斷的情況。

  • 加快評估速度:如果應用程式需要加快評估速度,您可能需要較高的 RPM 配額。對於時間敏感型應用程式或即時互動應用程式而言,這點尤其重要,因為評估延遲可能會影響使用者體驗。

  • 複雜的評估工作:較高的 RPM 配額可確保您有足夠的容量,處理複雜工作或大量文字的資源密集型評估。

  • 高使用者並行:如果您預期專案中會有大量使用者同時要求以模型為準的評估和模型推論,則較高的模型 RPM 限制至關重要,可避免瓶頸並維持回應能力。

如果您使用 gemini-2.0-flash 的預設評估模型或更新的模型,建議使用「佈建輸送量」管理配額。

如果是 gemini-2.0-flash 之前的機型,請按照下列操作說明提高評估模型 RPM 配額

  1. 在 Google Cloud 控制台中,前往「IAM & Admin」(IAM 與管理) 的「配額」頁面。

    在控制台中查看配額

  2. 在「Filter」(篩選器) 欄位中,指定「Dimension」(維度) (模型 ID) 和「Metric」(指標) (Gemini 模型的配額 ID):base_model:gemini-2.0-flashMetric:aiplatform.googleapis.com/generate_content_requests_per_minute_per_project_per_base_model

  3. 找出要增加的配額,然後按一下「更多動作」選單 按鈕。

  4. 在下拉式選單中,按一下「編輯配額」。「Quota changes」(配額變更) 面板隨即開啟。

  5. 在「編輯配額」下方輸入新的配額值。

  6. 按一下 [提交要求]

  7. 配額增加要求 (QIR) 會透過電子郵件確認,通常需要兩個工作天才能處理完畢。

如要使用新配額執行評估,請依下列方式設定 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 評估服務配額」和「Gen AI 評估服務 API」。

後續步驟