ContextRelevancyMetric
ContextRelevancyMetric
クラスは、RAG(Retrieval-Augmented Generation)パイプラインのリトリーバーが取得したコンテキストが入力クエリにどれだけ関連しているかを測定することで、その品質を評価します。このクラスは、まずコンテキストからステートメントを抽出し、それらが入力にどれだけ関連しているかを評価する、LLMベースの評価システムを使用します。
基本的な使い方
import { openai } from "@ai-sdk/openai";
import { ContextRelevancyMetric } from "@mastra/evals/llm";
// Configure the model for evaluation
const model = openai("gpt-4o-mini");
const metric = new ContextRelevancyMetric(model, {
context: [
"All data is encrypted at rest and in transit",
"Two-factor authentication is mandatory",
"The platform supports multiple languages",
"Our offices are located in San Francisco",
],
});
const result = await metric.measure(
"What are our product's security features?",
"Our product uses encryption and requires 2FA.",
);
console.log(result.score); // Score from 0-1
console.log(result.info.reason); // Explanation of the relevancy assessment
コンストラクタのパラメータ
model:
LanguageModel
コンテキストの関連性を評価するために使用されるモデルの設定
options:
ContextRelevancyMetricOptions
メトリックの設定オプション
ContextRelevancyMetricOptions
scale?:
number
= 1
スコアの最大値
context:
string[]
レスポンスを生成するために取得されたコンテキストドキュメントの配列
measure() のパラメーター
input:
string
元のクエリまたはプロンプト
output:
string
評価対象となるLLMの応答
戻り値
score:
number
コンテキスト関連性スコア(0からスケール、デフォルトは0-1)
info:
object
スコアの理由を含むオブジェクト
string
reason:
string
関連性評価の詳細な説明
スコアリングの詳細
このメトリックは、取得されたコンテキストがクエリにどれだけ適合しているかを、バイナリ関連性分類によって評価します。
スコアリングプロセス
-
コンテキストから文を抽出:
- コンテキストを意味のある単位に分割
- セマンティックな関係性を保持
-
文の関連性を評価:
- 各文をクエリと照合して評価
- 関連する文をカウント
- 関連性の比率を算出
最終スコア: (relevant_statements / total_statements) * scale
スコアの解釈
(0 から scale、デフォルトは 0-1)
- 1.0: 完全な関連性 - 取得されたコンテキストがすべて関連している
- 0.7-0.9: 高い関連性 - ほとんどのコンテキストが関連しており、無関係な部分は少ない
- 0.4-0.6: 中程度の関連性 - 関連するコンテキストと無関係なコンテキストが混在している
- 0.1-0.3: 低い関連性 - ほとんどが無関係なコンテキスト
- 0.0: 関連性なし - 完全に無関係なコンテキスト
カスタム設定の例
import { openai } from "@ai-sdk/openai";
import { ContextRelevancyMetric } from "@mastra/evals/llm";
// Configure the model for evaluation
const model = openai("gpt-4o-mini");
const metric = new ContextRelevancyMetric(model, {
scale: 100, // Use 0-100 scale instead of 0-1
context: [
"Basic plan costs $10/month",
"Pro plan includes advanced features at $30/month",
"Enterprise plan has custom pricing",
"Our company was founded in 2020",
"We have offices worldwide",
],
});
const result = await metric.measure(
"What are our pricing plans?",
"We offer Basic, Pro, and Enterprise plans.",
);
// Example output:
// {
// score: 60,
// info: {
// reason: "3 out of 5 statements are relevant to pricing plans. The statements about
// company founding and office locations are not relevant to the pricing query."
// }
// }