> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # Prompt alignment Scorer `createPromptAlignmentScorerLLM()` 関数は、意図の理解と要件の充足に加え、応答の完全性と形式の適切性という観点から、Agent の応答がユーザープロンプトにどの程度一致しているかを評価する Scorer を作成します。 ## パラメーター **model** (`MastraModelConfig`): プロンプトと応答の整合性を評価するために使用する言語モデル **options** (`PromptAlignmentOptions`): Scorer の設定オプション ## `.run()` の戻り値 **score** (`number`): 0 から scale までの多次元整合性スコア(デフォルト:0~1) **reason** (`string`): 詳細な内訳を含む、プロンプト整合性評価の人が読める説明 `.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 } } ``` ## スコアリングの詳細 ### Scorer の設定 scale パラメーターと評価モードを調整し、スコアリングの要件に合わせて Prompt Alignment Scorer をカスタマイズできます。 ```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 Alignment は、評価モードに応じて変化する重み付きスコアリングにより、4つの主要な観点から応答を評価します。 #### User モード('user') ユーザープロンプトとの整合性のみを評価します。 1. **意図の整合性**(重み 40%):応答がユーザーの中心的な要求に対応しているか 2. **要件の充足**(重み 30%):ユーザーのすべての要件を満たしているか 3. **完全性**(重み 20%):応答がユーザーのニーズに対して十分に詳しいか 4. **応答の適切性**(重み 10%):形式とトーンがユーザーの期待に合っているか #### System モード('system') システムガイドラインへの準拠のみを評価します。 1. **意図の整合性**(重み 35%):応答がシステムの振る舞いに関するガイドラインに従っているか 2. **要件の充足**(重み 35%):システムのすべての制約を遵守しているか 3. **完全性**(重み 15%):応答がシステムのすべてのルールに従っているか 4. **応答の適切性**(重み 15%):形式とトーンがシステム仕様に合っているか #### Both モード('both'、デフォルト) ユーザーとシステムの両方に対する整合性評価を組み合わせます。 - **ユーザーとの整合性**:最終スコアの 70%(User モードの重みを使用) - **システムへの準拠**:最終スコアの 30%(System モードの重みを使用) - ユーザー満足度とシステム準拠をバランスよく評価 ### スコアリング式 **User モード:** ```text Weighted Score = (intent_score × 0.4) + (requirements_score × 0.3) + (completeness_score × 0.2) + (appropriateness_score × 0.1) Final Score = Weighted Score × scale ``` **System モード:** ```text Weighted Score = (intent_score × 0.35) + (requirements_score × 0.35) + (completeness_score × 0.15) + (appropriateness_score × 0.15) Final Score = Weighted Score × scale ``` **Both モード(デフォルト):** ```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 ``` **重み配分の根拠**: - **User モード**:ユーザー満足度のため、意図(40%)と要件(30%)を優先 - **System モード**:振る舞いへの準拠(35%)と制約(35%)を同じ比率で評価 - **Both モード**: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**:整合性が非常に低く、応答がプロンプトに十分対応していない ### 各モードを使用する場面 **User モード(`'user'`)** — 次の場合に使用します。 - ユーザー満足度の観点からカスタマーサービスの応答を評価する - ユーザー視点でコンテンツ生成の品質をテストする - 応答がユーザーの質問にどの程度対応しているかを測定する - システム制約を考慮せず、要求の充足のみに注目する **System モード(`'system'`)** — 次の場合に使用します。 - AI の安全性と振る舞いに関するガイドラインへの準拠を監査する - Agent がブランドボイスとトーンの要件に従っていることを確認する - コンテンツポリシーと制約への準拠を検証する - システムレベルの振る舞いの一貫性をテストする **Both モード(`'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) ``` ### プロンプトエンジニアリングの最適化 異なるプロンプトをテストして整合性を改善します。 ```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}`) } ``` ### Multi-Agent システムの評価 異なる Agent またはモデルを比較します。 ```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) ``` ### 高い整合性の例 この例では、応答がユーザーのプロンプトに完全に対応し、すべての要件を満たしています。 ```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.' } ``` ### 評価モードの例 #### User モード — ユーザープロンプトのみに注目 システム指示を無視し、応答がユーザーの要求にどの程度対応しているかを評価します。 ```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 ``` #### System モード — システムガイドラインのみに注目 システムの振る舞いに関するガイドラインと制約への準拠を評価します。 ```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 ``` #### Both モード — 組み合わせた評価(デフォルト) ユーザーの意図の充足とシステム準拠の両方を、重み付きスコアリング(ユーザー 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 ``` ## 他の Scorer との比較 | 観点 | Prompt Alignment | Answer Relevancy | Faithfulness | | ---------- | ---------------- | ---------------- | ------------------- | | **焦点** | プロンプトへの多次元的な準拠 | クエリと応答の関連性 | コンテキストへの根拠付け | | **評価** | 意図、要件、完全性、形式 | クエリとの意味的類似性 | コンテキストとの事実的一貫性 | | **ユースケース** | 一般的なプロンプトへの追従 | 情報検索 | RAG/コンテキストベースのシステム | | **観点数** | 重み付きの4観点 | 単一の関連性観点 | 単一の Faithfulness 観点 | ## 関連項目 - [回答関連性 Scorer](https://mastra.zisheng.pro/ja/reference/evals/answer-relevancy):クエリと応答の関連性を評価します。 - [Faithfulness Scorer](https://mastra.zisheng.pro/ja/reference/evals/faithfulness):コンテキストへの根拠付けを測定します。 - [Tool Call Accuracy Scorer](https://mastra.zisheng.pro/ja/reference/evals/tool-call-accuracy):Tool の選択を評価します。 - [カスタム Scorer](https://mastra.zisheng.pro/ja/docs/evals/custom-scorers):独自の評価指標を作成します。