Enterprise RAG API Architecture with Traceable Citations and Offline Evaluation Suite, Including Compliance Rate Calculation
Automate scoring through hybrid retrieval and a gold standard evaluation suite to transform RAG performance into quantifiable engineering metrics, achieving an 86% overall completion rate.

Completion Score
The overall 86% completion rate is attributed to a mature hybrid retrieval strategy and standardized evaluation suite design, with AI demonstrating excellence in generating evaluation logic and prompt engineering. The main challenges lie in the complex logic orchestration for multi-hop reasoning (77 points) and the fine-tuning of specific domain refusal strategies, areas that require more human domain expertise intervention.
Dimension breakdown
The complementarity between BM25 and vector retrieval is extremely high, enabling precise coverage of proprietary terms and fuzzy semantic queries.
The mandatory anchor constraints effectively prevent hallucinations, though occasional citation misalignments occur during long-text summarization.
The system can accurately identify empty contexts and trigger refusals, but the friendliness of the refusal phrasing requires fine-tuning.
Cross-document association reasoning logic is complex; the current architecture tends to lose intermediate states in long-chain reasoning.
Human checkpoint
Before launch, domain experts must manually review 10 core questions in the gold standard evaluation suite to ensure expected answers align with business logic. Simultaneously, 5 real user queries must be manually spot-checked to verify the naturalness and accuracy of `[doc#chunk]` anchors in actual generation.
Upgrade / downgrade path
If budget or hardware is constrained, you can temporarily downgrade to pure vector retrieval and remove the BM25 component, while reducing the gold standard evaluation suite size to 10 questions for rapid core pipeline validation. For higher precision, you can introduce a reranking model (Reranker) and add Chain-of-Thought (CoT) prompts for multi-hop reasoning.
When to use & prerequisites
The target audience includes enterprise architects and backend engineers building high-trust Q&A systems. The environment must support vector databases (e.g., Milvus/Pinecone) and hybrid retrieval middleware. Ideal use cases include internal knowledge base Q&A, compliance policy queries, and multi-document complex reasoning tasks.
Ready-to-copy configs
定义包含问题、预期答案、引用锚点及评分规则的黄金评测集结构,用于自动化 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 in 4 steps
- 1
Initialize Golden Evaluation Suite Schema and Data Structure
Goal: Define a standardized evaluation data format to ensure subsequent automated scoring scripts can correctly parse questions, answers, and citation requirements.
PromptCreate a JSON Schema file 'eval/golden-dataset.schema.json' to define the RAG evaluation suite. It must include fields: id, question, expectedAnswer, requiredCitations (array containing docId, chunkIndex, snippet), and scoringRules. Ensure the schema complies with the JSON Schema Draft-07 standard and add detailed descriptions in Chinese.Verify:
Run 'cat eval/golden-dataset.schema.json' and verify its structure includes all required fields with no syntax errors. - 2
Implement Prompt Engineering for Mandatory Citation Anchor Constraints
Goal: Write system prompts that strictly bind the LLM to `[doc#chunk]` format citations when generating answers,杜绝 unsupported statements.
PromptWrite a TypeScript function 'generateCitationSystemPrompt()' that returns a system prompt. The prompt must explicitly require: 1. Answering only using provided citation information; 2. Immediately following each fact with `[doc#chunk]` format; 3. Explicitly refusing to answer when unable. Also write an 'enforceCitationConstraints' function to filter invalid contexts before generation.Verify:
Call 'generateCitationSystemPrompt()' and check if the output includes explicit format instructions and refusal logic. - 3
Build Hybrid Retrieval and Reranking Pipeline
Goal: Integrate BM25 and vector retrieval, and add a Reranker model to improve the relevance of Top-K results, supporting high recall rates.
PromptDesign a RAG retrieval service architecture using environment variables API_BASE_URL and API_KEY to call external retrieval services. Implement hybrid retrieval logic: execute BM25 and vector retrieval in parallel first, obtain Top-50 results, then call the Reranker model to rerank the results, finally returning Top-5 as context. Ensure no hardcoded keys are included in the code.Verify:
Start the service and send a test query, checking if the returned context includes hybrid retrieval results and correct citation formats. - 4
Deploy Automated Evaluation Scripts and Calculate Compliance Rate
Goal: Write a script to load the golden evaluation suite, call the RAG service, automatically compare answers with expected answers, and calculate scores for each dimension.
PromptCreate a Python script 'run_evaluation.py'. This script should load the evaluation suite defined in 'eval/golden-dataset.schema.json', call the RAG service for each question, extract generated citation anchors, and compare them with 'requiredCitations'. Calculate scores for the four dimensions: hybrid_recall, cite_fidelity, refusal_honesty, and multi_hop, and output the total score.Verify:
Run 'python run_evaluation.py' and confirm the output includes specific scores for the four dimensions and the total score, with score logic matching expectations.
Pitfalls & fixes
- Inconsistent citation anchor formats: The LLM might output `[doc:1]` instead of `[doc#1]`, requiring regex validation or post-processing standardization at the parsing layer.
- Lost multi-hop reasoning: Intermediate conclusions are not correctly passed during cross-document reasoning; CoT (Chain-of-Thought) prompts or step-by-step retrieval strategies need to be introduced.
- Evaluation suite bias: If the gold standard evaluation suite only covers simple queries, it may lead to inflated model performance in complex scenarios, requiring regular supplementation of long-tail questions.
FAQ
How to balance recall rate with answer accuracy?
By adjusting the weights of BM25 and vector retrieval in hybrid retrieval, and introducing a Reranker model to filter low-quality results; typically, Reranker significantly improves cite_fidelity.
If the knowledge base updates frequently, how to maintain the golden evaluation suite?
It is recommended to divide the evaluation suite into a core static set (covering basic business logic) and a dynamic test set (covering new documents). The core set should be updated quarterly, while the dynamic set is automatically generated as documents go live.
How to optimize low multi-hop reasoning scores (77 points)?
Optimization options include: 1. Explicitly require step-by-step reasoning in the prompt; 2. Modify the retrieval strategy to perform iterative retrieval for multi-hop questions; 3. Add more cross-document association test cases to the evaluation suite to train the model.


