2024-01-18 21:39:12 +08:00
|
|
|
import base64
|
2023-06-25 16:49:14 +08:00
|
|
|
import logging
|
2024-01-19 21:37:54 +08:00
|
|
|
from typing import List, Optional, cast
|
2023-06-25 16:49:14 +08:00
|
|
|
|
2023-08-23 19:10:11 +08:00
|
|
|
import numpy as np
|
2024-02-06 13:21:13 +08:00
|
|
|
from langchain.embeddings.base import Embeddings
|
|
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
|
2024-01-02 23:42:00 +08:00
|
|
|
from core.model_manager import ModelInstance
|
2024-01-19 21:37:54 +08:00
|
|
|
from core.model_runtime.entities.model_entities import ModelPropertyKey
|
|
|
|
from core.model_runtime.model_providers.__base.text_embedding_model import TextEmbeddingModel
|
2023-06-25 16:49:14 +08:00
|
|
|
from extensions.ext_database import db
|
2024-01-18 21:39:12 +08:00
|
|
|
from extensions.ext_redis import redis_client
|
2023-06-25 16:49:14 +08:00
|
|
|
from libs import helper
|
|
|
|
|
2024-01-02 23:42:00 +08:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2023-06-25 16:49:14 +08:00
|
|
|
|
|
|
|
class CacheEmbedding(Embeddings):
|
2024-01-02 23:42:00 +08:00
|
|
|
def __init__(self, model_instance: ModelInstance, user: Optional[str] = None) -> None:
|
|
|
|
self._model_instance = model_instance
|
|
|
|
self._user = user
|
2023-06-25 16:49:14 +08:00
|
|
|
|
|
|
|
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
2024-01-19 21:37:54 +08:00
|
|
|
"""Embed search docs in batches of 10."""
|
|
|
|
text_embeddings = []
|
|
|
|
try:
|
|
|
|
model_type_instance = cast(TextEmbeddingModel, self._model_instance.model_type_instance)
|
|
|
|
model_schema = model_type_instance.get_model_schema(self._model_instance.model, self._model_instance.credentials)
|
|
|
|
max_chunks = model_schema.model_properties[ModelPropertyKey.MAX_CHUNKS] \
|
|
|
|
if model_schema and ModelPropertyKey.MAX_CHUNKS in model_schema.model_properties else 1
|
|
|
|
for i in range(0, len(texts), max_chunks):
|
|
|
|
batch_texts = texts[i:i + max_chunks]
|
|
|
|
|
2024-01-02 23:42:00 +08:00
|
|
|
embedding_result = self._model_instance.invoke_text_embedding(
|
2024-01-19 21:37:54 +08:00
|
|
|
texts=batch_texts,
|
2024-01-02 23:42:00 +08:00
|
|
|
user=self._user
|
|
|
|
)
|
|
|
|
|
2024-01-19 21:37:54 +08:00
|
|
|
for vector in embedding_result.embeddings:
|
|
|
|
try:
|
|
|
|
normalized_embedding = (vector / np.linalg.norm(vector)).tolist()
|
|
|
|
text_embeddings.append(normalized_embedding)
|
|
|
|
except IntegrityError:
|
|
|
|
db.session.rollback()
|
|
|
|
except Exception as e:
|
|
|
|
logging.exception('Failed to add embedding to redis')
|
|
|
|
|
|
|
|
except Exception as ex:
|
|
|
|
logger.error('Failed to embed documents: ', ex)
|
|
|
|
raise ex
|
2023-06-25 16:49:14 +08:00
|
|
|
|
|
|
|
return text_embeddings
|
|
|
|
|
|
|
|
def embed_query(self, text: str) -> List[float]:
|
|
|
|
"""Embed query text."""
|
|
|
|
# use doc embedding cache or store if not exists
|
|
|
|
hash = helper.generate_text_hash(text)
|
2024-01-18 21:39:12 +08:00
|
|
|
embedding_cache_key = f'{self._model_instance.provider}_{self._model_instance.model}_{hash}'
|
|
|
|
embedding = redis_client.get(embedding_cache_key)
|
2023-06-25 16:49:14 +08:00
|
|
|
if embedding:
|
2024-01-19 21:37:54 +08:00
|
|
|
redis_client.expire(embedding_cache_key, 600)
|
2024-01-18 21:39:12 +08:00
|
|
|
return list(np.frombuffer(base64.b64decode(embedding), dtype="float"))
|
|
|
|
|
2023-06-25 16:49:14 +08:00
|
|
|
|
2023-08-12 00:57:00 +08:00
|
|
|
try:
|
2024-01-02 23:42:00 +08:00
|
|
|
embedding_result = self._model_instance.invoke_text_embedding(
|
|
|
|
texts=[text],
|
|
|
|
user=self._user
|
|
|
|
)
|
|
|
|
|
|
|
|
embedding_results = embedding_result.embeddings[0]
|
2023-08-23 19:10:11 +08:00
|
|
|
embedding_results = (embedding_results / np.linalg.norm(embedding_results)).tolist()
|
2023-08-12 00:57:00 +08:00
|
|
|
except Exception as ex:
|
2024-01-02 23:42:00 +08:00
|
|
|
raise ex
|
2023-06-25 16:49:14 +08:00
|
|
|
|
|
|
|
try:
|
2024-01-18 21:39:12 +08:00
|
|
|
# encode embedding to base64
|
|
|
|
embedding_vector = np.array(embedding_results)
|
|
|
|
vector_bytes = embedding_vector.tobytes()
|
|
|
|
# Transform to Base64
|
|
|
|
encoded_vector = base64.b64encode(vector_bytes)
|
|
|
|
# Transform to string
|
|
|
|
encoded_str = encoded_vector.decode("utf-8")
|
2024-01-19 21:37:54 +08:00
|
|
|
redis_client.setex(embedding_cache_key, 600, encoded_str)
|
2024-01-18 21:39:12 +08:00
|
|
|
|
2023-06-25 16:49:14 +08:00
|
|
|
except IntegrityError:
|
|
|
|
db.session.rollback()
|
|
|
|
except:
|
2024-01-18 21:39:12 +08:00
|
|
|
logging.exception('Failed to add embedding to redis')
|
2023-06-25 16:49:14 +08:00
|
|
|
|
|
|
|
return embedding_results
|