This prompt is for eval pipeline builders who need to measure how well their retrieval system returns context that actually helps answer a question. It uses an LLM judge to score each retrieved passage against a query and a gold-standard answer, producing calibrated relevance scores. Use this prompt when you are tuning retrieval parameters, comparing embedding models, setting noise-filter thresholds, or building regression tests that catch retrieval degradation. This is not a prompt for end users. It is infrastructure for your evaluation harness.
Prompt
LLM-as-Judge Prompt for Context Relevance

When to Use This Prompt
Understand the job-to-be-done, ideal user, required context, and when not to use this LLM-as-Judge prompt for context relevance scoring.
The prompt assumes you already have a set of queries, gold answers, and retrieved passages. It does not perform retrieval itself, and it does not generate answers. It judges the relevance of what retrieval already returned. You should wire this into a batch evaluation script that iterates over your test dataset, calls the LLM judge for each query-passage pair, and collects scores for analysis. The output is a structured relevance score per passage, not a final answer. This separation keeps your evaluation logic clean: retrieval quality is measured independently from generation quality.
Do not use this prompt when you lack gold-standard answers, when you need real-time retrieval decisions in a production path, or when you are evaluating end-to-end answer quality rather than retrieval quality. This prompt is also inappropriate for datasets where relevance is inherently subjective without clear ground truth—the judge needs a gold answer to calibrate against. If your evaluation requires pairwise comparison between retrieval systems rather than absolute relevance scoring, use a pairwise judge prompt instead. For production guardrails that filter context before generation, use the Context Quality Gate Evaluation Prompt or Retrieval Noise Classification Prompt Template, not this eval-focused judge.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if an LLM-as-Judge relevance scorer is the right tool for your eval pipeline.
Good Fit: Threshold Tuning
Use when: you need to calibrate a relevance filter threshold for your RAG pipeline and want per-passage scores to find the optimal cutoff. Guardrail: Run the judge on a golden dataset with known relevant/irrelevant labels to validate score calibration before using scores to gate production retrieval.
Good Fit: Regression Testing
Use when: you change your embedding model, chunking strategy, or retrieval method and need to detect relevance regressions across a fixed query set. Guardrail: Store judge scores per (query, passage) pair in your eval database and alert on statistically significant score drops between pipeline versions.
Bad Fit: Real-Time Filtering
Avoid when: you need to filter retrieved passages in the hot path of a user-facing request. LLM judge latency and cost are too high for synchronous filtering. Guardrail: Use judge scores offline to tune a lightweight classifier or similarity threshold, then apply that threshold in production without calling the judge.
Bad Fit: Binary Pass/Fail Only
Avoid when: you only need a yes/no relevance decision per passage. A calibrated similarity score or small classifier is cheaper and faster. Guardrail: Reserve the LLM judge for when you need graded relevance scores, nuanced partial-relevance detection, or explanations of why a passage is off-topic.
Required Inputs
Risk: Running the judge without a gold-standard answer produces unanchored scores that drift with model behavior. Guardrail: Always provide the query, the passage to evaluate, and a reference answer. The judge compares passage relevance against what the answer actually requires, not against the query alone.
Operational Risk: Judge Drift
Risk: The judge model's scoring behavior changes after a model update, making historical score thresholds invalid. Guardrail: Pin the judge to a specific model version. Re-baseline thresholds when the judge model changes. Maintain a small calibration set to detect score distribution shifts before they corrupt your eval pipeline.
Copy-Ready Prompt Template
A reusable LLM-as-judge prompt for scoring context passage relevance against a query and gold answer, ready for your eval harness.
This prompt template turns an LLM into a calibrated relevance judge for your RAG retrieval pipeline. It evaluates each retrieved passage against a user query and an optional gold-standard answer, producing a structured relevance score, a concise rationale, and a flag for passages that are misleading distractors. The output is designed to be machine-readable so you can aggregate scores across your eval dataset, tune retrieval thresholds, and catch regressions before they reach users.
textYou are a strict retrieval relevance judge. Your task is to evaluate how relevant each retrieved passage is to answering the given query. ## INPUT Query: [QUERY] Gold Answer (for calibration, optional): [GOLD_ANSWER] Retrieved Passages: [PASSAGES] ## EVALUATION CRITERIA For each passage, assign a relevance score from 1 to 5 using this rubric: - 5 (Directly Relevant): The passage contains information that directly answers the query or provides a key piece of evidence needed to construct the answer. - 4 (Supporting Context): The passage provides useful background, definitions, or supporting details that help contextualize the answer but does not directly answer the query on its own. - 3 (Tangentially Related): The passage shares a topic or keywords with the query but does not contribute meaningful information toward answering it. - 2 (Noise): The passage is from the right general domain but is irrelevant to the specific query. It would distract or dilute answer quality if included. - 1 (Misleading Distractor): The passage appears relevant but contains information that contradicts the gold answer, is factually incorrect for this query, or would actively mislead answer generation. ## CONSTRAINTS - Score every passage independently. Do not compare passages to each other. - If a gold answer is provided, use it to calibrate your judgment, especially for identifying distractors (score 1). - If no gold answer is provided, rely solely on query-passage alignment. - Provide a one-sentence rationale for each score that cites the specific evidence or lack thereof. - Flag any passage that is a near-duplicate of another with higher relevance. Note the duplicate's ID. ## OUTPUT_SCHEMA Return a JSON object with this exact structure: { "passage_scores": [ { "passage_id": "string", "relevance_score": integer (1-5), "rationale": "string (one sentence)", "is_distractor": boolean, "duplicate_of": "string | null" } ], "aggregate": { "average_relevance": float, "distractor_count": integer, "noise_ratio": float } } ## EXAMPLES [EXAMPLES] ## RISK_LEVEL [RISK_LEVEL]
Adapt this template by replacing the square-bracket placeholders with your data. [QUERY] takes the user's original question. [GOLD_ANSWER] is optional—include it when you have verified answers to calibrate distractor detection. [PASSAGES] should be a list of objects, each with an id and text field. [EXAMPLES] can contain 2-4 scored passage examples that demonstrate your specific relevance standards and edge cases. [RISK_LEVEL] accepts low, medium, or high—for high-risk domains like healthcare or legal, add an instruction requiring the judge to flag any passage where relevance is uncertain and recommend human review. After pasting this into your eval harness, validate the JSON output against the schema before recording scores. Run this judge across your golden eval set, track score distributions over time, and set automated alerts when the noise ratio or distractor count crosses your quality threshold.
Prompt Variables
Required inputs for the LLM-as-Judge prompt. Validate each variable before sending to prevent eval drift and scoring noise.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY] | The original user question or search string that triggered retrieval | What is the refund policy for annual subscriptions? | Must be non-empty string. Check for injection patterns. Truncate to 500 chars max to prevent judge distraction. |
[PASSAGE_LIST] | Array of retrieved passages to evaluate for relevance, each with an ID and text | [{"id":"chunk_42","text":"Annual subscriptions can be refunded within 30 days..."}] | Must be valid JSON array. Each object requires 'id' (string) and 'text' (string). Reject if array is empty or contains more than 50 passages. |
[GOLD_ANSWER] | The accepted correct answer used as ground truth for relevance calibration | Customers can request a full refund for annual subscriptions within 30 days of purchase. | Must be non-empty string. If no gold answer exists, use null and switch to query-only relevance mode. Warn if gold answer is shorter than 10 chars. |
[RELEVANCE_THRESHOLD] | Numeric threshold for binary pass/fail classification of passage relevance | 0.7 | Must be float between 0.0 and 1.0. Default to 0.5 if not provided. Log threshold in eval metadata for reproducibility. |
[OUTPUT_SCHEMA] | Expected JSON structure for the judge's response, including score fields and rationale | {"passage_id":"string","relevance_score":"float","rationale":"string","is_relevant":"boolean"} | Must be valid JSON Schema or example object. Validate that required fields include passage_id, relevance_score, and is_relevant. Reject schemas missing rationale field for auditability. |
[MAX_PASSAGES_PER_REQUEST] | Upper limit on passages sent in a single judge call to control latency and cost | 20 | Must be positive integer. Default to 20. If passage list exceeds this, batch into multiple judge calls and aggregate scores. Log batching in trace. |
[JUDGE_MODEL] | Identifier for the model acting as judge, used for routing and cost tracking | claude-3-5-sonnet-20241022 | Must match deployed model ID. Validate against allowed judge model list. Reject unknown models. Log model version in eval results for regression comparison. |
[CALIBRATION_SAMPLES] | Optional few-shot examples with known relevance scores to anchor judge behavior | [{"passage":"...","query":"...","gold_answer":"...","expected_score":0.9,"expected_rationale":"..."}] | If provided, must be valid JSON array with 2-5 examples. Each example requires expected_score and expected_rationale. Validate that calibration queries differ from eval query to avoid leakage. |
Implementation Harness Notes
How to wire the LLM-as-Judge context relevance prompt into an eval pipeline or regression test suite.
This prompt is designed to operate as a deterministic scoring step inside an automated evaluation pipeline, not as a one-off manual check. The typical integration pattern places it after retrieval and before answer generation in a RAG eval harness, or as a standalone context-quality gate in a regression suite. The judge prompt expects three inputs: a query, a gold-standard answer, and a list of retrieved passages. It returns a structured JSON object containing a relevance score and justification for each passage, making it directly consumable by downstream metric aggregators, threshold monitors, and CI checks.
To integrate this into a production eval pipeline, wrap the prompt in a function that accepts the query, gold answer, and passage list as arguments. Validate the output against a strict JSON schema before accepting it—reject any response where scores fall outside the 1-5 range, justifications are missing, or the passage count doesn't match the input. Implement a retry loop with a maximum of two attempts using a lower-temperature fallback (e.g., temperature=0.1 on retry). Log every judge call with the input query hash, passage IDs, raw scores, and any validation failures. For regression testing, store a golden dataset of query-answer-passage triples with expected score ranges, and run this judge on every prompt or retrieval change. Flag any passage whose score deviates from the expected range by more than one point for human review.
Model choice matters for judge 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 drift toward midpoint scores or produce malformed JSON under the scoring rubric. Set temperature to 0 for production eval runs to maximize reproducibility. If you're scoring thousands of passages per run, batch the calls but keep each batch independent—never let the judge see scores from other passages in the same request, as this introduces anchoring bias. For high-stakes pipelines where a bad relevance score could suppress critical evidence, add a human review step for passages scored 1 or 2 that the gold answer explicitly references.
Expected Output Contract
Fields, types, and validation rules for the LLM judge response when scoring context relevance. Use this contract to parse, validate, and log judge outputs before feeding scores into filter threshold tuning or regression tests.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
relevance_scores | Array of objects | Must be a JSON array. Length must equal the number of passages in [PASSAGES]. Reject if missing or mismatched length. | |
relevance_scores[].passage_id | String or Integer | Must match the id field of exactly one passage in [PASSAGES]. Reject if duplicate or orphaned id. | |
relevance_scores[].score | Integer (1-5) | Must be an integer between 1 and 5 inclusive. Reject if float, string, or out of range. 1 = completely irrelevant, 5 = perfectly relevant. | |
relevance_scores[].rationale | String (<= 280 chars) | Must be a non-empty string. Maximum 280 characters. Must reference specific content from the passage or query. Reject if generic boilerplate. | |
relevance_scores[].key_terms_match | Array of strings | If present, each string must be a term found in both the query and the passage. Null allowed. Reject if terms are fabricated. | |
overall_context_quality | Object | Must contain summary, noise_ratio, and coverage_gaps fields. Reject if any required sub-field is missing. | |
overall_context_quality.summary | String (<= 500 chars) | Must be a non-empty string summarizing the overall relevance of the context set. Maximum 500 characters. | |
overall_context_quality.noise_ratio | Float (0.0 - 1.0) | Must be a float between 0.0 and 1.0 representing the proportion of passages scored 1 or 2. Reject if negative or greater than 1.0. | |
overall_context_quality.coverage_gaps | Array of strings | Must be an array. Each string must describe a specific information need from [QUERY] not covered by any passage. Empty array allowed if coverage is complete. | |
judge_metadata | Object | Must contain model_id and timestamp fields. Reject if missing. Used for audit and regression comparison. | |
judge_metadata.model_id | String | Must be a non-empty string identifying the judge model used. Reject if null or empty. | |
judge_metadata.timestamp | ISO 8601 String | Must be a valid ISO 8601 datetime string. Reject if unparseable or in the future. |
Common Failure Modes
LLM judges for context relevance fail in predictable ways. Here are the most common failure modes and how to guard against them before they reach production.
Position Bias Skews Relevance Scores
What to watch: The judge assigns higher relevance scores to passages appearing first or last in the context list, regardless of actual relevance. This is a known attention bias in LLMs. Guardrail: Randomize passage order before scoring and run multiple scoring passes with different orderings. Average the scores and flag passages with high variance across orderings for manual review.
Semantic Similarity Confused with Relevance
What to watch: The judge scores passages as relevant because they share vocabulary, entities, or topic domain with the query, even when the passage contains no information that actually answers the question. Guardrail: Include a gold-standard answer in the judge prompt and instruct the model to score based on whether the passage contributes evidence toward that answer, not just topical overlap. Calibrate thresholds against human-labeled relevance pairs.
Score Inflation on Short or Vague Passages
What to watch: Brief passages with generic statements receive inflated relevance scores because the judge fills gaps with assumptions rather than penalizing missing specificity. Guardrail: Add a completeness dimension to the scoring rubric. Require the judge to note what specific information the passage lacks. Flag passages below a minimum token or entity count for separate evaluation.
Judge Overweights Query Keywords in Passage
What to watch: The judge treats keyword density as a proxy for relevance, giving high scores to passages that repeat query terms even when the surrounding context is off-topic or contradictory. Guardrail: Include negative examples in the judge prompt showing keyword-heavy but irrelevant passages scored low. Add an explicit instruction to evaluate whether the passage meaning aligns with the query intent, not just term overlap.
Calibration Drift Across Query Types
What to watch: The judge applies different implicit thresholds for factoid queries versus open-ended or comparative queries, making scores incomparable across query types and breaking automated threshold tuning. Guardrail: Normalize scores within query-type buckets. Maintain a calibration set with balanced query types and monitor score distributions per type over time. Retune thresholds when distributions shift.
Judge Hallucinates Passage Content
What to watch: The judge's explanation for a relevance score references information not actually present in the passage, indicating the model is reasoning from its own knowledge rather than the provided text. Guardrail: Add a verification step that checks whether each claim in the judge's explanation can be found verbatim or in close paraphrase in the original passage. Flag mismatches and discard scores with unsupported explanations.
Evaluation Rubric
Criteria for testing the LLM-as-Judge prompt's output quality before relying on it for automated context relevance decisions in a RAG pipeline.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Score Calibration | Judge scores correlate with human relevance labels (Spearman's ρ ≥ 0.8) on a golden dataset of 50+ query-passage pairs | Judge assigns high relevance to off-topic passages or low relevance to clearly relevant passages | Run judge on a labeled golden set; compute correlation between judge scores and human labels |
Score Discrimination | Judge produces a score distribution with at least 3 distinct score clusters (e.g., 0-2, 3-5, 6-10) across a mixed relevance test set | All passages receive similar scores regardless of actual relevance; judge fails to separate relevant from irrelevant | Plot score histogram on a test set with known relevance mix; check for multimodality and range spread |
Threshold Stability | Binary pass/fail decisions at a fixed threshold (e.g., score ≥ 5) match human relevance judgments with F1 ≥ 0.85 | Small threshold changes (±0.5) cause large swings in pass rate; precision-recall curve is unstable | Sweep thresholds from 0 to 10 on golden set; compute precision-recall curve and F1 at each threshold |
Rationale Quality | Judge provides a specific, evidence-based rationale referencing passage content for every score | Rationale is generic (e.g., 'this passage is relevant'), missing, or hallucinates content not in the passage | Manual review of 20 random rationales; check for passage-specific references and absence of fabricated details |
Consistency Across Runs | Judge produces identical scores (±1 point) on the same query-passage pair across 3 independent runs with temperature=0 | Scores vary by more than 2 points across runs; binary pass/fail decisions flip between runs | Run judge 3 times on a fixed test set of 30 pairs; compute mean absolute deviation and pass/fail flip rate |
Edge Case Handling | Judge correctly scores empty passages as 0, very short passages (1-2 words) appropriately, and passages in a different language as low relevance | Judge assigns non-zero scores to empty strings, crashes on malformed input, or assigns high scores to unrelated-language passages | Create a test set with edge cases: empty passage, single-word passage, passage in wrong language, passage with only punctuation |
Latency Budget Compliance | Judge completes scoring for a batch of 20 passages within [MAX_LATENCY_MS] milliseconds at P95 | Judge exceeds latency budget; scoring time grows super-linearly with passage count; timeouts occur | Benchmark judge on batches of 5, 10, 20, and 50 passages; measure P50 and P95 latency; check for timeouts |
Output Schema Compliance | Judge output parses successfully against [OUTPUT_SCHEMA] with zero parse errors across 100 runs | JSON is malformed, missing required fields, or contains extra fields not in schema; downstream pipeline breaks | Run judge on 100 test inputs; validate all outputs against the schema; count parse failures and schema violations |
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 relevance score per passage. Skip calibration and structured output validation. Run against 20-50 query-passage pairs to get a feel for score distributions.
codeScore each passage from 1-5 for relevance to [QUERY]. Return: {"passage_id": "...", "score": int, "reason": "..."}
Watch for
- Score inflation: the judge gives everything 4 or 5
- Missing
reasonfield when the model rushes - No baseline comparison—scores are meaningless without a reference distribution

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