This prompt is for RAG developers and AI reliability engineers who need to diagnose why a production response failed an automated evaluation when the root cause is suspected to be evidence truncated from the context window. The job-to-be-done is isolating whether the model had the right evidence but lost it during context assembly, versus never retrieving it at all. Use this prompt when you have a trace that captures the full retrieved document set, the final context window payload, the model output, and the eval scores. The prompt produces a before-and-after analysis showing exactly which documents or passages were dropped, their relevance scores, which eval dimensions were impacted, and a token budget attribution breakdown.
Prompt
Context Window Truncation Impact on Eval Prompt

When to Use This Prompt
Diagnose eval failures caused by evidence truncated from the context window, not by retrieval gaps.
The ideal user has access to structured trace data—typically from an observability platform or logging pipeline—that includes per-step retrieval results with relevance scores, the assembled context payload sent to the model, and the eval rubric with dimension-level scores. Without this trace fidelity, the prompt cannot distinguish between a retrieval gap (the document was never fetched) and a truncation gap (the document was fetched but dropped to fit the context window). The prompt requires the following inputs as square-bracket placeholders: [RETRIEVED_DOCUMENTS] with relevance scores, [CONTEXT_WINDOW_PAYLOAD] showing what was actually passed to the model, [MODEL_OUTPUT], [EVAL_SCORES] with dimension-level breakdowns, and [TOKEN_BUDGET] showing the model's context limit and actual usage. Optional inputs include [RANKING_CONFIG] if a reranker was used and [TRUNCATION_STRATEGY] if the system applies a specific truncation policy.
Do not use this prompt when you lack trace data showing what was retrieved versus what was actually passed to the model. If the eval failure is clearly caused by retrieval gaps—the search step never returned relevant documents—use the Retrieval Gap Root-Cause for Eval Failure Prompt instead. Similarly, if the failure is caused by the model ignoring evidence that was present in the context window, this is a grounding or instruction-following problem, not a truncation problem, and requires a different diagnostic prompt. This prompt is specifically scoped to the narrow failure mode where evidence was present in the retrieval set but absent from the context window payload, and you need to quantify the eval impact of that absence.
Use Case Fit
Where the Context Window Truncation Impact on Eval Prompt works, where it fails, and what you must have in place before using it.
Good Fit: Post-Failure Forensics
Use when: an eval run flags a RAG response as 'ungrounded' or 'incomplete' and you need to prove truncation was the root cause. Guardrail: run this prompt only after a failing eval score is recorded; do not use it for live request gating.
Good Fit: Token Budget Attribution
Use when: you need a line-item breakdown of what consumed the context window to justify infrastructure or retrieval changes. Guardrail: pair the output with cost and latency trace data to build a full business case before re-architecting the prompt assembly.
Bad Fit: Real-Time Guardrails
Avoid when: you need to block a response before it reaches the user. This prompt is a post-hoc diagnostic tool, not a streaming interceptor. Guardrail: implement pre-generation context-length checks and chunk budgets in your application layer for live prevention.
Bad Fit: Non-RAG or Single-Turn Systems
Avoid when: the system has no retrieval step or the context window is statically defined. The prompt's core logic depends on comparing retrieved evidence against what was actually provided to the model. Guardrail: verify that your trace contains distinct retrieval and generation segments before invoking this analysis.
Required Inputs
Must have: the original user query, the full list of retrieved documents with relevance scores, the final assembled context payload, the model's output, and the failing eval rubric with dimension-level scores. Guardrail: if any of these inputs are missing, the prompt will produce low-confidence or misleading attribution.
Operational Risk: Blame Misattribution
Risk: the prompt may attribute an eval failure to truncation when the real cause is poor retrieval ranking or embedding drift. Guardrail: always cross-reference the truncation analysis with a retrieval gap diagnosis before concluding that context length alone is the root cause.
Copy-Ready Prompt Template
A reusable prompt for diagnosing eval failures caused by evidence being truncated from the context window.
This prompt template is designed to be pasted directly into your trace analysis tool, evaluation pipeline, or manual review workflow. It instructs the model to act as a forensic RAG auditor, comparing the original retrieval results against what actually fit inside the context window for a specific production request. The goal is to produce a structured, evidence-backed report that links truncation events to specific eval dimension failures, enabling you to decide whether to increase context budgets, refactor your prompt's assembly logic, or adjust your retrieval strategy.
textYou are a forensic RAG auditor. Your task is to analyze a production trace where an LLM response failed an automated evaluation. Your specific focus is on context window truncation as the root cause. ## INPUT DATA - **Original Retrieved Documents:** A list of all documents and their metadata returned by the retrieval system before context assembly. [RETRIEVED_DOCUMENTS] - **Final Context Window Payload:** The exact text that was sent to the LLM as context. [FINAL_CONTEXT_PAYLOAD] - **LLM Output:** The final response generated by the model. [LLM_OUTPUT] - **Eval Failure Details:** The specific evaluation rubric, the failing score, and the evaluator's justification. [EVAL_FAILURE_DETAILS] - **Token Budget:** The maximum token limit for the context window. [TOKEN_BUDGET] ## ANALYSIS INSTRUCTIONS 1. **Identify Truncated Documents:** Compare [RETRIEVED_DOCUMENTS] against [FINAL_CONTEXT_PAYLOAD]. List every document or document chunk that was fully or partially excluded from the final context window. 2. **Score Relevance:** For each truncated document, assign a relevance score (High, Medium, Low) to the user's implied query, based on its content and metadata. 3. **Map to Eval Failure:** For each truncated document with High or Medium relevance, explain how its absence could have directly caused the specific failure described in [EVAL_FAILURE_DETAILS]. Link the missing information to a failed dimension in the rubric. 4. **Attribute Token Spend:** Provide a breakdown of how the [TOKEN_BUDGET] was consumed. Categorize the spend into: System Prompt, Retrieved Documents (by ID), Conversation History, and Generated Output. 5. **Formulate a Root-Cause Verdict:** State clearly whether context window truncation is the primary, contributing, or unlikely root cause of the eval failure. ## OUTPUT FORMAT Return your analysis as a JSON object conforming to this schema: { "truncation_analysis": [ { "document_id": "string", "relevance_score": "High | Medium | Low", "truncation_type": "Full | Partial", "eval_impact": "string explaining the causal link to the eval failure, or null if relevance is Low" } ], "token_attribution": { "system_prompt_tokens": "number", "retrieved_document_tokens": "number", "conversation_history_tokens": "number", "generated_output_tokens": "number", "total_tokens_used": "number" }, "root_cause_verdict": "Primary | Contributing | Unlikely", "verdict_rationale": "string" } ## CONSTRAINTS - Base your analysis strictly on the provided [RETRIEVED_DOCUMENTS] and [FINAL_CONTEXT_PAYLOAD]. Do not infer missing data. - If the eval failure is unrelated to truncation, state that clearly in your verdict and rationale. - Do not suggest fixes; focus only on diagnosis.
To adapt this template, replace the square-bracket placeholders with data from your production trace system. The [RETRIEVED_DOCUMENTS] should be a serialized list of objects, each with an id and content field at minimum. The [FINAL_CONTEXT_PAYLOAD] is the fully assembled string sent to the model. Ensure your trace tooling captures this pre- and post-assembly state, as it is the single most critical data dependency for this analysis. If your eval rubric has many dimensions, you can simplify [EVAL_FAILURE_DETAILS] to just the name of the failed dimension and the evaluator's one-line justification to keep the prompt focused.
Prompt Variables
Inputs required to reliably diagnose eval failures caused by context window truncation. Each variable must be extracted from your production trace or observability platform before running the prompt.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[FULL_CONTEXT_WINDOW_SNAPSHOT] | Complete final context payload sent to the model, including system prompt, retrieved documents, and user input | {"system": "You are...", "messages": [...], "documents": [{"id": "doc_1", "text": "..."}]} | Must be a valid JSON object. Parse check required. Null not allowed. Must include documents array with id and text fields. |
[TRUNCATION_LOG] | Step-by-step record of what was dropped, trimmed, or compressed during context assembly | [{"step": "retrieval_rerank", "dropped_docs": ["doc_7", "doc_12"], "reason": "token_budget_exceeded", "tokens_remaining": 0}] | Must be a valid JSON array. Each entry requires step, dropped_docs, reason, and tokens_remaining fields. Null allowed if no truncation occurred. |
[EVAL_RUBRIC_DIMENSIONS] | List of evaluation dimensions and their pass/fail criteria from the failing eval run | ["faithfulness", "completeness", "citation_accuracy"] | Must be a non-empty array of strings matching known rubric dimension names. Schema check against eval platform dimension registry required. |
[EVAL_SCORES] | Per-dimension scores from the failed evaluation, including thresholds | [{"dimension": "faithfulness", "score": 0.3, "threshold": 0.7, "passed": false}] | Must be a valid JSON array. Each entry requires dimension, score, threshold, and passed fields. Score must be numeric between 0 and 1. |
[MODEL_OUTPUT] | The exact model response that failed evaluation | "Based on the provided documents, the key findings are..." | Must be a non-empty string. Null not allowed. Should match the output captured in the trace exactly, including any trailing whitespace or formatting. |
[RETRIEVED_DOCUMENT_SET] | Full set of documents originally retrieved before any truncation or ranking | [{"id": "doc_1", "text": "...", "relevance_score": 0.92}] | Must be a valid JSON array of document objects with id, text, and relevance_score fields. Null not allowed. Array length must be greater than or equal to documents in [FULL_CONTEXT_WINDOW_SNAPSHOT]. |
[TOKEN_BUDGET_CONFIG] | Token allocation limits configured for the prompt assembly pipeline | {"total_budget": 8192, "system_prompt_allocation": 512, "retrieval_allocation": 6144, "response_reservation": 1536} | Must be a valid JSON object with total_budget and at least one allocation field. All values must be positive integers. Schema check required. |
[TRACE_ID] | Unique identifier for the production trace being analyzed | "trace_2025-01-15_14-32-07_a1b2c3" | Must be a non-empty string matching the trace ID format used by your observability platform. Regex validation against trace ID pattern required. |
Implementation Harness Notes
How to wire the context window truncation impact analysis prompt into an automated investigation workflow.
This prompt is designed to be triggered programmatically when an eval failure correlates with a context window overflow event in your trace data. The implementation harness should listen for traces where context_window.truncated == true and the final response failed a quality eval. When both conditions are met, the harness extracts the full document list, the truncated document list, the final output, and the eval rubric, then invokes this prompt to produce a structured impact analysis. Do not run this prompt on every request—it is a diagnostic tool for failure investigation, not a real-time guardrail.
Wire the prompt into an investigation queue or a retryable job runner. The harness must: (1) validate that the trace contains both pre_truncation_documents and post_truncation_documents arrays with document_id, content, and relevance_score fields; (2) confirm that the eval failure dimensions are explicitly tagged in the trace metadata; (3) call the prompt with a model that supports the full context window needed to hold the document list plus the analysis instructions—Claude 3.5 Sonnet or GPT-4o are suitable defaults; (4) parse the output against the expected JSON schema and retry once if parsing fails; (5) log the analysis result back to the trace for future correlation. For high-stakes domains such as healthcare or legal review, add a human approval step before the analysis is considered final. The token budget attribution breakdown produced by the prompt should be compared against your actual token usage logs to validate the model's self-reported allocation.
Avoid wiring this prompt directly into an automated rollback or retry loop. The output is a diagnostic artifact, not a remediation action. After the analysis is produced, route it to the prompt engineer or RAG developer responsible for the retrieval pipeline. Common next steps include adjusting the context window budget allocation, re-ranking documents with stricter relevance thresholds, or implementing a summarization step for lower-ranked evidence. If the analysis reveals that critical evidence was truncated despite a high relevance score, prioritize a retrieval pipeline fix over a prompt patch.
Expected Output Contract
Fields, format, and validation rules for the before-and-after truncation analysis output. Use this contract to validate the model response before surfacing it to an operator or feeding it into a downstream monitoring system.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
analysis_id | string (UUID v4) | Must match the request correlation ID. Parse check: valid UUID format. | |
truncation_event | object | Must contain | |
dropped_evidence | array of objects | Each object must include | |
token_budget_attribution | object | Must break down token consumption into | |
eval_dimension_impact_summary | array of objects | Each object must contain | |
root_cause_confidence | float | Value between 0.0 and 1.0 representing confidence that truncation is the primary cause of eval failure. Range check: 0.0 <= value <= 1.0. | |
alternative_hypotheses | array of strings | If present, each entry must be a non-empty string describing an alternative failure cause. Empty array allowed. Null not allowed if field present. Content check: no empty strings. | |
recommended_actions | array of objects | Each object must contain |
Common Failure Modes
Context window truncation silently removes evidence before the model can use it, causing eval failures that look like hallucination or poor reasoning. These cards cover the most common failure patterns and how to detect them.
Silent Evidence Drop
What to watch: The model produces an answer that contradicts or ignores key facts present in the original documents. The eval flags hallucination, but the root cause is that the evidence was truncated from the context window before generation. Guardrail: Always log the final token count and truncation status per source. Compare the retrieved document set against what actually fit in the context window before running the eval.
Mid-Document Cutoff
What to watch: A document is partially included, ending mid-sentence or mid-section. The model treats the fragment as complete evidence, leading to incorrect conclusions or missing critical disclaimers from the omitted portion. Guardrail: Implement a chunk-boundary-aware context packer that only includes complete sections or adds explicit truncation markers. Flag any response built from truncated documents for human review or lower confidence scoring.
Relevance Score Distortion
What to watch: The eval prompt compares the model's output against a golden answer that assumes all top-N documents were available. When high-relevance documents were dropped due to token limits, the eval score penalizes the model unfairly. Guardrail: Include a pre-eval step that checks which retrieved documents actually reached the model. Adjust eval expectations or flag the case as 'insufficient context' rather than a model failure.
Token Budget Misattribution
What to watch: System prompts, few-shot examples, or tool schemas consume a disproportionate share of the context window, leaving minimal room for evidence. The eval fails because the model had too little context to work with, not because the prompt logic was wrong. Guardrail: Produce a token budget attribution report before running evals. Set minimum token allocations for evidence and trigger an alert when evidence allocation drops below the threshold.
Ranking-Order Sensitivity
What to watch: The context packer fills the window by rank order, so a small change in retrieval scoring can push a critical document just past the cutoff. The eval result becomes sensitive to retrieval ranking noise rather than model quality. Guardrail: Run the eval with multiple context-window fill strategies. If the eval outcome flips based on which documents barely made the cut, flag the case as unstable and consider increasing the context budget or improving retrieval precision.
Cross-Turn Context Starvation
What to watch: In multi-turn conversations, prior turns, tool outputs, and conversation summaries consume the context window before new evidence is added. The model loses access to the retrieved documents needed for the current turn, and the eval fails on grounding. Guardrail: Monitor per-turn context allocation. Implement a sliding window or summarization strategy that reserves a fixed percentage of the context window for fresh evidence on each turn.
Evaluation Rubric
Criteria for testing the quality of the context window truncation analysis prompt's output before relying on it for root-cause decisions. Each row validates a specific dimension of the generated report.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Token Budget Attribution Accuracy | Sum of all line-item token counts equals the reported total context window size within a 2% margin | Sum of parts deviates from total by more than 5% or individual line items are missing token counts | Parse the output JSON, extract all token count fields, compute sum, compare against [TOTAL_TOKENS] field |
Truncated Evidence Completeness | Every document or passage that was partially or fully truncated appears in the dropped-content list with its identifier and truncation percentage | A document known to be in the retrieval set but absent from the final context is missing from the dropped-content list | Cross-reference the dropped-content list against the retrieval trace log; flag any retrieved document ID not present in either the kept or dropped sections |
Relevance Score Consistency | Each dropped passage has a relevance score between 0.0 and 1.0 and the score aligns with the original retriever ranking order | Relevance scores are missing, outside the 0-1 range, or contradict the retriever's rank order without explanation | Validate score range programmatically; compare sort order of scores against retriever rank from [RETRIEVAL_TRACE]; flag inversions |
Eval Dimension Impact Mapping | Each dropped passage is mapped to at least one eval dimension from [EVAL_RUBRIC] with a stated impact level of low, medium, or high | A dropped passage with relevance above 0.7 has no eval dimension mapping or impact level is missing | Check that every dropped passage with relevance_score > 0.7 has a non-empty eval_dimensions array and a valid impact_level enum value |
Before-and-After Eval Score Projection | The report includes a projected eval score delta for each affected dimension, expressed as a numeric change with direction | Projected score deltas are absent, are not numeric, or lack a sign indicating increase or decrease | Parse projected_score_delta fields; assert type is number; assert field is present for every dimension in affected_eval_dimensions |
Source Grounding of Truncation Claims | Every claim about what was truncated includes a reference to a specific trace event ID or context window position | Truncation claims appear without trace event references or use vague language like some documents were cut | Scan output for truncation claims; assert each claim block contains a trace_event_id or context_position field; fail if null or missing |
Actionable Remediation Suggestions | The output includes at least one concrete remediation step per high-impact truncation, specifying what to change in retrieval, ranking, or context assembly | High-impact truncations lack remediation steps or suggestions are generic like improve retrieval | Count high-impact truncations; assert remediation_steps array length >= count of high-impact items; validate each step contains a target_component field |
Output Schema Compliance | The entire response validates against the expected [OUTPUT_SCHEMA] with no missing required fields and no extra fields outside the schema | Schema validation fails due to missing required fields, type mismatches, or unexpected additional properties | Run automated JSON Schema validation using the provided [OUTPUT_SCHEMA]; fail on any validation errors |
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\nStart with the base prompt and a single trace JSON blob. Remove the token budget attribution breakdown and relevance scoring requirements. Ask only: 'What was truncated? Which eval dimensions were likely affected?'\n\n### Watch for\n- The model guessing truncation impact without trace evidence\n- Skipping the before-and-after comparison entirely\n- Overlooking silent truncation where the model didn't signal context loss

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