다음을 통해 공유


평가를 실행하고 결과를 보는 방법

Important

이 기능은 공개 미리 보기 상태입니다.

이 문서에서는 Mosaic AI 에이전트 평가를 사용하여 평가를 실행하고 결과를 보는 방법을 설명합니다.

평가를 실행하려면 평가 집합을 지정해야 합니다. 평가 집합은 사용자가 에이전트 애플리케이션에 대해 만드는 일반적인 요청 집합입니다. 평가 집합에는 각 입력 요청에 대한 예상 출력도 포함될 수 있습니다. 평가 집합의 목적은 대표적인 질문에 대해 테스트하여 에이전트 애플리케이션의 성능을 측정하고 예측하는 데 도움이 되는 것입니다.

필요한 스키마를 포함하여 평가 집합에 대한 자세한 내용은 평가 집합을 참조 하세요.

평가를 시작하려면 MLflow API의 메서드를 사용합니다 mlflow.evaluate() . mlflow.evaluate() 는 평가 집합의 각 입력에 대한 품질, 대기 시간 및 비용 메트릭을 계산하고 모든 입력에서 집계 메트릭을 계산합니다. 이러한 메트릭을 평가 결과라고도 합니다. 다음 코드에서는 호출 mlflow.evaluate()의 예를 보여 봅니다.

%pip install databricks-agents
dbutils.library.restartPython()

import mlflow
import pandas as pd

eval_df = pd.DataFrame(...)

# Puts the evaluation results in the current Run, alongside the logged model parameters
with mlflow.start_run():
        logged_model_info = mlflow.langchain.log_model(...)
        mlflow.evaluate(data=eval_df, model=logged_model_info.model_uri,
                       model_type="databricks-agent")

이 예제 mlflow.evaluate() 에서는 다른 명령(예: 모델 매개 변수)에 의해 기록된 정보와 함께 바깥쪽 MLflow 실행에 평가 결과를 기록합니다. MLflow 실행 외부에서 호출 mlflow.evaluate() 하는 경우 새 실행을 시작하고 해당 실행에서 평가 결과를 기록합니다. 실행에 기록된 평가 결과에 대한 mlflow.evaluate()세부 정보를 포함하여 자세한 내용은 MLflow 설명서를 참조 하세요.

요구 사항

작업 영역에 대해 Azure AI Services AI 보조 기능을 사용하도록 설정해야 합니다.

평가 실행에 입력을 제공하는 방법

평가 실행에 대한 입력을 제공하는 방법에는 두 가지가 있습니다.

  • 애플리케이션을 입력 인수로 전달합니다.mlflow.evaluate() 는 평가 집합의 각 입력에 대한 애플리케이션을 호출하고 생성된 출력에 대한 메트릭을 계산합니다. MLflow 추적을 사용하도록 설정된 MLflow를 사용하여 애플리케이션을 기록했거나 애플리케이션이 Notebook에서 Python 함수로 구현되는 경우 이 옵션을 사용하는 것이 좋습니다.
  • 평가 집합과 비교할 이전에 생성된 출력을 제공합니다. 이 옵션은 애플리케이션이 Databricks 외부에서 개발되었거나, 프로덕션에 이미 배포된 애플리케이션의 출력을 평가하려는 경우 또는 평가 구성 간의 평가 결과를 비교하려는 경우에 권장됩니다.

다음 코드 샘플은 각 메서드에 대한 최소 예제를 보여줍니다. 평가 집합 스키마에 대한 자세한 내용은 평가 집합 스키마를 참조 하세요.

  • 호출에서 출력을 mlflow.evaluate() 생성하도록 하려면 다음 코드와 같이 함수 호출에서 평가 집합 및 애플리케이션을 지정합니다. 자세한 예제는 예제: 에이전트 평가 실행 애플리케이션을 참조하세요.

    evaluation_results = mlflow.evaluate(
        data=eval_set_df,  # pandas Dataframe containing just the evaluation set
        model=model,  # Reference to the MLflow model that represents the application
        model_type="databricks-agent",
    )
    
  • 이전에 생성된 출력을 제공하려면 다음 코드와 같이 평가 집합만 지정하지만 생성된 출력이 포함되어 있는지 확인합니다. 자세한 예제 는 예제: 이전에 생성된 출력을 참조하세요.

    evaluation_results = mlflow.evaluate(
        data=eval_set_with_chain_outputs_df,  # pandas Dataframe with the evaluation set and application outputs
        model_type="databricks-agent",
    )
    

평가 출력

평가는 다음 두 가지 유형의 출력을 생성합니다.

  • 다음을 포함하여 평가 집합의 각 요청에 대한 데이터입니다.
    • 에이전트 애플리케이션으로 전송된 입력입니다.
    • 애플리케이션의 출력 response입니다.
    • 애플리케이션에서 생성된 모든 중간 데이터(예: retrieved_contexttrace)입니다.
    • 각 Databricks 지정 및 고객이 지정한 LLM 판사의 등급 및 근거입니다. 등급은 정확성, 접지성, 검색 정밀도 등을 포함하여 애플리케이션 출력의 다양한 품질 측면을 특징으로 합니다.
    • 다른 단계에 대한 대기 시간 및 토큰 수를 포함하여 애플리케이션의 추적을 기반으로 하는 다른 메트릭입니다.
  • 평균 및 총 토큰 수, 평균 대기 시간 등 전체 평가 집합에서 집계된 메트릭 값입니다.

이러한 두 가지 유형의 출력은 반환 mlflow.evaluate() 되며 MLflow 실행에도 기록됩니다. Notebook 또는 해당 MLflow 실행의 페이지에서 출력을 검사할 수 있습니다.

Notebook에서 출력 검토

다음 코드에서는 Notebook에서 평가 실행 결과를 검토하는 방법에 대한 몇 가지 예제를 보여 줍니다.

%pip install databricks-agents pandas
dbutils.library.restartPython()

import mlflow
import pandas as pd

###
# Run evaluation
###
evaluation_results = mlflow.evaluate(..., model_type="databricks-agent")

###
# Access aggregated metric values across the entire evaluation set
###
metrics_as_dict = evaluation_results.metrics
metrics_as_pd_df = pd.DataFrame([evaluation_results.metrics])

# Sample usage
print(f"The percentage of generated responses that are grounded: {metrics_as_dict['response/llm_judged/groundedness/percentage']}")

###
# Access data about each question in the evaluation set
###

per_question_results_df = evaluation_results.tables['eval_results']

# Show information about responses that are not grounded
per_question_results_df[per_question_results_df["response/llm_judged/groundedness/rating"] == "no"].display()

데이터 프레임에는 per_question_results_df 입력 스키마의 모든 열과 각 요청과 관련된 모든 계산 메트릭이 포함됩니다. 보고된 각 메트릭에 대한 자세한 내용은 에이전트 메트릭 및 LLM 심사위원을 사용하여 앱 성능을 평가하세요.

MLflow UI를 사용하여 출력 검토

평가 결과는 MLflow UI에서도 사용할 수 있습니다. MLflow UI에 액세스하려면 Notebook의 오른쪽 사이드바에서 실험 아이콘 실험 아이콘 을 클릭한 다음 해당 실행에서 실행하거나 실행 mlflow.evaluate()한 Notebook 셀의 셀 결과에 표시되는 링크를 클릭합니다.

단일 실행에 대한 메트릭 검토

이 섹션에서는 각 평가 실행에 사용할 수 있는 메트릭에 대해 설명합니다. 실행 간에 메트릭을 비교하려면 실행 간에 메트릭 비교를 참조하세요.

요청별 메트릭

요청별 메트릭은 버전 0.3.0 이상에서 databricks-agents 사용할 수 있습니다.

평가 집합의 각 요청에 대한 자세한 메트릭을 보려면 MLflow 실행 페이지에서 평가 결과 탭을 클릭합니다. 이 페이지에는 각 평가 실행의 요약 테이블이 표시됩니다. 자세한 내용은 실행의 평가 ID 를 클릭합니다.

평가 실행의 세부 정보 페이지에는 다음이 표시됩니다.

  • 모델 출력: 에이전트 앱에서 생성된 응답 및 포함된 경우 해당 추적입니다.
  • 예상 출력: 각 요청에 대한 예상 응답입니다.
  • 자세한 평가: 이 데이터에 대한 LLM 심사위원의 평가입니다. 세부 정보 보기를 클릭하여 심사위원이 제공한 근거를 표시합니다.

요청 메트릭당

전체 평가 집합에서 집계된 메트릭

전체 평가 집합에서 집계된 메트릭 값을 보려면 개요 탭(숫자 값) 또는 모델 메트릭 탭(차트의 경우)을 클릭합니다.

평가 메트릭, 값

평가 메트릭, 차트

실행 간에 메트릭 비교

에이전트 애플리케이션이 변경에 응답하는 방식을 확인하려면 실행 간에 평가 결과를 비교하는 것이 중요합니다. 결과를 비교하면 변경 내용이 품질에 긍정적인 영향을 미치는지 또는 변경 동작 문제를 해결하는 데 도움이 되는지 이해하는 데 도움이 될 수 있습니다.

실행에서 요청당 메트릭 비교

실행에서 각 개별 요청에 대한 데이터를 비교하려면 실험 페이지에서 평가 탭을 클릭합니다. 테이블은 평가 집합의 각 질문을 보여줍니다. 드롭다운 메뉴를 사용하여 볼 열을 선택합니다.

평가 집합의 개별 질문

실행 간에 집계된 메트릭 비교

실험 페이지에서 동일한 집계 메트릭에 액세스할 수 있으며, 이를 통해 여러 실행에서 이러한 메트릭을 비교할 수도 있습니다. 실험 페이지에 액세스하려면 전자 필기장 오른쪽 사이드바에서 실험 아이콘 실험 아이콘 을 클릭하거나 실행 mlflow.evaluate()한 Notebook 셀의 셀 결과에 표시되는 링크를 클릭합니다.

실험 페이지에서 을 클릭합니다 차트 표시 아이콘. 이렇게 하면 선택한 실행에 대해 집계된 메트릭을 시각화하고 과거 실행과 비교할 수 있습니다.

집계된 결과

호출의 mlflow.evaluate()

이 섹션에는 애플리케이션 및 평가 집합을 호출에 전달하기 위한 옵션을 보여 주는 호출의 코드 샘플 mlflow.evaluate() 이 포함되어 있습니다.

예: 에이전트 평가에서 애플리케이션 실행

%pip install databricks-agents pandas
dbutils.library.restartPython()

import mlflow
import pandas as pd

###
# mlflow.evaluate() call
###
evaluation_results = mlflow.evaluate(
    data=eval_set_df,  # pandas DataFrame with just the evaluation set
    model=model,  # Reference to the application
    model_type="databricks-agent",
)

###
# There are 4 options for passing an application in the `model` argument.
####

#### Option 1. Reference to a Unity Catalog registered model
model = "models:/catalog.schema.model_name/1"  # 1 is the version number

#### Option 2. Reference to a MLflow logged model in the current MLflow Experiment
model = "runs:/6b69501828264f9s9a64eff825371711/chain"
# `6b69501828264f9s9a64eff825371711` is the run_id, `chain` is the artifact_path that was
# passed when calling mlflow.xxx.log_model(...).
# If you called model_info = mlflow.langchain.log_model() or mlflow.pyfunc.log_model(), you can access this value using `model_info.model_uri`.

#### Option 3. A PyFunc model that is loaded in the notebook
model = mlflow.pyfunc.load_model(...)

#### Option 4. A local function in the notebook
def model_fn(model_input):
  # code that implements the application
  response = 'the answer!'
  return response

model = model_fn

###
# `data` is a pandas DataFrame with your evaluation set.
# These are simple examples. See the input schema for details.
####

# You do not have to start from a dictionary - you can use any existing pandas or
# Spark DataFrame with this schema.

# Minimal evaluation set
bare_minimum_eval_set_schema = [
    {
        "request": "What is the difference between reduceByKey and groupByKey in Spark?",
    }]

# Complete evaluation set
complete_eval_set_schema = [
    {
        "request_id": "your-request-id",
        "request": "What is the difference between reduceByKey and groupByKey in Spark?",
        "expected_retrieved_context": [
            {
                # In `expected_retrieved_context`, `content` is optional, and does not provide any additional functionality.
                "content": "Answer segment 1 related to What is the difference between reduceByKey and groupByKey in Spark?",
                "doc_uri": "doc_uri_2_1",
            },
            {
                "content": "Answer segment 2 related to What is the difference between reduceByKey and groupByKey in Spark?",
                "doc_uri": "doc_uri_2_2",
            },
        ],
        "expected_response": "There's no significant difference.",
    }]

#### Convert dictionary to a pandas DataFrame
eval_set_df = pd.DataFrame(bare_minimum_eval_set_schema)

#### Use a Spark DataFrame
import numpy as np
spark_df = spark.table("catalog.schema.table") # or any other way to get a Spark DataFrame
eval_set_df = spark_df.toPandas()

예: 이전에 생성된 출력 제공됨

필요한 평가 집합 스키마는 평가 집합을 참조 하세요.

%pip install databricks-agents pandas
dbutils.library.restartPython()

import mlflow
import pandas as pd

###
# mlflow.evaluate() call
###
evaluation_results = mlflow.evaluate(
    data=eval_set_with_app_outputs_df,  # pandas Dataframe with the evaluation set and application outputs
    model_type="databricks-agent",
)

###
# `data` is a pandas DataFrame with your evaluation set and outputs generated by the application.
# These are simple examples. See the input schema for details.
####

# You do not have to start from a dictionary - you can use any existing pandas or
# Spark DataFrame with this schema.

# Bare minimum data
bare_minimum_input_schema = [
    {
        "request": "What is the difference between reduceByKey and groupByKey in Spark?",
        "response": "reduceByKey aggregates data before shuffling, whereas groupByKey shuffles all data, making reduceByKey more efficient.",
    }]

complete_input_schema  = [
    {
        "request_id": "your-request-id",
        "request": "What is the difference between reduceByKey and groupByKey in Spark?",
        "expected_retrieved_context": [
            {
                # In `expected_retrieved_context`, `content` is optional, and does not provide any additional functionality.
                "content": "Answer segment 1 related to What is the difference between reduceByKey and groupByKey in Spark?",
                "doc_uri": "doc_uri_2_1",
            },
            {
                "content": "Answer segment 2 related to What is the difference between reduceByKey and groupByKey in Spark?",
                "doc_uri": "doc_uri_2_2",
            },
        ],
        "expected_response": "There's no significant difference.",
        "response": "reduceByKey aggregates data before shuffling, whereas groupByKey shuffles all data, making reduceByKey more efficient.",
        "retrieved_context": [
            {
                # In `retrieved_context`, `content` is optional. If provided, the Databricks Context Relevance LLM Judge is executed to check the `content`'s relevance to the `request`.
                "content": "reduceByKey reduces the amount of data shuffled by merging values before shuffling.",
                "doc_uri": "doc_uri_2_1",
            },
            {
                "content": "groupByKey may lead to inefficient data shuffling due to sending all values across the network.",
                "doc_uri": "doc_uri_6_extra",
            },
        ],
    }]

#### Convert dictionary to a pandas DataFrame
eval_set_with_app_outputs_df = pd.DataFrame(bare_minimum_input_schema)

#### Use a Spark DataFrame
import numpy as np
spark_df = spark.table("catalog.schema.table") # or any other way to get a Spark DataFrame
eval_set_with_app_outputs_df = spark_df.toPandas()

제한 사항

다중 턴 대화의 경우 평가 출력은 대화의 마지막 항목만 기록합니다.