Inferensys

Prompt

Topic Shift Detection Prompt for RAG Assistants

A practical prompt playbook for using Topic Shift Detection Prompt for RAG Assistants in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Learn when to deploy topic shift detection in your RAG pipeline and when simpler alternatives suffice.

Multi-turn RAG assistants degrade when stale context pollutes retrieval and answer generation. This prompt detects when a user changes subjects so your application can trigger a context reset, clear conversation history, or re-retrieve evidence. Use it as a guard before your main RAG pipeline to decide whether the current turn continues the prior topic or starts a new one. It classifies topic shifts as abrupt, gradual, or none, and provides a confidence score and boundary marker. This is not a follow-up question detector. It specifically identifies semantic topic boundaries, not anaphora or ellipsis resolution.

Deploy this prompt when your assistant handles open-domain conversations where users may pivot from troubleshooting to billing to technical specs without warning. It is most valuable in customer support copilots, internal knowledge base assistants, and any multi-turn system where context window pollution from irrelevant history degrades answer quality. The prompt works best when you have at least two prior turns to compare against the current message. Single-turn or stateless RAG systems do not need this detection layer. If your assistant operates in a narrow domain where topic changes are rare or predictable, a simpler keyword-based router may be more cost-effective than an LLM-based shift detector.

Avoid using this prompt when your primary need is resolving pronouns or follow-up references. Those require anaphora resolution, not topic boundary detection. Do not deploy this as the sole guard for context management—pair it with a context budget monitor and a staleness timer. For high-stakes domains where missed topic shifts could produce misleading answers, add a human review step when the confidence score falls below your threshold. Start by wiring this prompt before your retrieval step, log every shift classification, and measure whether context resets actually improve downstream answer accuracy before making it a permanent part of your pipeline.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Topic Shift Detection Prompt works, where it breaks, and what you need before deploying it in a multi-turn RAG assistant.

01

Good Fit: Multi-Turn Copilots with Retrieval

Use when: your RAG assistant maintains conversation history across turns and needs to decide when to re-retrieve evidence. Guardrail: wire the topic boundary marker into your retrieval pipeline so a detected shift triggers a fresh search before the next answer generation step.

02

Bad Fit: Single-Shot Q&A Systems

Avoid when: the system answers one question per session with no conversation history. Risk: topic shift detection adds latency and complexity with no benefit when there is no prior context to reset. Use a simpler classification or routing prompt instead.

03

Required Input: Conversation History Window

What to watch: the prompt needs at least the last 3-5 turns to distinguish a genuine topic shift from a brief clarification or follow-up. Guardrail: if the session has fewer than two turns, skip detection and treat the input as a new topic by default.

04

Operational Risk: Gradual Topic Drift

What to watch: users often drift topics slowly across several turns rather than switching abruptly. The prompt may miss the boundary. Guardrail: combine binary shift detection with a topic similarity score. Trigger re-retrieval when similarity drops below a threshold, even if no hard boundary is flagged.

05

Operational Risk: False Positives on Clarifications

What to watch: a user asking 'What did you mean by that?' may be classified as a topic shift, causing an unnecessary context reset. Guardrail: add a clarification intent check before the shift detector. If the turn is a clarification request, route to the clarification handler instead of resetting context.

06

Integration Point: Context Reset Scope

What to watch: detecting a shift is only half the work. The system must decide what to clear and what to keep. Guardrail: define a reset policy that specifies whether to drop all history, retain user preferences, or keep unresolved questions. Pass this policy alongside the shift detection output.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt for detecting topic shifts in multi-turn RAG conversations, triggering context resets or re-retrieval.

This prompt template is designed to be placed between conversation turns in a RAG assistant. Its job is to analyze the user's latest message against the recent conversation history and determine whether the user has shifted to a new, unrelated topic. The output is a structured decision that your application harness can use to clear stale context, flush prior evidence, and trigger a fresh retrieval pipeline. Use this when your assistant suffers from 'context clinging'—answering new questions with old, irrelevant documents.

text
SYSTEM: You are a topic continuity monitor for a multi-turn RAG assistant. Your only job is to detect topic shifts.

INPUT:
- [CONVERSATION_HISTORY]: The last [N] turns of the dialogue, each with a user message and assistant response.
- [CURRENT_USER_MESSAGE]: The user's latest message.
- [TOPIC_BOUNDARY_SENSITIVITY]: A value of 'strict', 'moderate', or 'loose'.

TASK:
Determine if [CURRENT_USER_MESSAGE] represents a topic shift from the conversation in [CONVERSATION_HISTORY]. A topic shift means the user has introduced a new subject that is not a follow-up, clarification, or natural continuation of the prior turns. Consider:
- Abrupt shifts: The user asks about a completely different domain (e.g., from 'deployment errors' to 'lunch plans').
- Gradual shifts: The user moves to a tangentially related but distinct subject (e.g., from 'Python performance' to 'hardware costs').
- False shifts: The user uses a pronoun or reference that ties back to the prior topic, even if the wording is new.

OUTPUT_SCHEMA:
{
  "topic_shift_detected": boolean,
  "confidence": 0.0-1.0,
  "reasoning": "string explaining the decision in one sentence",
  "recommended_action": "reset_context" | "re_retrieve" | "continue"
}

CONSTRAINTS:
- If [TOPIC_BOUNDARY_SENSITIVITY] is 'strict', classify any non-explicit follow-up as a shift.
- If 'loose', only classify a shift when the subject domain changes entirely.
- If 'moderate', use your best judgment for tangential shifts.
- Do not answer the user's question. Only output the JSON.

To adapt this template, replace the placeholders with your application's actual values. [CONVERSATION_HISTORY] should be a serialized list of recent turns, typically the last 3-5 exchanges. [N] is a tunable parameter; a smaller window is more sensitive to recent shifts, while a larger window provides more context for detecting gradual transitions. [TOPIC_BOUNDARY_SENSITIVITY] should be set based on your application's tolerance for unnecessary re-retrieval. A 'strict' setting is appropriate for focused technical assistants where context contamination is costly. A 'loose' setting works for open-domain chatbots. After pasting, wire the JSON output into your application's state machine: a topic_shift_detected: true with recommended_action: reset_context should clear the conversation history and the retrieved document cache before the next turn.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the topic shift detection prompt. Each variable must be populated before the prompt is assembled and sent to the model.

PlaceholderPurposeExampleValidation Notes

[CURRENT_USER_MESSAGE]

The latest user utterance to evaluate for topic shift

Can you also help me with my expense report?

Must be a non-empty string. Truncate if over 2000 characters to avoid diluting the shift signal.

[CONVERSATION_HISTORY]

Last N turns of the dialogue, including prior user messages and assistant responses

User: What is the Q3 revenue? Assistant: Q3 revenue was $12.4M. User: Break that down by region.

Must be an array of turn objects with role and content fields. Limit to last 5-10 turns. Exclude system prompts and tool calls.

[CURRENT_TOPIC_LABEL]

A short label describing the active topic before the current message

quarterly_financial_reporting

Must be a single string under 50 characters. If no topic is set, use null. Validate against a controlled vocabulary if topics are predefined.

[TOPIC_TAXONOMY]

Optional list of known topics the assistant can operate within

["financial_reporting", "hr_policies", "it_support", "product_features"]

If provided, must be a JSON array of strings. If null, the prompt performs open-set topic shift detection. Validate array is not empty if supplied.

[SHIFT_THRESHOLD]

Confidence score above which a topic shift is declared

0.7

Must be a float between 0.0 and 1.0. Default to 0.7 if not specified. Lower values increase sensitivity; higher values reduce false positives.

[OUTPUT_SCHEMA]

The exact JSON schema the model must return

{"type": "object", "properties": {"topic_shift": {"type": "boolean"}, "new_topic": {"type": "string"}, "confidence": {"type": "number"}, "rationale": {"type": "string"}}, "required": ["topic_shift", "confidence"]}

Must be a valid JSON Schema object. Parse and validate before prompt assembly. Reject if required fields are missing.

[ABRUPT_SHIFT_EXAMPLES]

Few-shot examples demonstrating clear topic boundaries

User: How do I reset my password? Assistant: Go to Settings > Security. User: What is the capital of France?

Must be an array of 2-4 example conversation snippets with expected outputs. Each example must include a topic_shift boolean and new_topic label. Validate example format matches OUTPUT_SCHEMA.

[GRADUAL_SHIFT_EXAMPLES]

Few-shot examples demonstrating subtle topic transitions

User: Show me Q3 revenue. Assistant: $12.4M. User: What about Q4 projections?

Must be an array of 2-4 example conversation snippets. Gradual examples should show topic continuity where a naive keyword match might falsely detect a shift. Validate format consistency with abrupt examples.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the topic shift detection prompt into a multi-turn RAG application with validation, retries, and context reset logic.

The topic shift detection prompt is a classification gate that sits between the user's latest message and the rest of your RAG pipeline. Its job is to decide whether the conversation has changed subjects enough to require a context reset and re-retrieval. This prompt should be called on every user turn before you assemble the final context for answer generation. The output is a structured decision—typically a JSON object with a topic_shift boolean, a confidence score, and an optional new_topic_label—that your application code reads to branch between two paths: continue with existing context or flush and re-retrieve.

Wire this prompt into your application as a pre-processing step in the turn loop. After receiving user input, call the LLM with the topic shift prompt, passing the last N turns of conversation history and the current user message as [CONVERSATION_HISTORY] and [CURRENT_MESSAGE]. Parse the response with a strict JSON validator. If the model returns malformed JSON, retry once with a repair prompt that includes the raw output and the expected schema. If topic_shift is true and confidence exceeds your threshold (start with 0.7), trigger a context reset: clear the retrieved evidence cache, re-run retrieval with the new message as a standalone query, and reset the conversation history to only the system prompt and the current turn. If confidence is below threshold, log the ambiguous case for review and default to keeping context—but flag the turn for potential re-retrieval if the next answer quality eval scores low.

Model choice matters here. This is a classification task that benefits from fast, cheap models. Use a lightweight model like GPT-4o-mini, Claude Haiku, or Gemini Flash for this gate. Reserve your larger reasoning model for the actual answer generation step. Add observability: log every topic shift decision with the confidence score, the turns compared, and whether a reset was triggered. This data becomes invaluable for tuning the confidence threshold and identifying patterns—like users who bounce between related topics without a true shift—that cause false positives. For high-stakes domains where a missed topic shift could produce dangerously irrelevant answers, add a human review queue for low-confidence decisions or implement a secondary check: after answer generation, run a quick relevance eval to catch cases where the topic shift detector failed and trigger a retroactive reset.

IMPLEMENTATION TABLE

Expected Output Contract

Concrete fields, types, and validation rules for the topic shift detection output. Wire these into your application parser and eval harness.

Field or ElementType or FormatRequiredValidation Rule

topic_shift_detected

boolean

Must be exactly true or false. Reject any string, integer, or null value.

shift_type

enum: abrupt | gradual | none

Must be one of the three allowed values. If topic_shift_detected is false, shift_type must be none.

current_topic_label

string (max 80 chars)

A short human-readable label for the detected current topic. Must not be empty. If no shift, label the existing topic.

previous_topic_label

string (max 80 chars) or null

Label for the prior topic. Must be null when topic_shift_detected is false. Required when a shift is detected.

confidence_score

float (0.0 to 1.0)

Must be a number between 0.0 and 1.0 inclusive. Reject values outside this range. Confidence reflects the model's certainty about the shift decision.

boundary_turn_index

integer or null

The conversation turn index where the shift occurred. Must be null when topic_shift_detected is false. Must be a non-negative integer when a shift is detected.

evidence_summary

string (max 200 chars)

Brief natural language explanation of which user utterance signals the shift. Must reference specific user text. Required even when no shift is detected to explain stability.

recommended_action

enum: reset_context | re_retrieve | continue | escalate

Must be one of the four allowed values. reset_context and re_retrieve are valid only when topic_shift_detected is true. continue is valid only when false. escalate is valid when confidence_score is below 0.7.

PRACTICAL GUARDRAILS

Common Failure Modes

Topic shift detection fails silently in production, causing retrieval of irrelevant context and incoherent answers. These are the most common failure modes and how to guard against them.

01

Gradual Shift Miss

What to watch: The user drifts topics over 2-3 turns without an explicit new question. The detector classifies each turn as a follow-up, accumulating stale context until the answer is completely ungrounded. Guardrail: Include a 'topic coherence score' that degrades as turns diverge from the original intent, triggering re-retrieval when the score drops below a threshold.

02

False Positive on Clarification

What to watch: A user asks for more detail or a specific example from the current answer, but the detector misclassifies this as a new topic. The system discards relevant context and retrieves unrelated documents. Guardrail: Weight explicit anaphora and direct reference to prior entities heavily against a topic shift. Require a minimum semantic distance before triggering a reset.

03

Keyword Overfit

What to watch: A shared keyword between the old and new topic (e.g., 'cell' in biology vs. 'cell' in telecommunications) tricks the detector into maintaining stale context. Guardrail: Use embedding-based semantic similarity rather than lexical overlap. Set a minimum similarity threshold below which a shift is forced regardless of shared tokens.

04

Empty Reset Failure

What to watch: The detector correctly identifies a topic shift but the system fails to clear conversation history or re-trigger retrieval. The new answer is generated with old, irrelevant evidence. Guardrail: Implement a hard state reset action tied to the shift marker. Log the reset event and verify that the subsequent retrieval call uses only the new query, not the accumulated history.

05

Over-Reset on Short Turns

What to watch: Brief, low-information turns like 'ok', 'thanks', or 'what about X?' trigger a full context reset, losing valuable conversation state. The assistant appears amnesic. Guardrail: Apply a minimum turn length or information content filter before evaluating for topic shift. Short, low-entropy turns should default to 'no shift' unless they contain an explicit new entity.

06

Ambiguous Boundary Exploitation

What to watch: A user intentionally or accidentally crafts a query that sits exactly on the boundary between follow-up and new topic. The detector oscillates between states, causing inconsistent retrieval and answers. Guardrail: Implement hysteresis: require a stronger signal to switch states than to stay in the current one. Log boundary cases for human review and threshold tuning.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the topic shift detection prompt's output quality before deploying it in a production RAG pipeline. Each criterion targets a specific failure mode common in multi-turn topic boundary detection.

CriterionPass StandardFailure SignalTest Method

Abrupt Topic Shift Detection

Correctly flags a topic boundary when the user's new question is semantically unrelated to the prior turn and requires different retrieval sources.

Outputs topic_shift: false or confidence below 0.7 when the subject clearly changes (e.g., from 'billing' to 'API authentication').

Run a golden set of 20 turn pairs with known topic boundaries. Require precision >= 0.95 and recall >= 0.90 on abrupt shifts.

Gradual Topic Drift Detection

Correctly identifies a topic boundary after a sequence of turns that slowly drift from the original subject, flagging the turn where the core intent no longer matches.

Fails to flag a boundary after 3+ turns of drift, or flags too early (on the first tangentially related turn) when the user is still exploring the original topic.

Use a curated drift sequence dataset. Measure boundary placement accuracy within ±1 turn of the human-annotated shift point.

False Positive Rate on Follow-Ups

Does not flag a topic shift when the user asks a clarifying question, requests more detail, or corrects a prior answer within the same subject.

Produces topic_shift: true for follow-up questions like 'Can you explain that in more detail?' or 'What about for enterprise accounts?'.

Run a set of 50 in-topic follow-up turns. Require false positive rate < 5%.

Confidence Score Calibration

Outputs a confidence score between 0.0 and 1.0 that correlates with actual boundary correctness. High-confidence predictions (>0.85) are rarely wrong.

Confidence scores are uniformly high (>0.9) even on incorrect predictions, or scores are erratic and uncorrelated with accuracy.

Plot a calibration curve using 100+ labeled examples. Expected calibration error (ECE) should be < 0.10 after binning.

Context Reset Trigger Correctness

When topic_shift: true, the output includes a reset_trigger field that correctly identifies whether re-retrieval is needed or if the shift is conversational only.

Flags reset_trigger: true for a greeting like 'Hello again' or reset_trigger: false when the user clearly asks about a new document set.

Validate reset_trigger against a labeled set where human annotators marked whether new retrieval is required. F1 score >= 0.90.

Prior Topic Label Accuracy

When a shift is detected, the prior_topic_label field contains a concise, accurate summary of the previous topic for logging and context management.

Prior topic label is hallucinated, overly vague ('previous discussion'), or copies the user's last message verbatim instead of summarizing the topic.

Compare generated labels against human-written topic summaries using semantic similarity (cosine similarity >= 0.85) or LLM-as-judge pairwise comparison.

Multi-Turn History Stability

The prompt produces consistent boundary decisions when the same conversation history is presented with minor variations in earlier turns that do not affect the topic.

Boundary decisions flip between runs for the same conversation when non-topic details (e.g., user's name, timestamp) change.

Run the same conversation history 5 times with minor irrelevant perturbations. Require identical topic_shift decisions in >= 4 of 5 runs.

Empty or Short History Handling

When conversation history is empty or contains only one prior turn, the prompt defaults to topic_shift: false with moderate confidence, avoiding false boundaries on session start.

Flags a topic shift on the second turn of a conversation when the user is clearly continuing the same subject, or crashes on null history input.

Test with empty history array, single-turn history, and null history. Output must be valid JSON with topic_shift: false and confidence between 0.4 and 0.6.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a simple sliding-window of the last 3 user messages. Use a lightweight topic_shift boolean and a confidence float. Skip strict schema validation during early testing.

code
[SYSTEM]
You are a topic shift detector for a RAG assistant. Given the last [N] user messages, determine if the latest message represents a topic shift from the prior conversation. Return JSON with "topic_shift": true/false and "confidence": 0.0-1.0.

[CONVERSATION_HISTORY]
[HISTORY]

[LATEST_MESSAGE]
[INPUT]

Watch for

  • False positives on clarifying follow-ups that use different words but same topic
  • Confidence scores that are always 0.9+ without real discrimination
  • No handling of gradual topic drift across multiple turns
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.