Skip to content

Detailed interpretation of LangGraph message filtering and clipping ​

📚 Overview ​

This document explains in detail the Message Filtering and Message Trimming technologies in LangGraph. These two technologies are the core skills for building long-term memory chatbots, helping us to efficiently manage conversation history and avoid token waste and delay problems.

In practical applications, chatbot conversations may last for a long time, and if all historical messages are passed to the LLM without control, it will lead to:

  • Token cost soars: pass full history on every call
  • Increased response latency: LLM needs to handle a lot of context
  • Context window overflow: Exceeded model's maximum token limit

This tutorial will show you three solutions to help you manage conversation state gracefully.

🎯 Core Concept ​

Challenges of message management ​

In the long-running conversation, the core questions we face are:

用户: Hi
Bot: Hi! How can I help?
用户: I'm researching whales
Bot: Great! Tell me more.
用户: What are other ocean mammals?
Bot: [这里需要完整上下文吗?]
用户: Tell me about dolphins
Bot: [还需要第一轮对话吗?]
... (100 轮对话后)
用户: What's the weather?
Bot: [需要前面 99 轮对话吗?❌]

Comparison of three solutions ​

SolutionPrincipleModify statusApplicable scenarios
RemoveMessageRemove old messages from status✅ YESPermanently delete unwanted history
Message FilteringPass a subset of messages to LLM❌ NoKeep full history, but limit LLM visibility
Message clippingIntelligent truncation based on the number of tokens❌ NoPrecisely control token usage

🎭 Practical Case: Marine Mammal Research Assistant ​

We will build a chatbot that demonstrates the application of three message management techniques.

Scene setting ​

The user was studying marine mammals and had multiple rounds of conversations:

  1. Say hello
  2. Discuss whales
  3. Ask other marine mammals
  4. Learn more about narwhals
  5. Ask about killer whale habitats

We need to control token usage while maintaining contextual coherence.


🔧 Option 1: Use RemoveMessage to delete the message ​

Core idea ​

Use the RemoveMessage and add_messages reducers to permanently remove old messages from the state.

Code implementation ​

1. Basic preparation ​

python
from pprint import pprint
from langchain_core.messages import AIMessage, HumanMessage
from langchain_openai import ChatOpenAI

# 初始化 LLM
llm = ChatOpenAI(model="gpt-4o")

# 创建对话历史
messages = [AIMessage("So you said you were researching ocean mammals?", name="Bot")]
messages.append(HumanMessage("Yes, I know about whales. But what others should I learn about?", name="Lance"))

# 查看消息
for m in messages:
    m.pretty_print()

Python knowledge point: Message object

LangChain uses specialized message classes to distinguish conversational roles:

python
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage

# HumanMessage - 用户输入
user_msg = HumanMessage(content="Hello!", name="Alice")

# AIMessage - AI 回复
ai_msg = AIMessage(content="Hi there!", name="Bot")

# SystemMessage - 系统指令
sys_msg = SystemMessage(content="You are a helpful assistant")

Important attributes:

  • content: message content
  • name: Sender name (optional)
  • id: unique identifier (for RemoveMessage)

2. Define filter nodes ​

python
from langchain_core.messages import RemoveMessage
from langgraph.graph import MessagesState

def filter_messages(state: MessagesState):
    """删除除最后 2 条消息外的所有消息"""
    # 获取要删除的消息(前 N-2 条)
    delete_messages = [RemoveMessage(id=m.id) for m in state["messages"][:-2]]
    return {"messages": delete_messages}

LangGraph knowledge point: RemoveMessage

RemoveMessage is a special message type that tells the add_messages reducer to delete the specified message:

python
RemoveMessage(id="message_id_123")
#             ^^^^^^^^^^^^^^^^^^^
#             要删除的消息的 ID

How ​​it works:

python
# 初始状态
state["messages"] = [msg1, msg2, msg3, msg4]

# filter_messages 返回
{"messages": [RemoveMessage(id=msg1.id), RemoveMessage(id=msg2.id)]}

# add_messages reducer 处理后
state["messages"] = [msg3, msg4]  # msg1 和 msg2 被删除

Key: The add_messages reducer will recognize RemoveMessage and remove the corresponding message from the state.

3. Define chat nodes ​

python
def chat_model_node(state: MessagesState):
    """调用 LLM 生成回复"""
    return {"messages": [llm.invoke(state["messages"])]}

Note: Returns {"messages": [ai_message]} instead of {"messages": ai_message} because the add_messages reducer expects a list.

4. Build the graph ​

python
from langgraph.graph import StateGraph, START, END

# 创建图
builder = StateGraph(MessagesState)

# 添加节点
builder.add_node("filter", filter_messages)
builder.add_node("chat_model", chat_model_node)

# 添加边
builder.add_edge(START, "filter")
builder.add_edge("filter", "chat_model")
builder.add_edge("chat_model", END)

# 编译
graph = builder.compile()

Execution process:

START → filter(删除旧消息)→ chat_model(LLM 回复)→ END

5. Execute the test ​

python
# 创建带 ID 的消息(RemoveMessage 需要 ID)
messages = [
    AIMessage("Hi.", name="Bot", id="1"),
    HumanMessage("Hi.", name="Lance", id="2"),
    AIMessage("So you said you were researching ocean mammals?", name="Bot", id="3"),
    HumanMessage("Yes, I know about whales. But what others should I learn about?", name="Lance", id="4")
]

# 调用图
output = graph.invoke({'messages': messages})

# 查看结果
for m in output['messages']:
    m.pretty_print()

Expected results:

# 只保留最后 2 条消息 + LLM 回复
================================== Ai Message ==================================
Name: Bot

So you said you were researching ocean mammals?
================================ Human Message =================================
Name: Lance

Yes, I know about whales. But what others should I learn about?
================================== Ai Message ==================================

Here are some ocean mammals: dolphins, seals, sea lions, ...

NOTE: The first two messages (id="1" and id="2") have been permanently deleted!

Python knowledge points: list slicing ​

python
messages = [msg1, msg2, msg3, msg4, msg5]

# 取最后 2 条
messages[-2:]  # → [msg4, msg5]

# 除了最后 2 条的所有消息
messages[:-2]  # → [msg1, msg2, msg3]

# 第一条
messages[:1]   # → [msg1]

# 最后一条
messages[-1:]  # → [msg5]

🔧 Option 2: Message filtering (no status modification) ​

Core idea ​

Graph state is not modified, only messages are filtered when passed to LLM. The state retains the full history, but LLM only sees partial messages.

Code implementation ​

1. Modify chat node ​

python
def chat_model_node(state: MessagesState):
    """只传递最后一条消息给 LLM"""
    return {"messages": [llm.invoke(state["messages"][-1:])]}
    #                                 ^^^^^^^^^^^^^^^^^^^
    #                                 只取最后一条消息

2. Simplified graph structure ​

python
# 创建图(无需 filter 节点!)
builder = StateGraph(MessagesState)
builder.add_node("chat_model", chat_model_node)
builder.add_edge(START, "chat_model")
builder.add_edge("chat_model", END)
graph = builder.compile()

Comparison plan one:

FeaturesRemoveMessageMessage Filtering
Number of nodes2 (filter + chat)1 (chat)
Status modifiedPermanently deletedRemain unchanged
Historical availabilityHistorical lossHistorical integrity preservation

3. Test multiple rounds of dialogue ​

python
# 初始消息
messages = [
    AIMessage("So you said you were researching ocean mammals?", name="Bot"),
    HumanMessage("Yes, I know about whales. But what others should I learn about?", name="Lance")
]

# 第一轮调用
output = graph.invoke({'messages': messages})

# 追加 LLM 回复和新问题
messages.append(output['messages'][-1])
messages.append(HumanMessage("Tell me more about Narwhals!", name="Lance"))

# 第二轮调用
output = graph.invoke({'messages': messages})

Key Observations:

While messages contains the full history, LLM only sees the last message each time!

python
# messages 实际内容:
[
    AIMessage("...ocean mammals?"),
    HumanMessage("...whales..."),
    AIMessage("...dolphins, seals..."),
    HumanMessage("Tell me more about Narwhals!")  # ← LLM 只看到这条
]

Validate in LangSmith ​

Looking at the LangSmith trace, you'll see that the messages parameter of the LLM call only contains the last message, not the full history.

Advantages:

  • Complete state retention (can be used for logs and analysis)
  • LLM token usage is controlled
  • Simple to implement (no additional nodes required)

Disadvantages:

  • LLM lacks context (may lead to incoherent answers)
  • Need to manually manage the scope of messages that need to be delivered

🔧 Option 3: Intelligent cropping (based on Token) ​

Core idea ​

Use LangChain's trim_messages tool to intelligently tailor messages based on token quantity instead of simply filtering by quantity.

Why do you need Token clipping? ​

The number of tokens varies greatly for different messages:

python
msg1 = HumanMessage("Hi")                    # ~1 token
msg2 = AIMessage("Hello! How can I help?")   # ~5 tokens
msg3 = HumanMessage("Tell me about whales... (1000 字)")  # ~1500 tokens

If you simply filter "last 2 messages":

  • maybe 6 tokens (msg1 + msg2)
  • May also be 1505 tokens (msg2 + msg3)

**Token cropping ensures precise control! **

Code implementation ​

1. Import the cropping tool ​

python
from langchain_core.messages import trim_messages

2. Modify chat node ​

python
def chat_model_node(state: MessagesState):
    """使用 token 裁剪"""
    # 裁剪消息到最多 100 tokens
    messages = trim_messages(
        state["messages"],          # 原始消息列表
        max_tokens=100,             # 最大 token 数
        strategy="last",            # 保留最后的消息
        token_counter=ChatOpenAI(model="gpt-4o"),  # Token 计数器
        allow_partial=False,        # 不允许截断消息
    )
    return {"messages": [llm.invoke(messages)]}

LangChain knowledge points: detailed explanation of trim_messages parameters

python
trim_messages(
    messages,                      # 要裁剪的消息列表
    max_tokens=100,                # 最大 token 数
    strategy="last",               # 裁剪策略(见下方)
    token_counter=model,           # Token 计数器(通常是模型实例)
    allow_partial=False,           # 是否允许部分截断单条消息
)

Cutting strategy (strategy):

StrategyDescriptionExample
"last"Keep last messageSuitable for chatbots (keep recent conversations)
"first"Keep the first messageSuitable for retaining system commands

allow_partial parameters:

python
# allow_partial=False(默认)
# 如果某条消息超过剩余 token,直接丢弃整条消息
messages = [msg1(50 tokens), msg2(60 tokens), msg3(40 tokens)]
trim_messages(messages, max_tokens=100, allow_partial=False)
# → [msg2, msg3]  # msg1 被丢弃,因为 msg2+msg3=100 tokens

# allow_partial=True
# 会截断消息以精确达到 max_tokens
trim_messages(messages, max_tokens=100, allow_partial=True)
# → [msg1(部分截断), msg2, msg3]

3. Test the cropping effect ​

python
# 准备长对话历史
messages = [
    AIMessage("Hi.", name="Bot", id="1"),
    HumanMessage("Hi.", name="Lance", id="2"),
    AIMessage("So you said you were researching ocean mammals?", name="Bot", id="3"),
    HumanMessage("Yes, I know about whales. But what others should I learn about?", name="Lance", id="4"),
    AIMessage("Consider dolphins, seals, sea lions...", name="Bot", id="5"),
    HumanMessage("Tell me where Orcas live!", name="Lance", id="6")
]

# 测试裁剪(不调用 LLM)
trimmed = trim_messages(
    messages,
    max_tokens=100,
    strategy="last",
    token_counter=ChatOpenAI(model="gpt-4o"),
    allow_partial=False
)

print(f"原始消息数: {len(messages)}")
print(f"裁剪后消息数: {len(trimmed)}")
for m in trimmed:
    m.pretty_print()

Expected output:

Depending on the token calculation, only the last 2-3 messages may be retained to ensure that the total does not exceed 100 tokens.

4. Use in pictures ​

python
# 构建图
builder = StateGraph(MessagesState)
builder.add_node("chat_model", chat_model_node)
builder.add_edge(START, "chat_model")
builder.add_edge("chat_model", END)
graph = builder.compile()

# 调用
output = graph.invoke({'messages': messages})

Verification: Check the trace in LangSmith to confirm that the total number of tokens in the messages received by LLM is ≤ 100.

Python knowledge points: function parameter passing ​

python
# trim_messages 接收模型实例作为 token_counter
token_counter=ChatOpenAI(model="gpt-4o")

# 内部调用模型的 token 计数方法
# model.get_num_tokens_from_messages(messages)

**Why do you need a model instance? **

Different models have different tokenizers:

  • GPT-4: use cl100k_base encoding
  • GPT-3.5: use cl100k_base encoding
  • Claude: use different tokenizers

You must use the tokenizer of the corresponding model to count accurately!


🎓 Summary of core knowledge points ​

LangGraph-specific concepts ​

1. MessagesState ​

Predefined status patterns, designed specifically for chat applications:

python
from langgraph.graph import MessagesState

class MessagesState(TypedDict):
    messages: Annotated[list, add_messages]
    #          ^^^^^^^^^^^^^^^^^^^^^^^
    #          自动使用 add_messages reducer

Advantages:

  • Automatically handle message appending -Support RemoveMessage
  • Simplify status definition

2. add_messages Reducer ​

Built-in smart message reducer:

python
# 普通追加
state["messages"] + [new_message]  # 追加消息

# 识别 RemoveMessage
state["messages"] + [RemoveMessage(id="123")]  # 删除消息

# 自动去重(基于 ID)
state["messages"] + [existing_message]  # 如果 ID 相同,不重复添加

3. Comparison of three message management modes ​

ModeStatus modificationToken controlHistory retentionComplexityApplicable scenarios
RemoveMessage✅ Permanent deletionIndirect (delete message)❌ Partially lostMediumWhen it is determined that the history is not needed
Message filtering❌ No modification✅ Accurate (by quantity)✅ Keep completeLowSimple scenario, fixed quantity
Token crop❌ No modification✅✅ Very accurate (by token)✅ Keep intactMediumNeed to control costs accurately

Python-specific knowledge points ​

1. Hierarchy of message classes ​

python
BaseMessage (基类)
    ├── HumanMessage (用户消息)
    ├── AIMessage (AI 回复)
    ├── SystemMessage (系统指令)
    ├── FunctionMessage (函数调用结果)
    └── RemoveMessage (删除标记)

Inheritance relationship:

python
from langchain_core.messages import BaseMessage, HumanMessage

# HumanMessage 继承自 BaseMessage
isinstance(HumanMessage("Hi"), BaseMessage)  # True

2. Advanced usage of list slicing ​

python
messages = [msg1, msg2, msg3, msg4, msg5]

# 负数索引
messages[-1]    # 最后一个元素
messages[-2:]   # 最后两个元素

# 步长切片
messages[::2]   # 每隔一个取一个: [msg1, msg3, msg5]
messages[::-1]  # 反转列表

# 省略参数
messages[2:]    # 从第3个到结尾
messages[:3]    # 从开头到第3个(不含)
messages[:]     # 完整复制

3. List comprehension ​

python
# 基础形式
[RemoveMessage(id=m.id) for m in messages[:-2]]

# 等价于:
result = []
for m in messages[:-2]:
    result.append(RemoveMessage(id=m.id))

Conditional list comprehension:

python
# 只删除 HumanMessage
[RemoveMessage(id=m.id) for m in messages if isinstance(m, HumanMessage)]

# 删除超过 100 tokens 的消息
[RemoveMessage(id=m.id) for m in messages if get_token_count(m) > 100]

💡 Best Practices ​

1. When to use which solution? ​

Scenarios for using RemoveMessage ​

✅ Applicable:

  • Determine old messages are no longer needed (such as completed tasks)
  • Need to permanently reduce state size (save memory)
  • Implement a "forget" mechanism (such as regularly clearing conversations 7 days ago)

❌ Not applicable:

  • May need to go back in history
  • Need to keep complete logs
  • Debugging phase (cannot be restored after deletion)

Example:

python
def cleanup_old_messages(state: MessagesState):
    """删除 7 天前的消息"""
    cutoff = datetime.now() - timedelta(days=7)
    to_remove = [
        RemoveMessage(id=m.id)
        for m in state["messages"]
        if m.timestamp < cutoff
    ]
    return {"messages": to_remove}

Scenarios for using message filtering ​

✅ Applicable:

  • Rapid prototyping
  • Simple "Last N messages" logic
  • Don’t want to modify the status (convenient for rollback)

❌ Not applicable:

  • Need to accurately control token cost
  • Message lengths vary widely

Example:

python
# 场景:客服机器人只需要最近 5 轮对话
def chat_node(state: MessagesState):
    recent_messages = state["messages"][-10:]  # 5 轮 = 10 条消息(用户+AI)
    return {"messages": [llm.invoke(recent_messages)]}

Scene cropped using Token ​

✅ Applicable:

  • Production environment (requires strict cost control) -Unpredictable message length
  • Need to fully utilize the context window (e.g. close to the 4096 tokens limit)

❌ Not applicable:

  • Early in development (increased complexity)
  • The number of messages is fixed and short

Example:

python
# 场景:文档问答,用户可能粘贴长文本
def qa_node(state: MessagesState):
    # 保留系统指令 + 尽可能多的对话历史
    messages = trim_messages(
        state["messages"],
        max_tokens=3500,  # 为 LLM 回复预留 500 tokens
        strategy="last",
        token_counter=llm,
        allow_partial=False
    )
    return {"messages": [llm.invoke(messages)]}

2. Use a combination of techniques ​

Best Practice: In real applications, multiple techniques are often used in combination.

Example: Intelligent customer service system ​

python
def intelligent_chat_node(state: MessagesState):
    messages = state["messages"]

    # 第 1 步:删除系统消息以外的过期消息(7 天前)
    # (在单独的 cleanup 节点中处理)

    # 第 2 步:保留系统指令
    system_messages = [m for m in messages if isinstance(m, SystemMessage)]
    conversation_messages = [m for m in messages if not isinstance(m, SystemMessage)]

    # 第 3 步:Token 裁剪对话历史
    trimmed_conversation = trim_messages(
        conversation_messages,
        max_tokens=2000,
        strategy="last",
        token_counter=llm,
        allow_partial=False
    )

    # 第 4 步:重组消息(系统指令 + 裁剪后的对话)
    final_messages = system_messages + trimmed_conversation

    # 第 5 步:调用 LLM
    return {"messages": [llm.invoke(final_messages)]}

3. Status management skills ​

Tip 1: Always keep system messages ​

python
def trim_with_system(messages, max_tokens):
    # 分离系统消息和对话消息
    system_msgs = [m for m in messages if isinstance(m, SystemMessage)]
    other_msgs = [m for m in messages if not isinstance(m, SystemMessage)]

    # 计算系统消息的 token 数
    system_tokens = sum(llm.get_num_tokens(m.content) for m in system_msgs)

    # 裁剪对话消息(减去系统消息占用的 tokens)
    trimmed = trim_messages(
        other_msgs,
        max_tokens=max_tokens - system_tokens,
        strategy="last",
        token_counter=llm
    )

    return system_msgs + trimmed

Tip 2: Keep important messages ​

python
def trim_with_pinned(state: MessagesState, max_tokens):
    messages = state["messages"]

    # 标记重要消息(假设通过 metadata)
    pinned = [m for m in messages if m.additional_kwargs.get("pinned")]
    unpinned = [m for m in messages if not m.additional_kwargs.get("pinned")]

    # 只裁剪非重要消息
    pinned_tokens = sum(llm.get_num_tokens(m.content) for m in pinned)
    trimmed = trim_messages(
        unpinned,
        max_tokens=max_tokens - pinned_tokens,
        strategy="last",
        token_counter=llm
    )

    # 重新排序(保持时间顺序)
    all_messages = sorted(pinned + trimmed, key=lambda m: m.timestamp)
    return {"messages": all_messages}

Tip 3: Dynamically adjust the cropping strategy ​

python
def adaptive_trim(state: MessagesState):
    messages = state["messages"]
    conversation_length = len(messages)

    # 根据对话长度动态调整 max_tokens
    if conversation_length < 10:
        max_tokens = 1000  # 短对话:保留更多上下文
    elif conversation_length < 50:
        max_tokens = 500   # 中等对话:适度裁剪
    else:
        max_tokens = 200   # 长对话:激进裁剪

    trimmed = trim_messages(
        messages,
        max_tokens=max_tokens,
        strategy="last",
        token_counter=llm
    )

    return {"messages": [llm.invoke(trimmed)]}

🚀 Advanced skills ​

1. Implement sliding window ​

Keep "the most recent N messages + the first system command":

python
def sliding_window_trim(messages, window_size=10):
    if len(messages) <= window_size:
        return messages

    # 假设第一条是系统指令
    system_msg = messages[0] if isinstance(messages[0], SystemMessage) else None

    if system_msg:
        # 保留系统指令 + 最后 N-1 条消息
        return [system_msg] + messages[-(window_size-1):]
    else:
        # 只保留最后 N 条
        return messages[-window_size:]

2. Summary-based history compression ​

For very long conversations, a summary can be generated periodically:

python
class ConversationState(TypedDict):
    messages: Annotated[list, add_messages]
    summary: str  # 对话摘要

def summarize_old_messages(state: ConversationState):
    messages = state["messages"]

    # 如果消息超过 50 条,生成摘要
    if len(messages) > 50:
        # 摘要前 40 条消息
        to_summarize = messages[:40]
        summary_prompt = f"Summarize this conversation:\n{to_summarize}"
        summary = llm.invoke(summary_prompt).content

        # 删除已摘要的消息
        to_remove = [RemoveMessage(id=m.id) for m in to_summarize]

        return {
            "messages": to_remove,
            "summary": summary  # 保存摘要
        }

    return {}

def chat_with_summary(state: ConversationState):
    # 构建上下文:摘要 + 最近消息
    context = []
    if state.get("summary"):
        context.append(SystemMessage(f"Previous conversation summary: {state['summary']}"))
    context.extend(state["messages"])

    return {"messages": [llm.invoke(context)]}

3. Filter by role ​

Keep only messages for specific roles:

python
def filter_by_role(messages, keep_roles=["human", "ai"]):
    """只保留用户和 AI 的消息,移除系统消息"""
    return [
        m for m in messages
        if m.type in keep_roles
    ]

# 使用
def chat_node(state: MessagesState):
    # 只传递用户和 AI 的对话给 LLM
    filtered = filter_by_role(state["messages"], keep_roles=["human", "ai"])
    return {"messages": [llm.invoke(filtered)]}

4. Intelligent deduplication ​

Remove duplicate or similar messages:

python
def deduplicate_messages(messages):
    """移除内容完全相同的连续消息"""
    if not messages:
        return messages

    deduplicated = [messages[0]]
    for msg in messages[1:]:
        if msg.content != deduplicated[-1].content:
            deduplicated.append(msg)

    return deduplicated

📊 Performance comparison ​

Token usage comparison ​

Assume 10 rounds of dialogue, with an average of 100 tokens per round:

SchemeToken usageCost (GPT-4 input)Latency
No clipping1000 tokens$0.03High
Filter last 5 items~500 tokens$0.015Medium
Cropped to 200 tokens200 tokens$0.006Low

Actual measurement example ​

python
import time

# 准备长对话(100 条消息)
long_conversation = [
    HumanMessage(f"Message {i}") if i % 2 == 0 else AIMessage(f"Response {i}")
    for i in range(100)
]

# 方案 1:无裁剪
start = time.time()
response1 = llm.invoke(long_conversation)
time1 = time.time() - start

# 方案 2:过滤最后 10 条
start = time.time()
response2 = llm.invoke(long_conversation[-10:])
time2 = time.time() - start

# 方案 3:Token 裁剪到 500
start = time.time()
trimmed = trim_messages(long_conversation, max_tokens=500, token_counter=llm)
response3 = llm.invoke(trimmed)
time3 = time.time() - start

print(f"无裁剪: {time1:.2f}s")
print(f"过滤: {time2:.2f}s (快 {(time1-time2)/time1*100:.0f}%)")
print(f"裁剪: {time3:.2f}s (快 {(time1-time3)/time1*100:.0f}%)")

🎯 Practical application cases ​

Case 1: Customer Service Chatbot ​

python
class CustomerServiceState(TypedDict):
    messages: Annotated[list, add_messages]
    customer_id: str
    session_start: datetime

def customer_service_chat(state: CustomerServiceState):
    """客服机器人:保留完整历史但限制 LLM 可见范围"""
    messages = state["messages"]

    # 1. 始终保留系统指令(客服规范)
    system_msg = SystemMessage("You are a helpful customer service agent. Be polite and professional.")

    # 2. 裁剪对话历史到 1500 tokens(约 10-15 轮对话)
    trimmed = trim_messages(
        messages,
        max_tokens=1500,
        strategy="last",
        token_counter=llm,
        allow_partial=False
    )

    # 3. 组合系统指令和裁剪后的对话
    final_messages = [system_msg] + trimmed

    return {"messages": [llm.invoke(final_messages)]}

# 构建图
builder = StateGraph(CustomerServiceState)
builder.add_node("chat", customer_service_chat)
builder.add_edge(START, "chat")
builder.add_edge("chat", END)
graph = builder.compile()

Case 2: Document Q&A Assistant ​

python
def document_qa_chat(state: MessagesState):
    """文档问答:用户可能粘贴长文档"""
    messages = state["messages"]

    # 1. 识别长消息(超过 1000 tokens 的)
    long_messages = []
    short_messages = []

    for m in messages:
        token_count = llm.get_num_tokens(m.content)
        if token_count > 1000:
            # 截断长消息
            truncated_content = m.content[:2000] + "... [truncated]"
            long_messages.append(m.__class__(content=truncated_content))
        else:
            short_messages.append(m)

    # 2. 裁剪短消息
    trimmed_short = trim_messages(
        short_messages,
        max_tokens=1500,
        strategy="last",
        token_counter=llm
    )

    # 3. 组合(保留最近的长消息 + 裁剪后的短消息)
    final_messages = (long_messages[-1:] if long_messages else []) + trimmed_short

    return {"messages": [llm.invoke(final_messages)]}

Case 3: Clean up old messages regularly ​

python
from datetime import datetime, timedelta

class TimedState(TypedDict):
    messages: Annotated[list, add_messages]
    last_cleanup: datetime

def cleanup_node(state: TimedState):
    """每 24 小时清理一次旧消息"""
    now = datetime.now()
    last_cleanup = state.get("last_cleanup", now)

    # 如果距离上次清理超过 24 小时
    if (now - last_cleanup).total_seconds() > 86400:
        messages = state["messages"]
        cutoff = now - timedelta(days=7)

        # 删除 7 天前的消息
        to_remove = [
            RemoveMessage(id=m.id)
            for m in messages
            if hasattr(m, 'timestamp') and m.timestamp < cutoff
        ]

        return {
            "messages": to_remove,
            "last_cleanup": now
        }

    return {}

# 在图中添加清理节点
builder.add_node("cleanup", cleanup_node)
builder.add_node("chat", chat_node)
builder.add_edge(START, "cleanup")
builder.add_edge("cleanup", "chat")
builder.add_edge("chat", END)

🔍 Frequently Asked Questions ​

Q1: Can RemoveMessage be restored after deletion? ​

**cannot! ** RemoveMessage is a permanent operation. If you need to preserve history:

python
# ❌ 错误:直接删除
return {"messages": [RemoveMessage(id=msg.id)]}

# ✅ 正确:先备份
archived_messages = state["messages"][:-10]  # 保存到数据库
to_remove = [RemoveMessage(id=m.id) for m in archived_messages]
return {"messages": to_remove}

Q2: Will trim_messages modify the original message? ​

**Won't! ** trim_messages returns a new list without modifying the input:

python
original = [msg1, msg2, msg3]
trimmed = trim_messages(original, max_tokens=50, token_counter=llm)

# original 仍然是 [msg1, msg2, msg3]
# trimmed 可能是 [msg2, msg3](新列表)

Q3: How to handle system messages? ​

Best Practice: Always keep system messages and handle them separately:

python
def smart_trim(messages, max_tokens):
    system = [m for m in messages if isinstance(m, SystemMessage)]
    others = [m for m in messages if not isinstance(m, SystemMessage)]

    # 只裁剪非系统消息
    system_tokens = sum(llm.get_num_tokens(m.content) for m in system)
    trimmed_others = trim_messages(
        others,
        max_tokens=max_tokens - system_tokens,
        token_counter=llm
    )

    return system + trimmed_others

Q4: Where will allow_partial=True be truncated? ​

Answer: Truncated to exactly the position of max_tokens:

python
message = HumanMessage("This is a very long message with many words...")
# 假设这条消息有 150 tokens

trimmed = trim_messages(
    [message],
    max_tokens=100,
    allow_partial=True,
    token_counter=llm
)

# 结果:消息被截断到约 100 tokens
# "This is a very long message with..."

Note: Truncation may result in incomplete semantics, use with caution!

Q5: How to count the number of Tokens? ​

Using the model's get_num_tokens method:

python
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o")

# 单条消息
message = HumanMessage("Hello, world!")
tokens = llm.get_num_tokens(message.content)
print(f"Tokens: {tokens}")

# 消息列表
messages = [HumanMessage("Hi"), AIMessage("Hello!")]
total_tokens = llm.get_num_tokens_from_messages(messages)
print(f"Total tokens: {total_tokens}")

📖 Further reading ​


🎓 Summary ​

Message management is a critical skill for building production-grade chat applications. This tutorial introduces three core technologies:

TechnologyCore ValuesUsage Scenarios
RemoveMessagePermanently delete, save memoryIdentify unwanted history
Message filteringSimple and efficient, no status modificationRapid prototyping, fixed rules
Token tailoringAccurate cost controlProduction environment, variable length messages

Key Takeaways:

  1. Understand the scenario: Choose appropriate technology based on application requirements
  2. Preserve flexibility: The state retains the complete history and is only trimmed when passed to LLM
  3. Combination use: In practical applications, it is often necessary to combine multiple technologies
  4. Monitor Token: Use LangSmith to track actual token usage
  5. Progressive Optimization: Start with a simple solution and gradually optimize according to needs

By mastering these techniques, you can build a long-term memory chatbot that is both efficient and cost-effective!

English translation of community learning materials. MIT licensed.