评估模型

评估生成式 AI 模型的性能。

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

Python

在尝试此示例之前,请按照《Vertex AI 快速入门:使用客户端库》中的 Python 设置说明执行操作。 如需了解详情,请参阅 Vertex AI Python API 参考文档。

如需向 Vertex AI 进行身份验证,请设置应用默认凭证。 如需了解详情,请参阅为本地开发环境设置身份验证。

import os

import vertexai
from vertexai.evaluation import EvalResult, EvalTask

# TODO (Developer) Set environment variables
PROJECT_ID = os.getenv("GOOGLE_CLOUD_PROJECT")
LOCATION_ID = os.getenv("LOCATION_ID", "us-central1")
MODEL_NAME = os.getenv("MODEL_NAME", "gemini-2.5-flash")


def evaluate_model() -> EvalResult:
    """Evaluate the performance of a generative AI model."""

    vertexai.init(project=PROJECT_ID, location=LOCATION_ID)

    # Dataset URI containing input prompts and ground truth labels
    dataset_uri = "gs://cloud-samples-data/ai-platform/generative_ai/llm_classification_bp_input_prompts_with_ground_truth.jsonl"

    metric_column_mapping = {"reference": "ground_truth"}

    # Define evaluation task
    eval_task = EvalTask(
        dataset=dataset_uri,
        metrics=["exact_match"],
        experiment="gemini-classification-eval",
        metric_column_mapping=metric_column_mapping,
    )

    # Define a prompt template so the generative Gemini model produces formatted labels
    prompt_template = (
        "Classify the following text into exactly one category from "
        "[nature, news, sports, health, startups]. Return only the category name:\n\n{prompt}"
    )

    # Evaluate using a modern Gemini model
    eval_result = eval_task.evaluate(
        model=MODEL_NAME,
        prompt_template=prompt_template,
    )

    print("=== SUMMARY METRICS ===")
    print(eval_result.summary_metrics)

    print("\n=== METRICS TABLE SAMPLE ===")
    print(eval_result.metrics_table.head())

    return eval_result

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅Google Cloud 示例浏览器。