Skip to content

Elsai Chat History

Package: elsai-chat-history  v1.1.0

Flexible conversation history management with multiple storage backends, memory management strategies, and semantic long-term memory.

Installation

bash
pip install --extra-index-url https://core-packages.elsai.ai/root/elsai-chat-history/ elsai-chat-history==1.1.0

Requirements: Python >= 3.11


Key features

FeatureDescription
Storage backendsIn-memory, JSON, SQLite, PostgreSQL
Memory strategiesTrimming, summarization, LRU, TTL, similarity search, semantic memory
Semantic memoryAuto-extract user facts and retrieve them across sessions (v1.1.0+)
Vector DB integrationPinecone, ChromaDB, Weaviate for similarity and semantic search
Async supportAll operations are async/await compatible
Multi-sessionTrack multiple users/sessions with per-session stats

ChatHistoryManager

The main class for all history operations. Takes a store (where messages are persisted) and an optional strategy (how messages are managed or pruned).

python
from elsai_chat_history.manager.chat_manager import ChatHistoryManager
from elsai_chat_history.stores.memory_store import MemoryStore

history = ChatHistoryManager(store=MemoryStore())

# Add messages
history.add_message(session_id="user-123", role="user", content="Hello!")
history.add_message(session_id="user-123", role="assistant", content="Hi there!")

# Retrieve conversation history
messages = history.get_history(session_id="user-123")

# Get formatted context string for an LLM
context = history.get_context(session_id="user-123", max_messages=10)

Constructor parameters:

ParameterDescription
storeStorage backend instance (see Storage backends below)
strategyOptional memory management strategy
semantic_strategyOptional semantic memory strategy (v1.1.0+)
auto_saveWhether to auto-save on each write. Defaults to True

Storage backends

In-memory (default)

Stores messages in-process. Data is lost when the process exits.

python
from elsai_chat_history.manager.chat_manager import ChatHistoryManager
from elsai_chat_history.stores.memory_store import MemoryStore

history = ChatHistoryManager(store=MemoryStore())

JSON file

Persists messages as a JSON file on disk.

python
from elsai_chat_history.manager.chat_manager import ChatHistoryManager
from elsai_chat_history.stores.json_store import JSONStore

history = ChatHistoryManager(store=JSONStore(storage_dir="./chat_history"))
ParameterDescription
storage_dirDirectory where JSON session files are stored

SQLite

Persists messages in a local SQLite database.

python
from elsai_chat_history.manager.chat_manager import ChatHistoryManager
from elsai_chat_history.stores.sqlite_store import SQLiteStore

history = ChatHistoryManager(store=SQLiteStore(db_path="./chat.db"))
ParameterDescription
db_pathPath to the SQLite database file

PostgreSQL

Persists messages in a PostgreSQL database.

python
from elsai_chat_history.manager.chat_manager import ChatHistoryManager
from elsai_chat_history.stores.postgres_store import PostgresStore

history = ChatHistoryManager(
    store=PostgresStore(
        connection_string="postgresql://user:password@localhost:5432/chat_db"
    )
)
ParameterDescription
connection_stringPostgreSQL connection string

Message operations

python
# Add a message — returns a Message object with a message_id
msg = history.add_message(
    session_id="user-123",
    role="user",
    content="What is the weather today?",
    metadata={"type": "query"},
)
print(msg.message_id)

# Get full history
messages = history.get_history(session_id="user-123")

# Get a single message
message = history.get_message(session_id="user-123", message_id=msg.message_id)

# Get formatted context string for an LLM prompt
context = history.get_context(
    session_id="user-123",
    max_messages=20,
    roles=["user", "assistant"],
)

# Update a message
history.update_message(
    session_id="user-123",
    message_id=msg.message_id,
    content="Updated content",
)

# Delete a message
history.delete_message(session_id="user-123", message_id=msg.message_id)

# Session management
sessions = history.list_sessions()
stats = history.get_session_stats(session_id="user-123")
history.clear_session(session_id="user-123")
history.save_session(session_id="user-123")

get_session_stats() returns a dictionary with total_messages and role_distribution.


Memory management strategies

Pass a strategy to ChatHistoryManager to control how messages are pruned or summarized.

TrimmingStrategy

Keeps only the most recent N messages. Optionally preserves system messages and a fixed number of recent messages.

python
from elsai_chat_history.manager.chat_manager import ChatHistoryManager
from elsai_chat_history.stores.memory_store import MemoryStore
from elsai_chat_history.strategies.trimming import TrimmingStrategy

history = ChatHistoryManager(
    store=MemoryStore(),
    strategy=TrimmingStrategy(
        max_messages=50,
        preserve_system=True,
        preserve_recent=5,
    ),
)

# Retrieve trimmed messages
messages = history.get_trimmed_messages(session_id="user-123")
ParameterDescription
max_messagesMaximum number of messages to retain
max_tokensOptional token limit (alternative to message count)
preserve_systemIf True, system messages are never trimmed
preserve_recentNumber of most recent messages always kept regardless of limit

SummarizationStrategy

Automatically summarizes older messages once the history exceeds a threshold, reducing token usage while preserving context.

python
from elsai_chat_history.strategies.summarization import SummarizationStrategy

history = ChatHistoryManager(
    store=MemoryStore(),
    strategy=SummarizationStrategy(
        summarizer_llm=your_llm,
        trigger_count=20,
        preserve_system=True,
    ),
)

# Retrieve the summarized history
summary = history.get_summary(session_id="user-123")
ParameterDescription
summarizer_llmLLM instance used to generate the summary
trigger_countNumber of messages that triggers summarization
preserve_systemIf True, system messages are excluded from summarization

LRUStrategy

Evicts least-recently-used messages when the history exceeds the limit.

python
from elsai_chat_history.strategies.lru import LRUStrategy

history = ChatHistoryManager(
    store=MemoryStore(),
    strategy=LRUStrategy(
        max_messages=100,
        preserve_system=True,
        preserve_recent=5,
    ),
)

messages = history.get_lru_messages(session_id="user-123")
ParameterDescription
max_messagesMaximum number of messages to retain
preserve_systemIf True, system messages are never evicted
preserve_recentNumber of most recent messages always kept

TTLStrategy

Automatically expires messages older than a given time window.

python
from elsai_chat_history.strategies.ttl import TTLStrategy

history = ChatHistoryManager(
    store=MemoryStore(),
    strategy=TTLStrategy(
        ttl_seconds=3600,
        preserve_system=True,
        preserve_recent=5,
        use_last_accessed=True,
    ),
)

messages = history.get_ttl_messages(session_id="user-123")
ParameterDescription
ttl_secondsTime-to-live in seconds — messages older than this are expired
preserve_systemIf True, system messages never expire
preserve_recentNumber of most recent messages always kept
use_last_accessedIf True, TTL resets on each access; if False, it counts from creation

SimilaritySearchStrategy

Retrieves only the messages most semantically similar to the current query, using a vector database.

python
from elsai_chat_history.strategies.similarity_search import SimilaritySearchStrategy
from elsai_vectordb.chromadb import ChromaVectorDb
from elsai_embeddings.azure_embeddings import AzureOpenAIEmbeddingModel

config = {
    "vector_database": {
        "name": "chroma",
        "client": ChromaVectorDb(persist_directory="./db"),
    },
    "embedding_model": {
        "name": "azure-openai",
        "client": AzureOpenAIEmbeddingModel(...),
    },
    "top_k": 5,
}

history = ChatHistoryManager(
    store=MemoryStore(),
    strategy=SimilaritySearchStrategy(config=config),
)

similar = history.get_similar_messages(
    user_query="What was my earlier question about embeddings?",
    session_id="user-123",
)

Semantic memory (v1.1.0+)

Automatically extracts facts from conversations and stores them in a vector database for retrieval across sessions.

python
from elsai_chat_history.manager.chat_manager import ChatHistoryManager
from elsai_chat_history.stores.memory_store import MemoryStore
from elsai_chat_history.strategies.semantic_memory_implementation import SemanticMemoryStrategyImpl
from elsai_vectordb.pinecone import PineconeVectorDb
from elsai_embeddings.azure_embeddings import AzureOpenAIEmbeddingModel

semantic_strategy = SemanticMemoryStrategyImpl(
    llm=your_llm,
    vector_db=PineconeVectorDb(...),
    embedding_model=AzureOpenAIEmbeddingModel(...),
    trigger_count=10,
    collection_name="user_facts",
)

history = ChatHistoryManager(
    store=MemoryStore(),
    semantic_strategy=semantic_strategy,
)

# Add conversation — facts are auto-extracted after trigger_count messages
history.add_message(session_id="user-123", role="user", content="I prefer Python over Java.")
history.add_message(session_id="user-123", role="assistant", content="Noted!")

# Retrieve semantic context for a user across all sessions
facts = history.get_semantic_context(user_id="user-123")
print(facts)

SemanticMemoryStrategyImpl parameters:

ParameterDescription
llmLLM instance used to extract facts from conversations
vector_dbVector database instance for storing and retrieving facts
embedding_modelEmbedding model used to vectorize extracted facts
trigger_countNumber of new messages that triggers fact extraction
collection_nameVector DB collection name for storing facts

Metadata filtering

All get_* methods support optional metadata_filter to narrow results:

python
# Single value filter
messages = history.get_trimmed_messages(
    session_id="user-123",
    metadata_filter={"type": "system"},
)

# List-based (IN-style) filter
messages = history.get_trimmed_messages(
    session_id="user-123",
    metadata_filter={"type": ["query", "followup"]},
)

Version history

VersionChanges
1.1.0SemanticMemoryStrategyImpl, SimilaritySearchStrategy, get_semantic_context()
1.0.0Initial release — ChatHistoryManager, storage backends, trimming/summarization/LRU/TTL strategies

Copyright © 2026 Elsai Foundry.