RedisChatMessageHistory#

class langchain_redis.chat_message_history.RedisChatMessageHistory(session_id: str, redis_url: str = 'redis://localhost:6379', key_prefix: str = 'chat:', ttl: int | None = None, index_name: str = 'idx:chat_history', redis_client: Redis | None = None, **kwargs: Any)[source]#

Redis-based implementation of chat message history.

This class provides a way to store and retrieve chat message history using Redis. It implements the BaseChatMessageHistory interface and uses Redis JSON capabilities for efficient storage and retrieval of messages.

redis_client#

The Redis client instance.

Type:

Redis

session_id#

A unique identifier for the chat session.

Type:

str

key_prefix#

Prefix for Redis keys to namespace the messages.

Type:

str

ttl#

Time-to-live for message entries in seconds.

Type:

Optional[int]

index_name#

Name of the Redis search index for message retrieval.

Type:

str

Parameters:
  • session_id (str) – A unique identifier for the chat session.

  • redis_url (str, optional) – URL of the Redis instance. Defaults to “redis://localhost:6379”.

  • key_prefix (str, optional) – Prefix for Redis keys. Defaults to “chat:”.

  • ttl (Optional[int], optional) – Time-to-live for entries in seconds. Defaults to None (no expiration).

  • index_name (str, optional) – Name of the Redis search index. Defaults to “idx:chat_history”.

  • redis (Optional[Redis], optional) – Existing Redis client instance. If provided, redis_url is ignored.

  • **kwargs (Any) – Additional keyword arguments to pass to the Redis client.

  • redis_client (Redis | None)

  • **kwargs

Example

from langchain_redis import RedisChatMessageHistory
from langchain_core.messages import HumanMessage, AIMessage

history = RedisChatMessageHistory(
    session_id="user123",
    redis_url="redis://localhost:6379",
    ttl=3600  # Messages expire after 1 hour
)

# Add messages to the history
history.add_message(HumanMessage(content="Hello, AI!"))
history.add_message(
  AIMessage(content="Hello, human! How can I assist you today?")
)

# Retrieve all messages
messages = history.messages
for message in messages:
    print(f"{message.type}: {message.content}")

# Clear the history
history.clear()

Note

  • This class uses Redis JSON for storing messages, allowing for efficient querying and retrieval.

  • A Redis search index is created to enable fast lookups and potential future search needs over the chat history.

  • If TTL is set, message entries will automatically expire after the specified duration.

  • The session_id is used to group messages belonging to the same conversation or user session.

Attributes

id

messages

Methods

__init__(session_id[, redis_url, ...])

aadd_messages(messages)

Async add a list of messages.

aclear()

Async remove all messages from the store

add_ai_message(message)

Convenience method for adding an AI message string to the store.

add_message(message)

Add a message to the chat history.

add_messages(messages)

Add a list of messages.

add_user_message(message)

Convenience method for adding a human message string to the store.

aget_messages()

Async version of getting messages.

clear()

Clear all messages from the chat history for the current session.

search_messages(query[, limit])

Search for messages in the chat history that match the given query.

__init__(session_id: str, redis_url: str = 'redis://localhost:6379', key_prefix: str = 'chat:', ttl: int | None = None, index_name: str = 'idx:chat_history', redis_client: Redis | None = None, **kwargs: Any)[source]#
Parameters:
  • session_id (str)

  • redis_url (str)

  • key_prefix (str)

  • ttl (int | None)

  • index_name (str)

  • redis_client (Redis | None)

  • kwargs (Any)

async aadd_messages(messages: Sequence[BaseMessage]) None#

Async add a list of messages.

Parameters:

messages (Sequence[BaseMessage]) – A sequence of BaseMessage objects to store.

Return type:

None

async aclear() None#

Async remove all messages from the store

Return type:

None

add_ai_message(message: AIMessage | str) None#

Convenience method for adding an AI message string to the store.

Please note that this is a convenience method. Code should favor the bulk add_messages interface instead to save on round-trips to the underlying persistence layer.

This method may be deprecated in a future release.

Parameters:

message (AIMessage | str) – The AI message to add.

Return type:

None

add_message(message: BaseMessage) None[source]#

Add a message to the chat history.

This method adds a new message to the Redis store for the current session.

Parameters:

message (BaseMessage) – The message to add to the history. This should be an instance of a class derived from BaseMessage, such as HumanMessage, AIMessage, or SystemMessage.

Returns:

None

Return type:

None

Example

from langchain_redis import RedisChatMessageHistory
from langchain_core.messages import HumanMessage, AIMessage

history = RedisChatMessageHistory(
    session_id="user123",
    redis_url="redis://localhost:6379",
    ttl=3600  # optional: set TTL to 1 hour
)

# Add a human message
history.add_message(HumanMessage(content="Hello, AI!"))

# Add an AI message
history.add_message(
  AIMessage(content="Hello! How can I assist you today?")
)

# Verify messages were added
print(f"Number of messages: {len(history.messages)}")

Note

  • Each message is stored as a separate entry in Redis, associated with the current session_id.

  • Messages are stored using Redis JSON capabilities for efficient storage and retrieval.

  • If a TTL (Time To Live) was specified when initializing the history, it will be applied to each message.

  • The message’s content, type, and any additional data (like timestamp) are stored.

  • This method is thread-safe and can be used in concurrent environments.

  • The Redis search index is automatically updated to include the new message, enabling future searches.

  • Large message contents may impact performance and storage usage. Consider implementing size limits if dealing with potentially large messages.

add_messages(messages: Sequence[BaseMessage]) None#

Add a list of messages.

Implementations should over-ride this method to handle bulk addition of messages in an efficient manner to avoid unnecessary round-trips to the underlying store.

Parameters:

messages (Sequence[BaseMessage]) – A sequence of BaseMessage objects to store.

Return type:

None

add_user_message(message: HumanMessage | str) None#

Convenience method for adding a human message string to the store.

Please note that this is a convenience method. Code should favor the bulk add_messages interface instead to save on round-trips to the underlying persistence layer.

This method may be deprecated in a future release.

Parameters:

message (HumanMessage | str) – The human message to add to the store.

Return type:

None

async aget_messages() list[BaseMessage]#

Async version of getting messages.

Can over-ride this method to provide an efficient async implementation.

In general, fetching messages may involve IO to the underlying persistence layer.

Return type:

list[BaseMessage]

clear() None[source]#

Clear all messages from the chat history for the current session.

This method removes all messages associated with the current session_id from the Redis store.

Returns:

None

Return type:

None

Example

from langchain_redis import RedisChatMessageHistory
from langchain_core.messages import HumanMessage, AIMessage

history = RedisChatMessageHistory(session_id="user123", redis_url="redis://localhost:6379")

# Add some messages
history.add_message(HumanMessage(content="Hello, AI!"))
history.add_message(AIMessage(content="Hello, human!"))

# Clear the history
history.clear()

# Verify that the history is empty
assert len(history.messages) == 0

Note

  • This method only clears messages for the current session_id.

  • It uses a Redis search query to find all relevant messages and then deletes them.

  • The operation is atomic - either all messages are deleted, or none are.

  • After clearing, the Redis search index is still maintained, allowing for immediate use of the same session_id for new messages if needed.

  • This operation is irreversible. Make sure you want to remove all messages before calling this method.

search_messages(query: str, limit: int = 10) List[Dict[str, Any]][source]#

Search for messages in the chat history that match the given query.

This method performs a full-text search on the content of messages in the current session.

Parameters:
  • query (str) – The search query string to match against message content.

  • limit (int, optional) – The maximum number of results to return.

  • 10. (Defaults to)

Returns:

A list of dictionaries, each representing a

matching message.

Each dictionary contains the message content and metadata.

Return type:

List[Dict[str, Any]]

Example

from langchain_redis import RedisChatMessageHistory
from langchain_core.messages import HumanMessage, AIMessage

history = RedisChatMessageHistory(session_id="user123", redis_url="redis://localhost:6379")

# Add some messages
history.add_message(
  HumanMessage(content="Tell me about Machine Learning")
)
history.add_message(
  AIMessage(content="Machine Learning is a subset of AI...")
)
history.add_message(
  HumanMessage(content="What are neural networks?")
)
history.add_message(
  AIMessage(
    content="Neural networks are a key component of deep learning..."
  )
)

# Search for messages containing "learning"
results = history.search_messages("learning", limit=5)

for result in results:
    print(f"Content: {result['content']}")
    print(f"Type: {result['type']}")
    print("---")

Note

  • The search is performed using the Redis search capabilities, which allows for efficient full-text search.

  • The search is case-insensitive and uses Redis’ default tokenization and stemming.

  • Only messages from the current session (as defined by session_id) are searched.

  • The returned dictionaries include all stored fields, which typically include ‘content’, ‘type’, and any additional metadata stored with the message.

  • This method is useful for quickly finding relevant parts of a conversation without having to iterate through all messages.

Examples using RedisChatMessageHistory