Use the Sliding Window Summary Prompt when you are building a conversational AI application that must maintain coherent state across long, multi-turn sessions that exceed the model's context window. The primary job-to-be-done is preserving critical conversational state—decisions, user preferences, unresolved action items, and key facts—while safely evicting older, less relevant turns. This prompt is designed for AI engineers and application developers who are implementing the memory layer of a chat copilot, support agent, or long-running assistant, not for one-shot Q&A or short sessions that fit comfortably within the context limit.
Prompt
Sliding Window Summary Prompt for Chat History

When to Use This Prompt
Define when the sliding window summary prompt solves a real problem and when it introduces unacceptable risk.
This prompt is appropriate when the cost of losing conversational context is high. Concrete scenarios include a customer support session spanning dozens of turns where an agent must remember a reported serial number and troubleshooting steps already taken, a coding assistant that needs to recall architectural decisions made earlier in a session, or a research assistant synthesizing findings over a multi-hour collaboration. The prompt template requires you to supply the current summary, the oldest turns to be evicted, and a schema for what must be preserved. You should wire this into your application's state management layer so the summary is updated and persisted after each sliding window operation, not regenerated from scratch on every turn.
Do not use this prompt when the conversation is short enough to fit entirely within the context window, as the summarization step adds latency and a non-zero risk of fact distortion. Avoid it in high-stakes domains—such as clinical handoffs or legal proceedings—where a summary artifact could be mistaken for a complete record; in these cases, a full transcript with human review is required. Also avoid using this prompt as a substitute for a proper long-term memory or personalization system. The sliding window summary is a context management technique for a single session, not a user profile store. Before deploying, build an eval harness that measures context retention accuracy by checking whether evicted facts critical to the task are still recoverable from the summary, and set a threshold below which the system must escalate for human review.
Use Case Fit
Where the Sliding Window Summary Prompt works, where it breaks, and the operational risks to manage before deploying it in a production AI pipeline.
Good Fit: Long Multi-Turn Sessions
Use when: your conversational AI handles sessions exceeding the model's context window, such as customer support, research interviews, or copilot threads. Guardrail: The prompt must explicitly preserve unresolved questions, user preferences, and pending decisions in the summary to avoid silent state loss.
Bad Fit: Single-Turn or Stateless Workflows
Avoid when: each request is independent, or the application already manages state externally. Adding a sliding window summary introduces unnecessary latency and token cost. Guardrail: Use a preflight check to bypass summarization when session turn count is below a configured threshold.
Required Inputs: Structured Turn History
Risk: The prompt fails silently if fed unstructured or interleaved multi-user chat logs without clear speaker roles. Guardrail: Require a structured input schema with role, content, and timestamp fields. Validate that the input array is well-formed before invoking the summary prompt.
Operational Risk: Silent Context Drift
What to watch: The summary gradually loses fidelity over many compression cycles, causing the assistant to forget early user constraints or make contradictory statements. Guardrail: Implement a periodic full-context audit by comparing the current summary against a sampled original turn. Escalate if fact retention drops below a defined threshold.
Operational Risk: Summary-Only Blindness
What to watch: The model relies entirely on the summary and cannot access evicted turns to resolve user follow-up questions about past details. Guardrail: Store evicted turns in external memory with metadata search. When a user references a past detail, retrieve the original turn and inject it alongside the summary before generating a response.
Bad Fit: Compliance-Heavy or Audit-Required Domains
Avoid when: regulations require a complete, immutable record of every interaction for audit or legal review. A lossy summary is not a substitute for the original transcript. Guardrail: Use the summary only for live conversation steering. Archive full turn history separately and never use the summary as the system of record.
Copy-Ready Prompt Template
A reusable prompt template for maintaining a rolling summary of chat history that evicts old turns while preserving decisions, preferences, and unresolved items.
This prompt template implements a sliding window summary strategy for long-running conversational AI sessions. When the conversation history approaches the model's context limit, this prompt instructs the model to compress earlier turns into a structured summary, preserving critical state while freeing token budget for new interactions. The template is designed to be called programmatically by your application harness whenever the estimated token count exceeds a configured threshold.
textYou are maintaining a rolling summary of an ongoing conversation to manage context window limits. Your task: Read the [CURRENT_SUMMARY] and the [NEW_TURNS] below, then produce an updated summary that preserves all critical information while fitting within [MAX_SUMMARY_TOKENS] tokens. [CURRENT_SUMMARY] [EXISTING_SUMMARY_TEXT] [NEW_TURNS] [RECENT_CONVERSATION_TURNS] [RETENTION_RULES] You must preserve the following categories of information in the updated summary: - [REQUIRED_CATEGORIES] [OUTPUT_FORMAT] Produce the updated summary as a single coherent paragraph with no bullet points or markdown. Begin with "SUMMARY:" followed by the compressed text. [CONSTRAINTS] - Do not exceed [MAX_SUMMARY_TOKENS] tokens in the output summary. - Prioritize recent information over older details when conflicts arise. - If a category in [RETENTION_RULES] has no content to preserve, omit it silently. - Do not include meta-commentary about the summarization process. - Preserve exact values for numbers, dates, identifiers, and code snippets.
To adapt this template for your application, replace each square-bracket placeholder with values from your conversation state manager. The [REQUIRED_CATEGORIES] field should list the specific information types your use case demands—common examples include user preferences, pending action items, decisions made, unresolved questions, and entity references. Wire the output of this prompt back into your session state as the new [CURRENT_SUMMARY] for the next summarization cycle. Test with eval checks that verify category-level retention accuracy before deploying to production.
Prompt Variables
Required inputs for the sliding window summary prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check that the input is well-formed and safe.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CHAT_HISTORY] | Full multi-turn conversation to be summarized, including user and assistant messages with timestamps or turn IDs | User: I need to change my billing address. Assistant: I can help with that. Can you provide your account number? User: It's 4821-9932. | Parse check: must be valid JSON array of message objects with role, content, and optional timestamp fields. Reject if empty or contains only system messages. |
[WINDOW_SIZE] | Number of most recent turns to preserve in full detail before summarizing older turns | 5 | Schema check: must be positive integer between 2 and 50. Null not allowed. Default to 10 if unset but log warning. |
[SUMMARY_SLOT] | Existing rolling summary from previous window eviction to be updated with new evicted turns | Previous summary: User wants to change billing address. Account number 4821-9932 verified. Pending: new address not yet provided. | Null allowed on first call. If non-null, must be string under 2000 tokens. Parse check: verify no markdown code fences embedded. Schema check: reject if contains unescaped JSON. |
[EVICTION_POLICY] | Rule for selecting which turns to evict: recency, relevance, or dependency-based | recency | Enum check: must be one of recency, relevance, dependency. Default to recency if invalid value provided. Log warning on fallback. |
[PRESERVED_ENTITIES] | List of entity types that must be retained in the summary even when their source turns are evicted | ["account_number", "email_address", "support_ticket_id", "decision"] | Schema check: must be array of strings. Empty array allowed. Reject if contains non-string elements. Max 20 entity types. |
[UNRESOLVED_ITEMS] | List of open questions, pending actions, or incomplete tasks that must survive eviction | ["New billing address not yet provided", "Awaiting account ownership verification"] | Schema check: must be array of strings. Null allowed if no unresolved items exist. Each string max 500 characters. Reject if contains only whitespace entries. |
[OUTPUT_SCHEMA] | Expected JSON structure for the updated summary output | {"summary_text": "string", "evicted_turn_ids": ["string"], "preserved_entities": {}, "unresolved_items": ["string"], "token_count_after_eviction": 0} | Schema check: must be valid JSON Schema object. Required fields: summary_text, evicted_turn_ids, preserved_entities, unresolved_items. Reject if schema allows additionalProperties: true without explicit intent. |
[MAX_OUTPUT_TOKENS] | Token budget for the summary output to prevent the summary itself from overflowing the context window | 800 | Schema check: must be positive integer between 100 and 4000. Null not allowed. If value exceeds model max output tokens, clamp and log warning. |
Implementation Harness Notes
How to wire the Sliding Window Summary Prompt into a production chat application with validation, retries, and state management.
The Sliding Window Summary Prompt is not a standalone call—it is a state-management step that runs inside a chat loop. When the conversation history approaches the model's context limit, the harness must trigger this prompt before the next user turn. The prompt receives the full conversation history and the last known summary, and it returns a new summary that replaces the evicted turns. The application then constructs the next model request using the new summary plus the most recent turns, keeping the total token count within budget. This means the harness needs a reliable token counter, a configurable threshold (e.g., trigger when 80% of the context window is full), and a place to store the rolling summary between turns.
Wire the prompt into a stateful session object that holds: conversation_history (list of turns), rolling_summary (string or null), summary_metadata (last summary timestamp, turn index covered, token count). Before each user turn, run a preflight check: count tokens in conversation_history plus the system prompt and any RAG context. If the total exceeds the trigger threshold, call the Sliding Window Summary Prompt with the full history and current rolling_summary. Validate the output: check that the returned summary is non-empty, contains fewer tokens than the evicted turns, and preserves key fields (decisions, preferences, unresolved items). If validation fails, retry once with a stronger constraint instruction. If it fails again, log the failure, keep the old summary, and escalate to a human reviewer or fallback model. On success, update rolling_summary, evict summarized turns from conversation_history, and proceed with the user turn.
For production deployment, treat this prompt as a critical state-mutation step. Log every summary generation with the turn range covered, token counts before and after, and a hash of the summary for auditability. Run periodic evals that compare the summary against the original turns to measure information retention—check that decisions, user preferences, and open questions survive the compression. Common failure modes include: the summary growing too large over many cycles (mitigate with a summary-of-summaries step), the model dropping a critical user preference (mitigate with a preference-extraction pre-check), or the summary prompt itself exceeding the context window (mitigate by summarizing in chunks if the history is extremely long). Do not use this prompt for sessions under 20 turns unless token pressure is severe; a simpler truncation strategy is cheaper and faster for short conversations.
Expected Output Contract
Fields, types, and validation rules for the sliding window summary output. Use this contract to parse the model response, validate correctness, and detect regressions before the summary is used as context for the next turn.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
summary_text | string | Must be non-empty. Length must be between 50 and 500 words. Must not contain unresolved template tokens or placeholder text. | |
key_decisions | array of strings | Each item must be a complete sentence describing a decision made in the conversation. Array must contain at least 1 item if decisions were present; otherwise, an empty array is allowed. | |
unresolved_items | array of objects | Each object must contain 'question' (string, required) and 'context' (string, optional). Array can be empty. No duplicate questions allowed. | |
user_preferences | array of strings | If present, each string must describe a stated preference or constraint. Null or empty array is acceptable. Must not invent preferences not stated in the source turns. | |
last_turn_id | string or null | Must match the ID of the last turn included in the summary window. Null only if no turns were processed. Must be a valid UUID or integer matching the source format. | |
evicted_turn_count | integer | Must be a non-negative integer. Must equal the number of turns removed from the active window. Must be 0 if no eviction occurred. | |
summary_timestamp | ISO 8601 string | Must be a valid UTC timestamp. Must be parseable by standard datetime libraries. Must be after the timestamp of the last included turn. | |
confidence_flag | string | Must be one of: 'high', 'medium', 'low'. 'low' requires at least one unresolved_item to be present. 'high' requires no unresolved_items and key_decisions present if decisions were made. |
Common Failure Modes
Sliding window summaries fail silently. The model drops critical details, misremembers user preferences, or summarizes the wrong turns. These are the most common failure modes and how to catch them before they corrupt the conversation state.
Critical Detail Eviction
What to watch: The summary drops a user preference, constraint, or decision made earlier in the conversation. The model continues as if the detail never existed, leading to contradictory or irrelevant responses. Guardrail: Maintain a separate, append-only 'key facts' list outside the sliding window. Before each summary generation, instruct the model to explicitly preserve all items from this list in the new summary.
Summary Drift and Fabrication
What to watch: Over successive summarization steps, the model subtly alters the meaning of past events, adds plausible but false details, or smooths over important nuances. The summary becomes a fictionalized version of the chat history. Guardrail: Implement a fact-verification step. After generating a new summary, use a separate prompt to extract all factual claims and cross-reference them against the original turns being evicted. Flag any unsupported claims for human review.
Unresolved Item Amnesia
What to watch: The user asked a question or requested an action that the assistant hasn't completed yet. The sliding window summary omits this pending item, and the assistant never follows up. Guardrail: Dedicate a section of the summary template to 'Unresolved Items.' The summarization prompt must be instructed to scan for questions, requests, or tasks that lack a final resolution and carry them forward verbatim.
Recency Bias Overwhelming History
What to watch: The summary prompt over-weights the most recent turns and compresses older, foundational context into a vague, useless sentence. The assistant loses the plot of the entire conversation. Guardrail: Structure the summary prompt with explicit sections for 'Long-Term Context & Decisions' and 'Recent Actions.' Instruct the model to preserve the original specificity of long-term items, even if it means using more tokens for that section.
Token Budget Exhaustion by Summary
What to watch: The summary itself grows too large over many cycles, consuming the context window it was meant to save. The system fails because the summary, not the history, causes the overflow. Guardrail: Set a hard token limit for the summary field. If the summary exceeds this limit, trigger a secondary 'summary-of-summary' compression step that is explicitly instructed to condense older sections while preserving the 'key facts' and 'unresolved items' lists.
Silent Context Window Overflow
What to watch: The application code fails to trigger the summarization prompt before the model's context limit is reached. The model's oldest turns are silently truncated by the API, losing information without any summary being generated. Guardrail: Never rely on the model to manage its own window. Use a token counter in the application harness to trigger the summarization prompt when a pre-defined safety threshold (e.g., 80% of the model's context limit) is reached, ensuring the summary is generated before any truncation occurs.
Evaluation Rubric
Use this rubric to test the Sliding Window Summary Prompt before shipping. Each criterion targets a specific failure mode in long-conversation compression.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Decision Preservation | All explicit user decisions (e.g., 'use PostgreSQL', 'budget is $5k') from evicted turns appear in the summary. | A decision from an evicted turn is missing from the summary, causing the assistant to contradict prior agreements. | Run a 12-turn conversation with 3 explicit decisions in turns 2-4. Evict turns 1-6. Verify all 3 decisions appear in the summary via substring match. |
Unresolved Item Retention | All open questions or action items from evicted turns are carried forward into the summary. | An open question from turn 3 is dropped after eviction, and the assistant never follows up. | Inject 2 unresolved questions in early turns. After sliding window evicts those turns, query the summary for both questions using an LLM-as-Judge check. |
Preference Continuity | User-stated preferences (tone, format, constraints) from evicted turns are preserved and applied in subsequent responses. | The assistant reverts to a default tone or format after the window slides, ignoring a prior user preference. | Set a preference in turn 1 (e.g., 'always respond in bullet points'). Evict turn 1. Prompt the assistant and validate the output format matches the preference. |
Entity and Reference Stability | Named entities, project names, and reference IDs from evicted turns remain accurate in the summary. | A project name or ID is hallucinated or dropped after eviction, breaking downstream tool calls or lookups. | Seed early turns with 5 unique entity-value pairs. After eviction, use exact string matching to confirm all 5 entities are present and unaltered in the summary. |
Summary Length Control | The summary stays within the configured token budget (e.g., 500 tokens) and does not grow unboundedly over multiple slides. | The summary accumulates cruft and exceeds the token budget after 3 slides, causing a new overflow. | Simulate 5 sliding-window operations. Measure the token count of the summary after each slide. Fail if any summary exceeds the budget by more than 10%. |
Temporal Ordering | The summary correctly sequences events and decisions from oldest to newest, preserving causal relationships. | A decision made in turn 2 is summarized as occurring after a decision from turn 4, reversing the dependency. | Create a sequence of 3 dependent decisions (A enables B enables C). After eviction, use an LLM judge to verify the summary states 'A, then B, then C' in correct order. |
Task Continuity | The assistant can resume the primary task after a slide without losing the goal or repeating completed steps. | After eviction, the assistant restarts the task from the beginning or asks 'What were we doing?' | Run a multi-step task (e.g., 'plan a 3-step deployment'). Complete step 1, evict those turns, then prompt 'Continue.' Verify the assistant proceeds to step 2 without redoing step 1. |
Negative Case: Irrelevant Detail Eviction | Low-priority small talk, filler, and resolved sub-tasks are successfully evicted and do not appear in the summary. | The summary wastes tokens on 'Hello, how are you?' exchanges or a task marked as DONE. | Inject 3 turns of small talk and 1 resolved sub-task before eviction. Verify the summary contains zero tokens related to these items using a keyword exclusion check. |
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
Start with the base sliding window summary prompt and a fixed window size (e.g., last 6 turns). Use a simple instruction: "Summarize the conversation so far, preserving decisions, user preferences, and unresolved questions. Keep the summary under [MAX_TOKENS] tokens." Append the summary to the system message on each turn. Skip schema validation and eval harness initially.
Watch for
- Summary drift where later summaries lose early decisions
- Over-summarization that drops specific user preferences (e.g., "I prefer dark mode" becomes "user has preferences")
- No mechanism to detect when the summary is stale or contradicts recent turns

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