In this tutorial, we will explore how to create an intelligent agent that remembers, learns, and adapts to us over time. we apply a Persistent memory and personalization System Using simple, rule-based logic to simulate how modern agentic AI frameworks store and recall relevant information. As we move forward, we see how agent responses evolve with experience, how memory decay helps prevent overload, and how personalization improves performance. Our goal is to understand step by step how Persistence transforms a static chatbot into a context-aware, evolving digital companion. check it out full code here,
import math, time, random
from typing import List
class MemoryItem:
def __init__(self, kind:str, content:str, score:float=1.0):
self.kind = kind
self.content = content
self.score = score
self.t = time.time()
class MemoryStore:
def __init__(self, decay_half_life=1800):
self.items: List[MemoryItem] = []
self.decay_half_life = decay_half_life
def _decay_factor(self, item:MemoryItem):
dt = time.time() - item.t
return 0.5 ** (dt / self.decay_half_life)
We established the foundation of our agent’s long-term memory. We define a MemoryItem class to hold each piece of information and create a memorystore with an exponential decay mechanism. We begin to lay the foundation for storing and storing information, just like human memory. check it out full code here,
def add(self, kind:str, content:str, score:float=1.0):
self.items.append(MemoryItem(kind, content, score))
def search(self, query:str, topk=3):
scored = []
for it in self.items:
decay = self._decay_factor(it)
sim = len(set(query.lower().split()) & set(it.content.lower().split()))
final = (it.score * decay) + sim
scored.append((final, it))
scored.sort(key=lambda x: x[0], reverse=True)
return [it for _, it in scored[:topk] if _ > 0]
def cleanup(self, min_score=0.1):
new = []
for it in self.items:
if it.score * self._decay_factor(it) > min_score:
new.append(it)
self.items = new
We extend the memory system by adding ways to insert, search, and clear old memories. We implement a simple similarity function and a decay-based cleaning routine, which enables the agent to remember relevant facts while automatically forgetting weak or old facts. check it out full code here,
class Agent:
def __init__(self, memory:MemoryStore, name="PersonalAgent"):
self.memory = memory
self.name = name
def _llm_sim(self, prompt:str, context:List[str]):
base = "OK. "
if any("prefers short" in c for c in context):
base = ""
reply = base + f"I considered len(context) past notes. "
if "summarize" in prompt.lower():
return reply + "Summary: " + " | ".join(context[:2])
if "recommend" in prompt.lower():
if any("cybersecurity" in c for c in context):
return reply + "Recommended: write more cybersecurity articles."
if any("rag" in c for c in context):
return reply + "Recommended: build an agentic RAG demo next."
return reply + "Recommended: continue with your last topic."
return reply + "Here's my response to: " + prompt
def perceive(self, user_input:str):
ui = user_input.lower()
if "i like" in ui or "i prefer" in ui:
self.memory.add("preference", user_input, 1.5)
if "topic:" in ui:
self.memory.add("topic", user_input, 1.2)
if "project" in ui:
self.memory.add("project", user_input, 1.0)
def act(self, user_input:str):
mems = self.memory.search(user_input, topk=4)
ctx = [m.content for m in mems]
answer = self._llm_sim(user_input, ctx)
self.memory.add("dialog", f"user said: user_input", 0.6)
self.memory.cleanup()
return answer, ctx
We design an intelligent agent that uses memory to inform its responses. We create a simulated language model simulator that customizes answers based on stored preferences and topics. Additionally, the perception function enables the agent to dynamically capture new insights about the user. check it out full code here,
def evaluate_personalisation(agent:Agent):
agent.memory.add("preference", "User likes cybersecurity articles", 1.6)
q = "Recommend what to write next"
ans_personal, _ = agent.act(q)
empty_mem = MemoryStore()
cold_agent = Agent(empty_mem)
ans_cold, _ = cold_agent.act(q)
gain = len(ans_personal) - len(ans_cold)
return ans_personal, ans_cold, gain
We now give our agents the ability to act and evaluate themselves. We allow it to recall memories to shape relevant answers and add a small evaluation loop to compare personalized responses versus a memory-less baseline, determining how much the memory helps. check it out full code here,
mem = MemoryStore(decay_half_life=60)
agent = Agent(mem)
print("=== Demo: teaching the agent about yourself ===")
inputs = [
"I prefer short answers.",
"I like writing about RAG and agentic AI.",
"Topic: cybersecurity, phishing, APTs.",
"My current project is to build an agentic RAG Q&A system."
]
for inp in inputs:
agent.perceive(inp)
print("\n=== Now ask the agent something ===")
user_q = "Recommend what to write next in my blog"
ans, ctx = agent.act(user_q)
print("USER:", user_q)
print("AGENT:", ans)
print("USED MEMORY:", ctx)
print("\n=== Evaluate personalisation benefit ===")
p, c, g = evaluate_personalisation(agent)
print("With memory :", p)
print("Cold start :", c)
print("Personalisation gain (chars):", g)
print("\n=== Current memory snapshot ===")
for it in agent.memory.items:
print(f"- it.kind | it.content[:60]... | score~round(it.score,2)")
Finally, we run the full demo to see our agent in action. We feed it user input, see how it recommends personalized actions, and examine its memory snapshots. We see the emergence of adaptive behavior, evidence that persistent memory transforms a stable script into a learning companion.
Finally, we demonstrate how adding memory and personalization makes our agent more human, able to remember preferences, adopt plans, and naturally forget old details. We see that even simple mechanisms like decay and retrieval significantly improve agent relevance and response quality. By the end, we realize that persistent memory is the foundation of next-generation agentic AI, which continuously learns, intelligently tailors experiences, and dynamically maintains context in a completely local, offline setup.
check it out full code hereFeel free to check us out GitHub page for tutorials, code, and notebooksAlso, feel free to follow us Twitter And don’t forget to join us 100k+ ml subreddit and subscribe our newsletterwait! Are you on Telegram? Now you can also connect with us on Telegram.
Asif Razzaq Marktechpost Media Inc. Is the CEO of. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. Their most recent endeavor is the launch of MarketTechPost, an Artificial Intelligence media platform, known for its in-depth coverage of Machine Learning and Deep Learning news that is technically robust and easily understood by a wide audience. The platform boasts of over 2 million monthly views, which shows its popularity among the audience.
🙌 Follow MarketTechPost: Add us as a favorite source on Google.