CassandraSemanticCache#

class langchain_community.cache.CassandraSemanticCache(session: CassandraSession | None = None, keyspace: str | None = None, embedding: Embeddings | None = None, table_name: str = 'langchain_llm_semantic_cache', distance_metric: str | None = None, score_threshold: float = 0.85, ttl_seconds: int | None = None, skip_provisioning: bool = False, similarity_measure: str = 'dot', setup_mode: CassandraSetupMode = SetupMode.SYNC)[source]#

Cache that uses Cassandra as a vector-store backend for semantic (i.e. similarity-based) lookup.

Example

import cassio

from langchain_community.cache import CassandraSemanticCache
from langchain_core.globals import set_llm_cache

cassio.init(auto=True)  # Requires env. variables, see CassIO docs

my_embedding = ...

set_llm_cache(CassandraSemanticCache(
    embedding=my_embedding,
    table_name="my_semantic_cache",
))

It uses a single (vector) Cassandra table and stores, in principle, cached values from several LLMs, so the LLM’s llm_string is part of the rows’ primary keys.

One can choose a similarity measure (default: “dot” for dot-product). Choosing another one (“cos”, “l2”) almost certainly requires threshold tuning. (which may be in order nevertheless, even if sticking to “dot”).

Parameters:
  • session (Optional[CassandraSession]) – an open Cassandra session. Leave unspecified to use the global cassio init (see below)

  • keyspace (Optional[str]) – the keyspace to use for storing the cache. Leave unspecified to use the global cassio init (see below)

  • embedding (Optional[Embeddings]) – Embedding provider for semantic encoding and search.

  • table_name (str) – name of the Cassandra (vector) table to use as cache. There is a default for “simple” usage, but remember to explicitly specify different tables if several embedding models coexist in your app (they cannot share one cache table).

  • distance_metric (Optional[str]) – an alias for the ‘similarity_measure’ parameter (see below). As the “distance” terminology is misleading, please prefer ‘similarity_measure’ for clarity.

  • score_threshold (float) – numeric value to use as cutoff for the similarity searches

  • ttl_seconds (Optional[int]) – time-to-live for cache entries (default: None, i.e. forever)

  • similarity_measure (str) – which measure to adopt for similarity searches. Note: this parameter is aliased by ‘distance_metric’ - however, it is suggested to use the “similarity” terminology since this value is in fact a similarity (i.e. higher means closer). Note that at most one of the two parameters ‘distance_metric’ and ‘similarity_measure’ can be provided.

  • setup_mode (CassandraSetupMode) – a value in langchain_community.utilities.cassandra.SetupMode. Choose between SYNC, ASYNC and OFF - the latter if the Cassandra table is guaranteed to exist already, for a faster initialization.

  • skip_provisioning (bool) –

Note

The session and keyspace parameters, when left out (or passed as None), fall back to the globally-available cassio settings if any are available. In other words, if a previously-run ‘cassio.init(…)’ has been executed previously anywhere in the code, Cassandra-based objects need not specify the connection parameters at all.

Methods

__init__([session, keyspace, embedding, ...])

aclear(**kwargs)

Clear the whole semantic cache.

adelete_by_document_id(document_id)

Given this is a "similarity search" cache, an invalidation pattern that makes sense is first a lookup to get an ID, and then deleting with that ID.

alookup(prompt, llm_string)

Async look up based on prompt and llm_string.

alookup_with_id(prompt, llm_string)

Look up based on prompt and llm_string.

alookup_with_id_through_llm(prompt, llm[, stop])

aupdate(prompt, llm_string, return_val)

Async update cache based on prompt and llm_string.

clear(**kwargs)

Clear the whole semantic cache.

delete_by_document_id(document_id)

Given this is a "similarity search" cache, an invalidation pattern that makes sense is first a lookup to get an ID, and then deleting with that ID.

lookup(prompt, llm_string)

Look up based on prompt and llm_string.

lookup_with_id(prompt, llm_string)

Look up based on prompt and llm_string.

lookup_with_id_through_llm(prompt, llm[, stop])

update(prompt, llm_string, return_val)

Update cache based on prompt and llm_string.

__init__(session: CassandraSession | None = None, keyspace: str | None = None, embedding: Embeddings | None = None, table_name: str = 'langchain_llm_semantic_cache', distance_metric: str | None = None, score_threshold: float = 0.85, ttl_seconds: int | None = None, skip_provisioning: bool = False, similarity_measure: str = 'dot', setup_mode: CassandraSetupMode = SetupMode.SYNC)[source]#
Parameters:
  • session (Optional[CassandraSession]) –

  • keyspace (Optional[str]) –

  • embedding (Optional[Embeddings]) –

  • table_name (str) –

  • distance_metric (Optional[str]) –

  • score_threshold (float) –

  • ttl_seconds (Optional[int]) –

  • skip_provisioning (bool) –

  • similarity_measure (str) –

  • setup_mode (CassandraSetupMode) –

async aclear(**kwargs: Any) None[source]#

Clear the whole semantic cache.

Parameters:

kwargs (Any) –

Return type:

None

async adelete_by_document_id(document_id: str) None[source]#

Given this is a “similarity search” cache, an invalidation pattern that makes sense is first a lookup to get an ID, and then deleting with that ID. This is for the second step.

Parameters:

document_id (str) –

Return type:

None

async alookup(prompt: str, llm_string: str) Sequence[Generation] | None[source]#

Async look up based on prompt and llm_string.

A cache implementation is expected to generate a key from the 2-tuple of prompt and llm_string (e.g., by concatenating them with a delimiter).

Parameters:
  • prompt (str) – a string representation of the prompt. In the case of a Chat model, the prompt is a non-trivial serialization of the prompt into the language model.

  • llm_string (str) – A string representation of the LLM configuration. This is used to capture the invocation parameters of the LLM (e.g., model name, temperature, stop tokens, max tokens, etc.). These invocation parameters are serialized into a string representation.

Returns:

On a cache miss, return None. On a cache hit, return the cached value. The cached value is a list of Generations (or subclasses).

Return type:

Sequence[Generation] | None

async alookup_with_id(prompt: str, llm_string: str) Tuple[str, Sequence[Generation]] | None[source]#

Look up based on prompt and llm_string. If there are hits, return (document_id, cached_entry)

Parameters:
  • prompt (str) –

  • llm_string (str) –

Return type:

Tuple[str, Sequence[Generation]] | None

async alookup_with_id_through_llm(prompt: str, llm: LLM, stop: List[str] | None = None) Tuple[str, Sequence[Generation]] | None[source]#
Parameters:
  • prompt (str) –

  • llm (LLM) –

  • stop (List[str] | None) –

Return type:

Tuple[str, Sequence[Generation]] | None

async aupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) None[source]#

Async update cache based on prompt and llm_string.

The prompt and llm_string are used to generate a key for the cache. The key should match that of the look up method.

Parameters:
  • prompt (str) – a string representation of the prompt. In the case of a Chat model, the prompt is a non-trivial serialization of the prompt into the language model.

  • llm_string (str) – A string representation of the LLM configuration. This is used to capture the invocation parameters of the LLM (e.g., model name, temperature, stop tokens, max tokens, etc.). These invocation parameters are serialized into a string representation.

  • return_val (Sequence[Generation]) – The value to be cached. The value is a list of Generations (or subclasses).

Return type:

None

clear(**kwargs: Any) None[source]#

Clear the whole semantic cache.

Parameters:

kwargs (Any) –

Return type:

None

delete_by_document_id(document_id: str) None[source]#

Given this is a “similarity search” cache, an invalidation pattern that makes sense is first a lookup to get an ID, and then deleting with that ID. This is for the second step.

Parameters:

document_id (str) –

Return type:

None

lookup(prompt: str, llm_string: str) Sequence[Generation] | None[source]#

Look up based on prompt and llm_string.

A cache implementation is expected to generate a key from the 2-tuple of prompt and llm_string (e.g., by concatenating them with a delimiter).

Parameters:
  • prompt (str) – a string representation of the prompt. In the case of a Chat model, the prompt is a non-trivial serialization of the prompt into the language model.

  • llm_string (str) – A string representation of the LLM configuration. This is used to capture the invocation parameters of the LLM (e.g., model name, temperature, stop tokens, max tokens, etc.). These invocation parameters are serialized into a string representation.

Returns:

On a cache miss, return None. On a cache hit, return the cached value. The cached value is a list of Generations (or subclasses).

Return type:

Sequence[Generation] | None

lookup_with_id(prompt: str, llm_string: str) Tuple[str, Sequence[Generation]] | None[source]#

Look up based on prompt and llm_string. If there are hits, return (document_id, cached_entry)

Parameters:
  • prompt (str) –

  • llm_string (str) –

Return type:

Tuple[str, Sequence[Generation]] | None

lookup_with_id_through_llm(prompt: str, llm: LLM, stop: List[str] | None = None) Tuple[str, Sequence[Generation]] | None[source]#
Parameters:
  • prompt (str) –

  • llm (LLM) –

  • stop (List[str] | None) –

Return type:

Tuple[str, Sequence[Generation]] | None

update(prompt: str, llm_string: str, return_val: Sequence[Generation]) None[source]#

Update cache based on prompt and llm_string.

The prompt and llm_string are used to generate a key for the cache. The key should match that of the lookup method.

Parameters:
  • prompt (str) – a string representation of the prompt. In the case of a Chat model, the prompt is a non-trivial serialization of the prompt into the language model.

  • llm_string (str) – A string representation of the LLM configuration. This is used to capture the invocation parameters of the LLM (e.g., model name, temperature, stop tokens, max tokens, etc.). These invocation parameters are serialized into a string representation.

  • return_val (Sequence[Generation]) – The value to be cached. The value is a list of Generations (or subclasses).

Return type:

None

Examples using CassandraSemanticCache