快速评估

您可以使用 Python 版 Vertex AI SDK 以编程方式评估生成式语言模型。

安装 Vertex AI SDK

如需通过 Python 版 Vertex AI SDK 安装快速评估,请运行以下命令:

pip install --upgrade google-cloud-aiplatform[rapid_evaluation]

如需了解详情,请参阅安装 Python 版 Vertex AI SDK

对 Vertex AI SDK 进行身份验证

安装 Python 版 Vertex AI SDK 后,您需要进行身份验证。以下主题介绍了在本地工作以及使用 Colaboratory 时如何向 Vertex AI SDK 进行身份验证:

  • 如果您是在本地开发,请在本地环境中设置应用默认凭据 (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()
    

    此命令将打开一个窗口,您可在其中完成身份验证。

创建评估任务

由于评估主要通过生成式 AI 模型任务驱动,因此在线评估引入了评估任务抽象化来支持评估用例。为了对生成模型进行公平的比较,您通常可以针对评估数据集及其相关指标重复地运行模型和提示模板评估。EvalTask 类旨在支持这种新的评估范式。此外,EvalTask 还可让您与 Vertex AI Experiments 无缝集成,这有助于跟踪每次评估运行的设置和结果。Vertex AI Experiments 可帮助管理和解释评估结果,使您能够更快地采取行动。以下示例展示了如何创建 EvalTask 类的实例并运行评估:

from vertexai.preview.evaluation import EvalTask

eval_task = EvalTask(
  dataset=DATASET,
  metrics=["bleu", "rouge_l_sum"],
  experiment=EXPERIMENT_NAME
)

metrics 参数接受指标列表,允许在单个评估调用中同时评估多个指标。

评估数据集准备

数据集以 Pandas DataFrame 的形式传递给 EvalTask 实例,其中每一行表示一个单独的评估样本(称为一个实例),每一列表示一个指标输入参数。如需了解每个指标预期的输入,请参阅指标。我们提供了为不同的评估任务构建评估数据集的一些示例。

摘要评估

使用以下指标构建数据集以进行逐点摘要:

  • summarization_quality
  • groundedness
  • fulfillment
  • summarization_helpfulness
  • summarization_verbosity

考虑到这些指标的必需输入参数,您必须在评估数据集中添加以下列:

  • instruction
  • context
  • response

在此示例中,我们有两个摘要实例。将 instructioncontext 字段构造为输入,这是摘要任务评估必需的输入:

instructions = [
  # example 1
  "Summarize the text in one sentence.",
  # example 2
  "Summarize the text such that a five-year-old can understand.",
]

contexts = [
  # example 1
  """As part of a comprehensive initiative to tackle urban congestion and foster
sustainable urban living, a major city has revealed ambitious plans for an
extensive overhaul of its public transportation system. The project aims not
only to improve the efficiency and reliability of public transit but also to
reduce the city\'s carbon footprint and promote eco-friendly commuting options.
City officials anticipate that this strategic investment will enhance
accessibility for residents and visitors alike, ushering in a new era of
efficient, environmentally conscious urban transportation.""",
# example 2
  """A team of archaeologists has unearthed ancient artifacts shedding light on a
previously unknown civilization. The findings challenge existing historical
narratives and provide valuable insights into human history.""",
]

如果您已准备好 LLM 回答(汇总),并希望进行自带预测 (BYOP) 评估,则可以按如下方式构建回答输入:

responses = [
  # example 1
  "A major city is revamping its public transportation system to fight congestion, reduce emissions, and make getting around greener and easier.",
  # example 2
  "Some people who dig for old things found some very special tools and objects that tell us about people who lived a long, long time ago! What they found is like a new puzzle piece that helps us understand how people used to live.",
]

有了这些输入,我们即准备好构建评估数据集和 EvalTask

eval_dataset = pd.DataFrame(
  {
    "instruction": instructions,
    "context":  contexts,
    "response":  responses,
  }
)

eval_task = EvalTask(
  dataset=eval_dataset,
  metrics=[
    'summarization_quality',
    'groundedness',
    'fulfillment',
    'summarization_helpfulness',
    'summarization_verbosity'
  ],
  experiment=EXPERIMENT_NAME
)

常规文本生成评估

某些基于模型的指标(例如 coherencefluencysafety)只需要模型回答来评估质量:

eval_dataset = pd.DataFrame({
  "response": ["""The old lighthouse, perched precariously on the windswept cliff,
had borne witness to countless storms. Its once-bright beam, now dimmed by time
and the relentless sea spray, still flickered with stubborn defiance."""]
})

  eval_task = EvalTask(
  dataset=eval_dataset,
  metrics=["coherence", "fluency", "safety"],
  experiment=EXPERIMENT_NAME
)

基于计算的评估

基于计算的指标(如完全匹配、bleu 和 rouge)会将回答与引用进行比较,因此需要评估数据集中的回答和引用字段:

eval_dataset = pd.DataFrame({
  "response": ["The Roman Senate was filled with exuberance due to Pompey's defeat in Asia."],
  "reference": ["The Roman Senate was filled with exuberance due to successes against Catiline."],
})

eval_task = EvalTask(
  dataset=eval_dataset,
  metrics=["exact_match", "bleu", "rouge"],
  experiment=EXPERIMENT_NAME
)

工具使用情况评估

对于工具使用情况评估,您只需在评估数据集中包含回答和引用。

eval_dataset = pd.DataFrame({
  "response": ["""{
    "content": "",
    "tool_calls":[{
      "name":"get_movie_info",
      "arguments": {"movie":"Mission Impossible", "time": "today 7:30PM"}
    }]
  }"""],
  "reference": ["""{
    "content": "",
    "tool_calls":[{
      "name":"book_tickets",
      "arguments":{"movie":"Mission Impossible", "time": "today 7:30PM"}
      }]
  }"""],
})

eval_task = EvalTask(
  dataset=eval_dataset,
  metrics=["tool_call_valid", "tool_name_match", "tool_parameter_key_match",
"tool_parameter_kv_match"],
  experiment=EXPERIMENT_NAME
)

查看评估结果

定义评估任务后,请运行该任务以获取评估结果,如下所示:

eval_result: EvalResult = eval_task.evaluate(
  model=MODEL,
  prompt_template=PROMPT_TEMPLATE
)

EvalResult 类表示评估运行的结果,其中包括摘要指标以及一个包含评估数据集实例和相应实例指标的指标表。按如下方式定义该类:

@dataclasses.dataclass
class EvalResult:
  """Evaluation result.

  Attributes:
    summary_metrics: the summary evaluation metrics for an evaluation run.
    metrics_table: a table containing eval inputs, ground truth, and
      metrics per row.
  """
  summary_metrics: Dict[str, float]
  metrics_table: Optional[pd.DataFrame] = None

通过使用辅助函数,评估结果可以显示在 Colab 笔记本中。

摘要质量

可视化

您可以在雷达图或条形图中绘制摘要指标,以直观呈现和比较不同评估运行的结果。可视化有助于评估不同的模型和不同的提示模板。

雷达图表

条形图指标

快速评估 API

如需了解快速评估 API,请参阅快速评估 API

了解服务账号

在线评估服务使用服务账号从在线预测服务获取基于模型的评估指标的预测结果。此服务账号会在在线评估服务收到第一个请求时自动预配。

名称 说明 电子邮件地址 角色
Vertex AI Rapid Eval Service Agent 用于为基于模型的评估获取预测结果的服务账号。 service-PROJECT_NUMBER@gcp-sa-ENV-vertex-eval.iam.gserviceaccount.com roles/aiplatform.rapidevalServiceAgent

与快速评估服务代理关联的权限包括:

角色 权限
Vertex AI Rapid Eval Service Agent (roles/aiplatform.rapidevalServiceAgent) aiplatform.endpoints.predict

后续步骤