09. Delete message (RemoveMessage)
How to delete messages
One of the general states of graphs is a list of messages. Normally, only add messages to that state. But sometimes Remove message You may need to.
for this RemoveMessage Modifiers are available. And, RemoveMessage Modifier reducer Is to have a key.
basic MessagesState has a messages key, and the reducer of that key is RemoveMessage Allow modifiers.
This reducer RemoveMessage Delete the message from the key using
Settings
First, let's build a simple graph that uses messages. Essential reducer Include MessagesState Please note that you are using.
# Configuration file for managing API keys as environment variables
from dotenv import load_dotenv
# Load API key information
load_dotenv() True # Set up LangSmith tracking. https://smith.langchain.com
# !pip install -qU langchain-teddynote
from langchain_teddynote import logging
# Enter a project name.
logging.langsmith("CH17-LangGraph-Modules")Build a basic LangGraph for tutorial progress
RemoveMessage Build the basic LangGraph required to use modifiers.
Visualize the graph.

Delete message using RemoveMessage modifier
First, let's look at how to delete messages manually. Let's check the status of the current thread.
update_state When you call and pass id of the first message, that message is deleted.
Now if you check the messages, you can confirm that the first message has been deleted.
Dynamically delete more messages
You can also delete messages programmatically inside the graph.
Let's take a look at how to modify the graph to delete old messages (messages earlier than 3 previous messages) when the graph execution ends.
Visualize the graph.

Now you can try this. graph You can call 2 times and then check the status.
When you check the final state, you can see that there are only three messages.
This is because I just deleted the previous messages.
Last updated