09. Delete message (RemoveMessage)

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.

Copy

# Configuration file for managing API keys as environment variables
from dotenv import load_dotenv

# Load API key information
load_dotenv()

Copy

 True 

Copy

# 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")

Copy

Build a basic LangGraph for tutorial progress

RemoveMessage Build the basic LangGraph required to use modifiers.

Copy

Visualize the graph.

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Delete message using RemoveMessage modifier

First, let's look at how to delete messages manually. Let's check the status of the current thread.

Copy

Copy

update_state When you call and pass id of the first message, that message is deleted.

Copy

Copy

Now if you check the messages, you can confirm that the first message has been deleted.

Copy

Copy

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.

Copy

Visualize the graph.

Copy

Now you can try this. graph You can call 2 times and then check the status.

Copy

Copy

Copy

Copy

When you check the final state, you can see that there are only three messages.

This is because I just deleted the previous messages.

Copy

Copy

Last updated