AI AgentsLangChain

How do you summarize long conversations without losing key facts?

Question 310 of 324 · Updated

On this page

Direct answer#

Use LangChain's SummarizationMiddleware to replace older conversational context with a compact summary while retaining a recent message window. For critical facts, supplement the generated summary with a structured, independently verified fact ledger, source references and unresolved-task records. Trigger summarization before the effective context budget is exhausted, cut only at valid conversation boundaries, and validate the resulting summary against the authorized source material.

Summarization is lossy by nature. A fluent summary is not proof that every necessary constraint, correction, approval or evidence reference survived. The objective is to preserve the information required for the remaining task, not to claim mathematically lossless compression of arbitrary conversations.

LangChain source #29 (AI Agents #309) covers non-destructive history trimming. Source #25 (#305) covers conversation continuity. AI Agents #227, #228 and #230 cover multi-agent compaction, information loss and compaction triggers. This lesson specifically addresses LangChain's single-agent conversational SummarizationMiddleware, the recent-message tail, rolling summaries and source-grounded acceptance of structured facts. Distributed compaction orchestration and general memory architecture are separate topics.

1. Why summarizing differs from trimming#

Trimming selects original messages and discards some from the current model input. Summarization synthesizes a shorter representation of earlier messages, potentially preserving facts that would otherwise disappear. It introduces a new failure mode: the generated representation can omit or alter the original meaning.

Imagine a fictional support conversation with the following progression.

TurnConversation eventWhat should survive
1User identifies order O-1Exact identifier and source
2User requests read-only assistanceNo-write constraint
3Assistant obtains a pending status from an authorized serviceStatus, evidence reference and observation time
4Another source reports shippedConflicting observation, not an invented resolution
5User asks for confirmation from the authoritative serviceUnresolved task
6Authoritative service confirms shipped and explicitly resolves the discrepancyCorrected current state and provenance

A simple recent-message window might discard the order identifier and no-write restriction. A careless summary might say "Order shipped, proceed" and omit the unresolved confirmation requirement. A faithful summary at turn 5 should instead preserve the two competing claims, the fact that confirmation is pending, and the restriction against writes.

The final summary should distinguish what the user stated, what a model proposed, what a tool actually reported, and what the application verified. A summary is a derived context object, not a new source of truth or permission.

Loading diagram…

The diagram describes a recommended application architecture. The structured ledger and validation boundary are additional application mechanisms, not automatically provided by the built-in middleware.

2. Configure SummarizationMiddleware#

Modern LangChain agents provide a summarization middleware in compatible versions. An illustrative configuration uses a summary model, a trigger and a recent-message retention policy.

PYTHON
from langchain.agents import create_agent from langchain.agents.middleware import SummarizationMiddleware from langgraph.checkpoint.memory import InMemorySaver agent = create_agent( model="openai:gpt-4o-mini", tools=[], system_prompt="Answer fictional support questions without inventing evidence.", middleware=[ SummarizationMiddleware( model="openai:gpt-4o-mini", trigger=("tokens", 4000), keep=("messages", 20), ) ], checkpointer=InMemorySaver(), ) # The host authenticates the caller and authorizes the thread first. config = {"configurable": {"thread_id": "demo-support-1"}} # agent.invoke({"messages": [{"role": "user", "content": "..."}]}, # config=config)

The model identifiers, token threshold and retention count are illustrative, not recommendations for a particular live model. In compatible modern releases, the middleware summarizes older messages when the configured trigger is met and retains a recent tail according to the keep policy. Exact trigger evaluation, counting, cut selection, summary-message representation and state-update semantics depend on the installed release.

Verification limitation: Python 3.13.5 is available locally, but langchain, langchain_core and langgraph are absent. The SDK example was not executed. The independently tested Python program in section 6 verifies structured summary acceptance, not the behavior of SummarizationMiddleware.

The middleware's configuration commonly supports trigger and retention policies expressed in tokens, messages or fractions of a model's context capacity, subject to version support and model-profile information. Check the pinned middleware documentation and actual installed signature. In particular, do not assume that a fraction-based rule works without a known context capacity.

Understand the persistence consequence#

SummarizationMiddleware can update graph message state, replacing older messages with a summary and retaining the recent tail. That differs from the previous lesson's temporary request-only override. Do not assume the current messages channel still contains the original conversation after compaction.

If exact earlier evidence is necessary for compliance, support, replay or future verification, retain it through an authorized source repository with a separate lifecycle and retention policy. Historical checkpoints may retain earlier state in some configurations, but they are not automatically a complete or indefinitely retained transcript archive. Test the actual persistence behavior.

InMemorySaver is an illustrative development checkpointer. It does not provide durable storage across process restarts. The application must manage an appropriately scoped production backend and protect both original and derived data.

3. Trigger before the next model request exceeds its budget#

A message count is convenient, but one long tool observation can be more expensive than fifty short chat messages. A token-based policy can adapt to history size, while a fraction-based policy can account for different context capacities if the model profile is accurate.

Use the effective deployed model's input allowance, not an advertised maximum in isolation. Reserve space for output, system instructions, tool definitions, response schemas, protocol overhead, retrieved evidence and a safety margin. Do not count the same component twice.

Suppose a fictional 16,000-token combined context has an output reserve of 2,000, fixed request overhead of 1,500 and a safety margin of 500. The remaining message allowance is 12,000 tokens. An application might trigger summarization at an estimated 9,000 history tokens to leave room for further tool observations. After compaction, it might aim for a 1,500-token summary plus a 3,000-token exact recent tail and enough room for the next expected step.

These figures are illustrative and do not establish provider token accounting or middleware output length. The summary call itself has a separate input and output budget. A prefix too large for the summary model must be processed in bounded, source-grounded segments or through a reviewed alternative.

Trigger designTrade-off
Message countCheap to evaluate, insensitive to message size
Estimated token countBetter size sensitivity, estimation error possible
Fraction of supported contextAdapts to model capacity if metadata is accurate
Task boundaryCan preserve coherent completed units, may need emergency admission control
Combined host policyCan consider budget and safe cut availability, but needs independent validation

A trigger is an invitation to attempt summarization, not permission to cut at an invalid boundary. If the current context contains pending tool calls or indispensable media, preserve them. If mandatory context cannot fit, narrow the task, use a reviewed compatible model configuration or return a controlled limitation.

4. Define what must survive in a structured summary#

For a long-running conversation, define a small domain-specific memory contract before generating prose. A useful contract distinguishes the following.

FieldPreservation rule
User objective and requested deliverablePreserve active objective, not an obsolete earlier task
Explicit constraintsKeep negation, scope, conditions, units and effective revisions
Entities and identifiersRetain exact IDs; never replace with guessed aliases
Verified factsPreserve claim, evidence reference, revision and relevant observation time
User assertionsPreserve source attribution; do not promote to verified facts
Decisions and correctionsPreserve decision scope, authority and supersession
Open tasksKeep unresolved work, blockers and required approvals
Conflicting evidenceRetain competing claims until an authorized resolution exists
Tool resultsRetain important domain evidence and durable operation references
Recent exact contextPreserve current request and the protocol-valid recent tail

A summary model can propose candidate facts in a structured response rather than return only unrestricted prose. The application should compare the proposed facts to a trusted fact inventory and the relevant source spans. Where exact correctness matters, keep the trusted structured fields directly and use the generated narrative as an optional convenience.

For example, the record for a verified order status can include a stable fact ID, the field being described, its value, the source message or tool operation reference, source revision and observation time. The narrative can say "Order O-1 is reported shipped," but the application should not depend on that sentence for exact identifier matching or evidence retrieval.

Provenance is more than attaching an arbitrary citation string. The reference must resolve to an authorized source that actually supports the claim. Store immutable source revision identifiers where possible. A source may be stale or have been deleted or access-revoked; recheck relevant current access and freshness before relying on it.

Keep application system instructions separate. A summary of earlier user or tool text must not become a privileged instruction simply because it is injected into a model context by trusted middleware. If a framework uses a particular summary-message role, inspect how the adapter serializes that role and ensure the summary is treated as conversation-derived data rather than new policy.

5. Maintain rolling summaries without amplifying errors#

A rolling summary incorporates newly completed conversation segments into an earlier compact representation. Re-summarizing the previous narrative alone can compound omissions and substitutions.

Consider a constraint originally stated as "Do not make any changes unless I explicitly confirm the proposed change." The first summary might omit "explicitly"; the second might omit the condition entirely. Repeated generation can alter the requirement even when no new instruction was issued.

A better update sequence is:

  1. Identify a completed source interval and its immutable revision.
  2. Load the prior accepted structured summary, authoritative required facts and the new authorized source events.
  3. Generate a candidate compact narrative or structured summary.
  4. Independently compare critical fields and provenance to the authoritative inventory.
  5. Activate the candidate only if the source revision and cut remain current.
  6. Preserve the exact recent messages and the last accepted version according to policy.
Loading diagram…

The validator must not derive its expected facts exclusively from the candidate. That would make its acceptance circular. Periodically compare the derived representation with original authorized sources rather than relying only on prior summaries. The ideal frequency depends on the task, source access and cost.

Resolve corrections explicitly#

An earlier status of pending and a later status of shipped may be compatible observations at different times. Alternatively, the two claims might genuinely conflict. Model the domain's temporal and authority semantics: observation time, effective time, source priority, source version and explicit correction when applicable.

Do not automatically prefer the most recent textual claim. A recent user assertion may not override a trusted service observation. Conversely, an authorized user correction of their preference may supersede the prior preference. Define the scope and authority for each type of update.

A practical conservative rule is to keep both observations while a discrepancy remains unresolved. Only an authorized source or reviewed policy can supersede one. A summary should say "conflicting evidence, confirmation pending" rather than claim a resolution.

6. Tested Python: validate a structured rolling summary#

The following standalone program uses an immutable synthetic fact ledger. A candidate must contain exactly the active required facts and conflict markers at the proposed prefix boundary. Supersession is explicit. The program deliberately avoids model calls: it tests the acceptance contract against independently supplied canonical records, not the quality of automatic extraction or summarization.

PYTHON
from dataclasses import dataclass, replace from collections import defaultdict import sys, importlib.util @dataclass(frozen=True) class Fact: id: str key: str value: str source: str supersedes: tuple[str, ...] = () @dataclass(frozen=True) class Summary: through: int facts: tuple[Fact, ...] conflicts: tuple[str, ...] class Rejected(Exception): pass def expected(ledger, through): active = {} seen = set() for f in ledger[:through]: if f.id in seen or not f.source: raise Rejected('invalid ledger') seen.add(f.id) for old in f.supersedes: if old not in active or active[old].key != f.key: raise Rejected('invalid supersession') del active[old] active[f.id] = f by_key = defaultdict(set) for f in active.values(): by_key[f.key].add(f.value) return Summary(through, tuple(sorted(active.values(), key=lambda f:f.id)), tuple(sorted(k for k,v in by_key.items() if len(v)>1))) def validate(candidate, ledger, through, *, previous, safe_cut): if not safe_cut or type(through) is not int or not previous <= through <= len(ledger): raise Rejected('unsafe or stale cut') target = expected(ledger, through) if candidate != target: raise Rejected('missing, changed or unsupported facts') return target def rejects(fn): try: fn() except Rejected: return raise AssertionError('expected rejection') ledger = ( Fact('f1','constraint','no writes','m1'), Fact('f2','order','O-1','m2'), Fact('f3','task','open','m3'), Fact('f4','status','pending','tool:c1'), Fact('f5','status','shipped','tool:c2'), Fact('f6','status','shipped','tool:c3',('f4','f5')), Fact('f7','task','done','m7',('f3',)), ) s1=expected(ledger,4); s2=expected(ledger,5); s3=expected(ledger,7) assert validate(s1,ledger,4,previous=0,safe_cut=True)==s1 assert s2.conflicts==('status',) assert {f.id for f in s2.facts}=={'f1','f2','f3','f4','f5'} assert s3.conflicts==() and {f.id for f in s3.facts}=={'f1','f2','f6','f7'} assert validate(s3,ledger,7,previous=5,safe_cut=True)==s3 rejects(lambda:validate(replace(s2,facts=s2.facts[1:]),ledger,5,previous=4,safe_cut=True)) rejects(lambda:validate(replace(s2,conflicts=()),ledger,5,previous=4,safe_cut=True)) rejects(lambda:validate(replace(s2,facts=tuple(replace(f,value='write allowed') if f.id=='f1' else f for f in s2.facts)),ledger,5,previous=4,safe_cut=True)) rejects(lambda:validate(replace(s2,facts=tuple(replace(f,source='fake') if f.id=='f4' else f for f in s2.facts)),ledger,5,previous=4,safe_cut=True)) rejects(lambda:validate(replace(s2,facts=s2.facts+(Fact('f9','approval','yes','fake'),)),ledger,5,previous=4,safe_cut=True)) rejects(lambda:validate(s2,ledger,5,previous=4,safe_cut=False)) rejects(lambda:validate(s1,ledger,4,previous=5,safe_cut=True)) rejects(lambda:validate(s1,ledger,8,previous=0,safe_cut=True)) rejects(lambda:expected(ledger+(Fact('f8','order','O-2','m8',('f1',)),),8)) rejects(lambda:expected(ledger+(ledger[0],),8)) assert expected(ledger,7)==s3 and len(ledger)==7 print('16 checks passed') print(sys.version.split()[0], {p:importlib.util.find_spec(p) is not None for p in ['langchain','langchain_core','langgraph']})

Actual execution output from the local Python runtime:

16 checks passed
3.13.5 {'langchain': False, 'langchain_core': False, 'langgraph': False}

Interpret the results#

TestVerified behavior
Initial valid prefixAccepted
Two competing status valuesConflict explicitly retained
Active record inventoryOriginal constraint, order, task and both status observations retained
Explicit status and task supersessionActive facts changed only as recorded
Valid subsequent summaryAccepted
Missing required factRejected
Missing conflict markerRejected
Changed no-write constraintRejected
Changed evidence sourceRejected
Fabricated approvalRejected
Unsafe cutRejected
Regressive boundaryRejected
Boundary beyond source ledgerRejected
Supersession across unrelated keysRejected
Duplicate fact identityRejected
Repeated reconstructionSame summary and unchanged ledger

At boundary 5, both status records survive, and the open task remains. At boundary 7, the authoritative correction explicitly supersedes both competing status observations and the completion record supersedes the open task. The immutable source ledger still retains all seven events.

This code assumes a trusted host has already extracted and authorized every required fact, classified genuine conflicts, and established which records can supersede others. A source string is not independently dereferenced; the equality check rejects a changed source relative to the trusted inventory. The synthetic record position is not a graph checkpoint ID or a real message offset. The safe_cut flag is a trusted verdict supplied by a separate protocol validator. Its false case is tested, but detection of incomplete LangChain tool exchanges is not implemented here.

The positive candidates are constructed from the deterministic expected inventory, not from actual LLM output. Negative candidates simulate omissions, altered facts and fabricated additions. The test proves exact field preservation for this narrow inventory, not natural-language entailment, extraction recall, real conflict resolution, data access control, chronological truth or model behavior. A real implementation should scope records by authorized conversation and entity, validate IDs, timestamps and revisions, distinguish source types and separately evaluate free-text claims.

The exact-equality policy intentionally treats ordering of the fact tuple as part of the canonical representation. A consumer that allows different ordering can normalize both sides safely before comparing. The current example rebuilds from the ledger prefix on each validation; for large records, an indexed verified materialized view can reduce work, with periodic source reconciliation. Do not replace the authoritative inventory with an unverified generated summary merely to save computation.

7. Preserve recent messages and tool-call consistency#

A summary of a tool exchange is not a valid substitute for the original protocol messages when the model is still waiting for observations. An AI message that proposes a tool call and the corresponding ToolMessage form a correlated unit. A cut between them can create an orphan response or an unanswered proposal.

Loading diagram…

Treat the exact tool-call sequence as indivisible for the current operation. Preserve the relevant assistant proposal and all required results with their call IDs. At a valid completed turn boundary, older exchanges may be summarized into domain facts and source references when the provider and graph contract permit it. Never fabricate a ToolMessage from a narrative summary to recreate an operation that did not run.

A recent-message retention count is a target, not a proof of protocol consistency. Test actual middleware behavior near tool boundaries: it may retain more or different messages than a naive count suggests. Inspect the effective provider request, especially after parallel tool calls and multiple rounds of model/tool activity.

A checkpoint can represent an interrupted turn. Do not summarize away required approval, an unresolved tool result or an ambiguous external commitment and then treat the task as completed. Reconcile the operation through the authoritative service. A summary never rolls back a mutation.

8. Compose the next context and verify the full request#

There are four useful conceptual components in the next request:

ComponentTreatment
Effective system instructionsStable approved policy, not regenerated from user text
Historical summaryDerived context, clearly separated from policy
Protected fact/evidence projectionTrusted required values and source references, scoped to current task
Recent exact tailCurrent request and complete relevant message exchanges

Avoid duplication when a fact appears in both the summary and the recent tail. The exact messages remain the better source for recent wording; a structured projection should make explicit which source revisions it describes. Do not erase original messages merely to deduplicate a temporary prompt.

In production, the built-in middleware may be suitable for conversational tasks where a generated summary is an acceptable context optimization. For critical workflows, use a separately validated structured fact projection and, if necessary, a custom application-controlled summarization and activation path. A built-in free-form summary is not automatically validated by the Python acceptance program. Integrate that validation explicitly before using it as a trusted derived view.

A compatible model-call middleware can add a bounded approved fact projection to the next request. The exact implementation depends on the pinned ModelRequest and state APIs. Do not have two middleware components independently discard or duplicate the same context. Verify their composition, count the final serialized request, and ensure the active summary and exact tail refer to the same source revision.

9. Evaluate summary quality across multiple turns#

A one-turn summarization example can miss degradation that appears only after many update cycles. Test both extraction and downstream task performance using conversations with independently established answer keys.

Build a dataset containing exact identifiers, numerical constraints, conditional instructions, corrected facts, conflicting observations, unresolved tasks and completed tool operations. Vary the location of essential information: near the start, in the middle, immediately before the cut and in the recent tail.

MetricDefinition or purpose
Critical-fact recallRequired canonical facts retained divided by required facts in the evaluation
Unsupported-claim rateUnsupported generated claims divided by evaluated generated claims
Provenance accuracyClaims whose cited authorized source supports them divided by checked cited claims
Constraint preservationActive constraints retained with their conditions and negation
Open-task recallUnresolved required tasks retained without false completion
Conflict preservationUnresolved conflicts represented rather than silently resolved
Downstream verified successTasks completed under the same evidence and policy acceptance gate
Compression ratioOriginal context size divided by compacted context size, using consistent measurement
End-to-end cost and latencyInclude summary generation, validation, retrieval and downstream retries

For a hypothetical evaluation, a summary reduces 8,000 history tokens to 2,000, a 4:1 compression ratio. If it retains 47 of 50 required facts, its fact recall is 94%. If any of the three omissions is a mandatory permission restriction or unresolved approval, the candidate fails even though aggregate recall looks high. These numbers are illustrative, not benchmark results. Critical constraints should have a stricter gate than optional conversational details.

Evaluate repeated rolling updates, not just isolated summaries. Compare full-history baselines on tasks that fit, trimming-only baselines, built-in summarization and structured fact-preserving designs. Keep the model revision, workload, evidence requirements and task scoring controlled where possible.

Loading diagram…

10. Production failure cases and operational safeguards#

Failure fixtureExpected behavior
Trigger reached within a pending tool exchangeDelay cut or preserve the whole required exchange
Summary omits user restrictionReject activation
Summary changes currency, amount or identifierReject altered canonical fact
Summary claims approval without sourceReject unsupported claim
Competing observationsPreserve uncertainty until reviewed resolution
User correctionApply explicit authorized supersession
Summary model timeoutKeep last valid view; do not drop original evidence
Oversized mandatory contextControlled failure or approved alternative
New messages arrive during generationValidate against intended source version; do not overwrite newer state
Repeated summarizationTest cumulative drift against original authorized records
Revoked evidence accessExclude or rebuild affected derived context according to policy
Provider or middleware upgradeRecheck trigger, retained tail, state update and actual request behavior

Keep a stable summary-policy version, source revision, cut reference, model profile, validator revision and normalized outcome in telemetry. Track summary frequency, candidate rejection categories, estimated and actual context size, correction attempts and downstream task acceptance. Do not log complete private conversations or raw evidence by default.

Summaries can retain sensitive data long after original messages have left the active context. They require the same authorization, purpose limitation, retention and deletion considerations as their source. If evidence is revoked or deleted, invalidate dependent derived summaries as appropriate; a valid summary at creation time is not perpetual permission to use that information.

If summarization fails, do not automatically fall back to an oversized full-history request. Reuse an approved previous summary only if it still covers the needed state, preserve recent exact messages, and recheck the budget and evidence sufficiency. Otherwise recover the required authorized evidence, choose an approved compatible context configuration or return a controlled limitation.

Interview-ready answer#

I use SummarizationMiddleware in a compatible LangChain agent to compact older conversation history when a reviewed token or message threshold is reached, while retaining a recent exact tail. For critical workflows I maintain a structured fact inventory containing user constraints, identifiers, evidence references, unresolved tasks and explicit corrections. I validate each candidate against authorized source records rather than trust the previous summary's prose. I preserve complete tool exchanges, distinguish conflicting observations from resolved facts, and activate only a revision-consistent candidate. I measure fact and constraint retention and downstream verified success across repeated summary updates, not just token savings.

Official documentation research leads and verification status#

Authorized offline research exception applied. These documentation URLs are research leads, not live-accessed citations. The exact standalone program was actually run in the local Python 3.13.5 environment and printed 16 checks passed. Package inspection confirmed that langchain, langchain_core and langgraph are absent. The SDK configuration, exact middleware trigger and retention semantics, actual tool-cut detection, provider token accounting, model-generated summary quality, production persistence and public website rendering were not executed or verified. The tests use synthetic structured facts and a trusted safe-cut verdict, not an LLM-generated summary or an actual conversation archive. Mermaid diagrams use standard triple-backtick fences; rendering was not tested.

References

  1. 1.
    LangChain short-term memorydocs.langchain.com
  2. 2.
  3. 3.
  4. 4.
  5. 5.
    LangChain messagesdocs.langchain.com
  6. 6.
    LangGraph persistencedocs.langchain.com
  7. 7.
    LangChain API referencereference.langchain.com
  8. 8.
    Python dataclassesdocs.python.org

Related questions

Explore other topics:Forward Deployed EngineeringLarge Language ModelsRetrieval-Augmented GenerationMLOps

Machinoai Logo
Machinoai

Your edge in the AI era. Deep dives into machine learning concepts, paper explainers, verified industry jobs, and developer tools.

© 2026 Machinoai. All rights reserved.