azd在项目目录中,验证代理是否已部署并可调用:
azd ai agent show
发送测试提示:
azd ai agent invoke "Write a haiku about deploying cloud applications."
应在几秒钟内看到响应。
- 打开 Foundry 门户 并进入您的项目。
- 选择您的代理,然后选择 Playground 选项卡。
- 发送测试提示,例如
Write a haiku about deploying cloud applications.
应在几秒钟内看到响应。
安装 Foundry SDK:
pip install "azure-ai-projects>=2.0.0"
设置两个环境变量,然后创建项目客户端。 将 FOUNDRY_PROJECT_ENDPOINT 设置为您的项目端点,将 FOUNDRY_MODEL_NAME 设置为用作评判模型的聊天完成部署。 以下代码示例假定在此上下文中运行它们:
import os
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
endpoint = os.environ["FOUNDRY_PROJECT_ENDPOINT"]
model_deployment = os.environ["FOUNDRY_MODEL_NAME"]
credential = DefaultAzureCredential()
project_client = AIProjectClient(endpoint=endpoint, credential=credential)
client = project_client.get_openai_client()
确认已部署的代理已注册且可用。 将 <your-agent-name> 替换为托管代理的名称:
agent = project_client.agents.get("<your-agent-name>")
print(f"Found agent: {agent.name}")
如果代理存在,则调用将返回代理,或者如果名称错误或未部署代理,则引发错误。
安装 Foundry SDK 和 OpenAI evals 客户端:
dotnet add package Azure.AI.Projects --prerelease
dotnet add package OpenAI
dotnet add package Azure.Identity
设置两个环境变量,然后创建客户端。 将 FOUNDRY_PROJECT_ENDPOINT 设置为您的项目端点,将 FOUNDRY_MODEL_NAME 设置为用作评判模型的聊天完成部署。 以下代码示例假定在此上下文中运行它们:
using System.ClientModel;
using System.Text.Json;
using Azure.AI.Projects;
using Azure.AI.Projects.Agents;
using Azure.Core;
using Azure.Identity;
using OpenAI;
using OpenAI.Evals;
#pragma warning disable AAIP001, OPENAI001
var endpoint = Environment.GetEnvironmentVariable("FOUNDRY_PROJECT_ENDPOINT")!;
var modelDeployment = Environment.GetEnvironmentVariable("FOUNDRY_MODEL_NAME")!;
var credential = new DefaultAzureCredential();
AIProjectClient projectClient = new(new Uri(endpoint), credential);
// OpenAI-compatible evals client bound to the Foundry project endpoint.
// A Microsoft Entra token works as the credential because both use "Authorization: Bearer".
var token = credential.GetToken(new TokenRequestContext(["https://ai.azure.com/.default"])).Token;
EvaluationClient evalClient = new(
new ApiKeyCredential(token),
new OpenAIClientOptions { Endpoint = new Uri($"{endpoint}/openai/v1") });
确认已部署的代理已注册且可用。 将 <your-agent-name> 替换为托管代理的名称:
ProjectsAgentRecord agent = projectClient.AgentAdministrationClient.GetAgent("<your-agent-name>");
Console.WriteLine($"Found agent: {agent.Name}");
如果代理存在,则调用将返回代理,或者如果名称错误或未部署代理,则引发错误。
安装 Foundry SDK:
npm install @azure/ai-projects @azure/identity dotenv
设置两个环境变量,然后创建项目客户端。 将 FOUNDRY_PROJECT_ENDPOINT 设置为您的项目端点,将 FOUNDRY_MODEL_NAME 设置为用作评判模型的聊天完成部署。 以下代码示例假定在此上下文中运行它们:
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
import "dotenv/config";
const endpoint = process.env["FOUNDRY_PROJECT_ENDPOINT"] || "";
const modelDeployment = process.env["FOUNDRY_MODEL_NAME"] || "";
const projectClient = new AIProjectClient(
endpoint,
new DefaultAzureCredential(),
);
const client = projectClient.getOpenAIClient();
确认已部署的代理已注册且可用。 将 <your-agent-name> 替换为托管代理的名称:
const agent = await projectClient.agents.get("<your-agent-name>");
console.log(`Found agent: ${agent.name}`);
如果代理存在,则调用将返回代理,或者如果名称错误或未部署代理,则引发错误。
参考: AIProjectClient 类
首先,为代理创建测试查询的 JSONL 文件。 每行都是一个带有 query 字段的 JSON 对象。 将其保存在代理的源文件夹中,如下所示 src/<your-agent-name>/tests/queries.jsonl:
{"query": "Write a haiku about deploying cloud applications."}
然后在同一代理源文件夹中创建一个eval.yaml文件,并将其命名为src/<your-agent-name>/eval.yaml。 它会指向你的数据集,并列出要应用的内置评估器。
dataset.local_uri 路径是相对于此文件夹的。 将 <your-agent-name> 替换为您托管智能体的名称,将 <your-chat-completion-deployment> 替换为评判模型的部署路径:
name: agent-eval
agent:
name: <your-agent-name>
kind: hosted
dataset:
local_uri: tests/queries.jsonl
evaluators:
- builtin.intent_resolution
- builtin.task_adherence
options:
eval_model: <your-chat-completion-deployment>
max_samples: 15
eval_model 值是用于对响应进行评分的评判模型;您可以复用智能体当前使用的部署。
- 在Foundry 门户中,打开你的代理并选择“评估”选项卡,然后选择“创建”。
- 对于 “选择评估目标”,请选择 “代理”。
- 在 选择评估范围 中,选择 单个轮次。
- 对于 “选择数据源”,请选择 “现有数据集 ”,并从项目的数据资产中选择测试查询的 CSV 或 JSONL 文件。
- 如果出现 “配置代理 ”步骤,请查看代理并接受默认用户提示
{{item.query}}。 仅当您的智能体期望不同的输入格式时才进行调整。
- 对于 选择测试标准,请选择一个或多个代理评估器,例如 任务遵循 和 意图解决。
保持向导窗口打开。 您将在下一步提交评估结果。
首先,为代理创建测试查询的 JSONL 文件。 每行都是一个带有 query 字段的 JSON 对象。 将其另存为 queries.jsonl:
{"query": "Write a haiku about deploying cloud applications."}
将文件作为数据集上传到项目中:
dataset = project_client.datasets.upload_file(
name="agent-test-queries",
version="1",
file_path="./queries.jsonl",
)
接下来,选择内置计算器并映射其输入。 该 data_mapping 参数告知每个计算器在何处查找查询和代理响应。 AI 辅助评估器需要在 initialization_parameters 中指定评判模型;该值必须是您项目中的聊天完成部署。
from azure.ai.projects.models import TestingCriterionAzureAIEvaluator
testing_criteria = [
TestingCriterionAzureAIEvaluator(
type="azure_ai_evaluator",
name="Intent Resolution",
evaluator_name="builtin.intent_resolution",
initialization_parameters={"model": model_deployment},
data_mapping={
"query": "{{item.query}}",
"response": "{{sample.output_items}}",
},
),
TestingCriterionAzureAIEvaluator(
type="azure_ai_evaluator",
name="Task Adherence",
evaluator_name="builtin.task_adherence",
initialization_parameters={"model": model_deployment},
data_mapping={
"query": "{{item.query}}",
"response": "{{sample.output_items}}",
},
),
]
创建评估。 它定义测试数据架构和测试条件,并充当一个或多个运行的容器:
from openai.types.eval_create_params import DataSourceConfigCustom
data_source_config = DataSourceConfigCustom(
type="custom",
item_schema={
"type": "object",
"properties": {"query": {"type": "string"}},
"required": ["query"],
},
include_sample_schema=True,
)
evaluation = client.evals.create(
name="Agent Quality Evaluation",
data_source_config=data_source_config,
testing_criteria=testing_criteria,
)
print(f"Evaluation created: {evaluation.id}")
首先,为代理创建测试查询的 JSONL 文件。 每行都是一个带有 query 字段的 JSON 对象。 将其另存为 queries.jsonl:
{"query": "Write a haiku about deploying cloud applications."}
将文件作为数据集上传到项目中:
AIProjectDataset dataset = projectClient.Datasets.UploadFile(
name: "agent-test-queries",
version: "1",
filePath: "./queries.jsonl");
接下来,选择内置计算器并映射其输入。 该 data_mapping 参数告知每个计算器在何处查找查询和代理响应。 AI 辅助评估器需要在 initialization_parameters 中指定评判模型;该值必须是您项目中的聊天完成部署。
var testingCriteria = new object[]
{
new
{
type = "azure_ai_evaluator",
name = "Intent Resolution",
evaluator_name = "builtin.intent_resolution",
initialization_parameters = new { model = modelDeployment },
data_mapping = new { query = "{{item.query}}", response = "{{sample.output_items}}" },
},
new
{
type = "azure_ai_evaluator",
name = "Task Adherence",
evaluator_name = "builtin.task_adherence",
initialization_parameters = new { model = modelDeployment },
data_mapping = new { query = "{{item.query}}", response = "{{sample.output_items}}" },
},
};
创建评估。 它定义测试数据架构和测试条件,并充当一个或多个运行的容器:
var createEvaluation = new
{
name = "Agent Quality Evaluation",
data_source_config = new
{
type = "custom",
item_schema = new
{
type = "object",
properties = new { query = new { type = "string" } },
required = new[] { "query" },
},
include_sample_schema = true,
},
testing_criteria = testingCriteria,
};
ClientResult evaluationResult = evalClient.CreateEvaluation(
BinaryContent.Create(BinaryData.FromObjectAsJson(createEvaluation)));
string evaluationId = JsonDocument.Parse(evaluationResult.GetRawResponse().Content.ToString())
.RootElement.GetProperty("id").GetString()!;
Console.WriteLine($"Evaluation created: {evaluationId}");
首先,为代理创建测试查询的 JSONL 文件。 每行都是一个带有 query 字段的 JSON 对象。 将其另存为 queries.jsonl:
{"query": "Write a haiku about deploying cloud applications."}
将文件作为数据集上传到项目中:
const dataset = await projectClient.datasets.uploadFile(
"agent-test-queries",
"1",
"./queries.jsonl",
);
接下来,选择内置计算器并映射其输入。 该 data_mapping 参数告知每个计算器在何处查找查询和代理响应。 AI 辅助评估器需要在 initialization_parameters 中指定评判模型;该值必须是您项目中的聊天完成部署。
const testingCriteria = [
{
type: "azure_ai_evaluator",
name: "Intent Resolution",
evaluator_name: "builtin.intent_resolution",
initialization_parameters: { model: modelDeployment },
data_mapping: {
query: "{{item.query}}",
response: "{{sample.output_items}}",
},
},
{
type: "azure_ai_evaluator",
name: "Task Adherence",
evaluator_name: "builtin.task_adherence",
initialization_parameters: { model: modelDeployment },
data_mapping: {
query: "{{item.query}}",
response: "{{sample.output_items}}",
},
},
];
创建评估。 它定义测试数据架构和测试条件,并充当一个或多个运行的容器:
const dataSourceConfig = {
type: "custom",
item_schema: {
type: "object",
properties: { query: { type: "string" } },
required: ["query"],
},
include_sample_schema: true,
};
const evaluation = await client.evals.create({
name: "Agent Quality Evaluation",
data_source_config: dataSourceConfig,
testing_criteria: testingCriteria,
});
console.log(`Evaluation created: ${evaluation.id}`);
在 azd 工作区根目录中运行评估:
azd ai agent eval run --config eval.yaml
注意
azd ai agent eval run 解析的是相对于 --config 下智能体源文件夹(例如 src/)的 src/<your-agent-name>/eval.yaml 路径,而不是当前目录。 将 eval.yaml 及其 local_uri 指向的数据集保留在该文件夹中。
该命令读取 eval.yaml、将每个查询发送到代理、对响应评分,并在完成时输出摘要:
Eval run started
Eval: eval_b36748dede424e4ba3f8e6c99ca2cf27
Run: evalrun_5f72ef189ad24790a32128e6f230b131
(✓) Done Eval run
Results: 1 total, 1 passed, 0 failed, 0 errored
Per-criteria results:
intent_resolution: 1 passed, 0 failed, 0 errored
task_adherence: 1 passed, 0 failed, 0 errored
- 在“审阅并提交”步骤中,输入该评估的名称。
- 查看目标、范围、数据源和所选评估人员。
- 选择 “提交 ”以启动运行。
创建一个运行流程,将每个测试查询发送给你的智能体,并应用评估器。 将 <your-agent-name> 替换为托管代理的名称:
eval_run = client.evals.runs.create(
eval_id=evaluation.id,
name="Agent Evaluation Run",
data_source={
"type": "azure_ai_target_completions",
"source": {"type": "file_id", "id": dataset.id},
"input_messages": {
"type": "template",
"template": [
{
"type": "message",
"role": "user",
"content": {"type": "input_text", "text": "{{item.query}}"},
}
],
},
"target": {
"type": "azure_ai_agent",
"name": "<your-agent-name>",
# "version": "1", # Optional; omit to use the latest version
},
},
)
print(f"Evaluation run started: {eval_run.id}")
创建一个运行流程,将每个测试查询发送给你的智能体,并应用评估器。 将 <your-agent-name> 替换为托管代理的名称:
var createRun = new
{
name = "Agent Evaluation Run",
data_source = new
{
type = "azure_ai_target_completions",
source = new { type = "file_id", id = dataset.Id },
input_messages = new
{
type = "template",
template = new object[]
{
new { type = "message", role = "user", content = new { type = "input_text", text = "{{item.query}}" } },
},
},
// Add a "version" property to the target to pin a specific agent version; omit to use the latest.
target = new { type = "azure_ai_agent", name = "<your-agent-name>" },
},
};
ClientResult runResult = evalClient.CreateEvaluationRun(
evaluationId, BinaryContent.Create(BinaryData.FromObjectAsJson(createRun)));
string runId = JsonDocument.Parse(runResult.GetRawResponse().Content.ToString())
.RootElement.GetProperty("id").GetString()!;
Console.WriteLine($"Evaluation run started: {runId}");
创建一个运行流程,将每个测试查询发送给你的智能体,并应用评估器。 将 <your-agent-name> 替换为托管代理的名称:
const evalRun = await client.evals.runs.create(evaluation.id, {
name: "Agent Evaluation Run",
data_source: {
type: "azure_ai_target_completions",
source: { type: "file_id", id: dataset.id },
input_messages: {
type: "template",
template: [
{
type: "message",
role: "user",
content: { type: "input_text", text: "{{item.query}}" },
},
],
},
target: {
type: "azure_ai_agent",
name: "<your-agent-name>",
// version: "1", // Optional; omit to use the latest version
},
},
});
console.log(`Evaluation run started: ${evalRun.id}`);
列出最近的评估:
azd ai agent eval list
Eval ID Name Status of last run Runs
------- ---- ------------------ ----
* eval_b36748dede424e4ba3f8e6c99ca2cf27 agent-eval Completed 1
* = active eval in current environment
显示最新的评估及其运行记录:
azd ai agent eval show
Eval: eval_b36748dede424e4ba3f8e6c99ca2cf27
Name: agent-eval
Agent: <your-agent-name>
Runs: 1
Recent runs:
Run ID Status Passed Failed Created
------ ------ ------ ------ -------
evalrun_5f72ef189ad24790a32128e6f230b131 Completed 1/1 0 2026-06-17 14:52 UTC
利用这些结果确认评估的是哪个代理版本,以及产生了哪些评估器评分。 要查看每个评估器的详细信息以及 Foundry 门户中的报告链接,请运行 azd ai agent eval show <eval-id> --eval-run-id <run-id>。
- 详细信息页面显示每个评估器的目标、数据集、状态、令牌使用情况以及聚合分数。
- 选择运行名称以查看行级结果:每个查询、代理响应、计算器分数和分数说明。
轮询完成,然后打印状态和报告 URL,以便在 Foundry 门户中打开结果:
import time
while True:
run = client.evals.runs.retrieve(run_id=eval_run.id, eval_id=evaluation.id)
if run.status in ["completed", "failed"]:
break
time.sleep(5)
print(f"Status: {run.status}")
print(f"Report URL: {run.report_url}")
在运行层面,您可以查看每个评估器的汇总通过和失败计数:
print(run.result_counts)
for criteria in run.per_testing_criteria_results:
print(criteria.testing_criteria, "passed:", criteria.passed, "failed:", criteria.failed)
ResultCounts(errored=0, failed=0, passed=1, total=1, skipped=0)
Intent Resolution passed: 1 failed: 0
Task Adherence passed: 1 failed: 0
对于行级详细信息,请列出输出项目。 每个结果都包括评估器名称、通过或失败,以及分数:
for item in client.evals.runs.output_items.list(run_id=eval_run.id, eval_id=evaluation.id):
for result in item.results:
print(item.id, result.name, "passed:", result.passed, "score:", result.score)
轮询完成情况,然后打印在 Foundry 门户中打开结果的状态和报告 URL:
JsonElement run = default;
while (true)
{
ClientResult runStatus = evalClient.GetEvaluationRun(evaluationId, runId, options: null);
run = JsonDocument.Parse(runStatus.GetRawResponse().Content.ToString()).RootElement;
string status = run.GetProperty("status").GetString()!;
if (status is "completed" or "failed") break;
Thread.Sleep(TimeSpan.FromSeconds(5));
}
Console.WriteLine($"Status: {run.GetProperty("status").GetString()}");
Console.WriteLine($"Report URL: {run.GetProperty("report_url").GetString()}");
在运行层面,您可以查看每个评估器的汇总通过和失败计数:
Console.WriteLine(run.GetProperty("result_counts").GetRawText());
foreach (JsonElement criteria in run.GetProperty("per_testing_criteria_results").EnumerateArray())
{
Console.WriteLine(
$"{criteria.GetProperty("testing_criteria").GetString()} " +
$"passed: {criteria.GetProperty("passed").GetInt32()} " +
$"failed: {criteria.GetProperty("failed").GetInt32()}");
}
对于行级详细信息,请列出输出项目。 每个结果都包括评估器名称、通过或失败,以及分数:
ClientResult outputItems = evalClient.GetEvaluationRunOutputItems(
evaluationId, runId, limit: 100, order: null, after: null, outputItemStatus: null, options: null);
foreach (JsonElement item in JsonDocument.Parse(outputItems.GetRawResponse().Content.ToString())
.RootElement.GetProperty("data").EnumerateArray())
{
foreach (JsonElement result in item.GetProperty("results").EnumerateArray())
{
Console.WriteLine(
$"{item.GetProperty("id").GetString()} {result.GetProperty("name").GetString()} " +
$"passed: {result.GetProperty("passed")} score: {result.GetProperty("score")}");
}
}
轮询完成情况,然后打印在 Foundry 门户中打开结果的状态和报告 URL:
let run = evalRun;
while (!["completed", "failed"].includes(run.status)) {
run = await client.evals.runs.retrieve(run.id, {
eval_id: evaluation.id,
});
await new Promise((resolve) => setTimeout(resolve, 5000));
}
console.log(`Status: ${run.status}`);
console.log(`Report URL: ${run.report_url}`);
在运行层面,您可以查看每个评估器的汇总通过和失败计数:
console.log(JSON.stringify(run.result_counts));
for (const criteria of run.per_testing_criteria_results) {
console.log(
criteria.testing_criteria,
"passed:",
criteria.passed,
"failed:",
criteria.failed,
);
}
{"errored":0,"failed":0,"passed":1,"total":1,"skipped":0}
Intent Resolution passed: 1 failed: 0
Task Adherence passed: 1 failed: 0
对于行级详细信息,请列出输出项目。 每个结果都包括评估器名称、通过或失败,以及分数:
for await (const item of client.evals.runs.outputItems.list(run.id, {
eval_id: evaluation.id,
})) {
for (const result of item.results) {
console.log(item.id, result.name, "passed:", result.passed, "score:", result.score);
}
}