快速入門:評估回應品質

在本快速入門中,您會建立 MSTest 應用程式,以評估 OpenAI 模型的聊天回應品質。 測試應用程式使用 Microsoft 擴充功能.AI.Evaluation函式庫。

備註

本快速入門示範評估 API 的最簡單用法。 值得注意的是,它不會示範 回應快取報告 功能的使用,如果您要撰寫在「離線」評估管線中執行的單元測試,這很重要。 本快速入門顯示的情境適用於使用案例,例如在生產程式碼中嵌入「線上」評估 AI 回應,並將分數記錄在遙測系統,此時快取和報告並不適用的情形。 如需示範快取和報告功能的教學課程,請參閱 教學課程:使用回應快取和報告評估模型的回應

先決條件

設定 AI 服務

若要使用 Azure 入口網站提供 Azure OpenAI 服務 與模型,請完成 建立並部署 Azure OpenAI 服務 資源 文章中的步驟。 在 [部署模型] 步驟中,選取 gpt-5 模型。

建立測試應用程式

完成以下步驟,建立一個連接 AI 模型的 MSTest 專案。

  1. 在終端機視窗中,流覽至您要建立應用程式的目錄,然後使用命令 dotnet new 建立新的 MSTest 應用程式:

    dotnet new mstest -o TestAI
    
  2. 瀏覽至 TestAI 目錄,並將必要的套件新增至您的應用程式:

    dotnet add package Azure.AI.OpenAI
    dotnet add package Azure.Identity
    dotnet add package Microsoft.Extensions.AI.Abstractions
    dotnet add package Microsoft.Extensions.AI.Evaluation
    dotnet add package Microsoft.Extensions.AI.Evaluation.Quality
    dotnet add package Microsoft.Extensions.AI.OpenAI
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    
  3. 執行以下指令,為你的Azure OpenAI 端點和租戶 ID 新增 app secrets

    dotnet user-secrets init
    dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint>
    dotnet user-secrets set AZURE_TENANT_ID <your-tenant-ID>
    

    (視你的環境而定,你可能不需要租戶ID。在這種情況下,從實例化 的 DefaultAzureCredential程式碼中移除它。)

  4. 在您選擇的編輯器中開啟新的應用程式。

新增測試應用程式程式碼

  1. Test1.cs 檔案重新命名為 MyTests.cs,然後開啟檔案並將類別重新命名為 MyTests

  2. 將私人 ChatConfiguration 和聊天訊息以及回應成員新增至 MyTests 類別。 欄位 s_messages 是包含兩個 ChatMessage 物件的清單,一個指示聊天機器人的行為,另一個是使用者的問題。

    private static ChatConfiguration? s_chatConfiguration;
    private static IList<ChatMessage> s_messages = [
        new ChatMessage(
            ChatRole.System,
            """
            You're an AI assistant that can answer questions related to astronomy.
            Keep your responses concise and try to stay under 100 words.
            Use the imperial measurement system for all measurements in your response.
            """),
        new ChatMessage(
            ChatRole.User,
            "How far is the planet Venus from Earth at its closest and furthest points?")];
    private static ChatResponse s_response = new();
    
  3. 將方法InitializeAsync新增至MyTests類別。

    [ClassInitialize]
    public static async Task InitializeAsync(TestContext _)
    {
        /// Set up the <see cref="ChatConfiguration"/>,
        /// which includes the <see cref="IChatClient"/> that the
        /// evaluator uses to communicate with the model.
        s_chatConfiguration = GetAzureOpenAIChatConfiguration();
    
        var chatOptions =
            new ChatOptions
            {
                Temperature = 0.0f,
                ResponseFormat = ChatResponseFormat.Text
            };
    
        // Fetch the response to be evaluated
        // and store it in a static variable.
        s_response = await s_chatConfiguration.ChatClient.GetResponseAsync(s_messages, chatOptions);
    }
    

    這個方法會完成下列工作:

  4. 新增GetAzureOpenAIChatConfiguration方法,以建立評估者用來與模型通訊的IChatClient

    private static ChatConfiguration GetAzureOpenAIChatConfiguration()
    {
        IConfigurationRoot config = new ConfigurationBuilder().AddUserSecrets<MyTests>().Build();
    
        string endpoint = config["AZURE_OPENAI_ENDPOINT"];
        string tenantId = config["AZURE_TENANT_ID"];
        string model = "gpt-5";
    
        // Get a chat client for the Azure OpenAI endpoint.
        AzureOpenAIClient azureClient =
            new(
                new Uri(endpoint),
                new DefaultAzureCredential(new DefaultAzureCredentialOptions() { TenantId = tenantId }));
        IChatClient client = azureClient.GetChatClient(deploymentName: model).AsIChatClient();
    
        return new ChatConfiguration(client);
    }
    
  5. 新增測試方法來評估模型的回應。

    [TestMethod]
    public async Task TestCoherence()
    {
        IEvaluator coherenceEvaluator = new CoherenceEvaluator();
        EvaluationResult result = await coherenceEvaluator.EvaluateAsync(
            s_messages,
            s_response,
            s_chatConfiguration);
    
        /// Retrieve the score for coherence from the <see cref="EvaluationResult"/>.
        NumericMetric coherence = result.Get<NumericMetric>(CoherenceEvaluator.CoherenceMetricName);
    
        // Validate the default interpretation
        // for the returned coherence metric.
        Assert.IsFalse(coherence.Interpretation!.Failed);
        Assert.IsTrue(coherence.Interpretation.Rating is EvaluationRating.Good or EvaluationRating.Exceptional);
    
        // Validate that no diagnostics are present
        // on the returned coherence metric.
        Assert.IsFalse(coherence.ContainsDiagnostics());
    }
    

    此方法會執行下列動作:

執行測試/評估

使用您慣用的測試工作流程來執行測試,例如,使用 CLI 命令 dotnet test 或透過 Test Explorer

清理資源

如果你不再需要它們,請刪除 Azure OpenAI 資源和 GPT-4 模型部署。

  1. Azure 入口網站,請前往 Azure OpenAI 資源。
  2. 選擇 Azure OpenAI 資源,然後選擇 Delete

後續步驟