A Long-Term Memory Agent
This tutorial shows how to implement an agent with long-term memory capabilities using LangGraph. The agent can store, retrieve, and use memories to enhance its interactions with users.
Inspired by papers like MemGPT and distilled from our own works on long-term memory, the graph extracts memories from chat interactions and persists them to a database. "Memory" in this tutorial will be represented in two ways:
- a piece of text information that is generated by the agent
- structured information about entities extracted by the agent in the shape of
(subject, predicate, object)
knowledge triples.
This information can later be read or queried semantically to provide personalized context when your bot is responding to a particular user.
The KEY idea is that by saving memories, the agent persists information about users that is SHARED across multiple conversations (threads), which is different from memory of a single conversation that is already enabled by LangGraph's persistence.
You can also check out a full implementation of this agent in this repo.
Install dependencies
%pip install -U --quiet langgraph langchain-openai langchain-tavily tiktoken
import getpass
import os
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
_set_env("TAVILY_API_KEY")
OPENAI_API_KEY: ········
TAVILY_API_KEY: ········
import json
from typing import List, Literal, Optional
import tiktoken
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.messages import get_buffer_string
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig
from langchain_core.tools import tool
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_openai import ChatOpenAI
from langchain_openai.embeddings import OpenAIEmbeddings
from langchain_tavily import TavilySearch
from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph import END, START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode
Define vectorstore for memories
First, let's define the vectorstore where we will be storing our memories. Memories will be stored as embeddings and later looked up based on the conversation context. We will be using an in-memory vectorstore.
recall_vector_store = InMemoryVectorStore(OpenAIEmbeddings())