> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # 提示詞一致性評分器 `createPromptAlignmentScorerLLM()` 函式會建立評分器,從意圖理解、要求滿足程度、回應完整性與格式適切性等面向,評估 Agent 回應與使用者提示詞相符的程度。 ## 參數 **model** (`MastraModelConfig`): 用於評估提示詞與回應一致性的語言模型 **options** (`PromptAlignmentOptions`): 評分器的設定選項 ## `.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 } } ``` ## 評分詳情 ### 評分器設定 你可以調整 scale 參數與評估模式,讓提示詞一致性評分器符合評分需求。 ```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) }, }) ``` ### 多面向分析 提示詞一致性會從四個主要面向評估回應,並依評估模式調整加權方式: #### 使用者模式('user') 只評估與使用者提示詞的一致性: 1. **意圖一致性**(權重 40%):回應是否處理使用者的核心要求 2. **要求滿足程度**(權重 30%):是否滿足所有使用者要求 3. **完整性**(權重 20%):回應對使用者需求而言是否足夠詳盡 4. **回應適切性**(權重 10%):格式與語氣是否符合使用者期待 #### 系統模式('system') 只評估系統規範遵循程度: 1. **意圖一致性**(權重 35%):回應是否遵循系統行為準則 2. **要求滿足程度**(權重 35%):是否遵守所有系統限制 3. **完整性**(權重 15%):回應是否遵循所有系統規則 4. **回應適切性**(權重 15%):格式與語氣是否符合系統規格 #### 雙重模式('both'——預設) 同時評估使用者與系統的一致性: - **使用者一致性**:占最終分數的 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** = 一致性極差,回應未能有效處理提示詞 ### 各模式的使用時機 **使用者模式(`'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) ``` ### 提示詞工程最佳化 測試不同提示詞以改善一致性: ```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 或模型: ```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.' } ``` ### 評估模式範例 #### 使用者模式——只聚焦於使用者提示詞 評估回應處理使用者要求的程度,忽略系統指示: ```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 ``` ## 與其他評分器比較 | 面向 | 提示詞一致性 | 答案相關性 | Faithfulness | | -------- | ------------ | --------- | -------------------- | | **重點** | 多面向的提示詞遵循情形 | 查詢與回應的相關性 | 以 context 為根據的程度 | | **評估內容** | 意圖、要求、完整性、格式 | 與查詢的語意相似度 | 與 context 的事實一致性 | | **使用情境** | 一般提示詞遵循 | 資訊擷取 | RAG/以 context 為基礎的系統 | | **面向** | 4 個加權面向 | 單一相關性面向 | 單一 faithfulness 面向 | ## 相關資源 - [答案相關性評分器](https://mastra.zisheng.pro/zh-TW/reference/evals/answer-relevancy):評估查詢與回應的相關性 - [Faithfulness 評分器](https://mastra.zisheng.pro/zh-TW/reference/evals/faithfulness):衡量以 context 為根據的程度 - [Tool 呼叫準確度評分器](https://mastra.zisheng.pro/zh-TW/reference/evals/tool-call-accuracy):評估 Tool 選擇 - [自訂評分器](https://mastra.zisheng.pro/zh-TW/docs/evals/custom-scorers):建立自己的評估指標