具備可追溯引用與離線評測集之企業級 RAG API 架構及達標率測算
透過混合檢索與黃金評測集自動化評分,將 RAG 效能轉化為可量化的工程指標,實現 86% 綜合完成度。

量化可完成度
整體 86% 的完成度得益於成熟的混合檢索策略與標準化的評測集設計,AI 在生成評測邏輯與提示詞工程方面表現卓越。主要挑戰在於多跳推理(77 分)的複雜邏輯編排及特定領域拒答策略的細化調優,此部分需要更多人工領域知識介入。
四維達成明細
BM25 與向量檢索的互補性極高,能精準覆蓋專有名詞與模糊語意查詢。
強制錨點約束有效防止了幻覺,但在長文本摘要時偶有引用錯位。
系統能準確識別空上下文並觸發拒答,但拒答話術的友好度需微調。
跨文件關聯推理邏輯複雜,當前架構在長鏈條推理中易丟失中間狀態。
人工把關檢查點
在部署上線前,必須由領域專家人工審核黃金評測集中的 10 道核心題目,確保預期答案與業務邏輯一致;同時需人工抽檢 5 個真實使用者查詢,驗證 `[doc#chunk]` 錨點在實際生成中的自然度與準確性。
升級 / 降級路徑
若預算或硬體受限,可暫時降級為純向量檢索並移除 BM25 元件,同時減少黃金評測集規模至 10 題以快速驗證核心鏈路。若需更高精度,可引入重排序模型(Reranker)並增加多跳推理的鏈式思考(CoT)提示詞。
適用場景與前提
目標使用者為需要建構高可信度問答系統的企業架構師與後端工程師。環境需支援向量資料庫(如 Milvus/Pinecone)及混合檢索中間件。理想用例包括內部知識庫問答、合規性政策查詢及多文件複雜推理任務。
可直接複製的工程設定
定义包含问题、预期答案、引用锚点及评分规则的黄金评测集结构,用于自动化 RAG 效果打分。
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Golden RAG Evaluation Dataset",
"description": "Schema for production-grade RAG evaluation with citation anchors",
"type": "object",
"properties": {
"id": { "type": "string", "description": "Unique identifier for the test case" },
"question": { "type": "string", "description": "The user query to be answered" },
"expectedAnswer": { "type": "string", "description": "The ground truth answer" },
"requiredCitations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"docId": { "type": "string" },
"chunkIndex": { "type": "integer" },
"expectedSnippet": { "type": "string" }
},
"required": ["docId", "chunkIndex"]
},
"description": "List of mandatory citation anchors the model must reference"
},
"scoringRules": {
"type": "object",
"properties": {
"hybrid_recall_weight": { "type": "number", "default": 0.3 },
"cite_fidelity_weight": { "type": "number", "default": 0.4 },
"refusal_honesty_weight": { "type": "number", "default": 0.2 },
"multi_hop_weight": { "type": "number", "default": 0.1 }
}
}
},
"required": ["id", "question", "expectedAnswer", "requiredCitations"]
}TypeScript utility to enforce strict citation anchor formatting and validate retrieval context before generation.
import { z } from 'zod';
// Schema for strict citation anchor validation
const CitationAnchorSchema = z.object({
docId: z.string(),
chunkIndex: z.number(),
snippet: z.string(),
});
type CitationAnchor = z.infer<typeof CitationAnchorSchema>;
/**
* Enforces `[doc#chunk]` format and validates context before generation.
* Ensures every claim in the response is backed by a retrieved anchor.
*/
export function enforceCitationConstraints(
context: CitationAnchor[],
userQuery: string
): {
validatedContext: CitationAnchor[];
missingAnchors: string[];
}
{
// Filter out empty or low-relevance chunks
const validatedContext = context.filter(c => c.snippet.length > 20);
// Simulate logic to check if query intent is covered by context
// In production, use semantic similarity here
const missingAnchors: string[] = [];
if (validatedContext.length === 0) {
missingAnchors.push("No relevant documents found for query.");
}
return { validatedContext, missingAnchors };
}
/**
* Generates the system prompt injection for the LLM to enforce citation rules.
*/
export function generateCitationSystemPrompt(): string {
return `
You are a strict RAG assistant. You MUST follow these rules:
1. Only answer using information from the provided [Citations].
2. Every factual claim must be immediately followed by a citation in the format: [doc#chunk].
3. If the answer cannot be derived from the citations, state clearly: "I cannot answer this based on the provided knowledge base."
4. Do not hallucinate citations. If no citation exists for a point, do not make the point.
[Citations]:
${(ctx: any) => ctx.map(c => `[${c.docId}#${c.chunkIndex}]: ${c.snippet}`).join('\n')}
`;
}AI Vibe Coding 四步實戰
- 1
初始化黃金評測集 Schema 與資料結構
目標: 定義標準化的評測資料格式,確保後續自動化評分腳本能正確解析問題、答案及引用要求。
Prompt建立一個 JSON Schema 檔案 'eval/golden-dataset.schema.json',用於定義 RAG 評測集。必須包含欄位:id, question, expectedAnswer, requiredCitations (陣列,包含 docId, chunkIndex, snippet), 以及 scoringRules。確保 schema 符合 JSON Schema Draft-07 標準,並添加詳細的中文描述。驗收標準:
執行 'cat eval/golden-dataset.schema.json' 並驗證其結構包含所有必需欄位,且無語法錯誤。 - 2
實現引用錨點強制約束的提示詞工程
目標: 編寫系統提示詞,強制 LLM 在生成回答時嚴格綁定 `[doc#chunk]` 格式的引用,杜絕無依據陳述。
Prompt編寫 TypeScript 函數 'generateCitationSystemPrompt()',該函數回傳一段系統提示詞。提示詞必須明確要求:1. 僅使用提供的引用資訊回答;2. 每個事實後緊跟 [doc#chunk] 格式;3. 無法回答時明確拒答。同時編寫 'enforceCitationConstraints' 函數用於在生成前過濾無效上下文。驗收標準:
呼叫 'generateCitationSystemPrompt()' 並檢查輸出是否包含明確的格式指令和拒答邏輯。 - 3
建構混合檢索與重排序流水線
目標: 整合 BM25 和向量檢索,並加入 Reranker 模型以提升 Top-K 結果的相關性,支撐高召回率。
Prompt設計一個 RAG 檢索服務架構,使用環境變數 API_BASE_URL 和 API_KEY 呼叫外部檢索服務。實現混合檢索邏輯:先並行執行 BM25 和向量檢索,取得 Top-50 結果,再呼叫 Reranker 模型對結果進行重排序,最終回傳 Top-5 作為上下文。確保程式碼中不包含硬編碼金鑰。驗收標準:
啟動服務並發送測試查詢,檢查回傳的上下文是否包含混合檢索結果,且引用格式正確。 - 4
部署自動化評測腳本並計算達標率
目標: 編寫腳本載入黃金評測集,呼叫 RAG 服務,自動比對回答與預期答案,計算各項維度得分。
Prompt建立一個 Python 腳本 'run_evaluation.py'。該腳本應載入 'eval/golden-dataset.schema.json' 定義的評測集,對每個問題呼叫 RAG 服務,提取生成的引用錨點,並與 'requiredCitations' 比對。計算 hybrid_recall, cite_fidelity, refusal_honesty, multi_hop 四個維度的得分,並輸出總分。驗收標準:
執行 'python run_evaluation.py',確認輸出包含四個維度的具體分數及總分,且分數邏輯符合預期。
常見踩坑與解法
- 引用錨點格式不一致:LLM 可能輸出 `[doc:1]` 而非 `[doc#1]`,需在解析層增加正規表示式驗證或後處理標準化。
- 多跳推理丟失:在跨文件推理中,中間結論未被正確傳遞,需引入 CoT(思維鏈)提示詞或分步檢索策略。
- 評測集偏差:黃金評測集若僅覆蓋簡單查詢,會導致模型在複雜場景下表現虛高,需定期補充長尾問題。
常見問題
如何平衡召回率與回答的準確性?
透過調整混合檢索中 BM25 和向量檢索的權重,並引入 Reranker 模型來過濾低品質結果,通常 Reranker 能顯著提升 cite_fidelity。
如果知識庫更新頻繁,如何維護黃金評測集?
建議將評測集分為核心靜態集(覆蓋基礎業務邏輯)和動態測試集(覆蓋新文件),核心集每季度更新一次,動態集隨文件上線自動生成。
多跳推理得分低(77 分)該如何優化?
優化方案包括:1. 在提示詞中顯式要求分步推理;2. 修改檢索策略,對多跳問題執行多次迭代檢索;3. 在評測集中增加更多跨文件關聯的測試用例以訓練模型。


