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

教程:第 3 部分 - 使用 Azure AI Foundry SDK 评估自定义聊天应用程序

在本教程中,你将使用 Azure AI SDK(和其他库)来评估在本教程系列的第 2 部分中构建的聊天应用。 在第 3 部分中,你将学习如何:

  • 创建评估数据集
  • 使用 Azure AI 评估程序评估聊天应用
  • 循环访问和改进应用

本教程是由三个部分构成的教程的第三部分。

先决条件

评估聊天应用回复的质量

现在,你已经知道聊天应用对查询做出了良好的响应,包括聊天记录,现在是时候根据几个不同的指标和更多数据来评估它的表现了。

将评估程序与评估数据集和 get_chat_response() 目标函数配合使用,然后评估评估结果。

运行评估后,即可对逻辑进行改进,例如完善系统提示,并观察聊天应用响应的更改和改进方式。

创建评估数据集

使用以下评估数据集,其中包含众多示例问题和预期答案。

  1. 在 assets 文件夹中创建名为 chat_eval_data.jsonl 的文件。

  2. 将此数据集粘贴到文件中:

    {"query": "Which tent is the most waterproof?", "truth": "The Alpine Explorer Tent has the highest rainfly waterproof rating at 3000m"}
    {"query": "Which camping table holds the most weight?", "truth": "The Adventure Dining Table has a higher weight capacity than all of the other camping tables mentioned"}
    {"query": "How much do the TrailWalker Hiking Shoes cost? ", "truth": "The Trailewalker Hiking Shoes are priced at $110"}
    {"query": "What is the proper care for trailwalker hiking shoes? ", "truth": "After each use, remove any dirt or debris by brushing or wiping the shoes with a damp cloth."}
    {"query": "What brand is TrailMaster tent? ", "truth": "OutdoorLiving"}
    {"query": "How do I carry the TrailMaster tent around? ", "truth": " Carry bag included for convenient storage and transportation"}
    {"query": "What is the floor area for Floor Area? ", "truth": "80 square feet"}
    {"query": "What is the material for TrailBlaze Hiking Pants?", "truth": "Made of high-quality nylon fabric"}
    {"query": "What color does TrailBlaze Hiking Pants come in?", "truth": "Khaki"}
    {"query": "Can the warrenty for TrailBlaze pants be transfered? ", "truth": "The warranty is non-transferable and applies only to the original purchaser of the TrailBlaze Hiking Pants. It is valid only when the product is purchased from an authorized retailer."}
    {"query": "How long are the TrailBlaze pants under warranty for? ", "truth": " The TrailBlaze Hiking Pants are backed by a 1-year limited warranty from the date of purchase."}
    {"query": "What is the material for PowerBurner Camping Stove? ", "truth": "Stainless Steel"}
    {"query": "Is France in Europe?", "truth": "Sorry, I can only queries related to outdoor/camping gear and equipment"}
    

使用 Azure AI 评估程序进行评估

现在定义一个评估脚本,该脚本将:

  • 围绕聊天应用逻辑生成一个目标函数包装器。
  • 上传示例 .jsonl 数据集。
  • 运行评估,该评估采用目标函数,并将评估数据集与聊天应用的响应合并。
  • 生成一组 GPT 辅助指标(相关性、真实性和连贯性)来评估聊天应用响应的质量。
  • 在本地输出结果,并将结果记录到云项目中。

通过脚本,可以在本地查看结果,方法是将结果输出到命令行和 json 文件。

该脚本还会将评估结果记录到云项目中,以便你在用户界面中比较评估运行。

  1. 在主文件夹中创建名为 evaluate.py 的文件。

  2. 添加以下代码以导入所需的库,创建一个项目客户端,并配置一些设置:

    import os
    import pandas as pd
    from azure.ai.projects import AIProjectClient
    from azure.ai.projects.models import ConnectionType
    from azure.ai.evaluation import evaluate, GroundednessEvaluator
    from azure.identity import DefaultAzureCredential
    
    from chat_with_products import chat_with_products
    
    # load environment variables from the .env file at the root of this repo
    from dotenv import load_dotenv
    
    load_dotenv()
    
    # create a project client using environment variables loaded from the .env file
    project = AIProjectClient.from_connection_string(
        conn_str=os.environ["AIPROJECT_CONNECTION_STRING"], credential=DefaultAzureCredential()
    )
    
    connection = project.connections.get_default(connection_type=ConnectionType.AZURE_OPEN_AI, include_credentials=True)
    
    evaluator_model = {
        "azure_endpoint": connection.endpoint_url,
        "azure_deployment": os.environ["EVALUATION_MODEL"],
        "api_version": "2024-06-01",
        "api_key": connection.key,
    }
    
    groundedness = GroundednessEvaluator(evaluator_model)
    
  3. 添加代码以创建一个包装器函数,该函数可实现用于查询和响应评估的计算接口:

    def evaluate_chat_with_products(query):
        response = chat_with_products(messages=[{"role": "user", "content": query}])
        return {"response": response["message"].content, "context": response["context"]["grounding_data"]}
    
  4. 最后,添加代码以运行评估,在本地查看结果,并提供一个指向 Azure AI Foundry 门户中的评估结果的链接:

    # Evaluate must be called inside of __main__, not on import
    if __name__ == "__main__":
        from config import ASSET_PATH
    
        # workaround for multiprocessing issue on linux
        from pprint import pprint
        from pathlib import Path
        import multiprocessing
        import contextlib
    
        with contextlib.suppress(RuntimeError):
            multiprocessing.set_start_method("spawn", force=True)
    
        # run evaluation with a dataset and target function, log to the project
        result = evaluate(
            data=Path(ASSET_PATH) / "chat_eval_data.jsonl",
            target=evaluate_chat_with_products,
            evaluation_name="evaluate_chat_with_products",
            evaluators={
                "groundedness": groundedness,
            },
            evaluator_config={
                "default": {
                    "query": {"${data.query}"},
                    "response": {"${target.response}"},
                    "context": {"${target.context}"},
                }
            },
            azure_ai_project=project.scope,
            output_path="./myevalresults.json",
        )
    
        tabular_result = pd.DataFrame(result.get("rows"))
    
        pprint("-----Summarized Metrics-----")
        pprint(result["metrics"])
        pprint("-----Tabular Result-----")
        pprint(tabular_result)
        pprint(f"View evaluation results in AI Studio: {result['studio_url']}")
    

配置评估模型

由于评估脚本会多次调用模型,因此可能需要增加评估模型的每分钟令牌数。

在本教程系列的第 1 部分中,你创建了一个指定评估模型名称 (gpt-4o-mini) 的 .env 文件。 如果有可用配额,请尝试增加此模型的每分钟令牌限制。 如果没有足够的配额来增加该值,请不要担心。 该脚本能够处理限制错误。

  1. 在 Azure AI Foundry 门户中的项目中,选择“模型 + 终结点”
  2. 选择“gpt-4o-mini”
  3. 选择“编辑” 。
  4. 如果有配额来增加“每分钟令牌数速率限制”,请尝试将其增加到 30。
  5. 选择“保存并关闭”。

运行评估脚本

  1. 在控制台中,使用 Azure CLI 登录到 Azure 帐户:

    az login
    
  2. 安装必需包:

    pip install azure-ai-evaluation[remote]
    
  3. 现在运行评估脚本:

    python evaluate.py
    

解释评估输出

在控制台输出中,你会看到每个问题的答案,后跟一个包含汇总指标的表。 (输出会存在不同的列。)

如果无法增加模型的每分钟令牌数限制,则可能会看到一些超时错误,这在意料之中。 评估脚本能够处理这些错误并继续运行。

注意

你可能还会看到许多 WARNING:opentelemetry.attributes: - 可以放心地忽略这些警告,它们不会影响评估结果。

====================================================
'-----Summarized Metrics-----'
{'groundedness.gpt_groundedness': 1.6666666666666667,
 'groundedness.groundedness': 1.6666666666666667}
'-----Tabular Result-----'
                                     outputs.response  ... line_number
0   Could you specify which tent you are referring...  ...           0
1   Could you please specify which camping table y...  ...           1
2   Sorry, I only can answer queries related to ou...  ...           2
3   Could you please clarify which aspects of care...  ...           3
4   Sorry, I only can answer queries related to ou...  ...           4
5   The TrailMaster X4 Tent comes with an included...  ...           5
6                                            (Failed)  ...           6
7   The TrailBlaze Hiking Pants are crafted from h...  ...           7
8   Sorry, I only can answer queries related to ou...  ...           8
9   Sorry, I only can answer queries related to ou...  ...           9
10  Sorry, I only can answer queries related to ou...  ...          10
11  The PowerBurner Camping Stove is designed with...  ...          11
12  Sorry, I only can answer queries related to ou...  ...          12

[13 rows x 8 columns]
('View evaluation results in Azure AI Foundry portal: '
 'https://xxxxxxxxxxxxxxxxxxxxxxx')

在 Azure AI Foundry 门户中查看评估结果

评估运行完成后,请点击链接在 Azure AI Foundry 门户中的评估页面上查看评估结果。

显示 Azure AI Foundry 门户中的评估概述的屏幕截图。

还可以查看各个行并查看每行的指标分数,并查看检索到的完整上下文/文档。 这些指标有助于解释和调试评估结果。

显示 Azure AI Foundry 门户中的评估结果行的屏幕截图。

有关 Azure AI Foundry 门户中的评估结果的详细信息,请参阅如何在 Azure AI Foundry 门户中查看评估结果

循环访问和改进

请注意,答复没有充分的依据。 在许多情况下,模型会回复问题但并非答案。 这是提示模板说明的结果。

  • 在 assets/grounded_chat.prompty 文件中,找到“如果问题与户外/露营装备和服装有关,但含糊不清,要求澄清问题,而不是引用文档”这句话
  • 将句子更改为“如果问题与户外/露营装备和服装有关,但含糊不清,请尝试根据参考文档回答,然后要求澄清问题”。
  • 保存文件并重新运行评估脚本。

尝试对提示模板进行其他修改,或尝试不同的模型,了解更改如何影响评估结果。

清理资源

为了避免产生不必要的 Azure 成本,如果不再需要在本快速入门中创建的资源,应该将其删除。 若要管理资源,可以使用 Azure 门户