Build AI Apps with Python: AI Agent That Remembers — JSON Memory Tools | Episode 19
Video: Build AI Apps with Python: AI Agent That Remembers — JSON Memory Tools | Episode 19 by Taught by Celeste AI - AI Coding Coach
Watch full page →Build AI Apps with Python: AI Agent That Remembers — JSON Memory Tools
Creating an AI agent that retains knowledge over time is essential for meaningful research applications. This example demonstrates how to equip an agent with persistent memory using JSON storage, enabling it to save, recall, and build on information across multiple sessions.
Code
import json
import os
# File to store the agent's memory persistently
MEMORY_FILE = "agent_memory.json"
def load_memory():
"""Load saved notes from JSON file or return empty dict if none."""
if os.path.exists(MEMORY_FILE):
with open(MEMORY_FILE, "r") as f:
return json.load(f)
return {}
def save_memory(memory):
"""Save the memory dictionary back to the JSON file."""
with open(MEMORY_FILE, "w") as f:
json.dump(memory, f, indent=2)
def save_note(topic, note):
"""Save a note under a specific topic."""
memory = load_memory()
if topic not in memory:
memory[topic] = []
memory[topic].append(note)
save_memory(memory)
print(f"Note saved under topic '{topic}'.")
def recall_notes(topic):
"""Retrieve all notes saved under a topic."""
memory = load_memory()
return memory.get(topic, [])
def lookup_info(topic):
"""Mock research tool that returns info about a topic."""
research_db = {
"Python": "Python is a versatile programming language known for readability.",
"AI": "Artificial Intelligence enables machines to perform tasks that require human intelligence.",
"JSON": "JSON is a lightweight data-interchange format easy for humans to read and write."
}
return research_db.get(topic, "No information found on this topic.")
# Example agent workflow
topic = "AI"
# Agent looks up info
info = lookup_info(topic)
print(f"Lookup info: {info}")
# Agent saves the info as a note
save_note(topic, info)
# Later, agent recalls notes on the topic
notes = recall_notes(topic)
print(f"Recalled notes for '{topic}':")
for i, note in enumerate(notes, 1):
print(f"{i}. {note}")
Key Points
- Persistent memory is implemented by saving and loading notes from a JSON file.
- The save_note tool appends new information under a topic, building knowledge over time.
- The recall_notes tool retrieves all saved notes for a given topic without re-searching.
- A mock lookup_info function simulates research to provide new information for saving.
- This approach enables an AI agent to remember and build on knowledge across multiple sessions.