Stay Hungry,Stay Foolish!

[Langgraph] Remove a message from the graph state

[Langgraph] Remove a message from the graph state

https://github.com/langchain-ai/langchain/discussions/22632

def function_node2(state):
updated_messages = state["messages"][:-1]
return {"messages":updated_messages}

 

https://www.studywithgpt.com/zh-cn/tutorial/632agd

def delete_messages(state):
    messages = state["messages"]
    if len(messages) > 3:
        return {"messages": [RemoveMessage(id=m.id) for m in messages[:-3]]}

 

https://aiproduct.engineer/tutorials/langgraph-tutorial-message-history-management-with-sliding-windows-unit-12-exercise-3

def message_windowing(state: State) -> State:
    """Maintain optimal message history through window-based pruning.

    This function implements several key concepts:
    1. Automatic message pruning
    2. Window-based history management
    3. State preservation during updates

    The windowing process follows this flow:
    1. Check current message count
    2. Apply window constraints if needed
    3. Preserve state consistency

    Args:
        state: Current conversation state with messages and window configuration

    Returns:
        State: Updated state with windowed message history

    Example:
        >>> state = {
        ...     "messages": [HumanMessage(content=f"Message {i}")
        ...                 for i in range(5)],
        ...     "summary": "",
        ...     "window_size": 3
        ... }
        >>> result = message_windowing(state)
        >>> len(result["messages"]) # Should be 3
    """
    if len(state["messages"]) > state["window_size"]:
        state["messages"] = state["messages"][-state["window_size"] :]
    return state

 

Initialize graph with windowed state support

graph = StateGraph(State)

Add windowing node for message management
graph.add_node("windowing", message_windowing)
Configure entry point with immediate windowing
graph.add_edge(START, "windowing")

 

posted @ 2025-04-20 16:30  lightsong  阅读(95)  评论(0)    收藏  举报
千山鸟飞绝,万径人踪灭