共用方式為


如何使用 Azure AI Foundry SDK 在線執行評估

重要

本文中標示為 (預覽) 的項目目前處於公開預覽狀態。 此預覽版本沒有服務等級協定,不建議將其用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款

在本文中,您將瞭解如何使用 Azure AI Foundry SDK 以連續的方式在線執行評估。 在生產前環境中評估對於確保應用程式安全、高效能及產生高質量結果至關重要。 不過,在部署應用程式之後,評估不會停止。 在生產環境中,各種專案可能會變更,例如用戶傳送至應用程式的查詢類型,這可能會影響應用程式的效能。 若要在生產環境產生 AI 應用程式中維持高度的可觀察性,請務必 追蹤 並持續評估應用程式的數據。 如此一來,您就可以對應用程式的安全性、品質和效能保持信心。

在線評估的運作方式

在本節中,您將瞭解在線評估的運作方式、它如何與 Azure 監視器 Application Insights 整合,以及如何使用它對來自您產生的 AI 應用程式的追蹤數據執行持續評估

檢測您的應用程式以將追蹤數據傳送至 Application Insights 之後,請設定在線評估排程以持續評估此資料。 在線評估是使用 Azure AI 計算持續執行一組可設定評估工具的服務。 使用 Azure AI Foundry SDK 設定在線評估排程之後,它會以可設定的排程執行。 每次排程的作業執行時,都會執行下列步驟:

  1. 使用提供的 Kusto (KQL) 查詢,從連線的 Application Insights 資源查詢應用程式追蹤數據。
  2. 在追蹤數據上執行每個評估工具,並計算每個計量(例如 ,基礎性:3)。
  3. 使用標準化語意慣例,將評估分數寫回每個追蹤。

注意

在線評估支援與 Azure AI 評估相同的計量。 如需評估運作方式及支援哪些評估計量的詳細資訊,請參閱 使用 Azure AI 評估 SDK 評估您的 Generative AI 應用程式。

例如,假設您有一個已部署的聊天應用程式,每天會收到許多客戶問題。 您想要持續評估應用程式回應的品質。 您設定了每日週期的在線評估排程。 您可以設定評估工具:基礎性連貫性和流暢性。 服務每天都會計算這些計量的評估分數,並將數據寫回 Application Insights,以取得在週期時間範圍期間收集的每個追蹤(在此範例中為過去 24 小時)。 然後,您可以從每個追蹤查詢數據,並在 Azure AI Foundry 和 Azure 監視器 Application Insights 中加以存取。

寫回 Application Insights 內每個追蹤的評估結果遵循下列慣例。 每個評估計量的每個追蹤都會新增唯一範圍:

屬性 Application Insights 數據表 指定operation_ID的欄位 範例值
評估計量 traces、AppTraces customDimensions[“event.name”] gen_ai.evaluation.relevance
評估計量分數 traces、AppTraces customDimensions[“gen_ai.evaluation.score”] 3
評估計量批註(如果適用) traces、AppTraces message {“comment”: “I like the response”}

既然您已瞭解在線評估的運作方式,以及其連線到 Azure 監視器 Application Insights 的方式,下一個步驟是設定服務。

設定在線評估

在本節中,您將瞭解如何設定在線評估排程,以持續監視已部署的產生 AI 應用程式。 Azure AI Foundry SDK 透過 提供這類功能。 Python API 並支援本機評估中可用的所有功能。 使用下列步驟,使用內建或自定義評估工具,在數據上提交在線評估排程。

注意

評估僅支援與 AI 輔助風險和安全性計量相同的 區域

必要條件

完成下列必要步驟,以設定您的環境和對必要資源的驗證:

  1. Azure 訂用帳戶
  2. 評估支援區域中的資源群組
  3. 相同資源群組和區域中的新 使用者指派受控識別 。 請記下 clientId;您稍後會用到它。
  4. 相同資源群組和區域中的 Azure AI 中樞。
  5. 此中樞的 Azure AI 專案,請參閱 在 Azure AI Foundry 入口網站中建立專案。
  6. Azure 監視器 Application Insights 資源
  7. 流覽至 Azure 入口網站 中的中樞頁面並新增Application Insights資源,請參閱更新 Azure 應用程式Insights和 Azure Container Registry
  8. 支援 GPT 模型的 chat completionAzure OpenAI 部署,例如 gpt-4
  9. Connection String 可讓 Azure AI 專案輕鬆建立 AIProjectClient 物件。 您可以從專案的 [概觀] 頁面,取得 [專案詳細數據] 底下的 [專案 連接字串
  10. 流覽至 Azure 入口網站 中的 Application Insights 資源,並使用 [存取控制 (IAM)] 索引標籤,將角色新增Log Analytics Contributor至您先前建立的使用者指派受控識別。
  11. 使用者指派的受控識別 附加至您的專案。
  12. 流覽至 Azure 入口網站 中的 Azure AI 服務,並使用 [存取控制 (IAM)] 索引標籤,Cognitive Services OpenAI Contributor將角色新增至您先前建立的使用者指派受控識別。

安裝說明

安裝 Azure CLI 並登入

您安裝 Azure CLI 並從您的本機開發環境登入,讓您可以使用您的使用者認證來呼叫 Azure OpenAI 服務。

在大部分情況下,您可以使用下列命令,從終端機安裝 Azure CLI:

winget install -e --id Microsoft.AzureCLI

如果這些命令不適合您的特定作業系統或設定,您可以遵循如何安裝 Azure CLI 的指示。

安裝 Azure CLI 之後,請使用 az login 命令登入並使用瀏覽器登入:

az login

或者,您可以使用裝置程式代碼透過瀏覽器手動登入。

az login --use-device-code

建立新的 Python 環境

首先,您必須建立新的 Python 環境,以用來安裝本教學課程所需的套件。 請勿將套件安裝到您的全域 Python 安裝中。 安裝 Python 套件時,您應該一律使用虛擬或 conda 環境,否則您可能會破壞 Python 的全域安裝。

如有需要,請安裝 Python

我們建議使用 Python 3.10 或更新版本,但至少需要 Python 3.8。 如果您未安裝適當的 Python 版本,可以遵循 VS Code Python 教學課程中的指示,以了解在作業系統上安裝 Python 的最簡單方式。

建立虛擬環境

如果您已安裝 Python 3.10 或更高版本,您可以使用下列命令來建立虛擬環境:

py -3 -m venv .venv
.venv\scripts\activate

啟用 Python 環境表示,當您命令列執行 pythonpip,將會使用應用程式的 .venv 資料夾中所包含的 Python 解譯器。

注意

您可以使用 deactivate 命令來結束 Python 虛擬環境,並可以稍後視需要重新啟用它。

您也可以使用 conda建立新的 Python 環境:

conda create -n online-evaluation
conda activate online-evaluation

安裝必要的套件:

pip install azure-identity azure-ai-projects azure-ai-ml

提示

您可以選擇性地使用 pip install azure-ai-evaluation 程式碼優先體驗來擷取程式代碼中內建評估工具的評估工具識別碼。 若要瞭解如何執行這項操作,請參閱 從評估工具連結庫指定評估工具。

設定您產生的 AI 應用程式的追蹤

在設定在線評估之前,請確定您必須先 設定產生 AI 應用程式的追蹤。

在追蹤數據中使用服務名稱

若要透過 Application Insights 中的唯一標識碼來識別您的應用程式,您可以在追蹤資料中使用服務名稱 OpenTelemetry 屬性。 如果您要將數據從多個應用程式記錄到相同的 Application Insights 資源,而且您想要區分它們,這特別有用。 例如,假設您有兩個應用程式: App-1App-2,且追蹤已設定為將數據記錄至相同的 Application Insights 資源。 也許您想要將 App-1 設定為依 相關性 持續評估,而 App-2 會持續受到 基礎性評估。 您可以使用服務名稱來區分在線評估組態中的應用程式。

若要設定服務名稱屬性,您可以依照步驟直接在應用程式程式代碼中執行此動作,請參閱 使用不同的資源使用多個追蹤提供者。 或者,您可以在部署應用程式之前設定環境變數 OTEL_SERVICE_NAME 。 若要深入瞭解如何使用服務名稱,請參閱 KEY環境變數 和服務 資源語意慣例

如需使用服務名稱來區分您產生的 AI 應用程式的詳細資訊,請參閱 追蹤

查詢 Application Insights 中儲存的追蹤數據

使用 Kusto 查詢語言 (KQL),您可以從 Application Insights 查詢您產生的 AI 應用程式的追蹤數據,以用於持續在線評估。 如果您使用 Azure AI 追蹤套件 來追蹤您的產生 AI 應用程式,您可以使用下列 Kusto 查詢:

重要

線上評估服務所使用的 KQL 查詢必須輸出下列資料列: operation_Idoperation_ParentIdgen_ai_response_id。 此外,每個評估工具都有自己的輸入數據需求。 KQL 查詢必須輸出這些數據行,才能做為評估工具本身的輸入。 如需評估工具的數據需求清單,請參閱 內建評估工具的數據需求。

let gen_ai_spans = (
    dependencies
    | where isnotnull(customDimensions["gen_ai.system"])
    | extend response_id = tostring(customDimensions["gen_ai.response.id"])
    | project id, operation_Id, operation_ParentId, timestamp, response_id
);
let gen_ai_events = (
    traces
    | where message in ("gen_ai.choice", "gen_ai.user.message", "gen_ai.system.message")
        or tostring(customDimensions["event.name"]) in ("gen_ai.choice", "gen_ai.user.message", "gen_ai.system.message")
    | project 
        id = operation_ParentId, 
        operation_Id, 
        operation_ParentId, 
        user_input = iff(
            message == "gen_ai.user.message" or tostring(customDimensions["event.name"]) == "gen_ai.user.message", 
            parse_json(iff(message == "gen_ai.user.message", tostring(customDimensions["gen_ai.event.content"]), message)).content, 
            ""
        ), 
        system = iff(
            message == "gen_ai.system.message" or tostring(customDimensions["event.name"]) == "gen_ai.system.message", 
            parse_json(iff(message == "gen_ai.system.message", tostring(customDimensions["gen_ai.event.content"]), message)).content, 
            ""
        ), 
        llm_response = iff(
            message == "gen_ai.choice", 
            parse_json(tostring(parse_json(tostring(customDimensions["gen_ai.event.content"])).message)).content, 
            iff(tostring(customDimensions["event.name"]) == "gen_ai.choice", parse_json(parse_json(message).message).content, "")
        )
    | summarize 
        operation_ParentId = any(operation_ParentId), 
        Input = maxif(user_input, user_input != ""), 
        System = maxif(system, system != ""), 
        Output = maxif(llm_response, llm_response != "") 
    by operation_Id, id
);
gen_ai_spans
| join kind=inner (gen_ai_events) on id, operation_Id
| project Input, System, Output, operation_Id, operation_ParentId, gen_ai_response_id = response_id

如果您在產生 AI 應用程式中使用 OTEL_SERVICE_NAME 環境變數來設定服務名稱,您可以在線上評估排程內查詢 cloud_RoleName ,方法是將下列這一行新增至 Kusto (KQL) 查詢:

| where cloud_RoleName == "service_name"

您可以選擇性地在 Kusto 查詢中使用 sample 運算符或 take 運算符,使其只會傳回追蹤的子集。 由於 AI 輔助評估的規模可能非常昂貴,因此這種方法可協助您只評估數據的隨機樣本(或 n 追蹤)來控制成本。

使用 Azure AI Project SDK 設定在線評估

您可以透過 Python API 向 Azure AI Project SDK 提交在線評估排程工作。 請參閱下列腳本,瞭解如何使用效能和品質(AI 輔助)評估工具來設定在線評估。 若要檢視支援評估工具的完整清單,請參閱 使用 Azure AI 評估 SDK 進行評估。 若要瞭解如何使用自定義評估工具,請參閱 自定義評估工具

從匯入必要的套件和設定必要的變數開始:

from azure.ai.projects import AIProjectClient 
from azure.identity import DefaultAzureCredential 
from azure.ai.projects.models import ( 
    ApplicationInsightsConfiguration,
    EvaluatorConfiguration,
    EvaluationSchedule,
    RecurrenceTrigger,
)
from azure.ai.evaluation import CoherenceEvaluator 

# This sample includes the setup for an online evaluation schedule using the Azure AI Project SDK and Azure AI Evaluation SDK
# The schedule is configured to run daily over the collected trace data while running two evaluators: CoherenceEvaluator and RelevanceEvaluator
# This sample can be modified to fit your application's requirements

# Name of your online evaluation schedule
SAMPLE_NAME = "online_eval_name"

# Connection string to your Azure AI Foundry project
# Currently, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>"
PROJECT_CONNECTION_STRING = "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>"

# Your Application Insights resource ID
APPLICATION_INSIGHTS_RESOURCE_ID = "appinsights_resource_id"

# Kusto Query Language (KQL) query to query data from Application Insights resource
# This query is compatible with data logged by the Azure AI Inferencing Tracing SDK (linked in documentation)
# You can modify it depending on your data schema
# The KQL query must output these required columns: operation_ID, operation_ParentID, and gen_ai_response_id
# You can choose which other columns to output as required by the evaluators you are using
KUSTO_QUERY = "let gen_ai_spans=(dependencies | where isnotnull(customDimensions[\"gen_ai.system\"]) | extend response_id = tostring(customDimensions[\"gen_ai.response.id\"]) | project id, operation_Id, operation_ParentId, timestamp, response_id); let gen_ai_events=(traces | where message in (\"gen_ai.choice\", \"gen_ai.user.message\", \"gen_ai.system.message\") or tostring(customDimensions[\"event.name\"]) in (\"gen_ai.choice\", \"gen_ai.user.message\", \"gen_ai.system.message\") | project id= operation_ParentId, operation_Id, operation_ParentId, user_input = iff(message == \"gen_ai.user.message\" or tostring(customDimensions[\"event.name\"]) == \"gen_ai.user.message\", parse_json(iff(message == \"gen_ai.user.message\", tostring(customDimensions[\"gen_ai.event.content\"]), message)).content, \"\"), system = iff(message == \"gen_ai.system.message\" or tostring(customDimensions[\"event.name\"]) == \"gen_ai.system.message\", parse_json(iff(message == \"gen_ai.system.message\", tostring(customDimensions[\"gen_ai.event.content\"]), message)).content, \"\"), llm_response = iff(message == \"gen_ai.choice\", parse_json(tostring(parse_json(tostring(customDimensions[\"gen_ai.event.content\"])).message)).content, iff(tostring(customDimensions[\"event.name\"]) == \"gen_ai.choice\", parse_json(parse_json(message).message).content, \"\")) | summarize operation_ParentId = any(operation_ParentId), Input = maxif(user_input, user_input != \"\"), System = maxif(system, system != \"\"), Output = maxif(llm_response, llm_response != \"\") by operation_Id, id); gen_ai_spans | join kind=inner (gen_ai_events) on id, operation_Id | project Input, System, Output, operation_Id, operation_ParentId, gen_ai_response_id = response_id"

接下來,定義用戶端和 Azure OpenAI GPT 部署(例如 ), GPT-4以用來執行在線評估排程。 此外,請連線到 Application Insights 資源:

# Connect to your Azure AI Foundry Project
project_client = AIProjectClient.from_connection_string(
    credential=DefaultAzureCredential(),
    conn_str=PROJECT_CONNECTION_STRING
)

# Connect to your Application Insights resource 
app_insights_config = ApplicationInsightsConfiguration(
    resource_id=APPLICATION_INSIGHTS_RESOURCE_ID,
    query=KUSTO_QUERY
)

# Connect to your Azure OpenAI Service resource. You must use a GPT model deployment for this example.
deployment_name = "gpt-4"
api_version = "2024-08-01-preview"

# This is your Azure OpenAI Service connection name, which can be found in your Azure AI Foundry project under the 'Models + Endpoints' tab.
default_connection = project_client.connections._get_connection(
    "aoai_connection_name"
)

model_config = {
    "azure_deployment": deployment_name,
    "api_version": api_version,
    "type": "azure_openai",
    "azure_endpoint": default_connection.properties["target"]
}

接下來,設定您想要使用的評估工具:

# RelevanceEvaluator
# id for each evaluator can be found in your Azure AI Foundry registry - please see documentation for more information
# init_params is the configuration for the model to use to perform the evaluation
# data_mapping is used to map the output columns of your query to the names required by the evaluator
relevance_evaluator_config = EvaluatorConfiguration(
    id="azureml://registries/azureml-staging/models/Relevance-Evaluator/versions/4",
    init_params={"model_config": model_config},
    data_mapping={"query": "${data.Input}", "response": "${data.Output}"}
)

# CoherenceEvaluator
coherence_evaluator_config = EvaluatorConfiguration(
    id=CoherenceEvaluator.id,
    init_params={"model_config": model_config},
    data_mapping={"query": "${data.Input}", "response": "${data.Output}"}
)

最後,定義週期並建立排程:

注意:在必要步驟中,您已建立使用者指派的受控識別,以向 Application Insights 資源驗證在線評估排程。 AzureMSIClientId類別properties參數EvaluationSchedule中的 是clientId這個身分識別的 。

# Frequency to run the schedule
recurrence_trigger = RecurrenceTrigger(frequency="day", interval=1)

# Dictionary of evaluators
evaluators = {
    "relevance": relevance_evaluator_config,
    "coherence" : coherence_evaluator_config
}

name = SAMPLE_NAME
description = f"{SAMPLE_NAME} description"
# AzureMSIClientId is the clientID of the User-assigned managed identity created during set-up - see documentation for how to find it
properties = {"AzureMSIClientId": "your_client_id"}

# Configure the online evaluation schedule
evaluation_schedule = EvaluationSchedule(
    data=app_insights_config,
    evaluators=evaluators,
    trigger=recurrence_trigger,
    description=description,
    properties=properties)

# Create the online evaluation schedule 
created_evaluation_schedule = project_client.evaluations.create_or_replace_schedule(name, evaluation_schedule)
print(f"Successfully submitted the online evaluation schedule creation request - {created_evaluation_schedule.name}, currently in {created_evaluation_schedule.provisioning_state} state.")

在在線評估排程上執行作業

您可以將下列程式代碼新增至線上評估組態腳本,以取得、列出和停用在線評估排程:

警告:請在建立在線評估排程和執行 get_schedule() API 之間等候少量的時間(~30 秒)。

取得線上評估排程:

name = "<my-online-evaluation-name>"
get_evaluation_schedule = project_client.evaluations.get_schedule(name)

列出所有線上評估排程:

count = 0
for evaluation_schedule in project_client.evaluations.list_schedule():
    count += 1
        print(f"{count}. {evaluation_schedule.name} "
        f"[IsEnabled: {evaluation_schedule.is_enabled}]")
        print(f"Total evaluation schedules: {count}")

停用 (虛刪除) 線上評估排程:

name = "<my-online-evaluation-name>"
project_client.evaluations.disable_schedule(name)