AI AgentsLangChain

How do you trim message history before model calls?

Question 309 of 324 · Updated

On this page

Direct answer#

Use LangChain's trim_messages utility with a token counter and a maximum message budget, normally with strategy="last" for conversational agents. Preserve required instructions and the current task, enforce valid message boundaries, and pass the trimmed list to the model rather than deleting messages from the authoritative conversation state. For tool-enabled agents, additionally preserve complete tool exchanges and verify the final provider request.

A production history projection must fit the selected model's usable context budget without silently losing mandatory evidence. A token-counting utility can enforce a size target, but does not establish that a shortened conversation remains semantically sufficient or that every provider accepts its tool-call sequence.

Source question #25 (AI Agents #305) covers history persistence; #26–28 cover message representation, roles and media. AI Agents #227–236 address multi-agent memory compaction, and the context-window lessons in LLM and FDE cover general budgeting. This lesson focuses on LangChain trim_messages and non-destructive per-model-call history projection, including protocol-valid cut boundaries. Summarization and short-term memory management are subsequent lessons.

1. Distinguish stored history from the next model input#

A conversation thread may retain hundreds of messages, while a particular model call needs only a relevant, valid subset. The stored state is the source of record for the graph; the model-facing projection is a temporary view.

Consider a fictional support agent. It previously discussed an unrelated order, then looked up the status of O-1, and now receives a follow-up about O-1. Removing the unrelated completed turn may be reasonable. Removing the exact lookup result needed to substantiate the follow-up is not.

RepresentationPurposeTrimming implication
Authoritative conversation stateContinue and inspect executionDo not mutate merely to reduce the next prompt
Model-facing historyProvide context for this inferenceSelect a bounded valid view
System instructionsApplication-defined constraintsPreserve the approved effective instruction channel
Current task and required evidenceEstablish what can be answeredMandatory; fail or choose an approved alternative if they do not fit
Old completed turnsOptional continuityRemove only when their omission is acceptable
Tool-call groupPreserve proposal and correlated resultsKeep or remove as a coherent unit
Loading diagram…

The diagram is an application design. It does not imply that the trimming operation changes the checkpointer, commits a state update or implements a provider's exact request format.

2. Use trim_messages for a simple conversation#

The common modern LangChain interface exposes trim_messages through langchain_core.messages or its utility module. The following is illustrative SDK code using text-only messages and the approximate counter.

PYTHON
from langchain_core.messages import ( SystemMessage, HumanMessage, AIMessage, ) from langchain_core.messages.utils import ( trim_messages, count_tokens_approximately, ) history = [ SystemMessage(content="Answer fictional support questions using verified evidence."), HumanMessage(content="Explain the return policy."), AIMessage(content="The fictional policy allows a review request."), HumanMessage(content="Now check order O-1."), ] view = trim_messages( history, max_tokens=120, token_counter=count_tokens_approximately, strategy="last", include_system=True, start_on="human", end_on=("human", "tool"), allow_partial=False, )

The intended output is a list fitting the supplied counter's allowance, retaining a leading system message where supported and feasible, and ending at an approved role boundary. The exact retained messages depend on the counter, utility version and contents. This example does not promise that the latest question always fits. Validate that the required current task and effective instruction survived.

Verification note: The local environment has Python 3.13.5 but does not have langchain, langchain_core or langgraph installed. SDK examples are illustrative and unexecuted. The standalone whole-turn projection in section 7 was actually executed and passed 16 checks. Confirm imports, argument semantics and counter behavior against the pinned release before use.

Important parameters#

ParameterIntended purpose
messagesInput sequence of supported message objects
max_tokensAllowance measured by the selected token counter
token_counterA supported model/token counter or callable
strategySelect from the beginning or end of the history
include_systemWith the last strategy, retain a leading system message when feasible
start_onWith the last strategy, restrict the start of the retained non-system sequence
end_onRestrict the allowed ending message type
allow_partialPermit supported splitting of a message when configured
text_splitterSpecify a supported text-splitting mechanism for partial trimming

The utility may also be configured as a reusable runnable by omitting the input messages and later invoking it with messages, in compatible versions. Do not assume every parameter combination is supported. For example, start_on and include_system are associated with the last strategy in common implementations. Confirm the actual installed signature and semantics.

3. Select first or last intentionally#

A first strategy retains an initial portion of the message sequence. It may be suitable when a workload needs the opening passage or first part of a bounded historical record. It is usually not the right default for a live conversational turn because it can omit the latest request.

A last strategy retains a recent portion. It is often appropriate for ordinary conversation, but recency is not evidence relevance. An old user constraint or verified observation may still be necessary for the current task.

StrategyStrengthMain risk
firstPreserves opening contextDrops recent question or recent correction
lastPreserves recent conversationDrops old constraints or evidence
Whole-turn suffixAvoids arbitrary cuts in complete exchangesMay retain fewer tokens than possible
Required-evidence-aware projectionProtects explicitly identified evidenceRequires trusted dependency tracking and protocol checks

The first and last strategies are not semantic retrieval or summarization algorithms. They do not independently decide that a message is irrelevant. If critical context would be omitted, use an explicitly reviewed alternate such as retrieving the authorized source evidence again, choosing a compatible larger context, or narrowing the task. The next lesson covers summarization; it is not part of this trimming utility.

System-message preservation#

include_system=True is useful when the message list begins with a SystemMessage and the selected utility supports this option. It does not guarantee that an oversized system message can fit together with the current user request.

In create_agent, the system instruction may be supplied through system_prompt and represented separately from the request's messages. Do not blindly prepend the same instruction to the messages a second time. Account for the effective system channel in the final request and ensure that your trimming operation does not remove or duplicate it.

A user-provided string resembling a system message is still untrusted user content. Never promote it to a system instruction to make it survive trimming.

4. Compute a realistic history budget#

The maximum model context is not the history budget. For a provider with a combined input/output context limit, a conservative planning equation is:

History allowance = context limit - reserved output/reasoning allowance - effective instructions - tool and response-schema metadata - other current inputs - protocol overhead - safety margin.

Allocate each component exactly once. If the current user message is already in the history list to be trimmed, count it inside that list and protect it as mandatory, rather than subtracting it twice. If it is sent separately, subtract its cost from the remaining history allowance.

Some providers expose separate input/output limits and account for reasoning or media differently. Use their actual contract and the effective deployment limits rather than assuming the above equation is universal.

Worked example#

Suppose a fictional deployment has a combined 8,192-token planning limit. The system instruction is separate from the messages list, while the current user request is part of that list.

ComponentIllustrative tokens
Combined limit8,192
Output/reasoning reserve1,024
System instruction350
Tool and response schema metadata800
Other separately supplied evidence400
Serialization overhead and safety margin418
Remaining messages allowance5,200

The 5,200-token allowance includes the latest user message and any intermediate tool messages that must remain visible. If the mandatory current exchange costs 1,600 tokens, at most 3,600 remain for optional history. These are constructed values, not a measured provider limit or measured token usage.

Choose the token counter#

A compatible LangChain model can often be used as a token counter through its get_num_tokens_from_messages support. A callable such as count_tokens_approximately can offer a faster approximate count when supported. A simple message-count policy can also use len as a counter, but then max_tokens is actually a message-count allowance, not a token limit.

PYTHON
# Illustrative: model is the already approved compatible chat model. view = trim_messages( history, max_tokens=5200, token_counter=model, strategy="last", include_system=True, start_on="human", allow_partial=False, )

Do not assume a model integration's token-counting method accounts exactly for tool definitions, native structured-output settings, media, protocol framing or provider-specific serialization. Approximate counting is useful for early admission and fast repeated selection. For the final request, use a supported provider-aware counter or conservative bound and reserve a margin calibrated against observed usage.

A word count is not a model tokenizer. Character heuristics can differ across languages, code, identifiers and punctuation. Cached input tokens may be billed differently, but caching does not necessarily remove those tokens from the context constraint.

5. Respect start_on, end_on and partial-message behavior#

For the last strategy, start_on="human" can help avoid beginning the non-system history with a tool result or a stray assistant reply. A leading retained system message is handled separately in the supported include_system case.

With end_on=("human", "tool"), the retained history is constrained to end at one of those types, useful for a simple next-model-call policy. In common implementations the end_on filtering is applied before last-strategy trimming, and start_on is applied after choosing the suffix. Verify the release's exact behavior. Neither option understands all provider-specific message rules or validates tool-call cardinality.

In particular, end_on can remove trailing messages that are not an allowed type. Do not use it as a substitute for knowing whether the current graph is ready to call the model. If an agent is waiting for a tool result, do not trim off the pending AI proposal and invoke the model again as though nothing happened. Resolve the runtime state first.

Partial messages#

allow_partial=True can retain a fragment of a message using supported splitting behavior. This may be useful for a long text passage when the task tolerates truncation. It is risky for:

  • JSON arguments and structured response objects.
  • Tool results that include multiple related fields or evidence references.
  • Code, tables and quoted constraints.
  • Images, audio and other indivisible or provider-specific blocks.
  • User instructions whose meaning changes when a qualifying sentence disappears.

For example, keeping only "approve the request" from "Do not approve the request until a reviewer confirms it" reverses the original meaning. Do not split safety constraints or necessary evidence merely to squeeze into a budget.

Keep allow_partial=False for general tool-enabled conversation history unless a particular message class and text transformation have an explicitly reviewed policy. If a required message is too large, report overflow or use an approved task-preserving transformation with provenance.

6. Preserve tool-call and tool-result consistency#

A completed agent turn can contain a user question, an AI message with two calls, two ToolMessages, and a final AI response. A naive suffix could retain only the last ToolMessage, leaving no originating call visible to the provider.

Loading diagram…

The illustrated tool results arrive in a different order than the proposed IDs. Correlation, not position, determines which result belongs to which call. Actual provider ordering and grouping constraints must be checked separately.

A safe whole-turn policy preserves the complete current user turn and chooses a contiguous suffix of preceding complete turns. Before a model call following tool execution, the current turn can end with the complete set of required tool observations. It must not have unresolved pending call IDs.

Required invariants for this deliberately conservative policy:

  • A retained tool result must have its corresponding retained originating AI proposal.
  • A retained proposal must have all required correlated results before the next model call.
  • No repeated or unknown result IDs are accepted.
  • Preserve the approved original ordering and role boundaries.
  • If required evidence is lost by cutting older turns, stop rather than claim the projection is sufficient.

The actual runtime may support more complex sequences, including multiple user messages, interrupted graphs and special provider-generated messages. A conservative whole-turn parser must reject unsupported sequences rather than repair them by fabricating observations.

7. Tested Python implementation: whole-turn, non-destructive projection#

This standalone implementation operates on immutable teaching fixtures with preassigned message-cost estimates. It is not a LangChain tokenizer, message class or implementation of trim_messages. Its purpose is to test whole-turn selection, evidence preservation and tool-call integrity independently.

PYTHON
from dataclasses import dataclass import sys, importlib.util class BudgetError(Exception): pass class SequenceError(Exception): pass @dataclass(frozen=True) class Msg: id: str role: str cost: int calls: tuple[str, ...] = () reply: str | None = None def groups(messages): turns=[]; pending=set(); seen=set(); ids=set() for m in messages: if m.id in ids or type(m.cost) is not int or m.cost < 0: raise SequenceError('invalid identity or cost') ids.add(m.id) if m.role != 'assistant' and m.calls or m.role != 'tool' and m.reply is not None: raise SequenceError('invalid fields') if m.role == 'user': if pending or (turns and (turns[-1][-1].role != 'assistant' or turns[-1][-1].calls)): raise SequenceError('unfinished prior turn') turns.append([m]) continue if not turns: raise SequenceError('missing user') if m.role == 'assistant': if pending or turns[-1][-1].role == 'assistant': raise SequenceError('invalid assistant boundary') if len(set(m.calls)) != len(m.calls) or seen.intersection(m.calls): raise SequenceError('duplicate call') pending.update(m.calls); seen.update(m.calls) elif m.role == 'tool': if m.reply not in pending: raise SequenceError('orphan or duplicate result') pending.remove(m.reply) else: raise SequenceError('unexpected role') turns[-1].append(m) if pending or not turns or turns[-1][-1].role not in ('user','tool'): raise SequenceError('not ready for next model call') return tuple(tuple(t) for t in turns) def project(messages, budget, *, required=frozenset()): if type(budget) is not int or budget < 0: raise BudgetError('invalid budget') if not messages or messages[0].role != 'system': raise SequenceError('missing system') system=messages[0] if type(system.cost) is not int or system.cost < 0 or system.calls or system.reply is not None: raise SequenceError('invalid system') if any(m.id == system.id for m in messages[1:]): raise SequenceError('duplicate ID') turns=groups(messages[1:]) chosen=[turns[-1]] used=system.cost+sum(m.cost for m in chosen[0]) if used>budget: raise BudgetError('required context too large') for t in reversed(turns[:-1]): cost=sum(m.cost for m in t) if used+cost>budget: break chosen.append(t); used+=cost result=(system,)+tuple(m for t in reversed(chosen) for m in t) if not required.issubset({m.id for m in result}): raise BudgetError('required evidence trimmed') return result, used s=Msg('s','system',20); u1=Msg('u1','user',10); a1=Msg('a1','assistant',15) u2=Msg('u2','user',10); c=Msg('c','assistant',15,('x','y')); y=Msg('y','tool',20,reply='y'); x=Msg('x','tool',20,reply='x'); a2=Msg('a2','assistant',10); u3=Msg('u3','user',10) h=(s,u1,a1,u2,c,y,x,a2,u3) def reject(kind,fn): try: fn() except kind: return raise AssertionError('expected rejection') assert project(h,130)==(h,130) assert project(h,105)==((s,u2,c,y,x,a2,u3),105) assert project(h,104)==((s,u3),30) assert project(h,30)==((s,u3),30) assert h==(s,u1,a1,u2,c,y,x,a2,u3) reject(BudgetError,lambda:project(h,29)) reject(BudgetError,lambda:project(h,105,required={'u1'})) assert project(h,105,required={'x'})[1]==105 reject(SequenceError,lambda:project((s,u2,c,y),200)) reject(SequenceError,lambda:project((s,u2,y),200)) reject(SequenceError,lambda:project((s,u2,c,y,y),200)) assert project((s,u2,c,y,x),85)==((s,u2,c,y,x),85) reject(SequenceError,lambda:project((s,u2,c,y,u3),200)) reject(SequenceError,lambda:project((s,u1,a1,u1),200)) reject(BudgetError,lambda:project(h,-1)) assert project((s,Msg('media','user',80)),100)[1]==100 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 local execution:

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

Worked trace and test interpretation#

SegmentFixture cost
Leading system instruction20
Old turn u1, a125
Tool-enabled turn u2, c, y, x, a275
Current question u310
Full history130

With budget 105 the current question, leading system instruction and entire most recent completed tool-enabled turn fit exactly. The oldest completed turn is omitted. At budget 104 the 75-cost group no longer fits, so the strict suffix policy retains only the leading system instruction and current question at cost 30. It does not jump backward to add the older 25-cost turn, even though that would fit: the implementation intentionally chooses a contiguous suffix.

The tests establish:

CaseObserved result
Full budgetEntire history retained
Budget 105Most recent complete tool turn retained
Budget 104Whole tool turn omitted, never sliced
Budget 30Mandatory system and user retained
Non-destructive selectionOriginal tuple unchanged
Budget 29Mandatory context overflow
Required older evidence removedBudgetError
Required retained observationAccepted
Missing resultSequenceError
Orphan tool resultSequenceError
Repeated observation fixtureSequenceError
Current complete batch ending in toolAccepted
New user during incomplete batchSequenceError
Duplicate message IDSequenceError
Negative budgetBudgetError
Preassigned media costIncluded in admission calculation

The repeated-observation fixture also repeats a message ID, so it does not isolate the duplicate-call-result check independently from the duplicate-ID check. The implementation contains both checks; a production test should use two distinct message IDs for repeated observations of the same call. The media test verifies only the arithmetic of an assigned cost, not image or audio token estimation. No SDK, provider, model inference or actual media accounting was executed.

The teaching parser accepts a deliberately narrow conversation protocol: one initial system message, user-started turns, completed prior turns and a current turn ending in user or complete tool results. It rejects unsupported boundaries. It assumes trusted, validated string IDs, immutable tuple fields and finite sequences; dataclass annotations do not enforce all those types automatically. It validates neither actual tool schemas nor permissions, and its costs are synthetic additive estimates. Provider counting may be nonadditive, so a production implementation must measure the final request. The algorithm traverses the input history and selects recent groups in linear time under ordinary hash-set assumptions. It intentionally sacrifices utilization rather than split a group or skip an intermediate turn. It does not implement relevance retrieval, summarization or state compaction.

8. Integrate trimming as a model-call middleware#

A compatible modern LangChain agent can use wrap_model_call to modify the next ModelRequest without changing the underlying state. The following illustrates a simple text-only setup with no business tools.

PYTHON
from langchain.agents import create_agent from langchain.agents.middleware import wrap_model_call from langchain_core.messages.utils import ( trim_messages, count_tokens_approximately, ) @wrap_model_call def bounded_history(request, handler): # Illustrative allowance established for this deployment, # after reserving the separate effective system instruction. budget = 1200 selected = trim_messages( request.messages, max_tokens=budget, token_counter=count_tokens_approximately, strategy="last", start_on="human", end_on="human", allow_partial=False, ) if not selected or not request.messages or selected[-1] != request.messages[-1]: raise ValueError("Current user message does not fit") # This illustrative profile supports ordinary user/assistant text only. return handler(request.override(messages=selected)) agent = create_agent( model="openai:gpt-4o-mini", tools=[], system_prompt="Answer fictional support questions using supplied context.", middleware=[bounded_history], )

This SDK snippet is unexecuted. The model identifier is illustrative. It assumes an approved text-only configuration, a current user message and a separately managed system instruction. Verify the actual ModelRequest fields, override API, system-message handling and middleware ordering in the pinned version. The simple guard checks that the current message survived; it is not a full evidence dependency check. It is not suitable unchanged for a tool-enabled agent or provider that requires additional message ordering.

In a tool-enabled deployment, use an appropriate grouping and validation adapter around the actual message types, preserve complete tool exchanges and account for the effective tool catalog on each request. Ensure later middleware does not reinsert oversized history or add metadata beyond the budget. For async agent execution, verify the supported asynchronous middleware interface.

Do not return state updates containing the trimmed list merely to control model context. Depending on the graph reducer, such updates may append, replace or remove messages differently from what you expect. Destructive graph-message removal and durable compaction are distinct mechanisms, with separate retention and recovery requirements.

Loading diagram…

9. Account for multimodal inputs and dynamic metadata#

As discussed in source question #28, a Base64-encoded media payload's string length is not a reliable model-token count. The provider may process image tiles, audio duration, sampled video frames or document pages separately. A text-only approximate counter may underestimate their true cost or overestimate a serialized representation.

For each deployed model, verify how the selected token counter treats media, including reference forms. Enforce both context allowance and independent raw/decoded media limits. Preserve the current task's required media blocks as a unit; do not drop the image and then claim it was inspected. If an old asset remains essential, retrieve the authorized original revision or a reviewed equivalent representation under the appropriate disclosure policy.

The final request's metadata can vary between model calls. Dynamic tool filtering, a different response schema or a model switch changes the available history allowance. Recalculate the budget after those choices or reserve a conservative upper bound. A larger model context window does not automatically make a larger request compatible with tool schemas, provider limits or privacy policy.

10. Production tests and release gates#

Test the actual utility and provider adapter in a pinned environment separately from the application projection. Use deterministic fixture messages and approved synthetic live requests.

TestAcceptance requirement
first and last strategiesActual retained boundaries match expected behavior
start_on and end_onNo unsupported starts or unintended current-task removal
System instructionEffective instructions retained exactly once
Full current exchangeRequired question, proposal and all results remain
Partial trimmingOnly approved text fragments permitted; no split tool or media objects
Tiny or zero budgetControlled overflow or documented empty result, never a false answer
Tool-call groupNo orphan, duplicate or missing result; correct provider ordering
Required old evidencePreserved or explicit controlled failure
Non-destructive projectionOriginal state and checkpoint remain unchanged by selection
Multimodal requestActual supported accounting and media limits checked
Dynamic tool/model profileAllowance recomputed for effective configuration
Final serialized requestFits deployed limits, including metadata and reserve
Concurrent sessionsNo shared mutable projection or cross-thread content
Regression evaluationEvidence-supported task success remains acceptable

Track estimated and observed input usage, selected versus stored message counts, dropped turns, budget overflow, provider context-limit errors, missing-evidence failures, tool-sequence errors and latency. Avoid logging full private history or raw media. Compare with a full-history baseline on tasks that fit, including cases where earlier decisions matter. Optimize cost per verified successful task rather than dropped-token count alone.

When the budget cannot contain required context, never silently lower the output reserve or weaken instructions below the approved minimum. Choose an approved larger-context profile, narrow the task, recover specific authorized evidence, or return a controlled incomplete result. Summarization is a separate, explicitly evaluated strategy.

Interview-ready answer#

I use trim_messages with a deployment-appropriate token counter and usually the last strategy, preserving the effective system instructions and the current task. I reserve space for output, tool metadata, response schemas and other input before calculating the history allowance. I use start_on and end_on as supported boundary controls and avoid partial trimming of structured tool or media messages. For agents, I preserve complete correlated tool exchanges and check required evidence separately, then pass a temporary validated subset through model-call middleware without destructively editing checkpointed history. I verify the actual serialized provider request and test semantic task success as well as context fit.

Official documentation research leads and verification status#

Authorized offline research exception applied. These official documentation URLs are research leads, not live-accessed citations. The exact standalone program ran on Python 3.13.5 and passed all 16 checks. LangChain, langchain_core and langgraph were absent; the actual trim_messages API, token counters, middleware, provider message conversion and multimodal accounting were not executed or version-verified. No real model, provider, customer data or media was used. Mermaid diagrams use triple-backtick fences; rendering and public website display were not tested.

References

  1. 1.
    LangChain messagesdocs.langchain.com
  2. 2.
    LangChain short-term memorydocs.langchain.com
  3. 3.
  4. 4.
  5. 5.
    LangChain modelsdocs.langchain.com
  6. 6.
    LangChain API referencereference.langchain.com
  7. 7.
    LangGraph persistencedocs.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.