Give Any AI Agent Long-Term Memory (in SQL)

Add persistent, semantic long-term memory to any AI agent — store and recall memories by meaning with vector embeddings in plain SQL. Framework-agnostic: works with Claude Code, OpenClaw, LangChain, or a custom or voice agent.

All recipes· agents· 12 minutesintermediateen
Instance: localhost:8080

Opens your running SynapCores (Give Any AI Agent Long-Term Memory (in SQL) will be staged for a preview — nothing runs until you click Run). No instance yet? Install free in ~30s.

Share

Objective

Every useful agent needs memory that survives the session — so it recalls what a user said last week, not just this turn. Most teams bolt on a separate vector store + a cache + glue code. Here you'll give any agent durable, semantic long-term memory with one table and a few SQL calls: write a memory, recall the most relevant ones by meaning, weight them by importance, and ground a reply in what you recalled. The same store works from any framework — or a voice agent — see Use it from your agent at the end.

Step 1: Create the agent memory store

One row per memory, with an embedding for semantic recall, an importance weight, and a timestamp.

CREATE TABLE IF NOT EXISTS recipe_agent_memory (
  memory_id   INTEGER PRIMARY KEY,
  agent_id    TEXT,                                  -- which agent/user this memory belongs to
  content     TEXT,                                  -- the memory, in natural language
  importance  DOUBLE,                                -- 0..1: how much this memory matters
  created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  embedding   VECTOR(384)
);

Step 2: Write some memories

What an agent would persist across sessions.

INSERT INTO recipe_agent_memory (memory_id, agent_id, content, importance) VALUES
 (1,'assistant','The user prefers dark mode and concise answers.',0.80),
 (2,'assistant','The user is allergic to peanuts.',0.95),
 (3,'assistant','The user is planning a trip to Japan in the spring.',0.70),
 (4,'assistant','The user works as a data engineer on a Rust codebase.',0.85),
 (5,'assistant','The user mentioned they dislike phone calls.',0.60);

Step 3: Embed the memories

One line — the embedding model runs inside the database, no external API.

UPDATE recipe_agent_memory SET embedding = EMBED(content);

Step 4: Recall memories by meaning

Given the user's new message, recall the most semantically relevant memories — even with no shared keywords.

SELECT memory_id, content,
       COSINE_SIMILARITY(embedding, EMBED('Does the user have any dietary restrictions?')) AS relevance
FROM recipe_agent_memory
WHERE agent_id = 'assistant'
ORDER BY relevance DESC
LIMIT 3;

Step 5: Weighted recall (relevance + importance)

Human-like memory blends relevance with importance, so a critical fact (an allergy) wins even when the query is loosely worded.

SELECT memory_id, content,
       COSINE_SIMILARITY(embedding, EMBED('planning what to cook for the user')) * 0.7
       + importance * 0.3 AS score
FROM recipe_agent_memory
WHERE agent_id = 'assistant'
ORDER BY score DESC
LIMIT 3;

Step 6: Ground a reply in what you recalled

Retrieve the single most relevant memory, then feed it to GENERATE() — retrieval-augmented generation. First materialize the top memory into a small context table (projecting the similarity score so we can order by it), then generate the reply from that recalled fact.

CREATE TABLE IF NOT EXISTS recipe_agent_recall (
  memory_id INTEGER PRIMARY KEY,
  content   TEXT,
  relevance DOUBLE
);
INSERT INTO recipe_agent_recall (memory_id, content, relevance)
SELECT memory_id, content,
       COSINE_SIMILARITY(embedding, EMBED('suggest a dinner')) AS relevance
FROM recipe_agent_memory
WHERE agent_id = 'assistant'
ORDER BY relevance DESC
LIMIT 1;
SELECT GENERATE(
  'Given this fact about the user: ' || content ||
  '. Suggest one dinner idea in a single sentence.') AS suggestion
FROM recipe_agent_recall;

Cleanup (Optional)

DROP TABLE IF EXISTS recipe_agent_memory;
DROP TABLE IF EXISTS recipe_agent_recall;

Expected Outcomes

  • Step 4 surfaces "allergic to peanuts" as the top memory for a dietary-restrictions query — by meaning, with no keyword overlap.
  • Step 5 keeps the allergy near the top for a loosely-worded "what to cook" query, because importance is blended in.
  • Step 6 returns a dinner suggestion grounded in the recalled allergy — retrieval-augmented generation in a single query.

You now have durable, semantic, importance-weighted long-term memory that any agent can read and write.

Use it from your agent (framework-agnostic — this is the whole point)

The memory store is just data + three operations (write, recall, generate), so any agent uses it — there is no framework lock-in:

  • REST / SDKPOST /v1/query/execute (any language), or @synapcores/sdk client.executeQuery(...). Your agent runs the Step-2 INSERT to remember and the Step-4/5 SELECT to recall.
  • MCP (native, on by default) — point any MCP client (Claude Code, Cursor, a custom loop, a voice runtime) at ws://<your-instance>/mcp?token=<jwt>. The agent gets query + vector tools, so "remember this" and "what do I know about X?" become MCP tool calls — no SDK required.
  • Any framework — OpenClaw's memory plugin stores into exactly this kind of vector table under the hood; LangChain / LlamaIndex / Semantic Kernel / custom loops / voice agents all read and write the same store. The database is the brain; the framework is swappable.

Key Concepts Learned

  • A VECTOR(n) column + EMBED() turns any table into semantic memory — no external vector DB.
  • COSINE_SIMILARITY recalls by meaning; blend it with an importance weight for human-like recall.
  • A subquery + GENERATE() produces a retrieval-grounded response in one statement.
  • Because it's plain data ops (SQL / REST / MCP), the memory works for any agent — the agent-agnostic backend pattern every recipe in this cluster builds on.

Tags

ai-agentlong-term-memoryvectorembeddingssemantic-memoryagent-memorymcp

Run this on your own machine

Install SynapCores Community Edition free, paste the SQL or Cypher above into the bundled web UI, and watch it run.

Download Free CE