튜토리얼: 에이전트를 평가하고 개선하기

평가 데이터셋은 에이전트의 품질을 측정하고, 문제를 식별하며, 회귀분석을 도입하지 않고도 개선이 효과적인지 검증할 수 있게 해줍니다. 이 자습서에서는 RAG(검색 보강 세대)를 사용하는 이메일 생성 앱을 평가하고 반복적으로 개선하는 단계를 안내합니다.

이 가이드에서는 RAG(Retrieval-Augmented Generation)를 사용하는 전자 메일 생성 앱을 평가하는 단계를 안내합니다. 앱은 데이터베이스에서 고객 정보 검색을 시뮬레이션하고 검색된 정보에 따라 개인 설정된 후속 이메일을 생성합니다.

평가에 대한 간단한 소개는 ' 평가 및 개선'을 참조하세요.

이 자습서에는 다음 단계가 포함되어 있습니다.

이 자습서에서는 배포된 앱의 추적을 사용하여 평가 데이터 세트를 만들지만 평가 데이터 세트를 만든 방법에 관계없이 동일한 워크플로가 적용됩니다. 평가 데이터 세트를 만드는 다른 방법은 MLflow 평가 데이터 세트 빌드를 참조하세요. 추적에 관한 정보는 추적 개요를 참조하세요.

오프라인 모니터링 워크플로 다이어그램

필수 조건

  1. 필요한 패키지 설치:

    %pip install -q --upgrade "mlflow[databricks]>=3.14.0" openai
    dbutils.library.restartPython()
    

    이 페이지의 예시들은 Unity 카탈로그에 저장된 트레이스에 접근할 수 있습니다. SQL 웨어하우스를 실행하기 전에 먼저 설정하세요:

    import os
    
    os.environ["MLFLOW_TRACING_SQL_WAREHOUSE_ID"] = "<SQL_WAREHOUSE_ID>"
    
  2. MLflow 실험을 만듭니다. Databricks Notebook을 사용하는 경우 이 단계를 건너뛰고 기본 Notebook 실험을 사용할 수 있습니다. 그렇지 않으면 환경 설정 빠른 시작 에 따라 실험을 만들고 MLflow 추적 서버에 연결합니다.

  3. 평가 데이터 세트를 만들려면 Unity 카탈로그의 스키마에 대한 권한이 있어야 합니다 CREATE TABLE .

비고

복잡한 에이전트를 실행하는 데 시간이 오래 걸릴 수 있습니다. 병렬 처리를 구성하려면 (선택 사항) 병렬 처리 구성을 참조하세요.

1단계: 애플리케이션 만들기

첫 번째 단계는 전자 메일 생성 앱을 만드는 것입니다. 검색 구성 요소는 MLflow의 검색 전용 LLM 평가자를 사용하기 위해 span_type="RETRIEVER"로 표시되어 있습니다.

  1. OpenAI 클라이언트를 초기화하여 Databricks가 호스팅하는 LLM 또는 OpenAI가 호스팅하는 LLM에 연결합니다.

    Databricks 호스팅 LLM

    databricks-openai를 사용하여 Databricks 호스팅 LLM에 연결하는 OpenAI 클라이언트를 가져옵니다. 사용 가능한 기본 모델에서 모델을 선택합니다.

    import mlflow
    from databricks_openai import DatabricksOpenAI
    from mlflow.entities.trace_location import UnityCatalog
    
    # Enable MLflow's autologging to instrument your application with Tracing
    mlflow.openai.autolog()
    
    # Set up MLflow tracking to Databricks
    mlflow.set_tracking_uri("databricks")
    mlflow.set_experiment(
        experiment_name="/Shared/docs-demo",
        trace_location=UnityCatalog(
            catalog_name="<UC_CATALOG_NAME>",
            schema_name="<UC_SCHEMA_NAME>",
            table_prefix="<UC_TABLE_PREFIX>",
        ),
    )
    
    # Create an OpenAI client that is connected to Databricks-hosted LLMs
    client = DatabricksOpenAI()
    
    # Select an LLM
    model_name = "databricks-claude-sonnet-4-6"
    

    OpenAI에서 호스팅되는 LLM

    네이티브 OpenAI SDK를 사용하여 OpenAI 호스팅 모델에 연결합니다. 사용 가능한 OpenAI 모델에서 모델을 선택합니다.

    import mlflow
    import os
    import openai
    from mlflow.entities.trace_location import UnityCatalog
    
    # Ensure your OPENAI_API_KEY is set in your environment
    # os.environ["OPENAI_API_KEY"] = "<YOUR_API_KEY>" # Uncomment and set if not globally configured
    
    # Enable auto-tracing for OpenAI
    mlflow.openai.autolog()
    
    # Set up MLflow tracking to Databricks
    mlflow.set_tracking_uri("databricks")
    mlflow.set_experiment(
        experiment_name="/Shared/docs-demo",
        trace_location=UnityCatalog(
            catalog_name="<UC_CATALOG_NAME>",
            schema_name="<UC_SCHEMA_NAME>",
            table_prefix="<UC_TABLE_PREFIX>",
        ),
    )
    
    # Create an OpenAI client connected to OpenAI SDKs
    client = openai.OpenAI()
    
    # Select an LLM
    model_name = "gpt-4o-mini"
    
  2. 전자 메일 생성 앱을 만듭니다.

    from mlflow.entities import Document
    from typing import List, Dict
    
    # Simulated customer relationship management database
    CRM_DATA = {
        "Acme Corp": {
            "contact_name": "Alice Chen",
            "recent_meeting": "Product demo on Monday, very interested in enterprise features. They asked about: advanced analytics, real-time dashboards, API integrations, custom reporting, multi-user support, SSO authentication, data export capabilities, and pricing for 500+ users",
            "support_tickets": ["Ticket #123: API latency issue (resolved last week)", "Ticket #124: Feature request for bulk import", "Ticket #125: Question about GDPR compliance"],
            "account_manager": "Sarah Johnson"
        },
        "TechStart": {
            "contact_name": "Bob Martinez",
            "recent_meeting": "Initial sales call last Thursday, requested pricing",
            "support_tickets": ["Ticket #456: Login issues (open - critical)", "Ticket #457: Performance degradation reported", "Ticket #458: Integration failing with their CRM"],
            "account_manager": "Mike Thompson"
        },
        "Global Retail": {
            "contact_name": "Carol Wang",
            "recent_meeting": "Quarterly review yesterday, happy with platform performance",
            "support_tickets": [],
            "account_manager": "Sarah Johnson"
        }
    }
    
    # Use a retriever span to enable MLflow's predefined RetrievalGroundedness judge to work
    @mlflow.trace(span_type="RETRIEVER")
    def retrieve_customer_info(customer_name: str) -> List[Document]:
        """Retrieve customer information from CRM database"""
        if customer_name in CRM_DATA:
            data = CRM_DATA[customer_name]
            return [
                Document(
                    id=f"{customer_name}_meeting",
                    page_content=f"Recent meeting: {data['recent_meeting']}",
                    metadata={"type": "meeting_notes"}
                ),
                Document(
                    id=f"{customer_name}_tickets",
                    page_content=f"Support tickets: {', '.join(data['support_tickets']) if data['support_tickets'] else 'No open tickets'}",
                    metadata={"type": "support_status"}
                ),
                Document(
                    id=f"{customer_name}_contact",
                    page_content=f"Contact: {data['contact_name']}, Account Manager: {data['account_manager']}",
                    metadata={"type": "contact_info"}
                )
            ]
        return []
    
    @mlflow.trace
    def generate_sales_email(customer_name: str, user_instructions: str) -> Dict[str, str]:
        """Generate personalized sales email based on customer data & a sale's rep's instructions."""
        # Retrieve customer information
        customer_docs = retrieve_customer_info(customer_name)
    
        # Combine retrieved context
        context = "\n".join([doc.page_content for doc in customer_docs])
    
        # Generate email using retrieved context
        prompt = f"""You are a sales representative. Based on the customer information below,
        write a brief follow-up email that addresses their request.
    
        Customer Information:
        {context}
    
        User instructions: {user_instructions}
    
        Keep the email concise and personalized."""
    
        response = client.chat.completions.create(
            model=model_name, # This example uses a Databricks hosted LLM - you can replace this with any AI Gateway or Model Serving endpoint. If you provide your own OpenAI credentials, replace with a valid OpenAI model e.g., gpt-4o, etc.
            messages=[
                {"role": "system", "content": "You are a helpful sales assistant."},
                {"role": "user", "content": prompt}
            ],
            max_tokens=2000
        )
    
        return {"email": response.choices[0].message.content}
    
    # Test the application
    result = generate_sales_email("Acme Corp", "Follow up after product demo")
    print(result["email"])
    

평가 앱 추적

2단계: 프로덕션 트래픽 시뮬레이션

이 단계에서는 데모를 위해 트래픽을 시뮬레이션합니다. 실제로 실제 사용량의 추적을 사용하여 평가 데이터 세트를 만듭니다.

# Simulate beta testing traffic with scenarios designed to fail guidelines
test_requests = [
    {"customer_name": "Acme Corp", "user_instructions": "Follow up after product demo"},
    {"customer_name": "TechStart", "user_instructions": "Check on support ticket status"},
    {"customer_name": "Global Retail", "user_instructions": "Send quarterly review summary"},
    {"customer_name": "Acme Corp", "user_instructions": "Write a very detailed email explaining all our product features, pricing tiers, implementation timeline, and support options"},
    {"customer_name": "TechStart", "user_instructions": "Send an enthusiastic thank you for their business!"},
    {"customer_name": "Global Retail", "user_instructions": "Send a follow-up email"},
    {"customer_name": "Acme Corp", "user_instructions": "Just check in to see how things are going"},
]

# Run requests and capture traces
print("Simulating production traffic...")
for req in test_requests:
    try:
        result = generate_sales_email(**req)
        print(f"✓ Generated email for {req['customer_name']}")
    except Exception as e:
        print(f"✗ Error for {req['customer_name']}: {e}")

3단계: 평가 데이터 세트 만들기

이 단계에서는 추적을 평가 데이터 세트에 저장합니다. 평가 데이터 세트에 추적을 저장하면 시간이 지남에 따라 데이터 세트의 변경 내용을 추적하고 이 데이터 세트를 사용하여 생성된 모든 평가 결과를 볼 수 있도록 평가 결과를 데이터 세트에 연결할 수 있습니다.

사용자 인터페이스 (UI)

  1. 사이드바에서 실험을 클릭하여 실험 페이지를 표시합니다.

  2. 실험의 이름을 클릭하여 엽니다.

    실험 열기

  3. 왼쪽 사이드바에서 추적을 클릭합니다.

  4. 추적 목록의 왼쪽에 있는 확인란을 사용하여 추가하려는 추적을 선택합니다. 현재 페이지에서 모든 추적을 선택하려면 열 머리글의 추적 ID 옆에 있는 확인란을 클릭합니다.

    데이터 추적 선택

  5. 작업을 클릭합니다. 단추 레이블에는 선택한 추적 수(예: 작업(3))가 표시됩니다.

    작업 메뉴

  6. 평가에 사용에서 평가 데이터 세트에 추가를 선택합니다. 평가 데이터 세트에 추적 추가 대화 상자가 열립니다.

  7. 이 실험에 대한 평가 데이터 세트가 없거나 새 데이터 세트에 추적을 추가하려는 경우 다음 단계에 따라 새 평가 데이터 세트를 만듭니다.

    1. 새 데이터 세트 만들기를 클릭합니다.
    2. 새 데이터 세트를 저장할 Unity 카탈로그 스키마를 선택합니다.
    3. 데이터 세트의 이름을 입력하고 데이터 세트 만들기를 클릭합니다.
    4. 내보내기를 클릭한 다음 완료를 클릭합니다.

    평가 데이터 세트가 없는 경우 추적 추가 대화 상자

    실험에 대한 평가 데이터 세트가 이미 있는 경우 추적을 추가할 데이터 세트의 오른쪽에 있는 내보내 기를 클릭합니다. 둘 이상의 데이터 세트로 내보낼 수 있습니다. 내보내기를 마쳤으면 완료를 클릭합니다.

    기존 평가 데이터 세트가 있는 경우 추적 추가 대화 상자

SDK

추적을 검색하고 데이터 세트에 추가하여 프로그래밍 방식으로 평가 데이터 세트를 만듭니다.

import mlflow
import mlflow.genai.datasets
import time
from databricks.connect import DatabricksSession

# 0. If you are using a local development environment, connect to Serverless Spark which powers MLflow's evaluation dataset service
spark = DatabricksSession.builder.remote(serverless=True).getOrCreate()

# 1. Create an evaluation dataset

# Replace with a Unity Catalog schema where you have CREATE TABLE permission
uc_schema = "workspace.default"
# This table will be created in the above UC schema
evaluation_dataset_table_name = "email_generation_eval"

eval_dataset = mlflow.genai.datasets.create_dataset(
    uc_table_name=f"{uc_schema}.{evaluation_dataset_table_name}",
)
print(f"Created evaluation dataset: {uc_schema}.{evaluation_dataset_table_name}")

# 2. Search for the simulated production traces from step 2: get traces from the last 20 minutes with our trace name.
ten_minutes_ago = int((time.time() - 10 * 60) * 1000)

traces = mlflow.search_traces(
    filter_string=f"attributes.timestamp_ms > {ten_minutes_ago} AND "
                 f"attributes.status = 'OK' AND "
                 f"tags.`mlflow.traceName` = 'generate_sales_email'",
    order_by=["attributes.timestamp_ms DESC"]
)

print(f"Found {len(traces)} successful traces from beta test")

# 3. Add the traces to the evaluation dataset
eval_dataset = eval_dataset.merge_records(traces)
print(f"Added {len(traces)} records to evaluation dataset")

# Preview the dataset
df = eval_dataset.to_df()
print(f"\nDataset preview:")
print(f"Total records: {len(df)}")
print("\nSample record:")
sample = df.iloc[0]
print(f"Inputs: {sample['inputs']}")

4단계: LLM 심사위원을 사용하여 평가 실행

이 단계에서는 MLflow에 내장된 LLM 심사자를 사용해 에이전트의 품질에 대한 다양한 측면을 자동으로 평가합니다. 자세한 내용은 LLM 심사위원 및 코드 기반 득점자를 참조하세요.

from mlflow.genai.scorers import (
    RetrievalGroundedness,
    RelevanceToQuery,
    Safety,
    Guidelines,
)

# Save the LLM judges as a variable so you can re-use them in step 7

email_judges = [
        RetrievalGroundedness(),  # Checks if email content is grounded in retrieved data
        Guidelines(
            name="follows_instructions",
            guidelines="The generated email must follow the user_instructions in the request.",
        ),
        Guidelines(
            name="concise_communication",
            guidelines="The email MUST be concise and to the point. The email should communicate the key message efficiently without being overly brief or losing important context.",
        ),
        Guidelines(
            name="mentions_contact_name",
            guidelines="The email MUST explicitly mention the customer contact's first name (e.g., Alice, Bob, Carol) in the greeting. Generic greetings like 'Hello' or 'Dear Customer' are not acceptable.",
        ),
        Guidelines(
            name="professional_tone",
            guidelines="The email must be in a professional tone.",
        ),
        Guidelines(
            name="includes_next_steps",
            guidelines="The email MUST end with a specific, actionable next step that includes a concrete timeline.",
        ),
        RelevanceToQuery(),  # Checks if email addresses the user's request
        Safety(),  # Checks for harmful or inappropriate content
    ]

# Run evaluation with LLM judges
eval_results = mlflow.genai.evaluate(
    data=eval_dataset,
    predict_fn=generate_sales_email,
    scorers=email_judges,
)

5단계: 결과 보기 및 해석

mlflow.genai.evaluate()를 실행하면 점수자 피드백이 포함된 트레이스가 생성됩니다. 각 트레이스는 평가 데이터셋의 한 행에 해당하며, 각 심사위원의 피드백 이 주석으로 달려 있습니다.

평가 실행을 사용하여 집계 메트릭을 보고 앱이 제대로 수행되지 않은 테스트 사례를 조사할 수 있습니다.

이 평가에서는 다음과 같은 몇 가지 문제를 보여 줍니다.

  • 지침 준수 부족 - 에이전트는 사용자 요청과 일치하지 않는 응답을 자주 제공하는데, 예를 들어 간단한 체크인을 요청받았을 때 자세한 제품 정보를 보내거나, 열정적인 감사 메시지를 요청받았을 때 지원 티켓 업데이트를 제공하는 경우가 있습니다.
  • 간결함 부족 - 대부분의 전자 메일은 불필요하게 길며 핵심 메시지를 희석시키는 과도한 세부 정보를 포함하며 전자 메일을 "간결하고 개인화"하는 지침에도 불구하고 효율적으로 통신하지 못했습니다.
  • 구체적인 다음 단계 누락 - 대부분의 이메일은 필수 요소로 식별된 구체적인 타임라인을 포함하는 실행 가능한 특정 다음 단계로 끝나지 않습니다.

사용자 인터페이스 (UI)

평가 요약

  1. 사이드바에서 실험을 클릭하여 실험 페이지를 표시합니다.

  2. 실험의 이름을 클릭하여 엽니다.

  3. 왼쪽 사이드바에서 평가 실행을 클릭합니다. 오른쪽 창에는 추적 테이블이 표시됩니다.

    평가 실행 테이블

    통과 및 실패 레이블이 있는 평가가 표시되지 않으면 오른쪽으로 스크롤하거나 창 구분 기호 위로 마우스를 가져가서 왼쪽 화살표를 클릭합니다.

    테이블 확장

  4. Pass 또는 Fail 레이블의 근거를 보려면 레이블을 마우스로 가리킵니다.

    레이블을 마우스로 가리키면 근거 표시

세부 정보 및 피드백 추가

각 추적에 대한 자세한 내용을 보려면 다음을 수행합니다.

  1. 요청 열에서 요청 식별자를 클릭합니다. 각 단계에 대한 입력 및 출력을 포함하여 전체 추적을 보여 주는 창이 나타납니다.

    요청 세부 정보 창

  2. 오른쪽에서 피드백 또는 기대치를 추가하여 이 요청에 대한 응답에 적용할 수 있습니다. 평가 창이 표시되지 않으면 평가 단추를 클릭합니다. 새 평가를 추가하려면 아래로 스크롤하여 새 평가 추가 단추를 클릭합니다.

  3. 이 창의 양쪽에 있는 화살표를 사용하여 요청을 단계별로 실행할 수 있습니다.

    화살표를 사용하여 요청 단계별 실행

SDK

자세한 결과를 프로그래밍 방식으로 보려면 다음을 수행합니다.

eval_traces = mlflow.search_traces(run_id=eval_results.run_id)

# eval_traces is a Pandas DataFrame that has the evaluated traces.  The column `assessments` includes each judge's feedback.
print(eval_traces)

6단계: 향상된 버전 만들기

평가 결과를 사용하여 식별된 문제를 해결하는 향상된 버전을 만듭니다.

향상된 버전을 만들 때 평가 결과에 따라 대상 변경 내용에 집중합니다. 일반적인 개선 전략은 다음과 같습니다.

  • 프롬프트 엔지니어링: 특정 오류 패턴을 해결하도록 시스템 프롬프트를 구체화하고, 에지 사례에 대한 명시적 지침을 추가하거나, 올바른 처리를 보여 주거나, 톤 또는 스타일을 조정하는 예제를 포함합니다.
  • Guardrails: 애플리케이션 논리에서 유효성 검사 단계를 구현하고 사용자에게 표시하기 전에 출력을 확인하는 사후 처리를 추가합니다.
  • 검색 개선 사항(RAG 앱의 경우): 검색 범위를 검사하거나, 모델 포함을 개선하거나, 청크 전략을 구체화하여 관련 문서를 찾을 수 없는 경우 검색 메커니즘을 향상시킵니다.
  • 향상된 추론: 복잡한 작업을 여러 범위로 나누거나, 사고 체인 기술을 구현하거나, 중요한 출력에 대한 확인 단계를 추가합니다.

아래 코드는 평가 결과에 따라 향상된 프롬프트 엔지니어링을 보여 줍니다.

@mlflow.trace
def generate_sales_email_v2(customer_name: str, user_instructions: str) -> Dict[str, str]:
    """Generate personalized sales email based on customer data & a sale's rep's instructions."""
    # Retrieve customer information
    customer_docs = retrieve_customer_info(customer_name) # retrive_customer_info is defined in Step 1

    if not customer_docs:
        return {"error": f"No customer data found for {customer_name}"}

    # Combine retrieved context
    context = "\n".join([doc.page_content for doc in customer_docs])

    # Generate email using retrieved context with better instruction following
    prompt = f"""You are a sales representative writing an email.

MOST IMPORTANT: Follow these specific user instructions exactly:
{user_instructions}

Customer context (only use what's relevant to the instructions):
{context}

Guidelines:
1. PRIORITIZE the user instructions above all else
2. Keep the email CONCISE - only include information directly relevant to the user's request
3. End with a specific, actionable next step that includes a concrete timeline (e.g., "I'll follow up with pricing by Friday" or "Let's schedule a 15-minute call this week")
4. Only reference customer information if it's directly relevant to the user's instructions

Write a brief, focused email that satisfies the user's exact request."""

    response = client.chat.completions.create(
        model="databricks-claude-sonnet-4-5",
        messages=[
            {"role": "system", "content": "You are a helpful sales assistant who writes concise, instruction-focused emails."},
            {"role": "user", "content": prompt}
        ],
        max_tokens=2000
    )

    return {"email": response.choices[0].message.content}

# Test the application
result = generate_sales_email("Acme Corp", "Follow up after product demo")
print(result["email"])

7단계: 새 버전 평가 및 비교

동일한 심사위원 및 데이터 세트를 사용하여 개선된 버전에서 평가를 실행하여 문제를 성공적으로 해결했는지 확인합니다.

import mlflow

# Run evaluation of the new version with the same judges as before
# Use start_run to name the evaluation run in the UI
with mlflow.start_run(run_name="v2"):
    eval_results_v2 = mlflow.genai.evaluate(
        data=eval_dataset, # same eval dataset
        predict_fn=generate_sales_email_v2, # new app version
        scorers=email_judges, # same judges as step 4
    )

8단계: 결과 비교

결과를 비교하여 변경 내용이 품질을 향상시켰는지 파악합니다. 이 비교 뷰는 새로운 프롬프트 버전이 이전 버전보다 더 우수한지 확인하는 주요 방법입니다. 평가를 실행하기 전에 프롬프트 버전 설정을 위해 프롬프트 생성 및 편집 프롬 프트를 참고하세요.

사용자 인터페이스 (UI)

  1. 사이드바에서 실험을 클릭하여 실험 페이지를 표시합니다.

  2. 실험의 이름을 클릭하여 엽니다.

  3. 왼쪽 사이드바에서 평가 실행을 클릭합니다. 왼쪽 창에는 이 실험에 대한 평가 실행 목록이 표시됩니다.

    실행 창

  4. 비교할 실행에 대한 확인란을 선택합니다.

  5. 작업 드롭다운 메뉴에서 비교 선택합니다.

    비교할 실행 선택

  6. 오른쪽 창에는 선택한 실행에서 각 추적의 개별 비교가 표시됩니다.

    추적 비교 화면

  7. 자세한 내용은 요청 열에서 요청 식별자를 클릭합니다. 비교를 위해 선택한 각 실행의 요청에 대한 전체 추적을 보여 주는 창이 나타납니다.

    비교 세부 정보 창

    각 평가의 세부 정보를 보려면 세부 정보 보기를 클릭합니다. 추적 세부 정보를 보려면 자세한 추적 보기 보기를 클릭합니다.

SDK

각 평가 실행에 저장된 평가 메트릭을 프로그래밍 방식으로 비교합니다.

import pandas as pd

# Fetch runs separately since mlflow.search_runs doesn't support IN or OR operators
run_v1_df = mlflow.search_runs(
    filter_string=f"run_id = '{eval_results_v1.run_id}'"
)
run_v2_df = mlflow.search_runs(
    filter_string=f"run_id = '{eval_results_v2.run_id}'"
)

# Extract metric columns (they end with /mean, not .aggregate_score)
# Skip the agent metrics (latency, token counts) for quality comparison
metric_cols = [col for col in run_v1_df.columns
               if col.startswith('metrics.') and col.endswith('/mean')
               and 'agent/' not in col]

# Create comparison table
comparison_data = []
for metric in metric_cols:
    metric_name = metric.replace('metrics.', '').replace('/mean', '')
    v1_score = run_v1_df[metric].iloc[0]
    v2_score = run_v2_df[metric].iloc[0]
    improvement = v2_score - v1_score

    comparison_data.append({
        'Metric': metric_name,
        'V1 Score': f"{v1_score:.3f}",
        'V2 Score': f"{v2_score:.3f}",
        'Improvement': f"{improvement:+.3f}",
        'Improved': '✓' if improvement >= 0 else '✗'
    })

comparison_df = pd.DataFrame(comparison_data)
print("\n=== Version Comparison Results ===")
print(comparison_df.to_string(index=False))

# Calculate overall improvement (only for quality metrics)
avg_v1 = run_v1_df[metric_cols].mean(axis=1).iloc[0]
avg_v2 = run_v2_df[metric_cols].mean(axis=1).iloc[0]
print(f"\nOverall average improvement: {(avg_v2 - avg_v1):+.3f} ({((avg_v2/avg_v1 - 1) * 100):+.1f}%)")
=== Version Comparison Results ===
                Metric V1 Score V2 Score Improvement Improved
                safety    1.000    1.000      +0.000        ✓
     professional_tone    1.000    1.000      +0.000        ✓
  follows_instructions    0.571    0.714      +0.143        ✓
   includes_next_steps    0.286    0.571      +0.286        ✓
 mentions_contact_name    1.000    1.000      +0.000        ✓
retrieval_groundedness    0.857    0.571      -0.286        ✗
 concise_communication    0.286    1.000      +0.714        ✓
    relevance_to_query    0.714    1.000      +0.286        ✓

Overall average improvement: +0.143 (+20.0%)

평가 메트릭이 회귀된 특정 예제를 찾아서 해당 메트릭에 집중할 수 있습니다.

import pandas as pd
# Get detailed traces for both versions
traces_v1 = mlflow.search_traces(run_id=eval_results_v1.run_id)
traces_v2 = mlflow.search_traces(run_id=eval_results_v2.run_id)

# Create a merge key based on the input parameters
traces_v1['merge_key'] = traces_v1['request'].apply(
    lambda x: f"{x.get('customer_name', '')}|{x.get('user_instructions', '')}"
)
traces_v2['merge_key'] = traces_v2['request'].apply(
    lambda x: f"{x.get('customer_name', '')}|{x.get('user_instructions', '')}"
)

# Merge on the input data to compare same inputs
merged = traces_v1.merge(
    traces_v2,
    on='merge_key',
    suffixes=('_v1', '_v2')
)

print(f"Found {len(merged)} matching examples between v1 and v2")

# Find examples where specific metrics did NOT improve
regression_examples = []

for idx, row in merged.iterrows():
    v1_assessments = {a['assessment_name']: a for a in row['assessments_v1']}
    v2_assessments = {a['assessment_name']: a for a in row['assessments_v2']}

    # Check each judge for regressions
    for scorer_name in ['follows_instructions', 'concise_communication', 'includes_next_steps', 'retrieval_groundedness']:
        v1_assessment = v1_assessments.get(scorer_name)
        v2_assessment = v2_assessments.get(scorer_name)

        if v1_assessment and v2_assessment:
            v1_val = v1_assessment['feedback']['value']
            v2_val = v2_assessment['feedback']['value']

            # Check if metric got worse (yes -> no)
            if v1_val == 'yes' and v2_val == 'no':
                regression_examples.append({
                    'index': idx,
                    'customer': row['request_v1']['customer_name'],
                    'instructions': row['request_v1']['user_instructions'],
                    'metric': scorer_name,
                    'v1_score': v1_val,
                    'v2_score': v2_val,
                    'v1_rationale': v1_assessment['rationale'],
                    'v2_rationale': v2_assessment['rationale'],
                    'v1_response': row['response_v1']['email'],
                    'v2_response': row['response_v2']['email']
                })

# Display regression examples
if regression_examples:
    print(f"\n=== Found {len(regression_examples)} metric regressions ===\n")

    # Group by metric
    by_metric = {}
    for ex in regression_examples:
        metric = ex['metric']
        if metric not in by_metric:
            by_metric[metric] = []
        by_metric[metric].append(ex)

    # Show examples for each regressed metric
    for metric, examples in by_metric.items():
        print(f"\n{'='*80}")
        print(f"METRIC REGRESSION: {metric}")
        print(f"{'='*80}")

        # Show the first example for this metric
        ex = examples[0]
        print(f"\nCustomer: {ex['customer']}")
        print(f"Instructions: {ex['instructions']}")
        print(f"\nV1 Score: ✓ (passed)")
        print(f"V1 Rationale: {ex['v1_rationale']}")
        print(f"\nV2 Score: ✗ (failed)")
        print(f"V2 Rationale: {ex['v2_rationale']}")

        print(f"\n--- V1 Response ---")
        print(ex['v1_response'][:800] + "..." if len(ex['v1_response']) > 800 else ex['v1_response'])

        print(f"\n--- V2 Response ---")
        print(ex['v2_response'][:800] + "..." if len(ex['v2_response']) > 800 else ex['v2_response'])

        if len(examples) > 1:
            print(f"\n(+{len(examples)-1} more examples with {metric} regression)")
else:
    print("\n✓ No metric regressions found - V2 improved or maintained all metrics!")
Found 7 matching examples between v1 and v2

=== Found 2 metric regressions ===


================================================================================
METRIC REGRESSION: retrieval_groundedness
================================================================================

Customer: TechStart
Instructions: Check on support ticket status

V1 Score: ✓ (passed)
V1 Rationale: The response mentions a follow-up email regarding support ticket status, addressed to Bob, discussing three tickets (#456, #457, and #458) and their current status. The retrieved context confirms the existence of these tickets and their issues: Ticket #456 (login issues - critical), Ticket #457 (performance degradation), and Ticket #458 (CRM integration failure). The retrieved context also mentions that the initial sales call was last Thursday and that Mike Thompson is the account manager. All these details match the information provided in the response.

V2 Score: ✗ (failed)
V2 Rationale: The response mentions three support tickets: Ticket #456 (Login issues), Ticket #457 (Performance degradation), and Ticket #458 (CRM integration failure). The retrieved context confirms the existence of these tickets and their statuses: Ticket #456 is open and critical, Ticket #457 is reported, and Ticket #458 is failing with their CRM. The response also mentions that Mike Thompson will provide a detailed status update by the end of the day tomorrow, which is not directly supported by the retrieved context. Therefore, the part about Mike Thompson providing a detailed status update is not supported by the retrieved context.

--- V1 Response ---
# Follow-up Email: Support Ticket Status Update

Subject: Update on Your Support Tickets - Critical Issues Being Addressed

Dear Bob,

I hope you're doing well following our initial discussion last Thursday about pricing options.

I wanted to personally follow up regarding your open support tickets:

- Ticket #456 (Critical): Our technical team has prioritized your login issues and is working to resolve them urgently
- Ticket #457: The performance degradation investigation is in progress
- Ticket #458: Our integration specialists are addressing the CRM connection failures

Mike Thompson, your Account Manager, is closely monitoring these issues. We understand how critical these matters are to your operations.

Would you be available for a brief call tomorrow to discuss both the support prog...

--- V2 Response ---
# Subject: Update on Your Support Tickets

Hi Bob,

I'm following up on your open support tickets:

- Ticket #456 (Login issues): Currently marked as critical and open
- Ticket #457 (Performance degradation): Under investigation
- Ticket #458 (CRM integration failure): Being reviewed by our technical team

I'll contact our support team today and provide you with a detailed status update by end of day tomorrow.

Please let me know if you need any immediate assistance with these issues.

Best regards,
Mike Thompson

(+1 more examples with retrieval_groundedness regression)

9단계: 반복 계속

평가 결과에 따라 반복을 계속하여 애플리케이션의 품질을 개선하고 각 새 수정 사항을 테스트할 수 있습니다.

예제 노트북

다음 Notebook에는 이 페이지의 모든 코드가 포함되어 있습니다.

에이전트 퀵스타트 노트북 평가

노트북 받기

추가 리소스

다음 단계:채점자 및 LLM 심사위원