> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ko/llms.txt # Prompt 정렬 채점자 그만큼`createPromptAlignmentScorerLLM()`기능은 Agent 응답이 의도 이해 및 요구 사항 이행, 응답 완전성 및 형식 적절성에 걸쳐 사용자 Prompt와 얼마나 잘 일치하는지 평가하는 점수를 생성합니다. ## 매개변수 **model** (`MastraModelConfig`): Prompt와 응답의 정렬을 평가하는 데 사용할 언어 Model **options** (`PromptAlignmentOptions`): 채점기 구성 옵션 ## `.run()`보고 **score** (`number`): 0과 scale 사이의 다차원 정렬 점수(기본값 0\~1) **reason** (`string`): Prompt 정렬 평가를 세부 내역과 함께 설명하는 사람이 읽을 수 있는 내용 `.run()`다음과 같은 형태로 결과를 반환합니다. ```typescript { runId: string, score: number, reason: string, analyzeStepResult: { intentAlignment: { score: number, primaryIntent: string, isAddressed: boolean, reasoning: string }, requirementsFulfillment: { requirements: Array<{ requirement: string, isFulfilled: boolean, reasoning: string }>, overallScore: number }, completeness: { score: number, missingElements: string[], reasoning: string }, responseAppropriateness: { score: number, formatAlignment: boolean, toneAlignment: boolean, reasoning: string }, overallAssessment: string } } ``` ## 채점 세부정보 ### 득점자 구성 척도 매개변수와 평가 모드를 점수 요구 사항에 맞게 조정하여 Prompt 정렬 점수 측정기를 사용자 정의할 수 있습니다. ```typescript const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { scale: 10, // Score from 0-10 instead of 0-1 evaluationMode: 'both', // 'user', 'system', or 'both' (default) }, }) ``` ### 다차원 분석 Prompt 정렬은 평가 모드에 따라 조정되는 가중치 채점을 통해 4가지 주요 차원에 걸쳐 응답을 평가합니다. #### 사용자 모드('사용자') 사용자 Prompt와의 정렬만 평가합니다. 1. **의도 정렬**(40% 가중치): 응답이 사용자의 핵심 요청을 해결하는지 여부 2. **요구사항 이행**(30% 가중치): 모든 사용자 요구 사항을 충족하는 경우 3. **완전성**(20% 가중치): 사용자 요구에 맞게 응답이 상세하게 작성되었는지 여부 4. **대응의 적절성**(가중치 10%): 형식과 어조가 사용자 기대와 일치하는 경우 #### 시스템 모드('시스템') 시스템 지침 준수 여부만 평가합니다. 1. **의도 정렬**(35% 가중치): 응답이 시스템 행동 지침을 따르는지 여부 2. **요구사항 이행**(35% 가중치): 모든 시스템 제약 조건을 준수하는 경우 3. **완전성**(15% 가중치): 응답이 모든 시스템 규칙을 준수하는지 여부 4. **대응의 적절성**(15% 가중치): 형식과 톤이 시스템 사양과 일치하는 경우 #### 둘 다 모드('모두' - 기본값) 사용자 및 시스템 정렬 평가를 결합합니다. - **사용자 정렬**: 최종 점수의 70% (사용자 모드 가중치 사용) - **시스템 준수**: 최종 점수의 30% (시스템 모드 가중치 사용) - 사용자 만족도와 시스템 준수에 대한 균형 잡힌 평가를 제공합니다. ### 채점 공식 **사용자 모드:** ```text Weighted Score = (intent_score × 0.4) + (requirements_score × 0.3) + (completeness_score × 0.2) + (appropriateness_score × 0.1) Final Score = Weighted Score × scale ``` **시스템 모드:** ```text Weighted Score = (intent_score × 0.35) + (requirements_score × 0.35) + (completeness_score × 0.15) + (appropriateness_score × 0.15) Final Score = Weighted Score × scale ``` **두 모드(기본값):** ```text User Score = (user dimensions with user weights) System Score = (system dimensions with system weights) Weighted Score = (User Score × 0.7) + (System Score × 0.3) Final Score = Weighted Score × scale ``` **무게 배분의 이론적 근거**: - **사용자 모드**: 사용자 만족도를 위해 의도(40%)와 요구사항(30%)을 우선시합니다. - **시스템 모드**: 행동 순응(35%)과 제약(35%)의 균형을 동일하게 유지합니다. - **둘 다 모드**: 70/30 분할로 시스템 규정 준수를 유지하면서 사용자 요구 사항을 최우선으로 보장합니다. ### 점수 해석 - **0.9-1.0**= 모든 차원에서 탁월한 정렬 - **0.8-0.9**= 약간의 틈이 있는 매우 좋은 정렬 - **0.7-0.8**= 정렬은 양호하지만 일부 요구 사항이나 완전성이 누락됨 - **0.6-0.7**= 눈에 띄는 간격이 있는 적당한 정렬 - **0.4-0.6**= 실질적인 문제와의 연계 불량 - **0.0-0.4**= 매우 열악한 정렬, 응답이 Prompt를 효과적으로 처리하지 못함 ### 각 모드를 사용하는 경우 **사용자 모드(`'user'`)**- 다음과 같은 경우에 사용하세요. - 사용자 만족도를 위한 고객 서비스 응답 평가 - 사용자 관점에서 콘텐츠 생성 품질 테스트 - 응답이 사용자 질문을 얼마나 잘 해결하는지 측정 - 시스템 제약 없이 요청 이행에만 집중 **시스템 모드(`'system'`)**- 다음과 같은 경우에 사용하세요. - AI 안전 및 행동 지침 준수 감사 - Agent가 브랜드 목소리 및 어조 요구 사항을 따르도록 합니다. - 콘텐츠 정책 및 제약 조건 준수 여부 확인 - 시스템 수준 동작 일관성 테스트 **두 모드(`'both'`)**- 다음 경우에 사용합니다(기본값, 권장): - AI Agent 성능 종합 평가 - 사용자 만족도와 시스템 규정 준수 간의 균형 유지 - 사용자 및 시스템 요구 사항이 모두 중요한 생산 모니터링 - 신속한 대응 조정에 대한 전체적인 평가 ## 일반적인 사용 사례 ### 코드 생성 평가 평가에 이상적: - 프로그래밍 작업 완료 - 코드 품질 및 완성도 - 코딩 요구 사항 준수 - 형식 사양(함수, 클래스 등) ```typescript // Example: API endpoint creation const codePrompt = 'Create a REST API endpoint with authentication and rate limiting' // Scorer evaluates: intent (API creation), requirements (auth + rate limiting), // completeness (full implementation), format (code structure) ``` ### 평가 후 지침 완벽한 대상: - 작업 완료 확인 - 다단계 지침 준수 - 요구 사항 준수 확인 - 교육 내용 평가 ```typescript // Example: Multi-requirement task const taskPrompt = 'Write a Python class with initialization, validation, error handling, and documentation' // Scorer tracks each requirement individually and provides detailed breakdown ``` ### 콘텐츠 형식 검증 다음에 유용합니다: - 형식 사양 준수 - 스타일 가이드 준수 - 출력 구조 검증 - 응답 적합성 확인 ```typescript // Example: Structured output const formatPrompt = 'Explain the differences between let and const in JavaScript using bullet points' // Scorer evaluates content accuracy AND format compliance ``` ### Agent 응답 품질 AI Agent가 사용자 지침을 얼마나 잘 따르는지 측정합니다. ```typescript const agent = new Agent({ id: 'coding-assistant', name: 'CodingAssistant', instructions: 'You are a helpful coding assistant. Always provide working code examples.', model: 'openai/gpt-5.6-sol', }) // Evaluate comprehensive alignment (default) const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { evaluationMode: 'both' }, // Evaluates both user intent and system guidelines }) // Evaluate just user satisfaction const userScorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { evaluationMode: 'user' }, // Focus only on user request fulfillment }) // Evaluate system compliance const systemScorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { evaluationMode: 'system' }, // Check adherence to system instructions }) const result = await scorer.run(agentRun) ``` ### 신속한 엔지니어링 최적화 정렬을 개선하기 위해 다양한 Prompt를 테스트합니다. ```typescript const prompts = [ 'Write a function to calculate factorial', 'Create a Python function that calculates factorial with error handling for negative inputs', 'Implement a factorial calculator in Python with: input validation, error handling, and docstring', ] // Compare alignment scores to find the best prompt for (const prompt of prompts) { const result = await scorer.run(createTestRun(prompt, response)) console.log(`Prompt alignment: ${result.score}`) } ``` ### 다중 Agent 시스템 평가 다양한 Agent 또는 Model을 비교하세요. ```typescript const agents = [agent1, agent2, agent3]; const testPrompts = [...]; // Array of test prompts for (const agent of agents) { let totalScore = 0; for (const prompt of testPrompts) { const response = await agent.run(prompt); const evaluation = await scorer.run({ input: prompt, output: response }); totalScore += evaluation.score; } console.log(`${agent.name} average alignment: ${totalScore / testPrompts.length}`); } ``` ## 예 ### 기본 구성 ```typescript import { createPromptAlignmentScorerLLM } from '@mastra/evals' const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', }) // Evaluate a code generation task const result = await scorer.run({ input: [ { role: 'user', content: 'Write a Python function to calculate factorial with error handling', }, ], output: { role: 'assistant', text: `def factorial(n): if n < 0: raise ValueError("Factorial not defined for negative numbers") if n == 0: return 1 return n * factorial(n-1)`, }, }) // Result: { score: 0.95, reason: "Excellent alignment - function addresses intent, includes error handling..." } ``` ### 사용자 정의 구성 예 ```typescript // Configure scale and evaluation mode const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { scale: 10, // Score from 0-10 instead of 0-1 evaluationMode: 'both', // 'user', 'system', or 'both' (default) }, }) // User-only evaluation - focus on user satisfaction const userScorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { evaluationMode: 'user' }, }) // System-only evaluation - focus on compliance const systemScorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { evaluationMode: 'system' }, }) const result = await scorer.run(testRun) // Result: { score: 8.5, reason: "Score: 8.5 out of 10 - Good alignment with both user intent and system guidelines..." } ``` ### 형식별 평가 ```typescript // Evaluate bullet point formatting const result = await scorer.run({ input: [ { role: 'user', content: 'List the benefits of TypeScript in bullet points', }, ], output: { role: 'assistant', text: 'TypeScript provides static typing, better IDE support, and enhanced code reliability.', }, }) // Result: Lower appropriateness score due to format mismatch (paragraph vs bullet points) ``` ### 우수한 정렬 예 이 예에서 응답은 모든 요구 사항이 충족된 사용자의 Prompt를 완전히 해결합니다. ```typescript import { createPromptAlignmentScorerLLM } from '@mastra/evals/scorers/prebuilt' const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', }) const inputMessages = [ { role: 'user', content: 'Write a Python function to calculate factorial with error handling for negative numbers', }, ] const outputMessage = { text: `def factorial(n): """Calculate factorial of a number.""" if n < 0: raise ValueError("Factorial not defined for negative numbers") if n == 0 or n == 1: return 1 return n * factorial(n - 1)`, } const result = await scorer.run({ input: inputMessages, output: outputMessage, }) console.log(result) ``` ### 뛰어난 정렬 출력 출력은 의도를 완벽하게 해결하고 모든 요구 사항을 충족하므로 높은 점수를 받습니다. 또한 적절한 형식을 사용합니다. ```typescript { score: 0.95, reason: 'The score is 0.95 because the response perfectly addresses the primary intent of creating a factorial function and fulfills all requirements including Python implementation, error handling for negative numbers, and proper documentation. The code format is appropriate and the implementation is complete.' } ``` ### 부분 정렬 예 이 예에서 응답은 핵심 의도를 다루지만 일부 요구 사항이 누락되었거나 형식 문제가 있습니다. ```typescript import { createPromptAlignmentScorerLLM } from '@mastra/evals/scorers/prebuilt' const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', }) const inputMessages = [ { role: 'user', content: 'List the benefits of TypeScript in bullet points', }, ] const outputMessage = { text: 'TypeScript provides static typing, better IDE support, and enhanced code reliability through compile-time error checking.', } const result = await scorer.run({ input: inputMessages, output: outputMessage, }) console.log(result) ``` #### 부분 정렬 출력 콘텐츠는 정확하지만 요청된 형식(글머리 기호)을 따르지 않기 때문에 출력은 낮은 점수를 받습니다. ```typescript { score: 0.75, reason: 'The score is 0.75 because the response addresses the intent of explaining TypeScript benefits and provides accurate information, but fails to use the requested bullet point format, resulting in lower appropriateness scoring.' } ``` ### 잘못된 정렬 예 이 예에서는 응답이 사용자의 특정 요구 사항을 해결하지 못합니다. ```typescript import { createPromptAlignmentScorerLLM } from '@mastra/evals/scorers/prebuilt' const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', }) const inputMessages = [ { role: 'user', content: 'Write a Python class with initialization, validation, error handling, and documentation', }, ] const outputMessage = { text: `class Example: def __init__(self, value): self.value = value`, } const result = await scorer.run({ input: inputMessages, output: outputMessage, }) console.log(result) ``` ### 정렬 출력 불량 출력은 요구 사항, 유효성 검사 누락, 오류 처리 및 문서를 부분적으로만 충족하기 때문에 낮은 점수를 받습니다. ```typescript { score: 0.35, reason: 'The score is 0.35 because while the response addresses the basic intent of creating a Python class with initialization, it fails to include validation, error handling, and documentation as specifically requested, resulting in incomplete requirement fulfillment.' } ``` ### 평가 모드 예 #### 사용자 모드 - 사용자 Prompt에만 집중 시스템 지침을 무시하고 응답이 사용자의 요청을 얼마나 잘 처리하는지 평가합니다. ```typescript const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { evaluationMode: 'user' }, }) const result = await scorer.run({ input: { inputMessages: [ { role: 'user', content: 'Explain recursion with an example', }, ], systemMessages: [ { role: 'system', content: 'Always provide code examples in Python', }, ], }, output: { text: 'Recursion is when a function calls itself. For example: factorial(5) = 5 * factorial(4)', }, }) // Scores high for addressing user request, even without Python code ``` #### 시스템 모드 - 시스템 지침에만 집중 시스템 동작 지침 및 제약 조건 준수 여부를 평가합니다. ```typescript const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { evaluationMode: 'system' }, }) const result = await scorer.run({ input: { systemMessages: [ { role: 'system', content: 'You are a helpful assistant. Always be polite, concise, and provide examples.', }, ], inputMessages: [ { role: 'user', content: 'What is machine learning?', }, ], }, output: { text: 'Machine learning is a subset of AI where computers learn from data. For example, spam filters learn to identify unwanted emails by analyzing patterns in previously marked spam.', }, }) // Evaluates politeness, conciseness, and example provision ``` #### 두 모드 - 통합 평가(기본값) 가중치 점수(사용자 70%, 시스템 30%)를 통해 사용자 의도 이행과 시스템 준수를 모두 평가합니다. ```typescript const scorer = createPromptAlignmentScorerLLM({ model: 'openai/gpt-5.6-sol', options: { evaluationMode: 'both' }, // This is the default }) const result = await scorer.run({ input: { systemMessages: [ { role: 'system', content: 'Always provide code examples when explaining programming concepts', }, ], inputMessages: [ { role: 'user', content: 'Explain how to reverse a string', }, ], }, output: { text: `To reverse a string, you can iterate through it backwards. Here's an example in Python: def reverse_string(s): return s[::-1] # Usage: reverse_string("hello") returns "olleh"`, }, }) // High score for both addressing the user's request AND following system guidelines ``` ## 다른 득점원과의 비교 | 측면 | Prompt 정렬 | 응답 관련성 | 충실성 | | --------- | ------------------ | ------------ | --------------- | | **초점** | 다차원적인 Prompt 준수 | 쿼리와 응답 간 관련성 | 컨텍스트 기반성 | | **평가** | 의도, 요구 사항, 완전성, 형식 | 쿼리와의 의미적 유사성 | 컨텍스트와의 사실적 일관성 | | **사용 사례** | 일반적인 Prompt 준수 | 정보 검색 | RAG/컨텍스트 기반 시스템 | | **차원** | 가중치가 적용된 4개 차원 | 단일 관련성 차원 | 단일 충실성 차원 | ## 관련된 - [답변 관련성 득점자](https://mastra.zisheng.pro/ko/reference/evals/answer-relevancy): 쿼리-응답 관련성을 평가합니다. - [성실성 득점자](https://mastra.zisheng.pro/ko/reference/evals/faithfulness): 맥락 기반성을 측정합니다. - [Tool 호출 정확도 득점자](https://mastra.zisheng.pro/ko/reference/evals/tool-call-accuracy): Tool 선택을 평가합니다. - [맞춤 채점자](https://mastra.zisheng.pro/ko/docs/evals/custom-scorers): 나만의 평가 지표 만들기