Day 6 — Adding Memory: Save & Recall Previous Plans

Welcome to Day 6 of the AI Task Helper Agent (Gemini Edition) series!
Until now, your agent could plan tasks and even perform multi-step reasoning — but today, we give it something extremely powerful:

Memory.

With memory, your agent becomes more useful, more personal, and more “alive.”
It can remember your past goals, recall previous plans, and show a history of your activity — just like a real assistant.

Let’s build it.


Goal

Today you’ll:

  • Add a simple JSON-based memory system
  • Store all generated plans (with timestamps + mode)
  • Add a --history flag to the CLI
  • Allow users to recall their recent activity

No vector databases.
No embeddings.
No RAG.
Just clean local JSON storage — perfect for a beginner agent.


1. What Does “Memory” Mean Here?

When we say memory, we simply mean:

Saving the output from your agent to a file,
and retrieving it later.

It doesn’t involve:

  • Embeddings
  • AI search
  • Knowledge bases
  • Vector databases (those come in advanced versions)

Right now, we just store:

  • The goal
  • The generated plan
  • The mode (simple or reasoned)
  • The timestamp

This keeps things simple while teaching the fundamentals of stateful AI agents.

If you’re new to AI concepts, this guide is a great companion:
https://tooltechsavvy.com/beginners-guide-to-ai-terms-you-actually-need-to-know/


2. Decide What to Store

Each memory entry will look like this:

{
  "goal": "Plan my week of workouts",
  "plan": "Final generated output from Gemini...",
  "mode": "reasoned",
  "timestamp": 1738439214
}

All entries go into a file:

plans_history.json

3. Implement memory.py (Day 6)

Create:

src/memory.py

Add this full code:

import json
import time
from pathlib import Path
from typing import List, Dict, Any

MEMORY_PATH = Path("plans_history.json")


def _load_raw() -> List[Dict[str, Any]]:
    if not MEMORY_PATH.exists():
        return []
    try:
        return json.loads(MEMORY_PATH.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return []


def _save_raw(data: List[Dict[str, Any]]) -> None:
    MEMORY_PATH.write_text(
        json.dumps(data, indent=2, ensure_ascii=False),
        encoding="utf-8",
    )


def save_plan(goal: str, plan: str, mode: str) -> None:
    history = _load_raw()
    history.append(
        {
            "goal": goal,
            "plan": plan,
            "mode": mode,
            "timestamp": int(time.time()),
        }
    )
    _save_raw(history)


def load_history(limit: int = 5) -> List[Dict[str, Any]]:
    history = _load_raw()
    history.sort(key=lambda x: x.get("timestamp", 0), reverse=True)
    return history[:limit]

This gives you:

Load saved plans
Append new ones
Sort by most recent
Display the latest history


4. Update TaskHelperAgent to Save Plans Automatically

Open:

src/agent.py

Add this wrapper method:

from textwrap import dedent
from typing import List
from memory import save_plan
from llm_client import generate_text

class TaskHelperAgent:
    # ...existing methods...

    def plan_and_store(self, user_goal: str, mode: str = "reasoned") -> str:
        """
        Wrapper for simple or reasoned planning.
        Saves the result, then returns it.
        """
        if mode == "simple":
            plan = self.plan_task(user_goal)
        else:
            plan = self.plan_task_reasoned(user_goal)

        save_plan(user_goal, plan, mode)
        return plan

Now every plan generated is automatically remembered.


5. Add History Option to CLI

Modify src/main.py to support:

  • --history
  • Using plan_and_store()

Here’s the updated full version:

import argparse
from agent import TaskHelperAgent
from memory import load_history


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        description="AI Task Helper Agent (Gemini)"
    )

    parser.add_argument(
        "goal",
        type=str,
        nargs="?",
        help="Your task or goal. Leave empty with --history to just show history.",
    )

    parser.add_argument(
        "--mode",
        type=str,
        choices=["simple", "reasoned"],
        default="reasoned",
        help="Planning mode: simple (1-step) or reasoned (2-step)",
    )

    parser.add_argument(
        "--history",
        action="store_true",
        help="Show recent plans instead of creating a new one.",
    )

    return parser


def main():
    parser = build_parser()
    args = parser.parse_args()

    if args.history:
        print("\n=== Recent Plans ===")
        for item in load_history():
            print(f"- Goal: {item['goal']} (mode={item['mode']})")
        return

    if not args.goal:
        parser.error("You must provide a goal unless using --history.")

    agent = TaskHelperAgent()
    plan = agent.plan_and_store(args.goal, mode=args.mode)

    print("\n=== AI Task Helper Agent ===")
    print(f"Goal: {args.goal}\n")
    print(plan)


if __name__ == "__main__":
    main()

6. Demo Commands

Generate a new plan (and store it):

python -m src.main "Plan my week of workouts"

Show history:

python -m src.main --history

Both features now work seamlessly — your agent officially remembers past interactions.


Bonus: Why Memory Matters

In real AI products, memory is everything.
It unlocks:

  • Personalized recommendations
  • Long-term workflows
  • Learning user habits
  • Multi-day projects
  • Contextual reasoning

Want more insights on how AI tools can help beginners?
https://tooltechsavvy.com/top-5-free-ai-tools-you-can-start-using-today-no-tech-skills-needed/


You’re Done with Day 6!

You’ve just turned your Task Helper Agent into a stateful, memory-capable assistant.

Today you added:

JSON-based memory storage
save_plan() and load_history()
Automatic saving via plan_and_store()
A full --history CLI feature

This transforms your assistant from a “task generator” into something that feels far more like a real personal AI helper.


Coming Next — Day 7: Build Your Own Custom Agent

Tomorrow, you’ll:

  • Create a domain-specific agent (fitness, coding, meal prep, productivity, etc.)
  • Customize prompts
  • Add personality
  • Build your final project

Leave a Comment

Your email address will not be published. Required fields are marked *