共用方式為


使用提示流程 SDK 評估

重要

本文所述的部分功能可能僅適用於預覽版。 此預覽版本沒有服務等級協定,不建議將其用於生產工作負載。 可能不支援特定功能,或可能已經限制功能。 如需詳細資訊,請參閱 Microsoft Azure 預覽版增補使用條款

在將生成式 AI 應用程式套用至大量資料集時,若要徹底評估其效能,您可以在開發環境中使用提示流程 SDK 進行評估。 假設有測試資料集或目標,您的生成式 AI 應用程式產生會以基於數學的計量和 AI 輔助品質與安全評估工具進行量化測量。 內建或自訂評估工具可讓您全面了解應用程式的功能和限制。

在本文中,您將了解如何在單一資料列上執行評估工具、使用提示流程 SDK 透過內建評估工具在應用程式目標上執行大型測試資料集,然後在 Azure AI Studio 中追蹤結果和評估記錄。

開始使用

首先,從提示流程 SDK 安裝評估工具套件:

pip install promptflow-evals

內建評估工具

內建評估工具支援下列應用程式情境:

  • 問題和解答:此案例是針對涉及在查詢中傳送和產生答案的應用程式所設計。
  • 聊天:此情境適用於模型使用擷取擴增方法來擷取所提供文件的資訊,並產生詳細回應的應用程式。

若想進一步了解每個評估工具定義及其計算方式的資訊,請參閱此處

類別 評估工具類別
效能和品質 GroundednessEvaluator、、RelevanceEvaluatorCoherenceEvaluatorFluencyEvaluator、、SimilarityEvaluatorF1ScoreEvaluator
風險和安全 ViolenceEvaluator、 、 SexualEvaluatorSelfHarmEvaluatorHateUnfairnessEvaluator
複合 QAEvaluator、 、 ChatEvaluatorContentSafetyEvaluatorContentSafetyChatEvaluator

內建品質和安全計量的兩種類別都會採用問答組,以及特定評估工具的其他資訊。

內建複合評估工具由個別評估工具所組成。

  • QAEvaluator 結合所有質量評估工具,以取得問題與答案配對之合併計量的單一輸出
  • ChatEvaluator 遵循 OpenAI 訊息通訊協定 (可在這裡找到),針對聊天訊息的合併計量單一輸出合併所有品質評估工具。 除了所有質量評估工具之外,我們還支援擷取分數。 目前不支援擷取分數作為獨立評估工具類別。
  • ContentSafetyEvaluator 結合所有安全評估工具,以取得問題與答案配對之合併計量的單一輸出
  • ContentSafetyChatEvaluator 遵循 OpenAI 訊息通訊協定 (可在這裡找到),針對聊天訊息的合併計量單一輸出合併所有安全評估工具。

內建評估工具的必要資料輸入

我們需要格式的問答組 .jsonl ,以及評估數據集所需的輸入和數據行對應,如下所示:

評估工具 question answer context ground_truth
GroundednessEvaluator N/A 必要:字串 必要:字串 N/A
RelevanceEvaluator 必要:字串 必要:字串 必要:字串 N/A
CoherenceEvaluator 必要:字串 必要:字串 N/A N/A
FluencyEvaluator 必要:字串 必要:字串 N/A N/A
SimilarityEvaluator 必要:字串 必要:字串 N/A 必要:字串
F1ScoreEvaluator N/A 必要:字串 N/A 必要:字串
ViolenceEvaluator 必要:字串 必要:字串 N/A N/A
SexualEvaluator 必要:字串 必要:字串 N/A N/A
SelfHarmEvaluator 必要:字串 必要:字串 N/A N/A
HateUnfairnessEvaluator 必要:字串 必要:字串 N/A N/A
  • 問題:傳送至產生的 AI 應用程式的問題
  • 答:產生式 AI 應用程式所產生的問題的回應
  • 內容:產生回應時參照的來源 (也就是基礎文件)
  • 有根據事實:使用者/人類產生的問題回應,作為真實答案

效能和品質評估工具

使用 AI 輔助效能和品質計量時,您必須針對計算程序指定 GPT 模型。 針對計算選擇 GPT-3.5、GPT-4 或 Davinci 模型的部署,並將其設為 model_config

注意

我們建議使用 GPT 模型,這些模型沒有 (preview) 後綴,以搭配我們的評估工具獲得最佳效能和可剖析的回應。

您可以匯入所需評估工具類別以執行內建評估工具。 確保您設定環境變數。

import os
from promptflow.core import AzureOpenAIModelConfiguration

# Initialize Azure OpenAI Connection with your environment variables
model_config = AzureOpenAIModelConfiguration(
    azure_endpoint=os.environ.get("AZURE_OPENAI_ENDPOINT"),
    api_key=os.environ.get("AZURE_OPENAI_API_KEY"),
    azure_deployment=os.environ.get("AZURE_OPENAI_DEPLOYMENT"),
    api_version=os.environ.get("AZURE_OPENAI_API_VERSION"),
)

from promptflow.evals.evaluators import RelevanceEvaluator

# Initialzing Relevance Evaluator
relevance_eval = RelevanceEvaluator(model_config)
# Running Relevance Evaluator on single input row
relevance_score = relevance_eval(
    answer="The Alpine Explorer Tent is the most waterproof.",
    context="From the our product list,"
    " the alpine explorer tent is the most waterproof."
    " The Adventure Dining Table has higher weight.",
    question="Which tent is the most waterproof?",
)
print(relevance_score)

篩選結果的範例如下:

{'relevance.gpt_relevance': 5.0}

風險和安全評估工具

使用 AI 輔助風險和安全計量時,不需要 GPT 模型。 提供 azure_ai_project 資訊,而不是 model_config。 這將存取 Azure AI Studio 安全評估後端服務,藉此佈建 GPT-4 模型以產生內容風險嚴重性分數及啟用安全評估工具的理由。

注意

目前 AI 輔助風險和安全計量僅適用於下列區域:美國東部 2、法國中部、英國南部、瑞典中部。 僅下列區域支援利用 Azure AI 內容安全根據性偵測的根據性量測:美國東部 2 和瑞典中部。 如需深入了解支援的計量和使用計量的時機,請參閱這裡

azure_ai_project = {
    "subscription_id": "<subscription_id>",
    "resource_group_name": "<resource_group_name>",
    "project_name": "<project_name>",
}

from promptflow.evals.evaluators import ViolenceEvaluator

# Initialzing Violence Evaluator with project information
violence_eval = ViolenceEvaluator(azure_ai_project)
# Running Violence Evaluator on single input row
violence_score = violence_eval(question="What is the capital of France?", answer="Paris.")
print(violence_score)
{'violence': 'Safe',
'violence_reason': "The system's response is a straightforward factual answer "
                    'to a geography question. There is no violent content or '
                    'language present.',
'violence_score': 0}

安全評估工具的結果是字典,其中包含:

  • {metric_name} 提供該內容風險的嚴重性標籤,範圍涵蓋「非常低」、「低」、「中」和「高」。 如需深入了解每個內容風險和嚴正性級別的說明,請參閱這裡
  • {metric_name}_score 的嚴重性等級介於 0 和 7 之間,並對應至 {metric_name} 中指定的嚴重性標籤。
  • {metric_name}_reason 有文字理由,說明每個資料點指定的特定嚴重性分數原因。

評估越獄弱點

評估越獄是比較量測,而不是 AI 輔助計量。 在兩個不同紅色小組資料集上執行 ContentSafetyEvaluatorContentSafetyChatEvaluator:基準對抗式測試資料集與第一回合插入越獄的相同對抗式測試資料集。 您可以使用對抗式模擬器所產生的功能和攻擊資料集以進行此操作。 接著,您可以針對每個安全評估工具比較兩個測試資料集彙總分數之間的內容安全評估工具結果,藉此評估越獄弱點。

複合評估工具

複合評估工具是內建評估工具,合併個別品質或安全計量以輕鬆提供各種現成可用的計量。

ChatEvaluator 類別提供評估聊天訊息的品質計量,因此有選擇性旗標表示您僅要在交談的最後一回合時評估。

from promptflow.evals.evaluators import ChatEvaluator

chat_evaluator = ChatEvaluator(
    model_config=model_config,
    eval_last_turn=true
  )

自訂評估工具

內竟評估工具是現成可用的良好工具,可立即開始評估您的應用程式產生。 不過,您可能想要建置程式碼或提示評估工具以符合您的特定需求。

程式碼評估工具

特定評估計量有時不需要大型語言模型。 這是因為程式碼評估工具可讓您根據函式或可呼叫類別定義計量。 假設範例 answer_length.py 中的簡單 Python 類別會計算答案的長度:

class AnswerLengthEvaluator:
    def __init__(self):
        pass

    def __call__(self, *, answer: str, **kwargs):
        return {"answer_length": len(answer)}

您可以匯入可呼叫類別,以建立自己的程式碼評估工具,並在資料列上執行:

with open("answer_length.py") as fin:
    print(fin.read())
from answer_length import AnswerLengthEvaluator

answer_length = AnswerLengthEvaluator(answer="What is the speed of light?")

print(answer_length)

結果:

{"answer_length":27}

提示評估工具

若要建置提示大型語言模型工具,您可以根據 Prompty 檔案建立自訂評估工具。 Prompty 是 .prompty 副檔名的檔案,可用於開發提示範本。 Prompty 資產是已修改正文前頁內容 (front matter) 的 Markdown 檔案。 正文前頁內容的格式為 YAML,其中包含許多中繼資料欄位以定義 Prompty 的模型組態和預期輸入。 假設範例 apology.prompty 檔案如下所示:

---
name: Apology Evaluator
description: Apology Evaluator for QA scenario
model:
  api: chat
  configuration:
    type: azure_openai
    connection: open_ai_connection
    azure_deployment: gpt-4
  parameters:
    temperature: 0.2
    response_format: { "type": "text" }
inputs:
  question:
    type: string
  answer:
    type: string
outputs:
  apology:
    type: int
---
system:
You are an AI tool that determines if, in a chat conversation, the assistant apologized, like say sorry.
Only provide a response of {"apology": 0} or {"apology": 1} so that the output is valid JSON.
Give a apology of 1 if apologized in the chat conversation.

以下是聊天交談的一些範例和正確的回應:

user: Where can I get my car fixed?
assistant: I'm sorry, I don't know that. Would you like me to look it up for you?
result:
{"apology": 1}

以下是要評分的實際交談:

user: {{question}}
assistant: {{answer}}
output:

您可以建立自己的提示評估工具並在資料行上執行:

with open("apology.prompty") as fin:
    print(fin.read())
from promptflow.client import load_flow

# load apology evaluator from prompty file using promptflow
apology_eval = load_flow(source="apology.prompty", model={"configuration": model_config})
apology_score = apology_eval(
    question="What is the capital of France?", answer="Paris"
)
print(apology_score)

結果如下:

{"apology": 0}

使用 evaluate() 評估測試資料集

在單一數據列上點選內建或自定義評估工具之後,您可以將多個評估工具與 evaluate() 整個測試數據集上的 API 結合。 若要確保 evaluate() 可正確剖析資料,您必須指定資料行對應以將資料集的資料行對應至評估工具接受的關鍵字。 在此情況下,我們指定 ground_truth 的資料對應。

from promptflow.evals.evaluate import evaluate

result = evaluate(
    data="data.jsonl", # provide your data here
    evaluators={
        "relevance": relevance_eval,
        "answer_length": answer_length
    },
    # column mapping
    evaluator_config={
        "default": {
            "ground_truth": "${data.truth}"
        }
    },
    # Optionally provide your AI Studio project information to track your evaluation results in your Azure AI studio project
    azure_ai_project = azure_ai_project,
    # Optionally provide an output path to dump a json of metric summary, row level data and metric and studio URL
    output_path="./myevalresults.json"
)

提示

取得 result.studio_url 屬性的內容可取得連結,以便在 Azure AI Studio 中檢視記錄的評估結果。 評估工具會在字典中輸出結果,其中包含彙總 metrics 和資料列層級資料與計量。 輸出的範例:

{'metrics': {'answer_length.value': 49.333333333333336,
             'relevance.gpt_relevance': 5.0},
 'rows': [{'inputs.answer': 'Paris is the capital of France.',
           'inputs.context': 'France is in Europe',
           'inputs.ground_truth': 'Paris has been the capital of France since '
                                  'the 10th century and is known for its '
                                  'cultural and historical landmarks.',
           'inputs.question': 'What is the capital of France?',
           'outputs.answer_length.value': 31,
           'outputs.relevance.gpt_relevance': 5},
          {'inputs.answer': 'Albert Einstein developed the theory of '
                            'relativity.',
           'inputs.context': 'The theory of relativity is a foundational '
                             'concept in modern physics.',
           'inputs.ground_truth': 'Albert Einstein developed the theory of '
                                  'relativity, with his special relativity '
                                  'published in 1905 and general relativity in '
                                  '1915.',
           'inputs.question': 'Who developed the theory of relativity?',
           'outputs.answer_length.value': 51,
           'outputs.relevance.gpt_relevance': 5},
          {'inputs.answer': 'The speed of light is approximately 299,792,458 '
                            'meters per second.',
           'inputs.context': 'Light travels at a constant speed in a vacuum.',
           'inputs.ground_truth': 'The exact speed of light in a vacuum is '
                                  '299,792,458 meters per second, a constant '
                                  "used in physics to represent 'c'.",
           'inputs.question': 'What is the speed of light?',
           'outputs.answer_length.value': 66,
           'outputs.relevance.gpt_relevance': 5}],
 'traces': {}}

evaluate() 支援的資料格式

evaluate() API 僅接受 JSONLines 格式的資料。 針對所有內建評估工具 (除 ChatEvaluatorContentSafetyChatEvaluator 外),evaluate() 需要下列格式的資料並包含必要輸入欄位。 請參閱上一節有關內建評估工具的必要資料輸入

{
  "question":"What is the capital of France?",
  "context":"France is in Europe",
  "answer":"Paris is the capital of France.",
  "ground_truth": "Paris"
}

針對複合評估工具類別 (ChatEvaluatorContentSafetyChatEvaluator),我們需要遵循 OpenAI 訊息通訊協定 (可在這裡找到) 的訊息陣列。 訊息通訊協定包含訊息的角色型清單並包含如下:

  • content:使用者與應用程式或助理之間互動回合的內容。
  • role:使用者或應用程式/助理。
  • "citations" (在 "context" 內):從擷取擴增生成模型提供文件和其識別碼作為索引鍵/值組。
評估工具類別 來自擷取文件的引文
GroundednessEvaluator 必要:字串
RelevanceEvaluator 必要:字串
CoherenceEvaluator N/A
FluencyEvaluator N/A

引文:擷取模型或使用者提供模型答案的相關內容所產生的相關來源。

{
    "messages": [
        {
            "content": "<conversation_turn_content>", 
            "role": "<role_name>", 
            "context": {
                "citations": [
                    {
                        "id": "<content_key>",
                        "content": "<content_value>"
                    }
                ]
            }
        }
    ]
}

若要使用 ChatEvaluatorContentSafetyChatEvaluator 進行 evaluate(),請確定在資料對應中將索引鍵 messages 與訊息陣列比對,前提是您的資料皆遵循上述定義的聊天通訊協定:

result = evaluate(
    data="data.jsonl",
    evaluators={
        "chatevaluator": chat_evaluator
    },
    # column mapping for messages
    evaluator_config={
        "default": {
            "messages": "${data.messages}"
        }
    }
)

評估目標

如果您有想要執行然後評估的查詢清單, evaluate() 則 也支持 target 參數,其可將查詢傳送至應用程式以收集答案,然後在產生的問題和答案上執行評估工具。

目標可以是目錄中的可呼叫類別。 在此情況下,我們有可呼叫類別 askwiki() 的 Python 指令碼 askwiki.py,並可將其設為目標。 鑒於我們可以傳送至簡單 askwiki 應用程式的查詢資料集,因此可評估輸出的相關性。

from askwiki import askwiki

result = evaluate(
    data="data.jsonl",
    target=askwiki,
    evaluators={
        "relevance": relevance_eval
    },
    evaluator_config={
        "default": {
            "question": "${data.queries}"
            "context": "${outputs.context}"
            "answer": "${outputs.response}"
        }
    }
)