Microsoft Foundry SDK를 사용하여 클라우드에서 평가 실행

중요

이 문서에서 표시된 항목(미리 보기)은 현재 공개 미리 보기로 제공됩니다. 이 미리 보기는 서비스 수준 계약 없이 제공되며 프로덕션 워크로드에는 권장되지 않습니다. 특정 기능이 지원되지 않거나 기능이 제한될 수 있습니다. 자세한 내용은 Microsoft Azure 미리 보기에 대한 사용 약관 참조하세요.

이 문서에서는 테스트 데이터 세트에 대한 사전 배포 테스트를 위해 클라우드(미리 보기)에서 평가를 실행하는 방법을 알아봅니다.

대부분의 시나리오에서 클라우드 평가를 사용합니다. 특히 대규모로 테스트하거나, 평가를 CI/CD(지속적인 통합 및 지속적인 업데이트) 파이프라인에 통합하거나, 배포 전 테스트를 수행할 때 사용합니다. 클라우드에서 평가를 실행하면 로컬 컴퓨팅 인프라를 관리할 필요가 없으며 대규모의 자동화된 테스트 워크플로를 지원합니다. 평가를 반복적으로 실행하도록 예약 하거나 프로덕션 환경에서 샘플링된 에이전트 응답을 자동으로 평가하도록 연속 평가를 설정할 수도 있습니다.

클라우드 평가 결과는 Foundry 프로젝트에 저장됩니다. 포털에서 결과를 검토하거나, SDK를 통해 검색하거나, 연결된 경우 Application Insights로 라우팅할 수 있습니다. 클라우드 평가는 모든 Microsoft에서 제공하는 내장 평가자 및 사용자 지정 평가자를 지원합니다. 평가자는 동일한 프로젝트 범위 역할 기반 액세스 제어를 사용하여 평가자 카탈로그 에서 관리됩니다.

실행 가능한 전체 예제는 GitHub Python SDK 평가 샘플을 참조하세요.

클라우드 평가 작동 방식

클라우드 평가를 실행하려면 데이터 스키마 및 테스트 조건(평가기)을 사용하여 평가 정의를 만든 다음 평가 실행을 만듭니다. 이 실행은 각 평가기를 데이터에 대해 실행하고 완료 여부를 확인할 수 있는 점수화된 결과를 반환합니다.

클라우드 평가는 다음 시나리오를 지원합니다.

시나리오 사용 시기 데이터 원본 형식 대상
데이터 세트 평가 JSONL 파일에서 미리 계산된 응답을 평가합니다. jsonl
CSV 데이터 세트 평가 CSV 파일에서 미리 계산된 응답을 평가합니다. csv
모델 대상 평가 평가를 위해 런타임에 쿼리를 제공하고 모델에서 응답을 생성합니다. azure_ai_target_completions azure_ai_model
에이전트 대상 평가 평가를 위해 런타임에 쿼리를 제공하고 Foundry 에이전트(프롬프트 또는 호스트됨)에서 응답을 생성합니다. azure_ai_target_completions azure_ai_agent
에이전트 응답 평가 응답 ID를 사용하여 Foundry 에이전트 응답을 검색하고 평가합니다. azure_ai_responses
추적 평가 추적 ID를 사용하여 Application Insights에 이미 캡처된 에이전트 상호 작용을 평가합니다. Foundry가 아닌 에이전트(OpenTelemetry 기반 로깅을 준수하는 LangChain 및 사용자 지정 프레임워크)에 이 방법을 사용합니다. azure_ai_traces
가상 데이터 평가(미리 보기) 가상 테스트 쿼리를 생성하고, 모델 또는 에이전트로 보내고, 응답을 평가합니다. azure_ai_synthetic_data_gen_preview azure_ai_model 또는 azure_ai_agent
레드 팀 평가 모델 또는 에이전트에 대해 자동화된 적대적 테스트를 실행합니다. azure_ai_red_team azure_ai_model 또는 azure_ai_agent

대부분의 시나리오에는 입력 데이터가 필요합니다. 다음 두 가지 방법으로 데이터를 제공할 수 있습니다.

원본 유형 설명
file_id ID별로 업로드된 데이터 세트를 참조합니다.
file_content 요청에 데이터를 인라인으로 제공합니다.

모든 평가에는 data_source_config가 데이터에서 기대되는 필드를 서비스에 설명해주는 역할을 합니다.

  • custom - 필드 이름 및 형식을 사용하여 item_schema 정의합니다. 대상 사용 시, include_sample_schema을(를) true(으)로 설정하여 평가자가 생성된 응답을 참조할 수 있도록 합니다.
  • azure_ai_source — 스키마가 서비스에서 유추됩니다. "scenario" 에이전트 응답 평가용, "traces" 추적 평가용, "synthetic_data_gen_preview" 합성 데이터 평가(미리 보기)용, 또는 "red_team" 레드 팀 활동용으로 설정합니다.

각 시나리오에는 테스트 조건을 정의하는 평가자가 필요합니다. 평가자 선택에 대한 지침은 기본 제공 평가기를 참조하세요.

필수 구성 요소

참고

일부 평가 기능에는 지역 제한이 있습니다. 자세한 내용은 지원되는 지역을 참조하세요 .

시작

SDK를 설치하고 클라이언트를 설정합니다.

pip install "azure-ai-projects>=2.0.0"
import os
from azure.identity import DefaultAzureCredential 
from azure.ai.projects import AIProjectClient 
from openai.types.eval_create_params import DataSourceConfigCustom
from openai.types.evals.create_eval_jsonl_run_data_source_param import (
    CreateEvalJSONLRunDataSourceParam,
    SourceFileContent,
    SourceFileContentContent,
    SourceFileID,
)

# Azure AI Project endpoint
# Example: https://<account_name>.services.ai.azure.com/api/projects/<project_name>
endpoint = os.environ["AZURE_AI_PROJECT_ENDPOINT"]

# Model deployment name (for AI-assisted evaluators)
# Example: gpt-5-mini
model_deployment_name = os.environ.get("AZURE_AI_MODEL_DEPLOYMENT_NAME", "")

# Dataset details (optional, for reusing existing datasets)
dataset_name = os.environ.get("DATASET_NAME", "")
dataset_version = os.environ.get("DATASET_VERSION", "1")

# Create the project client
project_client = AIProjectClient( 
    endpoint=endpoint, 
    credential=DefaultAzureCredential(), 
)

# Get the OpenAI client for evaluation API
client = project_client.get_openai_client()

입력 데이터 준비

대부분의 평가 시나리오에는 입력 데이터가 필요합니다. 다음 두 가지 방법으로 데이터를 제공할 수 있습니다.

JSONL 또는 CSV 파일을 업로드하여 Foundry 프로젝트에서 버전이 지정된 데이터 세트를 만듭니다. 데이터 세트는 여러 평가 실행에서 버전 관리 및 재사용을 지원합니다. 프로덕션 테스트 및 CI/CD 워크플로에 이 방법을 사용합니다.

평가자가 필요로 하는 필드를 포함하는 줄당 하나의 JSON 개체를 사용하여 JSONL 파일을 준비합니다.

{"query": "What is machine learning?", "response": "Machine learning is a subset of AI.", "ground_truth": "Machine learning is a type of AI that learns from data."}
{"query": "Explain neural networks.", "response": "Neural networks are computing systems inspired by biological neural networks.", "ground_truth": "Neural networks are a set of algorithms modeled after the human brain."}

또는 평가자 필드와 일치하는 열 머리글을 가진 CSV 파일을 준비합니다.

query,response,ground_truth
What is machine learning?,Machine learning is a subset of AI.,Machine learning is a type of AI that learns from data.
Explain neural networks.,Neural networks are computing systems inspired by biological neural networks.,Neural networks are a set of algorithms modeled after the human brain.
# Upload a local JSONL file. Skip this step if you already have a dataset registered.
data_id = project_client.datasets.upload_file(
    name=dataset_name,
    version=dataset_version,
    file_path="./evaluate_test_data.jsonl",
).id

인라인으로 데이터 제공

작은 테스트 집합을 사용하여 빠른 실험을 수행하려면 .를 사용하여 file_content평가 요청에 직접 데이터를 제공합니다.

source = SourceFileContent(
    type="file_content",
    content=[
        SourceFileContentContent(
            item={
                "query": "How can I safely de-escalate a tense situation?",
                "ground_truth": "Encourage calm communication, seek help if needed, and avoid harm.",
            }
        ),
        SourceFileContentContent(
            item={
                "query": "What is the largest city in France?",
                "ground_truth": "Paris",
            }
        ),
    ],
)

실행을 만들 때 데이터 원본 구성에서 "source" 필드로 source을(를) 전달합니다. 다음에 나오는 시나리오 섹션은 기본적으로 사용됩니다 file_id .

데이터 세트 평가

데이터 원본 형식을 사용하여 jsonl JSONL 파일에서 미리 계산된 응답을 평가합니다. 이 시나리오는 모델 출력이 이미 있고 해당 품질을 평가하려는 경우에 유용합니다.

시작하기 전에 시작입력 데이터 준비를 완료합니다.

데이터 스키마 및 계산기 정의

JSONL 필드와 일치하는 스키마를 지정하고 실행할 평가자(테스트 조건)를 선택합니다. 입력 데이터의 필드를 data_mapping 매개 변수로 사용하여 {{item.field}} 구문을 통해 평가자 매개 변수에 연결합니다. 항상 각 평가자에 필요한 입력 필드를 포함합니다 data_mapping . 필드 이름은 JSONL 파일에 있는 이름과 일치해야 합니다. 예를 들어, 데이터에 "question" 대신 "query"가 있는 경우, 매핑에 "{{item.question}}"를 사용하세요. 계산기당 필요한 매개 변수는 기본 제공 평가기를 참조하세요.

data_source_config = DataSourceConfigCustom(
    type="custom",
    item_schema={
        "type": "object",
        "properties": {
            "query": {"type": "string"},
            "response": {"type": "string"},
            "ground_truth": {"type": "string"},
        },
        "required": ["query", "response", "ground_truth"],
    },
)

testing_criteria = [
    {
        "type": "azure_ai_evaluator",
        "name": "coherence",
        "evaluator_name": "builtin.coherence",
        "initialization_parameters": {
            "deployment_name": model_deployment_name
        },
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{item.response}}",
        },
    },
    {
        "type": "azure_ai_evaluator",
        "name": "violence",
        "evaluator_name": "builtin.violence",
        "initialization_parameters": {
            "deployment_name": model_deployment_name
        },
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{item.response}}",
        },
    },
    {
        "type": "azure_ai_evaluator",
        "name": "f1",
        "evaluator_name": "builtin.f1_score",
        "data_mapping": {
            "response": "{{item.response}}",
            "ground_truth": "{{item.ground_truth}}",
        },
    },
]

평가 만들기 및 실행

평가를 만든 다음 업로드된 데이터 세트에 대한 실행을 시작합니다. 실행은 데이터 세트의 모든 행에서 각 계산기를 실행합니다.

# Create the evaluation
eval_object = client.evals.create(
    name="dataset-evaluation",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,
)

# Create a run using the uploaded dataset
eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="dataset-run",
    data_source=CreateEvalJSONLRunDataSourceParam(
        type="jsonl",
        source=SourceFileID(
            type="file_id",
            id=data_id,
        ),
    ),
)

실행 가능한 전체 예제는 GitHub sample_evaluations_builtin_with_dataset_id.py 참조하세요. 작업 완료 여부를 확인하고 결과를 분석하려면 결과 가져오기를 참조하세요.

CSV 데이터 세트 평가

데이터 원본 형식을 사용하여 csv CSV 파일에서 미리 계산된 응답을 평가합니다. 이 시나리오는 데이터 세트 평가 와 동일한 방식으로 작동하지만 JSONL 대신 CSV 파일을 허용합니다. 데이터가 이미 스프레드시트 또는 테이블 형식인 경우 CSV를 사용합니다.

시작하기 전에 시작입력 데이터 준비를 완료합니다.

CSV 파일 준비

평가자가 필요한 필드와 일치하는 열 머리글이 있는 CSV 파일을 만드십시오. 각 행은 하나의 테스트 사례를 나타냅니다.

query,response,context,ground_truth
What is cloud computing?,Cloud computing delivers computing services over the internet.,Cloud computing is a technology for on-demand resource delivery.,Cloud computing is the delivery of computing services including servers storage and databases over the internet.
What is machine learning?,Machine learning is a subset of AI that learns from data.,Machine learning is a branch of artificial intelligence.,Machine learning is a type of AI that enables computers to learn from data without being explicitly programmed.
Explain neural networks.,Neural networks are computing systems inspired by biological neural networks.,Neural networks are used in deep learning.,Neural networks are a set of algorithms modeled after the human brain designed to recognize patterns.

업로드 및 실행

CSV 파일을 데이터 세트로 업로드한 다음, 데이터 원본 형식을 csv 사용하여 평가를 만듭니다. 스키마 정의 및 계산기 구성은 JSONL 평가와 동일합니다. 유일한 차이점은 데이터 원본의 차이점입니다 "type": "csv" .

# Upload the CSV file
data_id = project_client.datasets.upload_file(
    name="eval-csv-data",
    version="1",
    file_path="./evaluation_data.csv",
).id

# Define the schema matching your CSV columns
data_source_config = DataSourceConfigCustom(
    type="custom",
    item_schema={
        "type": "object",
        "properties": {
            "query": {"type": "string"},
            "response": {"type": "string"},
            "context": {"type": "string"},
            "ground_truth": {"type": "string"},
        },
        "required": [],
    },
    include_sample_schema=True,
)

# Define evaluators with data mappings to CSV columns
testing_criteria = [
    {
        "type": "azure_ai_evaluator",
        "name": "coherence",
        "evaluator_name": "builtin.coherence",
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{item.response}}",
        },
        "initialization_parameters": {"deployment_name": model_deployment_name},
    },
    {
        "type": "azure_ai_evaluator",
        "name": "violence",
        "evaluator_name": "builtin.violence",
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{item.response}}",
        },
        "initialization_parameters": {"deployment_name": model_deployment_name},
    },
    {
        "type": "azure_ai_evaluator",
        "name": "f1",
        "evaluator_name": "builtin.f1_score",
    },
]

# Create the evaluation
eval_object = client.evals.create(
    name="CSV evaluation with built-in evaluators",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,
)

# Create a run using the CSV data source type
eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="csv-evaluation-run",
    data_source={
        "type": "csv",
        "source": {
            "type": "file_id",
            "id": data_id,
        },
    },
)

작업 완료 여부를 확인하고 결과를 분석하려면 결과 가져오기를 참조하세요.

모델 대상 평가

런타임에 배포된 모델에 쿼리를 보내고 대상과 함께 azure_ai_target_completions 데이터 원본 형식을 azure_ai_model 사용하여 응답을 평가합니다. 입력 데이터에는 쿼리가 포함됩니다. 모델은 응답을 생성한 다음 평가합니다.

시작하기 전에 시작입력 데이터 준비를 완료합니다.

메시지 템플릿 및 대상 정의

템플릿은 input_messages 쿼리를 모델로 보내는 방법을 제어합니다. 입력 데이터의 필드를 참조하는 데 사용합니다 {{item.query}} . 평가할 모델 및 선택적 샘플링 매개 변수를 지정합니다.

input_messages = {
    "type": "template",
    "template": [
        {
            "type": "message",
            "role": "user",
            "content": {
                "type": "input_text",
                "text": "{{item.query}}"
            }
        }
    ]
}

target = {
    "type": "azure_ai_model",
    "model": "gpt-5-mini",
    "sampling_params": {
        "top_p": 1.0,
        "max_completion_tokens": 2048,
    },
}

계산기 및 데이터 매핑 설정

모델이 런타임에 응답을 생성할 때, 출력 참조를 위해 {{sample.output_text}}data_mapping를 사용하십시오. 입력 데이터의 필드를 참조하는 데 사용합니다 {{item.field}} .

data_source_config = DataSourceConfigCustom(
    type="custom",
    item_schema={
        "type": "object",
        "properties": {
            "query": {"type": "string"},
        },
        "required": ["query"],
    },
    include_sample_schema=True,
)

testing_criteria = [
    {
        "type": "azure_ai_evaluator",
        "name": "coherence",
        "evaluator_name": "builtin.coherence",
        "initialization_parameters": {
            "deployment_name": model_deployment_name,
        },
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{sample.output_text}}",
        },
    },
    {
        "type": "azure_ai_evaluator",
        "name": "violence",
        "evaluator_name": "builtin.violence",
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{sample.output_text}}",
        },
    },
]

평가 만들기 및 실행

eval_object = client.evals.create(
    name="Model Target Evaluation",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,
)

data_source = {
    "type": "azure_ai_target_completions",
    "source": {
        "type": "file_id",
        "id": data_id,
    },
    "input_messages": input_messages,
    "target": target,
}

eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="model-target-evaluation",
    data_source=data_source,
)

실행 가능한 전체 예제는 GitHub sample_model_evaluation.py 참조하세요. 작업 완료 여부를 확인하고 결과를 분석하려면 결과 가져오기를 참조하세요.

다른 평가 실행을 추가하려면 동일한 코드를 사용할 수 있습니다.

에이전트 타겟 평가

런타임에 Foundry 에이전트에 쿼리를 보내고 대상과 함께 azure_ai_target_completions 데이터 원본 형식을 azure_ai_agent 사용하여 응답을 평가합니다. 이 시나리오는 프롬프트 에이전트호스트된 에이전트 모두에서 작동합니다.

시작하기 전에 시작입력 데이터 준비를 완료합니다.

응답 프로토콜을 사용하는 호스트된 에이전트는 여기에 표시된 것과 동일한 코드 샘플에서 작동합니다. 호출 프로토콜을 사용하는 호스트된 에이전트의 경우 형식이 input_messages 다릅니다. 자세한 내용은 호스트된 에이전트 호출 프로토콜 을 참조하세요.

메시지 템플릿 및 대상 정의

템플릿은 input_messages 쿼리를 에이전트로 보내는 방법을 제어합니다. 입력 데이터의 필드를 참조하는 데 사용합니다 {{item.query}} . 이름으로 평가할 에이전트를 지정합니다.

input_messages = {
    "type": "template",
    "template": [
        {
            "type": "message",
            "role": "developer",
            "content": {
                "type": "input_text",
                "text": "You are a helpful assistant. Answer clearly and safely."
            }
        },
        {
            "type": "message",
            "role": "user",
            "content": {
                "type": "input_text",
                "text": "{{item.query}}"
            }
        }
    ]
}

target = {
    "type": "azure_ai_agent",
    "name": "my-agent",
    "version": "1"  # Optional. Uses latest version if omitted.
}

계산기 및 데이터 매핑 설정

에이전트가 런타임에 응답을 생성하는 경우 변수를 {{sample.*}} 사용하여 data_mapping 에이전트의 출력을 참조합니다.

변수 설명 용도
{{sample.output_text}} 에이전트의 일반 텍스트 응답입니다. 문자열 응답을 예상하는 계산기(예: coherence, violence)입니다.
{{sample.output_items}} 도구 호출을 포함하여 에이전트의 구조적 JSON 출력입니다. 전체 상호 작용 컨텍스트(예: task_adherence)가 필요한 평가자입니다.
{{item.field}} 입력 데이터의 필드입니다. 입력 필드(예: query 또는 ground_truth.

필드에는 query 시스템 메시지 및 대화 기록을 포함하여 구조화된 JSON이 포함될 수 있습니다. 이러한 task_adherence 일부 에이전트 평가자는 보다 정확한 채점을 위해 이 컨텍스트를 사용합니다. 쿼리 형식 지정에 대한 자세한 내용은 에이전트 평가자를 참조하세요.

data_source_config = DataSourceConfigCustom(
    type="custom",
    item_schema={
        "type": "object",
        "properties": {
            "query": {"type": "string"},
        },
        "required": ["query"],
    },
    include_sample_schema=True,
)

testing_criteria = [
    {
        "type": "azure_ai_evaluator",
        "name": "coherence",
        "evaluator_name": "builtin.coherence",
        "initialization_parameters": {
            "deployment_name": model_deployment_name,
        },
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{sample.output_text}}",
        },
    },
    {
        "type": "azure_ai_evaluator",
        "name": "violence",
        "evaluator_name": "builtin.violence",
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{sample.output_text}}",
        },
    },
    {
        "type": "azure_ai_evaluator",
        "name": "task_adherence",
        "evaluator_name": "builtin.task_adherence",
        "initialization_parameters": {
            "deployment_name": model_deployment_name,
        },
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{sample.output_items}}",
        },
    },
]

평가 만들기 및 실행

eval_object = client.evals.create(
    name="Agent Target Evaluation",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,
)

data_source = {
    "type": "azure_ai_target_completions",
    "source": {
        "type": "file_id",
        "id": data_id,
    },
    "input_messages": input_messages,
    "target": target,
}

agent_eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="agent-target-evaluation",
    data_source=data_source,
)

실행 가능한 전체 예제는 GitHub sample_agent_evaluation.py 참조하세요. 완료를 점검하고 결과를 해석하려면 결과 가져오기를 확인하세요.

호스트된 에이전트 호출 프로토콜

호출 프로토콜을 사용하는 호스트된 에이전트는 동일한 azure_ai_agent 대상 형식을 지원하지만 자유형 input_messages 형식을 사용합니다. 구조화된 템플릿 형식 대신 에이전트의 /invocations 요청 본문에 직접 매핑되는 JSON 개체를 제공합니다. 자리 표시자를 사용하여 {{item.*}} 입력 데이터의 필드를 대체합니다.

호스트된 에이전트가 응답 및 호출 프로토콜을 모두 지원하는 경우 서비스는 기본적으로 호출 프로토콜을 사용합니다.

메시지 형식 및 대상 정의

input_messages = {"message": "{{item.query}}"}

target = {
    "type": "azure_ai_agent",
    "name": "my-hosted-agent",  # Replace with your hosted agent name
    "version": "1",
}

평가 만들기 및 실행

eval_object = client.evals.create(
    name="Hosted Agent Invocations Evaluation",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,
)

data_source = {
    "type": "azure_ai_target_completions",
    "source": {
        "type": "file_id",
        "id": data_id,
    },
    "input_messages": input_messages,
    "target": target,
}

eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="hosted-agent-invocations-evaluation",
    data_source=data_source,
)

평가기 설정 및 데이터 매핑은 프롬프트 에이전트 평가와 동일합니다. 에이전트의 텍스트 응답에는 {{sample.output_text}}을 사용하고, 도구 호출을 포함한 전체 구조화된 출력에는 {{sample.output_items}}을 사용합니다.

에이전트 응답 평가

데이터 원본 형식을 사용하여 azure_ai_responses 응답 ID로 Foundry 에이전트 응답을 검색하고 평가합니다. 이 시나리오를 사용하여 특정 에이전트 상호 작용이 발생한 후 평가합니다.

시작하기 전에 시작을 완료합니다.

응답 ID는 Foundry 에이전트가 응답을 생성할 때마다 반환되는 고유 식별자입니다. 응답 API를 사용하거나 애플리케이션의 추적 로그에서 에이전트 상호 작용에서 응답 ID를 수집할 수 있습니다. ID를 파일 콘텐츠로 인라인으로 제공하거나 데이터 세트로 업로드합니다( 입력 데이터 준비 참조).

응답 ID 수집

응답 API에 대한 각 호출은 고유한 id 필드가 있는 응답 개체를 반환합니다. 애플리케이션의 상호 작용에서 이러한 ID를 수집하거나 직접 생성합니다.

# Generate response IDs by calling a model through the Responses API
response = client.responses.create(
    model=model_deployment_name,
    input="What is machine learning?",
)
print(response.id)  # Example: resp_abc123

애플리케이션의 추적 로그 또는 모니터링 파이프라인의 에이전트 상호 작용에서 응답 ID를 수집할 수도 있습니다. 각 응답 ID는 평가 서비스에서 검색할 수 있는 저장된 응답을 고유하게 식별합니다.

평가 만들기 및 실행

data_source_config = {"type": "azure_ai_source", "scenario": "responses"}

testing_criteria = [
    {
        "type": "azure_ai_evaluator",
        "name": "coherence",
        "evaluator_name": "builtin.coherence",
        "initialization_parameters": {
            "deployment_name": model_deployment_name,
        },
    },
    {
        "type": "azure_ai_evaluator",
        "name": "violence",
        "evaluator_name": "builtin.violence",
    },
]

eval_object = client.evals.create(
    name="Agent Response Evaluation",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,
)

data_source = {
    "type": "azure_ai_responses",
    "item_generation_params": {
        "type": "response_retrieval",
        "data_mapping": {"response_id": "{{item.resp_id}}"},
        "source": {
            "type": "file_content",
            "content": [
                {"item": {"resp_id": "resp_abc123"}},
                {"item": {"resp_id": "resp_def456"}},
            ]
        },
    },
}

eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="agent-response-evaluation",
    data_source=data_source,
)

실행 가능한 전체 예제는 GitHub sample_agent_response_evaluation.py 참조하세요. 작업 완료 여부를 확인하고 결과를 분석하려면 결과 가져오기를 참조하세요.

추적 평가

Application Insights에서 이미 캡처된 에이전트 상호 작용을 평가합니다. 데이터 원본 형식을 azure_ai_traces 사용합니다. 이 시나리오는 배포 후 실제 프로덕션 트래픽을 평가하는 데 유용합니다. 모니터링 파이프라인에서 추적 데이터를 선택하여 요청을 재생하지 않고 이를 기반으로 평가 도구를 실행합니다.

중요

추적 평가는 Microsoft Foundry 에이전트 서비스를 사용하지 않고 빌드된 에이전트를 평가하는 데 권장되는 방법입니다, 여기에는 LangChain과 사용자 지정 프레임워크가 포함됩니다. 에이전트가 GenAI 의미 체계 규칙에 따라 OpenTelemetry 범위를 Application Insights 로 내보내는 한 추적 평가는 Foundry 에이전트에 사용할 수 있는 동일한 평가기를 사용하여 상호 작용을 평가할 수 있습니다.

추적 평가는 다음 두 가지 모드를 지원합니다.

  • 추적 ID로 - Application Insights에서 해당 operation_Id 값을 제공하여 특정 에이전트 상호 작용을 평가합니다.
  • 에이전트 필터 - 추적 ID를 수동으로 수집하지 않고 지정된 에이전트에 대한 최근 추적을 자동으로 검색하고 평가합니다.

시작하기 전에 시작을 완료합니다. 이 시나리오에서는 Foundry 프로젝트에 연결된 Application Insights 리소스도 필요합니다.

추적 데이터 요구 사항

추적 평가를 수행하려면 에이전트가 생성형 AI에 대한 OpenTelemetry 의미론적 규칙에 따라 스팬을 생성해야 합니다. 구체적으로, 평가 서비스는 Application Insights에서 invoke_agent 스팬을 읽어들이고, 해당 속성에서 대화 데이터를 추출합니다.

다음 범위 특성이 사용됩니다.

특성 필수 설명
gen_ai.operation.name "invoke_agent"과(와) 같아야 합니다. 서비스는 다른 모든 범위를 무시합니다.
gen_ai.agent.id 에이전트 필터 모드의 경우 고유 에이전트 식별자(형식: agent-name:version).
gen_ai.agent.name 에이전트 필터 모드의 경우 사람이 읽을 수 있는 에이전트 이름입니다.
gen_ai.input.messages 평가자 쿼리 입력의 경우 GenAI 의미 체계 규칙 메시지 형식에 따른 입력 메시지의 JSON 배열입니다. 역할 user 또는 query에 대한 system 매핑이 있는 메시지, 역할 assistant 또는 response에 대한 tool 매핑이 있는 메시지.
gen_ai.output.messages 평가자 쿼리 입력의 경우 모델 생성 출력 메시지의 JSON 배열입니다. 모든 출력 메시지는 response에 매핑됩니다. 출력에 tool_call 또는 type: tool_result 형식도 포함된 경우 다음으로 매핑됩니다. tool_calls
gen_ai.tool.definitions 선택적 에이전트에서 사용할 수 있는 도구 스키마의 JSON 배열입니다. 서비스가 없는 경우 도구 호출 메시지에서 도구 정의를 유추하려고 시도하지만 유추된 스키마는 불완전할 수 있습니다.
gen_ai.conversation.id 선택적 상관 관계에 대한 평가 결과에 전달되는 대화 식별자입니다.

참고

gen_ai.input.messagesgen_ai.output.messages가 비어 있거나 누락된 경우, 품질 평가자(일관성, 유창성, 관련성, 의도 해결)가 score=None를 반환합니다. 안전 평가자(폭력, 자해, 성적, 증오/불공정)는 여전히 부분 데이터로 점수를 생성할 수 있지만 의미 있는 결과를 생성하지 못할 수 있습니다.

Azure AI 에이전트 서버 SDK를 사용하여 빌드된 Python 에이전트의 경우 [tracing] extra를 추가하여 자동 span 배출을 활성화합니다.

pip install "azure-ai-agentserver-core[tracing]"

추적 평가를 위한 필수 구성 요소

일반적인 필수 구성 요소 외에도 추적 평가에는 다음이 필요합니다.

  • Foundry 프로젝트에 연결된 Application Insights 리소스 입니다. Microsoft Foundry에서 추적 설정 참조하세요.
  • 프로젝트의 관리 ID에는 Application Insights 리소스와 연결된 Log Analytics 작업 영역 모두에서 Log Analytics 읽기 권한자 역할이 있어야 합니다.
  • azure-monitor-query Python 패키지(추적 ID를 수동으로 수집하는 경우에만 필요).
pip install "azure-ai-projects>=2.0.0" azure-monitor-query

다음 환경 변수를 설정합니다.

  • APPINSIGHTS_RESOURCE_ID — Application Insights 리소스 ID(예: /subscriptions/<subscription_id>/resourceGroups/<rg_name>/providers/Microsoft.Insights/components/<resource_name>)입니다.
  • AGENT_ID - 추적을 필터링하는 데 사용되는 추적 통합(gen_ai.agent.id 특성)에서 내보낸 에이전트 식별자입니다. 형식: agent-name:version.
  • TRACE_LOOKBACK_HOURS — (선택 사항) 추적을 쿼리할 때 되돌아볼 시간 수입니다. 기본값은 1입니다.

옵션 A: 에이전트 필터로 평가

가장 간단한 방법 - 서비스에서 특정 에이전트에 대한 최근 추적을 자동으로 검색하고 평가할 수 있도록 합니다. 수동 추적 ID 컬렉션이 필요하지 않습니다.

import os

agent_id = os.environ["AGENT_ID"]  # e.g., "my-weather-agent:1"
trace_lookback_hours = int(os.environ.get("TRACE_LOOKBACK_HOURS", "1"))

# Create the evaluation
data_source_config = {
    "type": "azure_ai_source",
    "scenario": "traces",
}

eval_object = client.evals.create(
    name="Agent Trace Evaluation (by agent)",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,  # See "Set up evaluators" below
)

# Create a run — the service queries App Insights for matching traces
data_source = {
    "type": "azure_ai_traces",
    "agent_id": agent_id,
    "max_traces": 50,           # Maximum number of traces to evaluate
    "lookback_hours": trace_lookback_hours,
}

eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="agent-trace-eval-run",
    data_source=data_source,
)

print(f"Evaluation run started: {eval_run.id}")

서비스는 invoke_agent 스팬을 gen_ai.agent.id 속성별로 필터링하고, 최대 max_traces개의 고유 추적 ID를 샘플링하며, 해당 추적의 모든 스팬을 평가합니다.

옵션 B: 추적 ID로 평가

더 많은 제어를 위해 Application Insights에서 특정 추적 ID를 수집하고 평가합니다. 이는 큐레이팅된 상호 작용 집합(예: 경고에 의해 플래그가 지정되거나 품질 검토를 위해 샘플링된 추적)을 평가하려는 경우에 유용합니다.

Application Insights에서 추적 ID 수집

에이전트의 추적에서 operation_Id 값을 Application Insights로 쿼리합니다. 각각 operation_Id 은 전체 에이전트 상호 작용을 나타냅니다.

import os
from datetime import datetime, timedelta, timezone
from azure.identity import DefaultAzureCredential
from azure.monitor.query import LogsQueryClient, LogsQueryStatus

appinsights_resource_id = os.environ["APPINSIGHTS_RESOURCE_ID"]
agent_id = os.environ["AGENT_ID"]
trace_query_hours = int(os.environ.get("TRACE_LOOKBACK_HOURS", "1"))

end_time = datetime.now(timezone.utc)
start_time = end_time - timedelta(hours=trace_query_hours)

query = f"""dependencies
| where timestamp between (datetime({start_time.isoformat()}) .. datetime({end_time.isoformat()}))
| extend agent_id = tostring(customDimensions["gen_ai.agent.id"])
| where agent_id == "{agent_id}"
| distinct operation_Id"""

credential = DefaultAzureCredential()
logs_client = LogsQueryClient(credential)
response = logs_client.query_resource(
    appinsights_resource_id,
    query=query,
    timespan=None,  # Time range is specified in the query itself
)

trace_ids = []
if response.status == LogsQueryStatus.SUCCESS:
    for table in response.tables:
        for row in table.rows:
            trace_ids.append(row[0])

print(f"Found {len(trace_ids)} trace IDs")

추적 ID를 사용하여 평가 및 실행 만들기

# Create the evaluation
data_source_config = {
    "type": "azure_ai_source",
    "scenario": "traces",
}

eval_object = client.evals.create(
    name="Agent Trace Evaluation (by trace IDs)",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,  # See "Set up evaluators" below
)

# Create a run using the collected trace IDs
data_source = {
    "type": "azure_ai_traces",
    "trace_ids": trace_ids,
    "lookback_hours": trace_query_hours,
}

eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="agent-trace-eval-run",
    metadata={
        "agent_id": agent_id,
        "start_time": start_time.isoformat(),
        "end_time": end_time.isoformat(),
    },
    data_source=data_source,
)

print(f"Evaluation run started: {eval_run.id}")

계산기 및 데이터 매핑 설정

추적을 평가할 때 서비스는 OpenTelemetry 범위 특성에서 대화 데이터를 자동으로 추출합니다. 다른 시나리오에서 사용하는 item.sample. 접두사를 붙이지 않고 data_mapping에 이러한 필드 이름을 직접 사용합니다.

변수 원본 특성 설명
{{item.query}} gen_ai.input.messages (사용자/시스템 역할) 추적에서 추출된 사용자 쿼리입니다.
{{item.response}} gen_ai.input.messages (도우미/도구 역할) + gen_ai.output.messages 추적에서 추출된 에이전트의 응답입니다.
{{item.tool_definitions}} gen_ai.tool.definitions 에이전트에서 사용할 수 있는 도구 스키마입니다. 도구 관련 평가자에만 필요
{{item.tool_calls}} 에서 도우미 메시지에서 추출됨 gen_ai.input.messages / gen_ai.output.messages 상호 작용 중에 에이전트가 수행한 도구 호출입니다. 도구 평가자에 의해 사용됩니다. 도구 관련 평가자에만 필요
testing_criteria = [
    # Quality evaluators — require query and response from trace data
    {
        "type": "azure_ai_evaluator",
        "name": "intent_resolution",
        "evaluator_name": "builtin.intent_resolution",
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{item.response}}",
            "tool_definitions": "{{item.tool_definitions}}",
        },
        "initialization_parameters": {
            "deployment_name": model_deployment_name,
        },
    },
    # Tool evaluators — assess tool usage quality
    {
        "type": "azure_ai_evaluator",
        "name": "tool_call_accuracy",
        "evaluator_name": "builtin.tool_call_accuracy",
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{item.response}}",
            "tool_calls": "{{item.tool_calls}}",
            "tool_definitions": "{{item.tool_definitions}}",
        },
        "initialization_parameters": {
            "deployment_name": model_deployment_name,
        },
    },
    # Safety evaluators — work even with partial trace data
    {
        "type": "azure_ai_evaluator",
        "name": "violence",
        "evaluator_name": "builtin.violence",
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{item.response}}",
        },
        "initialization_parameters": {
            "threshold": 4,
        },
    },
]

실행 가능한 전체 예제는 GitHub sample_evaluations_builtin_with_traces.py 참조하세요. 작업 완료 여부를 확인하고 결과를 분석하려면 결과 가져오기를 참조하세요.

가상 데이터 평가(미리 보기)

가상 테스트 쿼리를 생성하고, 배포된 모델 또는 Foundry 에이전트로 보내고, 데이터 원본 형식을 azure_ai_synthetic_data_gen_preview 사용하여 응답을 평가합니다. 테스트 데이터 세트가 없는 경우 이 시나리오를 사용합니다. 서비스는 제공한 프롬프트(및/또는 에이전트의 지침)를 기반으로 쿼리를 생성하고, 대상에 대해 쿼리를 실행하고, 응답을 평가합니다.

시작하기 전에 시작을 완료합니다.

합성 데이터 평가의 작동 원리

  1. 서비스는 사용자 prompt 및 선택적 시드 데이터 파일을 기반으로 가상 쿼리를 생성합니다.
  2. 각 쿼리는 지정된 대상(모델 또는 에이전트)으로 전송되어 응답을 생성합니다.
  3. 계산기는 생성된 쿼리 및 응답을 사용하여 각 응답의 점수를 매깁니다.
  4. 생성된 쿼리는 재사용을 위해 프로젝트에 데이터 세트로 저장됩니다.

매개 변수

매개 변수 필수 설명
samples_count 생성할 가상 테스트 쿼리의 최대 수입니다.
model_deployment_name 가상 쿼리를 생성하는 데 사용할 모델 배포입니다. 응답 API 기능이 있는 모델만 지원됩니다. 가용성은 응답 API 지역 가용성을 참조하세요.
prompt 아니요 생성할 쿼리 유형을 설명하는 지침입니다. 에이전트 대상에 명령이 구성된 경우 선택 사항입니다.
output_dataset_name 아니요 생성된 쿼리가 저장되는 출력 데이터 세트의 이름입니다. 제공되지 않으면 서비스가 자동으로 이름을 생성합니다.
sources 아니요 생성된 쿼리의 관련성을 높이기 위해 파일 ID별로 데이터 파일을 시드합니다. 현재 하나의 파일만 지원됩니다.

계산기 및 데이터 매핑 설정

합성 데이터 생성기는 {{item.query}} 필드에서 쿼리를 생성합니다. 대상은 {{sample.output_text}}에서 이용할 수 있는 응답을 생성합니다. 평가자에 다음 필드를 매핑합니다.

data_source_config = {"type": "azure_ai_source", "scenario": "synthetic_data_gen_preview"}

testing_criteria = [
    {
        "type": "azure_ai_evaluator",
        "name": "coherence",
        "evaluator_name": "builtin.coherence",
        "initialization_parameters": {
            "deployment_name": model_deployment_name,
        },
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{sample.output_text}}",
        },
    },
    {
        "type": "azure_ai_evaluator",
        "name": "violence",
        "evaluator_name": "builtin.violence",
        "data_mapping": {
            "query": "{{item.query}}",
            "response": "{{sample.output_text}}",
        },
    },
]

평가 만들기 및 실행

모델 대상

가상 쿼리를 생성하고 모델을 평가합니다.

eval_object = client.evals.create(
    name="Synthetic Data Evaluation",
    data_source_config=data_source_config,
    testing_criteria=testing_criteria,
)

data_source = {
    "type": "azure_ai_synthetic_data_gen_preview",
    "item_generation_params": {
        "type": "synthetic_data_gen_preview",
        "samples_count": 5,
        "prompt": "Generate customer service questions about returning defective products",
        "model_deployment_name": model_deployment_name,
        "output_dataset_name": "my-synthetic-dataset",
    },
    "target": {
        "type": "azure_ai_model",
        "model": model_deployment_name,
    },
}

eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="synthetic-data-evaluation",
    data_source=data_source,
)

필요에 따라 시스템 프롬프트를 추가하여 대상 모델의 동작을 셰이프할 수 있습니다. 가상 데이터 생성과 함께 사용하는 input_messages 경우 역할 메시지만 system 포함합니다. 서비스는 생성된 쿼리를 사용자 메시지로 자동으로 제공합니다.

data_source = {
    "type": "azure_ai_synthetic_data_gen_preview",
    "item_generation_params": {
        "type": "synthetic_data_gen_preview",
        "samples_count": 5,
        "prompt": "Generate customer service questions about returning defective products",
        "model_deployment_name": model_deployment_name,
    },
    "target": {
        "type": "azure_ai_model",
        "model": model_deployment_name,
    },
    "input_messages": {
        "type": "template",
        "template": [
            {
                "type": "message",
                "role": "system",
                "content": {
                    "type": "input_text",
                    "text": "You are a helpful customer service agent. Be empathetic and solution-oriented."
                }
            }
        ]
    },
}

에이전트 타깃

가상 쿼리를 생성하고 Foundry 에이전트를 평가합니다.

data_source = {
    "type": "azure_ai_synthetic_data_gen_preview",
    "item_generation_params": {
        "type": "synthetic_data_gen_preview",
        "samples_count": 5,
        "prompt": "Generate questions about returning defective products",
        "model_deployment_name": model_deployment_name,
    },
    "target": {
        "type": "azure_ai_agent",
        "name": agent_name,
        "version": agent_version,
    },
}

eval_run = client.evals.runs.create(
    eval_id=eval_object.id,
    name="synthetic-agent-evaluation",
    data_source=data_source,
)

작업 완료 여부를 확인하고 결과를 분석하려면 결과 가져오기를 참조하세요. 응답에는 생성된 데이터 세트의 ID가 포함된 속성 output_dataset_id이 있어, 이를 통해 가상 데이터를 검색하거나 재사용할 수 있습니다.

결과 가져오기

평가 실행이 완료되면 채점된 결과를 검색하고 포털에서 또는 프로그래밍 방식으로 검토합니다.

결과 집계

평가 실행은 비동기적입니다. 실행 상태가 완료될 때까지 상태를 지속적으로 확인한 다음 결과를 가져옵니다.

import time
from pprint import pprint

while True:
    run = client.evals.runs.retrieve(
        run_id=eval_run.id, eval_id=eval_object.id
    )
    if run.status in ("completed", "failed"):
        break
    time.sleep(5)
    print("Waiting for eval run to complete...")

# Retrieve results
output_items = list(
    client.evals.runs.output_items.list(
        run_id=run.id, eval_id=eval_object.id
    )
)
pprint(output_items)
print(f"Report URL: {run.report_url}")

결과 해석

단일 데이터 예제의 경우 모든 평가자는 다음 스키마를 출력합니다.

  • 레이블: 단위 테스트의 출력과 유사한 이진 "pass" 또는 "fail" 레이블입니다. 이 결과를 사용하여 평가자 간 비교를 용이하게 합니다.
  • 점수: 각 평가자의 자연 눈금에서의 점수입니다. 일부 평가자는 세분화된 루브릭을 사용하여 5포인트 배율(품질 평가자) 또는 7포인트 배율(콘텐츠 안전 평가자)에서 점수를 매깁니다. 텍스트 유사성 평가기와 같은 다른 항목은 0에서 1 사이의 부동 소수점인 F1 점수를 사용합니다. 모든 비이진 "점수"는 "임계값"을 기준으로 "레이블" 필드에서 "합격" 또는 "불합격"으로 이진화됩니다.
  • 임계값: 이진 점수가 아닌 점수는 사용자가 SDK 환경에서 재정의할 수 있는 기본 임계값에 따라 "통과" 또는 "실패"로 이진화됩니다.
  • 이유: 지능성을 향상시키기 위해 모든 LLM-판사 평가자는 특정 점수가 지정된 이유를 설명하는 추론 필드를 출력합니다.
  • 세부 정보: (선택 사항) tool_call_accuracy 같은 일부 평가자의 경우 사용자가 애플리케이션을 디버그하는 데 도움이 되는 추가 정보가 포함된 "세부 정보" 필드 또는 플래그가 있을 수 있습니다.

예제 출력(단일 항목)

{
  "type": "azure_ai_evaluator",
  "name": "Coherence",
  "metric": "coherence",
  "score": 4.0,
  "label": "pass",
  "reason": "The response is well-structured and logically organized, presenting information in a clear and coherent manner.",
  "threshold": 3,
  "passed": true
}

예제 출력(집계)

여러 데이터 예제(데이터 세트)에 대한 집계 결과의 경우 "통과"가 있는 예제의 평균 속도는 해당 데이터 세트에 대한 전달 속도를 형성합니다.

{
  "eval_id": "eval_abc123",
  "run_id": "run_xyz789",
  "status": "completed",
  "result_counts": {
    "passed": 85,
    "failed": 15,
    "total": 100
  },
  "per_testing_criteria_results": [
    {
      "name": "coherence",
      "passed": 92,
      "failed": 8,
      "pass_rate": 0.92
    },
    {
      "name": "relevance", 
      "passed": 78,
      "failed": 22,
      "pass_rate": 0.78
    }
  ]
}

문제 해결

오랫동안 실행 중인 작업

평가 작업은 장기간 실행 중 상태로 유지될 수 있습니다. 이는 일반적으로 Azure OpenAI 모델 배포에 충분한 용량이 없어서 서비스가 요청을 다시 시도하게 하는 경우에 발생합니다.

해상도:

  1. 를 사용하여 현재 평가 작업을 취소합니다 client.evals.runs.cancel(run_id, eval_id=eval_id).
  2. Azure 포털에서 모델 용량을 늘입니다.
  3. 평가를 다시 실행합니다.

인증 오류

오류 메시지가 401 Unauthorized403 Forbidden 표시되면 다음을 확인합니다.

  • DefaultAzureCredential 올바르게 구성됩니다(Azure CLI 사용하는 경우 az login 실행).
  • 계정에는 Foundry 프로젝트에서 Azure AI 사용자 역할이 있습니다.
  • 프로젝트 엔드포인트 URL이 올바르며 계정과 프로젝트 이름을 모두 포함합니다.

데이터 형식 오류

스키마 또는 데이터 매핑 오류로 평가가 실패하는 경우:

  • JSONL 파일에 줄당 하나의 유효한 JSON 개체가 있는지 확인합니다.
  • 필드 이름이 data_mapping JSONL 파일의 필드 이름과 정확히 일치하는지 확인합니다(대/소문자 구분).
  • 속성이 item_schema 데이터 세트의 필드와 일치하는지 확인합니다.

속도 제한 오류

평가 실행 생성은 테넌트, 구독 및 프로젝트 수준에서 속도가 제한됩니다. 429 Too Many Requests 응답을 받으면:

  • 응답의 retry-after 헤더에서 권장 대기 시간을 확인합니다.
  • 응답 본문에서 속도 제한 세부 정보를 검토합니다.
  • 실패한 요청을 다시 시도할 때 지수 백오프를 사용합니다.

실행 중에 오류가 발생하여 평가 작업이 실패하는 429 경우:

  • 평가 데이터 세트의 크기를 줄이거나 더 작은 일괄 처리로 분할합니다.
  • Azure 포털에서 모델 배포에 대한 TPM(분당 토큰) 할당량을 늘입니다.

에이전트 계산기 도구 오류

에이전트 평가자가 지원되지 않는 도구에 대한 오류를 반환하는 경우:

  • 에이전트 평가자에 대해 지원되는 도구를 확인합니다.
  • 해결 방법으로 지원되지 않는 도구를 평가자가 평가할 수 있도록 사용자 정의 함수 도구로 래핑합니다.