Importante
Uma camada de armazenamento em cache para LLMs que exploram o Elasticsearch, totalmente compatíveis com o cache de Langchain, tanto para os modelos de bate -papo quanto de incorporação.
pip install llm-elasticsearch-cacheO cache Langchain pode ser usado de maneira semelhante às outras integrações do cache.
from langchain . globals import set_llm_cache
from llmescache . langchain import ElasticsearchCache
from elasticsearch import Elasticsearch
es_client = Elasticsearch ( hosts = "http://localhost:9200" )
set_llm_cache (
ElasticsearchCache (
es_client = es_client ,
es_index = "llm-chat-cache" ,
metadata = { "project" : "my_chatgpt_project" }
)
) O parâmetro es_index também pode levar aliases. Isso permite usar o ILM: gerencie o ciclo de vida do índice que sugerimos considerar para gerenciar a retenção e controlar o crescimento do cache.
Veja a classe Docstring para todos os parâmetros.
Os dados em cache não serão pesquisáveis por padrão. O desenvolvedor pode personalizar a construção do documento Elasticsearch para adicionar campos de texto indexados, onde colocar, por exemplo, o texto gerado pelo LLM.
Isso pode ser feito subclassificando métodos de substituição final. A nova classe de cache pode ser aplicada também a um índice de cache pré-existente:
from llmescache . langchain import ElasticsearchCache
from elasticsearch import Elasticsearch
from langchain_core . caches import RETURN_VAL_TYPE
from typing import Any , Dict , List
from langchain . globals import set_llm_cache
import json
class SearchableElasticsearchCache ( ElasticsearchCache ):
@ property
def mapping ( self ) -> Dict [ str , Any ]:
mapping = super (). mapping
mapping [ "mappings" ][ "properties" ][ "parsed_llm_output" ] = { "type" : "text" , "analyzer" : "english" }
return mapping
def build_document ( self , prompt : str , llm_string : str , return_val : RETURN_VAL_TYPE ) -> Dict [ str , Any ]:
body = super (). build_document ( prompt , llm_string , return_val )
body [ "parsed_llm_output" ] = self . _parse_output ( body [ "llm_output" ])
return body
@ staticmethod
def _parse_output ( data : List [ str ]) -> List [ str ]:
return [ json . loads ( output )[ "kwargs" ][ "message" ][ "kwargs" ][ "content" ] for output in data ]
es_client = Elasticsearch ( hosts = "http://localhost:9200" )
set_llm_cache ( SearchableElasticsearchCache ( es_client = es_client , es_index = "llm-chat-cache" ))O cache de incorporação é obtido usando o Cachebackedembeddings, de uma maneira ligeiramente diferente da documentação oficial.
from llmescache . langchain import ElasticsearchStore
from elasticsearch import Elasticsearch
from langchain . embeddings import CacheBackedEmbeddings
from langchain_openai import OpenAIEmbeddings
es_client = Elasticsearch ( hosts = "http://localhost:9200" )
underlying_embeddings = OpenAIEmbeddings ( model = "text-embedding-3-small" )
store = ElasticsearchStore (
es_client = es_client ,
es_index = "llm-embeddings-cache" ,
namespace = underlying_embeddings . model ,
metadata = { "project" : "my_llm_project" }
)
cached_embeddings = CacheBackedEmbeddings (
underlying_embeddings ,
store
) Da mesma forma que o cache de bate -papo, pode -se subclasse ElasticsearchStore para indexar vetores para pesquisa.
from llmescache . langchain import ElasticsearchStore
from typing import Any , Dict , List
class SearchableElasticsearchStore ( ElasticsearchStore ):
@ property
def mapping ( self ) -> Dict [ str , Any ]:
mapping = super (). mapping
mapping [ "mappings" ][ "properties" ][ "vector" ] = { "type" : "dense_vector" , "dims" : 1536 , "index" : True , "similarity" : "dot_product" }
return mapping
def build_document ( self , llm_input : str , vector : List [ float ]) -> Dict [ str , Any ]:
body = super (). build_document ( llm_input , vector )
body [ "vector" ] = vector
return body Esteja ciente de que atualmente não suporta consultas de cache, isso significa que as consultas de texto, para pesquisas CacheBackedEmbeddings vetores, não serão armazenadas em cache. No entanto, ao substituir o método embed_query , é possível implementá -lo facilmente.