#332: Long-Term Memory in LangGraph
Last week we added short-term memory to our LangGraph application. That works great as long as we stay in the same session. But when we want to keep the memory around between sessions, we need a different approach.
In this post we create our hand-written approach for a long-term memory solution. Do this only to understand what is going on and not to use it in production. For that purpose, we can use pre-build solutions that we explore next week.
Persist the InMemoryStore
To keep the memory around, we can take the InMemoryStore of LangGraph and dump it into a JSON file. That way we can see what is inside the store and load it back into the memory when we run our script once more:
Build the workflow
Our minimalistic workflow uses a State object and a greeter() method. The method gives us a customised greeting if it knows us and a generic one if we did not yet tell who we are:
Interact with the workflow
This time we generate a unique thread_id for each session and use a user_id to keep track of the user. As in a real use case, our sessions will come and go, but the knowledge about our user should stay around. To achieve that, we must not forget to persist the store after we let the user answered our questions:
We can run our script and pass our user id as a parameter:
$ python .\long_term_memory.py AA
Hello user, what is your name?
> Alice
Nice to meet you, Alice. Run me again to see me remember.
$ python .\long_term_memory.py AA
Hi Alice, welcome back!
$ python .\long_term_memory.py BB
Hello user, what is your name?
> Bob
Nice to meet you, Bob. Run me again to see me remember.
$ python .\long_term_memory.py BB
Hi Bob, welcome back!
What got persisted?
After our experiment with the two users, our memory.json file looks like this:
[
{
"namespace": [
"users",
"AA"
],
"key": "profile",
"value": {
"name": "Alice"
}
},
{
"namespace": [
"users",
"BB"
],
"key": "profile",
"value": {
"name": "Bob"
}
}
]
We can see the two names we specified and that are now tracked for the specific user id.
Next
With this minimal implementation of a long-term memory store, we can keep the knowledge about the users around. All we need is the matching user_id and we know who they are.
Next week we will switch to a pre-built solution for persistent storage. This will let us remember users, rerun failed tasks, and allows us to debug our graph.