AstraDBSemanticCache#

class langchain_astradb.cache.AstraDBSemanticCache(*, collection_name: str = 'langchain_astradb_semantic_cache', token: str | TokenProvider | None = None, api_endpoint: str | None = None, namespace: str | None = None, environment: str | None = None, setup_mode: SetupMode = SetupMode.SYNC, pre_delete_collection: bool = False, embedding: Embeddings, metric: str | None = None, similarity_threshold: float = 0.85, ext_callers: list[tuple[str | None, str | None] | str | None] | None = None, astra_db_client: AstraDB | None = None, async_astra_db_client: AsyncAstraDB | None = None)[source]#

Astra DB semantic cache.

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

It uses a single (vector) collection and can store cached values from several LLMs, so the LLM’s ‘llm_string’ is stored in the document metadata.

You can choose the preferred similarity (or use the API default). The default score threshold is tuned to the default metric. Tune it carefully yourself if switching to another distance metric.

Parameters:
  • collection_name (str) – name of the Astra DB collection to create/use.

  • token (str | TokenProvider | None) – API token for Astra DB usage, either in the form of a string or a subclass of astrapy.authentication.TokenProvider. If not provided, the environment variable ASTRA_DB_APPLICATION_TOKEN is inspected.

  • api_endpoint (str | None) – full URL to the API endpoint, such as https://<DB-ID>-us-east1.apps.astra.datastax.com. If not provided, the environment variable ASTRA_DB_API_ENDPOINT is inspected.

  • namespace (str | None) – namespace (aka keyspace) where the collection is created. If not provided, the environment variable ASTRA_DB_KEYSPACE is inspected. Defaults to the database’s “default namespace”.

  • environment (str | None) – a string specifying the environment of the target Data API. If omitted, defaults to “prod” (Astra DB production). Other values are in astrapy.constants.Environment enum class.

  • setup_mode (SetupMode) – mode used to create the Astra DB collection (SYNC, ASYNC or OFF).

  • pre_delete_collection (bool) – whether to delete the collection before creating it. If False and the collection already exists, the collection will be used as is.

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

  • metric (str | None) – the function to use for evaluating similarity of text embeddings. Defaults to ‘cosine’ (alternatives: ‘euclidean’, ‘dot_product’)

  • similarity_threshold (float) – the minimum similarity for accepting a (semantic-search) match.

  • ext_callers (list[tuple[str | None, str | None] | str | None] | None) – one or more caller identities to identify Data API calls in the User-Agent header. This is a list of (name, version) pairs, or just strings if no version info is provided, which, if supplied, becomes the leading part of the User-Agent string in all API requests related to this component.

  • astra_db_client (AstraDB | None) – DEPRECATED starting from version 0.3.5. Please use ‘token’, ‘api_endpoint’ and optionally ‘environment’. you can pass an already-created ‘astrapy.db.AstraDB’ instance (alternatively to ‘token’, ‘api_endpoint’ and ‘environment’).

  • async_astra_db_client (AsyncAstraDB | None) – DEPRECATED starting from version 0.3.5. Please use ‘token’, ‘api_endpoint’ and optionally ‘environment’. you can pass an already-created ‘astrapy.db.AsyncAstraDB’ instance (alternatively to ‘token’, ‘api_endpoint’ and ‘environment’).

Methods

__init__(*[, collection_name, token, ...])

Astra DB semantic cache.

aclear(**kwargs)

Async clear cache that can take additional keyword arguments.

adelete_by_document_id(document_id)

Delete by document 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])

Look up based on prompt and LLM.

aupdate(prompt, llm_string, return_val)

Async update cache based on prompt and llm_string.

clear(**kwargs)

Clear cache that can take additional keyword arguments.

delete_by_document_id(document_id)

Delete by document 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])

Look up based on prompt and LLM.

update(prompt, llm_string, return_val)

Update cache based on prompt and llm_string.

__init__(*, collection_name: str = 'langchain_astradb_semantic_cache', token: str | TokenProvider | None = None, api_endpoint: str | None = None, namespace: str | None = None, environment: str | None = None, setup_mode: SetupMode = SetupMode.SYNC, pre_delete_collection: bool = False, embedding: Embeddings, metric: str | None = None, similarity_threshold: float = 0.85, ext_callers: list[tuple[str | None, str | None] | str | None] | None = None, astra_db_client: AstraDB | None = None, async_astra_db_client: AsyncAstraDB | None = None)[source]#

Astra DB semantic cache.

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

It uses a single (vector) collection and can store cached values from several LLMs, so the LLM’s ‘llm_string’ is stored in the document metadata.

You can choose the preferred similarity (or use the API default). The default score threshold is tuned to the default metric. Tune it carefully yourself if switching to another distance metric.

Parameters:
  • collection_name (str) – name of the Astra DB collection to create/use.

  • token (str | TokenProvider | None) – API token for Astra DB usage, either in the form of a string or a subclass of astrapy.authentication.TokenProvider. If not provided, the environment variable ASTRA_DB_APPLICATION_TOKEN is inspected.

  • api_endpoint (str | None) – full URL to the API endpoint, such as https://<DB-ID>-us-east1.apps.astra.datastax.com. If not provided, the environment variable ASTRA_DB_API_ENDPOINT is inspected.

  • namespace (str | None) – namespace (aka keyspace) where the collection is created. If not provided, the environment variable ASTRA_DB_KEYSPACE is inspected. Defaults to the database’s “default namespace”.

  • environment (str | None) – a string specifying the environment of the target Data API. If omitted, defaults to “prod” (Astra DB production). Other values are in astrapy.constants.Environment enum class.

  • setup_mode (SetupMode) – mode used to create the Astra DB collection (SYNC, ASYNC or OFF).

  • pre_delete_collection (bool) – whether to delete the collection before creating it. If False and the collection already exists, the collection will be used as is.

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

  • metric (str | None) – the function to use for evaluating similarity of text embeddings. Defaults to ‘cosine’ (alternatives: ‘euclidean’, ‘dot_product’)

  • similarity_threshold (float) – the minimum similarity for accepting a (semantic-search) match.

  • ext_callers (list[tuple[str | None, str | None] | str | None] | None) – one or more caller identities to identify Data API calls in the User-Agent header. This is a list of (name, version) pairs, or just strings if no version info is provided, which, if supplied, becomes the leading part of the User-Agent string in all API requests related to this component.

  • astra_db_client (AstraDB | None) – DEPRECATED starting from version 0.3.5. Please use ‘token’, ‘api_endpoint’ and optionally ‘environment’. you can pass an already-created ‘astrapy.db.AstraDB’ instance (alternatively to ‘token’, ‘api_endpoint’ and ‘environment’).

  • async_astra_db_client (AsyncAstraDB | None) – DEPRECATED starting from version 0.3.5. Please use ‘token’, ‘api_endpoint’ and optionally ‘environment’. you can pass an already-created ‘astrapy.db.AsyncAstraDB’ instance (alternatively to ‘token’, ‘api_endpoint’ and ‘environment’).

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

Async clear cache that can take additional keyword arguments.

Parameters:

kwargs (Any)

Return type:

None

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

Delete by 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. 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) for the top hit

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, RETURN_VAL_TYPE] | None[source]#

Look up based on prompt and LLM.

If there are hits, return (document_id, cached_entry) for the top hit

Parameters:
  • prompt (str)

  • llm (LLM)

  • stop (list[str] | None)

Return type:

tuple[str, RETURN_VAL_TYPE] | 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 cache that can take additional keyword arguments.

Parameters:

kwargs (Any)

Return type:

None

delete_by_document_id(document_id: str) None[source]#

Delete by 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. 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) for the top hit

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, RETURN_VAL_TYPE] | None[source]#

Look up based on prompt and LLM.

If there are hits, return (document_id, cached_entry) for the top hit

Parameters:
  • prompt (str)

  • llm (LLM)

  • stop (list[str] | None)

Return type:

tuple[str, RETURN_VAL_TYPE] | 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