Skip to main content
SQLiteShortTermMemory implements the Memory Management Pattern using a local SQLite database. It stores messages keyed by session_id, supports chronological retrieval, session clearing, and an exact-match caching layer that can short-circuit redundant LLM calls.

Import

from memory.short_term_memory import SQLiteShortTermMemory

Constructor

db_path
str
default:"short_term_memory.db"
File system path for the SQLite database. Pass ":memory:" for an ephemeral, RAM-only store that is discarded when the process exits.

Database Schema

The constructor automatically creates the following table if it does not exist:
CREATE TABLE IF NOT EXISTS memory (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    session_id  TEXT     NOT NULL,
    role        TEXT     NOT NULL,
    content     TEXT     NOT NULL,
    metadata    TEXT,                              -- JSON-encoded dict or NULL
    timestamp   DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_session_id ON memory(session_id);

Methods

add_memory

Inserts a single message into the memory table.
def add_memory(
    self,
    session_id: str,
    role: str,
    content: str,
    metadata: Optional[Dict[str, Any]] = None
) -> None
session_id
str
required
Unique identifier for the conversation or workflow run.
role
str
required
Speaker role. Conventional values: "user", "assistant", "system", "tool".
content
str
required
The text content of the message.
metadata
Optional[Dict[str, Any]]
default:"None"
Arbitrary key/value data (e.g., tool names, token counts). Serialized to JSON before storage.

get_context

Retrieves the most recent messages for a session in chronological order.
def get_context(self, session_id: str, limit: int = 10) -> List[Dict[str, Any]]
session_id
str
required
The session whose history to fetch.
limit
int
default:"10"
Maximum number of messages to return. The limit most recent messages are returned, ordered oldest-first.
returns
List[Dict[str, Any]]
Ordered list of message dictionaries.

clear_session

Deletes all messages for the specified session.
def clear_session(self, session_id: str) -> None
session_id
str
required
The session to clear.

format_as_string

Formats session history as a plain-text block ready for LLM context injection.
def format_as_string(self, session_id: str, limit: int = 10) -> str
session_id
str
required
The session to format.
limit
int
default:"10"
Passed directly to get_context.
returns
str
Messages formatted as "ROLE: content" lines joined by double newlines ("\n\n"). Returns "No previous context." if the session has no messages.

get_exact_match_answer

Searches across all sessions for an exact user message match and returns the immediately following assistant reply. Acts as a simple caching layer.
def get_exact_match_answer(self, query: str) -> Optional[str]
query
str
required
The exact user message text to look up.
returns
Optional[str]
The content of the first assistant message that immediately follows the matched user message, or None if no match exists.
The lookup is a cross-session exact string match. Use this method to implement a check-before-call pattern: if a cached answer is found, skip the LLM call and return the cached result directly.

Usage Example

from memory.short_term_memory import SQLiteShortTermMemory

memory = SQLiteShortTermMemory(db_path="agent_memory.db")
session = "user-session-42"

# --- Caching pattern: check before calling LLM ---
user_query = "What is the capital of France?"

cached = memory.get_exact_match_answer(user_query)
if cached:
    answer = cached
else:
    # Call the LLM
    answer = llm.invoke(user_query)

    # Persist both turns
    memory.add_memory(session, role="user",      content=user_query)
    memory.add_memory(session, role="assistant", content=answer)

print(answer)

# --- Inject recent context into a prompt ---
context_block = memory.format_as_string(session, limit=5)
prompt = f"Previous conversation:\n{context_block}\n\nNew question: Tell me more."

# --- Inspect raw history ---
history = memory.get_context(session, limit=10)
for msg in history:
    print(f"[{msg['timestamp']}] {msg['role'].upper()}: {msg['content']}")

# --- Clean up ---
memory.clear_session(session)

Build docs developers (and LLMs) love