目標先講清楚:
LangChain/LangGraph框架透過不同的agent使用不同state、reducers的設計,可以進行更細緻的memory管理
大致整理LangChain/LangGraph的Memory管理有以下三種技巧可以使用;這三種在整個graph都可一起使用.
多代理(multi-agent)時,每個子任務有自己的上下文窗格,和state,能避免互相汙染;只把必要摘要回傳給總監(supervisor)彙整,避免全域訊息不斷膨脹。
把「記憶」當作「狀態(state)」管理,而不是把整段對話直接丟給模型。提供以下的function可以提供給state進行新、舊資訊整合的方式;以下只是將新、舊int加到同一個array中,其實可以依照需求,做更複雜的設計。(ex. 追加、合併、覆寫)
def Reducers(left: list | None, right: list | None) -> list:
"""Safely combine two lists, handling cases where either or both inputs might be None.
Args:
left (list | None): The first list to combine, or None.
right (list | None): The second list to combine, or None.
Returns:
list: A new list containing all elements from both input lists.
If an input is None, it's treated as an empty list.
"""
if not left:
left = []
if not right:
right = []
return left + right
Reducers是一個function的名稱(可以取其他任何function name)
class CustomReducerState(TypedDict):
foo: Annotated[list[int], Reducers]
state的key-foo會依照著個function的邏輯,整合資訊.
類似OpenAI Agent SDK的-TrimmingSession和SummarizingSession,但沒有OpenAI Agent SDK方便;需要自己寫function邏輯,但可以依需求,放在tool, sub-agent使用或是supervisor agent處理邏輯中.
def summarize_webpage_content(webpage_content: str) -> str:
"""Summarize webpage content using the configured summarization model.
Args:
webpage_content: Raw webpage content to summarize
Returns:
Formatted summary with key excerpts
"""
try:
# Set up structured output model for summarization
structured_model = summarization_model.with_structured_output(Summary)
# Generate summary
summary = structured_model.invoke([
HumanMessage(content=summarize_webpage_prompt.format(
webpage_content=webpage_content,
date=get_today_str()
))
])
# Format summary with clear structure
formatted_summary = (
f"<summary>\n{summary.summary}\n</summary>\n\n"
f"<key_excerpts>\n{summary.key_excerpts}\n</key_excerpts>"
)
return formatted_summary
except Exception as e:
print(f"Failed to summarize webpage: {str(e)}")
return webpage_content[:1000] + "..." if len(webpage_content) > 1000 else webpage_content
Summary使用llm去處理,要定義Prompt和schema; 如果報錯,也是直接截斷
簡單整理兩個框架的使用時機:
方案 | 優點 | 缺點 |
---|---|---|
OpenAI Agents SDK(Trimming / Summarizing) | • 上手快:不用先建 State/Reducer;一行開 Session 就能跑• Trimming 決定論、延遲低;Summarizing 能保留長程要點• 適合 POC、單代理、無強治理需求 | • 多分支合併與狀態規則不夠「型別化」• 摘要可能漂移;要自己寫模板和防呆 |
LangChain / LangGraph | • State/Reducer 讓記憶調整、篩選• 原生並行與合併規則;上下文隔離清楚 | • 前期設計成本較高• 如果只是短對話/臨時 demo,顯得過度工程 |
分享長期記憶的處理套件-mem0