基于 Microsoft Foundry 的智能体式 AI——AI 解决方案评估与负责任 AI

19 阅读13分钟

Responsible AI 是一个新兴领域,关注如何信任 model 或 AI Agent 的输出,以及如何构建 ethical AI system。信任 AI 的最大障碍之一是 hallucination。Hallucinations 指 model 生成了并非基于事实的输出。由于 models 是基于历史数据训练的,当被问到训练集之外或 knowledge cutoff 之后的信息时,它并不知道答案是什么,于是会根据训练数据生成听起来合理但实际错误的文本。另外,如果我们请求的 context 不在训练数据中,那么 model 也会预测并生成自己的文本。

Microsoft 自 2016 年以来一直在推动 Responsible AI principles,并且是该领域的领导者。最初目标是为 Microsoft 内部团队构建 ethical AI framework,后来这一框架也开放给 customers 使用。以下是六项原则:

  • Fairness
  • Reliability and Safety
  • Privacy and security
  • Transparency
  • Accountability
  • Inclusiveness

本章将覆盖面向 agents 的 Responsible AI。这是一个重要章节,内容包括如何建立对 AI agents 的信任,并确保它们安全运行。本章将覆盖以下主题:

  • Responsible AI Principles
  • Model Evaluation Using the User interface
  • Agent Evaluation – Realtime & Batch
  • Cybersecurity – Red Team

Technical requirements

本章需要在可用 region 中创建 Microsoft Foundry resources。每个 subscription 下 Foundry resource 有 quotas 和 limits,在扩展 solution 时需要注意这一点。下面提供了 quotas 和 limits 页面链接。该信息可能变化,因此在设计 scale 之前,请务必查看当前版本: learn.microsoft.com/en-us/azure…

接下来,我们将深入学习如何使用 prompt 和 context,或者不使用 context,来评估 model output。我们也可以使用多个 models 进行评估,并比较结果。然后,我们将详细学习使用 real-time 和 batch evaluation 进行 agent evaluation。

Responsible AI principles

下面进一步了解引言中列出的每一项原则。

Fairness:AI systems 应公平对待所有人。

Reliability and Safety:AI systems 在与 humans 和 other agents 交互时,应可靠且安全地执行。

Privacy and Security:所有 AI systems 在与 humans 和 other agents 交互时,应尊重隐私并确保安全。

Transparency:AI systems 应对其如何构建和记录保持透明,并且在与 people、agents 或 other systems 交互时,清楚传达自身 behavior。

Accountability:Humans 应对所有 AI systems 负责。保持 human-in-the-loop approach 对确保责任和监督至关重要。

Inclusiveness:AI systems 应赋能并吸引所有人参与,无论其背景如何。

有了 responsible AI principles 后,下一步是评估 model 在实践中的表现。Model evaluation 有助于确保 system 交付 accurate、relevant 和 safe outcomes,并与具体 business needs 对齐。

Model evaluation

在本节中,你将学习如何评估针对特定 business use cases 使用的 model prompt。Evaluation 取决于 model 的使用方式,例如 extraction、summarization 或 content creation。大多数 models 都有 knowledge cutoff date,这意味着它们只知道某个时间点之前的信息。但在大多数 business 或 industry use cases 中,我们需要在 runtime 向 model 提供 fresh data。这种技术称为 Retrieval Augmented Generation(RAG)。

Model evaluation 使用一组 KPIs,这些 KPIs 分为两类:

  • Quality
  • Safety

Quality Metrics 关注在给定 user input 下 model output 如何,以及 output 中生成的 tokens。下面列表是本书写作时的当前内容,未来可能随着领域发展而变化。

image.png

图 10.1:Quality metrics evaluators

Safety evaluators 关注生成内容在语言层面是否涉及 sexual、harmful 或 violent content。鉴于 language model outputs 具有开放式特征,这是一个关键领域。

image.png

图 10.2:Safety Evaluators

Evaluators 是用于评估 AI models 的机制,覆盖 harmful content、sexual content、indirect attacks 和 prompt injection 等关键风险类别。它们支持根据定义好的 criteria 系统化测试 model behavior,以确保 outputs 与 safety 和 quality standards 对齐。

通过在 development lifecycle 早期集成 evaluators,teams 可以主动识别 vulnerabilities、验证 model responses,并建立有效 guardrails。这有助于降低 misleading 或 unsafe model-generated content 的风险,并确保更安全、更可靠的 user experience。

关于这些 evaluators 的详情,请参考链接: learn.microsoft.com/en-us/azure…

大多数 definitions 和含义都已在上述链接中记录。由于 evaluators 可能会变化,可能新增一些,也可能弃用一些,因此请始终参考上述链接,确保使用当前 evaluation 可用的最新列表。

Dataset creation

现在,让我们创建一个 sample dataset,用于 model evaluation。进行 model evaluation 时,我们需要有 input、context、ground truth 和 response。建议你基于自己的具体 use case 创建 dataset。

Input:用户的问题或自然语言输入。

Context:Context 可以来自 prompt 本身,也可以来自 retrieved content,例如来自 Azure AI Search 的结果,或针对 domain-specific corpus 执行 vector embedding search 得到的结果。

Ground Truth:由 human 或 SME 验证的输出,用于特定 user input 集合,作为 expert output 来衡量 model response 并进行 evaluation。在某些情况下,可以使用更强大的 large language model 生成 ground truth,不过 SME-validated data 通常是最可靠的方法。最有效的方式是让 subject matter experts 创建 dataset。

Responses:这是 model 的输出。

下面是该 repo 中可用的 sample dataset: github.com/Azure/azure…

保持包含 input、context、ground truth 和 response 字段的一致 data schema 非常重要,因为本章后续需要为 evaluation 提供 mapping;evaluation SDK 会查找特定 field names。因此,请确保 column 或 property name 与 sample 中提供的名称一致。将 dataset 保存为本地 folder 中的 .jsonl 文件,以便上传进行 evaluation。

Model evaluation using the user interface

本章将逐步演示如何使用 Microsoft Foundry user interface 评估 models。请确保 dataset 已准备好,同时也需要一个 prompt 在 UI 中用于 evaluation。

进入: ai.azure.com/

选择 Build > Evaluations,并点击 Create

在右上角菜单选择 Build

在左侧菜单选择 Evaluations

image.png

图 10.3

现在在右侧找到 Create 按钮。

image.png

图 10.4

现在选择 Model 作为要评估的选项,然后在右侧确保选择要使用的 models。本书中,我选择 gpt-4o、gpt-4.1、gpt-4.1-mini 和 gpt。然后点击 Next 按钮。

下面的图会展示选择 target 的选项,例如 agent 或 model,以及选择要评估 models 的能力。

image.png

图 10.5:Model Selection

现在选择 Existing dataset

image.png

图 10.6:Data Set selection

现在右上角会有一个链接:Upload new dataset

image.png

图 10.7

点击 Upload new dataset,你应该会看到下面的 screen:

image.png

图 10.8:Upload evaluation dataset

在屏幕右下角,你应该会看到 dataset 的前 5 行显示出来供 review,请确保 column names 是预期的名称。

image.png

图 10.9:Preview of top 5 Row

上传完成后,Next 按钮应该会被激活。点击继续。

在下一屏中,从 model deployments 列表中选择 judge model。Dataset mapping 选项允许你将 dataset columns 映射到 evaluators 期望的 fields。

Column names 会带有 items 前缀。请引用你上传 dataset 中的 fields。按照下方方式匹配 columns。暂时忽略 tools properties。Model evaluation 不需要这些字段,但本章后续 Agent evaluation 会需要。

image.png

图 10.11:Mapping columns

现在点击进入下一屏。

现在为每个 model 配置你想评估的 prompt。对屏幕上显示的每个 model 重复下面步骤。

image.png

图 10.12:Model configuration Pending

点击其中一个 model 的 Configure,并提供如下 custom prompt:

image.png

图 10.13:Model configurator

System section 中输入:

You are an RFP AI Agent for the construction industry.

这是一个 sample,你应提供自己的 prompt,并包含详细 instructions 用于 evaluation。这里还提供 temperature 和 top_p parameters 的选项,可以根据需要调整 sliders。你也可以添加 user message 来模拟 chat-style input,也就是在 prompt 中模拟 chat style data input。完成后,点击 Save,并对列表中的每个 model 重复该流程。所有 models 配置完成后,点击 Next 按钮进入下一步,如下图所示:

image.png

图 10.14:model configuration complete

现在我们可以添加 evaluators,用于评估 models。这里有可用 evaluators 列表,请选择与你 use case 相关的 evaluators。有些 evaluators 只适用于特定场景。例如,如果你使用带 retrieved context 的 RAG,Relevance 很重要。对于不带 retrieval 的 simple Q&A,可以跳过它。如果你有 RAG context,则需要 relevancy;只是 question and answers,则不需要。下面是我选择的列表:

image.png

图 10.15:Evaluator selection

要添加更多 evaluators,点击 Add Evaluators

image.png

图 10.16

选择每个 evaluator,并配置它的 properties。

image.png

图 10.17:Evaluator configuration

完成后点击 Confirm,并重复该流程添加更多 evaluators。

点击 Next

Review 所有 settings,命名你的 evaluation,然后点击 Submit

image.png

图 10.18:Final review screen

现在你应该会看到 processing icon。

image.png

图 10.19

系统会带你进入 evaluation page。返回 Evaluations home page,你应该会看到 evaluation status 正在 running。根据 dataset size 和所选 models 数量,这可能需要一些时间。等待 execution 完成,然后进入 evaluation 并选择 evaluation run。

image.png

图 10.20:Evaluation Run details

你将能看到上面的 screen,其中包含每个 evaluator 的详情。Score 为 100% 表示 strong performance,较低 score 则说明 prompt 或 context 需要 tuning,或者 model 可能不适合你的 use case。

点击进入 run,可以分析 dataset、calculated metrics 和 detailed logs。

到此,models 的 batch evaluation 结束。

Model evaluation using SDK – python code

在本节中,我们将使用 Python SDK 执行同样的 batch model evaluation。在本地机器上设置 Python environment,并安装 Microsoft Agent Framework,它会将 Azure AI Evaluation SDK 作为 dependency 安装。如果 SDK 尚未安装,请运行:

pip install azure-ai-evaluation

运行代码之前,创建一个 .env 文件,包含以下 environment variables:

AZURE_AI_PROJECT=""
AZURE_OPENAI_KEY=""
AZURE_OPENAI_ENDPOINT=""
AZURE_OPENAI_DEPLOYMENT="gpt-4.1"
AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4.1"
AZURE_AI_PROJECT_ENDPOINT=""

在你的 Python project 中创建 .env 文件并保存。请从 Microsoft Foundry portal 中获取这些 values。

下面我们讲解代码中的关键部分。完整 script 可在 repository 中获取。

下面是创建 testing criteria 的 sample code。在代码中,我们会选择要使用的 evaluator_name,然后基于下面代码从 dataset 中将 columns 映射到对应 columns。例如,map query、context、response——这些是 evaluators 处理所需的 inputs。同时将 deployment_name 配置为 Microsoft Foundry 中实际部署的 Azure OpenAI model。

{
  "type": "azure_ai_evaluator",
  "name": "relevance",
  "evaluator_name": "builtin.relevance",
  "initialization_parameters": {
    "deployment_name": model_deployment_name
  },
  "data_mapping": {
    "query": "{{item.query}}",
    "context": "{{item.context}}",
    "response": "{{sample.output_text}}"
  }
},
{
  "type": "azure_ai_evaluator",
  "name": "retrieval",
  "evaluator_name": "builtin.retrieval",
  "initialization_parameters": {
    "deployment_name": model_deployment_name
  },
  "data_mapping": {
    "query": "{{item.query}}",
    "context": "{{item.context}}"
  }
}

下面是设置 batch model evaluation 并分配带 testing criteria 的 data source 的代码。下面代码会创建 evaluation objects,并设置 data source 和 testing criteria。然后,它会基于所使用的 file 设置 data source。之后,我们将调用 evaluation 来执行已配置的 test。

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,
)

完整 code block 很难在书中完整展示,完整代码可在 repository 中查看: github.com/balakreshna…

Agent evaluation – Real-time and batch

在本节中,你将学习如何使用 Batch 和 realtime 两种方式评估 agent。Batch 和 realtime 使用相同 code base,只有一个区别:batch 会提供 dataset file;realtime 则是 user input 和 agent 生成的 output。

进入: ai.azure.com/

选择 Build > Evaluations,并点击 Create

在右上角菜单选择 Build

image.png

图 10.21

在左侧菜单选择 Evaluations

image.png

图 10.22

现在在右侧找到 Create 按钮。

image.png

图 10.23

现在选择 Agent 作为要评估的选项,然后在右侧确保选择要使用的 models。本书中,我选择 gpt-4o、gpt-4.1、gpt-4.1-mini 和 gpt。然后点击 Next

image.png

图 10.24:Model Selection

选择 Existing dataset

image.png

图 10.25:Data Set selection

现在右上角会有一个链接:Upload new dataset

image.png

图 10.26

点击 Upload new dataset。你应该会看到下面的 screen:

image.png

图 10.27:Upload evaluation dataset

在屏幕右下角,你应该会看到 dataset 的前 5 行显示出来供 review,并确保 column names 是预期的名称。

image.png

图 10.28:Data set viewer

对于 agent evaluation,dataset schema 必须包含 tool_definitionstool_calls fields,因为 agent evaluators 除了 response 之外,还会评估 tool use behavior。

点击 Next 来映射 columns。

image.png

图 10.29:Data set mapping for Agent Evaluation

下一屏中,选择你想使用的 agent evaluators。

image.png

图 10.30:Agent Evaluator

如果想添加更多 evaluators:

image.png

图 10.31

选择 evaluator 并配置 settings。

image.png

图 10.32:Agent evaluator screen

点击 Confirm,然后 Next,再点击 Submit

image.png

图 10.33:Final review screen

下面是状态页面:

image.png

图 10.34

等待 run 完成。

返回 Evaluations home screen,并选择 agent eval run 查看 status。

image.png

图 10.35:Agent Eval Status

接近 100% 的 score 表示 agent 表现良好。较低 score 说明需要 refine prompt、context 或 model selection。

尝试改变 prompt、evaluators 和 models,观察它们如何影响结果。

在本节中,你学习了如何评估 agents。Agent evaluation 可以通过将 Python SDK 集成到 agent runtime code 中以 real time 方式运行,也可以在 development 阶段通过 Foundry UI 以 batch mode 运行。UI 中展示的所有内容也可以通过 Python SDK 以 programmatic 方式完成。完整代码可在这里查看: github.com/balakreshna…

下面是一个 sample code block:

eval_run_object = client.evals.runs.create(
    eval_id=eval_object.id,
    name="EvalBatchAgentEvalRun",
    metadata={"team": "eval-exp", "scenario": "dataset-id-v1"},
    data_source=CreateEvalJSONLRunDataSourceParam(
        type="jsonl",
        source=SourceFileID(
            type="file_id",
            id=dataset.id if dataset.id else "",
        ),
    ),
)

Cybersecurity – red team

在本节中,我们将学习如何在 Microsoft Foundry UI 中使用 Red team agent 运行 Red Team scan。

进入:

https://ai.azure.com/

选择 Build > Evaluations > Redteam,并点击 Create

在右上角菜单选择 Build

image.png

图 10.36

在左侧菜单选择 Red team

image.png

图 10.36

现在在右侧找到 Create 按钮。

选择一个 existing agent 进行测试;如果没有 agent,则创建一个名为 RedteamAgent 的新 empty agent。

image.png

图 10.37:Red team agent selection

然后点击 Next。在下一屏中,你会看到 Red Team Risk categories、每个 category 的 number of runs,以及 Attack strategies 的配置。有很多 attack strategies 可供选择。下面是所有 attack strategies 及其详情的链接: learn.microsoft.com/en-us/azure…

下面是 configuration screen 的样子:

image.png

图 10.38:Red Team configuration

如你所见,可以看到 Risk Categories。要添加或移除 risk categories,点击上方的 Modify

image.png

图 10.39:Risk Categories to choose from

对于每个 category 的 seed prompts 数量,我为了测试选择了 1。在 production 中,5 是常见值。

要修改 attack strategies,点击 Modify 并从列表中选择。

image.png

图 10.40:Attack strategies list

选择 Attack strategies 后,点击 Next

根据所选 attack strategies 和 seed turns 数量,red team run 可能需要相当长时间才能完成。你也可以使用 Python SDK 在本地运行 red team。不过,在 cloud 中运行可以提供更好的 visibility 和 observability,更容易比较不同 configurations 下的 runs,并随时间 review logs。

点击 Next,并使用你想测试的 prompt 配置 Red Team agent。

image.png

图 10.41:Red Team agent to configure

点击 Red Team Agent Test 打开 configuration window。填写必需 properties 以继续。

image.png

图 10.42:Red Team agent actions

该 screen 上显示的选项取决于你之前选择了多少 attack strategies。

点击 Save,并进入下一屏。

image.png

图 10.43:Review of agent configuration

在最终 review screen 中,为你的 red team test 提供 descriptive name。

image.png

图 10.44:Final review screen

等待 red team 完成。

然后进入 Evaluations → Red Team,选择 run,并查看 output。

image.png

图 1.45:Red team run

打开 details page,review 生成的数据以及每种 attack 的 status。

image.png

图 10.46:Attack details

本节覆盖的所有内容,也可以使用 Python SDK 完成。如果你更喜欢 code-based approach,可以查看如下代码链接: github.com/balakreshna…

下面是上述 repo 中的 sample code:

eval_run_object = client.evals.runs.create(
    eval_id=eval_object.id,
    name=eval_run_name,
    data_source={  # type: ignore
        "type": "azure_ai_red_team",
        "item_generation_params": {
            "type": "red_team_taxonomy",
            "attack_strategies": ["Flip", "Base64"],
            "num_turns": 1,
            "source": {"type": "file_id", "id": taxonomy.id},
        },
        "target": target.as_dict(),
    },
)

在本节中,我们学习了如何使用 Microsoft Foundry 进行 Red Team,运行一些 attack strategies。我们看到如何选择 risk categories,如何指定要处理的 turns 数量,以及如何选择 attack strategies。我们也看到如何创建 Red Team experiment 并提交到 cloud 运行。最后,我们还在 Foundry user interface 中查看了 output 和 details。

Summary

本章中,我们学习了什么是 Responsible AI,并探索了它的核心原则。我们看到了 Responsible AI 的六项原则。我们还学习了如何使用 Microsoft Foundry portal 进行 model evaluation。我们看到如何针对单个和多个 models 运行 batch evaluations,以比较哪个 model 在 Responsible AI criteria 下表现最好。

Responsible AI 本质上就是让 model 更 ethical 和 trustworthy。随后,我们学习了如何以 real-time 和 batch 两种模式评估 agents。我们也回顾了 evaluation 对 dataset 的要求。最后,我们覆盖了如何对 agent 进行 red team,以识别 security weaknesses,并通过 prompt engineering、instructions 和 guardrails 来缓解这些问题。

接下来,在第 11 章中,我们将学习如何将这些经过评估的 agents 部署并集成到真实 enterprise applications 中。