This prompt is designed for multi-turn chat and copilot systems where the raw conversation history has grown beyond practical token limits. The job-to-be-done is compressing a long transcript into a dense, structured summary that retains unresolved questions, explicit user corrections, key decisions, and active context while safely dropping turns that are resolved, redundant, or stale. The ideal user is an AI engineer or backend developer building a stateful chat product who needs a deterministic, testable compression step before the next inference call.
Prompt
Conversation History Compression Prompt for Chat Agents

When to Use This Prompt
Define the job, reader, and constraints for conversation history compression in production chat agents.
Use this prompt when your system maintains a full conversation log and you need to produce a compressed history block that fits inside a limited context window alongside system instructions, tool schemas, and retrieved evidence. It is appropriate for customer support copilots, long-running research assistants, and multi-turn agent workflows where losing track of an earlier user correction or an open question would degrade the user experience. The prompt expects a structured input containing the full conversation transcript and a set of compression directives—such as which categories of information to preserve and which to drop.
Do not use this prompt as a substitute for proper session state management in your application layer. If your product already tracks unresolved items, decisions, and corrections in a structured session object, you should assemble the compressed context programmatically rather than asking the model to reconstruct it from raw transcripts. This prompt is also not a replacement for a persistent memory system; it operates on a single session's history and does not carry user preferences or facts across sessions. For regulated domains where dropping any user statement could create compliance risk, pair this prompt with a risk-based retention check and human review gate before the compressed output is used downstream.
Use Case Fit
Where the Conversation History Compression Prompt works, where it fails, and the operational prerequisites for production use.
Good Fit: Long-Running Chat Sessions
Use when: multi-turn copilot or support sessions exceed the model's context window, and you need to retain unresolved questions, user corrections, and active decisions. Guardrail: always preserve the last N raw turns alongside the compressed summary to avoid losing recent nuance.
Bad Fit: Single-Turn or Stateless Workflows
Avoid when: the system has no conversation history or each request is independent. Compression adds latency and complexity with no benefit. Guardrail: check session turn count before invoking compression; skip entirely if turns < threshold.
Required Input: Structured Turn Metadata
What to watch: compression quality degrades without turn-level metadata such as timestamps, speaker roles, and resolution status. Guardrail: require a typed conversation log with role, content, timestamp, and resolved fields before compression runs.
Operational Risk: Silent Fact Drift
What to watch: the compression model may subtly alter facts, drop user corrections, or rephrase decisions in ways that change downstream behavior. Guardrail: run a factuality preservation check comparing compressed output against original turns before replacing history.
Operational Risk: Stale Context Accumulation
What to watch: compressed summaries can accumulate over many sessions, carrying forward outdated user preferences or resolved issues. Guardrail: implement staleness detection with TTL markers and force full re-compression when contradictions with fresh turns are detected.
Cost vs. Quality Trade-Off
What to watch: aggressive compression saves tokens but increases risk of dropping critical context like pending action items or user corrections. Guardrail: define a minimum retention set (unresolved questions, active decisions, recent corrections) that compression must never drop, regardless of token budget.
Copy-Ready Prompt Template
A reusable prompt template for compressing multi-turn conversation history into a dense, structured summary that retains unresolved questions, key decisions, and active context while dropping resolved or stale turns.
The prompt template below is designed to be inserted into your application's context assembly pipeline when the accumulated conversation history exceeds a token threshold you define. It instructs the model to act as a history compressor, producing a structured output that replaces the raw transcript. The template uses square-bracket placeholders for all dynamic inputs, making it straightforward to wire into a template engine or prompt builder. Before using this in production, you must define your own thresholds for when compression triggers, decide whether to run this synchronously before the next user turn or asynchronously in the background, and establish validation checks on the compressed output to ensure no critical information was dropped.
textYou are a conversation history compressor for a multi-turn chat agent. Your task is to compress the provided conversation history into a structured summary that preserves all information necessary for the agent to continue the conversation accurately. ## INPUT [CONVERSATION_HISTORY] ## COMPRESSION RULES 1. **Retain Unresolved Items**: Keep all user questions, requests, or issues that have not been fully resolved or answered. Include any partial progress toward resolution. 2. **Retain User Corrections and Feedback**: Preserve any instance where the user corrected the agent, expressed dissatisfaction, or provided explicit preferences. Note the correction and the agent's response. 3. **Retain Key Decisions and Facts**: Keep decisions made by the user or agent, confirmed facts, user-provided data (names, dates, numbers, constraints), and agreed-upon next steps. 4. **Retain Active Context**: Preserve the topic, goal, or task the user is currently working on. Include relevant entities, project names, or domain-specific terms. 5. **Drop Resolved Turns**: Remove turns where a question was fully answered and the user acknowledged or moved on without follow-up. 6. **Drop Greetings and Pleasantries**: Remove small talk, thank-yous, and conversational filler that carries no task information. 7. **Drop Redundant Repetition**: If the same information appears multiple times, keep only the most recent or most complete version. 8. **Preserve Temporal Order**: For retained items, maintain the chronological sequence of events, corrections, and decisions. ## OUTPUT FORMAT Return a JSON object with the following schema: { "summary": "A dense narrative summary of the conversation state, covering the current topic, what has been accomplished, and what remains open. Write in past tense. Maximum 3 sentences.", "unresolved_items": [ { "item": "Description of the unresolved question, request, or issue", "status": "not_started | in_progress | blocked | awaiting_user", "context": "Any relevant context needed to resolve this item" } ], "key_decisions": [ { "decision": "What was decided", "made_by": "user | agent | mutual", "timestamp_turn": "Approximate turn number or position reference" } ], "user_preferences_and_corrections": [ { "correction_or_preference": "What the user corrected or stated as a preference", "agent_response": "How the agent acknowledged or adapted" } ], "active_context": { "topic": "Current topic or task", "entities": ["Key entities, names, or terms"], "constraints": ["Any constraints or requirements in play"] }, "dropped_turns_summary": "Brief note on what types of turns were dropped and why (e.g., 'Dropped 4 turns of greetings and resolved Q&A')." } ## CONSTRAINTS - Do not invent information not present in the conversation history. - If the history is already short and contains no resolved turns, return a minimal summary without forcing compression. - If the conversation contains [SENSITIVE_DATA_POLICY], apply the redaction rules specified there before including any information in the output. - Output ONLY the JSON object. No preamble, no commentary.
To adapt this template for your application, start by replacing [CONVERSATION_HISTORY] with your formatted transcript. The transcript format matters: include speaker labels (e.g., User:, Agent:) and turn boundaries so the model can distinguish who said what. The [SENSITIVE_DATA_POLICY] placeholder should be replaced with your organization's PII handling rules or removed if not applicable. You may also adjust the output schema fields to match your downstream agent's state representation. For example, if your agent uses a different state tracking structure, modify the JSON schema to produce objects your agent can consume directly without an additional transformation step. Test the compressed output by feeding it into a fresh conversation with your agent and verifying that the agent behaves as if it has full context for unresolved items while not re-litigating resolved ones.
Before deploying this prompt, build a small evaluation set of 5-10 conversation transcripts with known critical items that must survive compression. Run the prompt against each transcript and check that every unresolved question, user correction, and key decision appears in the output. Common failure modes include the model summarizing too aggressively and dropping a correction the user made three turns ago, or treating a partially resolved item as fully resolved because the agent said 'I'll look into that' but never reported back. If your application operates in a regulated domain, add a human review step for compressed histories before they replace the raw transcript in the agent's context window. Finally, log the compression ratio (input tokens vs. output tokens) and the dropped turns summary to monitor whether the compressor is being too aggressive or too conservative over time.
Prompt Variables
Required and optional inputs for the Conversation History Compression Prompt. Validate each variable before assembly to prevent compression failures, context loss, or hallucination in downstream agent turns.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[CONVERSATION_HISTORY] | Full multi-turn transcript to compress, including user messages, assistant responses, tool calls, and tool results | User: What's the status of PR #142?\nAssistant: Let me check... [tool_call: get_pr(142)]\nTool: {"status": "open", "reviewers": ["alice"]}\nAssistant: PR #142 is open, awaiting review from Alice. | Must be valid JSON array of turn objects with role, content, and optional tool_calls fields. Reject if empty array or exceeds [MAX_INPUT_TOKENS]. Check that turn ordering is chronological. |
[COMPRESSION_TARGET_TOKENS] | Maximum token count for the compressed output, driving compression aggressiveness | 2048 | Must be positive integer. Should be less than [MAX_INPUT_TOKENS]. Validate that target is at least 20% of input token count to prevent over-compression. Reject if target exceeds model context limit. |
[UNRESOLVED_QUESTIONS] | List of questions or requests from the user that have not yet been fully answered or actioned | ["What's the status of PR #142?", "When will the staging deploy finish?"] | Optional array of strings. If null, the prompt will extract unresolved questions from [CONVERSATION_HISTORY]. If provided, cross-validate that listed questions actually appear in the history to prevent hallucinated retention mandates. |
[ACTIVE_DECISIONS] | Key decisions made during the conversation that affect current task state or next steps | ["User chose PostgreSQL over MySQL for the new service", "Deploy target set to us-east-1"] | Optional array of strings. If null, the prompt will infer decisions from history. Validate that each decision has traceable evidence in [CONVERSATION_HISTORY]. Reject decisions that contradict tool outputs or user corrections in the history. |
[USER_CORRECTIONS] | Explicit corrections the user made to assistant outputs or tool results that must survive compression | ["User corrected: the service name is 'payment-api' not 'billing-api'", "User corrected: the deadline is Friday not Monday"] | Optional array of strings. If null, the prompt will extract corrections from history. Validate that each correction maps to a specific turn where the user contradicted or amended a prior assistant statement. Flag corrections that appear to be hallucinations. |
[PERSISTENT_CONTEXT] | Session-level or user-level context that should be preserved across compression cycles, such as user preferences, project state, or role constraints | {"user_role": "backend engineer", "current_project": "payment-api migration", "preferred_language": "Python"} | Optional JSON object. Validate that keys match a known schema for the application. Reject if [PERSISTENT_CONTEXT] contains PII or secrets not explicitly allowed. Cross-check that persistent context does not conflict with recent user corrections in [CONVERSATION_HISTORY]. |
[OUTPUT_SCHEMA] | Expected structure for the compressed output, defining required fields and their types | {"summary": "string", "unresolved": ["string"], "decisions": ["string"], "corrections": ["string"], "active_context": "string", "dropped_turns": ["string"]} | Must be valid JSON Schema or TypeScript interface definition. Validate that required fields include at minimum: summary, unresolved items, and active context. Reject schemas that allow dropping all turns without justification. Ensure schema is parseable before prompt assembly. |
Implementation Harness Notes
How to wire the conversation history compression prompt into a production chat agent or copilot application.
The compression prompt is not a standalone feature; it is a middleware step inside a stateful conversation loop. When the accumulated conversation history exceeds a configurable token threshold (for example, 80% of the model's context window), the application should trigger compression before the next turn. The uncompressed history is archived for audit and debugging, while the compressed summary replaces the full history in the active prompt context. This keeps the agent responsive and cost-effective without losing critical conversational state.
Wire the compression call as a synchronous pre-processing step before assembling the main agent prompt. Pass the full conversation array into the [CONVERSATION_HISTORY] placeholder, set [MAX_OUTPUT_TOKENS] to a fraction of your total context budget (typically 10-20%), and define [RETENTION_PRIORITIES] explicitly: unresolved questions, user corrections, key decisions, active constraints, and any domain-specific entities. The output should be a structured JSON object with compressed_summary (string), retained_turns (array of turn indices kept verbatim), and dropped_turns (array of indices removed with a one-line reason). Validate this JSON strictly before accepting the compressed result—if parsing fails, retry once with a stricter schema instruction, then fall back to truncating the oldest turns if the retry also fails.
Log every compression event with a unique compression_id, the pre-compression token count, post-compression token count, compression ratio, and the model version used. Store the full pre-compression history and the compressed output side by side in your observability pipeline. This traceability is essential for debugging quality regressions: if the agent starts missing context, you can replay the compression step and compare outputs. For high-stakes domains (healthcare, legal, finance), add a human-review gate on the first N compression events or on any compression that drops turns containing flagged keywords (e.g., 'allergy', 'cancel', 'dispute').
Model choice matters. Use a fast, cost-efficient model for compression (e.g., GPT-4o-mini, Claude Haiku, or a fine-tuned small model) rather than your primary reasoning model. The compression task is extractive and summarization-focused, not reasoning-intensive. If your application uses tool calls, ensure the compression prompt's [TOOLS_USED] placeholder captures the tool names and key outputs so the compressed history preserves the fact that a tool was called and what it returned, even if the full output is summarized. Finally, build a periodic eval that samples compressed histories and checks for fact preservation, unresolved question retention, and absence of hallucinated content—run this eval weekly or on every prompt version change to catch drift before users do.
Common Failure Modes
Conversation history compression is lossy by design. These are the most common production failures and how to prevent them before they corrupt downstream agent behavior.
Silent Factual Drift
What to watch: The compressed summary subtly changes a user's stated constraint, preference, or fact without triggering an obvious error. The agent then acts on incorrect information for the rest of the session. Guardrail: Run a factuality preservation check prompt comparing compressed output against original turns for any semantic divergence before the compressed history replaces the live context.
Dropped Unresolved Questions
What to watch: The compression prompt treats an unanswered user question as stale or low-priority and omits it entirely. The agent loses track of what it still owes the user. Guardrail: Add an explicit instruction in the compression prompt to list all unresolved questions in a dedicated section. Validate the compressed output contains every open item from the original turns before accepting it.
Correction Overwrite
What to watch: A user corrects the agent mid-session, but the compression summarizes the final state without preserving the fact that a correction occurred. If the agent later re-retrieves the original wrong information, it has no memory of the override. Guardrail: Require the compression prompt to flag user corrections explicitly with a [CORRECTED] marker and retain both the original error context and the corrected value.
Tool Call Result Amnesia
What to watch: The compression summarizes a tool call and its result into a vague phrase like
Stale Context Retention
What to watch: The compression keeps early-turn context that has been superseded by later turns, wasting token budget on outdated information while newer critical details get truncated. Guardrail: Add a staleness check step that timestamps each turn and instructs the compression prompt to prefer more recent information when turns conflict. Drop turns that have been explicitly resolved or superseded.
Citation Chain Breakage
What to watch: The compressed summary references a fact or quote that originally came from a retrieved document, but the compression drops the source pointer. Downstream citation verification fails, and the output becomes ungrounded. Guardrail: Require the compression prompt to preserve source IDs and citation markers alongside any retained evidence. Run a citation integrity check after compression to confirm every claim still maps to a retrievable source.
Evaluation Rubric
Criteria for testing the quality of compressed conversation history before it replaces the original context in a production chat agent.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Unresolved Question Retention | All questions from the last [N] turns that lack a confirmed answer appear in the compressed output. | A user question from a recent turn is absent from the compressed history. | Diff the compressed output against the original last [N] turns; assert every interrogative sentence is present or summarized. |
User Correction Preservation | Every explicit user correction (e.g., 'no, that's wrong', 'I meant X') from the original history is retained with its corrected value. | A correction turn is dropped and the agent later repeats the corrected error. | Extract all turns containing negation or correction keywords; verify each appears in the compressed output. |
Key Decision Capture | All explicit decisions, confirmations, or user approvals (e.g., 'yes, proceed', 'use option B') are present in the compressed output. | A decision turn is summarized away and the agent later asks for reconfirmation. | Tag decision turns in the original history; assert each tag maps to a compressed segment with the decision value. |
Stale Turn Removal | Turns marked as resolved, fully executed, or superseded by a correction are absent from the compressed output. | A resolved turn (e.g., 'what's the weather?' already answered) appears verbatim in the compressed history. | Identify resolved turns by checking for subsequent acknowledgment; assert none appear in the compressed output. |
Entity and Reference Integrity | All named entities, IDs, ticket numbers, and user-provided reference codes from the original history appear unchanged in the compressed output. | A ticket ID or account number is truncated, paraphrased, or dropped. | Regex-extract structured identifiers from original and compressed outputs; assert set equality. |
Compression Ratio Compliance | The compressed output token count is ≤ [TARGET_TOKEN_COUNT] and ≥ 40% of the original token count. | Compressed output exceeds the token budget or collapses to an empty or near-empty string. | Run tokenizer on original and compressed outputs; assert compressed tokens ≤ [TARGET_TOKEN_COUNT] and ≥ 0.4 * original tokens. |
No Fabricated Content | The compressed output contains no claims, facts, or user statements not present in the original history. | The compressed output invents a user preference, decision, or question that never occurred. | Perform claim extraction on the compressed output; for each claim, verify a matching span exists in the original history using semantic similarity threshold. |
Active Context Coherence | The compressed output preserves the chronological and causal order of active tasks; downstream agent can continue without confusion. | The compressed output reorders turns such that a response appears before its triggering question. | Human or LLM-as-judge review: ask 'Can you reconstruct the task sequence?' and assert a score ≥ 4/5. |
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 simple instruction: "Compress the following conversation history. Retain unresolved questions, user corrections, key decisions, and active context. Drop resolved turns and stale information." Set [MAX_OUTPUT_TOKENS] to a generous ceiling. Skip schema enforcement initially.
Watch for
- The model dropping user corrections and reverting to earlier wrong answers
- Over-compression that loses the thread of multi-step tasks
- No way to verify what was dropped without manual inspection

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