你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 Microsoft Foundry SDK 在云中运行评估

重要

本文中标记为(预览)的项目目前以公共预览版提供。 此预览版在没有服务级别协议的情况下提供,不建议将其用于生产工作负荷。 某些功能可能不受支持,或者可能具有受限功能。 有关详细信息,请参阅 Microsoft Azure 预览版的使用条款

本文介绍如何在云中运行评估(预览版),以便在测试数据集上进行预部署测试。

对大多数方案使用云评估,尤其是在大规模测试时,将评估集成到持续集成和持续交付(CI/CD)管道中,或执行预部署测试。 在云中运行评估无需管理本地计算基础结构并支持大规模自动化测试工作流。 还可以计划定期运行的 评估 ,或设置 持续评估 以自动评估生产中的采样代理响应。

云评估结果存储在 Foundry 项目中。 可以在门户中查看结果、通过 SDK 检索结果,或将其路由到 Application Insights(如果已连接)。 云评估支持所有由微软策划的内置评估器和你自己的 自定义评估器。 在具有相同项目范围的基于角色的访问控制的评估器目录中,评估器进行管理。

提示

有关完整的可运行示例,请参阅 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_modelazure_ai_agent
红队评估 针对模型或代理运行自动对抗测试。 azure_ai_red_team azure_ai_modelazure_ai_agent

大多数方案都需要输入数据。 可以通过两种方式提供数据:

源类型 描述
file_id 按 ID 引用上传的数据集。
file_content 在请求中提供内联数据。

每个评估都需要一个 data_source_config 指示服务在数据中预期哪些字段:

  • custom — 通过字段名称和类型定义一个 item_schema 。 当使用目标时,设置include_sample_schematrue,以便评估者可以引用生成的响应。
  • azure_ai_source — 从服务推断架构。 设置"scenario""responses"代理响应评估,"traces"跟踪评估"synthetic_data_gen_preview"综合数据评估(预览版),或"red_team"红队测试

每个场景都需要评估者来定义您的测试标准。 有关选择评估器的指导,请参阅 内置评估器

先决条件

  • Foundry 项目
  • 具有支持聊天完成的 GPT 模型的 Azure OpenAI 部署(例如,gpt-5-mini)。
  • Azure AI 用户 Foundry 项目中的角色。
  • (可选)可以使用 自己的存储帐户 来运行评估。

注意

某些评估功能具有区域限制。 有关详细信息 ,请参阅支持的区域

开始

安装 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 工作流。

准备一个 JSONL 文件,每行包含一个 JSON 对象和评估者所需的字段:

{"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 文件中的预计算响应。 此方案的工作方式与 数据集评估 相同,但接受 CSV 文件而不是 JSONL。 如果数据已采用电子表格或表格格式,请使用 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}} 代理的纯文本响应。 需要字符串响应的评估器(例如,coherenceviolence)。
{{sample.output_items}} 代理的结构化 JSON 输出,包括工具调用。 需要完全交互上下文(例如,task_adherence)的评估器。
{{item.field}} 输入数据中的字段。 输入字段,例如 queryground_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 作为文件内容内联提供,或作为数据集上传(请参阅 准备输入数据)。

收集响应标识符

每次调用响应 API 都会返回一个具有唯 id 一字段的响应对象。 从应用程序的交互中收集这些 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 语义约定向 Application Insights 发出 OpenTelemetry 范围 ,跟踪评估就可以使用可用于 Foundry 代理的相同评估程序评估其交互。

跟踪评估支持两种模式:

  • 通过跟踪 ID — 提供来自 Application Insights 的 operation_Id 值以评估特定代理的交互。
  • 依据代理过滤器 - 自动发现和评估给定代理的最新跟踪,无需手动收集跟踪 ID。

提示

在开始之前,请完成 入门。 此方案还需要 Application Insights 资源连接到 Foundry 项目

跟踪数据要求

跟踪评估要求代理按照 生成 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 数组。 具有角色 usersystem 的消息映射到 query;具有角色 assistanttool 的消息映射到 response
gen_ai.output.messages 对于评估者的查询输入 模型生成的输出消息的 JSON 数组。 所有输出消息都映射到 response。 如果输出还包含类型:tool_call 或类型:tool_result,则该输出映射到 tool_calls
gen_ai.tool.definitions 可选的 代理可用的工具架构的 JSON 数组。 如果不存在,服务会尝试从工具调用消息推断工具定义,但推断的架构可能不完整。
gen_ai.conversation.id 可选 会话标识符,传递给评估结果以用于关联。

注意

如果 gen_ai.input.messagesgen_ai.output.messages 为空或缺失,则质量评估程序(一致性、流畅性、相关性、意向解决)将返回 score=None。 安全评估者(暴力、自我伤害、性、仇恨/不公平)仍然可以产生分数和部分数据,但它们可能不会产生有意义的结果。

对于使用 Azure AI Agent Server SDK 生成的Python代理,请添加 [tracing] 额外功能以启用自动跨度排放:

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

跟踪评估的先决条件

除了常规 先决条件之外,跟踪评估还需要:

  • 与您的 Foundry 项目连接的 Application Insights 资源 。 请参阅 在 Microsoft Foundry 中设置跟踪
  • 项目的托管标识必须在 Application Insights 资源及其链接 Log Analytics 工作区上具有 Log Analytics Reader 角色。
  • 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}")

服务根据gen_ai.agent.id属性筛选跨度,对最多max_traces个唯一的跟踪 ID 进行采样,并评估来自这些跟踪的所有跨度。

选项 B:按跟踪 ID 进行评估

有关更多控制措施,请从 Application Insights 收集特定的跟踪 ID 并对其进行评估。 如果您想评估一组精心挑选的交互(例如,由警报标记的踪迹或用于质量评审的采样),这将非常有用。

从 Application Insights 收集跟踪 ID

在 Application Insights 中查询 operation_Id 代理跟踪中的值。 每个 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 范围属性中提取会话数据。 在 data_mapping 中直接使用这些字段名称(不使用在其他方案中使用的 item.sample. 前缀):

变量 源属性 描述
{{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,
)

若要轮询完成结果和解释结果,请参阅 “获取结果”。 响应包含一个 output_dataset_id 属性,其中包含生成的数据集的 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}")

解释结果

对于单个数据示例,所有计算器都输出以下架构:

  • 标签:二元“通过”或“失败”标签,类似于单元测试的输出。 使用此结果可促进评估器之间的比较。
  • 评分:每个评估者的自然尺度的分数。 一些评估者使用细粒度的标尺,在 5 分级(质量评估器)或 7 分级(内容安全评估器)评分。 其他(如文本相似性计算器)使用 F1 分数,这些分数在 0 和 1 之间浮动。 任何非二进制的“得分”将根据“阈值”被二值化为“通过”或“失败”,并填写在“标签”字段中。
  • 阈值:任何非二进制分数将根据默认阈值被二元化为“通过”或“失败”,用户可以在 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 Unauthorized错误或403 Forbidden错误,请验证:

  • DefaultAzureCredential 已正确配置(如果使用 Azure CLI,请运行 az login)。
  • 你的帐户在 Foundry 项目中具有 Azure AI User 角色。
  • 项目终结点 URL 正确,包括帐户和项目名称。

数据格式错误

如果评估失败并出现架构或数据映射错误:

  • 验证 JSONL 文件是否每行有一个有效的 JSON 对象。
  • 确认 JSONL 文件中的字段名称与字段名称 data_mapping 完全匹配(区分大小写)。
  • 检查属性是否 item_schema 与数据集中的字段匹配。

速率限制错误

评估运行创建在租户、订阅和项目级别受到速率限制。 如果您收到 429 Too Many Requests 响应:

  • 检查 retry-after 响应中的标头,了解建议的等待时间。
  • 查看响应正文以了解速率限制详细信息。
  • 重试失败的请求时,请使用指数退避。

如果在执行过程中评估作业失败并出现 429 错误:

  • 减小评估数据集的大小,或将其拆分为较小的批处理。
  • 在 Azure 门户中增加模型部署的每分钟令牌(TPM)配额。

代理评估工具错误

如果代理评估器返回关于不受支持工具的错误:

  • 检查代理评估员 支持的工具
  • 解决方法是,将不受支持的工具包装为用户定义的函数工具,以便计算器可以评估它们。