Inferensys

Prompt

Dialogue History Compression Prompt for RAG

A practical prompt playbook for using Dialogue History Compression Prompt for RAG in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Learn when to deploy lossy dialogue compression to manage token budgets in long-running RAG conversations without breaking answer quality.

This prompt is for operators and engineers managing token budgets in long-running RAG conversations where the context window is filling up and cost or latency is becoming prohibitive. The job-to-be-done is injecting a compressed representation of the dialogue history into the next turn's prompt assembly so the model can maintain conversational coherence without reprocessing every prior exchange. The ideal user is an AI engineer or platform operator who has already instrumented their RAG pipeline to track token consumption per turn and needs a programmatic compression step before the next retrieval-augmented generation call. You should have access to the raw conversation transcript, the previously retrieved evidence chunks, and the system's prior answers before invoking this prompt.

Use this prompt when your conversation has exceeded 10-15 turns, when you observe answer quality degrading due to context truncation, or when your token accounting shows that dialogue history is consuming more than 40% of the available context window. The compression is specifically designed to preserve question-answer pairs, unresolved items, key facts extracted from evidence, and user corrections while dropping redundant turns, filler exchanges, and already-resolved clarifications. Do not use this prompt for general text summarization, for compressing retrieved documents (that's a separate retrieval-side concern), or for single-turn RAG systems where history is irrelevant. It is also not appropriate when the conversation contains legally binding statements, clinical decisions, or compliance-critical exchanges where lossy compression could drop material facts—in those cases, implement a full audit log alongside any compression step.

Before deploying this prompt in production, run a regression test suite that compares answer quality with and without compression across at least 20 multi-turn conversation scenarios. Measure factual consistency against source evidence, citation preservation, and unresolved question carry-forward. Common failure modes include dropping a user correction from 5 turns ago, compressing a clarification question into a statement of fact, or losing the distinction between 'the system couldn't answer this' and 'the system hasn't tried yet.' If your eval shows answer degradation above 5% after compression, reduce the compression ratio or add a human review step before the compressed history is injected into the next turn. Wire this prompt into your prompt assembly pipeline as a pre-processing step that runs when a token budget threshold is breached, not as a user-facing feature.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Dialogue History Compression Prompt works, where it fails, and the operational conditions required before you rely on it in production.

01

Good Fit: Long Multi-Turn Sessions

Use when: your RAG assistant handles sessions exceeding 20+ turns and raw history would overflow the context window. Compression preserves question-answer pairs and unresolved items while dropping redundant turns. Guardrail: measure answer quality before and after compression using your standard RAG eval rubric to confirm no degradation.

02

Bad Fit: Short or Single-Turn Interactions

Avoid when: sessions are under 5 turns or the full history fits comfortably within the context budget. Compression adds latency and risks losing nuance for no benefit. Guardrail: implement a token-count gate that only triggers compression when history exceeds a defined threshold (e.g., 60% of context limit).

03

Required Input: Structured Turn Records

Risk: feeding raw, unstructured chat logs produces inconsistent compression. The prompt needs turn boundaries, speaker roles, and whether each turn was answered or deferred. Guardrail: pre-process conversation history into a structured format with turn_id, role, content, status (resolved/unresolved), and grounding_facts before calling the compression prompt.

04

Operational Risk: Silent Fact Loss

Risk: the compression prompt drops a key fact that a future turn depends on, causing a downstream answer to become ungrounded or contradictory. This failure is silent—the model won't know it lost the fact. Guardrail: log a diff of dropped turns and their extracted facts. Run a post-compression check that asks the model to list all facts it retained, and compare against the pre-compression fact set.

05

Operational Risk: Unresolved Item Drift

Risk: an open question from turn 3 gets paraphrased during compression and loses its original specificity, leading to a wrong or vague answer when the user returns to it on turn 15. Guardrail: preserve the exact user phrasing for unresolved questions in a dedicated pending_items block. Do not allow the compressor to rephrase them.

06

Bad Fit: High-Precision Regulatory or Clinical Contexts

Avoid when: every prior exchange must be auditable and verbatim for compliance, such as clinical decision support or legal advice. Lossy compression breaks the chain of custody. Guardrail: in regulated domains, use full history with a larger context window or implement a retrieval-based history store instead of compression. If compression is unavoidable, log the full pre-compression history as an immutable audit record.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A ready-to-adapt prompt for compressing dialogue history into a dense, structured summary that preserves question-answer pairs, unresolved items, and key facts while discarding filler.

This prompt template is designed to be dropped into a RAG pipeline where long conversation histories threaten to exceed the model's context window or consume an unsustainable token budget. It instructs the model to act as a lossy compression engine, prioritizing the preservation of semantic content—questions, answers, factual claims, and unresolved threads—over conversational niceties like greetings, acknowledgments, and redundant turns. The output is a structured, machine-readable summary that can be injected into future context windows as a replacement for the raw transcript, maintaining multi-turn coherence without carrying the full weight of the dialogue.

text
Compress the following dialogue history into a dense, structured summary. Preserve every question-answer pair, any unresolved questions, and key factual claims. Drop greetings, acknowledgments, redundant turns, and filler. Output only the compressed history.

[DIALOGUE_HISTORY]

Output the compressed history in the following JSON format:
{
  "summary": "A single paragraph narrative summary of the conversation's core topics and outcomes.",
  "qa_pairs": [
    {
      "turn": <integer>,
      "question": "The user's exact question or request.",
      "answer": "The assistant's core answer, stripped of filler.",
      "citations": ["source_id_1", "source_id_2"]
    }
  ],
  "unresolved_questions": [
    "Question that was asked but not adequately answered."
  ],
  "key_facts": [
    "Factual claim made by the user or assistant that may be relevant later."
  ],
  "user_intent": "The inferred high-level goal of the user in this session."
}

To adapt this template, replace [DIALOGUE_HISTORY] with your raw conversation transcript, typically formatted as a sequence of User: and Assistant: turns. The output schema is a strong starting point but should be modified to match your application's needs. If your RAG system uses a specific citation format, adjust the citations field accordingly. If you do not need intent tracking, remove the user_intent field to save tokens. For high-stakes domains, add a [CONSTRAINTS] placeholder before the output schema to inject rules like 'Do not fabricate citations' or 'Mark any factual claim not grounded in the provided history with [UNVERIFIED].' Always validate the output JSON against your schema before injecting it into the next turn's context window; a malformed summary is worse than no summary.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the dialogue history compression prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Validation notes describe how to verify the input is well-formed before compression runs.

PlaceholderPurposeExampleValidation Notes

[DIALOGUE_HISTORY]

Full conversation transcript to compress, including user messages, assistant responses, and any system or tool messages

USER: What is the refund policy? ASSISTANT: Our refund policy allows returns within 30 days of purchase. USER: Does that apply to digital products? ASSISTANT: Yes, digital products are included if unused.

Must be a non-empty string with at least 2 turns. Validate that turn boundaries are clearly delimited. Reject if only one participant appears or if the transcript is malformed JSON.

[MAX_COMPRESSED_TOKENS]

Target maximum token count for the compressed output, used to guide compression aggressiveness

500

Must be a positive integer between 100 and 4096. Validate range before passing to the prompt. If null or missing, default to 500. Warn if [MAX_COMPRESSED_TOKENS] exceeds 50% of the model's context window.

[COMPRESSION_PRIORITY]

Instruction specifying which information to preserve: question-answer pairs, unresolved items, key facts, or user preferences

preserve_qa_pairs_and_unresolved

Must be one of: preserve_qa_pairs_and_unresolved, preserve_key_facts_only, preserve_user_intent, preserve_temporal_order. Reject unknown values. If null, default to preserve_qa_pairs_and_unresolved.

[OUTPUT_FORMAT]

Desired structure for the compressed output: structured JSON with labeled sections or a dense prose summary

structured_json

Must be one of: structured_json, prose_summary, bullet_list. Reject unknown values. If structured_json, validate that the output schema includes fields for resolved_qa, unresolved_items, and key_facts.

[SESSION_METADATA]

Optional metadata about the conversation: session ID, user role, topic tags, or domain context to help the model prioritize

{"session_id": "sess_891", "domain": "customer_support", "topic_tags": ["refund", "digital_products"]}

Must be valid JSON if provided. Null is allowed. If present, validate that session_id is a non-empty string. Topic tags must be an array of strings. Reject if metadata contains PII or sensitive fields not approved for model ingestion.

[UNRESOLVED_MARKER]

Token or phrase used in the dialogue to flag questions that were not answered, for the compressor to preserve

[UNANSWERED]

Must be a non-empty string that appears consistently in [DIALOGUE_HISTORY] wherever a question was not resolved. Validate that the marker is present at least once if unresolved items are expected. If null, the compressor will infer unresolved items from context.

[COMPRESSION_RATIO_TARGET]

Target ratio of compressed tokens to original tokens, used as a soft constraint alongside [MAX_COMPRESSED_TOKENS]

0.3

Must be a float between 0.1 and 0.8. Validate range. If null, the compressor uses [MAX_COMPRESSED_TOKENS] as the sole constraint. Warn if [COMPRESSION_RATIO_TARGET] and [MAX_COMPRESSED_TOKENS] conflict.

[PREVIOUS_COMPRESSION]

The compressed summary from the prior compression run, used to avoid re-compressing already-summarized turns

{"resolved_qa": [{"q": "What is the refund policy?", "a": "30-day returns for all products."}], "unresolved_items": [], "key_facts": ["Digital products included if unused."]}

Must be valid JSON matching the [OUTPUT_FORMAT] schema if provided. Null is allowed on first compression. If present, validate that it contains no turns newer than the earliest turn in [DIALOGUE_HISTORY] to prevent double compression.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the dialogue history compression prompt into a production RAG application with validation, retries, and observability.

The dialogue history compression prompt is not a standalone utility—it is a pipeline stage that sits between your conversation store and your next LLM call. In a typical RAG chat application, you maintain a list of conversation turns (user messages, assistant responses, and optionally retrieved evidence or citations). Before each new user message, you check whether the accumulated history plus the new retrieval context would exceed your model's context window or your token budget. If so, you invoke the compression prompt to produce a lossy summary that preserves question-answer pairs, unresolved items, and key facts while dropping redundant or resolved turns. The compressed summary then replaces the raw history in the context assembly step.

Implement this as a pre-call middleware in your LLM request pipeline. The middleware should: (1) calculate the current token count of the full conversation history plus the pending retrieval context and system prompt; (2) compare against a configured max_context_tokens threshold (typically 70-80% of the model's context limit to leave room for the output); (3) if over budget, call the compression model with the raw history and the [COMPRESSION_TARGET_TOKENS] parameter; (4) validate the compressed output before substituting it into the context. Use a separate, cheaper model for compression (such as GPT-4o-mini, Claude Haiku, or a local summarization model) to keep costs predictable. The compression model should be fast and reliable, not necessarily the same model that generates the final answer. Log the compression ratio (original tokens vs. compressed tokens) and the compression timestamp for observability.

Validation and retry logic are critical because a malformed compression can corrupt downstream answer quality. After receiving the compressed summary, run a lightweight validator that checks: (a) the output is non-empty and under the target token count; (b) it contains at least one question-answer pair or unresolved item marker; (c) it does not contain hallucinated facts not present in the original history (a simple overlap check against key entities or a follow-up fact-verification prompt can catch this). If validation fails, retry once with a more explicit instruction (e.g., 'The previous compression was empty. Please include all unresolved questions.'). If the retry also fails, fall back to truncating the raw history by dropping the oldest turns and log a warning. Never silently pass a failed compression into the answer-generation step.

Tool integration is straightforward: the compression prompt is a text-in, text-out operation with no external tool calls. However, if your conversation history includes structured metadata (citation IDs, evidence chunk references, tool call results), you must decide whether to preserve that structure in the compressed summary or flatten it. For most RAG applications, preserving citation IDs and evidence references in the compressed output is essential so the downstream answer generator can still ground claims. Include a [PRESERVE_METADATA] placeholder in the prompt template that specifies which fields to retain (e.g., 'Preserve all citation IDs in square brackets and unresolved question markers'). If your history contains tool-use turns (function calls and results), compress those into a concise 'tool used: [name], result: [summary]' format rather than dropping them entirely.

Human review is not required for every compression call—this is an automated pipeline stage. However, you should build a spot-check dashboard that samples compressed summaries alongside their original histories so operators can verify compression quality during development and after prompt changes. Set up an eval harness that runs the compression prompt against a golden dataset of conversation histories and measures: (1) answer quality preservation (does the downstream RAG answer remain correct when using compressed vs. raw history?); (2) unresolved item retention (are all open questions still present?); (3) compression ratio achieved. Run these evals as part of your prompt CI pipeline before deploying compression prompt changes. If your application operates in a regulated domain, log every compression event with the original history, compressed output, and validation result for audit trails.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the compressed dialogue history object. Use this contract to parse the model's response and validate it before injecting the compressed history into subsequent RAG turns.

Field or ElementType or FormatRequiredValidation Rule

compressed_history

Array of objects

Schema check: root must be a JSON array. Parse check: valid JSON.

compressed_history[].turn_id

String or Integer

Schema check: must match original turn identifiers. Uniqueness check: no duplicate turn_ids in array.

compressed_history[].type

Enum: ["question", "answer", "clarification", "correction", "unresolved"]

Enum check: value must be one of the listed types. Null not allowed.

compressed_history[].summary

String

Content check: must be a non-empty string. Length check: summary should be concise, not a verbatim copy of the original turn.

compressed_history[].key_facts

Array of strings

Schema check: if present, must be an array of strings. Each string must be a distinct, self-contained fact.

compressed_history[].unresolved_question

String

Conditional check: required when type is "unresolved". Must be a direct question that was not answered.

compressed_history[].citation_references

Array of strings

Schema check: if present, must be an array of source identifiers. Each identifier must match a source_id from the original evidence set.

compression_metadata

Object

Schema check: must be a JSON object containing the fields defined in the next rows.

compression_metadata.original_turn_count

Integer

Value check: must be a positive integer. Must match the number of turns provided in the input.

compression_metadata.compressed_turn_count

Integer

Value check: must be a positive integer less than or equal to original_turn_count.

compression_metadata.compression_ratio

Float

Value check: must be a float between 0.0 and 1.0. Calculation check: should equal compressed_turn_count / original_turn_count.

compression_metadata.dropped_turn_ids

Array of strings or integers

Schema check: must be an array of identifiers for turns excluded from compressed_history. Uniqueness check: no overlap with turn_ids in compressed_history.

PRACTICAL GUARDRAILS

Common Failure Modes

Dialogue history compression is a lossy operation. These are the most common production failure modes and how to prevent them before they degrade answer quality.

01

Loss of Unresolved Questions

What to watch: The compressor drops questions the system couldn't answer earlier, making the assistant appear forgetful when the user follows up. This breaks the carry-forward contract. Guardrail: Require a dedicated unresolved_items field in the compression output schema and validate that all open questions from prior turns are preserved before accepting the compressed payload.

02

Entity and Reference Collapse

What to watch: Compression summarizes 'the project deadline' and 'the budget approval' into a vague 'the discussion about planning,' destroying the specific entities needed for accurate follow-up retrieval and answer grounding. Guardrail: Add an entity preservation constraint to the compression prompt that requires key named entities, dates, and identifiers to survive compression verbatim rather than being paraphrased.

03

Temporal Ordering Corruption

What to watch: The compressed history reorders events, making it appear that the user asked about pricing before the product demo when the opposite was true. This corrupts multi-turn reasoning that depends on sequence. Guardrail: Include explicit turn timestamps or sequence markers in the input and require the compressor to maintain chronological order in the output. Validate turn ordering in evals.

04

Over-Compression of Clarification Turns

What to watch: The compressor collapses a multi-turn clarification sequence into a single summary, losing the specific options the user chose and the system's reasoning for asking. Future turns lose the disambiguation context. Guardrail: Flag clarification exchanges as high-priority for preservation. Test with a golden set of clarification sequences and verify the compressed output retains the specific ambiguity and the user's resolution choice.

05

Citation Chain Breakage

What to watch: The compressor drops source identifiers and citation anchors from prior answers. When the user asks 'tell me more about that second source,' the assistant has lost the reference. Guardrail: Require source IDs and citation markers to be preserved as structured fields in the compression output, not just as inline text that can be summarized away.

06

Silent Factual Drift

What to watch: The compressor subtly changes a prior answer's claim during summarization—'the API returns JSON' becomes 'the API handles data'—and subsequent turns build on the degraded fact. Guardrail: Run a post-compression consistency eval that compares key claims in the compressed history against the original turns. Flag semantic divergence above a threshold for human review or automatic rejection.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a compressed dialogue history before shipping the prompt to production. Use these checks to ensure the compression preserves answer-critical information while reducing token usage.

CriterionPass StandardFailure SignalTest Method

Question-Answer Pair Preservation

All explicit user questions and system answers from the original history are present in the compressed output.

A user question or its corresponding answer is missing from the compressed output.

Diff the list of questions in the original history against the compressed output. Flag any missing Q-A pairs.

Unresolved Item Retention

Any user question marked as unanswered or any open task is explicitly listed in the compressed output.

An open question from the original history is absent or marked as resolved in the compressed output.

Parse the original history for 'unresolved' markers. Check for their presence and correct status in the compressed output.

Key Fact Integrity

Specific entities, numbers, dates, and proper nouns from the original history are reproduced exactly in the compressed output.

A named entity or numerical value is altered or omitted in the compressed output.

Extract a set of key entities from the original history. Assert they are a subset of the entities in the compressed output.

Redundancy Removal

The compressed output contains no duplicate turns or semantically repeated information.

The same fact or exchange appears more than once in the compressed output.

Perform a semantic similarity check on all sentences in the compressed output. Flag pairs above a 0.95 similarity threshold.

Token Budget Adherence

The compressed output's token count is less than or equal to the [MAX_TOKENS] constraint.

The compressed output exceeds the specified [MAX_TOKENS] limit.

Count tokens in the compressed output using the target model's tokenizer. Assert count <= [MAX_TOKENS].

Answer Quality After Compression

A downstream RAG system using the compressed history produces an answer that is factually equivalent to one using the full history.

The answer generated using the compressed history contradicts or omits a fact from the answer generated using the full history.

Run a fact verification prompt on both answers against a ground-truth source. Assert no factual conflicts between the two answers.

Output Format Compliance

The compressed output is a single block of text with no extra commentary, prefixes, or meta-commentary.

The output includes phrases like 'Here is the compressed history:' or adds conversational filler.

Check that the output string does not start with a common meta-prefix and contains no new conversational turns.

Hallucination Prevention

The compressed output introduces no new facts, entities, or events not present in the original history.

A claim in the compressed output cannot be matched to any sentence in the original history.

Decompose the compressed output into atomic claims. For each claim, attempt to find a matching claim in the original history. Flag any unmatched claims.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base compression prompt but relax the output schema. Accept free-text summaries instead of strict JSON. Use a single example in the prompt to show the desired compression style. Skip token budget constraints initially—just observe what the model preserves and drops.

code
Compress the following dialogue history into a concise summary that preserves:
- All question-answer pairs
- Unresolved items
- Key facts mentioned

Drop redundant turns and filler.

Dialogue:
[DIALOGUE_HISTORY]

Watch for

  • The model dropping questions that weren't answered yet
  • Over-compression that loses entity names or numbers
  • Inconsistent level of detail across turns
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.