Use this prompt when a user reports that an AI assistant 'forgot' previously provided information, preferences, or context during a multi-turn conversation. The job-to-be-done is a structured root-cause analysis that distinguishes between three distinct failure modes: context window overflow (the information was pushed out of the model's attention window), premature summarization (a compression step discarded critical details), and state hydration failure (the application layer failed to load or correctly deserialize the saved session state). The ideal user is an AI reliability engineer, a platform SRE, or a developer on the conversational AI team who has access to raw turn-level trace data and session configuration metadata.
Prompt
Session Context Loss Root-Cause Analysis Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Session Context Loss Root-Cause Analysis Prompt.
This prompt is not a general-purpose debugging tool. Do not use it when you lack a complete trace export that includes every user message, every assistant response, every tool call, and the session state snapshots at turn boundaries. It is also inappropriate for diagnosing latency issues, token cost overruns, or safety policy violations—those require separate, specialized trace review prompts. The analysis assumes the assistant's architecture uses some form of state management, whether in-application memory, a database, or a context-carrying mechanism. If your system is stateless by design, the root cause is architectural, and this prompt will not add value.
Before running this prompt, assemble the required inputs: a full turn-level trace in a structured format (JSON or JSONL is preferred), the session's configuration metadata (context window size, summarization model and threshold, state serialization format), and the specific user report describing what context was lost and at which point in the conversation. The prompt will produce a structured root-cause report with a primary classification, supporting evidence from the trace, and a confidence score. For high-severity incidents where the context loss caused a compliance or safety issue, always route the output for human review before closing the incident. The next step after receiving the analysis is to implement the recommended remediation, which may involve adjusting summarization thresholds, increasing the context budget, or fixing state hydration logic in the application layer.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Session Context Loss Root-Cause Analysis Prompt is the right tool for your investigation.
Good Fit: Structured Trace Data Available
Use when: You have complete turn-level trace exports with timestamps, model inputs, outputs, and tool-call logs. Guardrail: The prompt requires structured trace data as input; do not use it with only user-facing chat logs or anecdotal reports.
Bad Fit: Undefined Session Boundaries
Avoid when: Session start and end points are ambiguous, or traces span multiple unrelated user intents without clear session IDs. Guardrail: Pre-process traces to segment sessions before analysis, or use a session reconstruction prompt first.
Required Input: Session Configuration Metadata
What to watch: The prompt needs context window size, summarization settings, and state hydration configuration to distinguish overflow from premature summarization. Guardrail: Collect deployment configuration metadata alongside trace data before running the analysis.
Operational Risk: False Attribution
What to watch: The prompt may attribute context loss to a single cause when multiple factors interact, such as summarization plus a tool-call failure. Guardrail: Review the output for multi-factor explanations and cross-reference with other trace analysis prompts before taking action.
Operational Risk: Trace Data Gaps
What to watch: Missing intermediate tool outputs, redacted PII, or truncated logs can lead to incomplete root-cause analysis. Guardrail: Validate trace completeness before analysis; flag gaps in the prompt input so the model can express uncertainty rather than fabricate causes.
Good Fit: Reproducible Context Loss Patterns
Use when: You have multiple sessions exhibiting the same context loss symptoms and need a systematic root-cause breakdown. Guardrail: Run the prompt on individual sessions first, then aggregate findings; do not batch unrelated sessions into a single analysis.
Copy-Ready Prompt Template
A reusable prompt with square-bracket placeholders for conducting a structured root-cause analysis of session context loss from production trace data.
The prompt below is designed to be copied directly into your AI harness, observability pipeline, or internal debugging tool. It accepts a raw multi-turn trace and session configuration metadata, then produces a structured root-cause analysis report. Every placeholder is enclosed in square brackets and must be replaced with real data before execution. The prompt forces the model to distinguish between three primary failure modes—context window overflow, premature summarization, and state hydration failure—rather than allowing a vague 'the assistant forgot' explanation.
textYou are an AI reliability engineer reviewing a production conversation trace where a user reported that the assistant lost context. Your job is to produce a structured root-cause analysis that identifies the exact failure mechanism, the turn where context was lost, and the evidence supporting your conclusion. ## INPUTS ### Conversation Trace [FULL_MULTI_TURN_TRACE] ### Session Configuration - Max context window tokens: [MAX_CONTEXT_WINDOW_TOKENS] - Summarization trigger threshold tokens: [SUMMARIZATION_THRESHOLD_TOKENS] - Summarization model or method: [SUMMARIZATION_METHOD] - State hydration mechanism: [STATE_HYDRATION_MECHANISM] - Session start timestamp: [SESSION_START_TIME] ### User Report [USER_REPORT_OF_CONTEXT_LOSS] ## ANALYSIS INSTRUCTIONS 1. Parse the full trace into individual turns, labeling each with turn number, role, token count, and a one-line summary of content. 2. Identify the earliest turn where the assistant's response demonstrates loss of previously established context. Cite the specific user utterance that was forgotten and the assistant response that reveals the loss. 3. Classify the root cause into exactly one of the following categories: - **Context Window Overflow**: The forgotten context was pushed out of the context window by newer turns. Provide the token count at the turn where overflow occurred and confirm that the forgotten context fell outside the window. - **Premature Summarization**: A summarization step compressed or omitted the critical context before it was needed. Identify the summarization event, the summary content, and what was lost. - **State Hydration Failure**: The assistant's session state was not correctly loaded, deserialized, or applied at a turn boundary. Identify the turn where state was expected to be present but was missing or corrupted. - **Other**: A different failure mode not listed above. Describe the mechanism with equal specificity. 4. For the identified root cause, provide: - The exact turn number where context loss occurred. - The specific context that was lost. - The downstream impact: which subsequent turns were affected and how. - A confidence score from 0.0 to 1.0. 5. If the evidence is ambiguous between two categories, list the alternative hypothesis and explain why it was not selected. 6. Recommend one actionable fix, such as increasing context window, adjusting summarization thresholds, adding state validation on hydration, or instrumenting additional logging. ## OUTPUT SCHEMA Return a JSON object with this exact structure: { "trace_summary": { "total_turns": <integer>, "total_tokens_consumed": <integer>, "session_duration_seconds": <integer> }, "context_loss_event": { "turn_number": <integer>, "lost_context": "<string describing what was forgotten>", "assistant_response_showing_loss": "<verbatim excerpt>", "root_cause_category": "context_window_overflow | premature_summarization | state_hydration_failure | other", "root_cause_description": "<detailed explanation>", "confidence": <float 0.0-1.0> }, "alternative_hypothesis": { "category": "<string or null>", "explanation": "<string or null>" }, "downstream_impact": { "affected_turns": [<list of turn numbers>], "impact_description": "<string>" }, "recommended_fix": "<actionable recommendation>" } ## CONSTRAINTS - Do not speculate beyond the evidence in the trace. - If token counts are not provided in the trace, estimate them conservatively and note that estimates were used. - If the trace is incomplete, flag what is missing and reduce confidence accordingly. - Do not fabricate turn content. Quote verbatim from the trace. - If no context loss is detected, set root_cause_category to "none_detected" and explain why the user may have perceived a loss.
To adapt this prompt for your environment, replace each square-bracket placeholder with real data from your tracing system. The [FULL_MULTI_TURN_TRACE] should include raw turn data with role labels, timestamps, and token counts if available. If your tracing system does not capture token counts per turn, modify the prompt to instruct the model to estimate from character counts, but always flag that estimates were used. The output schema is strict JSON to enable automated ingestion into your incident management pipeline. Before deploying, test this prompt against at least three known context-loss incidents and one negative case where no loss occurred to calibrate the confidence scoring and verify that the model does not hallucinate loss events.
Prompt Variables
Required inputs for the Session Context Loss Root-Cause Analysis Prompt. Each variable must be populated from production trace data and session metadata before the prompt is assembled. Missing or malformed inputs will cause the analysis to fail or produce unreliable conclusions.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[TURN_TRACE_JSON] | Full turn-by-turn trace export including user utterances, assistant responses, tool calls, retrieved context, and internal state snapshots for every turn in the session | {"session_id": "sess_abc123", "turns": [{"turn_id": 1, "user_utterance": "...", "assistant_response": "...", "retrieved_context": [...], "tool_calls": [...], "state_snapshot": {...}}]} | Must be valid JSON with a turns array containing at least 2 turns. Each turn object must include turn_id, user_utterance, and assistant_response fields. Null or empty turns array triggers a schema rejection before prompt execution. |
[SESSION_CONFIG] | Session-level configuration metadata including context window size, summarization settings, state hydration strategy, and memory retention policy active during the session | {"context_window_tokens": 128000, "summarization_strategy": "progressive", "summarization_trigger_threshold_pct": 80, "state_hydration_method": "full_serialize", "memory_retention_policy": "session_only"} | Must include context_window_tokens as integer and summarization_strategy as non-empty string. If summarization is disabled, set summarization_strategy to "none". Missing fields cause the root-cause analysis to skip entire diagnostic branches. |
[REPORTED_ISSUE] | User-reported description of what context was lost, when it occurred, and what the expected behavior should have been | "The assistant forgot my dietary restrictions from earlier in the conversation when I asked for restaurant recommendations at turn 7" | Must be a non-empty string with a clear description of the lost context and a reference to at least one turn number or approximate position in the conversation. Vague reports like "it forgot things" should be rejected with a request for clarification before analysis proceeds. |
[EXPECTED_CONTEXT] | Specific facts, preferences, entities, or constraints that the user expected the assistant to retain across turns | ["dietary_restriction: vegan", "cuisine_preference: italian", "budget_level: moderate"] | Must be a non-empty array of strings or key-value pairs. Each entry should name a discrete piece of context. If the user cannot specify what was lost, set to null and the prompt will attempt to infer expected context from early turns, but analysis confidence will be reduced. |
[CONTEXT_WINDOW_SNAPSHOT] | Snapshot of what was actually inside the model's context window at each turn boundary, including token counts and content summaries | {"turn_3": {"token_count": 45000, "content_summary": "User dietary preferences, cuisine history, location context"}, "turn_7": {"token_count": 112000, "content_summary": "Recent restaurant suggestions, location details, booking options"}} | Must be a JSON object keyed by turn_id with token_count as integer and content_summary as string. If context window snapshots are not available in the trace system, set to null and the prompt will rely on inference from turn data, but overflow diagnosis will be less precise. |
[SUMMARIZATION_LOG] | Log of any automatic summarization events that occurred during the session, including trigger reason, pre-summary token count, and the generated summary text | [{"turn": 5, "trigger": "threshold_80pct", "pre_summary_tokens": 102000, "summary_text": "User is vegan, prefers Italian cuisine, moderate budget, located in downtown area"}] | Must be an array of objects, each with turn, trigger, pre_summary_tokens, and summary_text fields. If no summarization occurred, set to empty array []. Missing summary_text for a logged event is a data quality failure that should block analysis. |
[STATE_HYDRATION_LOG] | Record of state serialization and deserialization events at turn boundaries, including expected state fields and actual loaded fields | {"turn_4": {"expected_fields": ["dietary_restrictions", "cuisine_preference", "budget", "location"], "loaded_fields": ["cuisine_preference", "budget", "location"], "missing_fields": ["dietary_restrictions"]}} | Must be a JSON object keyed by turn_id with expected_fields, loaded_fields, and missing_fields arrays. If state hydration logging is not enabled, set to null and the prompt will flag state hydration failure as unverifiable rather than ruled out. |
Implementation Harness Notes
How to wire the Session Context Loss Root-Cause Analysis Prompt into an observability pipeline or manual review workflow.
This prompt is designed to be invoked programmatically as part of an automated incident response or a manual QA review queue. The primary integration point is a trace ingestion service that fetches turn-level data and session configuration metadata from your observability platform (e.g., LangSmith, Arize, or a custom trace store). Before calling the LLM, the harness must validate that the [TRACE_DATA] payload contains the minimum required fields: a unique session_id, a list of turns with role, content, and timestamp, and a session_config object that includes context_window_limit and summarization_strategy. If these fields are missing, the harness should reject the request immediately and log a MISSING_TRACE_SCHEMA error rather than sending incomplete data to the model.
The harness should implement a two-stage validation pipeline. First, a structural validator checks that the input JSON conforms to the expected schema and that timestamps are monotonically increasing. Second, a content sanity checker verifies that the trace contains at least one user turn and that the session duration is plausible (e.g., not spanning negative time). After the LLM returns its root-cause classification and evidence, a post-processing validator must confirm that the output contains the required fields: root_cause_category (one of context_window_overflow, premature_summarization, state_hydration_failure, or other), confidence_score (0.0–1.0), evidence_turns (an array of turn indices), and diagnosis_rationale. If the model output fails this validation, the harness should retry once with a stricter output format instruction appended to the prompt. If the retry also fails, the trace should be routed to a human review queue with the raw model output attached.
For model selection, use a model with strong structured output capabilities and a context window large enough to hold the full trace plus the analysis instructions. GPT-4o or Claude 3.5 Sonnet are appropriate defaults. Set temperature to 0.0 to maximize reproducibility, and enable JSON mode or structured outputs if the provider supports it. The harness should log every invocation—including the prompt version, model, input trace ID, output classification, confidence score, and latency—to a dedicated analysis log table. This log becomes the audit trail for root-cause trends and model performance over time. Avoid using this prompt on traces that contain PII unless the data has been redacted upstream; the harness should check for common PII patterns and either reject or sanitize before sending.
Expected Output Contract
Defines the required fields, types, and validation rules for the root-cause analysis report. Use this contract to parse, validate, and store the model's output before surfacing it in a dashboard or incident ticket.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
root_cause_category | enum string | Must be one of: 'context_window_overflow', 'premature_summarization', 'state_hydration_failure', 'other'. Reject any other value. | |
confidence_score | float | Must be a number between 0.0 and 1.0 inclusive. Parse as float and check bounds. | |
evidence_turns | array of integers | Must be a non-empty array. Each element must be a positive integer corresponding to a turn index in the input trace. Validate against [TRACE_TURN_COUNT]. | |
lost_context_summary | string | Must be a non-empty string between 10 and 500 characters. Log a warning if length exceeds 500; truncation may have occurred. | |
failure_turn_index | integer or null | If root_cause_category is not 'other', must be a positive integer. If 'other', must be null. Validate conditional logic. | |
contributing_factors | array of strings | Must be an array with 1-5 items. Each item must be a non-empty string. Reject if array is empty or contains empty strings. | |
recommended_action | string | Must be a non-empty string. If root_cause_category is 'context_window_overflow', action must mention truncation or context management. Validate with keyword check. | |
requires_human_review | boolean | Must be true if confidence_score < 0.7 or root_cause_category is 'other'. Validate with boolean logic check. |
Common Failure Modes
Session context loss investigations fail when the analysis prompt cannot isolate root causes from noisy trace data. These failure modes target the most common breakdowns in root-cause analysis for forgotten user context.
Blames Context Window Without Evidence
What to watch: The analysis defaults to 'context overflow' without checking actual token counts, truncation markers, or summarization events. This masks the real failure. Guardrail: Require the prompt to output exact token counts at each turn boundary, the position of the lost context, and explicit evidence of truncation before accepting overflow as the cause.
Confuses Summarization Loss with Hydration Failure
What to watch: The analysis attributes lost context to a bad summary when the summary was correct but the state object failed to load or deserialize on the next turn. Guardrail: Add a step that compares the generated summary against the state object actually loaded by the assistant. Flag mismatches where the summary was accurate but the loaded state was stale or empty.
Misses Silent State Overwrites
What to watch: A tool call or background process overwrites session state without logging the change, making the context loss invisible in standard traces. Guardrail: Include a state-diff step that compares the state object before and after every tool call, not just at turn boundaries. Flag any field that changed without an explicit user or system instruction.
Treats User Correction as Context Loss
What to watch: The user explicitly changed their request, but the analysis flags it as 'forgotten context' because the assistant stopped referencing earlier details. Guardrail: Add a user-intent-change detection step before root-cause classification. If the user issued a correction or goal change, exclude those turns from context-loss scoring and label them as intentional shifts.
Fails on Partial Trace Data
What to watch: The analysis produces confident conclusions when critical trace fields are missing, such as state snapshots, tool-call responses, or summarization metadata. Guardrail: Require the prompt to output a data-completeness assessment first. If required fields are absent, the output must downgrade confidence and list what data is needed for a definitive diagnosis.
Propagates Hallucinated Timeline Events
What to watch: The analysis invents turn events, state changes, or user actions that do not appear in the trace, creating a false narrative of what happened. Guardrail: Require every causal claim in the output to cite a specific trace line number or event ID. Add a self-verification step that checks each cited event against the raw trace before finalizing the report.
Evaluation Rubric
Use this rubric to test the root-cause analysis output before integrating it into an automated monitoring pipeline or incident review workflow. Each criterion targets a specific failure mode of the analysis prompt.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Root-Cause Classification | Output selects exactly one primary cause from the allowed set: context_window_overflow, premature_summarization, or state_hydration_failure | Output proposes a cause not in the allowed set, selects multiple primary causes, or returns a generic label like 'unknown_error' | Parse the [ROOT_CAUSE] field and validate against the allowed enum. Fail if value is missing, null, or out of set. |
Evidence Turn Citation | Each causal claim references at least one specific turn ID from the [TRACE_DATA] where the failure event is observable | Causal claims lack turn references, cite turns outside the provided trace, or use vague language like 'earlier in the conversation' without an ID | Extract all turn ID references from the [EVIDENCE_LOG] section. Cross-reference against the turn IDs present in the input trace. Fail if any claim has zero valid references. |
Context Window Overflow Diagnosis | When root cause is context_window_overflow, output includes the estimated token count at the failure turn and identifies the specific content that was truncated | Output claims overflow without providing an estimated token count, or fails to identify which content was dropped from the context window | For overflow cases, assert that [TOKEN_COUNT_AT_FAILURE] is a positive integer and that [TRUNCATED_CONTENT] is a non-empty string referencing specific messages or passages. |
Premature Summarization Diagnosis | When root cause is premature_summarization, output identifies the turn where summarization occurred and the critical information that was lost or distorted in the summary | Output claims summarization caused the loss but cannot pinpoint the summarization turn or cannot name the specific fact that was dropped | For summarization cases, assert that [SUMMARIZATION_TURN_ID] matches a turn in the trace and that [LOST_INFORMATION] contains at least one concrete fact present in the pre-summary turns but absent from the summary. |
State Hydration Failure Diagnosis | When root cause is state_hydration_failure, output identifies the expected state field, its expected value from prior turns, and the actual null or incorrect value loaded | Output claims hydration failure but only describes symptoms without naming the specific state field and the expected-vs-actual mismatch | For hydration cases, assert that [FAILED_STATE_FIELD] is a non-empty string, [EXPECTED_VALUE] is not null, and [ACTUAL_VALUE] is explicitly null or a mismatched value. Fail if any of these fields are missing. |
Confidence Calibration | Output includes a confidence score between 0.0 and 1.0, and the score is below 0.7 when evidence is ambiguous or multiple causes are plausible | Confidence score is always 0.9 or higher regardless of evidence quality, or score is missing entirely | Parse [CONFIDENCE_SCORE] as a float. Fail if score is outside 0.0-1.0 range. Flag for human review if score is above 0.85 but the [EVIDENCE_LOG] contains fewer than two distinct supporting observations. |
Alternative Cause Acknowledgment | Output lists at least one alternative cause that was considered and explains why it was ruled out, using trace evidence | Output presents the primary cause as the only possibility without discussing alternatives, or dismisses alternatives without trace evidence | Assert that [ALTERNATIVE_CAUSES] array is non-empty and that each entry includes both a cause label and a [REJECTION_REASON] field referencing specific trace data. |
Actionable Remediation | Output includes at least one concrete remediation step tied to the diagnosed root cause, referencing a specific configuration parameter, code path, or prompt component | Remediation is generic advice like 'improve context management' without naming a specific parameter, threshold, or component to change | Validate that [REMEDIATION_STEPS] array is non-empty and that each step includes a [TARGET_COMPONENT] field matching a known system element from the [SESSION_CONFIG] metadata. |
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
Use the base prompt with a single representative trace and lighter validation. Focus on getting a readable root-cause narrative before adding strict schema checks. Replace [TRACE_DATA] with a raw JSON export of turn events and [SESSION_CONFIG] with a simple context-window size and summarization flag.
Watch for
- The model may produce plausible-sounding but incorrect root causes when evidence is thin
- Missing schema checks mean the output format will drift across runs
- Overly broad instructions can produce a generic analysis that doesn't isolate the specific failure turn

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