基于大语言模型知识问答应用落地实践 – 使用 TruLens 做自动化 RAG 项目评估测试
Modified from 2023.12。IVAN ILIN。Advanced RAG Techniques: an Illustrated Overview
🦑 TruLens 官方說明The RAG Triad
用來檢驗大型語言模型(LLMs)產生的回答在三個關鍵方面的品質:上下文相關性(Context Relevance)、真實性(Groundedness)和回答相關性(Answer Relevance)。確保LLM應用不會出現幻覺性錯誤(hallucinations),這種錯誤通常發生在檢索環節未能獲取足夠或相關的上下文時。
核心概念參考202309。RAGAS: Automated Evaluation of Retrieval Augmented Generation
在RAG(Retrieval Augmented Generation)評估中,利用TrueLens建立了三種評估模組,它們分別基於查詢(Query)、回應(Response)和上下文(Context)之間的配對比較。這被稱為RAG評估三角(The RAG Triad),其概念如下:
Feedback Functions can be implemented in different ways
評估方法根據它們提供的回饋品質/意義性上(Meaningful)和執行評估的易行性/可擴展性(Scalable)進行不同的權衡
Domain Expert/Ground Truth Evals(領域專家/基準真實評估)
Human Evals(人類評估)
Traditional NLP Evals(傳統NLP評估)
Medium Language Model,MLM Evals(中型語言模型評估)
Large Language Model,LLM Evals(大型語言模型評估)
🦑 TruLens 官方說明Honest, Harmless and Helpful Evaluations
自然語言處理應用時可能考慮的幾個關鍵指標,這些指標分為三大類:Honest(誠實性)、Harmless(無害性)和Helpful(有幫助性)。以下是各指標的詳細解釋:
Honest(誠實):
Harmless(無害):
Helpful(有幫助):
上面是理論與原則部分
TruLens官方指南core_concepts_feedback_functions
反饋函數(Feedback Functions)類似於標籤函數(labeling functions),提供了一種以程序化方式在應用運行中生成評估的方法。TruLens的反饋函數實現包裹了一個支持的提供者模型,例如相關性模型或情感分類器,這些模型被重新配置以提供評估。通常,為了獲得最大的靈活性,這個模型可以是另一個大型語言模型(LLM)
import nest_asyncio
nest_asyncio.apply()
from trulens_eval import OpenAI as fOpenAI
provider = fOpenAI()
Structure of Feedback function
Feedback functions, analogous to labeling functions, provide a programmatic method for generating evaluations on an application run.
用於生成對應用運行的評估的程序化方法。這個結構包含了幾個部分:
provider = fOpenAI()
:這表示使用了一個名為 fOpenAI
的大型語言模型(LLM),作為運行反饋函數的提供者f_qa_relevance
:這是被定義的反饋函數方法的實例Feedback()
:這是一個函數,它接受一個提供者的模型(在這個案例中是 provider.relevance
),這個模型是為了評估而重新用途的,比如相關性模型或情感分類器name="Answer Relevance"
:這是反饋函數的人類可讀名稱,用於評估儀表板上的顯示.on_input()
和 .on_output()
:這些方法指向用戶查詢和應用輸出,允許反饋函數訪問這些數據以產生評估標籤函數(labeling functions)是一種在機器學習中用於生成訓練數據標籤的程序化方法。這些函數允許研究人員使用專業知識、規則或模型來創建標籤,而不是手動標注整個數據集
def food_related(tweet):
food_keywords = ['pizza', 'restaurant', 'dinner', 'lunch']
return any(keyword in tweet.lower() for keyword in food_keywords)
# 假設 `tweets` 是一個推文列表
labels = [food_related(tweet) for tweet in tweets]
以下為Feedback function在 Answer Relevance、Context Relevance與Groundedness三項目的使用範例
Is the final response useful?
from trulens_eval import Feedback
f_qa_relevance = Feedback(
provider.relevance_with_cot_reasons,
name="Answer Relevance"
).on_input_output()
Q: “How can altruism be beneficial in building a career?”
- 回應詳細解釋了利他主義如何在建立職業生涯中起到積極作用。它指出,即使在專注於個人職業成長的同時幫助他人,也能為個體帶來更好的結果。這種行為能夠建立積極的聲譽和人脈網絡,進而導致新機會和合作的出現。此外,幫助他人還能帶來成就感和目的感,從而有助於整體的職業滿意度和福祉。
- 支持證據: 強調了回應如何清晰地提供了利他主義在職業發展中的益處。它提到,通過幫助他人,個體可以為自己獲得更好的結果,創造良好的聲譽和網絡,並導向新的機會和合作。它還突顯了幫助他人能夠提供成就感和目的感,這對職業滿意度和個人福祉有正面貢獻。
How good is the retrieval?
from trulens_eval import TruLlama
context_selection = TruLlama.select_source_nodes().node.text
qs_relevance
import numpy as np
f_qs_relevance = (
Feedback(provider.qs_relevance,
name="Context Relevance")
.on_input()
.on(context_selection)
.aggregate(np.mean)
)
qs_relevance_with_cot_reasons
The second piece is the supporting evidence or the rationale or the chain of thought reasoning behind why the evaluation produced this score.
f_qs_relevance = (
Feedback(provider.qs_relevance_with_cot_reasons,
name="Context Relevance")
.on_input()
.on(context_selection)
.aggregate(np.mean)
)
Q: “How can altruism be beneficial in building a career?”
回應包含了從一個指南或書籍的節選,這段文本提供了關於找到合適工作並增加找到支持個人職業成長職位的機會的建議。建議包括研究角色和公司、與朋友交談,並選擇性地安排與吸引人的公司中的人進行非正式的信息性面試。此外,如果可能的話,從內部人士那裡獲得推薦
- 上下文相關性(Context Relevance)得分為0.7
- 顯示這段回應與原始查詢有相當的相關性。這個得分反映出檢索到的內容與問題的主題密切相關,但可能不是完美匹配,因為問題是關於利他主義如何在職業生涯中有益,而回應似乎沒有直接提到利他主義。
支持證據部分說明了回應如何提供了建立職業生涯的有用信息,提供了關於潛在工作機會的洞察,並允許個體做出有關他們職業道路的明智決定
雖然回應提供了有關職業建設的實用建議,但沒有充分涉及查詢中提到的利他主義概念。
from trulens_eval.feedback import Groundedness
grounded = Groundedness(groundedness_provider=provider)
f_groundedness = (
Feedback(grounded.groundedness_measure_with_cot_reasons,
name="Groundedness"
)
.on(context_selection)
.on_output()
.aggregate(grounded.grounded_statements_aggregator)
)
使用TruLlama建立紀錄器
TruLens 提供與 Llama-Index 深度集成的 TruLlama,允許您檢查和評估使用 Llama-Index 構建的應用程序的內部結構
📓 Llama-Index Integration
from trulens_eval import TruLlama
from trulens_eval import FeedbackMode
tru_recorder = TruLlama(
sentence_window_engine,
app_id="App_1",
feedbacks=[
f_qa_relevance,
f_qs_relevance,
f_groundedness
]
)
sentence_window_engine
:這個參數是指句子窗口引擎,它是一個用於分析和處理輸入問題的核心程式碼。在這裡,它被傳遞給 TruLlama
,以便該物件可以利用這個引擎進行問題的分析。app_id
:這個參數是應用程序的 ID,用於識別不同的應用程序。在這個例子中,應用程序的 ID 被設置為 "App_1"。feedbacks
:這是一個列表,包含了要捕獲的反饋模式。在這個例子中,列表中包含了三個反饋模式:f_qa_relevance
、f_qs_relevance
和 f_groundedness
。這些反饋模式用於評估問題與回答之間的相關性,以及回答的合理性。建立評估用的問題集
eval_questions = []
with open('eval_questions.txt', 'r') as file:
for line in file:
# Remove newline character and convert to integer
item = line.strip()
eval_questions.append(item)
eval_questions
['What are the keys to building a career in AI?',
'How can teamwork contribute to success in AI?',
'What is the importance of networking in AI?',
'What are some good habits to develop for a successful career?',
'How can altruism be beneficial in building a career?',
'What is imposter syndrome and how does it relate to AI?',
'Who are some accomplished individuals who have experienced imposter syndrome?',
'What is the first step to becoming good at AI?',
'What are some common challenges in AI?',
'Is it normal to find parts of AI challenging?',
'How can I be successful in AI?']
進行評估
for question in eval_questions:
with tru_recorder as recording:
sentence_window_engine.query(question)
records, feedback = tru.get_records_and_feedback(app_ids=[])
records.head()
import pandas as pd
pd.set_option("display.max_colwidth", None)
records[["input", "output"] + feedback]
呼叫leaderboard與dashboard
tru.get_leaderboard(app_ids=[])
tru.run_dashboard()
learn how to apply traditional software evaluation techniques to AI, understand the different types of evaluations and when to use them, and see what the lifecycle of evaluating LLM applications looks like at the frontier of Generative AI.
Typical makeup of a test suite in software development CI. Unit tests tend to be the hardest to emulate for LLMs.
Heuristic/Code - using simple deterministic rules based judgments against attributes like cost, token usage, latency, regex rules on the output, etc. These are generally fast and cheap to run at scal
Model (or 'AI') - using other foundation models to provide judgments on the output of the component. This allows for more qualitative and nuanced judgments for a fraction of the cost of human judgments.
Human - getting gold standard judgments from either end users of your application, or internal domain experts. This can be the most expensive and slowest option, but also the most reliable.
《Judging LLM-as-a-Judge》LLM評估器(評估模型)與人類判斷達到了超過80%的一致性;這等同於人類之間的一致性水平。
《Benchmarking Cognitive Biases in Large Language Models as Evaluators在15種不同的LLM變體上測量了6種認知偏見。他們發現,將結果的順序呈現給模型的簡單細節可以對評估產生重大影響
The cognitive bias benchmark for LLMs. Simple details such as the order of the results presented to the model can have material impact on the evaluation. Source: https://arxiv.org/pdf/2309.17012
團隊應該考慮提升人類判斷努力,專注於改進模型評估器,以實現更可擴展、可重複且經濟的評估過程
Different stages of evaluation are necessary
Recommended stages for a robust evaluation process. Interactive, offline and online.
有3個互補的評估階段對於支持LLM塊相關干預的快速迭代循環具有最高的投資報酬率:
Illustration of model red teaming; one LLM makes adversarial requests to another to elicit bad behaviour. Source: https://arxiv.org/pdf/2202.03286
幾種RAG指標的整理
Galileo 公司提出的評估指標,可與Trulens的做對照
Choosing your Guardrail Metrics
細節見後面:
Output Quality Metrics:
RAG Quality Metrics
Insight:
measures the extent to which the retrieved context aligns with the annotated answer, treated as the ground truth.
evaluates whether all of the ground-truth relevant items present in the contexts are ranked higher or not.
Mean Reciprocal Rank (MRR)
MRR 是用來衡量檢索系統返回的相關項目在排名中的位置,計算公式為:
其中
Context Precision | MRR | |
---|---|---|
評估範圍 | 注重在前K名中的所有相關項目,反映了多個項目的排名精度 | 只關注第一個正確答案的排名,反映了找到首個正確答案的效率 |
計算方法 | 使用每個位置的 精度進行加權平均 |
使用第一個正確答案的 倒數排名進行平均 |
measure of recall of the retrieved context, based on the number of entities present in both ground_truths and contexts relative to the number of entities present in the ground_truths alone
回答正確性評估生成的答案與標準答案的準確度。分數範圍從0到1,分數越高,表示生成的答案與標準答案越接近,正確性越高。
核心要點
ground truth
:生成答案與標準答案的語義相似性。Answer semantic similarity
:生成答案與標準答案的語意相似度Answer semantic similarity計算方法
使用真陽 (True Positive, TP)、假陽 (False Positive, FP) 和假陰 (False Negative, FN) 來量化事實重合度(factual overlap)
計算 F1 分數來表示事實正確性ground truth
:
結合語義相似度和事實相似度,使用加權平均法得到最終的正確性分數
ground truth
weights:
score = np.average( [f1_score, similarity_score], weights=self.weights, )