0Pricing
AI Agents · Lesson

Simple Memory Stores (Key-Value)

Persist facts the user mentions (name, preferences) in a key-value store and inject them into the system prompt on each turn.

Simple Memory Stores (Key-Value) is a free AI Agents lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Agents learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Cheapest Long-Term Memory

Before vector DBs and embeddings, there is the humble key-value store. For storing user-specific facts (name, preferences, settings), this is all you need.

What to Store

Good candidates for KV memory:

  • User name and language
  • Preferences (units, timezone, tone)
  • Sticky context (current project, current topic)
  • Recent tool credentials / API tokens

A Tiny In-Memory Store

For a single-process prototype:

memory = {
    'user_name': 'Alice',
    'units': 'celsius',
    'language': 'tr'
}

def remember(key, value):
    memory[key] = value

def recall(key, default=None):
    return memory.get(key, default)

remember('city', 'Istanbul')
print("Recalled user_name:", recall('user_name'))
print("Recalled city:", recall('city'))
print("Recalled missing key:", recall('country', 'unknown'))

Inject Into the System Prompt

On each turn, render the KV store into the system prompt:

def build_system_prompt(user_id):
    facts = load_facts(user_id)
    rendered = '\n'.join(f'- {k}: {v}' for k, v in facts.items())
    return f'''
You are AssistantBot.

Known facts about this user:
{rendered}

Use these to personalise replies.
'''

Use Redis for Multi-User

For a production agent, use Redis:

import redis
r = redis.Redis()

def remember(user_id, key, value):
    r.hset(f'mem:{user_id}', key, json.dumps(value))

def recall_all(user_id):
    raw = r.hgetall(f'mem:{user_id}')
    return {k.decode(): json.loads(v) for k, v in raw.items()}

Or Just Postgres

Postgres works too — a JSON column per user:

CREATE TABLE user_memory (
    user_id TEXT PRIMARY KEY,
    facts JSONB NOT NULL DEFAULT '{}'
);

-- Update one field:
UPDATE user_memory SET facts = facts || '{"units": "celsius"}' WHERE user_id = $1;

Memory as a Tool

Expose memory operations as tools so the agent itself can write to memory:

tools = [
    {'name': 'remember', 'description': 'Save a fact about the user', 'parameters': {...}},
    {'name': 'forget', 'description': 'Remove a stored fact', 'parameters': {...}}
]

# The agent can call remember('user_name', 'Alice') itself.
for t in tools:
    print(f"{t['name']}: {t['description']}")

Prevent Memory Bloat

Cap the number of stored keys per user (50 or 100). Otherwise the system prompt grows without bound.

TTLs and Decay

Some memories are short-lived. Use Redis expirations:

r.hset(f'mem:{user_id}', 'last_topic', 'pricing')
r.expire(f'mem:{user_id}', 3600)  # 1 hour

User-Editable Memory

Let users see and edit what the agent remembers about them — ChatGPT memory works this way. Builds trust and avoids creepy mistakes.

Privacy: PII Care

Stored facts often include PII. Encrypt sensitive fields at rest, use per-user encryption keys, and delete on account closure.

From KV to Vector

KV is great for structured facts. For unstructured facts ("user prefers casual tone, likes anime references, hates emojis"), a vector store is better. We cover that in the next course.

When to Use KV Memory

For which kind of memory is a plain key-value store best?

Recap

For 90% of personal-assistant use cases, a Redis or Postgres KV store + rendering into the system prompt is enough memory.

Frequently asked questions

Is the “Simple Memory Stores (Key-Value)” lesson free?

Yes — the full text of “Simple Memory Stores (Key-Value)” is free to read here on the web, and the AI Agents course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Agents course, upgrade to CoddyKit PRO.

What will I learn in “Simple Memory Stores (Key-Value)”?

Persist facts the user mentions (name, preferences) in a key-value store and inject them into the system prompt on each turn. You practise AI Agents with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start AI Agents?

No prior experience is required. AI Agents on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Simple Memory Stores (Key-Value)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this AI Agents lesson?

Yes. Every AI Agents lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Short-Term Memory in the Context Window
  2. Why Long Contexts Don't Scale
  3. Summarisation as Compression
  4. Simple Memory Stores (Key-Value)
← Back to AI Agents