Delete some messages from the State in a long conversation

I’m using create_react_agent along with an InMemorySaver checkpointer to manage a conversation.
Is there a way to do the following: after each turn (so after the agent gives the answer to the user) I want to delete from the state[‘messages’] all messages that are not HumanMessage, AIMessage.

Hi @radu-juyo

Use that Memory - Docs by LangChain

And leverage post_model_hook of create_react_agent

Nonetheless, I find it not a good pattern to remove almost all messages after each turn. E.g. When you remove an AiMessage that called a tool, your next LLM call will fail.

Why do you actually want to remove the messages? What’s the purpose?

I only want to remove ToolMessages, but keep the user questions (I guess these are in HumanMessages) and also the AI answers (AIMessage). Probably also the SystemMessage. Everything else I would like to delete after each turn.

And I want to do the removal only after (or before) a full graph run.

Related to post or pre hooks: can I make this work only after a graph run is finished (or before it starts), not inside a graph?

@radu-juyo does it mean you want to build one turn chat without any history between human messages?

No, I want to remove ToolMessages after each turn.

then simply create a loop that I mentioned in one of my previous messages