LangMem
LangMem (version 0.0.30) is a Python library providing prebuilt utilities for memory management and retrieval, specifically designed for AI agents and LLM applications. It offers abstractions for integrating with various embedding models and vector stores, facilitating the creation of intelligent systems with long-term memory. The library is under active development with frequent minor updates.
Warnings
- breaking API stability is not guaranteed below version 1.0.0. The library is in early development (0.0.x), and breaking changes may occur frequently between minor versions without extensive prior notice.
- gotcha Many useful components (e.g., specific embedding models, vector stores) are optional dependencies. You must explicitly install them (e.g., `pip install openai chromadb`) to use them with `langmem`.
- gotcha When initializing vector stores like `Chroma`, ensure you pass the embedding model instance using the correct parameter name, which is `embedding_function`, not `embeddings`.
- gotcha For cloud-based embedding services (e.g., OpenAIEmbeddings), the necessary API key (e.g., `OPENAI_API_KEY`) must be set in your environment variables or passed directly during initialization. Forgetting this will lead to authentication errors.
Install
-
pip install langmem -
pip install langmem[openai,chromadb]
Imports
- MemoryManager
from langmem import MemoryManager
- OpenAIEmbeddings
from langmem.embeddings import OpenAIEmbeddings
- Chroma
from langmem.vectorstores import Chroma
Quickstart
import os
from langmem import MemoryManager
from langmem.embeddings import OpenAIEmbeddings
from langmem.vectorstores import Chroma
# NOTE: For this example, you need to install 'openai' and 'chromadb'
# pip install langmem openai chromadb
# Ensure OPENAI_API_KEY is set in your environment variables.
# For testing, you can uncomment and set it directly:
# os.environ['OPENAI_API_KEY'] = 'YOUR_OPENAI_API_KEY'
openai_api_key = os.environ.get('OPENAI_API_KEY', '')
if not openai_api_key:
print("Warning: OPENAI_API_KEY environment variable not set. OpenAIEmbeddings might fail.")
# Initialize embeddings and vector store
embeddings = OpenAIEmbeddings(openai_api_key=openai_api_key)
vectorstore = Chroma(embedding_function=embeddings) # Chroma requires embedding_function
# Initialize MemoryManager
memory_manager = MemoryManager(vectorstore=vectorstore)
# Add memories
memory_manager.add_memory("The quick brown fox jumps over the lazy dog.")
memory_manager.add_memory("The quick red bird flies high in the sky.")
memory_manager.add_memory("The lazy dog often naps under the oak tree.")
# Recall information
results = memory_manager.recall("What is the fox doing?")
print("\nRecall results for 'What is the fox doing?':", results)
results = memory_manager.recall("Where does the dog nap?")
print("\nRecall results for 'Where does the dog nap?':", results)