DeleteMessages
Author: Suhyun Lee
Design:
Peer Review:
This is a part of LangChain Open Tutorial
Overview
In LangChain, you can not only add messages but also delete them when necessary. The RemoveMessage tool is used for this purpose.
This tool sends a deletion request for a specific message. The deletion is then processed according to the reducer rules defined in MessagesState.
In essence, RemoveMessage initiates the deletion, the reducer determines how those requests are processed, and MessagesState serves as the storage and the management system for messages.
Table of Contents
References
Environment Setup
Setting up your environment is the first step. See the Environment Setup guide for more details.
[Note]
The langchain-opentutorial is a package of easy-to-use environment setup guidance, useful functions and utilities for tutorials.
Check out the langchain-opentutorial for more details.
You can set API keys in a .env file or set them manually.
[Note] If you’re not using the .env file, no worries! Just enter the keys directly in the cell below, and you’re good to go.
Building a Basic LangGraph
LangGraph offers a powerful way to design workflows that integrate message state management and tool invocation. This section demonstrates the basic process of constructing a LangGraph.
Key Components
MemorySaver: A memory object for saving checkpoints, allowing you to save and restore conversation states.ToolNode: A node for executing custom tools. In this tutorial, it includes asearchtool that simulates a web search.MessagesState: Stores and updates message states, serving as the central hub for state-based workflows.StateGraph: A graph object that defines the state-based workflow, controlling the flow of execution between nodes and edges.should_continue: A conditional function that determines the next node to execute based on the current statue of the agent.
Key Workflow Details
Defining and Registering Tools:
The
searchfunction simulates a web search and returns results for a given query.This tool is then wrapped in a
ToolNodeand integrated into the LangGraph.
Model Initialization and Binding:
Initialize an LLM model, such as
ChatOpenAI, and bind it with tools to ensure they can be executed during runtime.
Defining the Workflow:
The
StateGraphis used to define the workflow by adding nodes and connecting them with edges.The workflow begins at the
STARTnode. Theagentis executed first, calling tools as needed, and then control returns to the agent.
Conditional Flow Control:
The
should_continuefunction checks the state of the last message to determine whether a tool should be executed or the workflow should terminate.

The following code snippet, for event in app.stream({"messages": [input_message]}, config, stream_mode="values"), operates as follows:
Calling
app.stream():
This initiates the workflow and streams each event.
Parameters:
{"messages": [input_message]}: Sets the initial message for the workflow.config: Contains configuration values, includingthread_idset to"1".stream_mode="values": Specifies the streaming mode as value-based.
Loop Behavior:
The loop iterates through each event generated by the workflow.
Event details:
event["messages"][-1]: Retrieves the most recent message.pretty_print(): Prints the retrieved message.
Key Streaming Modes of app.stream():
valuesMode
This mode receives the entire state of the graph after each node execution.
Suitable for basic state monitoring.
Example: Receiving the complete response from an LLM after it finishes its response.
updatesMode
This mode receives only the changes made to the state after each node execution.
Useful for efficient state management.
Example: Receiving only the newly added content compared to the previous state.
messagesMode
This mode provides the most detailed, real-time information.
Ideal for real-time applications, such as chatbots.
Example: Observing the step-by-step "thought process" of an LLM in real-time. For instance, "Thinking..." → "Chocolate is..." → "a delicious snack."
Deleting Messages
There are two primary methods for deleting messages within a LangGraph workflow: Manual Deletion and Dynamic Deletion . Let's take a closer look at each method.
Manual Deletion of Messages
This section demonstrates how to manually retrieve message logs from the LangGraph workflow, delete specific messages, and then update the graph's state. This process enables effective message management and conversation record manipulation.
Key Steps for Manual Deletion
Message Retrieval:
Use the
app.get_state(config)method to extract the list of messages from the current state.Use
pretty_print()method to display each message in a user-friendly format.
Message Deletion:
Utilize a
RemoveMessageobject, specifying the ID of the message to delete.The code example demonstrates removing the first message in the array.
State Update:
Use the
app.update_state(config, ...)method to apply the deletion and update the graph's state.After the update, retrieve and display the message list again to verify the deletion.
Code Flow
Output Stored Messages:
Retrieve the messages from the current state using
messages = app.get_state(config).values["messages"].Iterate through the
messsageslist and print each message to review the current conversation history.
Delete a Specific Message:
Use
RemoveMessage(id=messages[0].id)to create a delete request for the first message.Update the graph's state using
app.update_state(config, ...)to reflect the deletion.
Output Updated Messages:
After updating the state, retrieve the updated message list and print it to confirm the deletion.
Dynamic Deletion of Messages
Dynamic deletion automates the process of deleting older messages during workflow execution, ensuring that only the most recent messages are retained.
Key Components for Dynamic Deletion
delete_messages(state: dict) -> dict:
This function implements the logic for deleting old messages when it checks if the number of messages exceeds a specific limit (e.g., 3). It retains only the latest ones.
should_continue(state: dict) -> str:
This conditional function determins the next node to execute based on the current state.
If there is no function call in the current messages, the workflow proceeds to the
delete_messagesnode. If a function call exists, the workflow proceeds to theactionnode.
StateGraph: Defines the state-based workflow, connecting theagent,action, anddelete_messagesnodes with appropriate edges.
Key Details
Message Management:
The
delete_messagesfunction manages the message state by removing older messages during prolonged conversations, thus maintaining memory efficiency.
Conditional Flow Control:
The
should_continuefunction inspects the state of the last message to determine if a tool call is required. This determines the next node in the execution flow.
Workflow Definition:
The
StateGraphdefines the workflow by adding nodes foragent,action, anddelete_messagesnodes.Each node is configured to follow the appropriate flow based on state and conditions.
Memory Checkpoint Integration:
The
MemorySaverobject allows for saving and restoring checkpoints, enabling seamless compilation and resumption of the workflow.
Process Flow
The workflow starts at the
STARTnode and executes theagentnode.The
should_continuefunction then determines the next node based on the current state:
If no function call is present in the messages, the workflow proceeds to the
delete_messagesnode.If a function call is present, the workflow proceeds to the
actionnode.
Each node transitions to the next execution path based on the defined conditions.
The
delete_messagenode then connects to theENDnode, terminating that branch of the workflow.

Final State: Because messages are automatically deleted when the count exceeds 3, only the 3 most recent messages are retained in the final state.
Last updated