2023-06-25 16:49:14 +08:00
|
|
|
import logging
|
|
|
|
from typing import List
|
|
|
|
|
2023-08-23 19:10:11 +08:00
|
|
|
import numpy as np
|
2023-06-25 16:49:14 +08:00
|
|
|
from langchain.embeddings.base import Embeddings
|
|
|
|
from sqlalchemy.exc import IntegrityError
|
|
|
|
|
2023-08-12 00:57:00 +08:00
|
|
|
from core.model_providers.models.embedding.base import BaseEmbedding
|
2023-06-25 16:49:14 +08:00
|
|
|
from extensions.ext_database import db
|
|
|
|
from libs import helper
|
|
|
|
from models.dataset import Embedding
|
|
|
|
|
|
|
|
|
|
|
|
class CacheEmbedding(Embeddings):
|
2023-08-12 00:57:00 +08:00
|
|
|
def __init__(self, embeddings: BaseEmbedding):
|
2023-06-25 16:49:14 +08:00
|
|
|
self._embeddings = embeddings
|
|
|
|
|
|
|
|
def embed_documents(self, texts: List[str]) -> List[List[float]]:
|
|
|
|
"""Embed search docs."""
|
|
|
|
# use doc embedding cache or store if not exists
|
|
|
|
text_embeddings = []
|
|
|
|
embedding_queue_texts = []
|
|
|
|
for text in texts:
|
|
|
|
hash = helper.generate_text_hash(text)
|
2023-08-12 00:57:00 +08:00
|
|
|
embedding = db.session.query(Embedding).filter_by(model_name=self._embeddings.name, hash=hash).first()
|
2023-06-25 16:49:14 +08:00
|
|
|
if embedding:
|
|
|
|
text_embeddings.append(embedding.get_embedding())
|
|
|
|
else:
|
|
|
|
embedding_queue_texts.append(text)
|
|
|
|
|
2023-08-12 00:57:00 +08:00
|
|
|
if embedding_queue_texts:
|
|
|
|
try:
|
|
|
|
embedding_results = self._embeddings.client.embed_documents(embedding_queue_texts)
|
|
|
|
except Exception as ex:
|
|
|
|
raise self._embeddings.handle_exceptions(ex)
|
|
|
|
i = 0
|
2023-08-23 19:10:11 +08:00
|
|
|
normalized_embedding_results = []
|
2023-08-12 00:57:00 +08:00
|
|
|
for text in embedding_queue_texts:
|
|
|
|
hash = helper.generate_text_hash(text)
|
2023-06-25 16:49:14 +08:00
|
|
|
|
2023-08-12 00:57:00 +08:00
|
|
|
try:
|
|
|
|
embedding = Embedding(model_name=self._embeddings.name, hash=hash)
|
2023-08-23 19:10:11 +08:00
|
|
|
vector = embedding_results[i]
|
|
|
|
normalized_embedding = (vector / np.linalg.norm(vector)).tolist()
|
|
|
|
normalized_embedding_results.append(normalized_embedding)
|
|
|
|
embedding.set_embedding(normalized_embedding)
|
2023-08-12 00:57:00 +08:00
|
|
|
db.session.add(embedding)
|
|
|
|
db.session.commit()
|
|
|
|
except IntegrityError:
|
|
|
|
db.session.rollback()
|
|
|
|
continue
|
|
|
|
except:
|
|
|
|
logging.exception('Failed to add embedding to db')
|
|
|
|
continue
|
|
|
|
finally:
|
|
|
|
i += 1
|
2023-06-25 16:49:14 +08:00
|
|
|
|
2023-08-23 19:10:11 +08:00
|
|
|
text_embeddings.extend(normalized_embedding_results)
|
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)
|
2023-08-12 00:57:00 +08:00
|
|
|
embedding = db.session.query(Embedding).filter_by(model_name=self._embeddings.name, hash=hash).first()
|
2023-06-25 16:49:14 +08:00
|
|
|
if embedding:
|
|
|
|
return embedding.get_embedding()
|
|
|
|
|
2023-08-12 00:57:00 +08:00
|
|
|
try:
|
|
|
|
embedding_results = self._embeddings.client.embed_query(text)
|
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:
|
|
|
|
raise self._embeddings.handle_exceptions(ex)
|
2023-06-25 16:49:14 +08:00
|
|
|
|
|
|
|
try:
|
2023-08-12 00:57:00 +08:00
|
|
|
embedding = Embedding(model_name=self._embeddings.name, hash=hash)
|
2023-06-25 16:49:14 +08:00
|
|
|
embedding.set_embedding(embedding_results)
|
|
|
|
db.session.add(embedding)
|
|
|
|
db.session.commit()
|
|
|
|
except IntegrityError:
|
|
|
|
db.session.rollback()
|
|
|
|
except:
|
|
|
|
logging.exception('Failed to add embedding to db')
|
|
|
|
|
|
|
|
return embedding_results
|
2023-08-12 00:57:00 +08:00
|
|
|
|