使用 Vertex AI 評估 RAG 系統

1. 總覽

在本實驗室中,您將學習如何為檢索增強生成 (RAG) 系統建構評估管道。您將使用 Vertex AI Gen AI Evaluation Service 建立自訂評估標準,並為問答工作建構評估架構。

您將使用 Stanford Question Answering Dataset (SQuAD 2.0) 的範例準備評估資料集、設定無參考和有參考的評估,並解讀結果。在本實驗室結束時,您將瞭解如何評估 RAG 系統,以及為何選擇特定評估方法。

資料集基礎

我們會使用精心設計的範例,涵蓋 SQuAD 2.0 問答資料集中的多個領域:

  • 神經科學:在科學情境中測試技術準確度
  • 歷史:評估歷史敘述的準確度
  • 地理:評估地域和政治知識

這項多元性有助於您瞭解評估方法如何普遍適用於不同主題領域。

參考資料

課程內容

在本實驗室中,您將瞭解如何執行下列工作:

  • 準備 RAG 系統的評估資料集。
  • 使用有根據和相關性等指標,實作無參考評估。
  • 使用語意相似度指標,套用以參照為準的評估。
  • 建立自訂評估指標,並提供詳細的評分標準。
  • 解讀並以圖表呈現評估結果,做為模型選擇的依據。

2. 專案設定

Google 帳戶

如果沒有個人 Google 帳戶,請建立 Google 帳戶

使用個人帳戶,而非公司或學校帳戶。

登入 Google Cloud 控制台

使用個人 Google 帳戶登入 Google Cloud 控制台

啟用計費功能

兌換 $5 美元的 Google Cloud 抵免額 (選用)

如要參加這個研討會,您需要有具備部分抵免額的帳單帳戶。如果您打算使用自己的帳單,可以略過這個步驟。

  1. 按一下這個連結,然後登入個人 Google 帳戶。畫面顯示的內容如下:按這裡前往「抵免額」頁面
  2. 按一下「按這裡存取抵免額」按鈕。系統會將您帶往設定帳單資料的頁面 設定帳單資料頁面
  3. 按一下「確認」。您現在已連結至 Google Cloud Platform 試用帳單帳戶。帳單總覽的螢幕截圖

設定個人帳單帳戶

如果使用 Google Cloud 抵免額設定計費,可以略過這個步驟。

如要設定個人帳單帳戶,請前往這裡在 Cloud 控制台中啟用帳單

注意事項:

  • 完成本實驗室的 Cloud 資源費用應不到 $1 美元。
  • 您可以按照本實驗室結尾的步驟刪除資源,避免產生額外費用。
  • 新使用者可享有價值 $300 美元的免費試用期

建立專案 (選用)

如果沒有要用於本實驗室的現有專案,請在這裡建立新專案

3. 什麼是檢索增強生成 (RAG)?

RAG 是一種技術,可提升大型語言模型 (LLM) 回覆的事實準確度和關聯性。這項技術會將 LLM 連結至外部知識庫,確保回覆內容以可驗證的特定資訊為依據。

這項程序包含下列步驟:

  1. 將使用者的問題轉換為數值表示法 (嵌入)。
  2. 在知識庫中搜尋具有類似嵌入的文件。
  3. 將這些相關文件連同原始問題提供給 LLM 做為背景資訊,以生成答案。

進一步瞭解 RAG

RAG 評估為何如此複雜?

評估 RAG 系統與評估傳統語言模型不同。

多重元件挑戰:RAG 系統結合了三項作業,每一項都可能發生故障:

  • 檢索品質:系統是否找到正確的背景文件?
  • 背景資訊運用:模型是否有效運用擷取的資訊?
  • 生成品質:最終回覆是否撰寫得當、實用且準確?

如果這些元件有任何一個無法正常運作,回應就可能失敗。舉例來說,系統可能會擷取正確的情境,但模型會忽略該情境。或者,模型可能會生成內容正確但無關的回覆,因為擷取的脈絡資訊不相關。

4. 設定 Vertex AI Workbench 環境

首先,請啟動新的筆記本環境,我們將在其中執行評估 RAG 系統所需的程式碼。

  1. 前往 Cloud 控制台的「API 和服務」頁面
  2. 按一下「Vertex AI API」的「啟用」Vertex 資訊主頁

存取 Vertex AI Workbench

  1. 前往 Google Cloud 控制台,依序點選「導覽選單」圖示 ☰ >「Vertex AI」 >「Workbench」,即可前往 Vertex AI
  2. 建立新的 Workbench 執行個體。建立 Workbench
  3. 將 Workbench 執行個體命名為 evaluation-workbench
  4. 如果尚未設定區域和時區,請選取這些值。
  5. 按一下「建立」命名 Workbench
  6. 等待工作台設定完成。這可能需要幾分鐘的時間。等待 Workbench
  7. 工作台佈建完成後,按一下「open jupyterlab」開啟 Workbench
  8. 在工作台中,建立新的 Python3 筆記本。建立筆記本

如要進一步瞭解這個環境的功能和特性,請參閱 Vertex AI Workbench 官方說明文件。

安裝 Vertex AI 評估 SDK

現在安裝專用的評估 SDK,提供 RAG 評估工具。

  1. 在筆記本的第一個儲存格中,新增並執行下列匯入陳述式 (按 SHIFT+ENTER 鍵),安裝 Vertex AI SDK (含評估元件)。
    %pip install --upgrade --user --quiet google-cloud-aiplatform[evaluation]
    
    這會安裝 Vertex AI SDK,以及包含下列項目的評估擴充功能:
    • EvalTask:執行評估作業的主要類別
    • MetricPromptTemplateExamples:預先定義的評估指標
    • PointwiseMetric:用於建立自訂指標的架構
    • notebook_utils:用於分析結果的視覺化工具
  2. 重要事項:安裝完成後,您必須重新啟動核心,才能使用新套件。在 JupyterLab 視窗頂端的選單列中,依序前往「Kernel」 >「Restart Kernel」

5. 初始化 SDK 並匯入程式庫

您必須先設定環境,才能建構評估管道。包括設定專案詳細資料、初始化 Vertex AI SDK 以連線至 Google Cloud,以及匯入用於評估的專用 Python 程式庫。

  1. 定義評估工作的設定變數。在新的儲存格中,新增並執行下列程式碼,設定 PROJECT_IDLOCATIONEXPERIMENT 名稱,以便整理這次執行作業。
    import vertexai
    
    PROJECT_ID = "YOUR PROJECT ID"
    LOCATION = "YOUR LOCATION"  # @param {type:"string"}
    EXPERIMENT = "rag-eval-01"  # @param {type:"string"}
    
    if not PROJECT_ID or PROJECT_ID == "[your-project-id]":
        raise ValueError("Please set your PROJECT_ID")
    
  2. 初始化 Vertex AI SDK。在新的儲存格中新增並執行下列程式碼。
    vertexai.init(project=PROJECT_ID, location=LOCATION)
    
    這個步驟會驗證筆記本,並將其連結至 Google Cloud 專案。
  3. 在下一個儲存格中執行下列程式碼,從評估 SDK 匯入必要類別:
    import pandas as pd
    from vertexai.evaluation import EvalTask, MetricPromptTemplateExamples, PointwiseMetric
    from vertexai.preview.evaluation import notebook_utils
    
    以下是各項匯入作業的摘要:
    • pandas:用於在 DataFrame 中建立及管理資料。
    • EvalTask:執行評估工作的核心類別。
    • MetricPromptTemplateExamples:提供 Google 預先定義的評估指標。
    • PointwiseMetric:用於建立自訂指標的架構。
    • notebook_utils:用於將結果視覺化的工具集合。

6. 準備評估資料集

結構良好的資料集是任何可靠評估的基礎。對於 RAG 系統,資料集中的每個範例都需要兩個重要欄位:

  • 提示:這是提供給語言模型的總輸入內容。您必須將使用者的問題與 RAG 系統擷取的內容合併 (prompt = User Question + Retrieved Context)。這項步驟非常重要,因為評估服務需要知道模型用來生成答案的資訊。
  • 回覆:這是 RAG 模型產生的最終答案。

如要獲得統計上可靠的結果,建議使用約 100 個樣本的資料集。在本實驗室中,您將使用小型資料集來示範這個程序。

現在來建立資料集。您會先看到問題清單,以及 RAG 系統的 retrieved_contexts。接著定義兩組答案:一組來自效能良好的模型 (generated_answers_by_rag_a),另一組來自效能不佳的模型 (generated_answers_by_rag_b)。

最後,您會按照上述結構,將這些片段合併為兩個 pandas DataFrame,分別是 eval_dataset_rag_aeval_dataset_rag_b

  1. 在新的儲存格中新增並執行下列程式碼,定義問題和兩組 generated_answers。
    questions = [
        "Which part of the brain does short-term memory seem to rely on?",
        "What provided the Roman senate with exuberance?",
        "What area did the Hasan-jalalians command?",
    ]
    
    generated_answers_by_rag_a = [
        "frontal lobe and the parietal lobe",
        "The Roman Senate was filled with exuberance due to successes against Catiline.",
        "The Hasan-Jalalians commanded the area of Syunik and Vayots Dzor.",
    ]
    
    generated_answers_by_rag_b = [
        "Occipital lobe",
        "The Roman Senate was subdued because they had food poisoning.",
        "The Galactic Empire commanded the state of Utah.",
    ]
    
    這會定義資料集的核心元件:問題、RAG 系統為每個問題擷取的長篇脈絡段落,以及兩個不同模型 (效能較高的模型 A 和效能較低的模型 B) 生成的答案。
  2. 定義 retrieved_contexts。在新的儲存格中新增並執行下列程式碼。
    retrieved_contexts = [
        "Short-term memory is supported by transient patterns of neuronal communication, dependent on regions of the frontal lobe (especially dorsolateral prefrontal cortex) and the parietal lobe. Long-term memory, on the other hand, is maintained by more stable and permanent changes in neural connections widely spread throughout the brain. The hippocampus is essential (for learning new information) to the consolidation of information from short-term to long-term memory, although it does not seem to store information itself. Without the hippocampus, new memories are unable to be stored into long-term memory, as learned from patient Henry Molaison after removal of both his hippocampi, and there will be a very short attention span. Furthermore, it may be involved in changing neural connections for a period of three months or more after the initial learning.",
        "In 62 BC, Pompey returned victorious from Asia. The Senate, elated by its successes against Catiline, refused to ratify the arrangements that Pompey had made. Pompey, in effect, became powerless. Thus, when Julius Caesar returned from a governorship in Spain in 61 BC, he found it easy to make an arrangement with Pompey. Caesar and Pompey, along with Crassus, established a private agreement, now known as the First Triumvirate. Under the agreement, Pompey's arrangements would be ratified. Caesar would be elected consul in 59 BC, and would then serve as governor of Gaul for five years. Crassus was promised a future consulship.",
        "The Seljuk Empire soon started to collapse. In the early 12th century, Armenian princes of the Zakarid noble family drove out the Seljuk Turks and established a semi-independent Armenian principality in Northern and Eastern Armenia, known as Zakarid Armenia, which lasted under the patronage of the Georgian Kingdom. The noble family of Orbelians shared control with the Zakarids in various parts of the country, especially in Syunik and Vayots Dzor, while the Armenian family of Hasan-Jalalians controlled provinces of Artsakh and Utik as the Kingdom of Artsakh.",
    ]
    
    現在您已擁有所有原始元件,接下來要將這些元件合併為評估服務所需的結構化 pandas DataFrame。
  3. 在新的儲存格中,新增並執行下列程式碼,即可建立 eval_dataset_rag_aeval_dataset_rag_b
    eval_dataset_rag_a = pd.DataFrame(
        {
        "prompt": [
                "Answer the question: " + question + " Context: " + item
                for question, item in zip(questions, retrieved_contexts)
        ],
        "response": generated_answers_by_rag_a,
        }
    )
    
    eval_dataset_rag_b = pd.DataFrame(
        {
        "prompt": [
                "Answer the question: " + question + " Context: " + item
                for question, item in zip(questions, retrieved_contexts)
        ],
        "response": generated_answers_by_rag_b,
        }
    )
    
  4. 在新儲存格中執行下列程式碼,即可查看模型 A 的資料集前幾列。
    eval_dataset_rag_a
    
    這是確保建立正確的實用做法。

7. 選取及建立指標

資料集準備就緒後,即可決定成效評估方式。您可以根據一或多個指標評估模型。每個指標都會評估模型回應的特定面向,例如事實準確度或關聯性。

您可以結合使用下列兩種指標:

  • 預先定義的指標:SDK 提供的現成指標,適用於常見的評估工作。
  • 自訂指標:您定義的指標,用於測試與用途相關的品質。

在本節中,您將瞭解 RAG 可用的預先定義指標。

探索預先定義的指標

SDK 內建多項指標,可評估問答系統。這些指標會使用語言模型做為「評估者」,根據一組指令為模型答案評分。

  1. 在新的儲存格中新增並執行下列程式碼,即可查看預先定義的指標名稱完整清單:
    MetricPromptTemplateExamples.list_example_metric_names()
    
    這會輸出可用指標清單,方便您直接使用。
  2. 如要瞭解這些指標的運作方式,可以檢查基礎提示範本。在新的儲存格中新增並執行下列程式碼,即可查看提供給評估 LLM 的 question_answering_quality 指標指令。
    # See the prompt example for one of the pointwise metrics
    print(MetricPromptTemplateExamples.get_prompt_template("question_answering_quality"))
    

8. 建立自訂指標

除了預先定義的指標,您也可以建立自訂指標,評估特定用途的條件。如要建立自訂指標,請撰寫提示範本,指示評估 LLM 如何評估回覆。

建立自訂指標的程序包含兩個步驟:

  1. 定義提示範本:包含評估人員 LLM 指示的字串。好的範本應包含明確的角色、評估標準、評分量表和預留位置 (例如 {prompt}{response})。
  2. 例項化 PointwiseMetric 物件:將提示範本字串包裝在這個類別中,並為指標命名。

您將建立兩個自訂指標,評估 RAG 系統回覆的關聯性和實用性。

  1. 定義關聯性指標的提示範本。這個範本提供詳細的評估標準,供評估者 LLM 使用。在新的儲存格中,新增並執行下列程式碼:
    relevance_prompt_template = """
    You are a professional writing evaluator. Your job is to score writing responses according to pre-defined evaluation criteria.
    
    You will be assessing relevance, which measures the ability to respond with relevant information when given a prompt.
    
    You will assign the writing response a score from 5, 4, 3, 2, 1, following the rating rubric and evaluation steps.
    
    ## Criteria
    Relevance: The response should be relevant to the instruction and directly address the instruction.
    
    ## Rating Rubric
    5 (completely relevant): Response is entirely relevant to the instruction and provides clearly defined information that addresses the instruction's core needs directly.
    4 (mostly relevant): Response is mostly relevant to the instruction and addresses the instruction mostly directly.
    3 (somewhat relevant): Response is somewhat relevant to the instruction and may address the instruction indirectly, but could be more relevant and more direct.
    2 (somewhat irrelevant): Response is minimally relevant to the instruction and does not address the instruction directly.
    1 (irrelevant): Response is completely irrelevant to the instruction.
    
    ## Evaluation Steps
    STEP 1: Assess relevance: is response relevant to the instruction and directly address the instruction?
    STEP 2: Score based on the criteria and rubrics.
    
    Give step by step explanations for your scoring, and only choose scores from 5, 4, 3, 2, 1.
    
    
    # User Inputs and AI-generated Response
    ## User Inputs
    ### Prompt
    {prompt}
    
    ## AI-generated Response
    {response}
    """
    
    
  2. 使用相同方法定義實用性指標的提示範本。在新的儲存格中新增並執行下列程式碼:
    helpfulness_prompt_template = """
    You are a professional writing evaluator. Your job is to score writing responses according to pre-defined evaluation criteria.
    
    You will be assessing helpfulness, which measures the ability to provide important details when answering a prompt.
    
    You will assign the writing response a score from 5, 4, 3, 2, 1, following the rating rubric and evaluation steps.
    
    ## Criteria
    Helpfulness: The response is comprehensive with well-defined key details. The user would feel very satisfied with the content in a good response.
    
    ## Rating Rubric
    5 (completely helpful): Response is useful and very comprehensive with well-defined key details to address the needs in the instruction and usually beyond what explicitly asked. The user would feel very satisfied with the content in the response.
    4 (mostly helpful): Response is very relevant to the instruction, providing clearly defined information that addresses the instruction's core needs.  It may include additional insights that go slightly beyond the immediate instruction.  The user would feel quite satisfied with the content in the response.
    3 (somewhat helpful): Response is relevant to the instruction and provides some useful content, but could be more relevant, well-defined, comprehensive, and/or detailed. The user would feel somewhat satisfied with the content in the response.
    2 (somewhat unhelpful): Response is minimally relevant to the instruction and may provide some vaguely useful information, but it lacks clarity and detail. It might contain minor inaccuracies. The user would feel only slightly satisfied with the content in the response.
    1 (unhelpful): Response is useless/irrelevant, contains inaccurate/deceptive/misleading information, and/or contains harmful/offensive content. The user would feel not at all satisfied with the content in the response.
    
    ## Evaluation Steps
    STEP 1: Assess comprehensiveness: does the response provide specific, comprehensive, and clearly defined information for the user needs expressed in the instruction?
    STEP 2: Assess relevance: When appropriate for the instruction, does the response exceed the instruction by providing relevant details and related information to contextualize content and help the user better understand the response.
    STEP 3: Assess accuracy: Is the response free of inaccurate, deceptive, or misleading information?
    STEP 4: Assess safety: Is the response free of harmful or offensive content?
    
    Give step by step explanations for your scoring, and only choose scores from 5, 4, 3, 2, 1.
    
    
    # User Inputs and AI-generated Response
    ## User Inputs
    ### Prompt
    {prompt}
    
    ## AI-generated Response
    {response}
    """
    
  3. 為兩個自訂指標建立 PointwiseMetric 物件的例項。這會將提示範本包裝成可重複使用的元件,以用於評估工作。在新的儲存格中新增並執行下列程式碼:
    relevance = PointwiseMetric(
        metric="relevance",
        metric_prompt_template=relevance_prompt_template,
    )
    
    helpfulness = PointwiseMetric(
        metric="helpfulness",
        metric_prompt_template=helpfulness_prompt_template,
    )
    

您現在有兩個新的可重複使用的指標 (relevancehelpfulness),可供評估工作使用。

9. 執行評估工作

資料集和指標準備就緒後,即可執行評估。方法是為要測試的每個資料集建立 EvalTask 物件。

EvalTask 會將評估執行作業的元件組合在一起:

  • dataset:包含提示和回應的 DataFrame。
  • 指標:要評估的指標清單。
  • 實驗:要將結果記錄至其中的 Vertex AI 實驗,有助於追蹤及比較執行作業。
  1. 為每個模型建立 EvalTask。這個物件會將資料集、指標和實驗名稱綁在一起。在新的儲存格中新增並執行下列程式碼,設定工作:
    rag_eval_task_rag_a = EvalTask(
        dataset=eval_dataset_rag_a,
        metrics=[
            "question_answering_quality",
            relevance,
            helpfulness,
            "groundedness",
            "safety",
            "instruction_following",
        ],
        experiment=EXPERIMENT,
    )
    
    rag_eval_task_rag_b = EvalTask(
        dataset=eval_dataset_rag_b,
        metrics=[
            "question_answering_quality",
            relevance,
            helpfulness,
            "groundedness",
            "safety",
            "instruction_following",
        ],
        experiment=EXPERIMENT,
    )
    
    您現在已設定兩個 EvalTask 物件,分別對應一組模型回覆。您提供的 metrics 清單展示了評估服務的一項重要功能:預先定義的指標 (例如 safety) 和自訂 PointwiseMetric 物件。
  2. 設定工作後,請呼叫 .evaluate() 方法來執行工作。這會將工作傳送至 Vertex AI 後端進行處理,可能需要幾分鐘才能完成。在新的儲存格中,新增並執行下列程式碼:
    result_rag_a = rag_eval_task_rag_a.evaluate()
    result_rag_b = rag_eval_task_rag_b.evaluate()
    

評估完成後,結果會儲存在 result_rag_aresult_rag_b 物件中,供我們在下一節中進行分析。

10. 分析結果

評估結果現已出爐。result_rag_aresult_rag_b 物件包含每個資料列的匯總分數和詳細說明。在這項工作中,您將使用 notebook_utils 的輔助函式分析這些結果。

查看匯總摘要

  1. 如要取得高層級總覽,請使用 display_eval_result() 輔助函式查看各項指標的平均分數。在新的儲存格中新增並執行下列程式碼,即可查看模型 A 的摘要:
    notebook_utils.display_eval_result(
        title="Model A Eval Result", eval_result=result_rag_a
    )
    
  2. 對模型 B 執行相同操作。在新的儲存格中新增並執行下列程式碼:
    notebook_utils.display_eval_result(
        title="Model B Eval Result",
        eval_result=result_rag_b,
    )
    

以圖表呈現評估結果

圖表可讓您更輕鬆地比較模型效能。您會使用兩種視覺化效果:

  • 雷達圖:顯示每個模型的整體成效「形狀」。形狀越大,表示整體效能越好。
  • 長條圖:直接並列比較各項指標。

這些視覺化內容可協助您比較模型的主觀品質,例如關聯性、根據基準生成內容的程度和實用性。

  1. 如要準備繪製圖表,請將結果合併為單一元組清單。每個元組都應包含模型名稱和對應的結果物件。在新的儲存格中,新增並執行下列程式碼:
    eval_results = []
    eval_results.append(("Model A", result_rag_a))
    eval_results.append(("Model B", result_rag_b))
    
  2. 現在,請產生雷達圖,一次比較所有指標的模式。在新的儲存格中新增並執行下列程式碼:
    notebook_utils.display_radar_plot(
        eval_results,
        metrics=[
        "question_answering_quality",
        "safety",
        "groundedness",
        "instruction_following",
        "relevance",
        "helpfulness",
        ],
    )
    
    形狀越大,表示整體效能越好。
  3. 如要直接比較各項指標,請產生長條圖。在新的儲存格中,新增並執行下列程式碼:
    notebook_utils.display_bar_plot(
        eval_results,
        metrics=[
        "question_answering_quality",
        "safety",
        "groundedness",
        "instruction_following",
        "relevance",
        "helpfulness",
        ],
    )
    
    這項視覺化功能可讓您輕鬆查看兩種模型之間的成效差距。

從視覺化圖表可清楚看出,模型 A 的成效 (雷達圖上的大型形狀和長條圖上的高長條) 優於模型 B。

查看個別執行個體的詳細說明

匯總分數會顯示整體成效。如要瞭解模型為何以特定方式運作,請查看評估 LLM 為每個範例產生的詳細說明。

  1. display_explanations() 輔助函式可讓您檢查個別結果。如要查看第二個範例 (num=2) 的詳細分類結果,請在新的儲存格中新增並執行下列程式碼:
    notebook_utils.display_explanations(result_rag_a, num=2)
    
  2. 您也可以使用這項功能,在所有範例中篩選特定指標。這有助於偵錯成效不佳的特定區域。如要瞭解模型 B 在 groundedness 指標上的表現為何如此不佳,請在新儲存格中新增並執行下列程式碼:
    notebook_utils.display_explanations(result_rag_b, metrics=["groundedness"])
    
    這項功能可針對模型失敗之處提供具體意見,有助於反覆改良模型。

11. 使用「黃金答案」進行參考評估

先前您執行的是無參考評估,也就是只根據提示判斷模型的回覆。這個方法很實用,但評估結果較為主觀。

現在,您將使用參照評估。這個方法會在資料集中新增「正確答案」(也稱為參考答案)。將模型的回覆與基準真相答案進行比較,可更客觀地評估模型成效。這項功能可讓您評估:

  • 事實正確性:模型回覆是否與正確答案中的事實一致?
  • 語意相似度:模型答案與正確答案是否具有相同含意?
  • 完整性:模型的回覆是否包含黃金答案的所有重要資訊?

準備參照的資料集

如要執行參照評估,您需要在資料集中的每個範例新增「正確答案」。

首先定義 golden_answers 清單。比較黃金答案與模型 A 的答案,即可看出這個方法的價值:

  • 問題 1 (Brain):生成的答案與正確答案完全相同。模型 A 正確。
  • 問題 2 (參議院):答案語意相似,但用字遣詞不同。好的指標應該能辨識出這點。
  • 問題 3 (Hasan-Jalalians):根據內容,模型 A 的答案與事實不符。golden_answer 會公開這項錯誤。
  1. 在新的儲存格中,定義 golden_answers 清單
    golden_answers = [
        "frontal lobe and the parietal lobe",
        "Due to successes against Catiline.",
        "The Hasan-Jalalians commanded the area of Artsakh and Utik.",
    ]
    
  2. 在下一個儲存格中執行這段程式碼,建立參照的評估 DataFrame:
    referenced_eval_dataset_rag_a = pd.DataFrame(
        {
            "prompt": [
                "Answer the question: " + question + " Context: " + item
                for question, item in zip(questions, retrieved_contexts)
            ],
            "response": generated_answers_by_rag_a,
            "reference": golden_answers,
        }
    )
    
    referenced_eval_dataset_rag_b = pd.DataFrame(
        {
            "prompt": [
                "Answer the question: " + question + " Context: " + item
                for question, item in zip(questions, retrieved_contexts)
            ],
            "response": generated_answers_by_rag_b,
            "reference": golden_answers,
        }
    )
    
    這段程式碼會將 golden_answers 與您先前建立的現有變數合併。

現在即可使用這些資料集進行參照評估。

建立自訂參照指標

您也可以建立自訂指標,用於參照評估。流程類似,但提示範本現在包含黃金答案的 {reference} 預留位置。

如果答案「正確」,則可使用較嚴格的二元評分 (例如 1 代表正確,0 代表不正確),藉此評估事實準確度。現在來建立新的 question_answering_correctness 指標,實作這項邏輯。

  1. 定義提示範本。在新的儲存格中,新增並執行下列程式碼:
    question_answering_correctness_prompt_template = """
    You are a professional writing evaluator. Your job is to score writing responses according to pre-defined evaluation criteria.
    
    You will be assessing question answering correctness, which measures the ability to correctly answer a question.
    
    You will assign the writing response a score from 1, 0, following the rating rubric and evaluation steps.
    
    ### Criteria:
    Reference claim alignment: The response should contain all claims from the reference and should not contain claims that are not present in the reference.
    
    ### Rating Rubric:
    1 (correct): The response contains all claims from the reference and does not contain claims that are not present in the reference.
    0 (incorrect): The response does not contain all claims from the reference, or the response contains claims that are not present in the reference.
    
    ### Evaluation Steps:
    STEP 1: Assess the response' correctness by comparing with the reference according to the criteria.
    STEP 2: Score based on the rubrics.
    
    Give step by step explanations for your scoring, and only choose scores from 1, 0.
    
    
    # User Inputs and AI-generated Response
    ## User Inputs
    ### Prompt
    {prompt}
    
    ## Reference
    {reference}
    
    ## AI-generated Response
    {response}
    
    """
    
    這個範本會指示評估 LLM 嚴格比較模型的回覆「{response}」和黃金參考答案「{reference}」,並評估是否正確 (1) 或不正確 (0)。
  2. 將提示範本字串包裝在 PointwiseMetric 物件中。這會為指標提供正式名稱,並將其設為評估工作的可重複使用元件。在新的儲存格中新增並執行下列程式碼:
    question_answering_correctness = PointwiseMetric(
        metric="question_answering_correctness",
        metric_prompt_template=question_answering_correctness_prompt_template,
    )
    

您現在已擁有自訂的參考指標,可進行嚴格的事實查核。

12. 執行參照評估作業

現在,您將使用參照的資料集和新指標設定評估工作。您會再次使用 EvalTask 類別。

指標清單現在會合併自訂模型指標和以運算為基礎的指標。參考評估可使用傳統的運算型指標,對生成的文字和參考文字進行數學比較。您會用到三種常見的:

  • exact_match:只有在生成的答案與參考答案完全相同時,才會獲得 1 分,否則為 0 分。
  • bleu:精確度指標。這項指標會計算生成答案中有多少字詞也出現在參考答案中。
  • rouge:召回率指標。這項指標會測量生成答案中包含的參考答案字詞數量。
  1. 使用參照資料集和新的指標組合,設定評估工作。在新的儲存格中,新增並執行下列程式碼,建立 EvalTask 物件:
    referenced_answer_eval_task_rag_a = EvalTask(
        dataset=referenced_eval_dataset_rag_a,
        metrics=[
        question_answering_correctness,
        "rouge",
        "bleu",
        "exact_match",
        ],
        experiment=EXPERIMENT,
    )
    
    referenced_answer_eval_task_rag_b = EvalTask(
        dataset=referenced_eval_dataset_rag_b,
        metrics=[
        question_answering_correctness,
        "rouge",
        "bleu",
        "exact_match",
        ],
        experiment=EXPERIMENT,
    )
    
  2. 呼叫 .evaluate() 方法,執行參照的評估。在新的儲存格中新增並執行下列程式碼:
    referenced_result_rag_a = referenced_answer_eval_task_rag_a.evaluate()
    referenced_result_rag_b = referenced_answer_eval_task_rag_b.evaluate()
    

13. 分析參照結果

評估已完成。在這項工作中,您將比較模型回覆與黃金參考答案,分析結果並評估模型的實況準確度。

查看摘要結果

  • 分析所參照評估的摘要結果。在新的儲存格中,新增並執行下列程式碼,顯示兩個模型的摘要表格:
    notebook_utils.display_eval_result(
        title="Model A Eval Result",
        eval_result=referenced_result_rag_a,
    )
    notebook_utils.display_eval_result(
        title="Model B Eval Result",
        eval_result=referenced_result_rag_b,
    )
    
    您會發現模型 A 在自訂 question_answering_correctness 指標的表現良好,但在 exact_match 的分數較低。這凸顯了以模型為基礎的指標價值,因為這類指標可辨識語意相似度,而不只是相同的文字。

以圖表呈現結果,方便比較

視覺化圖表可讓您更清楚看出兩者之間的成效差距。首先,將結果合併成單一清單,以便繪製圖表,然後產生雷達圖和長條圖。

  1. 將參照的評估結果合併為單一清單,以便繪製圖表。在新的儲存格中新增並執行下列程式碼:
    referenced_eval_results = []
    referenced_eval_results.append(("Model A", referenced_result_rag_a))
    referenced_eval_results.append(("Model B", referenced_result_rag_b))
    
  2. 生成雷達圖,以視覺化方式呈現各模型在新指標集中的成效。在新的儲存格中新增並執行下列程式碼:
    notebook_utils.display_radar_plot(
        referenced_eval_results,
        metrics=[
            "question_answering_correctness",
            "rouge",
            "bleu",
            "exact_match",
        ],
    )
    
  3. 建立長條圖,直接並列比較。這會顯示每個模型在不同指標上的成效。在新的儲存格中新增並執行下列程式碼:
    notebook_utils.display_bar_plot(
        referenced_eval_results,
        metrics=[
            "question_answering_correctness",
            "rouge",
            "bleu",
            "exact_match",
        ],
    )
    

這些視覺化內容證實,與模型 B 相比,模型 A 的準確度顯著提升,且與參考答案的內容一致。

14. 從練習到實際工作環境

您已成功執行 RAG 系統的完整評估管道。最後一節會總結您學到的重要策略概念,並提供架構,協助您將這些技能應用於實際專案。

正式環境最佳做法

如要在實際的生產環境中運用本實驗室的技能,請考慮下列四項重要做法:

  • 透過 CI/CD 自動化:將評估套件整合至 CI/CD 管道 (例如 Cloud Build、GitHub Actions)。針對程式碼變更自動執行評估,以找出迴歸問題,並在品質分數低於標準時封鎖部署作業。
  • 演進資料集:靜態資料集會過時。使用 Git LFS 或 Cloud Storage 控管「黃金」測試集的版本,並從實際 (匿名) 使用者查詢中取樣,持續新增具挑戰性的範例。
  • 評估檢索器,而不只是生成器:如果沒有正確的脈絡,就不可能生成優質回覆。使用命中率 (是否找到正確的文件?) 和平均倒數排名 (MRR) (正確的文件排名有多高?) 等指標,為檢索系統實作個別的評估步驟。
  • 監控一段時間內的指標:將評估執行作業的摘要分數匯出至 Google Cloud Monitoring 等服務。建立資訊主頁來追蹤品質趨勢,並設定自動快訊,在效能大幅下滑時接收通知。

進階評估方法矩陣

選擇合適的評估方法取決於您的具體目標。下表總結了各種方法的適用時機。

評估方法

最佳用途

主要優點

限制

免參考

監控正式環境、持續評估

不需要黃金答案,可擷取主觀品質

成本較高,評估人員可能會有偏見

參考資料

模型比較、基準測試

客觀評估,運算速度更快

需要正確答案,可能無法判斷語意是否相等

自訂指標

特定領域評估

滿足業務需求

需要驗證,開發成本較高

混合式做法

全方位生產系統

所有方法的優點

複雜度較高,需要進行成本最佳化

重要技術洞察

建構及評估自己的 RAG 系統時,請謹記以下核心原則:

  • 基礎性對 RAG 至關重要:這項指標能持續區分高品質和低品質的 RAG 系統,因此是監控正式環境的必要指標。
  • 多項指標可提供穩健性:單一指標無法擷取 RAG 品質的所有層面。全面評估需要多個評估維度。
  • 自訂指標可提供重要價值:特定領域的評估條件通常能掌握一般指標遺漏的細微差異,進而提高評估準確度。
  • 嚴謹的統計分析有助於提升信心:適當的樣本大小和顯著性檢定,可將評估作業從猜測轉變為可靠的決策工具。

正式版部署決策架構

請參考這個分階段架構,瞭解如何部署 RAG 系統:

  • 階段 1 - 開發:使用以參照為準的評估方式,搭配已知的測試集,比較及選取模型。
  • 第 2 階段 - 預先製作:結合兩種方法進行全面評估,驗證是否已準備好投入製作。
  • 第 3 階段 - 製作:導入無參考監控功能,持續評估品質,無需黃金答案。
  • 第 4 階段 - 最佳化:根據評估深入分析結果,改善模型和檢索系統。

15. 結語

恭喜!您已完成實驗室。

這個實驗室是「打造可用於正式環境的 AI」Google Cloud 學習路徑的一部分。

  • 探索完整課程,瞭解如何從設計原型到投入正式環境。
  • 使用主題標記 ProductionReadyAI 分享你的進度。

重點回顧

您已學會以下技能:

  • 執行無參考評估,根據擷取的背景資訊評估答案品質。
  • 新增「黃金答案」來評估事實正確性,藉此執行參照評估。
  • 這兩種做法都可使用預先定義和自訂指標。
  • 同時使用以模型為基準的指標 (例如 question_answering_quality) 和以運算為基準的指標 (rougebleuexact_match)。
  • 分析及呈現結果,瞭解模型的優缺點。

這種評估方法有助於建構更可靠且準確的生成式 AI 應用程式。