Inferensys

Prompt

Feedback-Driven Context Window Inspection Prompt

A practical prompt playbook for using Feedback-Driven Context Window Inspection Prompt in production AI workflows.
Engineer optimizing context window usage on laptop, token usage charts visible, technical work session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for inspecting the context window when a user reports a quality issue.

This prompt is for RAG developers and search engineers who need to audit exactly what was inside the model's context window when a user reported a quality problem. The job-to-be-done is forensic: a user has flagged a response as irrelevant, incomplete, or hallucinated, and you must determine whether the root cause is a retrieval gap, a context truncation issue, or a ranking failure. The prompt reconstructs the context window from trace data, scores each chunk for relevance to the user's query, and identifies what was missing or truncated. Use this when you have access to a production trace containing the retrieved documents, the final assembled context, and the user's feedback signal.

Do not use this prompt when you lack trace data that captures the exact context window contents at inference time. If your observability pipeline only logs final outputs without retrieval intermediates, you cannot perform a meaningful context-window audit. This prompt is also not a substitute for offline retrieval evaluation against a golden dataset—it is a reactive, single-session diagnostic tool, not a batch evaluation system. The prompt requires the user's original query, the feedback signal (e.g., 'irrelevant response,' 'missing information,' 'hallucination'), and the raw trace spans that include retrieved chunks, their ranking scores, and the final assembled context. Without these inputs, the audit will produce unreliable or incomplete results.

The output is a structured context-window audit containing: a list of chunks that were included in the context window with per-chunk relevance scores, a list of chunks that were retrieved but truncated or excluded, and a diagnostic summary explaining whether missing or irrelevant context explains the user's feedback. This audit is designed to be consumed by a human engineer making a fix decision—update the retrieval query, adjust chunk size, re-rank, or expand the context budget. Always validate the audit against the original trace spans to confirm that no chunks were misattributed. For high-severity user reports where the fix will be deployed to production, require a second engineer to review the audit before accepting the diagnostic conclusion.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Feedback-Driven Context Window Inspection Prompt delivers reliable audits and where it introduces operational risk.

01

Good Fit: User-Reported Quality Issues

Use when: a user reports a vague quality issue (e.g., 'the answer was wrong' or 'it missed key details') and you need to determine if the context window is the root cause. Guardrail: Always pair the prompt output with the original user feedback text to keep the inspection anchored to the reported symptom.

02

Bad Fit: Real-Time Guardrails

Avoid when: you need to block a response before it reaches the user. This prompt is designed for post-hoc trace analysis, not synchronous pre-flight checks. Guardrail: Use this in a batch investigation workflow or a support tool, never in the hot path of a user-facing request.

03

Required Inputs

What you must provide: a specific user feedback report, the full trace data for that session (including retrieved chunks and final prompt), and the model's final output. Guardrail: If the trace data is incomplete or truncated, the prompt must explicitly flag missing spans rather than guessing what was in the context window.

04

Operational Risk: False Attribution

What to watch: the model may blame the retrieval system for a missing fact that was actually present but ignored by the generator. Guardrail: Require the prompt to output a relevance score for each chunk and a separate 'generator attention' flag to distinguish retrieval gaps from generation failures.

05

Operational Risk: Sensitive Data Exposure

What to watch: context windows often contain PII, credentials, or proprietary data from retrieved documents. Guardrail: Redact sensitive fields from the trace before passing it to the inspection prompt, and run all outputs through a PII scanner before they are stored in a support ticket or audit log.

06

Variant: Proactive Context Window Sampling

Use when: you want to audit context windows periodically, not just when a user complains. Guardrail: Adapt the prompt to sample traces based on a quality threshold (e.g., low confidence scores) rather than waiting for explicit user feedback, but keep a human reviewer in the loop for any suggested prompt or retrieval changes.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for auditing the context window when a user reports a quality issue.

This template is designed to be copied directly into your prompt library or observability tool. It instructs the model to act as a context-window auditor, reconstructing what the model saw during a specific request that received user feedback. The prompt forces the model to list every chunk, assess relevance, and identify whether missing or irrelevant context explains the reported issue. All dynamic inputs are represented as square-bracket placeholders that your application must populate before execution.

text
You are a context-window auditor for a RAG system. Your job is to inspect the full context window from a production request that received user feedback and determine whether the context explains the reported quality issue.

## INPUTS

### User Feedback
[USER_FEEDBACK]

### User Query (Original)
[USER_QUERY]

### Model Response (As Delivered to User)
[MODEL_RESPONSE]

### Retrieved Context Chunks (In Order of Retrieval)
[RETRIEVED_CHUNKS]

### Truncation Metadata
- Max context window size: [MAX_TOKENS]
- Actual tokens used: [ACTUAL_TOKENS]
- Chunks truncated: [TRUNCATED_CHUNK_IDS]

### Retrieval Configuration
- Retrieval query used: [RETRIEVAL_QUERY]
- Retrieval method: [RETRIEVAL_METHOD]
- Top-K setting: [TOP_K]
- Reranker applied: [RERANKER_NAME]

## OUTPUT SCHEMA

Return a JSON object with this exact structure:
{
  "audit_summary": {
    "total_chunks_retrieved": number,
    "chunks_in_context_window": number,
    "chunks_truncated": number,
    "overall_relevance_score": number (0.0 to 1.0),
    "missing_context_likely": boolean,
    "irrelevant_context_likely": boolean,
    "truncation_impact": "none" | "low" | "medium" | "high"
  },
  "chunk_analysis": [
    {
      "chunk_id": string,
      "position_in_window": number,
      "relevance_score": number (0.0 to 1.0),
      "relevance_rationale": string (one sentence),
      "used_in_response": boolean,
      "evidence_in_response": string or null (exact quote from response if used),
      "truncated": boolean
    }
  ],
  "feedback_alignment": {
    "feedback_type": string (classify: "missing_info" | "incorrect_info" | "irrelevant_response" | "incomplete_response" | "other"),
    "context_explains_feedback": boolean,
    "explanation": string (how context does or does not explain the feedback),
    "root_cause_candidate": "retrieval_gap" | "ranking_failure" | "truncation" | "irrelevant_retrieval" | "prompt_issue" | "model_error" | "unclear"
  },
  "recommendations": [
    {
      "action": string,
      "target": "retrieval_query" | "top_k" | "reranker" | "chunk_size" | "context_window" | "prompt_instructions" | "model" | "investigate_further",
      "rationale": string (one sentence tied to audit evidence)
    }
  ]
}

## CONSTRAINTS
- Score relevance against the user query AND the user feedback, not against the model response.
- If a chunk was truncated, mark it and assess whether the truncated portion likely contained needed information.
- For the root_cause_candidate, select only ONE primary cause. Use "unclear" if evidence is insufficient.
- Every recommendation must reference specific chunk IDs or metadata from the audit.
- Do not speculate about retrieval system internals beyond what is provided in the metadata.

## RISK_LEVEL: [RISK_LEVEL]
- If RISK_LEVEL is "high": flag the audit for human review and do not auto-apply recommendations.
- If RISK_LEVEL is "medium": recommendations can be queued for review but not auto-deployed.
- If RISK_LEVEL is "low": recommendations can be logged for trend analysis.

Adaptation notes: Replace each square-bracket placeholder with data from your trace store or observability platform. The [RETRIEVED_CHUNKS] field should contain the full text of each chunk with its ID and retrieval rank. If your system does not capture truncation metadata, remove the truncated fields from the schema or set them to false. The [RISK_LEVEL] placeholder should be set by your application based on the severity of the user feedback—use "high" for complaints involving factual errors, safety concerns, or regulated content. For low-stakes feedback, you can remove the human-review constraints to enable automated analysis pipelines.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Feedback-Driven Context Window Inspection Prompt. Each variable must be supplied at runtime to produce a reliable context-window audit. Missing or malformed inputs are the most common cause of incomplete inspection reports.

PlaceholderPurposeExampleValidation Notes

[USER_FEEDBACK]

The exact user-reported quality issue or complaint text

The answer cited a policy that doesn't exist in our docs

Must be non-empty string. Truncate to 500 chars if longer. Flag if sentiment is neutral or positive when a defect is expected.

[FULL_TRACE_JSON]

Complete production trace including retrieval spans, generation spans, and tool calls

{"spans":[{"span_id":"abc","operation":"retrieve","input":"...","output":"..."}]}

Must be valid JSON. Reject if missing retrieval spans or generation span. Validate span ordering is chronological. Flag if trace exceeds 100 spans for truncation risk.

[CONTEXT_WINDOW_SNAPSHOT]

The exact context chunks passed to the model during generation

["chunk_1":"Our return policy requires...","chunk_2":"Shipping costs are..."]

Must be array of objects with chunk_id and content fields. Reject if empty array. Validate chunk count against retrieval span output. Flag if total token count exceeds model context limit.

[MODEL_OUTPUT]

The final model response the user received and complained about

Based on our policy, you are eligible for a full refund within 30 days.

Must be non-empty string. Compare against generation span output for consistency. Flag if output contains refusal language or disclaimers that may explain user dissatisfaction.

[RETRIEVAL_QUERY]

The query used to retrieve context for this turn

What is the return policy for electronics?

Must be non-empty string. Validate query is present in retrieval span input. Flag if query appears malformed, empty, or unrelated to user feedback topic.

[CHUNK_METADATA]

Metadata for each retrieved chunk including source, score, and rank

{"chunk_id":"1","source":"help_center/returns.md","score":0.87,"rank":1}

Must be array of objects with chunk_id, source, score, and rank fields. Validate scores are between 0 and 1. Flag if top-ranked chunk score is below 0.5 or if all scores are within 0.1 of each other.

[TRUNCATION_POLICY]

The context window truncation rules active during this request

max_chunks=10, max_tokens=8000, strategy=fifo

Must be non-empty string or object. Validate against actual chunk count in context window. Flag if chunk count exceeds max_chunks or if truncation strategy is not documented in system config.

[SESSION_METADATA]

Session-level data including user ID, timestamp, and model version

{"user_id":"u_123","timestamp":"2025-01-15T14:30:00Z","model":"claude-3-opus"}

Must be valid JSON with user_id and timestamp fields. Reject if timestamp is future-dated. Flag if model version differs from expected production version for cross-reference with deployment logs.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Feedback-Driven Context Window Inspection Prompt into a production RAG observability pipeline.

This prompt is designed to be triggered by a user feedback event, such as a 'thumbs down' or a support ticket flagging a low-quality answer. The implementation harness should automatically fetch the full trace for the flagged session, extract the final context window payload, and pass it to the prompt alongside the user's original query and the model's generated response. The goal is to produce a structured audit that your observability dashboard or support tool can display, allowing an engineer to immediately see which chunks were relevant, which were missing, and whether truncation explains the failure.

To wire this into an application, build a feedback webhook handler that queries your trace store (e.g., LangSmith, Arize, or a custom OpenTelemetry backend) for the retrieval_context and generation spans associated with the flagged session_id. Construct the [CONTEXT_WINDOW] variable by serializing the retrieved documents in order, preserving their doc_id, position, and content fields. The [USER_QUERY] and [MODEL_OUTPUT] variables come directly from the trace. Before calling the LLM, validate that the trace is complete and that the context window payload is not empty; if it is, return an error immediately rather than invoking the model. After receiving the LLM's JSON output, validate it against the expected schema—each chunk must have a relevance_score between 0 and 1, and the truncation_analysis must account for the model's actual context limit. Log the full audit result to your observability platform, linking it back to the original trace and feedback event for future querying.

For high-stakes applications where a missed retrieval gap could impact user trust or regulatory compliance, require a human to review the audit before closing the feedback loop. Implement a retry with exponential backoff if the LLM call fails or returns malformed JSON, but stop after three attempts and escalate to a manual review queue. Avoid running this prompt on every session—it is cost-effective only when triggered by explicit negative feedback or a sampling rule for quality assurance. Finally, store the audit results in a structured format that allows you to aggregate findings over time, identifying systemic retrieval issues like consistently low relevance scores for a specific document source or frequent truncation of long documents.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the Feedback-Driven Context Window Inspection Prompt before shipping. Each criterion targets a specific failure mode in context-window audits, from missing chunk attribution to incorrect relevance scoring.

CriterionPass StandardFailure SignalTest Method

Context chunk completeness

All chunks present in the trace's retrieval step are listed in the audit output with no omissions

Audit output has fewer chunks than the trace retrieval span; chunks are silently dropped

Count chunks in trace retrieval span vs. audit output; diff the chunk IDs

Truncation flag accuracy

Every chunk that exceeds the model's context limit is flagged as truncated with the actual token count at cutoff

Truncated chunks are not flagged; flag is present but token count is missing or estimated

Inject a known oversized chunk into a test trace; verify flag and token count match the trace metadata

Relevance score calibration

Each chunk receives a relevance score from 0.0 to 1.0 that correlates with the user feedback signal (higher scores for chunks that explain the issue)

All chunks receive identical scores; scores contradict the feedback signal direction

Run against 5 labeled traces with known relevant chunks; check Spearman correlation > 0.7

Missing context identification

Audit explicitly lists documents or facts that should have been retrieved but were absent, with a confidence note

Missing context section is empty when retrieval coverage is known to be incomplete; section contains hallucinated document titles

Use a trace with a known retrieval gap; verify the gap is identified and no invented sources appear

Feedback-to-context linkage

Audit connects the user's reported issue to specific chunks or missing chunks with trace evidence

Linkage is generic ('context was insufficient') without pointing to specific chunk IDs or retrieval steps

Provide a trace with a clear feedback signal; verify the audit cites at least one specific chunk ID or retrieval span ID

Output format compliance

Audit output matches the [OUTPUT_SCHEMA] exactly: all required fields present, no extra fields, correct types

Output is missing required fields; contains markdown instead of structured JSON; field types are wrong

Validate output against the JSON schema with a strict validator; reject on any schema violation

Source grounding for audit claims

Every claim about what was or was not in the context window is backed by a trace span ID or chunk ID

Audit makes assertions about context content without citing trace evidence; citations point to non-existent spans

Spot-check 3 claims per audit; verify each cited span ID exists in the trace and contains the claimed content

Abstention on ambiguous feedback

When user feedback is vague or contradictory, audit explicitly notes low confidence and requests clarification instead of forcing a diagnosis

Audit assigns high confidence to a root cause when the feedback signal is ambiguous or trace evidence is inconclusive

Feed a trace with deliberately vague feedback ('it was bad'); verify confidence score is below 0.5 and clarification is requested

PRACTICAL GUARDRAILS

Common Failure Modes

When inspecting context windows from user feedback, these failures surface first. Each card pairs a common breakage with a concrete guardrail you can implement before the audit reaches a stakeholder.

01

Truncation Masks the Missing Evidence

What to watch: The context window was full, so the retriever dropped the most relevant chunk. The audit then reports 'no relevant context found,' but the real problem is a budget limit, not a retrieval gap. Guardrail: Always report the total token fill percentage and flag any chunks that were retrieved but truncated before insertion. Require the audit to distinguish 'never retrieved' from 'retrieved but dropped.'

02

Relevance Scoring Drift

What to watch: The inspection prompt assigns high relevance to a chunk that matches the model's answer but ignores the user's original question. The audit becomes a self-justification loop. Guardrail: Anchor every relevance score to the user's reported intent from the feedback ticket, not to the model's final output. Require a separate 'intent alignment' check before scoring any chunk.

03

Citation Hallucination in the Audit Itself

What to watch: The inspection prompt fabricates a source line number or invents a chunk ID that doesn't exist in the trace. The audit looks authoritative but is wrong. Guardrail: Require the prompt to quote the exact chunk text and its trace span ID for every claim. Add a post-audit validator that checks every cited span ID against the raw trace before the report is shown to a human.

04

Feedback-to-Trace Mismatch

What to watch: The user reported a factual error, but the inspection prompt analyzes the wrong turn or the wrong session. The audit is thorough but irrelevant. Guardrail: Require the prompt to first output the session ID, turn number, and user feedback text it is analyzing. Add a pre-audit gate that halts if these don't match the ticket fields exactly.

05

Over-Attribution to a Single Chunk

What to watch: The inspection prompt finds one weak chunk and declares it the sole cause of failure, ignoring how multiple chunks interacted or contradicted each other. Guardrail: Require the audit to report chunk interactions, not just individual scores. Flag any case where two chunks in the window contradict each other and the model had to choose, because that's a retrieval quality issue, not a single-chunk problem.

06

Missing the Tool-Call Context Gap

What to watch: The inspection prompt only looks at retrieved text chunks and misses that a tool call failed silently, returned an empty result, or timed out before the context window was assembled. The audit blames retrieval when the real failure is a tool execution gap. Guardrail: Require the audit to include a tool-call summary section that lists every tool invoked before context assembly, its status, and whether its output reached the context window. Flag any tool whose output was expected but absent.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single trace JSON and a user feedback string. Skip strict schema validation on the output. Focus on getting a readable audit that explains whether missing context explains the feedback.

Prompt modification

  • Remove the relevance_score field requirement if the model struggles with numeric scoring.
  • Replace structured output instructions with a simpler request: "List each context chunk and mark whether it was relevant to the user's question."
  • Use a shorter [FEEDBACK] field: one sentence describing the user complaint.

Watch for

  • The model inventing context chunks that were not in the trace.
  • Relevance scores that are all 0.5 (non-committal).
  • Missing the distinction between truncated context and absent context.
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.