This prompt is for retrieval quality engineers and RAG pipeline builders who need to catch a specific, high-cost failure mode: passages that score well on embedding similarity but are semantically off-topic for the user's actual question. The job-to-be-done is not general relevance filtering, but targeted semantic drift detection. You use this prompt when your vector store returns a set of candidate passages, and you need to programmatically identify and flag any passage that has drifted onto a different subject, entity, or intent despite surface-level keyword or embedding overlap. The ideal user is someone who already has retrieval metrics in place and is now debugging precision failures that standard similarity scores miss.
Prompt
Topic Drift Detection Prompt for Retrieved Passages

When to Use This Prompt
Define the job, reader, and constraints for the Topic Drift Detection Prompt.
You should reach for this prompt when you observe answers that are factually correct in isolation but wrong for the query—for example, a query about 'Apple's M3 chip performance' returning a highly-ranked passage about 'Apple's Q3 financial performance.' The prompt is designed to operate as a post-retrieval filter, sitting between your retriever and your answer generation step. It expects a specific query and a list of retrieved passages as input, and it outputs a structured drift assessment for each passage, identifying the off-topic element. This is not a general-purpose relevance classifier; it is a precision tool for catching semantic drift that embedding models miss.
Do not use this prompt as your primary or only relevance filter. It is too narrow and too expensive for broad filtering. It is a diagnostic and precision-enhancement tool. Do not use it when your retrieval pipeline is already producing high-precision results, or when the cost of an extra LLM call per passage outweighs the risk of a drifted answer. Avoid using it on very short, ambiguous queries where 'topic' itself is ill-defined. In high-stakes domains like healthcare or finance, the output of this prompt should be treated as a strong signal for human review or automatic exclusion, but never as the sole gatekeeper for answer generation. The next step after reading this section is to examine the prompt template and adapt its output schema to your logging and filtering infrastructure.
Use Case Fit
Where the Topic Drift Detection Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt belongs in your retrieval pipeline.
Good Fit: High-Recall Retrieval Pipelines
Use when: your retrieval system prioritizes recall over precision, returning many passages with high embedding similarity but variable relevance. Guardrail: run drift detection as a post-retrieval filter before answer generation to catch passages that score well on vector distance but miss the query's semantic intent.
Bad Fit: Low-Latency Streaming Applications
Avoid when: you need sub-second response times and cannot afford an additional LLM call per passage. Guardrail: for latency-sensitive paths, use a lightweight classifier or threshold-based embedding distance check instead. Reserve this prompt for offline evaluation or async quality monitoring pipelines.
Required Inputs
Must have: the original user query, each retrieved passage with its source identifier, and the embedding similarity score that triggered retrieval. Guardrail: without the original query for comparison, drift detection degrades into generic relevance classification. Always pass the query alongside each passage.
Operational Risk: Over-Filtering
What to watch: the prompt may flag passages as off-topic when they contain relevant background or tangential but useful context. Guardrail: pair drift detection with an over-filtering risk assessment step. Log all flagged passages and periodically review false positives against gold-standard answers to tune your drift threshold.
Operational Risk: Embedding Blind Spots
What to watch: passages that drift on subtle semantic dimensions your embedding model cannot capture will pass through undetected. Guardrail: use drift detection as one signal in a multi-layered quality gate. Combine with factual consistency checks and answer grounding verification before surfacing results to users.
Variant: Batch Evaluation Mode
Use when: you need to audit retrieval quality across a dataset rather than filter in real time. Guardrail: run drift detection in batch over sampled query-passage pairs, aggregate drift rates by query type, and use the results to tune retrieval parameters or retrain embeddings. Do not use batch mode for real-time filtering.
Copy-Ready Prompt Template
A reusable prompt template for detecting topic drift in retrieved passages, with square-bracket placeholders for easy adaptation.
This prompt template is designed to be copied directly into your application code or prompt management system. It instructs the model to analyze a set of retrieved passages against a user query and identify any that have drifted off-topic despite high embedding similarity. The template uses square-bracket placeholders for all variable inputs, making it straightforward to wire into a RAG pipeline where the query and retrieved context are injected at runtime.
textYou are a retrieval quality auditor. Your task is to analyze a set of retrieved passages and identify any that exhibit topic drift relative to the user's query. ## INPUT **User Query:** [QUERY] **Retrieved Passages:** [PASSAGES] ## TASK For each passage, determine whether it is on-topic or off-topic relative to the query. A passage is off-topic if it discusses a different subject, answers a different question, or focuses on an aspect unrelated to the user's intent, even if it shares keywords or surface-level similarity with the query. For each off-topic passage, identify: 1. The specific element that has drifted (e.g., subject entity, time period, action, domain, or question type). 2. A brief explanation of why the passage is not relevant. ## OUTPUT_SCHEMA Return a JSON object with the following structure: ```json { "query": "string (the original query)", "total_passages": integer, "on_topic_count": integer, "off_topic_count": integer, "passages": [ { "passage_id": "string or integer", "passage_text": "string (the full passage text)", "is_on_topic": boolean, "drift_element": "string | null (the specific off-topic element, or null if on-topic)", "drift_explanation": "string | null (brief explanation of the drift, or null if on-topic)" } ] }
CONSTRAINTS
- Do not mark a passage as off-topic simply because it lacks sufficient detail to fully answer the query. Topic drift is about subject mismatch, not completeness.
- If a passage is partially relevant but contains some off-topic content, mark it as on-topic if the primary focus aligns with the query.
- Be precise in identifying the drift element. Use categories such as: subject entity, time period, geographic location, action or event, domain or field, question type, or sentiment mismatch.
- If all passages are on-topic, return an empty list for off-topic passages and set off_topic_count to 0.
EXAMPLES
Example 1: Clear Topic Drift Query: "What are the side effects of metformin?" Passage: "Metformin was first synthesized in 1922 and received FDA approval in 1994. The drug's development history includes several formulation improvements." Drift Element: time period and focus (history vs. side effects) Explanation: The passage discusses the drug's development history, not its side effects.
Example 2: No Drift Query: "How do I reset my router password?" Passage: "To reset your router password, locate the reset button on the back of the device. Press and hold for 10 seconds until the lights flash." Drift Element: null Explanation: null
To adapt this template for your own use, replace the [QUERY] and [PASSAGES] placeholders with your actual data. The passages should be provided as a JSON array of objects, each with at least an id and text field. If your retrieval system uses different identifiers, adjust the passage_id field in the output schema accordingly. For high-stakes applications where topic drift could lead to misleading answers, consider adding a [RISK_LEVEL] parameter that adjusts the strictness of drift detection—for example, flagging borderline cases as off-topic when risk is high.
Before deploying this prompt in production, validate its behavior against a golden dataset of known on-topic and off-topic passage-query pairs. Pay special attention to borderline cases where passages share keywords with the query but address a different intent. If your application operates in a regulated domain, always include a human review step for flagged off-topic passages before they are excluded from answer generation, as over-filtering can remove context that a human would recognize as relevant.
Prompt Variables
Required inputs for the topic drift detection prompt. Each variable must be populated before the prompt is sent. Validation notes describe how to check the input at runtime before incurring model cost.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[QUERY] | The original user question or search query that produced the retrieved passages | What are the latency requirements for PCIe 5.0 NVMe drives in database workloads? | Non-empty string. Length between 5 and 2000 characters. Must be the exact query used for retrieval, not a rewritten version. |
[PASSAGES] | The set of retrieved passages to evaluate for topic drift, each with a unique identifier | [{"id":"chunk-42","text":"NVMe over Fabrics uses RDMA for remote direct memory access..."},{"id":"chunk-87","text":"The best hiking trails in Colorado include..."}] | Valid JSON array. Each object must have string fields id and text. Array length between 1 and 50. Text fields must be non-empty. Reject if any passage exceeds 4000 tokens. |
[EMBEDDING_MODEL] | The embedding model used for retrieval, to contextualize similarity expectations | text-embedding-3-large | Non-empty string matching a known model identifier. Used to calibrate drift severity language. Accept values from an allowlist of supported models. |
[SIMILARITY_THRESHOLD] | The minimum cosine similarity score a passage needed to be included in the retrieved set | 0.78 | Float between 0.0 and 1.0. Must be the actual threshold used in retrieval. Used to explain why a drifted passage passed the similarity filter despite semantic mismatch. |
[DRIFT_SEVERITY_LEVELS] | The classification labels for drift severity the prompt should use | ["on_topic","tangential","off_topic","adversarial"] | Non-empty array of unique strings. Minimum 2 levels. Must include at least one positive and one negative label. First label is treated as the no-drift baseline. |
[OUTPUT_SCHEMA] | The expected JSON structure for each passage evaluation | {"passage_id":"string","drift_label":"string","off_topic_element":"string|null","drift_explanation":"string","confidence":0.0} | Valid JSON Schema object or example structure. Must include fields for passage identification, drift classification, and the specific off-topic element. Confidence field must be a float between 0.0 and 1.0. |
[MAX_DRIFT_EXPLANATION_LENGTH] | Maximum character length for the drift explanation to control output verbosity | 200 | Integer between 50 and 500. Prevents verbose explanations that bloat downstream processing. Enforced by output validator, not the prompt alone. |
Implementation Harness Notes
How to wire the topic drift detection prompt into a production RAG pipeline with validation, retries, and monitoring.
The topic drift detection prompt operates as a post-retrieval filter, sitting between your vector store and answer generation. For each retrieved passage, call this prompt to classify whether the passage has drifted off the query topic despite high embedding similarity. The prompt expects two inputs: the original user query and a single retrieved passage. It returns a structured classification with a drift flag, the specific off-topic element identified, and a confidence score. Wire this as a batch operation—process all retrieved passages in parallel before they reach the context assembly step, discarding or deprioritizing passages flagged as drifted.
Implement a validation layer that checks the structured output before acting on it. The response must contain a drift_detected boolean, an off_topic_element string (empty if no drift), and a confidence float between 0.0 and 1.0. If the model returns malformed JSON or missing fields, retry once with the same inputs and a stronger format constraint appended to the prompt. Log all validation failures and retry outcomes. For high-stakes pipelines, route passages with confidence scores in the ambiguous range (0.4–0.6) to a human review queue rather than auto-filtering. Set a drift threshold based on your tolerance for false positives—starting at confidence >= 0.7 with drift_detected == true is a reasonable default that you should tune against a labeled eval set.
Model choice matters here. This is a classification task that benefits from instruction-following precision over creative fluency. GPT-4o, Claude 3.5 Sonnet, and similarly capable models handle this well. Avoid smaller or older models that may struggle with the nuanced distinction between semantic similarity and topical relevance. If latency is critical, consider running this check on only the top-N retrieved passages rather than the full retrieval set. Instrument the pipeline to emit metrics: drift rate per query, average confidence, validation failure rate, and latency per passage. These metrics feed your retrieval quality dashboards and help detect embedding model drift or index staleness over time.
Do not use this prompt as a standalone quality gate without upstream retrieval hygiene. If your vector store consistently returns off-topic passages with high similarity scores, the root cause is likely in your embedding model, chunking strategy, or index configuration—not something a downstream filter should silently absorb. Use the drift detection output to flag problematic queries and passages for retrieval tuning. Store the off_topic_element field in your observability traces so you can cluster failure patterns and identify which topics or query types trigger the most semantic drift.
Common Failure Modes
Topic drift detection fails silently when embeddings mislead. These are the most common production failure patterns and how to catch them before they corrupt downstream answers.
High Similarity, Wrong Topic
What to watch: Passages score high on embedding similarity but discuss a different domain entirely—e.g., 'apple the fruit' vs. 'Apple the company.' The model trusts the retrieval score and fails to flag the drift. Guardrail: Include explicit entity disambiguation in the prompt. Require the model to identify the primary subject of both the query and each passage before comparing them.
Keyword Overlap Masks Semantic Drift
What to watch: Retrieved passages share vocabulary with the query but address a different intent—e.g., 'training a model' (ML) vs. 'training an employee' (HR). Lexical overlap fools both embeddings and superficial drift checks. Guardrail: Prompt the model to extract the core action and object from the query, then verify each passage addresses the same action-object pair. Flag mismatches explicitly.
Drift Accumulation Across Passages
What to watch: Individual passages drift only slightly, but collectively the context window shifts to an unrelated topic. No single passage triggers a drift flag, yet the assembled context is misleading. Guardrail: After per-passage drift checks, add a holistic step: ask the model whether the full set of retained passages coherently addresses the original query. Require a summary justification.
Overly Permissive Drift Thresholds
What to watch: The prompt's drift criteria are too loose—'generally related' passes as on-topic. Passages about adjacent but irrelevant subjects slip through and dilute answer quality. Guardrail: Define strict drift categories in the prompt: on-topic, adjacent-but-irrelevant, and off-topic. Require the model to classify each passage into one category and exclude everything except on-topic.
Drift Detection Ignores Temporal Context
What to watch: A passage is on-topic but describes outdated information—e.g., a product feature removed last quarter. The drift check passes because the subject matches, but the temporal context is wrong. Guardrail: Add a temporal alignment check. If the query implies recency or a specific time frame, require the model to verify the passage's temporal context matches before accepting it as on-topic.
Silent Failure When No Passages Survive
What to watch: Drift detection correctly filters all passages as off-topic, but the pipeline proceeds to answer generation with an empty context—producing a hallucinated or generic response. Guardrail: Add a hard stop after drift filtering. If zero passages remain on-topic, return a structured 'insufficient context' signal and escalate to retrieval expansion or human review instead of proceeding to generation.
Evaluation Rubric
Use this rubric to test the Topic Drift Detection Prompt before integrating it into a production retrieval pipeline. Each criterion targets a specific failure mode common to semantic drift detection.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Drift Classification Accuracy | Prompt correctly labels off-topic passages as 'drifted' and on-topic passages as 'on_topic' for a curated test set of 20 passage-query pairs. | Off-topic passage receives 'on_topic' label or on-topic passage receives 'drifted' label. | Run prompt against a golden dataset with known drift labels; require >= 90% accuracy. |
Drift Element Identification | For passages labeled 'drifted', the [DRIFT_ELEMENT] field identifies the specific phrase, entity, or concept that caused the semantic shift. | [DRIFT_ELEMENT] is empty, null, or describes a topic that is actually relevant to the query. | Manually review 10 drifted outputs; check that the identified element is the root cause of the mismatch. |
Embedding Similarity vs. Drift Correlation | Prompt correctly identifies drift even when the passage-query embedding cosine similarity is >= 0.85. | Prompt labels a high-similarity drifted passage as 'on_topic', relying on surface-level lexical overlap. | Construct test pairs with high embedding similarity but clear semantic drift; require drift detection rate >= 80%. |
On-Topic False Positive Rate | Prompt does not flag passages as 'drifted' when they address the query's core intent, even if using different terminology. | A passage answering the query with synonyms or related concepts is incorrectly flagged as 'drifted'. | Use a set of 15 on-topic passages with low lexical overlap; false positive rate must be <= 10%. |
Output Schema Compliance | Every response is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed. | Missing [DRIFT_DETECTED] boolean, malformed JSON, or [DRIFT_ELEMENT] present when [DRIFT_DETECTED] is false. | Validate 50 outputs with a JSON schema validator; require 100% schema compliance. |
Boundary Case Handling | Prompt handles partially relevant passages by classifying them as 'drifted' when the dominant topic is off-query. | Partially relevant passage is labeled 'on_topic' without noting the off-topic portion. | Test with 10 passages that contain one relevant sentence and three off-topic sentences; check that drift is detected. |
Null or Empty Passage Handling | Prompt returns [DRIFT_DETECTED]: true with [DRIFT_ELEMENT] set to 'empty_passage' when the input passage is empty or whitespace-only. | Empty passage causes JSON parse error, hallucinated drift element, or incorrect 'on_topic' label. | Submit empty string and whitespace-only passages; verify consistent error handling output. |
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 small sample of retrieved passages and a single query. Remove the strict JSON output schema and ask for a plain-text drift report instead. This lets you iterate on drift definitions before locking in field contracts.
Watch for
- The model may produce verbose explanations instead of structured flags
- Drift categories may be inconsistent across runs without a fixed taxonomy
- Token usage can spike if you don't cap the number of passages per call

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