LangGraph Chatbot with Message Summarization Detailed interpretation
📚 Overview
This document explains in detail the Message Summarization technology in LangGraph. This is an intelligent memory management scheme that uses LLM to generate conversation summaries to compress historical messages, thereby enabling long-term conversations without high token costs and latency issues.
🎯 Core Concept
Why do we need conversation summaries?
When building chatbots, we face a fundamental contradiction:
- Long-term memory requirements: Users expect the bot to remember the entire conversation history
- token restriction: LLM has context window restrictions
- Cost and Latency: Sending a large number of historical messages will increase cost and response time
Comparison of three message management strategies
| Strategy | Advantages | Disadvantages | Applicable scenarios |
|---|---|---|---|
| Keep it intact | Complete information | High token cost, may exceed limit | Short conversation |
| Crop/Filter | Simple and efficient | Lost historical information | Simple conversation |
| Smart Summary | Retain key information and control costs | High implementation complexity | Long-term dialogue |
Solution for this tutorial: Use LLM to generate conversation summaries, retaining compressed historical information to support long-term conversations.
🏗️ System architecture
Core Mechanism
用户消息流
↓
检查消息数量
↓
├─ ≤6 条消息 → 直接使用历史
│ ↓
│ [call_model] 生成回复
│ ↓
│ END
│
└─ >6 条消息 → 触发摘要
↓
[summarize_conversation] 生成/更新摘要
↓
保留最新 2 条消息 + 摘要
↓
ENDWork flow chart
graph TD
START --> conversation[call_model]
conversation --> check{消息数 > 6?}
check -->|No| END1[END]
check -->|Yes| summarize[summarize_conversation]
summarize --> END2[END]🔧 Detailed explanation of code implementation
1. Environment settings
%%capture --no-stderr
%pip install --quiet -U langchain_core langgraph langchain_openaiDescription:
%%capture --no-stderr: Jupyter magic command that hides installation output (but keeps errors)- Install core dependencies: LangChain, LangGraph, OpenAI integration
import os, getpass
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")Python knowledge points: Environment variable management
os.environ.get(var): Get the environment variable, if it does not exist, returnNonegetpass.getpass(): Enter passwords securely (without showing clear text)- This is a best practice for production environments: sensitive information is not hardcoded
2. LangSmith tracking settings
_set_env("LANGSMITH_API_KEY")
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_PROJECT"] = "langchain-academy"LangSmith role:
- Track every LLM call
- Visualized execution process
- Debugging and performance analysis
3. Initialize model
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o", temperature=0)Parameter description:
model="gpt-4o": Use GPT-4 Optimized modeltemperature=0: deterministic output (suitable for tasks requiring consistency)
4. Define State⭐
This is the core of the entire system!
from langgraph.graph import MessagesState
class State(MessagesState):
summary: strLangGraph knowledge point: MessagesState
MessagesState is the built-in state base class provided by LangGraph:
class MessagesState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]Key Features:
- Automatic message management:
messagesfield has been configuredadd_messagesreducer - Smart Merge: New messages are automatically appended to history
- ID Management: Each message has a unique ID and supports deletion/update
Our extensions:
class State(MessagesState):
summary: str # 新增摘要字段The current status includes:
messages: message list (inherited from MessagesState)summary: Conversation summary (new)
Python knowledge points: Class inheritance
class State(MessagesState):
# 继承 MessagesState 的所有字段和方法
summary: str # 添加新字段This is Python’s single inheritance pattern, and State has:
messagesfield of parent class- own
summaryfield
5. Dialogue node: call_model ⭐
from langchain_core.messages import SystemMessage, HumanMessage, RemoveMessage
def call_model(state: State):
# 获取摘要(如果存在)
summary = state.get("summary", "")
# 如果有摘要,添加到系统消息
if summary:
# 创建包含摘要的系统消息
system_message = f"Summary of conversation earlier: {summary}"
# 将摘要追加到消息历史前面
messages = [SystemMessage(content=system_message)] + state["messages"]
else:
# 没有摘要,直接使用消息历史
messages = state["messages"]
# 调用 LLM
response = model.invoke(messages)
return {"messages": response}Code analysis:
Step 1: Check if there is a summary
summary = state.get("summary", "")state.get("summary", ""): Get digest safely, return empty string if not present- Avoid
KeyErrorexception
Step 2: Build message list
Case A: With summary
messages = [SystemMessage(content=system_message)] + state["messages"]Message structure:
[
SystemMessage("Summary of conversation earlier: 用户叫 Lance,喜欢 49ers..."),
HumanMessage("最新用户消息"),
...
]Case B: No Summary
messages = state["messages"]Straight from the original history.
Step 3: Call the model and return
response = model.invoke(messages)
return {"messages": response}model.invoke(messages): Send message to LLMreturn {"messages": response}: The returned dictionary will be updated withState.messages
LangGraph knowledge point: status update mechanism
The dictionary returned by the node is automatically merged into the state:
# 当前 State.messages = [msg1, msg2]
return {"messages": response}
# 更新后 State.messages = [msg1, msg2, response]This is because the add_messages reducer appends new messages to the list.
6. Summary node: summarize_conversation ⭐⭐⭐
This is the heart of this tutorial!
def summarize_conversation(state: State):
# 第一步:获取现有摘要
summary = state.get("summary", "")
# 第二步:创建摘要提示
if summary:
# 已有摘要 → 增量更新
summary_message = (
f"This is summary of the conversation to date: {summary}\n\n"
"Extend the summary by taking into account the new messages above:"
)
else:
# 无摘要 → 首次创建
summary_message = "Create a summary of the conversation above:"
# 第三步:生成摘要
messages = state["messages"] + [HumanMessage(content=summary_message)]
response = model.invoke(messages)
# 第四步:删除旧消息,只保留最新 2 条
delete_messages = [RemoveMessage(id=m.id) for m in state["messages"][:-2]]
return {"summary": response.content, "messages": delete_messages}Detailed analysis
Step 1: Check existing abstracts
summary = state.get("summary", "")Determine whether it is a first summary or an updated summary.
Step 2: Build summary prompt
Two prompting strategies:
First abstract (no existing abstract):
"Create a summary of the conversation above:"Incremental summary (with existing summary):
"This is summary of the conversation to date: {旧摘要} Extend the summary by taking into account the new messages above:"
**Why use incremental summaries? **
- Preserve the continuity of historical information
- Avoid repeating summaries of entire conversations
- Just process new messages
Step 3: Call LLM to generate summary
messages = state["messages"] + [HumanMessage(content=summary_message)]
response = model.invoke(messages)Message structure:
[
...历史消息...,
HumanMessage("Create a summary of the conversation above:")
]LLM generates summaries based on all history.
Step 4: Delete old messages ⭐
delete_messages = [RemoveMessage(id=m.id) for m in state["messages"][:-2]]Key knowledge point: RemoveMessage
RemoveMessage is a special message type provided by LangGraph for removing messages from the state:
RemoveMessage(id=message_id)Code analysis:
state["messages"][:-2] # 除了最后 2 条消息外的所有消息
[RemoveMessage(id=m.id) for m in ...] # 为每条消息创建删除标记Execution effect:
Assume there are 8 messages:
[msg1, msg2, msg3, msg4, msg5, msg6, msg7, msg8]
^^^^^ ^^^^^ 保留最新 2 条
^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ 删除这 6 条After deletion:
[msg7, msg8] # 只保留最新 2 条**Why keep 2 items? **
- Latest user news
- Latest AI replies
- Ensure dialogue continuity
Step 5: Return for updates
return {
"summary": response.content, # 更新摘要
"messages": delete_messages # 删除旧消息
}LangGraph knowledge point: update multiple fields at the same time
A node can return updates for multiple fields:
summary: Store new summary textmessages: Apply delete operation (add_messagesreducer will handleRemoveMessage)
7. Conditional edge: should_continue
from langgraph.graph import END
from typing_extensions import Literal
def should_continue(state: State) -> Literal["summarize_conversation", END]:
"""返回下一个要执行的节点"""
messages = state["messages"]
# 如果消息超过 6 条,进行摘要
if len(messages) > 6:
return "summarize_conversation"
# 否则结束
return ENDPython knowledge point: Literal type
from typing_extensions import Literal
def should_continue(state: State) -> Literal["summarize_conversation", END]:
...Literal means that the return value can only be the specified literal:
"summarize_conversation": string literalEND: special constants of LangGraph
Function:
- Type safety: IDE checks return value
- Auto-completion: IDE will prompt for possible return values
LangGraph knowledge point: conditional edge return value
The return value of the conditional edge function determines the next node:
- Return node name → jump to this node
- Return to
END→ End graph execution
8. Add Memory ⭐⭐⭐
Core Issue: By default, LangGraph's state is temporary and is brand new for each execution.
Solution: Use Checkpointer (checkpoint mechanism) to persist the state.
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()MemorySaver function:
- In-memory key-value storage
- Automatically save the status of each step -Support multi-threaded conversations
LangGraph knowledge point: state persistence
graph = workflow.compile(checkpointer=memory)Execution process:
- Before execution: Load the last state from checkpointer
- After each node: Automatically save the current state to checkpointer
- After execution: The status is retained in the checkpointer
**Why is it important? **
- Support long-term conversations: users can continue previous conversations at any time
- Interruption recovery: Even if the program is restarted, the conversation history still exists
- Multi-user isolation: conversations with different thread_ids do not interfere with each other
9. Construction diagram
from IPython.display import Image, display
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import StateGraph, START
# 定义图
workflow = StateGraph(State)
# 添加节点
workflow.add_node("conversation", call_model)
workflow.add_node(summarize_conversation) # 函数名自动作为节点名
# 设置入口
workflow.add_edge(START, "conversation")
# 添加条件边
workflow.add_conditional_edges("conversation", should_continue)
# 摘要后结束
workflow.add_edge("summarize_conversation", END)
# 编译(带内存)
memory = MemorySaver()
graph = workflow.compile(checkpointer=memory)
# 可视化
display(Image(graph.get_graph().draw_mermaid_png()))Graph structure analysis:
START
↓
conversation (call_model)
↓
should_continue (条件判断)
├─ ≤6 条 → END
└─ >6 条 → summarize_conversation
↓
ENDLangGraph knowledge point: node naming
workflow.add_node("conversation", call_model) # 显式命名
workflow.add_node(summarize_conversation) # 使用函数名Two ways:
- Provide name:
add_node(name, func) - Automatic naming:
add_node(func)→ use the function name as the node name
10. Threads⭐⭐⭐
Core Concept: A Thread is a collection of related checkpoints, similar to a Slack channel.
# 创建配置,指定线程 ID
config = {"configurable": {"thread_id": "1"}}The role of Thread:
- Isolated conversations: Conversations with different thread_ids do not affect each other
- Status Grouping: All checkpoints in the same thread share history
- Multi-user support: Each user uses an independent thread_id
Analogy understanding:
| Concepts | LangGraph | Slack |
|---|---|---|
| Thread | thread_id | channel |
| Checkpoint | Status Snapshot | Message History |
| State | Current conversation status | Current channel content |
11. Execute dialogue
# 创建线程配置
config = {"configurable": {"thread_id": "1"}}
# 第一轮对话
input_message = HumanMessage(content="hi! I'm Lance")
output = graph.invoke({"messages": [input_message]}, config)
for m in output['messages'][-1:]:
m.pretty_print()Output:
================================== Ai Message ==================================
Hello Lance! How can I assist you today?Execution process:
- Check whether thread "1" has history → None
- Create a new state:
{"messages": [HumanMessage("hi! I'm Lance")]} - Enter the
conversationnode - No summary, call LLM directly
- Return to AI reply
- Save state to thread "1"
# 第二轮对话
input_message = HumanMessage(content="what's my name?")
output = graph.invoke({"messages": [input_message]}, config)
for m in output['messages'][-1:]:
m.pretty_print()Output:
================================== Ai Message ==================================
You mentioned that your name is Lance. How can I help you today?Execution process:
- Load historical status from thread "1":
{"messages": [ HumanMessage("hi! I'm Lance"), AIMessage("Hello Lance!...") ]} - Add new message:
HumanMessage("what's my name?") - Call LLM (with full history)
- AI can recall that the name is "Lance"
- Save the updated state
# 第三轮对话
input_message = HumanMessage(content="i like the 49ers!")
output = graph.invoke({"messages": [input_message]}, config)
for m in output['messages'][-1:]:
m.pretty_print()Output:
================================== Ai Message ==================================
That's great! The San Francisco 49ers have a rich history and a passionate fan base.
Do you have a favorite player or a memorable game that you particularly enjoyed?Current status:
messages: [
HumanMessage("hi! I'm Lance"),
AIMessage("Hello Lance!..."),
HumanMessage("what's my name?"),
AIMessage("You mentioned that your name is Lance..."),
HumanMessage("i like the 49ers!"),
AIMessage("That's great! The San Francisco 49ers...")
]
summary: "" # 还未触发摘要At this point there are 6 messages and the threshold to trigger the summary (>6) has not yet been reached.
12. Check summary status
graph.get_state(config).values.get("summary", "")Output:
''LangGraph knowledge point: get_state API
state_snapshot = graph.get_state(config)
state_snapshot.values # 获取当前状态的所有值Return StateSnapshot object:
values: current status dictionarynext: The next node to be executedconfig: Configuration informationmetadata: metadata
13. Trigger Summary
# 第四轮对话(触发摘要)
input_message = HumanMessage(content="i like Nick Bosa, isn't he the highest paid defensive player?")
output = graph.invoke({"messages": [input_message]}, config)
for m in output['messages'][-1:]:
m.pretty_print()Output:
================================== Ai Message ==================================
Yes, as of September 2023, Nick Bosa became the highest-paid defensive player in NFL history.
He signed a five-year contract extension with the San Francisco 49ers worth $170 million,
with $122.5 million guaranteed. Bosa is known for his exceptional skills as a defensive end
and has been a key player for the 49ers.Execution process:
- Load history (6 messages)
- Add new messages → 7 messages
- Enter the
conversationnode and generate a reply - There are now 8 messages → trigger condition
len(messages) > 6 should_continueReturn"summarize_conversation"- Enter the
summarize_conversationnode:- Generate summary
- Delete first 6 messages
- Keep the latest 2 items
- Status update:
messages: [最新 2 条消息] summary: "Lance introduced himself and mentioned..."
14. View the generated summary
graph.get_state(config).values.get("summary", "")Output:
'Lance introduced himself and mentioned that he is a fan of the San Francisco 49ers,
specifically highlighting his admiration for Nick Bosa. The conversation noted that
as of September 2023, Nick Bosa became the highest-paid defensive player in NFL history
with a five-year, $170 million contract extension with the 49ers.'Abstract Content Analysis:
✅ Information included:
- Username: Lance
- Hobbies: 49ers fans
- Favorite player: Nick Bosa
- Factual information: Nick Bosa’s contract details
✅ Compression effect:
- Original: 8 messages (hundreds of tokens)
- Abstract: 1 paragraph of text (about 50 tokens)
- Compression ratio: about 80-90%
🎓 Summary of core knowledge points
LangGraph-specific concepts
1. MessagesState
Built-in state base class, providing out-of-the-box message management:
from langgraph.graph import MessagesState
class State(MessagesState):
# 自动拥有 messages 字段
summary: str # 添加自定义字段Features:
messagesfield preconfigurationadd_messagesreducer- Support message addition, update, and deletion
- Automatically manage message IDs
2. RemoveMessage
Mechanism for deleting messages:
from langchain_core.messages import RemoveMessage
# 删除特定消息
delete_messages = [RemoveMessage(id=m.id) for m in old_messages]
return {"messages": delete_messages}How it works:
add_messagesreducer identifiesRemoveMessage- Remove the message corresponding to the ID from the status -Support batch deletion
3. Checkpointer
Mechanism of persistent state:
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
graph = workflow.compile(checkpointer=memory)Function:
- Automatically save status snapshots at each step
- Support status recovery and continuation
- Implement long-term memory
4. Thread
Status Grouping and Isolation:
config = {"configurable": {"thread_id": "1"}}
graph.invoke(input, config)Features:
- Independent state space for each thread -Isolate different conversations by thread_id
- Database-like session concept
5. Flexible return of conditional edges
from typing_extensions import Literal
def should_continue(state: State) -> Literal["next_node", END]:
if condition:
return "next_node"
return ENDReturn value type:
- node name (string)
END(special constant)- Lists or other complex logic
Python-specific knowledge points
1. TypedDict inheritance
from langgraph.graph import MessagesState
class State(MessagesState):
summary: strNote: TypedDict supports inheritance, and the subclass has all the fields of the parent class.
2. Dictionary get method
summary = state.get("summary", "")
# ^^^^^^^^^ ^^^^
# 键名 默认值Avoid KeyError:
- key exists → return value
- key does not exist → return to default value
3. List slicing
state["messages"][:-2] # 除了最后 2 个元素的所有元素
# ^^^^
# 负索引切片| slice | meaning |
|---|---|
[:-2] | From the beginning to the third from the bottom |
[-2:] | Last 2 |
[2:-2] | 3rd to 3rd from the bottom |
4. List comprehension
delete_messages = [RemoveMessage(id=m.id) for m in state["messages"][:-2]]Equivalent to:
delete_messages = []
for m in state["messages"][:-2]:
delete_messages.append(RemoveMessage(id=m.id))5. f-string multi-line string
summary_message = (
f"This is summary of the conversation to date: {summary}\n\n"
"Extend the summary by taking into account the new messages above:"
)Python features:
- Multi-line strings in brackets will be automatically concatenated
- Can mix f-strings and normal strings
💡 Best Practices
1. Summary triggering strategy
Option A: Based on the number of messages (this tutorial)
def should_continue(state: State):
if len(state["messages"]) > 6:
return "summarize_conversation"
return END✅ Benefits: Simple and predictable ❌ Disadvantages: Does not consider message length
Option B: Based on the number of Tokens
def should_continue(state: State):
total_tokens = sum(len(m.content.split()) for m in state["messages"])
if total_tokens > 1000:
return "summarize_conversation"
return END✅ Benefits: More precise cost control ❌ Disadvantages: Computational overhead
Solution C: Time-based
def should_continue(state: State):
# 假设 messages 有 timestamp 字段
oldest = state["messages"][0].timestamp
newest = state["messages"][-1].timestamp
if (newest - oldest).days > 1:
return "summarize_conversation"
return END✅ Advantages: Suitable for long-term conversations ❌ Disadvantages: Requires additional timestamp management
2. Digest retention policy
Current implementation: keep the latest 2 items
delete_messages = [RemoveMessage(id=m.id) for m in state["messages"][:-2]]Applicable scenarios: General conversation
Option B: Keep the latest N items
KEEP_LAST_N = 4
delete_messages = [RemoveMessage(id=m.id) for m in state["messages"][:-KEEP_LAST_N]]Applicable scenarios: Conversations that require more context
Solution C: Keep important messages
def is_important(message):
# 自定义重要性判断逻辑
return "重要" in message.content or message.type == "system"
delete_messages = [
RemoveMessage(id=m.id)
for m in state["messages"]
if not is_important(m)
]Applicable scenarios: Key information needs to be retained
3. Summary quality optimization
Tip 1: Structured summary tips
summary_prompt = """
Summarize the conversation with the following structure:
- User profile: Name, preferences, interests
- Key topics discussed: Main themes
- Important facts: Specific details mentioned
- Action items: Any pending tasks
Current summary: {summary}
New messages: {messages}
"""Tip 2: Incremental Summary
if summary:
# 告诉 LLM 只更新新信息
prompt = f"Current summary: {summary}\n\nUpdate ONLY with new information from above messages."
else:
prompt = "Create a comprehensive summary of the conversation."Tip 3: Digest Verification
def summarize_conversation(state: State):
# 生成摘要
response = model.invoke(messages)
summary = response.content
# 验证摘要质量(可选)
if len(summary) < 50:
# 摘要太短,重新生成
prompt = "Create a MORE DETAILED summary..."
response = model.invoke(prompt)
summary = response.content
# ...4. Memory management strategy
Development environment: MemorySaver
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver() # 内存存储,重启丢失✅ Advantages: Simple and fast ❌ Disadvantages: Not persistent
Production environment: SqliteSaver
from langgraph.checkpoint.sqlite import SqliteSaver
memory = SqliteSaver.from_conn_string("checkpoints.db")✅ Advantages: Persistence to disk ✅ Applicable: Stand-alone application
Distributed environment: RedisSaver (custom)
# 需要自己实现或使用第三方库
from langgraph.checkpoint.redis import RedisSaver
memory = RedisSaver(redis_url="redis://localhost:6379")✅ Advantages: Supports distributed and high performance ✅ Applicable: Multi-instance deployment
5. Thread management best practices
Strategy 1: Based on User ID
def get_config(user_id: str):
return {"configurable": {"thread_id": f"user_{user_id}"}}
# 使用
config = get_config("alice")
graph.invoke(input, config)Strategy 2: Based on session ID
import uuid
def create_session():
session_id = str(uuid.uuid4())
return {"configurable": {"thread_id": session_id}}
# 新会话
config = create_session()Strategy 3: Multi-dimensional isolation
def get_config(user_id: str, conversation_id: str):
thread_id = f"{user_id}_{conversation_id}"
return {"configurable": {"thread_id": thread_id}}
# 使用
config = get_config("alice", "project_discussion")🚀 Advanced skills
1. Multi-level summary
For very long conversations, multi-level summaries can be implemented:
class State(MessagesState):
recent_summary: str # 最近几轮的摘要
long_term_summary: str # 长期总结
def should_summarize(state: State):
msg_count = len(state["messages"])
if msg_count > 20:
return "create_long_term_summary"
elif msg_count > 6:
return "create_recent_summary"
return ENDStructure:
最新消息 (2-6 条)
↓
recent_summary (压缩最近 10-20 轮)
↓
long_term_summary (压缩整个对话历史)2. Topic-driven abstracts
class State(MessagesState):
summary_by_topic: dict[str, str] # 按主题分类的摘要
def summarize_conversation(state: State):
# 先提取主题
topics = extract_topics(state["messages"])
# 为每个主题生成摘要
summaries = {}
for topic in topics:
topic_messages = filter_by_topic(state["messages"], topic)
summary = create_summary(topic_messages)
summaries[topic] = summary
return {"summary_by_topic": summaries}3. Smart summary trigger
Decide whether to summarize based on the dynamic content of the conversation:
def should_continue(state: State):
messages = state["messages"]
# 检查是否有话题转换
if detect_topic_change(messages):
return "summarize_conversation"
# 检查是否有重要信息
if has_important_info(messages):
return "summarize_conversation"
# 否则根据长度判断
if len(messages) > 6:
return "summarize_conversation"
return END4. Compare the abstract with the original text
Provide access to the original text while retaining the abstract:
class State(MessagesState):
summary: str
archived_messages: list # 被摘要的原始消息
def summarize_conversation(state: State):
summary_response = model.invoke(...)
# 归档被删除的消息
archived = state["messages"][:-2]
delete_messages = [RemoveMessage(id=m.id) for m in archived]
return {
"summary": summary_response.content,
"archived_messages": archived,
"messages": delete_messages
}Use:
- Debugging and auditing
- Users can view the original conversation
- Summary quality assessment
📊Performance optimization
1. Token cost analysis
No summary (full history):
轮次 1: 10 tokens (输入) + 20 tokens (输出) = 30 tokens
轮次 2: 30 tokens (输入) + 20 tokens (输出) = 50 tokens
轮次 3: 50 tokens (输入) + 20 tokens (输出) = 70 tokens
...
轮次 10: 210 tokens (输入) + 20 tokens (输出) = 230 tokens
总计: 约 1300 tokensWith summary:
轮次 1-3: 同上 (150 tokens)
轮次 4: 触发摘要
- 摘要生成: 70 tokens (输入) + 50 tokens (摘要) = 120 tokens
轮次 5: 50 tokens (摘要) + 20 tokens (新消息) + 20 tokens (输出) = 90 tokens
...
轮次 10: 类似轮次 5
总计: 约 800 tokens (节省 38%)2. Latency optimization
Option A: Asynchronous summary
# 当前:同步摘要(阻塞用户)
conversation → (6条消息后) → summarize → 返回
# 优化:异步摘要(不阻塞)
conversation → 返回
↓ (后台)
summarize (下次对话前完成)Option B: Batch summary
# 每 N 轮对话才触发一次摘要
def should_continue(state: State):
if len(state["messages"]) > 6 and len(state["messages"]) % 10 == 0:
return "summarize_conversation"
return END🔍 Frequently Asked Questions
Q1: Why use state.get("summary", "") instead of state["summary"]?
A: Prevent KeyError.
- On first run, there is no
summaryfield in the status state["summary"]will throw an exceptionstate.get("summary", "")returns to the default value""
Q2: Will RemoveMessage really delete the data?
A: Depends on Checkpointer.
MemorySaver: only deleted from the current state, historical snapshots remainSqliteSaver: also retain historical snapshots- Historical status can be accessed via
get_state_history()
Q3: What if the summary node fails?
Answer: Error handling can be added:
def summarize_conversation(state: State):
try:
# 摘要逻辑
response = model.invoke(messages)
# ...
return {"summary": response.content, "messages": delete_messages}
except Exception as e:
# 失败时不删除消息,保留原状态
print(f"Summarization failed: {e}")
return {} # 返回空字典,状态不变Q4: Can different digest strategies be used for different threads?
Answer: Yes! Store the policy in state:
class State(MessagesState):
summary: str
summary_threshold: int = 6 # 可配置
def should_continue(state: State):
threshold = state.get("summary_threshold", 6)
if len(state["messages"]) > threshold:
return "summarize_conversation"
return END
# 使用时
config = {
"configurable": {"thread_id": "user_1"}
}
graph.invoke({
"messages": [HumanMessage("...")],
"summary_threshold": 10 # 这个用户用更高的阈值
}, config)Q5: How to preserve the structure of the message (such as role, timestamp) in the summary?
Answer: Use structured snippets:
from pydantic import BaseModel
class StructuredSummary(BaseModel):
user_info: str
topics: list[str]
key_facts: list[str]
timestamp: str
def summarize_conversation(state: State):
response = model.with_structured_output(StructuredSummary).invoke(prompt)
# response 是 StructuredSummary 对象
summary_json = response.json()
return {"summary": summary_json, "messages": delete_messages}🎯 Practical application cases
Case 1: Customer service robot
Requirements: Support long-term customer service conversations and remember user problems and solutions.
class CustomerServiceState(MessagesState):
summary: str
customer_info: dict # 客户信息
issues: list[str] # 问题列表
def summarize_conversation(state: State):
# 提取客户信息和问题
prompt = """
Summarize this customer service conversation:
- Customer name and contact
- Issues reported
- Solutions provided
- Pending actions
"""
# ...Case 2: Educational tutoring robot
Requirements: Record students' learning progress and understanding.
class TutoringState(MessagesState):
summary: str
student_progress: dict # 学习进度
weak_areas: list[str] # 薄弱环节
def summarize_conversation(state: State):
prompt = """
Summarize the tutoring session:
- Topics covered
- Student's understanding level
- Areas needing improvement
- Homework assigned
"""
# ...Case 3: Project Management Assistant
Requirement: Track project discussions and decisions.
class ProjectState(MessagesState):
summary: str
decisions: list[str] # 决策记录
action_items: list[str] # 待办事项
def summarize_conversation(state: State):
prompt = """
Summarize the project discussion:
- Decisions made
- Action items and owners
- Blockers identified
- Next steps
"""
# ...📖 Further reading
- LangGraph Checkpointer official document
- MessagesState API Reference
- RemoveMessage detailed description
- Memory Management Best Practices
Summarize
Through this tutorial we learned:
✅ Core Technology:
- Use LLM to generate conversation summaries
RemoveMessageDelete old messagesMessagesStatesimplifies status management- Checkpointer implements persistence
- Thread isolates different conversations
✅ Key Benefits:
- Support long-term conversations without exceeding token limits
- Intelligent compression of history to retain key information
- Cost optimization (reducing token usage by 30-50%)
- User experience improvement (remember complete conversation history)
✅ Best Practices:
- Select summary triggering strategy based on application scenarios
- Use structured snippets to retain important information
- Reasonably configure the number of retained messages
- Choose the appropriate Checkpointer implementation
This is a key technology for building production-grade dialogue systems! 🚀