컨텍스트 관련성 점수 측정기
그만큼createContextRelevanceScorerLLM()함수는 Agent 응답을 생성하는 데 제공된 컨텍스트가 얼마나 적절하고 유용한지 평가하는 점수 측정기를 생성합니다. 가중치가 부여된 관련성 수준을 사용하고 사용되지 않은 관련성이 높은 컨텍스트 및 누락된 정보에 대해 페널티를 적용합니다.
다음과 같은 사용 사례에 특히 유용합니다.
콘텐츠 생성 평가콘텐츠 생성 평가에 대한 직접 링크
다음에서 컨텍스트 품질을 평가하는 데 가장 적합합니다.
- 컨텍스트 사용이 중요한 채팅 시스템
- 상세한 관련성 평가가 필요한 RAG 파이프라인
- 누락된 컨텍스트가 품질에 영향을 미치는 시스템
컨텍스트 선택 최적화컨텍스트 선택 최적화에 대한 직접 링크
다음을 최적화할 때 사용:
- 포괄적인 상황 범위
- 효과적인 컨텍스트 활용
- 컨텍스트 격차 식별
매개변수매개변수에 대한 직접 링크
model:
options:
참고: context 또는 contextExtractor 중 하나를 제공해야 합니다. 둘 다 제공하면 contextExtractor가 우선합니다.
.run()보고run-returns에 대한 직접 링크
score:
reason:
채점 세부정보채점 세부정보에 대한 직접 링크
가중 관련성 점수가중 관련성 점수에 대한 직접 링크
컨텍스트 관련성은 다음을 고려하는 고급 채점 알고리즘을 사용합니다.
-
관련성 수준: 각 컨텍스트 조각은 가중치가 부여된 값으로 분류됩니다.
high= 1.0(쿼리를 직접 해결)medium= 0.7 (지원 정보)low= 0.3(접선적으로 관련됨)none= 0.0 (완전히 관련 없음)
-
사용량 감지: 해당 컨텍스트가 실제로 응답에 사용되었는지 추적합니다.
-
적용되는 페널티(
penalties옵션으로 구성 가능):- 사용되지 않은 높은 관련성: 사용되지 않은 관련성 높은 컨텍스트마다
unusedHighRelevanceContext페널티 적용(기본값: 0.1) - 누락된 컨텍스트: 확인된 누락 정보에 최대
maxMissingContextPenalty적용(기본값: 0.5)
- 사용되지 않은 높은 관련성: 사용되지 않은 관련성 높은 컨텍스트마다
채점 공식채점 공식에 대한 직접 링크
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(사용되지 않은 관련성이 높은 컨텍스트당 10% 페널티)missingContextPerItem= 0.15(누락된 컨텍스트 항목당 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: 매우 나쁨 - 관련 컨텍스트를 찾을 수 없음
이유분석이유분석에 대한 직접 링크
이유 필드는 다음에 대한 통찰력을 제공합니다.
- 각 컨텍스트 부분의 관련성 수준(높음/중간/낮음/없음)
- 응답에 실제로 사용된 컨텍스트
- 사용되지 않은 관련성 높은 컨텍스트에 적용되는 페널티(
unusedHighRelevanceContext로 구성 가능) - 응답을 개선할 수 있는 누락된 컨텍스트(
missingContextPerItem으로 페널티를 적용하며 최대maxMissingContextPenalty까지 적용)
최적화 전략최적화 전략에 대한 직접 링크
결과를 사용하여 시스템을 개선하십시오.
- 관련 없는 컨텍스트 필터링: 처리하기 전에 관련성이 낮거나 없는 부분을 제거합니다.
- 컨텍스트 사용 보장: 관련성이 높은 컨텍스트가 통합되었는지 확인합니다.
- 컨텍스트 공백 채우기: 채점자가 확인한 누락 정보를 추가합니다.
- 컨텍스트 크기 조정: 관련성을 극대화할 수 있는 최적의 컨텍스트 양을 찾습니다.
- 페널티 민감도 조정: 애플리케이션이 사용되지 않거나 누락된 컨텍스트를 허용하는 정도에 따라
unusedHighRelevanceContext,missingContextPerItem,maxMissingContextPenalty를 조정합니다.
상황 정밀도와의 차이점상황 정밀도와의 차이점에 대한 직접 링크
| 측면 | 컨텍스트 관련성 | 컨텍스트 정밀도 |
|---|---|---|
| 알고리즘 | 페널티가 적용되는 가중 수준 | 평균 정밀도 평균(MAP) |
| 관련성 | 여러 수준(높음/중간/낮음/없음) | 이진(예/아니요) |
| 위치 | 고려하지 않음 | 중요함(앞쪽 배치에 보상) |
| 사용 여부 | 사용되지 않은 컨텍스트를 추적하고 페널티 적용 | 고려하지 않음 |
| 누락 | 공백을 식별하고 페널티 적용 | 평가하지 않음 |
득점자 구성득점자 구성에 대한 직접 링크
사용자 정의 페널티 구성사용자 정의 페널티 구성에 대한 직접 링크
사용되지 않거나 누락된 컨텍스트에 대해 페널티가 적용되는 방식을 제어합니다.
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."
// }
동적 컨텍스트 추출동적 컨텍스트 추출에 대한 직접 링크
실행 입력을 기반으로 런타임 시 컨텍스트를 추출합니다.
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
}
컨텍스트 정밀도와의 비교컨텍스트 정밀도와의 비교에 대한 직접 링크
귀하의 필요에 맞는 채점자를 선택하십시오:
| 사용 사례 | 컨텍스트 관련성 | 컨텍스트 정밀도 |
|---|---|---|
| RAG 평가 | 사용 여부가 중요할 때 | 순위가 중요할 때 |
| 컨텍스트 품질 | 세분화된 수준 | 이진 관련성 |
| 누락 감지 | ✓ 공백 식별 | ✗ 평가하지 않음 |
| 사용 추적 | ✓ 활용 여부 추적 | ✗ 고려하지 않음 |
| 위치 민감도 | ✗ 위치와 무관 | ✓ 앞쪽 배치에 보상 |
관련된관련된에 대한 직접 링크
- 상황별 정밀 득점자: MAP을 사용하여 컨텍스트 순위를 평가합니다.
- 성실성 득점자: 문맥에 따른 답변 근거성을 측정합니다.
- 맞춤 채점자: 나만의 평가 지표 만들기