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
Constructor
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:Methods
add_memory
Inserts a single message into the memory table.
Unique identifier for the conversation or workflow run.
Speaker role. Conventional values:
"user", "assistant", "system", "tool".The text content of the message.
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.
The session whose history to fetch.
Maximum number of messages to return. The
limit most recent messages are returned, ordered oldest-first.Ordered list of message dictionaries.
clear_session
Deletes all messages for the specified session.
The session to clear.
format_as_string
Formats session history as a plain-text block ready for LLM context injection.
The session to format.
Passed directly to
get_context.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.
The exact user message text to look up.
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.