Tony20100/langchain_full huggingface dataset:
you can pass an already-created ‘astrapy.db.AsyncAstraDB’ instance.
namespace (Optional[str]) – namespace (aka keyspace) where the
collection is created. Defaults to the database’s “default namespace”.
setup_mode (AstraSetupMode) – 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 (Optional[str]) – 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.
Methods
__init__(*[, collection_name, token, ...])
Cache that uses Astra DB as a vector-store backend for semantic (i.e.
aclear(**kwargs)
Clear cache that can take additional keyword arguments.
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)
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)
Update cache based on prompt and llm_string.
clear(**kwargs)
Clear cache that can take additional keyword arguments.
delete_by_document_id(document_id)
Clear cache that can take additional keyword arguments.
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__(*, collection_name: str = 'langchain_astradb_semantic_cache', token: Optional[str] = None, api_endpoint: Optional[str] = None, astra_db_client: Optional[AstraDB] = None, async_astra_db_client: Optional[AsyncAstraDB] = None, namespace: Optional[str] = None, setup_mode: AstraSetupMode = SetupMode.SYNC, pre_delete_collection: bool = False, embedding: Embeddings, metric: Optional[str] = None, similarity_threshold: float = 0.85)[source]¶
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 (Optional[str]) – API token for Astra DB usage.
token (Optional[str]) – API token for Astra DB usage.
api_endpoint (Optional[str]) – full URL to the API endpoint,
such as https://<DB-ID>-us-east1.apps.astra.datastax.com.
astra_db_client (Optional[AstraDB]) – alternative to token+api_endpoint,
you can pass an already-created ‘astrapy.db.AstraDB’ instance.
async_astra_db_client (Optional[AsyncAstraDB]) – alternative to token+api_endpoint,
you can pass an already-created ‘astrapy.db.AsyncAstraDB’ instance.
namespace (Optional[str]) – namespace (aka keyspace) where the
collection is created. Defaults to the database’s “default namespace”.
setup_mode (AstraSetupMode) – 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 (Optional[str]) – 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.
async aclear(**kwargs: Any) → None[source]¶
Clear cache that can take additional keyword arguments.
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
with that ID. This is for the second step.
Parameters
document_id (str) – 
Return type
None
async alookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][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
Optional[Sequence[Generation]]
async alookup_with_id(prompt: str, llm_string: str) → Optional[Tuple[str, Sequence[Generation]]][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
Optional[Tuple[str, Sequence[Generation]]]
async alookup_with_id_through_llm(prompt: str, llm: LLM, stop: Optional[List[str]] = None) → Optional[Tuple[str, Sequence[Generation]]][source]¶
Parameters
prompt (str) – 
llm (LLM) –
Parameters
prompt (str) – 
llm (LLM) – 
stop (Optional[List[str]]) – 
Return type
Optional[Tuple[str, Sequence[Generation]]]
async aupdate(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 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]¶
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) → Optional[Sequence[Generation]][source]¶
Look up based on prompt and llm_string.
A cache implementation is expected to generate a key from the 2-tuple
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
Optional[Sequence[Generation]]
lookup_with_id(prompt: str, llm_string: str) → Optional[Tuple[str, Sequence[Generation]]][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
Optional[Tuple[str, Sequence[Generation]]]
lookup_with_id_through_llm(prompt: str, llm: LLM, stop: Optional[List[str]] = None) → Optional[Tuple[str, Sequence[Generation]]][source]¶
Parameters
prompt (str) – 
llm (LLM) – 
stop (Optional[List[str]]) – 
Return type
Optional[Tuple[str, Sequence[Generation]]]
update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶
Update cache based on prompt and llm_string.
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
langchain_community.cache.RedisCache¶
class langchain_community.cache.RedisCache(redis_: Any, *, ttl: Optional[int] = None)[source]¶
Cache that uses Redis as a backend. Allows to use a sync redis.Redis client.
Initialize an instance of RedisCache.
This method initializes an object with Redis caching capabilities.
It takes a redis_ parameter, which should be an instance of a Redis
client class (redis.Redis), allowing the object
to interact with a Redis server for caching purposes.
Parameters
redis (Any) – An instance of a Redis client class
(redis.Redis) to be used for caching.
This allows the object to communicate with a
Redis server for caching operations.
ttl (int, optional) – Time-to-live (TTL) for cached items in seconds.
If provided, it sets the time duration for how long cached
items will remain valid. If not provided, cached items will not
have an automatic expiration.
redis_ (Any) – 
Methods
__init__(redis_, *[, ttl])
Initialize an instance of RedisCache.
aclear(**kwargs)
Clear cache that can take additional keyword arguments.
alookup(prompt, llm_string)
Look up based on prompt and llm_string.
aupdate(prompt, llm_string, return_val)
Update cache based on prompt and llm_string.
clear(**kwargs)
Clear cache.
lookup(prompt, llm_string)
Look up based on prompt and llm_string.
update(prompt, llm_string, return_val)
Update cache based on prompt and llm_string.
__init__(redis_: Any, *, ttl: Optional[int] = None)[source]¶
Initialize an instance of RedisCache.
This method initializes an object with Redis caching capabilities.
Initialize an instance of RedisCache.
This method initializes an object with Redis caching capabilities.
It takes a redis_ parameter, which should be an instance of a Redis
client class (redis.Redis), allowing the object
to interact with a Redis server for caching purposes.
Parameters
redis (Any) – An instance of a Redis client class
(redis.Redis) to be used for caching.
This allows the object to communicate with a
Redis server for caching operations.
ttl (int, optional) – Time-to-live (TTL) for cached items in seconds.
If provided, it sets the time duration for how long cached
items will remain valid. If not provided, cached items will not
have an automatic expiration.
redis_ (Any) – 
async aclear(**kwargs: Any) → None¶
Clear cache that can take additional keyword arguments.
Parameters
kwargs (Any) – 
Return type
None
async alookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]]¶
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).
The cached value is a list of Generations (or subclasses).
Return type
Optional[Sequence[Generation]]
async aupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None¶
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. If asynchronous is True, flush asynchronously.
Parameters
kwargs (Any) – 
Return type
None
lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶
Look up based on prompt and llm_string.
Parameters
prompt (str) – 
llm_string (str) – 
Return type
Optional[Sequence[Generation]]
update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶
Update cache based on prompt and llm_string.
Parameters
prompt (str) – 
llm_string (str) – 
return_val (Sequence[Generation]) – 
Return type
None
Examples using RedisCache¶
Model caches
Redis
langchain_community.cache.AzureCosmosDBSemanticCache¶
class langchain_community.cache.AzureCosmosDBSemanticCache(cosmosdb_connection_string: str, database_name: str, collection_name: str, embedding: Embeddings, *, cosmosdb_client: Optional[Any] = None, num_lists: int = 100, similarity: CosmosDBSimilarityType = CosmosDBSimilarityType.COS, kind: CosmosDBVectorSearchType = CosmosDBVectorSearchType.VECTOR_IVF, dimensions: int = 1536, m: int = 16, ef_construction: int = 64, ef_search: int = 40, score_threshold: Optional[float] = None, application_name: str = 'LANGCHAIN_CACHING_PYTHON')[source]¶
Cache that uses Cosmos DB Mongo vCore vector-store backend
Parameters
cosmosdb_connection_string (str) – Cosmos DB Mongo vCore connection string
cosmosdb_client (Optional[Any]) – Cosmos DB Mongo vCore client
embedding (Embedding) – Embedding provider for semantic encoding and search.
database_name (str) – Database name for the CosmosDBMongoVCoreSemanticCache
collection_name (str) – Collection name for the CosmosDBMongoVCoreSemanticCache
num_lists (int) – This integer is the number of clusters that the
inverted file (IVF) index uses to group the vector data.
We recommend that numLists is set to documentCount/1000
for up to 1 million documents and to sqrt(documentCount)
for more than 1 million documents.
Using a numLists value of 1 is akin to performing
brute-force search, which has limited performance
dimensions (int) – Number of dimensions for vector similarity.
The maximum number of supported dimensions is 2000
similarity (CosmosDBSimilarityType) – Similarity metric to use with the IVF index.
Possible options are:
Possible options are:
CosmosDBSimilarityType.COS (cosine distance),
CosmosDBSimilarityType.L2 (Euclidean distance), and
CosmosDBSimilarityType.IP (inner product).
kind (CosmosDBVectorSearchType) – Type of vector index to create.
Possible options are:
vector-ivf
vector-hnsw: available as a preview feature only,to enable visit https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/preview-features
m (int) – The max number of connections per layer (16 by default, minimum
value is 2, maximum value is 100). Higher m is suitable for datasets
with high dimensionality and/or high accuracy requirements.
ef_construction (int) – the size of the dynamic candidate list for constructing
the graph (64 by default, minimum value is 4, maximum
value is 1000). Higher ef_construction will result in
better index quality and higher accuracy, but it will
also increase the time required to build the index.
ef_construction has to be at least 2 * m
ef_search (int) – The size of the dynamic candidate list for search
(40 by default). A higher value provides better
recall at the cost of speed.
score_threshold (Optional[float]) – Maximum score used to filter the vector search documents.
application_name (str) – Application name for the client for tracking and logging
Attributes
DEFAULT_COLLECTION_NAME
DEFAULT_DATABASE_NAME
Methods
__init__(cosmosdb_connection_string, ...[, ...])
param cosmosdb_connection_string
Cosmos DB Mongo vCore connection string
aclear(**kwargs)
Clear cache that can take additional keyword arguments.
alookup(prompt, llm_string)
Look up based on prompt and llm_string.
Look up based on prompt and llm_string.
aupdate(prompt, llm_string, return_val)
Update cache based on prompt and llm_string.
clear(**kwargs)
Clear semantic cache for a given llm_string.
lookup(prompt, llm_string)
Look up based on prompt and llm_string.
update(prompt, llm_string, return_val)
Update cache based on prompt and llm_string.
__init__(cosmosdb_connection_string: str, database_name: str, collection_name: str, embedding: Embeddings, *, cosmosdb_client: Optional[Any] = None, num_lists: int = 100, similarity: CosmosDBSimilarityType = CosmosDBSimilarityType.COS, kind: CosmosDBVectorSearchType = CosmosDBVectorSearchType.VECTOR_IVF, dimensions: int = 1536, m: int = 16, ef_construction: int = 64, ef_search: int = 40, score_threshold: Optional[float] = None, application_name: str = 'LANGCHAIN_CACHING_PYTHON')[source]¶
Parameters
cosmosdb_connection_string (str) – Cosmos DB Mongo vCore connection string
cosmosdb_client (Optional[Any]) – Cosmos DB Mongo vCore client
embedding (Embedding) – Embedding provider for semantic encoding and search.
database_name (str) – Database name for the CosmosDBMongoVCoreSemanticCache
collection_name (str) – Collection name for the CosmosDBMongoVCoreSemanticCache
num_lists (int) – This integer is the number of clusters that the
inverted file (IVF) index uses to group the vector data.
We recommend that numLists is set to documentCount/1000
for up to 1 million documents and to sqrt(documentCount)
for more than 1 million documents.
for more than 1 million documents.
Using a numLists value of 1 is akin to performing
brute-force search, which has limited performance
dimensions (int) – Number of dimensions for vector similarity.
The maximum number of supported dimensions is 2000
similarity (CosmosDBSimilarityType) – Similarity metric to use with the IVF index.
Possible options are:
CosmosDBSimilarityType.COS (cosine distance),
CosmosDBSimilarityType.L2 (Euclidean distance), and
CosmosDBSimilarityType.IP (inner product).
kind (CosmosDBVectorSearchType) – Type of vector index to create.
Possible options are:
vector-ivf
vector-hnsw: available as a preview feature only,to enable visit https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/preview-features
m (int) – The max number of connections per layer (16 by default, minimum
value is 2, maximum value is 100). Higher m is suitable for datasets
with high dimensionality and/or high accuracy requirements.
ef_construction (int) – the size of the dynamic candidate list for constructing
the graph (64 by default, minimum value is 4, maximum
value is 1000). Higher ef_construction will result in
better index quality and higher accuracy, but it will
also increase the time required to build the index.
ef_construction has to be at least 2 * m
ef_search (int) – The size of the dynamic candidate list for search
(40 by default). A higher value provides better
recall at the cost of speed.
score_threshold (Optional[float]) – Maximum score used to filter the vector search documents.
application_name (str) – Application name for the client for tracking and logging
async aclear(**kwargs: Any) → None¶
async aclear(**kwargs: Any) → None¶
Clear cache that can take additional keyword arguments.
Parameters
kwargs (Any) – 
Return type
None
async alookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]]¶
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
Optional[Sequence[Generation]]
async aupdate(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None¶
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
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 semantic cache for a given llm_string.
Parameters
kwargs (Any) – 
Return type
None
lookup(prompt: str, llm_string: str) → Optional[Sequence[Generation]][source]¶
Look up based on prompt and llm_string.
Parameters
prompt (str) – 
llm_string (str) – 
Return type
Optional[Sequence[Generation]]
update(prompt: str, llm_string: str, return_val: Sequence[Generation]) → None[source]¶
Update cache based on prompt and llm_string.
Parameters
prompt (str) – 
llm_string (str) – 
return_val (Sequence[Generation]) – 
Return type
None
Examples using AzureCosmosDBSemanticCache¶
Model caches