비고
이 문서는 Microsoft Foundry(신규) 포털을 참조하세요.
중요합니다
이 문서에 표시된 항목(미리 보기)은 현재 퍼블릭 미리 보기에서 확인할 수 있습니다. 이 미리 보기는 서비스 수준 계약 없이 제공되며, 프로덕션 워크로드에는 권장되지 않습니다. 특정 기능이 지원되지 않거나 기능이 제한될 수 있습니다. 자세한 내용은 Microsoft Azure Preview에 대한 추가 사용 약관을 참조하세요.
AI 에이전트는 비즈니스 요구 사항에 맞는 워크플로를 만드는 강력한 생산성 도우미입니다. 그러나 복잡한 상호 작용 패턴 때문에 관찰성이 어렵습니다. 이 문서에서는 기본 제공 평가기를 사용하여 Microsoft Foundry 에이전트 또는 기타 에이전트를 평가하는 방법을 알아봅니다.
프로덕션 지원 에이전트 애플리케이션을 빌드하고 관찰 가능성과 투명성을 보장하기 위해 개발자는 에이전트 워크플로의 최종 출력뿐만 아니라 워크플로의 품질과 효율성을 평가하는 도구가 필요합니다.
"내일 날씨"를 쿼리하는 사용자와 같은 이벤트는 에이전트 워크플로를 트리거합니다. 최종 응답을 생성하기 위해 워크플로에는 사용자 의도를 통한 추론, 도구 호출 및 검색 보강 생성 사용이 포함됩니다.
비고
평가용 Microsoft Foundry SDK 및 Foundry 포털은 공개 미리 보기로 제공되지만 API는 일반적으로 모델 및 데이터 세트 평가에 사용할 수 있습니다(에이전트 평가는 공개 미리 보기로 유지됨). 이 문서에서 표시된 Azure AI 평가 SDK 및 평가자(미리 보기)는 현재 모든 위치에서 공개 미리 보기로 제공됩니다.
비고
평가용 Microsoft Foundry SDK 및 Foundry 포털은 공개 미리 보기로 제공되지만 API는 일반적으로 모델 및 데이터 세트 평가에 사용할 수 있습니다(에이전트 평가는 공개 미리 보기로 유지됨). 이 문서에 (미리 보기)로 표시된 평가자는 현재 모든 곳에서 공개적으로 미리 보기로 제공됩니다.
이 프로세스에서는 워크플로의 각 단계와 최종 출력의 품질 및 안전성 평가가 중요합니다. 이러한 평가 측면을 에이전트에 대한 다음 평가자로 공식화합니다.
- 의도 확인: 에이전트가 사용자의 의도를 올바르게 식별하는지 여부를 측정합니다.
- 도구 호출 정확도: 에이전트가 사용자의 요청에 대해 올바른 함수 도구를 호출했는지 여부를 측정합니다.
- 작업 준수: 에이전트의 최종 응답이 시스템 메시지 및 이전 단계에 따라 할당된 작업을 준수하는지 여부를 측정합니다.
포괄적인 기본 제공 평가기 제품군을 사용하여 에이전트 워크플로의 다른 품질 및 안전 측면을 평가합니다. 일반적으로 에이전트는 에이전트 메시지를 내보낸다. 에이전트 메시지를 평가자에 대한 올바른 평가 데이터로 변환하는 것은 어려울 수 있습니다. Foundry 에이전트 서비스를 사용하여 에이전트를 빌드하는 경우 변환기 지원을 통해 원활하게 평가할 수 있습니다. 만약 Foundry 에이전트 서비스 외부에서 에이전트를 빌드하는 경우, 에이전트 메시지를 필요한 데이터 형식으로 구문 분석하여, 에이전트 워크플로에 적합하게 평가자를 사용할 수 있습니다. 다른 에이전트를 평가하는 예제를 참조하세요.
모범 사례로 다음을 수행하는 것이 중요합니다.
- 시스템 평가: 에이전트 워크플로의 전반적인 품질과 효율성을 평가합니다. 그리고
- 프로세스 평가: 워크플로의 도구 호출 단계를 평가합니다.
두 가지 실천의 사용 사례 및 각 에이전트 평가자의 샘플에 대한 자세한 내용은 에이전트 평가자 항목을 참조하세요.
또한 포괄적인 기본 제공 평가기 제품군을 사용하거나 사용자 지정 평가자를 작성하여 에이전트 워크플로의 다른 품질 및 안전 측면을 평가할 수도 있습니다.
Foundry 에이전트를 빌드하는 경우 원활하게 평가해 볼 수 있습니다.
Foundry 외부에서 에이전트를 빌드하는 경우 에이전트 메시지를 필요한 데이터 형식으로 구문 분석하여 에이전트 워크플로에 적절하게 평가자를 사용할 수 있습니다. 다른 에이전트 평가의 세부 정보를 참조하세요.
시작하기
Azure AI 평가 SDK에서 평가기 패키지를 설치합니다.
pip install azure-ai-evaluation
Azure AI 평가 SDK에서 패키지를 설치합니다.
pip install "azure-ai-projects>=2.0.0b1" azure-identity python-dotenv
환경 변수를 귀하의 값으로 지정하여 .env 파일에 설정하십시오.
AZURE_AI_PROJECT_ENDPOINT="<your-endpoint>" # The Azure AI Project project endpoint, as found in the Home page of your Microsoft Foundry portal.
AZURE_AI_MODEL_DEPLOYMENT_NAME="<your-model-deployment-name>" # The deployment name of the AI model, as found under the "Build" page in the "Models" tab in your Foundry project.
Microsoft Foundry 에이전트 평가하기
Foundry 에이전트 서비스를 사용하는 경우 Microsoft Foundry 에이전트 및 의미 체계 커널 에이전트에 대한 변환기 지원을 사용하여 에이전트를 원활하게 평가할 수 있습니다. 다음 평가기는 변환기에서 IntentResolutionToolCallAccuracyTaskAdherenceRelevance반환된 평가 데이터를 지원합니다. Groundedness
비고
다른 스키마를 출력하는 다른 에이전트를 빌드하는 경우 일반 OpenAI 스타일 에이전트 메시지 스키마 로 변환하고 이전 평가자를 사용합니다. 일반적으로 에이전트 메시지를 필요한 데이터 형식으로 구문 분석할 수 있는 경우 모든 평가자를 사용할 수도 있습니다.
AI 지원 평가자에 대한 모델 지원
AzureOpenAI 및 OpenAI 추론 모델 및 비이성 모델은 평가자에 따라 LLM-judge를 지원합니다.
| 평가자 | 판단 모델로서의 추론(예: Azure OpenAI/OpenAI의 o-시리즈 모델) | 판사로서의 비 추론 모델(예: gpt-4.1, gpt-4o 등) | 사용자가 |
|---|---|---|---|
IntentResolution, TaskAdherence, ToolCallAccuracy, ResponseCompleteness, Coherence, Fluency, SimilarityGroundedness, RetrievalRelevance |
지원됨 | 지원됨 | 계산기 초기화에 추가 매개 변수 is_reasoning_model=True 설정 |
| 기타 평가자 | 지원되지 않음 | 지원됨 | -- |
정교한 추론이 필요한 복잡한 평가의 경우 추론 성능과 비용 효율성의 균형을 맞추기 위해 강력한 4.1-mini 추론 모델을 사용합니다.
도구 호출 평가를 위한 지원
ToolCallAccuracyEvaluator 에서는 다음 도구에 대한 Microsoft Foundry 에이전트의 평가를 지원합니다.
- 파일 검색
- Azure AI 검색
- 빙 그라운딩
- Bing 맞춤 검색
- SharePoint 기초
- 코드 인터프리터
- 패브릭 데이터 에이전트
- OpenAPI
- 함수 도구(사용자 정의 도구)
그러나 에이전트 실행에서 지원되지 않는 도구를 사용하는 경우 평가기는 이러한 사례를 쉽게 필터링하기 위해 "통과"와 호출된 도구 평가가 지원되지 않는 이유를 출력합니다. 평가를 사용하도록 설정하려면 지원되지 않는 도구를 사용자 정의 도구로 래핑합니다.
이 예제에서는 Microsoft Foundry 에이전트를 빌드하고 평가하는 방법을 보여줍니다. 평가와 별도로 Foundry 에이전트 서비스에는 pip install azure-ai-projects azure-identityFoundry 프로젝트 연결 문자열 및 지원되는 모델이 필요합니다.
에이전트 스레드 및 실행 만들기
에이전트는 도구를 사용할 수 있습니다. 다음은 에이전트가 사용할 사용자 지정 도구를 만드는 예제입니다(모의 날씨 함수를 예로 사용).
from azure.ai.projects.models import FunctionTool, ToolSet
from typing import Set, Callable, Any
import json
# Define a custom Python function.
def fetch_weather(location: str) -> str:
"""
Fetches the weather information for the specified location.
:param location (str): The location to fetch weather for.
:return: Weather information as a JSON string.
:rtype: str
"""
# In a real-world scenario, you'd integrate with a weather API.
# In the following code snippet, we mock the response.
mock_weather_data = {"Seattle": "Sunny, 25°C", "London": "Cloudy, 18°C", "Tokyo": "Rainy, 22°C"}
weather = mock_weather_data.get(location, "Weather data not available for this location.")
weather_json = json.dumps({"weather": weather})
return weather_json
user_functions: Set[Callable[..., Any]] = {
fetch_weather,
}
# Add tools that the agent will use.
functions = FunctionTool(user_functions)
toolset = ToolSet()
toolset.add(functions)
AGENT_NAME = "Seattle Tourist Assistant"
Foundry(비 허브) 프로젝트를 사용하는 경우 다음과 같이 도구 집합을 사용하여 에이전트를 만듭니다.
비고
더 낮은 버전만 지원하는 azure-ai-projects<1.0.0b10 azure-ai-agents<1.0.0b10 사용하는 경우 일괄 처리 평가 결과를 로깅하기 위해 설정된 Foundry 프로젝트를 사용하여 최신 Foundry 에이전트 서비스 SDK Python 클라이언트 라이브러리로 마이그레이션하는 것이 좋습니다.
다음과 같이 도구 집합을 사용하여 에이전트를 만듭니다.
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from dotenv import load_dotenv
load_dotenv()
# Create an Azure AI Client from an endpoint, copied from your Foundry project.
# You need to login to Azure subscription via Azure CLI and set the environment variables
# Foundry project endpoint, example: AZURE_AI_PROJECT=https://your-account.services.ai.azure.com/api/projects/your-project
project_endpoint = os.environ["AZURE_AI_PROJECT"] # Ensure the PROJECT_ENDPOINT environment variable is set
# Create an AIProjectClient instance
project_client = AIProjectClient(
endpoint=project_endpoint,
credential=DefaultAzureCredential(), # Use Azure Default Credential for authentication
)
# Create an agent with the toolset
agent = project_client.agents.create_agent(
model=os.environ["MODEL_DEPLOYMENT_NAME"], # Model deployment name
name="my-agent", # Name of the agent
instructions="You are a helpful agent", # Instructions for the agent
toolset=toolset
)
print(f"Created agent, ID: {agent.id}")
# Create a thread for communication
thread = project_client.agents.threads.create()
print(f"Created thread, ID: {thread.id}")
# Add a message to the thread
message = project_client.agents.messages.create(
thread_id=thread.id,
role="user", # Role of the message sender
content="What is the weather in Seattle today?", # Message content
)
print(f"Created message, ID: {message['id']}")
# Create and process an agent run
run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
print(f"Run finished with status: {run.status}")
# Check if the run failed
if run.status == "failed":
print(f"Run failed: {run.last_error}")
# Fetch and log all messages
messages = project_client.agents.messages.list(thread_id=thread.id)
for message in messages:
print(f"Role: {message.role}, Content: {message.content}")
단일 에이전트 실행 평가
에이전트 실행을 만든 후에는 변환기를 사용하여 Microsoft Foundry 에이전트 스레드 데이터를 평가자가 이해할 수 있는 필수 평가 데이터로 변환할 수 있습니다.
import json, os
from azure.ai.evaluation import AIAgentConverter, IntentResolutionEvaluator
# Initialize the converter for Microsoft Foundry agents.
converter = AIAgentConverter(project_client)
# Specify the thread and run ID.
thread_id = thread.id
run_id = run.id
converted_data = converter.convert(thread_id, run_id)
이것으로 끝입니다.
converted_data 에는 이러한 평가자에 필요한 모든 입력이 포함됩니다. 각 평가자에 대한 입력 요구 사항을 읽거나 입력을 구문 분석하는 작업을 수행할 필요가 없습니다. 평가기를 선택하고 이 단일 실행에서 평가자를 호출합니다. 평가자에 따라 판사에 대한 Azure OpenAI 또는 OpenAI 추론 모델 및 비이성 모델을 지원합니다.
| 평가자 | 판단 모델로서의 추론(예: Azure OpenAI/OpenAI의 o-시리즈 모델) | 판사로서의 비 추론 모델(예: gpt-4.1, gpt-4o 등) | 사용자가 |
|---|---|---|---|
GroundednessProEvaluator를 제외한 모든 품질 평가자 |
지원됨 | 지원됨 | 계산기 초기화에 추가 매개 변수 is_reasoning_model=True 설정 |
GroundednessProEvaluator |
사용자가 모델을 지원할 필요가 없습니다. | 사용자가 모델을 지원할 필요가 없습니다. | -- |
평가에 대한 정교한 추론이 필요한 복잡한 작업의 경우 추론 성능과 비용 효율성의 균형을 통해 나중에 출시된 강력한 추론 모델 o3-mini 또는 o 시리즈 미니 모델을 사용하는 것이 좋습니다.
품질 및 안전 평가자 quality_evaluatorssafety_evaluators 목록을 설정하고 다중 에이전트 실행 또는 스레드 평가에서 참조합니다.
# This is specific to agentic workflows.
from azure.ai.evaluation import IntentResolutionEvaluator, TaskAdherenceEvaluator, ToolCallAccuracyEvaluator
# Other quality, risk, and safety metrics:
from azure.ai.evaluation import RelevanceEvaluator, CoherenceEvaluator, CodeVulnerabilityEvaluator, ContentSafetyEvaluator, IndirectAttackEvaluator, FluencyEvaluator
from azure.identity import DefaultAzureCredential
import os
from dotenv import load_dotenv
load_dotenv()
model_config = {
"azure_deployment": os.getenv("AZURE_DEPLOYMENT_NAME"),
"api_key": os.getenv("AZURE_API_KEY"),
"azure_endpoint": os.getenv("AZURE_ENDPOINT"),
"api_version": os.getenv("AZURE_API_VERSION"),
}
# example config for a reasoning model
reasoning_model_config = {
"azure_deployment": "o3-mini",
"api_key": os.getenv("AZURE_API_KEY"),
"azure_endpoint": os.getenv("AZURE_ENDPOINT"),
"api_version": os.getenv("AZURE_API_VERSION"),
}
# Evaluators you might want to use with reasoning models
quality_evaluators = {evaluator.__name__: evaluator(model_config=reasoning_model_config, is_reasoning_model=True) for evaluator in [IntentResolutionEvaluator, TaskAdherenceEvaluator, ToolCallAccuracyEvaluator]}
# Other evaluators you might NOT want to use with reasoning models
quality_evaluators.update({ evaluator.__name__: evaluator(model_config=model_config) for evaluator in [CoherenceEvaluator, FluencyEvaluator, RelevanceEvaluator]})
## Using Foundry (non-Hub) project endpoint, example: AZURE_AI_PROJECT=https://your-account.services.ai.azure.com/api/projects/your-project
azure_ai_project = os.environ.get("AZURE_AI_PROJECT")
safety_evaluators = {evaluator.__name__: evaluator(azure_ai_project=azure_ai_project, credential=DefaultAzureCredential()) for evaluator in [ContentSafetyEvaluator, IndirectAttackEvaluator, CodeVulnerabilityEvaluator]}
# Reference the quality and safety evaluator list above.
quality_and_safety_evaluators = {**quality_evaluators, **safety_evaluators}
for name, evaluator in quality_and_safety_evaluators.items():
result = evaluator(**converted_data)
print(name)
print(json.dumps(result, indent=4))
출력 형식
AI 지원 품질 평가자는 쿼리 및 응답 쌍에 대한 결과를 반환합니다. 결과는 다음을 포함하는 사전입니다.
-
{metric_name}: Likert 눈금(정수 1~5) 또는 0에서 1 사이의 부동 소수점수로 숫자 점수를 제공합니다. -
{metric_name}_label: 이진 레이블을 제공합니다(메트릭이 자연스럽게 이진 점수를 출력하는 경우). -
{metric_name}_reason: 각 데이터 요소에 대해 특정 점수 또는 레이블이 지정된 이유를 설명합니다. -
details: 단일 에이전트 실행의 품질에 대한 디버깅 정보를 포함하는 선택적 출력입니다.
명확성을 높이기 위해 모든 평가자는 이진 임계값(출력이 이미 이진이 아닌 경우)을 수락하고 두 개의 새 키를 생성합니다. 이진화 임계값의 경우 기본값이 제공되며, 사용자가 이를 재정의할 수 있습니다. 두 개의 새 키는 다음과 같습니다.
-
{metric_name}_result: 이진화 임계값을 기반으로 하는 "pass" 또는 "fail" 문자열입니다. -
{metric_name}_threshold: 기본적으로 또는 사용자가 설정한 숫자 이진화 임계값입니다.
일부 평가자에 대한 다음 예제 출력을 참조하세요.
{
"intent_resolution": 5.0, # likert scale: 1-5 integer
"intent_resolution_threshold": 3,
"intent_resolution_result": "pass", # pass because 5 > 3 the threshold
"intent_resolution_reason": "The assistant correctly understood the user's request to fetch the weather in Seattle. It used the appropriate tool to get the weather information and provided a clear and accurate response with the current weather conditions in Seattle. The response fully resolves the user's query with all necessary information."
}
{
"task_adherence": 5.0, # likert scale: 1-5 integer
"task_adherence_threshold": 3,
"task_adherence_result": "pass", # pass because 5 > 3 the threshold
"task_adherence_reason": "The response accurately follows the instructions, fetches the correct weather information, and relays it back to the user without any errors or omissions."
}
{
"tool_call_accuracy": 5, # a score between 1-5, higher is better
"tool_call_accuracy_threshold": 3,
"tool_call_accuracy_result": "pass", # pass because 5 > 3 the threshold
"details": { ... } # helpful details for debugging the tool calls made by the agent
}
여러 에이전트 실행 또는 스레드를 평가하다
여러 에이전트 실행 또는 스레드를 평가하려면 비동기 평가에 일괄 처리 evaluate() API를 사용합니다. 먼저 변환기 지원을 사용하여 에이전트 스레드 데이터를 파일로 변환합니다.
import json
from azure.ai.evaluation import AIAgentConverter
# Initialize the converter.
converter = AIAgentConverter(project_client)
# Specify a file path to save the agent output (evaluation input data) to.
filename = os.path.join(os.getcwd(), "evaluation_input_data.jsonl")
evaluation_data = converter.prepare_evaluation_data(thread_ids=thread_id, filename=filename)
print(f"Evaluation data saved to {filename}")
한 줄의 코드로 준비된 평가 데이터를 사용하여 평가자를 선택하여 에이전트 품질을 평가하고 일괄 처리 평가 실행을 제출할 수 있습니다. 다음 예제에서는 단일 에이전트 실행quality_and_safety_evaluators 평가 섹션에서 동일한 품질 및 안전 평가자 목록을 참조합니다.
import os
from dotenv import load_dotenv
load_dotenv()
# Batch evaluation API (local):
from azure.ai.evaluation import evaluate
response = evaluate(
data=filename,
evaluation_name="agent demo - batch run",
evaluators=quality_and_safety_evaluators,
# optionally, log your results to your Foundry project for rich visualization
azure_ai_project=os.environ.get("AZURE_AI_PROJECT"), # example: https://your-account.services.ai.azure.com/api/projects/your-project
)
# Inspect the average scores at a high level.
print(response["metrics"])
# Use the URL to inspect the results on the UI.
print(f'Foundry URL: {response.get("studio_url")}')
URL을 선택하면 Foundry로 리디렉션됩니다. Foundry 프로젝트에서 평가 결과를 보고 애플리케이션을 디버그합니다. 애플리케이션의 품질 및 안전성 성능을 평가하기 위해 이유 필드와 합격/불합격 결과를 사용합니다. 여러 실행을 실행하고 비교하여 회귀 또는 개선 사항을 테스트할 수 있습니다.
Azure AI Evaluation SDK 클라이언트 라이브러리를 사용하여 변환기 지원을 통해 Microsoft Foundry 에이전트를 평가하여 에이전트 워크플로에 대한 가시성과 투명성을 지원합니다.
에이전트 계산기 및 RAG 계산기에서 평가자를 사용하여 Foundry 에이전트 를 원활하게 평가할 수 있습니다. 이 섹션에서는 에이전트를 만들고 평가하는 단계를 안내합니다.
비고
다른 스키마를 출력하는 다른 에이전트를 빌드하는 경우 일반 OpenAI 스타일 에이전트 메시지 스키마 로 변환하고 이전 평가자를 사용합니다. 일반적으로 에이전트 메시지를 필요한 데이터 형식으로 구문 분석할 수 있는 경우 모든 평가자를 사용할 수도 있습니다.
필수 조건
import json
from azure.ai.projects.models import Tool, FunctionTool
# Define a function tool for the model to use
func_tool = fetch_weather(
name="fetch_weather",
parameters={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The location to fetch weather for.",
},
},
"required": ["location"],
"additionalProperties": False,
},
description="Get the current weather for a location.",
strict=True,
)
tools: list[Tool] = [func_tool]
# Define a custom Python function.
async def fetch_weather(location: str) -> str:
"""
Fetches the weather information for the specified location.
:param location (str): The location to fetch weather for.
:return: Weather information as a JSON string.
:rtype: str
"""
# In a real-world scenario, you'd integrate with a weather API.
# In the following code snippet, we mock the response.
mock_weather_data = {"Seattle": "Sunny, 25°C", "London": "Cloudy, 18°C", "Tokyo": "Rainy, 22°C"}
weather = mock_weather_data.get(location, "Weather data not available for this location.")
weather_json = json.dumps({"weather": weather})
return weather_json
도구 집합을 사용하여 에이전트를 설정하고 평가할 응답 실행을 만듭니다.
다음과 같이 도구 집합을 사용하여 에이전트를 만듭니다.
import os
import json
from dotenv import load_dotenv
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition
from azure.identity import DefaultAzureCredential
from openai.types.responses.response_input_param import FunctionCallOutput, ResponseInputParam
credential = DefaultAzureCredential()
project_client = AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=DefaultAzureCredential(),
)
with project_client:
openai_client = project_client.get_openai_client()
agent = await project_client.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
instructions="You are a helpful assistant that can use function tools.",
tools=tools,
),
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
conversation = openai_client.conversations.create(
items=[{"type": "message", "role": "user", "content": "What is the weather in Seattle?"}],
)
print(f"Created conversation with initial user message (id: {conversation.id})")
response = openai_client.responses.create(
conversation=conversation.id,
extra_body={"agent": {"name": agent.name, "type": "agent_reference"}},
)
print(f"Response output: {response.output_text} (id: {response.id})")
# Now create evaluation for the response
data_source_config = {"type": "azure_ai_source", "scenario": "responses"}
# add your desired evaluators here
testing_criteria = [
{"type": "azure_ai_evaluator", "name": "task_adherence", "evaluator_name": "builtin.task_adherence"},
{"type": "azure_ai_evaluator", "name": "groundedness", "evaluator_name": "builtin.groundedness"},
]
eval_object = openai_client.evals.create(
name="Agent Response Evaluation",
data_source_config=data_source_config,
testing_criteria=testing_criteria,
)
print(f"Evaluation created (id: {eval_object.id}, name: {eval_object.name})")
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": response.id}}]},
},
}
response_eval_run = openai_client.evals.runs.create(
eval_id=eval_object.id, name=f"Evaluation Run for Agent {agent.name}", data_source=data_source
)
print(f"Evaluation run created (id: {response_eval_run.id})")
while response_eval_run.status not in ["completed", "failed"]:
response_eval_run = openai_client.evals.runs.retrieve(run_id=response_eval_run.id, eval_id=eval_object.id)
print(f"Waiting for eval run to complete... current status: {response_eval_run.status}")
time.sleep(5)
if response_eval_run.status == "completed":
print("\n✓ Evaluation run completed successfully!")
print(f"Result Counts: {response_eval_run.result_counts}")
print(f"Eval Run Report URL: {response_eval_run.report_url}")
output_items = list(
openai_client.evals.runs.output_items.list(run_id=response_eval_run.id, eval_id=eval_object.id)
)
print(f"\nOUTPUT ITEMS (Total: {len(output_items)})")
print(f"{'-'*60}")
pprint(output_items)
print(f"{'-'*60}")
else:
print("\n✗ Evaluation run failed.")
결과 해석
단일 데이터 예제의 경우 모든 평가자는 항상 다음 스키마를 출력합니다.
- 레이블: 단위 테스트의 출력과 유사한 이진 "pass" 또는 "fail" 레이블입니다. 이 결과를 사용하여 평가자 간 비교를 용이하게 합니다.
- 점수: 각 평가자의 자연 눈금에서의 점수입니다. 일부 평가자는 세분화된 루브릭을 사용하여 5포인트 배율(품질 평가자) 또는 7포인트 배율(콘텐츠 안전 평가자)에서 점수를 매깁니다. 텍스트 유사성 평가기와 같은 다른 항목은 0에서 1 사이의 부동 소수점인 F1 점수를 사용합니다. "label" 필드는 "threshold"를 기준으로 비이진 "score"를 "pass" 또는 "fail"로 이진화합니다.
- 임계값: 이진 점수가 아닌 점수는 SDK 환경에서 재정의할 수 있는 기본 임계값에 따라 "통과" 또는 "실패"로 이진화됩니다.
- 이유: 지능성을 향상시키기 위해 모든 LLM-판사 평가자는 특정 점수가 지정된 이유를 설명하는 추론 필드를 출력합니다.
- 세부 정보: (선택 사항) tool_call_accuracy 같은 일부 평가자의 경우 사용자가 애플리케이션을 디버그하는 데 도움이 되는 추가 정보가 포함된 "세부 정보" 필드 또는 플래그가 있을 수 있습니다. 여러 데이터 예제(데이터 세트)에 대한 집계 결과의 경우 "통과"가 있는 예제의 평균 속도는 해당 데이터 세트에 대한 전달 속도를 형성합니다.
URL 이후에 Foundry로 리디렉션됩니다. Foundry 프로젝트에서 평가 결과를 보고 애플리케이션을 디버그할 수 있습니다. "이유" 필드를 사용하고 통과/실패하여 애플리케이션의 품질 및 안전성 성능을 평가합니다. 여러 실행을 실행하고 비교하여 회귀 또는 개선 사항을 테스트할 수 있습니다.
Microsoft Foundry SDK Python 클라이언트 라이브러리를 사용하여 Microsoft Foundry 에이전트를 평가하여 에이전트 워크플로의 가시성과 투명성을 지원합니다.
다른 에이전트를 평가
에이전트 서비스 외부에서 에이전트를 사용하는 경우에도 선택한 평가자에 적합한 데이터를 준비하여 평가할 수 있습니다.
에이전트는 일반적으로 사용자 또는 다른 에이전트와 상호 작용하기 위해 메시지를 내보낸다. 기본 제공 평가자는 query 따라 문자열responseground_truth과 같은 간단한 데이터 형식을 허용합니다. 그러나 에이전트의 복잡한 상호 작용 패턴과 프레임워크 차이로 인해 에이전트 메시지에서 이러한 간단한 데이터 형식을 추출하는 것은 어려울 수 있습니다. 예를 들어 단일 사용자 쿼리는 일반적으로 여러 도구 호출이 호출된 긴 에이전트 메시지 목록을 트리거할 수 있습니다.
에이전트는 일반적으로 사용자 또는 다른 에이전트와 상호 작용하기 위해 메시지를 내보낸다. 기본 제공 평가자는 단일 턴 데이터 입력 요구 사항에 따라 문자열 queryresponseground_truth 과 같은 간단한 데이터 형식을 허용할 수 있습니다. 그러나 에이전트의 복잡한 상호 작용 패턴과 프레임워크 차이로 인해 에이전트 메시지에서 이러한 간단한 데이터 형식을 추출하는 것은 어려울 수 있습니다. 예를 들어 단일 사용자 쿼리는 일반적으로 여러 도구 호출이 호출된 긴 에이전트 메시지 목록을 트리거할 수 있습니다. 에이전트 메시지 스키마 내의 예제들은 에이전트 메시지 스키마로, tool_definitions와 tool_calls가 query와 response에 포함되어 있는 형태로 보여줍니다.
다음 예제에 설명된 것처럼 다음 기본 제공 평가자에 대한 에이전트 메시지 지원을 사용하여 에이전트 워크플로의 이러한 측면을 평가할 수 있습니다. 이 평가자들은 에이전트를 평가할 때 에이전트에 특정한 매개변수인 tool_calls 또는 tool_definitions을 사용할 수 있습니다.
| 평가기 | query |
response |
tool_calls |
tool_definitions |
|---|---|---|---|---|
IntentResolutionEvaluator |
필수: Union[str, list[Message]] |
필수: Union[str, list[Message]] |
적용되지 않음 | 선택적: list[ToolCall] |
ToolCallAccuracyEvaluator |
필수: Union[str, list[Message]] |
선택적: Union[str, list[Message]] |
선택적: Union[dict, list[ToolCall]] |
필수: list[ToolDefinition] |
TaskAdherenceEvaluator |
필수: Union[str, list[Message]] |
필수: Union[str, list[Message]] |
적용되지 않음 | 선택적: list[ToolCall] |
GroundednessEvaluator |
필수: Union[str, list[Message]] |
필수: Union[str, list[Message]] |
적용되지 않음 | 필수: list[ToolCall] |
-
Message:dict사용자와의 에이전트 상호 작용을 설명하는 OpenAI 스타일 메시지입니다. 여기서query시스템 메시지를 첫 번째 메시지로 포함해야 합니다. -
ToolCall:dict사용자와의 에이전트 상호 작용 중에 호출되는 도구 호출을 지정합니다. -
ToolDefinition:dict에이전트에서 사용할 수 있는 도구를 설명합니다.
ToolCallAccuracyEvaluator의 경우 response 또는 tool_calls 중 하나를 제공해야 합니다.
GroundednessEvaluator는 tool_definitions 에이전트가 도구 출력과 관련하여 받는 응답의 합리성을 평가하도록 요구합니다.
다음 예제에서는 간단한 에이전트 데이터와 에이전트 메시지의 두 가지 데이터 형식을 보여 줍니다. 그러나 이러한 평가자의 고유한 요구 사항으로 인해 각 평가자에 대해 가능한 입력 경로를 보여 주기 위해 샘플 Notebook을 참조하는 것이 좋습니다.
모든 기본 제공 AI 지원 품질 평가기는 각 입력에 대한 통과 또는 실패를 출력합니다.
간단한 에이전트 데이터
간단한 에이전트 데이터 형식 query 이며 response 간단한 Python 문자열입니다. 다음은 그 예입니다.
import os
import json
from azure.ai.evaluation import AzureOpenAIModelConfiguration
from azure.identity import DefaultAzureCredential
from azure.ai.evaluation import IntentResolutionEvaluator, ResponseCompletenessEvaluator
model_config = AzureOpenAIModelConfiguration(
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
api_key=os.environ["AZURE_OPENAI_API_KEY"],
api_version=os.environ["AZURE_OPENAI_API_VERSION"],
azure_deployment=os.environ["MODEL_DEPLOYMENT_NAME"],
)
intent_resolution_evaluator = IntentResolutionEvaluator(model_config)
# Evaluate the query and response as strings.
# The following is a positive example. Intent is identified and understood and the response correctly resolves user intent.
result = intent_resolution_evaluator(
query="What are the opening hours of the Eiffel Tower?",
response="Opening hours of the Eiffel Tower are 9:00 AM to 11:00 PM.",
)
print(json.dumps(result, indent=4))
다음 출력을 참조하세요(자세한 내용은 출력 형식 참조).
{
"intent_resolution": 5.0,
"intent_resolution_result": "pass",
"intent_resolution_threshold": 3,
"intent_resolution_reason": "The response provides the opening hours of the Eiffel Tower, which directly addresses the user's query. The information is clear, accurate, and complete, fully resolving the user's intent.",
}
에이전트 도구 호출 및 정의
tool_calls의 tool_definitions 및 ToolCallAccuracyEvaluator 예제를 참조하세요.
import json
query = "How is the weather in Seattle?"
tool_calls = [{
"type": "tool_call",
"tool_call_id": "call_CUdbkBfvVBla2YP3p24uhElJ",
"name": "fetch_weather",
"arguments": {
"location": "Seattle"
}
},
{
"type": "tool_call",
"tool_call_id": "call_CUdbkBfvVBla2YP3p24uhElJ",
"name": "fetch_weather",
"arguments": {
"location": "London"
}
}]
tool_definitions = [{
"name": "fetch_weather",
"description": "Fetches the weather information for the specified location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The location to fetch weather for."
}
}
}
}]
from azure.ai.evaluation import ToolCallAccuracyEvaluator
tool_call_accuracy = ToolCallAccuracyEvaluator(model_config) # reuse the config defined above
response = tool_call_accuracy(query=query, tool_calls=tool_calls, tool_definitions=tool_definitions)
print(json.dumps(response, indent=4))
다음 출력을 참조하세요(자세한 내용은 출력 형식 참조).
{
"tool_call_accuracy": 3, # a score between 1-5, higher is better
"tool_call_accuracy_result": "fail",
"tool_call_accuracy_threshold": 4,
"details": { ... } # helpful details for debugging the tool calls made by the agent
}
tool_calls의 tool_definitions 및 tool_call_accuracy 예제를 참조하세요.
import json
query = "How is the weather in Seattle?"
tool_calls = [{
"type": "tool_call",
"tool_call_id": "call_CUdbkBfvVBla2YP3p24uhElJ",
"name": "fetch_weather",
"arguments": {
"location": "Seattle"
}
},
{
"type": "tool_call",
"tool_call_id": "call_CUdbkBfvVBla2YP3p24uhElJ",
"name": "fetch_weather",
"arguments": {
"location": "London"
}
}]
tool_definitions = [{
"name": "fetch_weather",
"description": "Fetches the weather information for the specified location.",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The location to fetch weather for."
}
}
}
}]
에이전트 메시지 스키마
에이전트 메시지 형식 query 이며 response OpenAI 스타일 메시지 목록입니다. 특히 query 마지막 사용자 쿼리로 이어지는 과거 에이전트-사용자 상호 작용을 전달하고 목록 맨 위에 있는 에이전트의 시스템 메시지가 필요합니다.
response 는 마지막 사용자 쿼리에 대한 응답으로 에이전트의 마지막 메시지를 전달합니다.
평가자에 대한 예상 입력 형식은 다음과 같은 Python 메시지 목록입니다.
[
{
"role": "system" | "user" | "assistant" | "tool",
"createdAt": "ISO 8601 timestamp", // Optional for 'system'
"run_id": "string", // Optional, only for assistant/tool in tool call context
"tool_call_id": "string", // Optional, only for tool/tool_result
"name": "string", // Present if it's a tool call
"arguments": { ... }, // Parameters passed to the tool (if tool call)
"content": [
{
"type": "text" | "tool_call" | "tool_result",
"text": "string", // if type == text
"tool_call_id": "string", // if type == tool_call
"name": "string", // tool name if type == tool_call
"arguments": { ... }, // tool args if type == tool_call
"tool_result": { ... } // result if type == tool_result
}
]
}
]
샘플 쿼리 및 응답 개체:
query = [
{
"role": "system",
"content": "You are an AI assistant interacting with Azure Maps services to serve user requests."
},
{
"createdAt": "2025-04-25T23:55:43Z",
"role": "user",
"content": [
{
"type": "text",
"text": "Find the address for coordinates 41.8781,-87.6298."
}
]
},
{
"createdAt": "2025-04-25T23:55:45Z",
"run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
"role": "assistant",
"content": [
{
"type": "tool_call",
"tool_call_id": "call_nqNyhOFRw4FmF50jaCCq2rDa",
"name": "azure_maps_reverse_address_search",
"arguments": {
"lat": "41.8781",
"lon": "-87.6298"
}
}
]
},
{
"createdAt": "2025-04-25T23:55:47Z",
"run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
"tool_call_id": "call_nqNyhOFRw4FmF50jaCCq2rDa",
"role": "tool",
"content": [
{
"type": "tool_result",
"tool_result": {
"address": "300 South Federal Street, Chicago, IL 60604",
"position": {
"lat": "41.8781",
"lon": "-87.6298"
}
}
}
]
},
{
"createdAt": "2025-04-25T23:55:48Z",
"run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
"role": "assistant",
"content": [
{
"type": "text",
"text": "The address for the coordinates 41.8781, -87.6298 is 300 South Federal Street, Chicago, IL 60604."
}
]
},
{
"createdAt": "2025-04-25T23:55:50Z",
"role": "user",
"content": [
{
"type": "text",
"text": "What timezone corresponds to 41.8781,-87.6298?"
}
]
},
]
response = [
{
"createdAt": "2025-04-25T23:55:52Z",
"run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
"role": "assistant",
"content": [
{
"type": "tool_call",
"tool_call_id": "call_qi2ug31JqzDuLy7zF5uiMbGU",
"name": "azure_maps_timezone",
"arguments": {
"lat": 41.878100000000003,
"lon": -87.629800000000003
}
}
]
},
{
"createdAt": "2025-04-25T23:55:54Z",
"run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
"tool_call_id": "call_qi2ug31JqzDuLy7zF5uiMbGU",
"role": "tool",
"content": [
{
"type": "tool_result",
"tool_result": {
"ianaId": "America/Chicago",
"utcOffset": None,
"abbreviation": None,
"isDaylightSavingTime": None
}
}
]
},
{
"createdAt": "2025-04-25T23:55:55Z",
"run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
"role": "assistant",
"content": [
{
"type": "text",
"text": "The timezone for the coordinates 41.8781, -87.6298 is America/Chicago."
}
]
}
]
비고
평가기는 쿼리(현재 실행까지의 대화 기록) 또는 에이전트 응답(쿼리에 대한 응답)이 예상 형식이 아닌 경우 경고를 표시합니다.
다음과 같이 ToolCallAccuracyEvaluator를 사용하여 에이전트 메시지를 평가하는 예제를 참조하세요.
import json
# The user asked a question.
query = [
{
"role": "system",
"content": "You are a friendly and helpful customer service agent."
},
# Past interactions are omitted.
# ...
{
"createdAt": "2025-03-14T06:14:20Z",
"role": "user",
"content": [
{
"type": "text",
"text": "Hi, I need help with the last 2 orders on my account #888. Could you please update me on their status?"
}
]
}
]
# The agent emits multiple messages to fulfill the request.
response = [
{
"createdAt": "2025-03-14T06:14:30Z",
"run_id": "0",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello! Let me quickly look up your account details."
}
]
},
{
"createdAt": "2025-03-14T06:14:35Z",
"run_id": "0",
"role": "assistant",
"content": [
{
"type": "tool_call",
"tool_call_id": "tool_call_20250310_001",
"name": "get_orders",
"arguments": {
"account_number": "888"
}
}
]
},
# Many more messages are omitted.
# ...
# Here is the agent's final response:
{
"createdAt": "2025-03-14T06:15:05Z",
"run_id": "0",
"role": "assistant",
"content": [
{
"type": "text",
"text": "The order with ID 123 has been shipped and is expected to be delivered on March 15, 2025. However, the order with ID 124 is delayed and should now arrive by March 20, 2025. Is there anything else I can help you with?"
}
]
}
]
# An example of tool definitions available to the agent:
tool_definitions = [
{
"name": "get_orders",
"description": "Get the list of orders for a given account number.",
"parameters": {
"type": "object",
"properties": {
"account_number": {
"type": "string",
"description": "The account number to get the orders for."
}
}
}
},
# Other tool definitions are omitted.
# ...
]
result = tool_call_accuracy(
query=query,
response=response,
tool_definitions=tool_definitions
)
print(json.dumps(result, indent=4))
다음 출력을 참조하세요(자세한 내용은 출력 형식 참조).
{
"tool_call_accuracy": 2, # a score between 1-5, higher is better
"tool_call_accuracy_result": "fail",
"tool_call_accuracy_threshold": 3,
"details": { ... } # helpful details for debugging the tool calls made by the agent
}
query = [
{
"role": "system",
"content": "You are an AI assistant interacting with Azure Maps services to serve user requests."
},
{
"createdAt": "2025-04-25T23:55:43Z",
"role": "user",
"content": [
{
"type": "text",
"text": "Find the address for coordinates 41.8781,-87.6298."
}
]
},
{
"createdAt": "2025-04-25T23:55:45Z",
"run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
"role": "assistant",
"content": [
{
"type": "tool_call",
"tool_call_id": "call_nqNyhOFRw4FmF50jaCCq2rDa",
"name": "azure_maps_reverse_address_search",
"arguments": {
"lat": "41.8781",
"lon": "-87.6298"
}
}
]
},
{
"createdAt": "2025-04-25T23:55:47Z",
"run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
"tool_call_id": "call_nqNyhOFRw4FmF50jaCCq2rDa",
"role": "tool",
"content": [
{
"type": "tool_result",
"tool_result": {
"address": "300 South Federal Street, Chicago, IL 60604",
"position": {
"lat": "41.8781",
"lon": "-87.6298"
}
}
}
]
},
{
"createdAt": "2025-04-25T23:55:48Z",
"run_id": "run_DGE8RWPS8A9SmfCg61waRx9u",
"role": "assistant",
"content": [
{
"type": "text",
"text": "The address for the coordinates 41.8781, -87.6298 is 300 South Federal Street, Chicago, IL 60604."
}
]
},
{
"createdAt": "2025-04-25T23:55:50Z",
"role": "user",
"content": [
{
"type": "text",
"text": "What timezone corresponds to 41.8781,-87.6298?"
}
]
},
]
response = [
{
"createdAt": "2025-04-25T23:55:52Z",
"run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
"role": "assistant",
"content": [
{
"type": "tool_call",
"tool_call_id": "call_qi2ug31JqzDuLy7zF5uiMbGU",
"name": "azure_maps_timezone",
"arguments": {
"lat": 41.878100000000003,
"lon": -87.629800000000003
}
}
]
},
{
"createdAt": "2025-04-25T23:55:54Z",
"run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
"tool_call_id": "call_qi2ug31JqzDuLy7zF5uiMbGU",
"role": "tool",
"content": [
{
"type": "tool_result",
"tool_result": {
"ianaId": "America/Chicago",
"utcOffset": None,
"abbreviation": None,
"isDaylightSavingTime": None
}
}
]
},
{
"createdAt": "2025-04-25T23:55:55Z",
"run_id": "run_DmnhUGqYd1vCBolcjjODVitB",
"role": "assistant",
"content": [
{
"type": "text",
"text": "The timezone for the coordinates 41.8781, -87.6298 is America/Chicago."
}
]
}
]
비고
평가자는 쿼리(현재 실행까지의 대화 기록)나 에이전트 응답(쿼리에 대한 응답)의 형식이 예상된 형식이 아닐 때 이를 구문 분석할 수 없다고 경고를 발생시킵니다.
에이전트 메시지의 추가 예:
import json
# The user asked a question.
query = [
{
"role": "system",
"content": "You are a friendly and helpful customer service agent."
},
# Past interactions are omitted.
# ...
{
"createdAt": "2025-03-14T06:14:20Z",
"role": "user",
"content": [
{
"type": "text",
"text": "Hi, I need help with the last 2 orders on my account #888. Could you please update me on their status?"
}
]
}
]
# The agent emits multiple messages to fulfill the request.
response = [
{
"createdAt": "2025-03-14T06:14:30Z",
"run_id": "0",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello! Let me quickly look up your account details."
}
]
},
{
"createdAt": "2025-03-14T06:14:35Z",
"run_id": "0",
"role": "assistant",
"content": [
{
"type": "tool_call",
"tool_call_id": "tool_call_20250310_001",
"name": "get_orders",
"arguments": {
"account_number": "888"
}
}
]
},
# Many more messages are omitted.
# ...
# Here is the agent's final response:
{
"createdAt": "2025-03-14T06:15:05Z",
"run_id": "0",
"role": "assistant",
"content": [
{
"type": "text",
"text": "The order with ID 123 has been shipped and is expected to be delivered on March 15, 2025. However, the order with ID 124 is delayed and should now arrive by March 20, 2025. Is there anything else I can help you with?"
}
]
}
]
# An example of tool definitions available to the agent:
tool_definitions = [
{
"name": "get_orders",
"description": "Get the list of orders for a given account number.",
"parameters": {
"type": "object",
"properties": {
"account_number": {
"type": "string",
"description": "The account number to get the orders for."
}
}
}
},
# Other tool definitions are omitted.
# ...
]
이 평가 스키마는 에이전트 서비스 외부에서 에이전트 데이터를 구문 분석하는 데 도움이 되며, 기본 제공 평가기를 사용하여 에이전트 워크플로의 관찰 가능성을 지원할 수 있습니다.
샘플 Notebook
각 평가자에 대한 샘플을 사용해 보세요.
샘플 리포지토리에서 이러한 각 평가자에 대한 샘플을 사용해 보세요.