跳转到内容

自定义指标(Custom Metrics)

用于代理评估的自定义指标

在 ADK 中得到支持。Python v1.18.0

如果您需要根据特定的使用场景或领域来定制专门的指标(而这些场景或领域并未被内置的选项所涵盖),那么您可以自行定义自定义指标。

定义一个自定义指标

自定义指标(Custom Metric)是一个 Python 函数,用于评估代理(Agent)在特定评估案例(Evaluation Case)中的表现,并返回相应的评估结果。 EvaluationResult该函数接收以下参数: EvalMetric该列表包含…… Invocation 在评估过程中,代理程序生成的对象;此外,还可以选择性地提供预期被调用的函数列表(或相关数据)。 ConversationScenario 如 `eval` 情况中所定义的那样。

每个 Invocation 该对象表示用户与智能代理之间的一次交互过程,其中包含了该交互过程中的各种信息,例如工具的运动轨迹、中间的响应内容以及最终的响应结果。

您的自定义指标函数必须具有以下签名:

from typing import Optional
from google.adk.evaluation.eval_case import Invocation
from google.adk.evaluation.eval_metrics import EvalMetric
from google.adk.evaluation.conversation_scenarios import ConversationScenario
from google.adk.evaluation.evaluator import EvaluationResult

def my_custom_metric_function(
    eval_metric: EvalMetric,
    actual_invocations: list[Invocation],
    expected_invocations: Optional[list[Invocation]],
    conversation_scenario: Optional[ConversationScenario],
) -> EvaluationResult:
  ...

该函数应该返回一个值。 EvaluationResult 具有该属性的对象…… overall_score, overall_eval_status,以及 per_invocation_results 这些字段已经被填充(即它们的值已经被设置)。

示例:

以下是一个简单的自定义指标示例:该指标用于检查代理在每个轮次中的最终响应是否与预期的最终响应完全一致。

import statistics
from typing import Optional

from google.adk.evaluation.conversation_scenarios import ConversationScenario
from google.adk.evaluation.eval_case import Invocation
from google.adk.evaluation.eval_metrics import EvalMetric
from google.adk.evaluation.eval_metrics import EvalStatus
from google.adk.evaluation.evaluator import EvaluationResult, PerInvocationResult

def check_final_response_exact_match(
    eval_metric: EvalMetric,
    actual_invocations: list[Invocation],
    expected_invocations: Optional[list[Invocation]],
    conversation_scenario: Optional[ConversationScenario],
) -> EvaluationResult:
  """Checks if the final response of the first turn matches the expected
  response."""
  if not expected_invocations:
    return EvaluationResult(overall_score=0.0, overall_eval_status=EvalStatus.NOT_EVALUATED)

  per_invocation_results = []

  for actual, expected in zip(actual_invocations, expected_invocations):
    actual_final_response = "".join([part.text for part in actual.final_response.parts])
    expected_final_response = "".join([part.text for part in expected.final_response.parts])
    score = 1.0 if actual_final_response == expected_final_response else 0.0
    eval_status = EvalStatus.PASSED if score else EvalStatus.FAILED
    invocation_result = PerInvocationResult(
        actual_invocation=actual,
        expected_invocation=expected,
        score=score,
        eval_status=eval_status
    )
    per_invocation_results.append(invocation_result)

  average_score = statistics.mean(result.score for result in per_invocation_results)

  threshold = eval_metric.criterion.threshold
  overall_eval_status = (
    EvalStatus.PASSED if average_score >= threshold else EvalStatus.FAILED
  )
  return EvaluationResult(
      overall_score=average_score,
      overall_eval_status=overall_eval_status,
      per_invocation_results=per_invocation_results,
  )

异步指标(Async Metric)

如果你的自定义指标需要执行异步操作(例如调用 API),你可以将其定义为…… async function.

以下是一个自定义指标函数的示例:该函数使用了一个虚构的异步脏话检测 API 来检查代理服务器的响应中是否包含脏话。

import asyncio
import statistics
from typing import Optional

from google.adk.evaluation.conversation_scenarios import ConversationScenario
from google.adk.evaluation.eval_case import Invocation
from google.adk.evaluation.eval_metrics import EvalMetric
from google.adk.evaluation.eval_metrics import EvalStatus
from google.adk.evaluation.evaluator import EvaluationResult, PerInvocationResult

class ProfanityChecker:
  """A fake profanity checker that mimics an async API."""

  async def check(self, text: str) -> bool:
    """Returns True if profanity is detected, False otherwise."""
    await asyncio.sleep(0.01)
    return "profanity" in text.lower()

profanity_checker = ProfanityChecker()

async def check_for_profanity(
    eval_metric: EvalMetric,
    actual_invocations: list[Invocation],
    expected_invocations: Optional[list[Invocation]],
    conversation_scenario: Optional[ConversationScenario],
) -> EvaluationResult:
  """Checks if the agent response contains profanity using a fake async API."""
  per_invocation_results = []

  for invocation in actual_invocations:
    agent_response = "".join(part.text for part in invocation.final_response.parts)
    has_profanity = await profanity_checker.check(agent_response)
    score = 0.0 if has_profanity else 1.0
    eval_status = EvalStatus.FAILED if has_profanity else EvalStatus.PASSED

    invocation_result = PerInvocationResult(
        actual_invocation=invocation,
        score=score,
        eval_status=eval_status
    )
    per_invocation_results.append(invocation_result)

  scores = [
      result.score
      for result in per_invocation_results
      if result.eval_status != EvalStatus.NOT_EVALUATED
  ]

  average_score = statistics.mean(scores)

  threshold = eval_metric.criterion.threshold
  overall_eval_status = (
      EvalStatus.PASSED if average_score >= threshold else EvalStatus.FAILED
  )
  return EvaluationResult(
      overall_score=average_score,
      overall_eval_status=overall_eval_status,
      per_invocation_results=per_invocation_results,
  )

使用自定义指标

要在评估运行中使用您的自定义指标,请按照以下步骤操作: adk eval您需要在您的配置文件中指定它。 EvalConfig JSON文件。

  1. 将您的自定义指标添加为评估项(eval)之一。 criteria关键在于你的指标名称(metric name),而值(value)则是该指标的阈值(passing threshold)。
  2. 添加一个 custom_metrics 反对;不同意 EvalConfig在这个对象内部,为每个自定义指标添加一个条目。其中,键(key)就是该指标的名称(应与系统中对应的指标名称一致)。 criteria)其值是一个对象,该对象包含其他内容。 code_config.
  3. The code_config 该对象应包含一个…… name 一个字符串字段,用于表示您的自定义指标函数的 Python 导入路径,格式如下: my.module.my_function.

示例: EvalConfig

假设你的……(Assuming your……) check_final_response_exact_match 该函数(`is`)的定义位于……(即函数的具体定义位置)。 my_agent.metrics.py, 你的 EvalConfig 可能看起来像这样:

{
  "criteria": {
    "my_check_final_response_exact_match": {
      "threshold": 0.8
    },
    "tool_trajectory_avg_score": {
      "threshold": 1.0
    }
  },
  "custom_metrics": {
    "my_check_final_response_exact_match": {
      "code_config": {
        "name": "my_agent.metrics.check_final_response_exact_match"
      }
    }
  }
}

使用这种配置方式,当你运行程序时…… adk eval --config_file_path=<path_to_this_config>ADK 将会执行该操作。 check_final_response_exact_match 对于每个评估案例(eval case),检查返回的分数(score)是否大于或等于 0.8,如果是,则将其标记为合格(passed)。 my_check_final_response_exact_match 评估标准是:是否通过(即是否达到要求)。

提供指标信息

您可以选择提供有关自定义指标的元数据(如该指标的描述和值范围),方法是在相关配置中添加相应的元数据信息。 MetricInfo 在你的自定义指标定义中,该对象位于……(“within your custom metric definition in”指明了对象在自定义指标结构中的具体位置)。 EvalConfig. 如果 metric_info 相关信息未提供,因此 ADK 将使用默认值。)min_value=0.0, max_value=1.0).

这些信息可以被 ADK 工具用于显示和结果汇总等目的。

以下是一个提供示例的例子: metric_info 对于一个返回分数在 -1.0 到 1.0 之间的自定义指标(custom metric):

{
  "criteria": {
    "my_metric": {
      "threshold": 0.5
    }
  },
  "custom_metrics": {
    "my_metric": {
      "code_config": {
        "name": "my_agent.metrics.my_metric_function"
      },
      "metric_info": {
        "metric_name": "my_metric",
        "description": "This metric evaluates XYZ and returns a score between -1.0 and 1.0.",
        "metric_value_info": {
          "interval": {
            "min_value": -1.0,
            "max_value": 1.0
          }
        }
      }
    }
  }
}