コンテキスト関連度 Scorer
createContextRelevanceScorerLLM() 関数は、与えられたコンテキストが Agent の応答生成にどの程度関連し、有用だったかを評価する scorer を作成します。重み付きの関連度レベルを使用し、関連度が高いのに使われなかったコンテキストや不足情報にペナルティを適用します。
特に次のユースケースに適しています。
コンテンツ生成の評価コンテンツ生成の評価への直接リンク
次のような場合のコンテキスト品質評価に適しています。
- コンテキストの利用が重要なチャットシステム
- 詳細な関連度評価が必要な RAG パイプライン
- コンテキスト不足が品質に影響するシステム
コンテキスト選択の最適化コンテキスト選択の最適化への直接リンク
次の項目を最適化する場合に使用します。
- コンテキストの網羅性
- コンテキストの効果的な活用
- コンテキストの不足箇所の特定
パラメーターパラメーターへの直接リンク
model:
MastraModelConfig
コンテキストの関連度評価に使用する言語モデル
options:
ContextRelevanceOptions
scorer の設定オプション
注:context または contextExtractor のいずれかを指定する必要があります。両方を指定した場合は、contextExtractor が優先されます。
.run() の戻り値run-returnsへの直接リンク
score:
number
0 から scale までの重み付き関連度スコア(デフォルト:0〜1)
reason:
string
コンテキスト関連度評価についての人が読める説明
スコアリングの詳細スコアリングの詳細への直接リンク
重み付き関連度スコアリング重み付き関連度スコアリングへの直接リンク
Context Relevance は、次の要素を考慮する高度なスコアリングアルゴリズムを使用します。
-
関連度レベル:各コンテキスト断片を重み付きの値で分類します。
high= 1.0(クエリに直接答える)medium= 0.7(補足情報)low= 0.3(間接的に関連する)none= 0.0(まったく関連しない)
-
利用検出:関連するコンテキストが応答で実際に使われたかを追跡します。
-
ペナルティの適用(
penaltiesオプションで設定可能):- 未使用の高関連度コンテキスト:未使用の高関連度コンテキスト 1 件につき
unusedHighRelevanceContextのペナルティ(デフォルト:0.1) - 不足コンテキスト:特定された不足情報に対し、最大
maxMissingContextPenaltyのペナルティ(デフォルト:0.5)
- 未使用の高関連度コンテキスト:未使用の高関連度コンテキスト 1 件につき
スコアリング式スコアリング式への直接リンク
Base Score = Σ(relevance_weights) / (num_contexts × 1.0)
Usage Penalty = count(unused_high_relevance) × unusedHighRelevanceContext
Missing Penalty = min(count(missing_context) × missingContextPerItem, maxMissingContextPenalty)
Final Score = max(0, Base Score - Usage Penalty - Missing Penalty) × scale
デフォルト値:
unusedHighRelevanceContext= 0.1(未使用の高関連度コンテキスト 1 件につき 10% のペナルティ)missingContextPerItem= 0.15(不足しているコンテキスト項目 1 件につき 15% のペナルティ)maxMissingContextPenalty= 0.5(コンテキスト不足に対する最大 50% のペナルティ)scale= 1
スコアの解釈スコアの解釈への直接リンク
- 0.9〜1.0:非常に良い — すべてのコンテキストの関連度が高く、使用されている
- 0.7〜0.8:良い — ほぼ関連しているが、わずかな不足がある
- 0.4〜0.6:混在 — 関連しない、または未使用のコンテキストが多い
- 0.2〜0.3:悪い — コンテキストの大部分が関連しない
- 0.0〜0.1:非常に悪い — 関連するコンテキストが見つからない
reason の分析reason の分析への直接リンク
reason フィールドから次の情報を確認できます。
- 各コンテキスト断片の関連度レベル(high/medium/low/none)
- 応答で実際に使われたコンテキスト
- 未使用の高関連度コンテキストに適用されたペナルティ(
unusedHighRelevanceContextで設定可能) - 応答の改善につながる不足コンテキスト(
missingContextPerItemにより最大maxMissingContextPenaltyまでペナルティを適用)
最適化戦略最適化戦略への直接リンク
結果を活用してシステムを改善します。
- 関連しないコンテキストを除外:処理前に関連度が low/none の断片を削除する
- コンテキストの利用を徹底:関連度が高いコンテキストを確実に取り入れる
- コンテキストの不足を補完:scorer が特定した不足情報を追加する
- コンテキスト量を調整:最適な関連度が得られるコンテキスト量を見つける
- ペナルティ感度を調整:未使用または不足しているコンテキストに対するアプリケーションの許容度に応じて、
unusedHighRelevanceContext、missingContextPerItem、maxMissingContextPenaltyを調整する
Context Precision との違いContext Precision との違いへの直接リンク
| 観点 | Context Relevance | Context Precision |
|---|---|---|
| アルゴリズム | ペナルティ付きの重み付きレベル | Mean Average Precision(MAP) |
| 関連度 | 複数レベル(high/medium/low/none) | 二値(yes/no) |
| 位置 | 考慮しない | 重要(前方にあるほど高評価) |
| 利用状況 | 未使用のコンテキストを追跡し、ペナルティを適用 | 考慮しない |
| 不足 | 不足を特定し、ペナルティを適用 | 評価しない |
Scorer の設定Scorer の設定への直接リンク
カスタムペナルティ設定カスタムペナルティ設定への直接リンク
未使用および不足しているコンテキストへのペナルティの適用方法を制御します。
import { createContextRelevanceScorerLLM } from '@mastra/evals'
// Stricter penalty configuration
const strictScorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
context: [
'Einstein won the Nobel Prize for photoelectric effect',
'He developed the theory of relativity',
'Einstein was born in Germany',
],
penalties: {
unusedHighRelevanceContext: 0.2, // 20% penalty per unused high-relevance context
missingContextPerItem: 0.25, // 25% penalty per missing context item
maxMissingContextPenalty: 0.6, // Maximum 60% penalty for missing context
},
scale: 1,
},
})
// Lenient penalty configuration
const lenientScorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
context: [
'Einstein won the Nobel Prize for photoelectric effect',
'He developed the theory of relativity',
'Einstein was born in Germany',
],
penalties: {
unusedHighRelevanceContext: 0.05, // 5% penalty per unused high-relevance context
missingContextPerItem: 0.1, // 10% penalty per missing context item
maxMissingContextPenalty: 0.3, // Maximum 30% penalty for missing context
},
scale: 1,
},
})
const testRun = {
input: {
inputMessages: [
{
id: '1',
role: 'user',
content: 'What did Einstein achieve in physics?',
},
],
},
output: [
{
id: '2',
role: 'assistant',
content: 'Einstein won the Nobel Prize for his work on the photoelectric effect.',
},
],
}
const strictResult = await strictScorer.run(testRun)
const lenientResult = await lenientScorer.run(testRun)
console.log('Strict penalties:', strictResult.score) // Lower score due to unused context
console.log('Lenient penalties:', lenientResult.score) // Higher score, less penalty
コンテキストの動的抽出コンテキストの動的抽出への直接リンク
const scorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
contextExtractor: (input, output) => {
// Extract context based on the query
const userQuery = input?.inputMessages?.[0]?.content || ''
if (userQuery.includes('Einstein')) {
return [
'Einstein won the Nobel Prize for the photoelectric effect',
'He developed the theory of relativity',
]
}
return ['General physics information']
},
penalties: {
unusedHighRelevanceContext: 0.15,
},
},
})
カスタムスケール係数カスタムスケール係数への直接リンク
const scorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
context: ['Relevant information...', 'Supporting details...'],
scale: 100, // Scale scores from 0-100 instead of 0-1
},
})
// Result will be scaled: score: 85 instead of 0.85
複数のコンテキストソースの結合複数のコンテキストソースの結合への直接リンク
const scorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
contextExtractor: (input, output) => {
const query = input?.inputMessages?.[0]?.content || ''
// Combine from multiple sources
const kbContext = knowledgeBase.search(query)
const docContext = documentStore.retrieve(query)
const cacheContext = contextCache.get(query)
return [...kbContext, ...docContext, ...cacheContext]
},
scale: 1,
},
})
例例への直接リンク
関連度が高い例関連度が高い例への直接リンク
この例では、すべてのコンテキストが応答を直接裏付けており、関連度が非常に高くなっています。
import { createContextRelevanceScorerLLM } from '@mastra/evals'
const scorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
context: [
'Einstein won the Nobel Prize for his discovery of the photoelectric effect in 1921.',
'He published his theory of special relativity in 1905.',
'His general relativity theory, published in 1915, revolutionized our understanding of gravity.',
],
scale: 1,
},
})
const result = await scorer.run({
input: {
inputMessages: [
{
id: '1',
role: 'user',
content: "What were Einstein's major scientific achievements?",
},
],
},
output: [
{
id: '2',
role: 'assistant',
content:
"Einstein's major achievements include the Nobel Prize for the photoelectric effect, special relativity in 1905, and general relativity in 1915.",
},
],
})
console.log(result)
// Output:
// {
// score: 1.0,
// reason: "The score is 1.0 because all context pieces are highly relevant to Einstein's achievements and were effectively used in generating the comprehensive response."
// }
関連度が混在する例関連度が混在する例への直接リンク
この例では、一部のコンテキストが関連しないか未使用のため、関連度は中程度です。
import { createContextRelevanceScorerLLM } from '@mastra/evals'
const scorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
context: [
'Solar eclipses occur when the Moon blocks the Sun.',
'The Moon moves between the Earth and Sun during eclipses.',
'The Moon is visible at night.',
'Stars twinkle due to atmospheric interference.',
'Total eclipses can last up to 7.5 minutes.',
],
scale: 1,
},
})
const result = await scorer.run({
input: {
inputMessages: [
{
id: '1',
role: 'user',
content: 'What causes solar eclipses?',
},
],
},
output: [
{
id: '2',
role: 'assistant',
content:
'Solar eclipses happen when the Moon moves between Earth and the Sun, blocking sunlight.',
},
],
})
console.log(result)
// Output with default penalties:
// {
// score: 0.64,
// reason: "The score is 0.64 because contexts 1 and 2 are highly relevant and used, context 5 is relevant but unused (10% penalty), while contexts 3 and 4 are irrelevant."
// }
// With custom penalty configuration
const customScorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
context: [
'Solar eclipses occur when the Moon blocks the Sun.',
'The Moon moves between the Earth and Sun during eclipses.',
'The Moon is visible at night.',
'Stars twinkle due to atmospheric interference.',
'Total eclipses can last up to 7.5 minutes.',
],
penalties: {
unusedHighRelevanceContext: 0.05, // Lower penalty for unused context
missingContextPerItem: 0.1,
maxMissingContextPenalty: 0.3,
},
},
})
const customResult = await customScorer.run({
input: {
inputMessages: [{ id: '1', role: 'user', content: 'What causes solar eclipses?' }],
},
output: [
{
id: '2',
role: 'assistant',
content:
'Solar eclipses happen when the Moon moves between Earth and the Sun, blocking sunlight.',
},
],
})
console.log(customResult)
// Output with lenient penalties:
// {
// score: 0.69, // Higher score due to reduced penalty for unused context
// reason: "The score is 0.69 because contexts 1 and 2 are highly relevant and used, context 5 is relevant but unused (5% penalty), while contexts 3 and 4 are irrelevant."
// }
関連度が低い例関連度が低い例への直接リンク
この例では、大部分の情報が関連しておらず、コンテキストの関連度が低くなっています。
import { createContextRelevanceScorerLLM } from '@mastra/evals'
const scorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
context: [
'The Great Barrier Reef is located in Australia.',
'Coral reefs need warm water to survive.',
'Many fish species live in coral reefs.',
'Australia has six states and two territories.',
'The capital of Australia is Canberra.',
],
scale: 1,
},
})
const result = await scorer.run({
input: {
inputMessages: [
{
id: '1',
role: 'user',
content: 'What is the capital of Australia?',
},
],
},
output: [
{
id: '2',
role: 'assistant',
content: 'The capital of Australia is Canberra.',
},
],
})
console.log(result)
// Output:
// {
// score: 0.26,
// reason: "The score is 0.26 because only context 5 is relevant to the query about Australia's capital, while the other contexts about reefs are completely irrelevant."
// }
コンテキストの動的抽出コンテキストの動的抽出への直接リンク
run の入力に基づいて、実行時にコンテキストを抽出します。
import { createContextRelevanceScorerLLM } from '@mastra/evals'
const scorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
contextExtractor: (input, output) => {
// Extract query from input
const query = input?.inputMessages?.[0]?.content || ''
// Dynamically retrieve context based on query
if (query.toLowerCase().includes('einstein')) {
return [
'Einstein developed E=mc²',
'He won the Nobel Prize in 1921',
'His theories revolutionized physics',
]
}
if (query.toLowerCase().includes('climate')) {
return [
'Global temperatures are rising',
'CO2 levels affect climate',
'Renewable energy reduces emissions',
]
}
return ['General knowledge base entry']
},
penalties: {
unusedHighRelevanceContext: 0.15, // 15% penalty for unused relevant context
missingContextPerItem: 0.2, // 20% penalty per missing context item
maxMissingContextPenalty: 0.4, // Cap at 40% total missing context penalty
},
scale: 1,
},
})
RAG システムとの統合RAG システムとの統合への直接リンク
RAG パイプラインと統合し、取得したコンテキストを評価します。
import { createContextRelevanceScorerLLM } from '@mastra/evals'
const scorer = createContextRelevanceScorerLLM({
model: 'openai/gpt-5.6-sol',
options: {
contextExtractor: (input, output) => {
// Extract from RAG retrieval results
const ragResults = inputData.metadata?.ragResults || []
// Return the text content of retrieved documents
return ragResults.filter(doc => doc.relevanceScore > 0.5).map(doc => doc.content)
},
penalties: {
unusedHighRelevanceContext: 0.12, // Moderate penalty for unused RAG context
missingContextPerItem: 0.18, // Higher penalty for missing information in RAG
maxMissingContextPenalty: 0.45, // Slightly higher cap for RAG systems
},
scale: 1,
},
})
// Evaluate RAG system performance
const evaluateRAG = async testCases => {
const results = []
for (const testCase of testCases) {
const score = await scorer.run(testCase)
results.push({
query: testCase.inputData.inputMessages[0].content,
relevanceScore: score.score,
feedback: score.reason,
unusedContext: score.reason.includes('unused'),
missingContext: score.reason.includes('missing'),
})
}
return results
}
Context Precision との比較Context Precision との比較への直接リンク
用途に適した scorer を選択してください。
| ユースケース | Context Relevance | Context Precision |
|---|---|---|
| RAG の評価 | 利用状況が重要な場合 | 順位が重要な場合 |
| コンテキスト品質 | 段階的なレベル | 二値の関連度 |
| 不足の検出 | ✓ 不足を特定 | ✗ 評価しない |
| 利用状況の追跡 | ✓ 利用状況を追跡 | ✗ 考慮しない |
| 位置への感度 | ✗ 位置に依存しない | ✓ 前方にあるほど高評価 |
関連項目関連項目への直接リンク
- Context Precision Scorer:MAP を使用してコンテキストの順位を評価します
- Faithfulness Scorer:回答がコンテキストにどの程度根拠を持つかを測定します
- カスタム Scorer:独自の評価指標を作成します