
How to Add Memory to a Python AI Agent
Your AI agent forgets everything the moment it responds. Ask it a follow-up question and it has zero context. Without memory, every interaction starts from scratch. Here's how to fix that in under 40 lines of Python -- no LangChain, no frameworks, just the standard library and the OpenAI SDK. The Code import json import os from pathlib import Path from openai import OpenAI MEMORY_FILE = " agent_memory.json " client = OpenAI () # uses OPENAI_API_KEY env var def load_memory () -> list [ dict ]: """ Load conversation history from disk. """ if Path ( MEMORY_FILE ). exists (): with open ( MEMORY_FILE , " r " ) as f : return json . load ( f ) return [] def save_memory ( messages : list [ dict ]) -> None : """ Persist conversation history to disk. """ with open ( MEMORY_FILE , " w " ) as f : json . dump ( messages , f , indent = 2 ) def chat ( user_input : str , messages : list [ dict ]) -> str : """ Send a message with full conversation history. """ messages . append ({ " role " : " user " ,
Continue reading on Dev.to Tutorial
Opens in a new tab




