Inferensys

Prompt

Session Context Scoring Prompt for Query Fusion

A practical prompt playbook for retrieval pipeline architects who need to score prior conversation turns by relevance and weight their contribution to a fused retrieval query, with harness checks for scoring calibration and recency bias detection.
Developer working on RAG retrieval system, document chunks visible on screen, technical workspace with code editor.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Session Context Scoring Prompt for Query Fusion.

This prompt is for retrieval pipeline architects who need to fuse context from a multi-turn conversation into a single, high-quality search query. The core job-to-be-done is to score the relevance of each prior user and assistant turn against the user's current question, then use those scores to weight the contribution of each turn when generating a fused, context-aware query. You should use this prompt when your RAG system suffers from 'context dilution'—where naively stuffing the entire conversation history into a query rewriter introduces noise, exceeds context windows, or gives equal weight to irrelevant small talk and critical prior instructions. The ideal user is an engineer who already has a working conversational retrieval system and needs to add a selective attention mechanism before the final query rewrite step.

This prompt is not a standalone query rewriter. It is a scoring and weighting component that should sit upstream of a query generation prompt. Do not use this prompt if your application consists of single-turn queries, if you have no mechanism to pass weighted context to a downstream rewriter, or if your conversation history is consistently short enough to include in its entirety without degradation. The prompt requires a structured conversation history as input, with each turn clearly labeled by role and index. It also requires a defined output schema that maps turn indices to relevance scores and weights. Without this structured input, the model cannot produce calibrated scores, and without a downstream consumer for the weights, the output has no operational value.

Before implementing this prompt, ensure you have a calibration harness in place. Session context scoring is prone to recency bias, where the model over-weights the most recent turns regardless of their actual relevance to the current query. Your eval suite should include test cases where the critical context is deliberately placed several turns back, behind filler exchanges. Measure whether the scoring prompt correctly assigns higher weights to semantically relevant turns over temporally proximate but irrelevant ones. If your harness cannot detect this failure mode, you risk building a system that appears functional but silently ignores important user instructions issued earlier in the session.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Session Context Scoring Prompt for Query Fusion delivers value and where it introduces risk. Use these cards to decide if this prompt fits your retrieval pipeline before you integrate it.

01

Good Fit: Long, Multi-Turn Conversations

Use when: your RAG system handles sessions with 5+ turns where users ask follow-ups that depend on earlier context. Why: the scoring mechanism prevents distant, irrelevant turns from polluting the rewritten query while preserving critical dependencies.

02

Bad Fit: Single-Turn or Stateless Search

Avoid when: each query is independent with no conversation history. Risk: the scoring layer adds latency and complexity with no benefit. Guardrail: bypass the prompt entirely when session_turns.length <= 1 and use a simpler query reformulation path.

03

Required Inputs

Must have: the current user query, a list of prior turns with timestamps, and a defined relevance scoring rubric. Risk without these: the model cannot calibrate scores or will hallucinate turn importance. Guardrail: validate input shape before calling the prompt and abort if prior turns are missing or malformed.

04

Operational Risk: Recency Bias

What to watch: the model over-weights the most recent turn and ignores older but still-relevant context. Guardrail: include explicit instructions in the prompt to score based on topical relevance, not temporal proximity. Add a calibration check that flags when the last turn always receives the highest score.

05

Operational Risk: Scoring Drift

What to watch: score distributions shift over time as conversation patterns change, causing the fusion step to include too much or too little context. Guardrail: log score distributions per session and alert when the mean relevance score crosses a predefined threshold. Periodically review a sample of scored turns against human judgment.

06

Latency and Cost Sensitivity

What to watch: scoring every prior turn adds an LLM call that grows with session length, increasing latency and token costs. Guardrail: cap the number of prior turns scored. For sessions exceeding the cap, use a lightweight heuristic pre-filter to select candidate turns before running the full scoring prompt.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that scores each prior turn's relevance to the current query and weights their contribution to the fused rewrite.

This prompt template is the core instruction set for the Session Context Scoring Prompt for Query Fusion. It takes the current user query, the full conversation history, and a set of scoring criteria, then outputs a relevance-weighted fusion of prior context into a single, self-contained retrieval query. The template uses square-bracket placeholders for all dynamic inputs, making it safe to copy directly into your prompt management system or codebase. Before using it in production, you must define your scoring dimensions, set a minimum relevance threshold to exclude noise, and decide on a weighting strategy for the final fusion.

text
You are a retrieval query rewriter for a conversational AI system. Your task is to fuse relevant context from the conversation history into the current user query to produce a single, self-contained retrieval query.

**Current Query:**
[CURRENT_QUERY]

**Conversation History:**
[CONVERSATION_HISTORY]

**Scoring Dimensions:**
[SCORING_DIMENSIONS]

**Instructions:**
1. For each turn in the conversation history, assign a relevance score from 0.0 to 1.0 against the current query for each scoring dimension listed above.
2. Calculate a composite relevance score for each turn by [WEIGHTING_STRATEGY].
3. Exclude any turn with a composite score below [MINIMUM_RELEVANCE_THRESHOLD].
4. For turns that meet the threshold, extract the key entities, constraints, and unresolved references that are still relevant to the current query.
5. Fuse the extracted context into the current query to produce a single, self-contained retrieval query. Do not introduce information not present in the history or current query.
6. Output the result as a JSON object with the following structure:

**Output Schema:**
{
  "fused_query": "string",
  "turn_scores": [
    {
      "turn_index": integer,
      "turn_text": "string",
      "dimension_scores": {
        "[DIMENSION_NAME]": float
      },
      "composite_score": float,
      "included": boolean,
      "extracted_context": "string or null"
    }
  ],
  "excluded_turns": integer,
  "fusion_notes": "string"
}

**Constraints:**
- Do not hallucinate entities or constraints not present in the history.
- If no turns meet the relevance threshold, return the current query unchanged as the fused query.
- If the current query is already self-contained, do not force irrelevant context into the rewrite.

To adapt this template, start by defining your scoring dimensions. Common dimensions include topical overlap, entity co-reference, temporal proximity, and constraint persistence. For a customer support system, you might score on issue continuity and product mention overlap. For a research assistant, you might score on conceptual relevance and evidence chain continuity. Next, choose a weighting strategy: simple averaging works for balanced dimensions, while weighted sums let you prioritize recency or entity persistence. Set the minimum relevance threshold based on your precision-recall trade-off; a threshold of 0.3 is a reasonable starting point, but calibrate it against your eval dataset. Finally, wire the output into your retrieval pipeline by passing fused_query to your search backend and logging turn_scores for observability. If you are operating in a high-stakes domain where incorrect context fusion could produce misleading answers, add a human review step for queries where the maximum composite score falls in an ambiguous range, or where the fusion notes flag uncertainty.

IMPLEMENTATION TABLE

Prompt Variables

Inputs required for the Session Context Scoring Prompt to reliably score prior turns and weight their contribution to the rewritten query. Each variable must be validated before scoring execution.

PlaceholderPurposeExampleValidation Notes

[CURRENT_QUERY]

The user's latest question or statement that needs to be rewritten for retrieval.

What were the key findings from that report?

Must be a non-empty string. Validate length > 0. Reject if identical to the immediately preceding turn without modification.

[SESSION_HISTORY]

An ordered array of prior conversation turns, each containing a role, content, and optional timestamp.

[{"role": "user", "content": "Show me the Q3 revenue report.", "timestamp": "2025-01-15T10:00:00Z"}, {"role": "assistant", "content": "Here is the Q3 report summary..."}]

Must be a valid JSON array. Each object requires 'role' and 'content' fields. 'timestamp' is optional but recommended for recency weighting. Reject if array contains only the current query.

[SCORING_CRITERIA]

A list of dimensions used to score each prior turn's relevance to the current query.

["topical_overlap", "entity_continuity", "temporal_proximity", "intent_alignment"]

Must be a non-empty array of strings. Each string must map to a defined scoring function in the harness. Reject if criteria list is empty or contains unrecognized dimension names.

[RECENCY_WEIGHT_FACTOR]

A float between 0.0 and 1.0 that controls how much a turn's position in the session influences its score.

0.15

Must be a float. Validate range 0.0 <= value <= 1.0. A value of 0.0 disables recency bias; 1.0 makes recency the dominant factor. Default to 0.1 if not provided.

[MIN_SCORE_THRESHOLD]

The minimum relevance score a prior turn must achieve to be included in the query fusion context.

0.4

Must be a float. Validate range 0.0 <= value <= 1.0. Turns scoring below this threshold are pruned from the context window. Set to 0.0 to include all turns.

[OUTPUT_SCHEMA]

The expected JSON schema for the scored and weighted turn output.

{"type": "object", "properties": {"scored_turns": {"type": "array", "items": {"type": "object", "properties": {"turn_id": {"type": "integer"}, "score": {"type": "number"}, "weight": {"type": "number"}}}}}}

Must be a valid JSON Schema object. Validate with a schema validator before passing to the model. Ensure 'score' and 'weight' fields are defined as numbers.

[MAX_CONTEXT_TURNS]

The maximum number of prior turns to score and return, preventing context window overflow.

5

Must be a positive integer. Validate value >= 1. If the number of scored turns exceeds this value, retain only the top-scoring turns. Set to null to disable truncation.

[FUSION_STRATEGY]

Specifies how scored turns are combined into the final query context: weighted concatenation, summary, or keyword extraction.

weighted_concatenation

Must be one of an allowed enum: ['weighted_concatenation', 'summary_fusion', 'keyword_union']. Reject any unrecognized strategy. Default to 'weighted_concatenation' if not provided.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Session Context Scoring Prompt into a production retrieval pipeline with validation, calibration checks, and fallback logic.

Integrating the Session Context Scoring Prompt into a query fusion pipeline requires treating it as a deterministic pre-retrieval scoring step, not a standalone chat interaction. The prompt receives the current user query and a structured array of prior conversation turns, each with a unique turn ID, timestamp, and text. It returns a JSON object mapping each turn ID to a relevance score between 0.0 and 1.0, along with a brief justification. This output feeds directly into a weighted query fusion module that constructs the final retrieval query by blending the current query with high-scoring prior turns. The harness must enforce strict input and output schemas to prevent malformed scores from corrupting downstream retrieval.

Build the harness with these concrete checks: (1) Validate that every input turn ID appears in the output mapping and that no hallucinated IDs are introduced. (2) Clamp all scores to the [0.0, 1.0] range and reject any response where scores fall outside this interval. (3) Implement a recency bias detector that flags if the model consistently assigns the highest scores to the most recent turns regardless of semantic relevance—this indicates calibration drift. (4) Log the raw prompt, model response, and parsed scores for every call to enable offline calibration analysis. (5) Set a minimum score threshold (e.g., 0.3) below which turns are excluded from fusion to prevent noise injection. For model choice, use a fast, instruction-tuned model such as GPT-4o-mini or Claude 3.5 Haiku; latency matters here because this step sits on the critical path before retrieval. If the model returns invalid JSON after one retry, fall back to a recency-only weighting scheme rather than blocking the user.

Avoid wiring this prompt directly into a user-facing chat loop without caching. Session context scoring should be recomputed only when a new user turn arrives, not on every retrieval attempt. Cache the score map per turn and invalidate it only when the conversation history changes. For high-traffic systems, consider batching scoring requests for multiple concurrent sessions. Finally, run periodic offline evaluations using a golden dataset of session-turn pairs with human-annotated relevance scores to detect scoring drift. If the model's agreement with human annotators drops below a defined threshold, recalibrate the prompt or switch to a simpler recency-decay baseline until the issue is resolved.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required JSON structure, field types, and validation rules for the Session Context Scoring Prompt output. Use this contract to parse and validate the model's response before feeding scores into the query fusion step.

Field or ElementType or FormatRequiredValidation Rule

turn_scores

Array of objects

Must be a JSON array. Length must equal the number of [SESSION_TURNS] provided. If empty, return an empty array.

turn_scores[].turn_id

String or Integer

Must match the identifier provided in the corresponding [SESSION_TURNS] input element. No fabricated IDs allowed.

turn_scores[].relevance_score

Number (float)

Must be a float between 0.0 and 1.0 inclusive. Parse check: reject non-numeric strings. A score of 0.0 indicates no relevance.

turn_scores[].rationale

String

Must be a non-empty string summarizing the key terms or topics that justify the score. Null or empty string validation should trigger a retry.

current_query_embedding_hint

String

If present, must be a concise string of keywords and phrases extracted from [CURRENT_QUERY] used for comparison. Validate length is under 200 characters.

scoring_model_version

String

If present, must match the pattern 'v<number>.<number>' (e.g., 'v1.0'). Used for traceability; reject malformed version strings.

recency_bias_flag

Boolean

Must be true if the scoring distribution shows a statistically improbable weight on the most recent turns (e.g., last turn > 0.9 and all others < 0.1). Otherwise false. Triggers a calibration review in the harness.

processing_notes

String

If present, must not contain any PII or sensitive entity names from the session context. Validate with a PII redaction check before logging.

PRACTICAL GUARDRAILS

Common Failure Modes

Session context scoring for query fusion fails in predictable ways. These are the most common production failure modes and the guardrails that catch them before they degrade retrieval quality.

01

Recency Bias Overweights Adjacent Turns

What to watch: The scoring prompt assigns disproportionately high relevance to the immediately preceding turn while ignoring earlier turns that contain critical context. This happens when the model defaults to conversational adjacency heuristics rather than semantic relevance. Guardrail: Add a calibration check that compares the score distribution across all turns. Flag sessions where the most recent turn receives more than 60% of total weight while earlier turns with overlapping entities score near zero. Require explicit justification in the prompt for high scores on adjacent turns.

02

Entity Drift Causes False Relevance

What to watch: The model scores a prior turn as highly relevant because it shares surface-level terms with the current query, but the underlying entity or topic has shifted. For example, 'the budget' in turn one refers to Q3 marketing budget while 'the budget' in turn five refers to Q4 engineering budget. Guardrail: Include entity disambiguation in the scoring prompt. Require the model to identify the specific entity instance referenced in each turn before scoring relevance. Add a post-scoring validation that checks for entity collision across high-scoring turns and flags ambiguous mappings.

03

Zero-Score Collapse on Short Sessions

What to watch: When a session has only two or three prior turns, the scoring prompt may assign near-zero relevance to all of them because the model expects longer history for meaningful context. This causes the fusion step to treat the query as standalone, losing available context. Guardrail: Add a minimum score threshold that triggers a fallback. If all prior turns score below 0.2 on a normalized scale, force inclusion of the most recent turn with a floor weight. Test scoring behavior on sessions with one, two, and three prior turns explicitly.

04

Score Calibration Drift Across Sessions

What to watch: The scoring prompt produces inconsistent score distributions across different sessions. One session may have scores tightly clustered between 0.7 and 0.9 while another spreads scores from 0.1 to 0.95. This makes downstream fusion thresholds unreliable. Guardrail: Normalize scores within each session before fusion. Apply min-max scaling or softmax across the turn scores so the distribution is consistent regardless of the model's raw output range. Log raw and normalized scores separately for monitoring.

05

Implicit Reference Resolution Fails Before Scoring

What to watch: The scoring prompt evaluates relevance between the current query and prior turns that contain unresolved pronouns or implicit references. The model cannot accurately score relevance when prior turns say 'that approach' or 'her proposal' without resolving what those refer to. Guardrail: Run anaphora and implicit reference resolution on all prior turns before they enter the scoring prompt. Feed resolved, decontextualized versions of prior turns into the scorer. Validate that resolved turns contain explicit entity mentions rather than pronouns.

06

Topic Boundary Blindness Inflates Irrelevant Scores

What to watch: The scoring prompt treats all prior turns as part of one continuous conversation and assigns moderate relevance to turns from a clearly different topic that happened earlier in the same session. This pollutes the fusion step with irrelevant context. Guardrail: Pre-process the session with a topic boundary detector before scoring. Only pass turns from the current topic segment into the scoring prompt. If topic boundary detection is uncertain, include a boundary confidence flag in the scoring input so the model can down-weight turns from potential topic shifts.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Session Context Scoring Prompt before deployment. Each criterion targets a specific failure mode in scoring calibration, recency bias, and relevance weighting. Run these checks against a golden dataset of multi-turn sessions with known relevant prior turns.

CriterionPass StandardFailure SignalTest Method

Relevance Score Calibration

Scores for clearly relevant prior turns are >= 0.8 and scores for clearly irrelevant turns are <= 0.2

All turns receive mid-range scores (0.4-0.6) regardless of relevance; scores are uniformly high or uniformly low

Run 20 multi-turn sessions with hand-labeled relevance pairs. Calculate mean absolute error between model scores and human labels. Pass if MAE < 0.15

Recency Bias Detection

A highly relevant turn at position N-3 outscores an irrelevant turn at position N-1 in at least 80% of test cases

The most recent turn always receives the highest score regardless of relevance to current query

Construct 10 sessions where the most recent turn is irrelevant but an earlier turn is highly relevant. Pass if earlier turn outscores recent turn in >= 8 cases

Anaphora Resolution Awareness

Turns containing the antecedent for a pronoun in the current query score >= 0.7

Turns with the correct antecedent score below 0.5 while unrelated turns score higher

Create 15 sessions ending with a pronoun-heavy query. Verify the turn introducing the referred entity receives the highest or second-highest score in >= 13 cases

Topic Shift Handling

When current query introduces a new topic, all prior turns score <= 0.3

Prior turns from a different topic retain scores above 0.5 after a clear topic shift

Build 10 sessions with an abrupt topic shift at the final turn. Pass if mean score of all prior turns is <= 0.3 in >= 8 sessions

Weight Distribution Sanity

Sum of all turn weights equals 1.0 within a tolerance of 0.01

Weight sum deviates by more than 0.05 from 1.0; negative weights appear; weights are null or undefined

Parse the output weights array. Assert sum is between 0.99 and 1.01. Assert all weights are non-negative. Run on 50 sessions with zero failures

Zero-Relevance Session Handling

When no prior turn is relevant, all scores are <= 0.2 and the rewritten query is identical to or minimally different from the current query

Irrelevant turns receive scores above 0.4; the rewritten query injects terms from irrelevant history

Create 10 sessions where the final query is completely unrelated to all prior turns. Pass if max score <= 0.2 and the rewritten query contains no terms exclusive to prior turns in all 10 cases

Multi-Reference Aggregation

When multiple prior turns contribute relevant information, all relevant turns score >= 0.6 and their combined weight exceeds 0.8

Only one relevant turn is scored highly while other equally relevant turns are suppressed below 0.3

Construct 8 sessions where the current query depends on information distributed across 3 prior turns. Pass if all 3 relevant turns score >= 0.6 in >= 7 sessions

Output Schema Compliance

Response is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed

Missing fields; wrong types; extra fields not in schema; malformed JSON

Validate output against the defined JSON schema using a programmatic validator. Run on 100 sessions. Pass if 100% schema compliance

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a frontier model and a small conversation history window (last 3-5 turns). Remove the calibration harness and scoring justification fields. Accept raw 0-1 scores without normalization checks.

code
For each prior turn, output:
{
  "turn_id": [TURN_ID],
  "relevance_score": [0.0-1.0]
}

Watch for

  • Recency bias: recent turns always score high regardless of relevance
  • Missing calibration: scores drift across sessions without a baseline
  • Over-scoring filler turns ("ok", "thanks") that add no retrieval value
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.