
This is the tutorial version of Agentic Memory Systems: The Complete Guide. The guide explains what an agentic memory system is and why the multi-store stack hurts. This post is the how — a working chat memory system you can stand up in an afternoon, with code you can paste, on data you bring. The implementation uses SynapCores' Community Edition because that's the engine I work on every day, but the pattern translates to any stack that supports vectors and a graph in one place (or a vector store plus a graph store if you're willing to wear the sync cost).
By the end of this you'll have: a chat agent that remembers facts across sessions, can recall by meaning and by relationship, summarizes old conversations into durable facts, and lets you audit which memory contributed to which answer. The total code is under 300 lines and the demo data is fictional.
What we're building
A chat memory system has four jobs:
- Write new memories from each turn of the conversation.
- Retrieve relevant memories when the user sends a new message.
- Consolidate old detailed memories into durable summaries (so the store doesn't grow forever).
- Audit which memories influenced any given response.
We'll build all four, in order, with real code at each step.
Step 0: setup
You'll need:
- SynapCores Community Edition running locally on port 8080.
- An OpenAI-compatible LLM endpoint (the CE ships with an Ollama integration, or point at OpenAI/Anthropic).
- Python 3.10+ for the orchestration. The Rust SDK or any HTTP client would also work; I'll use Python for readability.
A minimal client setup:
import os, json, requests
SC_URL = os.environ.get('SYNAPCORES_URL', 'http://localhost:8080')
def sql(query, params=None):
r = requests.post(f"{SC_URL}/sql", json={"query": query, "params": params or {}})
r.raise_for_status()
return r.json().get('data', [])
Step 1: the memory schema

A memory has a few essential properties: who/what it's about, what it says, when it was created, how important it is, and an embedding for semantic recall. We'll also model entities and edges so we can do multi-hop recall later.
-- One row per atomic memory
CREATE TABLE chat_memory (
id BIGINT PRIMARY KEY,
agent_id TEXT NOT NULL,
user_id TEXT NOT NULL,
session_id TEXT,
content TEXT NOT NULL,
memory_type TEXT NOT NULL, -- 'fact' | 'event' | 'preference' | 'summary'
importance DOUBLE DEFAULT 0.5,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_accessed_at TIMESTAMP,
source_turn_id BIGINT, -- for audit
embedding VECTOR(384)
);
CREATE INDEX chat_memory_embedding_idx ON chat_memory
USING HNSW (embedding)
WITH (m = 32, ef_construction = 400, metric = 'cosine');
-- Per-user recall goes through this B-tree index
CREATE INDEX chat_memory_user_idx ON chat_memory (user_id);
-- The graph side: entities mentioned, edges between them
-- (SynapCores' Cypher engine shares storage with the SQL planner,
-- so we MERGE entities at write time and traverse them at read time.)
Two things worth noting:
memory_typeseparates facts from events from preferences. Different recall strategies later. (Yes, this is the cognitive-architectures taxonomy from the memory guide.)source_turn_idis the audit hook. Every memory points back to the chat turn that produced it.- The HNSW index syntax is SynapCores 2.4.3's: the column goes in bare and the metric is an option. pgvector-style
USING HNSW (embedding COSINE)is a parse error. The HNSW index serves top-k similarity searches across all memories. The per-user recall query in Step 3 goes throughchat_memory_user_idx, which narrows to one user's rows before the blended score is computed.
Step 2: writing memories
When a chat turn comes in, we don't just dump the whole message into memory — that fills the store with junk. We extract three things:
- Atomic facts the user stated or implied ("I live in San Diego").
- Preferences they revealed ("I prefer concise answers").
- Events that happened ("they asked about pricing").
The extraction itself is a call to the LLM, but the write is in SQL. The trick is to make the LLM extraction deterministic-ish by giving it a schema.
def extract_memories(user_message, assistant_response, user_id):
prompt = f"""
You are a memory extractor. From the conversation turn below, extract:
- facts (things stated as true about the user or world)
- preferences (stated likes/dislikes/style preferences)
- events (things that happened in the conversation)
Return JSON ONLY:
{{"facts": [...], "preferences": [...], "events": [...]}}
User: {user_message}
Assistant: {assistant_response}
"""
# SynapCores can do this inline with GENERATE() but we'll do it
# from Python so the tutorial reads like a normal LLM client.
r = sql("SELECT GENERATE(:p) AS out", {"p": prompt})
return json.loads(r[0]['out'])
The corresponding SQL write:
def write_memory(agent_id, user_id, session_id, content, memory_type,
importance=0.5, source_turn_id=None):
sql("""
INSERT INTO chat_memory
(id, agent_id, user_id, session_id, content, memory_type,
importance, source_turn_id, embedding)
VALUES (
NEXTVAL('chat_memory_id_seq'),
:a, :u, :s, :c, :t, :i, :st,
EMBED(:c)
)
""", {
"a": agent_id, "u": user_id, "s": session_id, "c": content,
"t": memory_type, "i": importance, "st": source_turn_id,
})
Note the EMBED(:c) inside the INSERT. The embedding happens in the database — no Python service calling an embedding API and writing the result back. This is the SQLv2 point in concrete form: embedding is a SQL function, not a foreign call.
For the entity graph side, we merge entities mentioned in the memory and add MENTIONS edges:
def merge_entities(memory_id, entity_list):
for ent in entity_list:
sql("""
GRAPH MERGE (e:Entity {name: :n, type: :t})
GRAPH MERGE (m:Memory {id: :mid})
GRAPH MERGE (m)-[:MENTIONS]->(e)
""", {"n": ent["name"], "t": ent["type"], "mid": memory_id})
Now every memory is both a row (with an embedding) and a graph node (with edges to its entities).
Step 3: retrieval
When a new user message arrives, we retrieve memories that are relevant. "Relevant" is the magic word. There are three signals:
- Semantic similarity: the memory says something close to the user's question.
- Recency: newer memories are more likely to apply.
- Importance: facts we've already flagged as high-importance get a boost.
A single SQL query fuses all three:
-- Recall query: top-k memories by weighted score
SELECT m.id, m.content, m.memory_type, m.importance, m.created_at,
COSINE_SIMILARITY(m.embedding, EMBED(:q)) * 0.6
+ (1.0 / (1.0 + EXTRACT(EPOCH FROM (NOW() - m.created_at))/86400)) * 0.25
+ m.importance * 0.15
AS score
FROM chat_memory m
WHERE m.user_id = :u
AND m.agent_id = :a
ORDER BY score DESC
LIMIT 8;
That's the vector-flavored recall. For the graph-flavored side — "what other entities did this user mention recently, and what memories are attached to them?" — we walk the graph:
WITH seed_entities AS (
SELECT e.name, e.type
FROM chat_memory m
GRAPH MATCH (Memory {id: m.id})-[:MENTIONS]->(e:Entity)
WHERE m.user_id = :u
ORDER BY m.created_at DESC
LIMIT 10
)
SELECT m2.content, m2.memory_type, m2.created_at
FROM seed_entities se
GRAPH MATCH (e:Entity {name: se.name})<-[:MENTIONS]-(m2:Memory)
ORDER BY m2.created_at DESC
LIMIT 10;
In production you'd fuse these into one query. The split is for explanation.
The retrieval result is what goes into the LLM's context as the "memory you have about this user." A typical implementation feeds 5-12 memories per turn — enough to be useful, not so many that the context window thrashes.