title: LLM Cache

title: SemanticCache

title: `class SemanticCache(name='llmcache', distance_threshold=0.1, ttl=None, vectorizer=None, filterable_fields=None, redis_client=None, redis_url='redis://localhost:6379', connection_kwargs={}, overwrite=False, **kwargs)`

text:
Bases: `BaseLLMCache`

Semantic Cache for Large Language Models.

Semantic Cache for Large Language Models.

* **Parameters:**
  * **name** (*str* *,* *optional*) – The name of the semantic cache search index.
    Defaults to "llmcache".
  * **distance_threshold** (*float* *,* *optional*) – Semantic threshold for the
    cache. Defaults to 0.1.
  * **ttl** (*Optional* *[* *int* *]* *,* *optional*) – The time-to-live for records cached
    in Redis. Defaults to None.
  * **vectorizer** (*Optional* *[* *BaseVectorizer* *]* *,* *optional*) – The vectorizer for the cache.
    Defaults to HFTextVectorizer.
  * **filterable_fields** (*Optional* *[* *List* *[* *Dict* *[* *str* *,* *Any* *]* *]* *]*) – An optional list of RedisVL fields
    that can be used to customize cache retrieval with filters.
  * **redis_client** (*Optional* *[* *Redis* *]* *,* *optional*) – A redis client connection instance.
    Defaults to None.
  * **redis_url** (*str* *,* *optional*) – The redis url. Defaults to redis://localhost:6379.
  * **connection_kwargs** (*Dict* *[* *str* *,* *Any* *]*) – The connection arguments
    for the redis client. Defaults to empty {}.
  * **overwrite** (*bool*) – Whether or not to force overwrite the schema for
    the semantic cache index. Defaults to false.
* **Raises:**
  * **TypeError** – If an invalid vectorizer is provided.
  * **TypeError** – If the TTL value is not an int.
  * **ValueError** – If the threshold is not between 0 and 1.
  * **ValueError** – If existing schema does not match new schema and overwrite is False.

#### `async acheck(prompt=None, vector=None, num_results=1, return_fields=None, filter_expression=None, distance_threshold=None)`

Async check the semantic cache for results similar to the specified prompt
or vector.

This method searches the cache using vector similarity with
either a raw text prompt (converted to a vector) or a provided vector as
input. It checks for semantically similar prompts and fetches the cached
LLM responses.

* **Parameters:**
  * **prompt** (*Optional* *[* *str* *]* *,* *optional*) – The text prompt to search for in
    the cache.
  * **vector** (*Optional* *[* *List* *[* *float* *]* *]* *,* *optional*) – The vector representation
    of the prompt to search for in the cache.
  * **num_results** (*int* *,* *optional*) – The number of cached results to return.
    Defaults to 1.
  * **return_fields** (*Optional* *[* *List* *[* *str* *]* *]* *,* *optional*) – The fields to include
    in each returned result. If None, defaults to all available
    fields in the cached entry.
  * **filter_expression** (*Optional* *[*[*FilterExpression*]() *]*) – Optional filter expression
    that can be used to filter cache results. Defaults to None and
    the full cache will be searched.
  * **distance_threshold** (*Optional* *[* *float* *]*) – The threshold for semantic
    vector distance.
* **Returns:**
  A list of dicts containing the requested
  : return fields for each similar cached response.
* **Return type:**
  List[Dict[str, Any]]
* **Raises:**
  * **ValueError** – If neither a prompt nor a vector is specified.
  * **ValueError** – if ‘vector’ has incorrect dimensions.
  * **TypeError** – If return_fields is not a list when provided.

[code example]

#### `async aclear()`

Async clear the cache of all keys.

* **Return type:**
  None

#### `async adelete()`

Async delete the cache and its index entirely.

* **Return type:**
  None

#### `async adisconnect()`

Asynchronously disconnect from Redis and search index.

Closes all Redis connections and index connections.

#### `async adrop(ids=None, keys=None)`

Async drop specific entries from the cache by ID or Redis key.

* **Parameters:**
  * **ids** (*Optional* *[* *List* *[* *str* *]* *]*) – List of entry IDs to remove from the cache.
    Entry IDs are the unique identifiers without the cache prefix.
  * **keys** (*Optional* *[* *List* *[* *str* *]* *]*) – List of full Redis keys to remove from the cache.
    Keys are the complete Redis keys including the cache prefix.
* **Return type:**
  None

#### `NOTE`
At least one of ids or keys must be provided.

* **Raises:**
  **ValueError** – If neither ids nor keys is provided.
* **Parameters:**
  * **ids** (*List* *[* *str* *]*  *|* *None*)
  * **keys** (*List* *[* *str* *]*  *|* *None*)
* **Return type:**
  None

#### `async aexpire(key, ttl=None)`

Asynchronously set or refresh the expiration time for a key in the cache.

* **Parameters:**
  * **key** (*str*) – The Redis key to set the expiration on.
  * **ttl** (*Optional* *[* *int* *]* *,* *optional*) – The time-to-live in seconds. If None,
    uses the default TTL configured for this cache instance.
    Defaults to None.
* **Return type:**
  None

#### `NOTE`
If neither the provided TTL nor the default TTL is set (both are None),
this method will have no effect.

#### `async astore(prompt, response, vector=None, metadata=None, filters=None, ttl=None)`

Async stores the specified key-value pair in the cache along with metadata.

* **Parameters:**
  * **prompt** (*str*) – The user prompt to cache.
  * **response** (*str*) – The LLM response to cache.
  * **vector** (*Optional* *[* *List* *[* *float* *]* *]* *,* *optional*) – The prompt vector to
    cache. Defaults to None, and the prompt vector is generated on
    demand.
  * **metadata** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *optional*) – The optional metadata to cache
    alongside the prompt and response. Defaults to None.
  * **filters** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]*) – The optional tag to assign to the cache entry.
    Defaults to None.
  * **ttl** (*Optional* *[* *int* *]*) – The optional TTL override to use on this individual cache
    entry. Defaults to the global TTL setting.
* **Returns:**
  The Redis key for the entries added to the semantic cache.
* **Return type:**
  str
* **Raises:**
  * **ValueError** – If neither prompt nor vector is specified.
  * **ValueError** – if vector has incorrect dimensions.
  * **TypeError** – If provided metadata is not a dictionary.

[code example]

#### `async aupdate(key, **kwargs)`

Async update specific fields within an existing cache entry. If no fields
are passed, then only the document TTL is refreshed.

* **Parameters:**
  **key** (*str*) – the key of the document to update using kwargs.
* **Raises:**
  * **ValueError if an incorrect mapping is provided as a kwarg.** –
  * **TypeError if metadata is provided and not** **of** **type dict.** –
* **Return type:**
  None

[code example]

#### `check(prompt=None, vector=None, num_results=1, return_fields=None, filter_expression=None, distance_threshold=None)`

Checks the semantic cache for results similar to the specified prompt
or vector.

This method searches the cache using vector similarity with
either a raw text prompt (converted to a vector) or a provided vector as
input. It checks for semantically similar prompts and fetches the cached
LLM responses.

* **Parameters:**
  * **prompt** (*Optional* *[* *str* *]* *,* *optional*) – The text prompt to search for in
    the cache.
  * **vector** (*Optional* *[* *List* *[* *float* *]* *]* *,* *optional*) – The vector representation
    of the prompt to search for in the cache.
  * **num_results** (*int* *,* *optional*) – The number of cached results to return.
    Defaults to 1.
  * **return_fields** (*Optional* *[* *List* *[* *str* *]* *]* *,* *optional*) – The fields to include
    in each returned result. If None, defaults to all available
    fields in the cached entry.
  * **filter_expression** (*Optional* *[*[*FilterExpression*]() *]*) – Optional filter expression
    that can be used to filter cache results. Defaults to None and
    the full cache will be searched.
  * **distance_threshold** (*Optional* *[* *float* *]*) – The threshold for semantic
    vector distance.
* **Returns:**
  A list of dicts containing the requested
  : return fields for each similar cached response.
* **Return type:**
  List[Dict[str, Any]]
* **Raises:**
  * **ValueError** – If neither a prompt nor a vector is specified.
  * **ValueError** – if ‘vector’ has incorrect dimensions.
  * **TypeError** – If return_fields is not a list when provided.

[code example]

#### `clear()`

Clear the cache of all keys.

* **Return type:**
  None

#### `delete()`

Delete the cache and its index entirely.

* **Return type:**
  None

#### `disconnect()`

Disconnect from Redis and search index.

Closes all Redis connections and index connections.

#### `drop(ids=None, keys=None)`

Drop specific entries from the cache by ID or Redis key.

* **Parameters:**
  * **ids** (*Optional* *[* *List* *[* *str* *]* *]*) – List of entry IDs to remove from the cache.
    Entry IDs are the unique identifiers without the cache prefix.
  * **keys** (*Optional* *[* *List* *[* *str* *]* *]*) – List of full Redis keys to remove from the cache.
    Keys are the complete Redis keys including the cache prefix.
* **Return type:**
  None

#### `NOTE`
At least one of ids or keys must be provided.

* **Raises:**
  **ValueError** – If neither ids nor keys is provided.
* **Parameters:**
  * **ids** (*List* *[* *str* *]*  *|* *None*)
  * **keys** (*List* *[* *str* *]*  *|* *None*)
* **Return type:**
  None

#### `expire(key, ttl=None)`

Set or refresh the expiration time for a key in the cache.

* **Parameters:**
  * **key** (*str*) – The Redis key to set the expiration on.
  * **ttl** (*Optional* *[* *int* *]* *,* *optional*) – The time-to-live in seconds. If None,
    uses the default TTL configured for this cache instance.
    Defaults to None.
* **Return type:**
  None

#### `NOTE`
If neither the provided TTL nor the default TTL is set (both are None),
this method will have no effect.

#### `set_threshold(distance_threshold)`

Sets the semantic distance threshold for the cache.

* **Parameters:**
  **distance_threshold** (*float*) – The semantic distance threshold for
  the cache.
* **Raises:**
  **ValueError** – If the threshold is not between 0 and 1.
* **Return type:**
  None

#### `set_ttl(ttl=None)`

Set the default TTL, in seconds, for entries in the cache.

* **Parameters:**
  **ttl** (*Optional* *[* *int* *]* *,* *optional*) – The optional time-to-live expiration
  for the cache, in seconds.
* **Raises:**
  **ValueError** – If the time-to-live value is not an integer.
* **Return type:**
  None

#### `store(prompt, response, vector=None, metadata=None, filters=None, ttl=None)`

Stores the specified key-value pair in the cache along with metadata.

* **Parameters:**
  * **prompt** (*str*) – The user prompt to cache.
  * **response** (*str*) – The LLM response to cache.
  * **vector** (*Optional* *[* *List* *[* *float* *]* *]* *,* *optional*) – The prompt vector to
    cache. Defaults to None, and the prompt vector is generated on
    demand.
  * **metadata** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]* *,* *optional*) – The optional metadata to cache
    alongside the prompt and response. Defaults to None.
  * **filters** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]*) – The optional tag to assign to the cache entry.
    Defaults to None.
  * **ttl** (*Optional* *[* *int* *]*) – The optional TTL override to use on this individual cache
    entry. Defaults to the global TTL setting.
* **Returns:**
  The Redis key for the entries added to the semantic cache.
* **Return type:**
  str
* **Raises:**
  * **ValueError** – If neither prompt nor vector is specified.
  * **ValueError** – if vector has incorrect dimensions.
  * **TypeError** – If provided metadata is not a dictionary.

[code example]

#### `update(key, **kwargs)`

Update specific fields within an existing cache entry. If no fields
are passed, then only the document TTL is refreshed.

* **Parameters:**
  **key** (*str*) – the key of the document to update using kwargs.
* **Raises:**
  * **ValueError if an incorrect mapping is provided as a kwarg.** –
  * **TypeError if metadata is provided and not** **of** **type dict.** –
* **Return type:**
  None

[code example]

#### `property aindex: `[`AsyncSearchIndex`]()`  | None`

The underlying AsyncSearchIndex for the cache.

* **Returns:**
  The async search index.
* **Return type:**
  [AsyncSearchIndex]()

#### `property distance_threshold: float`

The semantic distance threshold for the cache.

* **Returns:**
  The semantic distance threshold.
* **Return type:**
  float

#### `property index: `[`SearchIndex`]()` `

The underlying SearchIndex for the cache.

* **Returns:**
  The search index.
* **Return type:**
  [SearchIndex]()

#### `property ttl: int | None`

The default TTL, in seconds, for entries in the cache.

# Embeddings Cache

title: EmbeddingsCache

title: `class EmbeddingsCache(name='embedcache', ttl=None, redis_client=None, async_redis_client=None, redis_url='redis://localhost:6379', connection_kwargs={})`

text:
Bases: `BaseCache`

Embeddings Cache for storing embedding vectors with exact key matching.

Initialize an embeddings cache.

* **Parameters:**
  * **name** (*str*) – The name of the cache. Defaults to "embedcache".
  * **ttl** (*Optional* *[* *int* *]*) – The time-to-live for cached embeddings. Defaults to None.
  * **redis_client** (*Optional* *[* *SyncRedisClient* *]*) – Redis client instance. Defaults to None.
  * **redis_url** (*str*) – Redis URL for connection. Defaults to "redis://localhost:6379".
  * **connection_kwargs** (*Dict* *[* *str* *,* *Any* *]*) – Redis connection arguments. Defaults to {}.
  * **async_redis_client** (*Redis* *|* *RedisCluster* *|* *None*)
* **Raises:**
  **ValueError** – If vector dimensions are invalid

[code example]

#### `async aclear()`

Async clear the cache of all keys.

* **Return type:**
  None

#### `async adisconnect()`

Async disconnect from Redis.

* **Return type:**
  None

#### `async adrop(text, model_name)`

Async remove an embedding from the cache.

Asynchronously removes an embedding from the cache.

* **Parameters:**
  * **text** (*str*) – The text input that was embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Return type:**
  None

[code example]

#### `async adrop_by_key(key)`

Async remove an embedding from the cache by its Redis key.

Asynchronously removes an embedding from the cache by its Redis key.

* **Parameters:**
  **key** (*str*) – The full Redis key for the embedding.
* **Return type:**
  None

[code example]

#### `async aexists(text, model_name)`

Async check if an embedding exists.

Asynchronously checks if an embedding exists for the given text and model.

* **Parameters:**
  * **text** (*str*) – The text input that was embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Returns:**
  True if the embedding exists in the cache, False otherwise.
* **Return type:**
  bool

[code example]

#### `async aexists_by_key(key)`

Async check if an embedding exists for the given Redis key.

Asynchronously checks if an embedding exists for the given Redis key.

* **Parameters:**
  **key** (*str*) – The full Redis key for the embedding.
* **Returns:**
  True if the embedding exists in the cache, False otherwise.
* **Return type:**
  bool

[code example]

#### `async aexpire(key, ttl=None)`

Asynchronously set or refresh the expiration time for a key in the cache.

* **Parameters:**
  * **key** (*str*) – The Redis key to set the expiration on.
  * **ttl** (*Optional* *[* *int* *]* *,* *optional*) – The time-to-live in seconds. If None,
    uses the default TTL configured for this cache instance.
    Defaults to None.
* **Return type:**
  None

#### `NOTE`
If neither the provided TTL nor the default TTL is set (both are None),
this method will have no effect.

#### `async aget(text, model_name)`

Async get embedding by text and model name.

Asynchronously retrieves a cached embedding for the given text and model name.
If found, refreshes the TTL of the entry.

* **Parameters:**
  * **text** (*str*) – The text input that was embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Returns:**
  Embedding cache entry or None if not found.
* **Return type:**
  Optional[Dict[str, Any]]

[code example]

#### `async aget_by_key(key)`

Async get embedding by its full Redis key.

Asynchronously retrieves a cached embedding for the given Redis key.
If found, refreshes the TTL of the entry.

* **Parameters:**
  **key** (*str*) – The full Redis key for the embedding.
* **Returns:**
  Embedding cache entry or None if not found.
* **Return type:**
  Optional[Dict[str, Any]]

[code example]

#### `async amdrop(texts, model_name)`

Async remove multiple embeddings from the cache by their texts and model name.

Asynchronously removes multiple embeddings in a single operation.

* **Parameters:**
  * **texts** (*List* *[* *str* *]*) – List of text inputs that were embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Return type:**
  None

[code example]

#### `async amdrop_by_keys(keys)`

Async remove multiple embeddings from the cache by their Redis keys.

Asynchronously removes multiple embeddings in a single operation.

* **Parameters:**
  **keys** (*List* *[* *str* *]*) – List of Redis keys to remove.
* **Return type:**
  None

[code example]

#### `async amexists(texts, model_name)`

Async check if multiple embeddings exist by their texts and model name.

Asynchronously checks existence of multiple embeddings in a single operation.

* **Parameters:**
  * **texts** (*List* *[* *str* *]*) – List of text inputs that were embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Returns:**
  List of boolean values indicating whether each embedding exists.
* **Return type:**
  List[bool]

[code example]

#### `async amexists_by_keys(keys)`

Async check if multiple embeddings exist by their Redis keys.

Asynchronously checks existence of multiple keys in a single operation.

* **Parameters:**
  **keys** (*List* *[* *str* *]*) – List of Redis keys to check.
* **Returns:**
  List of boolean values indicating whether each key exists.
  The order matches the input keys order.
* **Return type:**
  List[bool]

[code example]

#### `async amget(texts, model_name)`

Async get multiple embeddings by their texts and model name.

Asynchronously retrieves multiple cached embeddings in a single operation.
If found, refreshes the TTL of each entry.

* **Parameters:**
  * **texts** (*List* *[* *str* *]*) – List of text inputs that were embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Returns:**
  List of embedding cache entries or None for texts not found.
* **Return type:**
  List[Optional[Dict[str, Any]]]

[code example]

#### `async amget_by_keys(keys)`

Async get multiple embeddings by their Redis keys.

Asynchronously retrieves multiple cached embeddings in a single network roundtrip.
If found, refreshes the TTL of each entry.

* **Parameters:**
  **keys** (*List* *[* *str* *]*) – List of Redis keys to retrieve.
* **Returns:**
  List of embedding cache entries or None for keys not found.
  The order matches the input keys order.
* **Return type:**
  List[Optional[Dict[str, Any]]]

[code example]

#### `async amset(items, ttl=None)`

Async store multiple embeddings in a batch operation.

Each item in the input list should be a dictionary with the following fields:
- ‘text’: The text input that was embedded
- ‘model_name’: The name of the embedding model
- ‘embedding’: The embedding vector
- ‘metadata’: Optional metadata to store with the embedding

* **Parameters:**
  * **items** (*List* *[* *Dict* *[* *str* *,* *Any* *]* *]*) – List of dictionaries, each containing text, model_name, embedding, and optional metadata.
  * **ttl** (*int* *|* *None*) – Optional TTL override for these entries.
* **Returns:**
  List of Redis keys where the embeddings were stored.
* **Return type:**
  List[str]

[code example]

#### `async aset(text, model_name, embedding, metadata=None, ttl=None)`

Async store an embedding with its text and model name.

Asynchronously stores an embedding with its text and model name.

* **Parameters:**
  * **text** (*str*) – The text input that was embedded.
  * **model_name** (*str*) – The name of the embedding model.
  * **embedding** (*List* *[* *float* *]*) – The embedding vector to store.
  * **metadata** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]*) – Optional metadata to store with the embedding.
  * **ttl** (*Optional* *[* *int* *]*) – Optional TTL override for this specific entry.
* **Returns:**
  The Redis key where the embedding was stored.
* **Return type:**
  str

[code example]

#### `clear()`

Clear the cache of all keys.

* **Return type:**
  None

#### `disconnect()`

Disconnect from Redis.

* **Return type:**
  None

#### `drop(text, model_name)`

Remove an embedding from the cache.

* **Parameters:**
  * **text** (*str*) – The text input that was embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Return type:**
  None

[code example]

#### `drop_by_key(key)`

Remove an embedding from the cache by its Redis key.

* **Parameters:**
  **key** (*str*) – The full Redis key for the embedding.
* **Return type:**
  None

[code example]

#### `exists(text, model_name)`

Check if an embedding exists for the given text and model.

* **Parameters:**
  * **text** (*str*) – The text input that was embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Returns:**
  True if the embedding exists in the cache, False otherwise.
* **Return type:**
  bool

[code example]

#### `exists_by_key(key)`

Check if an embedding exists for the given Redis key.

* **Parameters:**
  **key** (*str*) – The full Redis key for the embedding.
* **Returns:**
  True if the embedding exists in the cache, False otherwise.
* **Return type:**
  bool

[code example]

#### `expire(key, ttl=None)`

Set or refresh the expiration time for a key in the cache.

* **Parameters:**
  * **key** (*str*) – The Redis key to set the expiration on.
  * **ttl** (*Optional* *[* *int* *]* *,* *optional*) – The time-to-live in seconds. If None,
    uses the default TTL configured for this cache instance.
    Defaults to None.
* **Return type:**
  None

#### `NOTE`
If neither the provided TTL nor the default TTL is set (both are None),
this method will have no effect.

#### `get(text, model_name)`

Get embedding by text and model name.

Retrieves a cached embedding for the given text and model name.
If found, refreshes the TTL of the entry.

* **Parameters:**
  * **text** (*str*) – The text input that was embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Returns:**
  Embedding cache entry or None if not found.
* **Return type:**
  Optional[Dict[str, Any]]

[code example]

#### `get_by_key(key)`

Get embedding by its full Redis key.

Retrieves a cached embedding for the given Redis key.
If found, refreshes the TTL of the entry.

* **Parameters:**
  **key** (*str*) – The full Redis key for the embedding.
* **Returns:**
  Embedding cache entry or None if not found.
* **Return type:**
  Optional[Dict[str, Any]]

[code example]

#### `mdrop(texts, model_name)`

Remove multiple embeddings from the cache by their texts and model name.

Efficiently removes multiple embeddings in a single operation.

* **Parameters:**
  * **texts** (*List* *[* *str* *]*) – List of text inputs that were embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Return type:**
  None

[code example]

#### `mdrop_by_keys(keys)`

Remove multiple embeddings from the cache by their Redis keys.

Efficiently removes multiple embeddings in a single operation.

* **Parameters:**
  **keys** (*List* *[* *str* *]*) – List of Redis keys to remove.
* **Return type:**
  None

[code example]

#### `mexists(texts, model_name)`

Check if multiple embeddings exist by their texts and model name.

Efficiently checks existence of multiple embeddings in a single operation.

* **Parameters:**
  * **texts** (*List* *[* *str* *]*) – List of text inputs that were embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Returns:**
  List of boolean values indicating whether each embedding exists.
* **Return type:**
  List[bool]

[code example]

#### `mexists_by_keys(keys)`

Check if multiple embeddings exist by their Redis keys.

Efficiently checks existence of multiple keys in a single operation.

* **Parameters:**
  **keys** (*List* *[* *str* *]*) – List of Redis keys to check.
* **Returns:**
  List of boolean values indicating whether each key exists.
  The order matches the input keys order.
* **Return type:**
  List[bool]

[code example]

#### `mget(texts, model_name)`

Get multiple embeddings by their texts and model name.

Efficiently retrieves multiple cached embeddings in a single operation.
If found, refreshes the TTL of each entry.

* **Parameters:**
  * **texts** (*List* *[* *str* *]*) – List of text inputs that were embedded.
  * **model_name** (*str*) – The name of the embedding model.
* **Returns:**
  List of embedding cache entries or None for texts not found.
* **Return type:**
  List[Optional[Dict[str, Any]]]

[code example]

#### `mget_by_keys(keys)`

Get multiple embeddings by their Redis keys.

Efficiently retrieves multiple cached embeddings in a single network roundtrip.
If found, refreshes the TTL of each entry.

* **Parameters:**
  **keys** (*List* *[* *str* *]*) – List of Redis keys to retrieve.
* **Returns:**
  List of embedding cache entries or None for keys not found.
  The order matches the input keys order.
* **Return type:**
  List[Optional[Dict[str, Any]]]

[code example]

#### `mset(items, ttl=None)`

Store multiple embeddings in a batch operation.

Each item in the input list should be a dictionary with the following fields:
- ‘text’: The text input that was embedded
- ‘model_name’: The name of the embedding model
- ‘embedding’: The embedding vector
- ‘metadata’: Optional metadata to store with the embedding

* **Parameters:**
  * **items** (*List* *[* *Dict* *[* *str* *,* *Any* *]* *]*) – List of dictionaries, each containing text, model_name, embedding, and optional metadata.
  * **ttl** (*int* *|* *None*) – Optional TTL override for these entries.
* **Returns:**
  List of Redis keys where the embeddings were stored.
* **Return type:**
  List[str]

[code example]

#### `set(text, model_name, embedding, metadata=None, ttl=None)`

Store an embedding with its text and model name.

* **Parameters:**
  * **text** (*str*) – The text input that was embedded.
  * **model_name** (*str*) – The name of the embedding model.
  * **embedding** (*List* *[* *float* *]*) – The embedding vector to store.
  * **metadata** (*Optional* *[* *Dict* *[* *str* *,* *Any* *]* *]*) – Optional metadata to store with the embedding.
  * **ttl** (*Optional* *[* *int* *]*) – Optional TTL override for this specific entry.
* **Returns:**
  The Redis key where the embedding was stored.
* **Return type:**
  str

[code example]

#### `set_ttl(ttl=None)`

Set the default TTL, in seconds, for entries in the cache.

* **Parameters:**
  **ttl** (*Optional* *[* *int* *]* *,* *optional*) – The optional time-to-live expiration
  for the cache, in seconds.
* **Raises:**
  **ValueError** – If the time-to-live value is not an integer.
* **Return type:**
  None

#### `property ttl: int | None`

The default TTL, in seconds, for entries in the cache.

code:
response = await cache.acheck(
    prompt="What is the capital city of France?"
)

code:
key = await cache.astore(
    prompt="What is the capital city of France?",
    response="Paris",
    metadata={"city": "Paris", "country": "France"}
)

code:
key = await cache.astore('this is a prompt', 'this is a response')
await cache.aupdate(
    key,
    metadata={"hit_count": 1, "model_name": "Llama-2-7b"}
)

code:
response = cache.check(
    prompt="What is the capital city of France?"
)

code:
key = cache.store(
    prompt="What is the capital city of France?",
    response="Paris",
    metadata={"city": "Paris", "country": "France"}
)

code:
key = cache.store('this is a prompt', 'this is a response')
cache.update(key, metadata={"hit_count": 1, "model_name": "Llama-2-7b"})

code:
cache = EmbeddingsCache(
    name="my_embeddings_cache",
    ttl=3600,  # 1 hour
    redis_url="redis://localhost:6379"
)

code:
await cache.adrop(
    text="What is machine learning?",
    model_name="text-embedding-ada-002"
)

code:
if await cache.aexists("What is machine learning?", "text-embedding-ada-002"):
    print("Embedding is in cache")

code:
if await cache.aexists_by_key("embedcache:1234567890abcdef"):
    print("Embedding is in cache")

code:
embedding_data = await cache.aget(
    text="What is machine learning?",
    model_name="text-embedding-ada-002"
)

code: embedding_data = await cache.aget_by_key("embedcache:1234567890abcdef")

code:
# Remove multiple embeddings asynchronously
await cache.amdrop(
    texts=["What is machine learning?", "What is deep learning?"],
    model_name="text-embedding-ada-002"
)

code:
# Remove multiple embeddings asynchronously
await cache.amdrop_by_keys(["embedcache:key1", "embedcache:key2"])

code:
# Check if multiple embeddings exist asynchronously
exists_results = await cache.amexists(
    texts=["What is machine learning?", "What is deep learning?"],
    model_name="text-embedding-ada-002"
)

code:
# Check if multiple keys exist asynchronously
exists_results = await cache.amexists_by_keys(["embedcache:key1", "embedcache:key2"])

code:
# Get multiple embeddings asynchronously
embedding_data = await cache.amget(
    texts=["What is machine learning?", "What is deep learning?"],
    model_name="text-embedding-ada-002"
)

code:
# Get multiple embeddings asynchronously
embedding_data = await cache.amget_by_keys([
    "embedcache:key1",
    "embedcache:key2"
])

code:
# Store multiple embeddings asynchronously
keys = await cache.amset([
    {
        "text": "What is ML?",
        "model_name": "text-embedding-ada-002",
        "embedding": [0.1, 0.2, 0.3],
        "metadata": {"source": "user"}
    },
    {
        "text": "What is AI?",
        "model_name": "text-embedding-ada-002",
        "embedding": [0.4, 0.5, 0.6],
        "metadata": {"source": "docs"}
    }
])

code:
key = await cache.aset(
    text="What is machine learning?",
    model_name="text-embedding-ada-002",
    embedding=[0.1, 0.2, 0.3, ...],
    metadata={"source": "user_query"}
)

code:
cache.drop(
    text="What is machine learning?",
    model_name="text-embedding-ada-002"
)

code:
if cache.exists("What is machine learning?", "text-embedding-ada-002"):
    print("Embedding is in cache")

code:
if cache.exists_by_key("embedcache:1234567890abcdef"):
    print("Embedding is in cache")

code:
embedding_data = cache.get(
    text="What is machine learning?",
    model_name="text-embedding-ada-002"
)

code:
# Remove multiple embeddings
cache.mdrop(
    texts=["What is machine learning?", "What is deep learning?"],
    model_name="text-embedding-ada-002"
)

code:
# Remove multiple embeddings
cache.mdrop_by_keys(["embedcache:key1", "embedcache:key2"])

code:
# Check if multiple embeddings exist
exists_results = cache.mexists(
    texts=["What is machine learning?", "What is deep learning?"],
    model_name="text-embedding-ada-002"
)

code:
# Check if multiple keys exist
exists_results = cache.mexists_by_keys(["embedcache:key1", "embedcache:key2"])

code:
# Get multiple embeddings
embedding_data = cache.mget(
    texts=["What is machine learning?", "What is deep learning?"],
    model_name="text-embedding-ada-002"
)

code:
# Get multiple embeddings
embedding_data = cache.mget_by_keys([
    "embedcache:key1",
    "embedcache:key2"
])

code:
# Store multiple embeddings
keys = cache.mset([
    {
        "text": "What is ML?",
        "model_name": "text-embedding-ada-002",
        "embedding": [0.1, 0.2, 0.3],
        "metadata": {"source": "user"}
    },
    {
        "text": "What is AI?",
        "model_name": "text-embedding-ada-002",
        "embedding": [0.4, 0.5, 0.6],
        "metadata": {"source": "docs"}
    }
])

code:
key = cache.set(
    text="What is machine learning?",
    model_name="text-embedding-ada-002",
    embedding=[0.1, 0.2, 0.3, ...],
    metadata={"source": "user_query"}
)


title: Filter

page_type: content

title: Overview

role: overview

title: FilterExpression

role: content

title: `class FilterExpression(_filter=None, operator=None, left=None, right=None)`

text:
A FilterExpression is a logical combination of filters in RedisVL.

FilterExpressions can be combined using the & and | operators to create
complex expressions that evaluate to the Redis Query language.

This presents an interface by which users can create complex queries
without having to know the Redis Query language.

[code example]

This can be combined with the VectorQuery class to create a query:

[code example]

#### `NOTE`
Filter expressions are typically not called directly. Instead they are
built by combining filter statements using the & and | operators.

* **Parameters:**
  * **\_filter** (*str* *|* *None*)
  * **operator** (*FilterOperator* *|* *None*)
  * **left** ([FilterExpression](#filterexpression) *|* *None*)
  * **right** ([FilterExpression](#filterexpression) *|* *None*)

title: Tag

title: `class Tag(field)`

text:
A Tag filter can be applied to Tag fields

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Create a Tag equality filter expression.

* **Parameters:**
  **other** (*Union* *[* *List* *[* *str* *]* *,* *str* *]*) – The tag(s) to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__ne__(other)`

Create a Tag inequality filter expression.

* **Parameters:**
  **other** (*Union* *[* *List* *[* *str* *]* *,* *str* *]*) – The tag(s) to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__str__()`

Return the Redis Query string for the Tag filter

* **Return type:**
  str

title: Text

title: `class Text(field)`

text:
A Text is a FilterField representing a text field in a Redis index.

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Create a Text equality filter expression. These expressions yield
filters that enforce an exact match on the supplied term(s).

* **Parameters:**
  **other** (*str*) – The text value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__mod__(other)`

Create a Text "LIKE" filter expression. A flexible expression that
yields filters that can use a variety of additional operators like
wildcards (\*), fuzzy matches (%%), or combinatorics (|) of the supplied
term(s).

* **Parameters:**
  **other** (*str*) – The text value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__ne__(other)`

Create a Text inequality filter expression. These expressions yield
negated filters on exact matches on the supplied term(s). Opposite of an
equality filter expression.

* **Parameters:**
  **other** (*str*) – The text value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__str__()`

Return the Redis Query string for the Text filter

* **Return type:**
  str

title: Num

title: `class Num(field)`

text:
A Num is a FilterField representing a numeric field in a Redis index.

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Create a Numeric equality filter expression.

* **Parameters:**
  **other** (*int*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__ge__(other)`

Create a Numeric greater than or equal to filter expression.

* **Parameters:**
  **other** (*int*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__gt__(other)`

Create a Numeric greater than filter expression.

* **Parameters:**
  **other** (*int*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__le__(other)`

Create a Numeric less than or equal to filter expression.

* **Parameters:**
  **other** (*int*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__lt__(other)`

Create a Numeric less than filter expression.

* **Parameters:**
  **other** (*int*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__ne__(other)`

Create a Numeric inequality filter expression.

* **Parameters:**
  **other** (*int*) – The value to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__str__()`

Return the Redis Query string for the Numeric filter

* **Return type:**
  str

#### `between(start, end, inclusive='both')`

Operator for searching values between two numeric values.

* **Parameters:**
  * **start** (*int*)
  * **end** (*int*)
  * **inclusive** (*str*)
* **Return type:**
  [FilterExpression](#filterexpression)

title: Geo

title: `class Geo(field)`

text:
A Geo is a FilterField representing a geographic (lat/lon) field in a
Redis index.

* **Parameters:**
  **field** (*str*)

#### `__eq__(other)`

Create a geographic filter within a specified GeoRadius.

* **Parameters:**
  **other** ([GeoRadius](#georadius)) – The geographic spec to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__ne__(other)`

Create a geographic filter outside of a specified GeoRadius.

* **Parameters:**
  **other** ([GeoRadius](#georadius)) – The geographic spec to filter on.
* **Return type:**
  [FilterExpression](#filterexpression)

[code example]

#### `__str__()`

Return the Redis Query string for the Geo filter

* **Return type:**
  str

title: GeoRadius

title: `class GeoRadius(longitude, latitude, radius=1, unit='km')`

text:
A GeoRadius is a GeoSpec representing a geographic radius.

Create a GeoRadius specification (GeoSpec)

* **Parameters:**
  * **longitude** (*float*) – The longitude of the center of the radius.
  * **latitude** (*float*) – The latitude of the center of the radius.
  * **radius** (*int* *,* *optional*) – The radius of the circle. Defaults to 1.
  * **unit** (*str* *,* *optional*) – The unit of the radius. Defaults to "km".
* **Raises:**
  **ValueError** – If the unit is not one of "m", "km", "mi", or "ft".

#### `__init__(longitude, latitude, radius=1, unit='km')`

Create a GeoRadius specification (GeoSpec)

* **Parameters:**
  * **longitude** (*float*) – The longitude of the center of the radius.
  * **latitude** (*float*) – The latitude of the center of the radius.
  * **radius** (*int* *,* *optional*) – The radius of the circle. Defaults to 1.
  * **unit** (*str* *,* *optional*) – The unit of the radius. Defaults to "km".
* **Raises:**
  **ValueError** – If the unit is not one of "m", "km", "mi", or "ft".

code:
from redisvl.query.filter import Tag, Num

brand_is_nike = Tag("brand") == "nike"
price_is_over_100 = Num("price") < 100
f = brand_is_nike & price_is_over_100

print(str(f))

>> (@brand:{nike} @price:[-inf (100)])

code:
from redisvl.query import VectorQuery

v = VectorQuery(
    vector=[0.1, 0.1, 0.5, ...],
    vector_field_name="product_embedding",
    return_fields=["product_id", "brand", "price"],
    filter_expression=f,
)

code:
from redisvl.query.filter import Tag

f = Tag("brand") == "nike"

section_id: class-tag-field

code:
from redisvl.query.filter import Tag
f = Tag("brand") != "nike"

code:
from redisvl.query.filter import Text

f = Text("job") == "engineer"

section_id: class-text-field

code:
from redisvl.query.filter import Text

f = Text("job") % "engine*"         # suffix wild card match
f = Text("job") % "%%engine%%"      # fuzzy match w/ Levenshtein Distance
f = Text("job") % "engineer|doctor" # contains either term in field
f = Text("job") % "engineer doctor" # contains both terms in field

code:
from redisvl.query.filter import Text

f = Text("job") != "engineer"

code:
from redisvl.query.filter import Num
f = Num("zipcode") == 90210

section_id: class-num-field

code:
from redisvl.query.filter import Num

f = Num("age") >= 18

code:
from redisvl.query.filter import Num

f = Num("age") > 18

code:
from redisvl.query.filter import Num

f = Num("age") <= 18

code:
from redisvl.query.filter import Num

f = Num("age") < 18

code:
from redisvl.query.filter import Num

f = Num("zipcode") != 90210

code:
from redisvl.query.filter import Geo, GeoRadius

f = Geo("location") == GeoRadius(-122.4194, 37.7749, 1, unit="m")

section_id: class-geo-field

code:
from redisvl.query.filter import Geo, GeoRadius

f = Geo("location") != GeoRadius(-122.4194, 37.7749, 1, unit="m")


title: RedisVL API

title: Filter

title: LLM Cache

title: LLM Message History

title: LLM Session Manager

title: Query

title: Rerankers

title: Schema

title: Search Index Classes

title: Semantic Router

title: Threshold Optimizers

title: Vector

title: Vectorizers

title: Content

text:
Reference documentation for the RedisVL API.

* [Schema](schema/)
  * [IndexSchema](schema/#indexschema)
  * [Index-Level Stopwords Configuration](schema/#index-level-stopwords-configuration)
  * [Defining Fields](schema/#defining-fields)
  * [Basic Field Types](schema/#basic-field-types)
  * [Vector Field Types](schema/#vector-field-types)
  * [SVS-VAMANA Configuration Utilities](schema/#svs-vamana-configuration-utilities)
  * [Vector Algorithm Comparison](schema/#vector-algorithm-comparison)
* [Search Index Classes](searchindex/)
  * [SearchIndex](searchindex/#searchindex)
  * [AsyncSearchIndex](searchindex/#asyncsearchindex)
* [Vector](vector/)
  * [Vector](vector/#id1)
* [Query](query/)
  * [VectorQuery](query/#vectorquery)
  * [VectorRangeQuery](query/#vectorrangequery)
  * [HybridQuery](query/#hybridquery)
  * [TextQuery](query/#textquery)
  * [FilterQuery](query/#filterquery)
  * [CountQuery](query/#countquery)
  * [MultiVectorQuery](query/#multivectorquery)
* [Filter](filter/)
  * [FilterExpression](filter/#filterexpression)
  * [Tag](filter/#tag)
  * [Text](filter/#text)
  * [Num](filter/#num)
  * [Geo](filter/#geo)
  * [GeoRadius](filter/#georadius)
* [Vectorizers](vectorizer/)
  * [HFTextVectorizer](vectorizer/#hftextvectorizer)
  * [OpenAITextVectorizer](vectorizer/#openaitextvectorizer)
  * [AzureOpenAITextVectorizer](vectorizer/#azureopenaitextvectorizer)
  * [VertexAITextVectorizer](vectorizer/#vertexaitextvectorizer)
  * [CohereTextVectorizer](vectorizer/#coheretextvectorizer)
  * [BedrockTextVectorizer](vectorizer/#bedrocktextvectorizer)
  * [CustomTextVectorizer](vectorizer/#customtextvectorizer)
  * [VoyageAITextVectorizer](vectorizer/#voyageaitextvectorizer)
* [Rerankers](reranker/)
  * [CohereReranker](reranker/#coherereranker)
  * [HFCrossEncoderReranker](reranker/#hfcrossencoderreranker)
  * [VoyageAIReranker](reranker/#voyageaireranker)
* [LLM Cache](cache/)
  * [SemanticCache](cache/#semanticcache)
* [Embeddings Cache](cache/#embeddings-cache)
  * [EmbeddingsCache](cache/#embeddingscache)
* [LLM Message History](message_history/)
  * [SemanticMessageHistory](message_history/#semanticmessagehistory)
  * [MessageHistory](message_history/#messagehistory)
* [Semantic Router](router/)
  * [Semantic Router](router/#semantic-router-api)
  * [Routing Config](router/#routing-config)
  * [Route](router/#route)
  * [Route Match](router/#route-match)
  * [Distance Aggregation Method](router/#distance-aggregation-method)


title: LLM Message History

title: SemanticMessageHistory

title: `class SemanticMessageHistory(name, session_tag=None, prefix=None, vectorizer=None, distance_threshold=0.3, redis_client=None, redis_url='redis://localhost:6379', connection_kwargs={}, overwrite=False, **kwargs)`

text:
Bases: `BaseMessageHistory`

Initialize message history with index

Semantic Message History stores the current and previous user text prompts
and LLM responses to allow for enriching future prompts with session
context. Message history is stored in individual user or LLM prompts and
responses.

* **Parameters:**
  * **name** (*str*) – The name of the message history index.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
  * **prefix** (*Optional* *[* *str* *]*) – Prefix for the keys for this message data.
    Defaults to None and will be replaced with the index name.
  * **vectorizer** (*Optional* *[* *BaseVectorizer* *]*) – The vectorizer used to create embeddings.
  * **distance_threshold** (*float*) – The maximum semantic distance to be
    included in the context. Defaults to 0.3.
  * **redis_client** (*Optional* *[* *Redis* *]*) – A Redis client instance. Defaults to
    None.
  * **redis_url** (*str* *,* *optional*) – The redis url. Defaults to redis://localhost:6379.
  * **connection_kwargs** (*Dict* *[* *str* *,* *Any* *]*) – The connection arguments
    for the redis client. Defaults to empty {}.
  * **overwrite** (*bool*) – Whether or not to force overwrite the schema for
    the semantic message index. Defaults to false.

The proposed schema will support a single vector embedding constructed
from either the prompt or response in a single string.

#### `add_message(message, session_tag=None)`

Insert a single prompt or response into the message history.
A timestamp is associated with it so that it can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **message** (*Dict* *[* *str* *,**str* *]*) – The user prompt or LLM response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entry to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `add_messages(messages, session_tag=None)`

Insert a list of prompts and responses into the session memory.
A timestamp is associated with each so that they can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **messages** (*List* *[* *Dict* *[* *str* *,* *str* *]* *]*) – The list of user prompts and LLM responses.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `clear()`

Clears the message history.

* **Return type:**
  None

#### `delete()`

Clear all message keys and remove the search index.

* **Return type:**
  None

#### `drop(id=None)`

Remove a specific exchange from the message history.

* **Parameters:**
  **id** (*Optional* *[* *str* *]*) – The id of the message entry to delete.
  If None then the last entry is deleted.
* **Return type:**
  None

#### `get_recent(top_k=5, as_text=False, raw=False, session_tag=None, role=None)`

Retrieve the recent message history in sequential order.

* **Parameters:**
  * **top_k** (*int*) – The number of previous exchanges to return. Default is 5.
  * **as_text** (*bool*) – Whether to return the conversation as a single string,
    or list of alternating prompts and responses.
  * **raw** (*bool*) – Whether to return the full Redis hash entry or just the
    prompt and response
  * **session_tag** (*Optional* *[* *str* *]*) – Tag of the entries linked to a specific
    conversation session. Defaults to instance ULID.
  * **role** (*Optional* *[* *Union* *[* *str* *,* *List* *[* *str* *]* *]* *]*) – Filter messages by role(s).
    Can be a single role string ("system", "user", "llm", "tool") or
    a list of roles. If None, all roles are returned.
* **Returns:**
  A single string transcription of the session
  : or list of strings if as_text is false.
* **Return type:**
  Union[str, List[str]]
* **Raises:**
  **ValueError** – if top_k is not an integer greater than or equal to 0,
      or if role contains invalid values.

#### `get_relevant(prompt, as_text=False, top_k=5, fall_back=False, session_tag=None, raw=False, distance_threshold=None, role=None)`

Searches 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** (*str*) – The message text to search for in message history
  * **as_text** (*bool*) – Whether to return the prompts and responses as text
  * **JSON.** (*or as*)
  * **top_k** (*int*) – The number of previous messages to return. Default is 5.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag of the entries linked to a specific
    conversation session. Defaults to instance ULID.
  * **distance_threshold** (*Optional* *[* *float* *]*) – The threshold for semantic
    vector distance.
  * **fall_back** (*bool*) – Whether to drop back to recent conversation history
    if no relevant context is found.
  * **raw** (*bool*) – Whether to return the full Redis hash entry or just the
    message.
  * **role** (*Optional* *[* *Union* *[* *str* *,* *List* *[* *str* *]* *]* *]*) – Filter messages by role(s).
    Can be a single role string ("system", "user", "llm", "tool") or
    a list of roles. If None, all roles are returned.
* **Returns:**
  Either a list of strings, or a
  list of prompts and responses in JSON containing the most relevant.
* **Return type:**
  Union[List[str], List[Dict[str,str]]

Raises ValueError: if top_k is not an integer greater or equal to 0,
: or if role contains invalid values.

#### `store(prompt, response, session_tag=None)`

Insert a prompt:response pair into the message history. A timestamp
is associated with each message so that they can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **prompt** (*str*) – The user prompt to the LLM.
  * **response** (*str*) – The corresponding LLM response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `property messages: List[str] | List[Dict[str, str]]`

Returns the full message history.

title: MessageHistory

title: `class MessageHistory(name, session_tag=None, prefix=None, redis_client=None, redis_url='redis://localhost:6379', connection_kwargs={}, **kwargs)`

text:
Bases: `BaseMessageHistory`

Initialize message history

Message History stores the current and previous user text prompts and
LLM responses to allow for enriching future prompts with session
context. Message history is stored in individual user or LLM prompts and
responses.

* **Parameters:**
  * **name** (*str*) – The name of the message history index.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
  * **prefix** (*Optional* *[* *str* *]*) – Prefix for the keys for this conversation data.
    Defaults to None and will be replaced with the index name.
  * **redis_client** (*Optional* *[* *Redis* *]*) – A Redis client instance. Defaults to
    None.
  * **redis_url** (*str* *,* *optional*) – The redis url. Defaults to redis://localhost:6379.
  * **connection_kwargs** (*Dict* *[* *str* *,* *Any* *]*) – The connection arguments
    for the redis client. Defaults to empty {}.

#### `add_message(message, session_tag=None)`

Insert a single prompt or response into the message history.
A timestamp is associated with it so that it can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **message** (*Dict* *[* *str* *,**str* *]*) – The user prompt or LLM response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `add_messages(messages, session_tag=None)`

Insert a list of prompts and responses into the message history.
A timestamp is associated with each so that they can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **messages** (*List* *[* *Dict* *[* *str* *,* *str* *]* *]*) – The list of user prompts and LLM responses.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `clear()`

Clears the conversation message history.

* **Return type:**
  None

#### `delete()`

Clear all conversation keys and remove the search index.

* **Return type:**
  None

#### `drop(id=None)`

Remove a specific exchange from the conversation history.

* **Parameters:**
  **id** (*Optional* *[* *str* *]*) – The id of the message entry to delete.
  If None then the last entry is deleted.
* **Return type:**
  None

#### `get_recent(top_k=5, as_text=False, raw=False, session_tag=None, role=None)`

Retrieve the recent message history in sequential order.

* **Parameters:**
  * **top_k** (*int*) – The number of previous messages to return. Default is 5.
  * **as_text** (*bool*) – Whether to return the conversation as a single string,
    or list of alternating prompts and responses.
  * **raw** (*bool*) – Whether to return the full Redis hash entry or just the
    prompt and response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag of the entries linked to a specific
    conversation session. Defaults to instance ULID.
  * **role** (*Optional* *[* *Union* *[* *str* *,* *List* *[* *str* *]* *]* *]*) – Filter messages by role(s).
    Can be a single role string ("system", "user", "llm", "tool") or
    a list of roles. If None, all roles are returned.
* **Returns:**
  A single string transcription of the messages
  : or list of strings if as_text is false.
* **Return type:**
  Union[str, List[str]]
* **Raises:**
  **ValueError** – if top_k is not an integer greater than or equal to 0,
      or if role contains invalid values.

#### `store(prompt, response, session_tag=None)`

Insert a prompt:response pair into the message history. A timestamp
is associated with each exchange so that they can be later sorted
in sequential ordering after retrieval.

* **Parameters:**
  * **prompt** (*str*) – The user prompt to the LLM.
  * **response** (*str*) – The corresponding LLM response.
  * **session_tag** (*Optional* *[* *str* *]*) – Tag to be added to entries to link to a specific
    conversation session. Defaults to instance ULID.
* **Return type:**
  None

#### `property messages: List[str] | List[Dict[str, str]]`

Returns the full message history.