你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
Important
本文中标记为预览的项目目前为预览版。 此预览版在没有服务级别协议的情况下提供,Microsoft不建议将其用于生产工作负荷。 某些功能可能不受支持,或者可能具有受限功能。 有关详细信息,请参阅 Microsoft Azure 预览版补充使用条款。
评估已部署代理和模型的存储响应或 OpenTelemetry 跟踪,而无需重播原始请求。
先决条件
- 完成 云评估先决条件 和 客户端设置。
- 响应评估的已存储响应 ID,或连接到 Foundry 项目、用于跟踪评估的 Application Insights 资源。
- OpenTelemetry 在评估跟踪时满足跟踪数据要求。
这些示例使用在 设置 SDK 客户端中配置的 SDK 客户端。
按响应 ID 评估交互
使用 azure_ai_responses 数据源类型按响应 ID 检索和评估 Foundry 代理响应。 使用此方案评估发生特定代理交互后的情况。
提示
在开始之前,请完成 客户端设置。
响应 ID 是每次 Foundry 代理生成响应时返回的唯一标识符。 可以使用 响应 API 或应用程序的跟踪日志从代理交互收集响应 ID。 以内联方式提供 ID 作为文件内容。
Important
代理响应评估(azure_ai_responses)仅支持使用 file_content 提供响应 ID。
file_id源类型不受支持,并返回错误400 Bad Request。
收集响应标识符
每次调用响应 API 都会返回一个具有唯 id 一字段的响应对象。 从应用程序的交互中收集这些 ID,或直接生成这些 ID:
# Generate response IDs by calling a model through the Responses API
response = openai_client.responses.create(
model=model_deployment_name,
input="What is machine learning?",
)
print(response.id) # Example: resp_abc123
还可以从应用程序的跟踪日志或监视管道中的代理交互中收集响应 ID。 每个响应 ID 唯一标识评估服务可以检索的存储响应。
创建评估并运行
from azure.ai.projects.models import TestingCriterionAzureAIEvaluator
data_source_config = {"type": "azure_ai_source", "scenario": "responses"}
testing_criteria = [
TestingCriterionAzureAIEvaluator(
type="azure_ai_evaluator",
name="coherence",
evaluator_name="builtin.coherence",
initialization_parameters={"model": model_deployment_name},
),
TestingCriterionAzureAIEvaluator(
type="azure_ai_evaluator",
name="violence",
evaluator_name="builtin.violence",
),
]
eval_object = openai_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 = openai_client.evals.runs.create(
eval_id=eval_object.id,
name="agent-response-evaluation",
data_source=data_source,
)
有关完整的可运行示例,请参阅 GitHub 上的 sample_agent_response_evaluation.py 。 若要轮询完成结果和解释结果,请参阅获取云评估结果。
有关完整的.NET响应评估示例,请参阅 GitHub 上的 Sample7_EvaluationsAgent.md。
评估跟踪
评估 Application Insights 已捕获的智能体交互。 使用 azure_ai_traces 数据源类型。 此方案适用于实际生产流量的部署后评估。 可以从监控管道中选择追踪,并在不重播任何请求的情况下对其运行评估器。
Important
跟踪评估是用于评估未使用 Microsoft Foundry 智能体服务生成的智能体的推荐方法,适用于包括 LangChain 和自定义框架这样的技术。 只要代理按照 GenAI 语义约定向 Application Insights 发出 OpenTelemetry 范围 ,跟踪评估就可以使用适用于 Foundry 代理的相同评估程序来评估其交互。
跟踪评估支持两种模式:
-
通过跟踪 ID - 通过提供从 Application Insights 获取的其
operation_Id值来评估特定的代理交互。 - 按代理筛选 - 自动发现并评估指定代理的最近跟踪,无需手动收集跟踪 ID。
提示
在开始之前,请完成 客户端设置。 在此场景中,还需要一个 连接到 Foundry 项目的 Application Insights 资源。
智能采样
跟踪评估支持智能采样,它选择代表性的跟踪子集进行评估,而不是评估每个捕获的跟踪。 配置跟踪评估运行时,在 Foundry 门户中打开智能采样开关。 智能采样可降低评估成本,同时保留跟踪多样性 - 确保评估集中包含边缘事例、错误路径和各种聊天模式。
智能采样的工作原理
采样算法采用基于 MinHash 的最远优先多样性方法,分多个阶段运行:
- 精确去重 - 从池中删除重复跟踪。
- 硬筛选器 - 删除中断的会话、截断的跟踪和不适合评估的格式错误的工具调用。
- 聚合 - 将跟踪级信号合并为统一表示形式。
- MinHash 最远优先选择 - 计算用户文本的局部敏感哈希(MinHash 签名),以估计轨迹之间的相似性,然后迭代地从剩余池中选择最不同的轨迹。 每一次后续选择,都会使其与所有先前已选跟踪之间的距离最大化。
与随机采样相比,此方法产生的词法多样性和更广泛的词汇覆盖率明显更高,这意味着评估集更好地表示代理交互的全部范围,包括随机采样往往错过的罕见、硬和新颖的情况。
智能采样特别适用于:
- 评估和基准 - 最大化输入分布的覆盖面,使评估分数反映现实世界的多样性。
- 评分标准生成 - 通过呈现多样化的对话模式,产生更专注和可操作的准则。
- 微调数据集筛选 - 选择有助于模型更高效学习的轨迹。
该算法完全在本地计算上运行,无需额外的 API 调用,因此它不会产生超出评估本身的额外模型推理成本。
智能采样示例
# Eval group for trace-based evaluations
data_source_config = {
"type": "azure_ai_source",
"scenario": "traces",
}
print("Creating trace-based evaluation group")
eval_object = client.evals.create(
name="Trace Evaluation (Agent Smart Filter)",
data_source_config=data_source_config, # type: ignore
testing_criteria=testing_criteria,
)
print(f"Evaluation created (id: {eval_object.id})")
# Compute time window in unix seconds
# Pad end_time by +600s (10 min) to avoid ingestion-delay edge exclusion
now_unix = int(time.time())
end_time = now_unix + 600
start_time = now_unix - (args.lookback_hours * 3600)
# Build trace_source based on mode
trace_source: dict = {
"type": "agent_filter",
"start_time": start_time,
"end_time": end_time,
"max_traces": args.max_traces,
"filter_strategy": "smart_filtering"
}
# Add agent name/version or agent id
trace_source["agent_name"] = agent_name
trace_source["agent_version"] = agent_version
## trace_source["agent_id"] = args.agent_id
data_source = {
"type": "azure_ai_trace_data_source_preview",
"trace_source": trace_source,
}
eval_run = client.evals.runs.create(
eval_id=eval_object.id,
name="trace-evaluation-agent-smart-filter-run",
data_source=data_source, # type: ignore
)
跟踪数据要求
跟踪评估要求你的智能体遵循生成式 AI 的 OpenTelemetry 语义约定发出跨度。 具体而言,评估服务从 Application Insights 读取 invoke_agent 范围 并从其属性中提取会话数据。
使用以下范围属性:
| Attribute | 必需 | Description |
|---|---|---|
gen_ai.operation.name |
Yes | 必须与 "invoke_agent" 相等。 该服务将忽略所有其他范围。 |
gen_ai.agent.id |
在代理过滤器模式中 | 唯一代理标识符(格式: agent-name:version) 。 |
gen_ai.agent.name |
在代理过滤器模式中 | 人工可读代理名称。 |
gen_ai.input.messages |
对于评估程序查询输入 | 遵循 GenAI 语义约定消息格式的输入消息的 JSON 数组。
user 或 system 角色的消息会映射到 query。
assistant 或 tool 角色的消息会映射到 response。 |
gen_ai.output.messages |
对于评估程序查询输入 | 模型生成的输出消息的 JSON 数组。 所有输出消息都映射到 response。 如果输出还包含 type: tool_call 或 type: tool_result映射到 tool_calls。 |
gen_ai.tool.definitions |
Optional | 代理可用的工具架构的 JSON 数组。 如果不存在,服务会尝试从工具调用消息推断工具定义,但推断的架构可能不完整。 |
gen_ai.conversation.id |
Optional | 会话标识符,传递给评估结果以用于关联。 |
注释
如果 gen_ai.input.messages 和 gen_ai.output.messages 为空或缺失,则质量评估器(连贯性、流畅性、相关性、意图解决)会返回 score=None。 安全评估者(暴力,自我伤害,性,仇恨/不公平)仍然可以产生分数与部分数据,但他们可能不会产生有意义的结果。
对于使用 Azure AI 智能体服务器 SDK 构建的 Python 智能体,添加 [tracing] 额外项以启用自动跨度发出:
pip install "azure-ai-agentserver-core[tracing]"
跟踪评估的先决条件
除了常规 先决条件之外,跟踪评估还需要:
- 与您的 Foundry 项目连接的 Application Insights 资源 。 请参阅 在 Microsoft Foundry 中设置跟踪。
- 项目的托管标识必须在 Application Insights 资源上具有 读取者角色。 如果存储跟踪的表受到 保护 (其保护级别设置为 “受保护”),则还会在该资源上分配 特权监视数据读取者 角色。 如果将链接Log Analytics工作区配置为“需要工作区权限”,则也会在工作区上分配Log Analytics读取者。 有关所有跟踪评估角色要求和其他工作区配置,请参阅 设置评估工作流的权限。
-
azure-monitor-queryPython 包(仅当手动收集跟踪 ID 时才需要)。
pip install "azure-ai-projects>=2.2.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 = openai_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 = openai_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个唯一的跟踪 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 = openai_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 = openai_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. 前缀):
| Variable | 源属性 | Description |
|---|---|---|
{{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 |
智能体在交互期间进行的工具调用。 供工具评估者使用。 仅适用于与工具相关的评估程序。 |
from azure.ai.projects.models import TestingCriterionAzureAIEvaluator
testing_criteria = [
# Quality evaluators — require query and response from trace data
TestingCriterionAzureAIEvaluator(
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={"model": model_deployment_name},
),
# Tool evaluators — assess tool usage quality
TestingCriterionAzureAIEvaluator(
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={"model": model_deployment_name},
),
]
使用 .NET 运行跟踪评估
输入要评估的 Application Insights 跟踪 ID。 该服务从连接的 Application Insights 资源检索相应的范围。
string[] traceIds = ["trace-id-1", "trace-id-2"];
object[] testingCriteria =
[
new
{
type = "azure_ai_evaluator",
name = "intent_resolution",
evaluator_name = "builtin.intent_resolution",
initialization_parameters = new { model = modelDeploymentName },
data_mapping = new
{
query = "{{item.query}}",
response = "{{item.response}}",
tool_definitions = "{{item.tool_definitions}}"
}
},
new
{
type = "azure_ai_evaluator",
name = "violence",
evaluator_name = "builtin.violence",
data_mapping = new
{
query = "{{item.query}}",
response = "{{item.response}}"
},
initialization_parameters = new { threshold = 4 }
}
];
BinaryData evaluationData = BinaryData.FromObjectAsJson(new
{
name = "Agent Trace Evaluation",
data_source_config = new
{
type = "azure_ai_source",
scenario = "traces"
},
testing_criteria = testingCriteria
});
using BinaryContent evaluationContent = BinaryContent.Create(evaluationData);
ClientResult evaluation = await evaluationClient.CreateEvaluationAsync(
evaluationContent);
string evaluationId = GetString(evaluation, "id");
BinaryData runData = BinaryData.FromObjectAsJson(new
{
name = "agent-trace-evaluation",
data_source = new
{
type = "azure_ai_traces",
trace_ids = traceIds,
lookback_hours = 1
}
});
using BinaryContent runContent = BinaryContent.Create(runData);
ClientResult evaluationRun = await evaluationClient.CreateEvaluationRunAsync(
evaluationId: evaluationId,
content: runContent);
Console.WriteLine($"Evaluation run created: {GetString(evaluationRun, "id")}");
后续步骤
- 若要轮询完成结果和解释结果,请参阅获取云评估结果。
- 有关完整的可运行示例,请参阅 GitHub 上的 sample_evaluations_builtin_with_traces.py。