Memory Search
How to search for user memories using different retrieval methods.
last_n: Retrieves the last n memoriesfirst_n: Retrieves the first n memoriesagentic: Retrieves memories using agentic search
Code
1from kern.db.postgres import PostgresDb2from kern.memory import MemoryManager, UserMemory3from kern.models.openai import OpenAIResponses4from rich.pretty import pprint56db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"78memory_db = PostgresDb(db_url=db_url)910memory = MemoryManager(model=OpenAIResponses(id="gpt-5.2"), db=memory_db)1112john_doe_id = "john_doe@example.com"13memory.add_user_memory(14 memory=UserMemory(memory="The user enjoys hiking in the mountains on weekends"),15 user_id=john_doe_id,16)17memory.add_user_memory(18 memory=UserMemory(19 memory="The user enjoys reading science fiction novels before bed"20 ),21 user_id=john_doe_id,22)23print("John Doe's memories:")24pprint(memory.get_user_memories(user_id=john_doe_id))2526memories = memory.search_user_memories(27 user_id=john_doe_id, limit=1, retrieval_method="last_n"28)29print("\nJohn Doe's last_n memories:")30pprint(memories)3132memories = memory.search_user_memories(33 user_id=john_doe_id, limit=1, retrieval_method="first_n"34)35print("\nJohn Doe's first_n memories:")36pprint(memories)3738memories = memory.search_user_memories(39 user_id=john_doe_id,40 query="What does the user like to do on weekends?",41 retrieval_method="agentic",42)43print("\nJohn Doe's memories similar to the query (agentic):")44pprint(memories)Usage
Set up your virtual environment
1uv venv --python 3.122source .venv/bin/activate1uv venv --python 3.122.venv\Scripts\activateInstall dependencies
1uv pip install -U kern-aiRun Example
1python memory-search.py1python memory-search.py