Inferensys

Prompt

Context Window Truncation and Hallucination Correlation Prompt

A practical prompt playbook for using Context Window Truncation and Hallucination Correlation 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

Defines the precise conditions, required inputs, and inappropriate use cases for the context window truncation and hallucination correlation prompt.

This prompt is designed for infrastructure and RAG engineers who have already confirmed a hallucination in a production output and suspect the root cause is context window truncation. The job-to-be-done is correlating specific truncated passages with specific hallucinated claims to produce a structured, evidence-backed report. The ideal user has access to a trace system that records the full retrieved context, the truncated context actually passed to the model, and the final generated output. Without this complete trace data, the prompt cannot perform a meaningful correlation and will produce unreliable results.

To use this prompt effectively, you must provide a single trace object containing three distinct data structures: the full list of retrieved documents before truncation, the subset of those documents that fit within the model's context window, and the final generated output containing the hallucinated claim. The prompt's instructions force the model to operate as a forensic analyst, not a general-purpose assistant. It requires the model to cite specific truncated passage IDs and map them to specific hallucinated claims using a structured output schema. This constraint prevents the model from offering vague speculation about why a hallucination occurred and instead demands traceable, auditable evidence. For high-stakes domains, the output should be reviewed by a human before any remediation is applied to the retrieval or chunking pipeline.

Do not use this prompt for real-time guardrails, as it is designed for post-hoc forensic analysis and is not optimized for latency. Do not use it when the hallucination cause is clearly a retrieval failure where relevant documents were never fetched, a source conflict where two retrieved documents contradict each other, or a prompt instruction leakage where the system prompt overrode the evidence. In those cases, use the sibling prompts for retrieval failure analysis, source conflict resolution, or instruction leakage detection. After running this prompt, the next step is typically to adjust your chunking strategy, context window budget, or reranking logic based on the specific truncated passages identified in the correlation report.

PRACTICAL GUARDRAILS

Use Case Fit

This prompt is designed for infrastructure and RAG engineers diagnosing production hallucinations caused by context window limits. It is not a general-purpose hallucination checker.

01

Good Fit: Post-Mortem of Truncation-Induced Hallucinations

Use when: A production trace shows the model received a truncated context window and the output contains a factual error. Guardrail: Run this prompt only on traces where you have already confirmed truncation occurred via token-count metadata in the trace.

02

Bad Fit: Real-Time Guardrails or Streaming

Avoid when: You need to block a hallucination before it reaches the user. Risk: This prompt performs a deep, multi-step correlation analysis that is too slow and token-intensive for inline safety checks. Guardrail: Use this offline for root-cause analysis and feed findings back into your retrieval or chunking strategy.

03

Required Inputs: Full Trace with Token Metadata

What to watch: The prompt will fail or produce low-confidence results if it only receives the final output. Guardrail: Ensure the input includes the final generated text, the full list of retrieved chunks, and the truncated status with token_count for each chunk from your observability platform.

04

Operational Risk: Blaming the Wrong Root Cause

What to watch: A hallucination might correlate with a truncated passage by coincidence, while the true cause is a conflicting source or model bias. Guardrail: Treat the output as a correlation hypothesis, not a final verdict. Always cross-reference with a Source Conflict Resolution Trace Review before changing the chunking strategy.

05

Operational Risk: High Token Consumption

What to watch: Analyzing a large trace with hundreds of chunks can consume significant context window space in the analysis model. Guardrail: Pre-filter the trace to include only chunks that were truncated and the specific claims flagged as hallucinations. Do not send the entire raw trace.

06

Bad Fit: Non-RAG or Black-Box Models

Avoid when: The model had no access to retrieved context, or the trace does not capture retrieval events. Risk: The prompt assumes a RAG architecture with observable retrieval and truncation events. Guardrail: Only apply this to systems where you control or can observe the context assembly pipeline.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for correlating context window truncation events with hallucinated claims in production traces.

This prompt template is designed to be pasted directly into your trace analysis tool, evaluation pipeline, or LLM workbench. It instructs the model to act as a diagnostic auditor, comparing the full retrieved context against the truncated context that actually fit in the window, then mapping each hallucinated claim to the specific evidence that was lost during truncation. The output is a structured correlation report that infrastructure and RAG engineers can use to adjust chunking strategies, re-rankers, or context budgets.

text
You are a trace diagnostic auditor specializing in RAG systems. Your task is to analyze a production trace where context window truncation occurred and determine whether the truncation caused specific hallucinations in the model's output.

## INPUTS
- Full Retrieved Context: [FULL_RETRIEVED_CONTEXT]
- Truncated Context (what actually fit in the window): [TRUNCATED_CONTEXT]
- Generated Output: [GENERATED_OUTPUT]
- Ground Truth or Expected Claims (optional): [GROUND_TRUTH_CLAIMS]

## INSTRUCTIONS
1. Extract every factual claim from the Generated Output. Number them sequentially.
2. For each claim, check whether it is supported by the Truncated Context. Mark as SUPPORTED, UNSUPPORTED, or PARTIALLY_SUPPORTED.
3. For every UNSUPPORTED or PARTIALLY_SUPPORTED claim, search the Full Retrieved Context for evidence that was lost during truncation.
4. If lost evidence is found, record the exact passage that was truncated and explain how it would have supported or corrected the claim.
5. If no evidence exists in either context, classify the claim as a MODEL-GENERATED HALLUCINATION (no grounding available).
6. Identify any claims that appear in the Truncated Context but were contradicted by truncated evidence in the Full Retrieved Context. Flag these as TRUNCATION-INDUCED CONTRADICTIONS.

## OUTPUT SCHEMA
Return a JSON object with this structure:
{
  "trace_summary": {
    "total_claims_extracted": <int>,
    "supported_by_truncated_context": <int>,
    "unsupported_claims_total": <int>,
    "truncation_correlated_hallucinations": <int>,
    "model_generated_hallucinations_no_grounding": <int>,
    "truncation_induced_contradictions": <int>
  },
  "claims_analysis": [
    {
      "claim_id": <int>,
      "claim_text": "<string>",
      "truncated_context_status": "SUPPORTED | UNSUPPORTED | PARTIALLY_SUPPORTED",
      "lost_evidence_found": <bool>,
      "lost_evidence_passage": "<string or null>",
      "lost_evidence_position": "<string or null, e.g., 'document_3_paragraph_5'>",
      "correlation_explanation": "<string>",
      "hallucination_category": "TRUNCATION-CORRELATED | MODEL-GENERATED | TRUNCATION-INDUCED-CONTRADICTION | NONE"
    }
  ],
  "truncation_impact_assessment": {
    "severity": "CRITICAL | HIGH | MEDIUM | LOW | NONE",
    "summary": "<string>",
    "recommended_actions": ["<string>"]
  }
}

## CONSTRAINTS
- Do not invent evidence. If a passage is not in the provided contexts, do not claim it exists.
- If the Ground Truth Claims are provided, use them to validate your analysis but do not treat them as retrieved context.
- Flag any claims where the Truncated Context appears to support the claim but the Full Retrieved Context reveals the support was misleading or incomplete.
- If the Generated Output contains no hallucinations, return an empty claims_analysis array and set severity to NONE.

To adapt this template for your environment, replace the square-bracket placeholders with data extracted from your trace store. The FULL_RETRIEVED_CONTEXT should include every document or chunk returned by your retrieval pipeline before truncation, while TRUNCATED_CONTEXT should contain only what survived your context window budget. If you use a re-ranker, the truncated context should reflect post-ranking order. For automated pipelines, wire this prompt into a batch evaluation job that runs nightly against sampled production traces, and route any CRITICAL severity findings to an incident channel. Always include a human review step before acting on HIGH or CRITICAL assessments, as the correlation analysis itself can contain errors.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Context Window Truncation and Hallucination Correlation Prompt. Each variable must be populated from production trace data before the prompt is executed.

PlaceholderPurposeExampleValidation Notes

[TRACE_LOG]

Full production trace containing retrieval events, context window snapshots, truncation markers, and final generated output

{"trace_id": "abc123", "events": [...]}

Must be valid JSON with trace_id, events array, and at least one retrieval event and one generation event. Reject if events array is empty or missing.

[TRUNCATION_EVENTS]

Array of trace events where context window limits forced passage removal or truncation

[{"event_id": "evt_45", "truncated_passage_id": "doc_12", "truncation_reason": "token_limit"}]

Must contain at least one truncation event with event_id, truncated_passage_id, and truncation_reason fields. Reject if array is empty when [HALLUCINATION_CLAIMS] is non-empty.

[HALLUCINATION_CLAIMS]

Pre-extracted list of hallucinated claims from the output, each with claim text and severity classification

[{"claim_id": "c1", "claim_text": "Revenue grew 40%", "severity": "major"}]

Must be a non-empty array of claim objects with claim_id, claim_text, and severity fields. Severity must be one of: critical, major, minor, stylistic. Reject if claims are not pre-extracted before running this prompt.

[RETRIEVED_CONTEXT]

Full text of all retrieved passages present in the context window before truncation occurred

[{"passage_id": "doc_12", "content": "Revenue increased by 12% year-over-year..."}]

Must include passage_id and content for every passage referenced in [TRUNCATION_EVENTS]. Content field must be non-empty string. Reject if passage_id in truncation events has no matching entry here.

[OUTPUT_SCHEMA]

Expected JSON schema for the correlation report output

{"type": "object", "properties": {"correlations": [...]}}

Must be a valid JSON Schema object. Reject if schema does not include required correlations array with claim_id, truncated_passage_id, and correlation_strength fields.

[CONFIDENCE_THRESHOLD]

Minimum confidence score for reporting a correlation between a truncated passage and a hallucinated claim

0.7

Must be a float between 0.0 and 1.0. Values below 0.5 produce noisy correlations. Reject if non-numeric or outside range. Default to 0.7 if not specified.

[MAX_CORRELATIONS_PER_CLAIM]

Maximum number of truncated passages to correlate with each hallucinated claim to keep output focused

3

Must be a positive integer. Values above 10 risk diluting the report. Reject if zero, negative, or non-integer. Default to 3 if not specified.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Context Window Truncation and Hallucination Correlation Prompt into a production observability pipeline.

This prompt is designed to be run as a post-hoc analysis step, not as a real-time guardrail. It should be triggered by an observability pipeline after a trace has been fully recorded and a hallucination has been flagged by an upstream evaluator or user report. The harness must assemble the full trace payload—including the final generated output, the list of retrieved chunks with their order and metadata, and the model's context window limit at the time of the request—before invoking the prompt. The prompt's primary value is in correlating specific truncated passages with specific unsupported claims, so the harness must preserve the exact truncation boundary: which chunks were included, which were dropped, and the token counts at the point of eviction.

Wire the prompt into a batch analysis job that listens for hallucination_detected events from your eval system. For each event, fetch the corresponding trace from your observability store (e.g., LangSmith, Arize, or a custom trace database). Construct the [TRACE_DATA] input as a structured JSON object containing three arrays: retrieved_chunks (with chunk_id, content, token_count, and included_in_context boolean), generated_claims (extracted by a prior claim extraction step), and truncation_events (marking where the context window limit forced eviction). The harness should validate that included_in_context is false for at least one chunk before running the prompt; if no truncation occurred, skip the analysis and log a no_truncation status. Use a model with a large context window (e.g., Claude 3.5 Sonnet or GPT-4o) to ensure the prompt itself can ingest the full trace without secondary truncation. Set temperature=0 and enforce structured output using the [OUTPUT_SCHEMA] defined in the prompt template—a JSON array of correlation objects, each linking a truncated chunk ID to a generated claim ID with a correlation_strength score and rationale.

After the prompt returns, validate the output against the input trace: every truncated_chunk_id must reference a chunk where included_in_context is false, and every generated_claim_id must exist in the input claims array. Discard correlations with correlation_strength below a configurable threshold (start at 0.7) and log them as weak_correlation_discarded for later review. For high-severity hallucinations—those flagged as critical or major by your severity classifier—route the correlation report to a human review queue before accepting it as a root-cause finding. Store the validated correlation report back into your trace store, linked to the original trace ID, so that future incident reviews can surface the truncation-to-hallucination chain without re-running the analysis. Avoid running this prompt on every request; it is expensive in both tokens and latency, and should be reserved for diagnosed hallucinations where context window pressure is a plausible contributing factor.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, types, and validation rules for the correlation report. Use this contract to parse, validate, and store the model output before surfacing it in a dashboard or alert.

Field or ElementType or FormatRequiredValidation Rule

correlation_id

string (UUID v4)

Must match regex ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$

trace_id

string

Must match the input trace identifier exactly; reject if missing or mismatched

truncation_events

array of objects

Array length must be >= 1; each object must contain 'passage_id', 'truncation_point', and 'estimated_tokens_lost' fields

truncation_events[].passage_id

string

Must reference a valid passage ID present in the input trace; reject unknown IDs

truncation_events[].truncation_point

string (ISO 8601 offset)

Must parse as valid ISO 8601 with character offset; reject if offset exceeds passage length

truncation_events[].estimated_tokens_lost

integer

Must be >= 1; warn if > 1000 without explicit justification in notes

hallucinated_claims

array of objects

Array length must be >= 1; each object must contain 'claim_text', 'severity', and 'linked_truncation_event_index'

hallucinated_claims[].claim_text

string

Must be non-empty; must not exactly match any retrieved passage text (exact match suggests citation failure, not hallucination)

hallucinated_claims[].severity

string (enum)

Must be one of: 'critical', 'major', 'minor'; reject any other value

hallucinated_claims[].linked_truncation_event_index

integer

Must be a valid index into the truncation_events array (0-based); reject out-of-range indices

correlation_strength

string (enum)

Must be one of: 'direct', 'probable', 'speculative'; reject any other value

evidence_summary

string

Must be 50-500 characters; reject if shorter than 50 or longer than 500

recommended_action

string (enum)

Must be one of: 'increase_context_window', 'reorder_passages', 'summarize_before_truncation', 'flag_for_human_review'; reject unknown actions

confidence_score

number (float 0.0-1.0)

Must be between 0.0 and 1.0 inclusive; warn if below 0.5 and correlation_strength is 'direct'

generated_at

string (ISO 8601 datetime UTC)

Must parse as valid ISO 8601 in UTC; reject non-UTC timezone offsets

PRACTICAL GUARDRAILS

Common Failure Modes

Context window truncation silently removes evidence before the model generates a response. These failure modes explain what breaks when truncation occurs and how to detect the correlation between missing context and hallucinated claims.

01

Silent Evidence Loss Before Generation

What to watch: The context window limit forces truncation of retrieved passages before the model ever sees them. The model generates an answer as if the evidence exists, but critical facts were dropped during context assembly. Guardrail: Log the token count and truncation boundary for every request. Compare the set of retrieved document IDs against the set of document IDs actually present in the assembled prompt to detect dropped sources.

02

Hallucination Spikes at Truncation Boundaries

What to watch: Claims that appear in the output but have no supporting passage in the trace often correlate with passages that were retrieved but truncated. The model fills the gap with plausible-sounding fabrication. Guardrail: For each unsupported claim, search the pre-truncation retrieval set for passages that were dropped. Flag any claim where a dropped passage contains related entities or topics as a high-probability truncation-induced hallucination.

03

Mid-Document Truncation Produces Partial Facts

What to watch: When a long document is split across the context window boundary, the model sees only the first portion. It may generate claims based on incomplete information, producing statements that are partially true but misleading. Guardrail: Mark any retrieved document that spans the truncation boundary as partially visible. Require the model to qualify claims from partially visible documents or abstain from using them entirely.

04

Ranking Position Masks Truncation Impact

What to watch: Retrieval rankers place the most relevant passages first, so truncation disproportionately drops lower-ranked but still-important evidence. The model over-relies on top-ranked passages and misses contradictory or qualifying information that was truncated. Guardrail: Run a post-hoc check comparing claims against the full retrieval set, not just the context-window subset. Flag claims contradicted by truncated passages as ranking-truncation interaction failures.

05

Token Budget Competition Between Components

What to watch: System prompts, few-shot examples, tool definitions, and conversation history all consume tokens from the same window. When these components grow, less room remains for retrieved evidence, increasing hallucination risk even if retrieval quality is unchanged. Guardrail: Monitor the token allocation breakdown per request. Set a minimum token reservation for retrieved context and alert when other components exceed their budget, forcing evidence truncation.

06

Truncation-Induced Overconfidence

What to watch: When evidence is truncated, the model loses signals that would have triggered uncertainty or abstention. It generates confident-sounding answers because it never saw the conflicting or insufficient evidence that was dropped. Guardrail: Compare the model's confidence signals against the completeness of the context window. When a high percentage of retrieved passages were truncated, inject an explicit instruction to express lower confidence or acknowledge limited visibility.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the correlation report generated by the Context Window Truncation and Hallucination Correlation Prompt. Each criterion should be scored before the report is considered actionable for engineering follow-up.

CriterionPass StandardFailure SignalTest Method

Truncation Identification

Every truncated passage in the trace is identified with its start and end token offsets

Missing truncated passages or offsets that do not match trace metadata

Parse trace for truncation markers; compare count and offsets against report output

Claim-to-Passage Mapping

Each hallucinated claim is mapped to at least one truncated passage with a confidence score

Hallucinated claims listed without any truncated passage mapping or with null confidence scores

Extract claim-passage pairs; verify each claim has a non-null passage reference and score in [0,1]

Correlation Strength Classification

Each correlation is classified as direct, partial, or speculative with explicit rationale

All correlations labeled direct without differentiation or rationale field is empty

Check classification field values against allowed enum; verify rationale field is non-empty for each correlation

Trace Event Referencing

Every correlation includes a trace event ID or span ID pointing to the truncation event

Trace event IDs are missing, malformed, or do not match any event in the source trace

Validate each trace event ID against the source trace event list; flag unmatched IDs

False Positive Flagging

Report explicitly flags truncated passages that did NOT correlate with any hallucination

No false-positive section present or section contains only correlated passages

Check for dedicated false-positive section; verify it contains passages absent from correlation list

Severity Classification

Each hallucination is classified by severity (critical, major, minor) with trace-grounded justification

All hallucinations classified as minor or severity justification references output text instead of trace evidence

Validate severity values against allowed enum; check that justification references trace spans, not generated output

Remediation Recommendation

Each correlation includes a specific remediation action tied to the failure mechanism

Recommendations are generic (e.g., increase context window) without per-failure specificity

Check that each correlation has a unique remediation field; verify at least two distinct remediation types across the report

Report Completeness

Report covers all trace sessions in the input batch without gaps or skipped sessions

Some trace sessions in the input batch produce no report section or are silently omitted

Count input trace sessions; verify report contains a section for each; flag missing sessions

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a small trace sample (5-10 traces) and lighter validation. Replace [TRACE_BATCH] with a single JSONL file. Set [CORRELATION_THRESHOLD] to a high value (e.g., 0.8) to surface only the strongest truncation-hallucination links. Skip the statistical significance section by removing [INCLUDE_CONFIDENCE_INTERVALS].

Watch for

  • Small sample sizes producing false correlations
  • Missing trace fields causing silent extraction failures
  • Overly broad [HALLUCINATION_DEFINITION] catching stylistic variation as hallucination
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.