This prompt is designed for RAG and search teams who need to programmatically evaluate the relevance of an AI-generated answer against a user's query and the provided context. It acts as an LLM judge, producing a structured relevance score, a detailed justification, and flags for off-topic drift or context misuse. Use this when you are building an automated evaluation harness, running regression tests on retrieval pipelines, or need a repeatable metric for answer-to-query alignment before shipping a new prompt or model. It is not a replacement for human evaluation of tone or style, nor is it designed for open-ended creative writing tasks.
Prompt
Relevance Scoring Prompt Template

When to Use This Prompt
Understand the job-to-be-done, the ideal user, and the operational boundaries for deploying an automated relevance scoring judge in a RAG or search pipeline.
The ideal user is an AI quality engineer or platform engineer embedding this prompt into a CI/CD gate. You must supply three inputs: the user's original query, the retrieved context chunks, and the final generated answer. The prompt expects these to be clearly delimited so the judge does not confuse evidence with output. In practice, wire this into your existing eval harness by feeding it the same query-context-answer triples you already log. Run it against a golden dataset of known-relevant and known-irrelevant examples to calibrate your pass/fail thresholds before relying on it as a gate. Avoid using this prompt when the answer quality depends on subjective style, brand voice, or creative flair—those dimensions require separate human-aligned rubrics.
Do not deploy this prompt as a real-time user-facing feature. It is an internal evaluation tool. If your application operates in a regulated domain—such as healthcare, legal, or finance—the output of this judge is a signal, not a compliance check. Always pair automated relevance scores with human review for high-stakes decisions, and log every judgment with its query, context, and answer for auditability. Next, copy the prompt template into your eval harness and run it against at least 50 labeled examples to establish your baseline score distribution before setting any automated gates.
Use Case Fit
Where the Relevance Scoring Prompt Template delivers reliable signal and where it introduces risk. Use these cards to decide if this eval harness fits your retrieval pipeline before integrating it into CI/CD.
Strong Fit: RAG Answer Quality Gates
Use when: you need automated, per-query scoring of how well a generated answer aligns with the user's question and the retrieved context. Guardrail: Pair relevance scores with a hallucination detection eval; a highly relevant answer can still fabricate details.
Poor Fit: Open-Domain Chat Without Retrieval
Avoid when: there is no retrieved context to ground the answer. The template measures context utilization and off-topic drift relative to provided evidence. Guardrail: For context-free generation, switch to a reference-free evaluation prompt that scores coherence and safety intrinsically.
Required Inputs: Query, Context, and Answer Triples
Risk: Missing or malformed inputs produce garbage scores. The template requires [USER_QUERY], [RETRIEVED_CONTEXT], and [GENERATED_ANSWER] in a structured format. Guardrail: Add a schema conformance eval upstream that validates input shape before the relevance scorer runs.
Operational Risk: Partial-Relevance Ambiguity
Risk: Answers that address the query but ignore half the context can score misleadingly high on simple relevance checks. Guardrail: Use the template's partial-relevance scoring axis and set a minimum context-utilization threshold. Flag outputs that cherry-pick evidence.
Operational Risk: Distraction-Resistance Gaps
Risk: Retrievers often pull tangentially related documents. The model may weave in off-topic details that sound plausible. Guardrail: Enable the template's distraction-resistance tests by injecting irrelevant passages into [RETRIEVED_CONTEXT] during eval runs and measuring score degradation.
Pipeline Fit: Pre-Release Regression Gate
Use when: you are comparing a new prompt or retriever version against a golden dataset of query-context-answer triples. Guardrail: Run the relevance scorer on both the baseline and candidate versions. Require no statistically significant regression in mean relevance score before promotion.
Copy-Ready Prompt Template
A reusable system prompt for an LLM judge that scores the relevance of a generated answer against a user query and its supporting context.
This prompt template is the core instruction set for an LLM judge tasked with evaluating retrieval-augmented generation (RAG) outputs. It is designed to be used as a system message in your evaluation harness, producing a structured relevance score that measures how well an answer aligns with the query, utilizes the provided context, and avoids off-topic drift. The template uses square-bracket placeholders for all dynamic inputs, making it ready to be wired into a scripted evaluation loop where you iterate over a golden dataset of query-context-answer triples.
textYou are an expert relevance evaluator for a RAG system. Your job is to score the alignment between a user's query, the retrieved context, and the generated answer. ## INPUT [QUERY] [CONTEXT] [ANSWER] ## SCORING CRITERIA Evaluate the answer on a scale of 1 to 5 based on the following: - **Score 5 (Perfect):** The answer directly addresses the query using only information from the context. It is concise and contains no extraneous information. - **Score 4 (Good):** The answer addresses the query using context, but includes minor, harmless extra details or is slightly verbose. - **Score 3 (Partial):** The answer partially addresses the query, but misses a key point, or relies on a mix of context and general knowledge. - **Score 2 (Weak):** The answer is tangentially related to the query but fails to use the context effectively, or mostly ignores the context. - **Score 1 (Irrelevant):** The answer does not address the query, directly contradicts the context, or is completely off-topic. ## DISTRACTION RESISTANCE If the context contains information irrelevant to the query, a perfect answer must ignore it. Penalize answers that incorporate distracting context. ## OUTPUT FORMAT Return ONLY a valid JSON object. Do not include any text outside the JSON block. { "score": <integer 1-5>, "rationale": "<One-sentence explanation referencing the context and query.>" } ## CONSTRAINTS - Do not judge the truthfulness of the context itself, only the answer's use of it. - If the answer is an empty string, the score must be 1. - If the query is unanswerable from the context, a perfect score requires the answer to state that clearly.
To adapt this template, replace the [QUERY], [CONTEXT], and [ANSWER] placeholders with your test data at runtime. For high-stakes production gates, you should calibrate this judge against human-annotated scores using the LLM Judge Calibration Prompt Template to validate that its scoring distribution matches your quality bar. Always run this evaluation on a held-out golden dataset before promoting a new prompt version, and log the rationale field to debug scoring disagreements.
Prompt Variables
Required and optional inputs for the Relevance Scoring Prompt Template. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before scoring begins.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY] | The user question or search intent to evaluate relevance against | What is the refund policy for annual subscriptions? | Non-empty string; max 2000 chars; reject if only whitespace or single word |
[CANDIDATE_ANSWER] | The retrieved or generated answer being scored for relevance | Annual subscriptions can be refunded within 30 days of purchase by contacting support. | Non-empty string; max 8000 chars; reject if identical to [QUERY] |
[RETRIEVED_CONTEXT] | Source passages used to produce the candidate answer, if RAG was used | ["Section 4.2: Refunds are processed within 30 days for annual plans."] | Array of strings or null; each passage max 4000 chars; null allowed for non-RAG answers |
[RELEVANCE_DIMENSIONS] | Specific relevance axes to score, overriding the default set | ["query_alignment", "context_utilization", "off_topic_drift"] | Array of strings from allowed enum; default used if null; reject unknown dimension names |
[SCORING_SCALE] | The numeric range for relevance scores | 0-5 | Must match pattern 'min-max' with integers; min >= 0; max <= 10; default 0-5 if null |
[PARTIAL_CREDIT_THRESHOLD] | Minimum score to consider an answer partially relevant | 2 | Integer within [SCORING_SCALE] range; must be less than full-credit threshold if both provided; null allowed |
[DISTRACTION_SOURCES] | Known off-topic or misleading passages to test distraction resistance | ["Our competitor offers free returns forever."] | Array of strings or null; each max 2000 chars; null allowed; used only for adversarial eval runs |
Implementation Harness Notes
How to wire the relevance scoring prompt into a RAG evaluation pipeline with validation, retries, and model selection.
The relevance scoring prompt is designed to operate as a synchronous evaluation step within a larger RAG QA pipeline or a regression test suite. It should be called after retrieval and answer generation are complete, receiving the user query, the generated answer, and the retrieved context chunks as inputs. The prompt is stateless and idempotent for the same inputs, making it safe to retry on transient model errors. Wire it as a post-generation gate: if the relevance score falls below a configured threshold, the system can either flag the output for human review, discard it and regenerate, or log it for offline analysis.
Validation and output parsing are critical because the prompt returns a structured JSON block. Implement a post-processing validator that checks: (1) the response contains valid JSON, (2) the score field is a float between 0.0 and 1.0, (3) the partial_relevance array contains valid sub-scores if present, and (4) the distraction_resistance object includes a distracted boolean and a rationale string. If validation fails, retry up to two times with a slightly lowered temperature (e.g., 0.1 → 0.0) to reduce output variance. Log all validation failures and retry attempts with the raw model output for debugging. For high-stakes use cases, route scores in the ambiguous range (0.4–0.6) to a human reviewer queue rather than relying on automated pass/fail gating.
Model choice matters for consistency. Use a model with strong instruction-following and JSON output capabilities—GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro are suitable defaults. Avoid smaller or older models that may drift on the structured output format or produce inconsistent relevance judgments. If running at scale, consider caching scores for identical (query, answer, context) tuples to avoid redundant LLM calls. For regression test suites, store all scores alongside the prompt version, model version, and timestamp to enable trace-based analysis and drift detection over time. Never use this prompt as the sole quality gate for production RAG systems—pair it with factual accuracy checks, citation verification, and user-facing feedback signals.
Expected Output Contract
Defines the strict JSON schema, field types, validation rules, and retry conditions for the LLM judge's response when scoring relevance. Use this contract to parse, validate, and gate the judge's output before accepting a score.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
relevance_score | integer (0-100) | Must be an integer between 0 and 100 inclusive. Reject if float, string, or out of range. | |
score_reasoning | string | Must be a non-empty string with 20-500 characters. Reject if null, empty, or exceeds 500 characters. | |
context_utilization | string enum | Must be one of: 'fully_used', 'partially_used', 'ignored', 'no_context_provided'. Reject on any other value. | |
off_topic_detected | boolean | Must be a strict boolean true or false. Reject if string 'true'/'false', integer 1/0, or null. | |
distraction_resistance_passed | boolean | Must be a strict boolean true or false. Reject if string 'true'/'false', integer 1/0, or null. | |
partial_relevance_flags | array of strings | If present, must be an array of strings from the allowed set: ['tangential_answer', 'missing_key_point', 'overly_broad', 'overly_narrow']. Reject if array contains invalid flags or non-string elements. | |
confidence_estimate | number (0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Reject if string, integer, or out of range. If confidence is below 0.6, trigger human review regardless of score. | |
retry_eligibility | boolean | Must be a strict boolean. Set to true if the judge believes the output is malformed or unscoreable and a retry is appropriate. If true, the calling system should retry up to [MAX_RETRIES] before escalating. |
Common Failure Modes
Relevance scoring prompts break in predictable ways. Here are the most common failure modes and how to guard against them before they reach production.
Context Blindness
What to watch: The model ignores retrieved context entirely and answers from its own knowledge, producing confident but ungrounded responses. This happens when the prompt doesn't enforce context dependency or when the context contradicts the model's training data. Guardrail: Add an explicit instruction requiring every claim to cite a specific passage. Use a citation format like [source_id] and validate that all claims have corresponding citations before accepting the output.
Partial Relevance Drift
What to watch: The model starts on-topic but gradually drifts into adjacent but irrelevant territory, especially with multi-part queries or long responses. This is common when the prompt lacks explicit boundaries for what constitutes acceptable scope. Guardrail: Define relevance tiers in your scoring rubric (directly relevant, tangentially relevant, off-topic) and require the model to flag when it's entering tangential territory. Add a self-check instruction: 'Before responding, verify each paragraph directly addresses the query.'
Distraction by Irrelevant Passages
What to watch: When retrieved context includes misleading or irrelevant passages, the model incorporates them into the response despite their lack of relevance. This is especially dangerous in RAG systems with noisy retrieval. Guardrail: Include a pre-response filtering step: 'First, identify which passages are relevant to the query. Only use those passages. Explicitly discard irrelevant passages and explain why they were excluded.' Test with deliberately injected distractor passages.
Overly Generous Relevance Scoring
What to watch: The LLM judge gives high relevance scores to responses that are fluent and plausible but don't actually answer the query. This happens when the scoring prompt prioritizes coherence over precision or lacks concrete scoring anchors. Guardrail: Calibrate with anchor examples showing clear score boundaries. Include a 'partially relevant' tier with specific criteria. Add a counter-check: 'Would a user who asked this question find this response directly useful? If not, reduce the score.'
Query Misinterpretation Under Ambiguity
What to watch: The model resolves ambiguous queries incorrectly and scores relevance against the wrong interpretation. This is common with short queries, domain-specific jargon, or queries that have multiple valid meanings. Guardrail: Add a disambiguation step before scoring: 'If the query is ambiguous, state your interpretation and score against that interpretation. Flag alternative interpretations that would produce different scores.' Log interpretation choices for review.
Score Inflation from Surface-Level Keyword Matching
What to watch: The model assigns high relevance scores based on keyword overlap rather than semantic alignment. A response can share vocabulary with the query while missing the actual intent. Guardrail: Require semantic reasoning in the scoring justification: 'Explain why the response does or does not address the user's underlying need, not just whether it uses similar words.' Test with adversarial examples that match keywords but miss intent.
Evaluation Rubric
Use this rubric to test the reliability and accuracy of the Relevance Scoring Prompt Template before integrating it into your RAG eval harness. Each criterion targets a specific failure mode common in relevance judgments.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Answer-to-Query Alignment | Score accurately reflects semantic alignment between [QUERY] and [ANSWER]; off-topic responses score 0 | Score > 0.5 for an answer that ignores the query intent or addresses a different topic | Golden dataset with 10 query-answer pairs labeled by human experts for direct relevance |
Context Utilization Detection | Score penalizes answers that ignore provided [CONTEXT] and hallucinate or use external knowledge | High relevance score for a factually correct answer that uses zero provided context passages | Adversarial test: provide relevant context but inject a correct answer that cites none of it |
Partial-Relevance Scoring | Score reflects partial relevance when only a subset of the query is addressed; not binary pass/fail | Score of 1.0 when answer addresses only 1 of 3 sub-questions in a multi-part query | Multi-part query test set with expected partial-relevance scores calibrated by human raters |
Distraction Resistance | Score is not inflated by semantically similar but irrelevant context passages injected into [CONTEXT] | Score increases by more than 0.2 when 3 distractor passages are added to relevant context | A/B test: score the same answer with clean context vs. context with injected distractors |
Off-Topic Drift Detection | Score drops to near-zero when the answer starts on-topic but drifts into unrelated content mid-response | Score remains above 0.5 for an answer that begins relevant but ends with unrelated commentary | Drift test set: answers that shift topic at sentence N, with expected score drop at drift boundary |
Null or Empty Input Handling | Returns a score of 0 or an explicit error when [QUERY] or [ANSWER] is empty or null | Returns a non-zero score or hallucinates a relevance judgment for empty input | Edge-case test: submit null, empty string, and whitespace-only inputs; expect 0 or structured error |
Confidence Calibration | Score confidence or justification text matches score magnitude; low confidence for ambiguous queries | High-confidence score of 0.9 for a genuinely ambiguous query with no clear answer in context | Ambiguous query test set with human-rated uncertainty labels; compare judge confidence to human uncertainty |
Schema Conformance | Output strictly matches [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing required field, wrong type, or extra text outside the expected JSON structure | Schema validation check: parse output against [OUTPUT_SCHEMA] and reject on any field-level mismatch |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single LLM judge call. Drop the partial-relevance scoring and distraction-resistance tests. Focus on a simple 1–5 Likert scale for answer-to-query alignment. Accept raw text output without schema enforcement.
codeScore the relevance of [ANSWER] to [QUERY] on a scale of 1–5. Context provided: [CONTEXT] Return only the integer score.
Watch for
- Score inflation when the answer is fluent but off-topic
- No distinction between partial relevance and full relevance
- Judge leniency on short queries where any answer seems plausible

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us