Class SemanticMessageHistory
java.lang.Object
com.redis.vl.extensions.messagehistory.BaseMessageHistory
com.redis.vl.extensions.messagehistory.SemanticMessageHistory
Semantic Message History for storing and retrieving LLM conversation history with vector
embeddings for semantic search.
Stores user prompts and LLM responses with vector embeddings to allow for enriching future prompts with semantically relevant session context. Messages are tagged by session to support multiple concurrent conversations.
Matches the Python SemanticMessageHistory from redisvl.extensions.message_history.semantic_history
This class is final to prevent finalizer attacks (SEI CERT OBJ11-J).
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final doubleDefault distance threshold for semantic search.Fields inherited from class com.redis.vl.extensions.messagehistory.BaseMessageHistory
name, sessionTag -
Constructor Summary
ConstructorsConstructorDescriptionSemanticMessageHistory(String name, BaseVectorizer vectorizer, redis.clients.jedis.UnifiedJedis redisClient) Initialize semantic message history with required parameters.SemanticMessageHistory(String name, String sessionTag, String prefix, BaseVectorizer vectorizer, double distanceThreshold, redis.clients.jedis.UnifiedJedis redisClient, boolean overwrite) Initialize semantic message history with all parameters.SemanticMessageHistory(String name, String sessionTag, String prefix, BaseVectorizer vectorizer, redis.clients.jedis.UnifiedJedis redisClient) Initialize semantic message history with session tag and prefix. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddMessage(Map<String, String> message) Insert a single prompt or response into the message history using the default session tag.voidaddMessage(Map<String, String> message, String sessionTag) Insert a single prompt or response into the message history.voidaddMessages(List<Map<String, String>> messages) Insert a list of prompts and responses into the message history using the default session tag.voidInsert a list of prompts and responses into the message history.voidclear()Clears the chat message history.voiddelete()Clear all conversation history and remove any search indices.voidRemove a specific exchange from the conversation history.protected <T> List<T> formatContext(List<Map<String, Object>> messages, boolean asText) Format messages with metadata deserialization support.doubleGet the distance threshold for semantic search.getIndex()Get the underlying search index.Returns the full chat history.<T> List<T> Retrieve the recent conversation history in sequential order.<T> List<T> Retrieve the recent conversation history in sequential order.<T> List<T> getRelevant(String prompt, boolean asText, int topK, boolean fallBack, String sessionTag, Double distanceThreshold, Object role) Search the message history for information semantically related to the specified prompt.Get the vectorizer used for embeddings.voidsetDistanceThreshold(double distanceThreshold) Set the distance threshold for semantic search.voidInsert a prompt:response pair into the message history using the default session tag.voidInsert a prompt:response pair into the message history.Methods inherited from class com.redis.vl.extensions.messagehistory.BaseMessageHistory
getName, getSessionTag, validateRoles
-
Field Details
-
DEFAULT_DISTANCE_THRESHOLD
public static final double DEFAULT_DISTANCE_THRESHOLDDefault distance threshold for semantic search.- See Also:
-
-
Constructor Details
-
SemanticMessageHistory
public SemanticMessageHistory(String name, BaseVectorizer vectorizer, redis.clients.jedis.UnifiedJedis redisClient) Initialize semantic message history with required parameters.- Parameters:
name- The name of the message history indexvectorizer- The vectorizer used to create embeddingsredisClient- A Jedis client instance
-
SemanticMessageHistory
public SemanticMessageHistory(String name, String sessionTag, String prefix, BaseVectorizer vectorizer, redis.clients.jedis.UnifiedJedis redisClient) Initialize semantic message history with session tag and prefix.- Parameters:
name- The name of the message history indexsessionTag- Tag to be added to entries to link to a specific conversation session. Defaults to instance ULID.prefix- Prefix for the keys for this conversation data. Defaults to the index name.vectorizer- The vectorizer used to create embeddingsredisClient- A Jedis client instance
-
SemanticMessageHistory
public SemanticMessageHistory(String name, String sessionTag, String prefix, BaseVectorizer vectorizer, double distanceThreshold, redis.clients.jedis.UnifiedJedis redisClient, boolean overwrite) Initialize semantic message history with all parameters.- Parameters:
name- The name of the message history indexsessionTag- Tag to be added to entries to link to a specific conversation session. Defaults to instance ULID.prefix- Prefix for the keys for this conversation data. Defaults to the index name.vectorizer- The vectorizer used to create embeddingsdistanceThreshold- The maximum semantic distance for results. Defaults to 0.3.redisClient- A Jedis client instanceoverwrite- Whether to overwrite existing index schema. Defaults to false.
-
-
Method Details
-
getDistanceThreshold
public double getDistanceThreshold()Get the distance threshold for semantic search.- Returns:
- The current distance threshold
-
setDistanceThreshold
public void setDistanceThreshold(double distanceThreshold) Set the distance threshold for semantic search.- Parameters:
distanceThreshold- The new distance threshold
-
getVectorizer
Get the vectorizer used for embeddings.- Returns:
- The vectorizer
-
getIndex
Get the underlying search index.- Returns:
- The search index
-
clear
public void clear()Description copied from class:BaseMessageHistoryClears the chat message history.- Specified by:
clearin classBaseMessageHistory
-
delete
public void delete()Description copied from class:BaseMessageHistoryClear all conversation history and remove any search indices.- Specified by:
deletein classBaseMessageHistory
-
drop
Description copied from class:BaseMessageHistoryRemove a specific exchange from the conversation history.- Specified by:
dropin classBaseMessageHistory- Parameters:
id- The id of the entry to delete. If null then the last entry is deleted.
-
getMessages
Description copied from class:BaseMessageHistoryReturns the full chat history.- Specified by:
getMessagesin classBaseMessageHistory
-
getRecent
Retrieve the recent conversation history in sequential order.- Parameters:
topK- The number of previous messages to returnasText- Whether to return as text strings or mapsraw- Whether to return full Redis hash entriessessionTag- Session tag to filter by- Returns:
- List of messages
-
getRecent
Description copied from class:BaseMessageHistoryRetrieve the recent conversation history in sequential order.- Specified by:
getRecentin classBaseMessageHistory- Parameters:
topK- The number of previous messages to return. Default is 5.asText- Whether to return the conversation as a list of content strings, or list of message maps.raw- Whether to return the full Redis hash entry or just the role/content/tool_call_id.sessionTag- Tag of the entries linked to a specific conversation session. Defaults to instance ULID.role- Filter messages by role(s). Can be a single role string ("system", "user", "llm", "tool"), a List of role strings, or null for no filtering.- Returns:
- List of messages (either as text strings or maps depending on asText parameter)
-
getRelevant
public <T> List<T> getRelevant(String prompt, boolean asText, int topK, boolean fallBack, String sessionTag, Double distanceThreshold, Object role) Search the message history for information semantically related to the specified prompt.This method uses vector similarity search with a text prompt as input. It checks for semantically similar prompts and responses and gets the top k most relevant previous prompts or responses to include as context to the next LLM call.
- Parameters:
prompt- The message text to search for in message historyasText- Whether to return as text strings or mapstopK- The number of previous messages to return (default is 5)fallBack- Whether to fall back to recent conversation history if no relevant contextsessionTag- Tag of the entries linked to a specific conversation sessiondistanceThreshold- The threshold for semantic vector distance (null uses instance threshold)role- Filter messages by role(s) - single string or List of strings- Returns:
- List of semantically relevant messages
- Throws:
IllegalArgumentException- if topK is negative or role contains invalid values
-
store
Description copied from class:BaseMessageHistoryInsert a prompt:response pair into the message history.- Specified by:
storein classBaseMessageHistory- Parameters:
prompt- The user prompt to the LLMresponse- The corresponding LLM responsesessionTag- The tag to mark the messages with. Defaults to instance session tag.
-
store
Insert a prompt:response pair into the message history using the default session tag.- Parameters:
prompt- The user prompt to the LLMresponse- The corresponding LLM response
-
addMessages
Description copied from class:BaseMessageHistoryInsert a list of prompts and responses into the message history.- Specified by:
addMessagesin classBaseMessageHistory- Parameters:
messages- The list of user prompts and LLM responsessessionTag- The tag to mark the messages with. Defaults to instance session tag.
-
addMessage
Description copied from class:BaseMessageHistoryInsert a single prompt or response into the message history.- Specified by:
addMessagein classBaseMessageHistory- Parameters:
message- The user prompt or LLM responsesessionTag- The tag to mark the message with. Defaults to instance session tag.
-
addMessage
Insert a single prompt or response into the message history using the default session tag.- Parameters:
message- The user prompt or LLM response
-
addMessages
Insert a list of prompts and responses into the message history using the default session tag.- Parameters:
messages- The list of user prompts and LLM responses
-
formatContext
Format messages with metadata deserialization support.- Overrides:
formatContextin classBaseMessageHistory- Parameters:
messages- The raw messages from RedisasText- Whether to return as text- Returns:
- Formatted messages
-