Inferensys

Prompt

Evidence Selection Harness Prompt with JSON Output Contract

A practical prompt playbook for using Evidence Selection Harness Prompt with JSON Output Contract in production AI workflows.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

A guide to the ideal use cases, required context, and boundaries for the Evidence Selection Harness Prompt.

This prompt is designed for AI engineers and RAG pipeline builders who need a deterministic, auditable step between retrieval and answer synthesis. The core job-to-be-done is selecting, ranking, and justifying evidence passages before any final text is generated. The ideal user is someone integrating this into a production system where downstream components—such as a synthesis prompt, a citation formatter, or a logging service—consume structured JSON directly. Required context includes a set of retrieved passages, the original user query, and any domain-specific ranking criteria such as source freshness or authority. Without this context, the prompt cannot produce a meaningful selection.

Use this prompt when you need an explicit, machine-readable contract for evidence selection. It is particularly valuable in high-stakes domains like legal research, clinical literature review, or financial analysis, where the reasoning behind including or excluding a source must be auditable. The strict JSON output contract, with fields for rank, score, justification, and exclusion_reason, allows you to build validation and retry logic that fails closed on malformed output. For example, if a downstream validator detects a missing exclusion_reason for a low-scoring passage, the system can trigger a repair loop before the answer is synthesized, preventing unsupported claims from reaching the user.

Do not use this prompt for open-ended chat or when the model should synthesize an answer directly without an intermediate structured selection step. It is also not a replacement for a vector database's native similarity scoring; instead, it adds a layer of semantic reasoning, conflict detection, and explainability on top of initial retrieval results. Before implementing, ensure you have a clear schema for the expected JSON output and a plan for handling malformed responses. The next step is to review the prompt template and adapt the [OUTPUT_SCHEMA] and [CONSTRAINTS] placeholders to match your application's exact contract.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if the Evidence Selection Harness is the right tool for your RAG pipeline stage.

01

Good Fit: Pre-Synthesis Filtering

Use when: You need to reduce noise and token waste before answer generation. This prompt excels at selecting the top-k most relevant, fact-dense passages from a large retrieval set. Guardrail: Always run a sufficiency check after selection to ensure the filtered set still contains enough evidence to answer the query.

02

Bad Fit: Real-Time Chat Without Retrieval

Avoid when: You are building a general-purpose chatbot that does not use a retrieval step. This prompt requires a pre-existing set of candidate passages to rank and select. Guardrail: Use a classification router to direct non-RAG queries to a standard conversation prompt instead.

03

Required Inputs

Risk: Garbage in, garbage out. The prompt requires a structured list of candidate passages with unique IDs and the original user query. Missing IDs break downstream citation linking. Guardrail: Validate the input payload in your application layer before calling the model. Reject requests with empty passage arrays or missing IDs.

04

Operational Risk: JSON Schema Drift

Risk: The model may return malformed JSON, missing required fields like exclusion_reason, or hallucinate new keys under load. Guardrail: Implement a strict post-processing validation layer. On failure, use a lightweight repair prompt or retry with a stronger schema constraint. Never pass unvalidated JSON to the synthesis step.

05

Operational Risk: Budget Overrun

Risk: Selecting too many passages to be "safe" can silently blow your context window budget for the final synthesis prompt. Guardrail: Set a hard max_total_tokens parameter in your harness. If the selected passages exceed it, trigger a secondary deduplication or summarization step rather than truncating silently.

06

Good Fit: Audit Log Generation

Use when: You need to explain why certain sources were used to generate an answer. The structured justification and exclusion_reason fields provide a machine-readable audit trail. Guardrail: Store the full JSON output alongside the final answer. This enables debugging hallucinations and provides evidence for compliance reviews.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A production-ready prompt for scoring, ranking, and selecting evidence passages with a strict JSON output contract, designed for direct integration into RAG pipelines.

The following prompt template is the core engine for your evidence selection step. It is designed to be called after retrieval, taking a user query and a set of candidate passages, and returning a structured JSON payload that a downstream synthesis prompt or application logic can consume directly. The prompt enforces a strict contract: it scores for relevance and credibility, computes a weighted combined score, filters out low-quality evidence, and provides explicit justifications for every decision. This makes the selection process auditable and debuggable, which is critical for high-stakes applications where hallucination must be minimized.

text
You are an evidence selection engine. Your job is to analyze a set of retrieved passages against a user query and produce a strict JSON output that ranks, scores, and justifies which passages are most relevant and credible.

## Input
- User Query: [USER_QUERY]
- Retrieved Passages: [RETRIEVED_PASSAGES]
- Ranking Criteria: [RANKING_CRITERIA]
- Max Passages to Return: [MAX_PASSAGES]
- Minimum Relevance Score (0.0-1.0): [MIN_SCORE]

## Instructions
1. Score each passage for relevance to the query on a 0.0 to 1.0 scale.
2. Score each passage for credibility based on source authority, recency, and factual consistency on a 0.0 to 1.0 scale.
3. Compute a combined score as (relevance * [RELEVANCE_WEIGHT]) + (credibility * [CREDIBILITY_WEIGHT]).
4. Exclude passages with combined score below [MIN_SCORE].
5. Rank remaining passages by combined score descending.
6. For each excluded passage, provide a specific reason.
7. For each included passage, provide a one-sentence justification.
8. Return only the top [MAX_PASSAGES] passages.
9. Output must be valid JSON matching the schema below. No other text.

## Output Schema
{
  "query": "string",
  "selected_passages": [
    {
      "passage_id": "string",
      "passage_text": "string",
      "relevance_score": number,
      "credibility_score": number,
      "combined_score": number,
      "justification": "string"
    }
  ],
  "excluded_passages": [
    {
      "passage_id": "string",
      "combined_score": number,
      "exclusion_reason": "string"
    }
  ],
  "selection_summary": "string"
}

## Constraints
- Do not fabricate passage content. Use only the provided text.
- If no passages meet the minimum score, return an empty selected_passages array and explain in selection_summary.
- If the query is ambiguous, note this in selection_summary but still rank based on best interpretation.
- All scores must be numbers, not strings.
- Justifications and exclusion reasons must reference specific passage content.

To adapt this template for your application, you must populate the square-bracket placeholders at runtime. [USER_QUERY] and [RETRIEVED_PASSAGES] are your dynamic inputs. [RANKING_CRITERIA] should be a short string describing what matters for your use case (e.g., 'Prioritize recent documentation and official sources'). [RELEVANCE_WEIGHT] and [CREDIBILITY_WEIGHT] are floats that sum to 1.0; start with 0.7 and 0.3 respectively and tune based on your eval results. [MAX_PASSAGES] should be set based on the context window you have budgeted for the subsequent synthesis step. The [MIN_SCORE] acts as a quality gate—set it too low and you risk including noise; set it too high and you may get empty results. Begin with 0.6 and adjust by observing the excluded_passages array in your logs.

Before deploying, you must implement a validation layer around the model's response. The primary failure mode is malformed JSON or missing keys. Your application code should parse the response, validate it against the schema, and implement a retry loop. On a ValidationError, feed the raw output and the error message back to the model with a repair prompt. A secondary failure mode is hallucinated content within the passage_text field; your validator should check that the returned text is an exact substring match of the input passages. If your use case is high-risk—such as legal, financial, or clinical applications—log every response for human audit and consider routing outputs with an empty selected_passages array or a high exclusion rate for mandatory human review before any answer is shown to the user.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Evidence Selection Harness prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to check the input before execution.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The original question or search query from the end user that requires evidence-backed answering.

What are the side effects of drug X in patients over 65?

Must be non-empty string. Check for injection attempts, delimiter characters, and length under 2000 chars. Strip leading/trailing whitespace.

[RETRIEVED_PASSAGES]

Array of passage objects returned from the retrieval step, each containing text and source metadata.

[{"id":"doc-12-chunk-3","text":"...","source":"clinical_trial_2024.pdf","date":"2024-03-15"}]

Must be valid JSON array with 1-50 objects. Each object requires id and text fields. Reject if text fields are empty or exceed 4000 tokens each. Validate source field is present.

[OUTPUT_SCHEMA]

JSON Schema definition that constrains the model's output format for ranked passages, scores, and justifications.

{"type":"object","properties":{"ranked_passages":{"type":"array"}},"required":["ranked_passages"]}

Must be valid JSON Schema draft-07 or later. Schema must include ranked_passages array, relevance_score number field, and justification string field. Validate with ajv or similar before prompt assembly.

[MAX_PASSAGES]

Integer specifying the maximum number of passages to return after ranking and filtering.

5

Must be integer between 1 and 20. Default to 5 if not provided. Validate range before prompt assembly. Lower values reduce downstream token usage but may omit relevant evidence.

[MIN_RELEVANCE_SCORE]

Float threshold below which passages are excluded from the ranked output.

0.3

Must be float between 0.0 and 1.0. Default to 0.0 if not provided. Higher values reduce noise but risk excluding marginally relevant evidence. Validate range and type.

[SOURCE_CREDIBILITY_WEIGHTS]

Optional object mapping source identifiers to credibility multipliers for ranking adjustment.

{"peer_reviewed":1.0,"preprint":0.7,"forum_post":0.2}

If provided, must be valid JSON object with string keys and float values between 0.0 and 1.0. Null allowed. Validate that referenced sources exist in retrieved passages. Missing sources default to weight 0.5.

[REQUIRE_DIVERSE_SOURCES]

Boolean flag that enforces minimum source diversity in the final ranked set.

Must be true or false. Default to false. When true, the prompt includes additional constraints to avoid over-reliance on a single source. Validate boolean type before assembly.

[EXCLUSION_REASONS_REQUIRED]

Boolean flag controlling whether the output must include explicit reasons for excluding passages.

Must be true or false. Default to true for auditability. When true, the output schema must include exclusion_reasons array. Validate boolean type and confirm output schema compatibility.

PROMPT PLAYBOOK

Implementation Harness Notes

Wire the Evidence Selection prompt into your RAG pipeline with validation, retries, and observability.

This prompt is designed to be called as a pre-synthesis step in your RAG pipeline, after retrieval but before answer generation. Its job is to produce a structured, machine-readable ranking of retrieved passages that downstream synthesis prompts can consume directly. The JSON output contract eliminates the ambiguity of free-text rankings and enables automated validation before evidence reaches the answer-generation stage. Treat this prompt as a deterministic component in your pipeline: it expects a specific input shape, returns a specific output shape, and must be validated before its results are trusted.

Wire the prompt into your application by calling the LLM with the populated template and parsing the response as JSON immediately. Validate the output against the expected schema before passing it downstream. If validation fails, retry up to [RETRY_LIMIT] times (start with 3) by appending the validation error message to the prompt as additional context. This error-feedback loop often corrects malformed JSON, missing fields, or out-of-range scores. If retries are exhausted, log the full failure payload and either fall back to a simpler ranking method (e.g., vector similarity score ordering) or escalate for human review. For model selection, prefer gpt-4o, claude-3-opus, or equivalent models with strong JSON-mode reliability. When using open-weight models, enable any available JSON mode flag and increase your retry budget to 5–7 attempts, as schema adherence is less consistent.

Observability is non-negotiable. Log every call's inputs, outputs, scores, validation results, and retry count. This trace data is essential for debugging ranking quality issues, detecting prompt drift, and comparing performance across model versions. If your RAG system operates in a regulated or high-stakes domain, add a human review gate when confidence scores fall below a configurable threshold or when the evidence set is flagged as insufficient. The structured output from this prompt makes both automated gating and audit review straightforward. Next, integrate the validated ranking output into your synthesis prompt by passing the top-K passages and their scores as structured context, and configure your eval pipeline to compare answer quality with and without this evidence selection step to measure its impact on hallucination reduction.

IMPLEMENTATION TABLE

Expected Output Contract

Schema contract for the Evidence Selection Harness. Validate every model response against these rules before passing data to downstream synthesis prompts.

Field or ElementType or FormatRequiredValidation Rule

selected_passages

Array of objects

Array length must be >= 1. Reject if empty or null.

selected_passages[].passage_id

String

Must match an ID from the [INPUT_PASSAGES] array. Reject if ID not found in input set.

selected_passages[].relevance_score

Number (0.0-1.0)

Must be a float between 0.0 and 1.0 inclusive. Reject if out of range or non-numeric.

selected_passages[].justification

String

Must be non-empty string with minimum 10 characters. Reject if null, empty, or whitespace-only.

excluded_passages

Array of objects

Array can be empty. Reject if null or missing.

excluded_passages[].passage_id

String

Must match an ID from [INPUT_PASSAGES] not present in selected_passages. Reject if ID appears in both arrays.

excluded_passages[].exclusion_reason

String enum

Must be one of: 'irrelevant', 'redundant', 'low_credibility', 'outdated', 'contradictory'. Reject on unknown values.

confidence

Object

Must contain overall_score and calibration_note fields. Reject if either field is missing.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when evidence selection runs in production and how to guard against it.

01

JSON Output Contract Violations

What to watch: The model returns malformed JSON, missing required fields, or extra commentary outside the structured block. This breaks downstream parsers and halts the pipeline. Guardrail: Validate output against a strict JSON schema immediately after generation. If validation fails, retry with the error message injected into the retry prompt. Set a max retry count (2-3) before escalating to a human or fallback model.

02

Hallucinated Passage Scores and Justifications

What to watch: The model assigns high relevance scores to passages that don't actually contain the claimed information, or fabricates justifications that sound plausible but misrepresent the source text. Guardrail: Implement a post-selection verification step that extracts the specific claim from the justification and checks for its presence in the original passage text using substring or semantic similarity. Flag mismatches for human review.

03

Silent Exclusion of Relevant Evidence

What to watch: The model omits a passage that is clearly relevant without providing an exclusion reason, or provides a vague justification like 'less relevant' when the passage contains unique, critical information. Guardrail: Require an explicit exclusion_reason field for every passage not included in the final ranked set. Run a periodic eval comparing the selected set against a human-annotated gold set to measure recall and detect systematic omissions.

04

Score Calibration Drift Across Batches

What to watch: The model's relevance scoring becomes inconsistent across different requests, with similar passages receiving wildly different scores depending on batch composition or ordering. Guardrail: Include a small set of calibration passages with known scores in each request as anchor points. Monitor score distributions in production logs and trigger an alert if the mean or variance shifts beyond a defined threshold.

05

Context Window Overflow and Truncation

What to watch: The combined length of the prompt, retrieved passages, and output schema exceeds the model's context window, causing silent truncation of evidence or instructions. This leads to selections made on incomplete information. Guardrail: Implement a pre-flight token counter that trims or summarizes passages before they enter the prompt. Always reserve a fixed token budget for the output JSON. Log a warning if any passage was truncated before selection.

06

Overfitting to Surface Keyword Matches

What to watch: The model ranks passages highly because they share keywords with the query, ignoring passages that are semantically relevant but use different terminology. This is common with technical or domain-specific language. Guardrail: Include a query expansion or synonym mapping step before evidence selection. In the prompt, explicitly instruct the model to prioritize semantic relevance over keyword overlap and to justify selections using concepts, not just terms.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Evidence Selection Harness Prompt before production deployment. Each row defines a pass standard, a failure signal, and a concrete test method.

CriterionPass StandardFailure SignalTest Method

Schema Compliance

100% of outputs parse as valid JSON matching the [OUTPUT_SCHEMA] contract

JSON parse error, missing required fields, or type mismatch in any field

Validate 100+ outputs against the JSON schema using a programmatic validator; reject any non-conforming output

Ranking Order Consistency

Passages with higher [RELEVANCE_SCORE] appear before lower-scored passages in the ranked list

A passage with score 0.9 appears after a passage with score 0.3 in the output array

Sort output array by score descending and compare to original order; flag any position swaps as failures

Exclusion Justification Completeness

Every passage in [EXCLUDED_PASSAGES] has a non-empty, specific [EXCLUSION_REASON]

Exclusion reason is null, empty string, or generic text like 'not relevant' without specifics

Assert [EXCLUSION_REASON] length > 20 characters and contains at least one query-specific term from [USER_QUERY]

Score Calibration

[RELEVANCE_SCORE] for clearly relevant passages exceeds 0.7; clearly irrelevant passages score below 0.3

A passage containing the exact answer entity scores 0.2, or a completely off-topic passage scores 0.8

Run 20 golden queries with known relevant/irrelevant passage pairs; assert score thresholds hold across all pairs

No Fabricated Passages

All passage IDs in output match IDs present in the [RETRIEVED_PASSAGES] input set

Output contains a passage ID not found in the input, or a synthesized passage text not present in input

Extract all passage IDs from output; assert set is a subset of input passage IDs using exact string matching

Justification Faithfulness

[SELECTION_JUSTIFICATION] references specific content from the passage, not generic praise

Justification says 'This passage is highly relevant' without quoting or paraphrasing passage content

Check that justification contains at least one direct quote or specific entity mention from the passage text

Token Budget Adherence

Total selected passage tokens do not exceed [MAX_CONTEXT_TOKENS] constraint

Selected passages sum to more tokens than the specified budget limit

Tokenize selected passages with the target model's tokenizer; assert total <= [MAX_CONTEXT_TOKENS]

Retry Recovery

After a schema validation failure, the retry prompt produces a valid output on the next attempt

Retry output repeats the same schema error or introduces a new schema violation

Inject 5 known schema-violating outputs into the retry path; assert 100% recovery rate within 2 retries

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt\nUse the base prompt with lighter validation. Remove the strict JSON schema enforcement and allow the model to return ranked passages with scores and justifications in a more flexible format. Replace `[OUTPUT_SCHEMA]` with a simple description like 'Return a list of passages with relevance scores and brief justifications.' Skip the retry logic and schema validator.\n\n### Watch for\n- Missing or inconsistent field names across runs\n- Scores that drift in scale (0-1 vs 1-10 vs ordinal)\n- Exclusion reasons that are vague or missing entirely\n- Passages returned without scores when the model gets lazy

Prasad Kumkar

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.