2023-09-05 20:42:22 +08:00
|
|
|
from .vector_base import VectorBase
|
|
|
|
|
from ..object import ObjectID
|
|
|
|
|
import chromadb
|
|
|
|
|
import logging
|
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ChromaVectorStore(VectorBase):
|
2023-09-21 18:32:17 +08:00
|
|
|
def __init__(self, root_dir, model_name: str) -> None:
|
2023-09-12 15:28:59 +08:00
|
|
|
super().__init__(model_name)
|
2023-09-05 20:42:22 +08:00
|
|
|
|
|
|
|
|
logging.info(
|
2023-09-12 15:28:59 +08:00
|
|
|
"will init chroma vector store, model={}".format(model_name)
|
2023-09-05 20:42:22 +08:00
|
|
|
)
|
|
|
|
|
|
2023-09-21 18:32:17 +08:00
|
|
|
directory = os.path.join(root_dir, "vector")
|
2023-09-05 20:42:22 +08:00
|
|
|
logging.info("will use vector store: {}".format(directory))
|
|
|
|
|
|
|
|
|
|
client = chromadb.PersistentClient(
|
|
|
|
|
path=directory, settings=chromadb.Settings(anonymized_telemetry=False)
|
|
|
|
|
)
|
|
|
|
|
# client = chromadb.Client()
|
|
|
|
|
|
|
|
|
|
collection_name = "coll_{}".format(model_name)
|
|
|
|
|
logging.info("will init chroma colletion: %s", collection_name)
|
|
|
|
|
|
|
|
|
|
collection = client.get_or_create_collection(collection_name)
|
|
|
|
|
self.collection = collection
|
|
|
|
|
|
|
|
|
|
async def insert(self, vector: [float], id: ObjectID):
|
2023-09-28 14:03:52 -07:00
|
|
|
logging.info(f"will insert vector: {len(vector)} id: {str(id)}")
|
|
|
|
|
logging.debug(f"vector is {vector}")
|
2023-09-05 20:42:22 +08:00
|
|
|
self.collection.add(
|
|
|
|
|
embeddings=vector,
|
2023-09-18 11:28:21 +08:00
|
|
|
ids=str(id),
|
2023-09-05 20:42:22 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
async def query(self, vector: [float], top_k: int) -> [ObjectID]:
|
|
|
|
|
ret = self.collection.query(
|
|
|
|
|
query_embeddings=vector,
|
|
|
|
|
n_results=top_k,
|
|
|
|
|
)
|
2023-09-18 11:28:21 +08:00
|
|
|
logging.info(f"query result {ret}")
|
|
|
|
|
if len(ret['ids']) == 0:
|
|
|
|
|
return []
|
|
|
|
|
return list(map(ObjectID.from_base58, ret["ids"][0]))
|
2023-09-05 20:42:22 +08:00
|
|
|
|
|
|
|
|
async def delete(self, id: ObjectID):
|
|
|
|
|
self.collection.delete(
|
|
|
|
|
ids=id,
|
|
|
|
|
)
|