iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
自我挑戰組

從讀書筆記到可落地 AI:LangChain、LangSmith 與 Agent 工具 30 講系列 第 16

Day 16|Agent Design - Memory - 客製化的LangChain/LangGraph(2/5)

  • 分享至 

  • xImage
  •  

目標先講清楚:
LangChain/LangGraph框架透過不同的agent使用不同state、reducers的設計,可以進行更細緻的memory管理

三種以上的策略

大致整理LangChain/LangGraph的Memory管理有以下三種技巧可以使用;這三種在整個graph都可一起使用.

1) 上下文隔離

多代理(multi-agent)時,每個子任務有自己的上下文窗格,和state,能避免互相汙染;只把必要摘要回傳給總監(supervisor)彙整,避免全域訊息不斷膨脹。
https://ithelp.ithome.com.tw/upload/images/20250930/20178568zZTsxlGXan.png

2) 可設計的Reducers

把「記憶」當作「狀態(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的邏輯,整合資訊.

3)先壓縮再彙整

類似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; 如果報錯,也是直接截斷

LangChain vs OpenAI Agent SDK

簡單整理兩個框架的使用時機:

方案 優點 缺點
OpenAI Agents SDK(Trimming / Summarizing) • 上手快:不用先建 State/Reducer;一行開 Session 就能跑• Trimming 決定論、延遲低;Summarizing 能保留長程要點• 適合 POC、單代理、無強治理需求 • 多分支合併與狀態規則不夠「型別化」• 摘要可能漂移;要自己寫模板和防呆
LangChain / LangGraph State/Reducer 讓記憶調整、篩選• 原生並行合併規則;上下文隔離清楚 • 前期設計成本較高• 如果只是短對話/臨時 demo,顯得過度工程

接下來要做什麼

分享長期記憶的處理套件-mem0


參考資源

  1. Google Agentic Design Patterns-CH8
  2. deep_research_from_scratch
  3. langchain-academy

上一篇
Day 15|Agent Design - Memory - 簡單、方便的Openai Agent SDK(1/5)
下一篇
Day 17|Agent Design - Memory - 長期記憶的處理-mem0(3/5)
系列文
從讀書筆記到可落地 AI:LangChain、LangSmith 與 Agent 工具 30 講17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言