|
| 1 | +from typing import List, Optional, Tuple, Union |
| 2 | +import numpy as np |
| 3 | + |
| 4 | +from gptcache.utils import import_weaviate |
| 5 | +from gptcache.utils.log import gptcache_log |
| 6 | +from gptcache.manager.vector_data.base import VectorBase, VectorData |
| 7 | + |
| 8 | +import_weaviate() |
| 9 | + |
| 10 | +from weaviate import Client |
| 11 | +from weaviate.auth import AuthCredentials |
| 12 | +from weaviate.config import Config |
| 13 | +from weaviate.embedded import EmbeddedOptions |
| 14 | +from weaviate.types import NUMBERS |
| 15 | + |
| 16 | + |
| 17 | +class Weaviate(VectorBase): |
| 18 | + """ |
| 19 | + vector store: Weaviate |
| 20 | + """ |
| 21 | + |
| 22 | + TIMEOUT_TYPE = Union[Tuple[NUMBERS, NUMBERS], NUMBERS] |
| 23 | + |
| 24 | + def __init__( |
| 25 | + self, |
| 26 | + url: Optional[str] = None, |
| 27 | + auth_client_secret: Optional[AuthCredentials] = None, |
| 28 | + timeout_config: TIMEOUT_TYPE = (10, 60), |
| 29 | + proxies: Union[dict, str, None] = None, |
| 30 | + trust_env: bool = False, |
| 31 | + additional_headers: Optional[dict] = None, |
| 32 | + startup_period: Optional[int] = 5, |
| 33 | + embedded_options: Optional[EmbeddedOptions] = None, |
| 34 | + additional_config: Optional[Config] = None, |
| 35 | + top_k: Optional[int] = 1, |
| 36 | + ) -> None: |
| 37 | + |
| 38 | + if url is None and embedded_options is None: |
| 39 | + embedded_options = EmbeddedOptions() |
| 40 | + |
| 41 | + self.client = Client( |
| 42 | + url=url, |
| 43 | + auth_client_secret=auth_client_secret, |
| 44 | + timeout_config=timeout_config, |
| 45 | + proxies=proxies, |
| 46 | + trust_env=trust_env, |
| 47 | + additional_headers=additional_headers, |
| 48 | + startup_period=startup_period, |
| 49 | + embedded_options=embedded_options, |
| 50 | + additional_config=additional_config, |
| 51 | + ) |
| 52 | + |
| 53 | + self._create_class() |
| 54 | + self.top_k = top_k |
| 55 | + |
| 56 | + def _create_class(self): |
| 57 | + class_schema = self._get_default_class_schema() |
| 58 | + |
| 59 | + self.class_name = class_schema.get("class") |
| 60 | + |
| 61 | + if self.client.schema.exists(self.class_name): |
| 62 | + gptcache_log.warning( |
| 63 | + "The %s collection already exists, and it will be used directly.", |
| 64 | + self.class_name, |
| 65 | + ) |
| 66 | + else: |
| 67 | + self.client.schema.create_class(class_schema) |
| 68 | + |
| 69 | + @staticmethod |
| 70 | + def _get_default_class_schema() -> dict: |
| 71 | + return { |
| 72 | + "class": "GPTCache", |
| 73 | + "description": "LLM response cache", |
| 74 | + "properties": [ |
| 75 | + { |
| 76 | + "name": "data_id", |
| 77 | + "dataType": ["int"], |
| 78 | + "description": "The data-id generated by GPTCache for vectors.", |
| 79 | + } |
| 80 | + ], |
| 81 | + "vectorIndexConfig": {"distance": "cosine"}, |
| 82 | + } |
| 83 | + |
| 84 | + def mul_add(self, datas: List[VectorData]): |
| 85 | + with self.client.batch(batch_size=100, dynamic=True) as batch: |
| 86 | + for data in datas: |
| 87 | + properties = { |
| 88 | + "data_id": data.id, |
| 89 | + } |
| 90 | + |
| 91 | + batch.add_data_object( |
| 92 | + data_object=properties, class_name=self.class_name, vector=data.data |
| 93 | + ) |
| 94 | + |
| 95 | + def search(self, data: np.ndarray, top_k: int = -1): |
| 96 | + if top_k == -1: |
| 97 | + top_k = self.top_k |
| 98 | + |
| 99 | + result = ( |
| 100 | + self.client.query.get(class_name=self.class_name, properties=["data_id"]) |
| 101 | + .with_near_vector(content={"vector": data}) |
| 102 | + .with_additional(["distance"]) |
| 103 | + .with_limit(top_k) |
| 104 | + .do() |
| 105 | + ) |
| 106 | + |
| 107 | + return list( |
| 108 | + map( |
| 109 | + lambda x: (x["_additional"]["distance"], x["data_id"]), |
| 110 | + result["data"]["Get"][self.class_name], |
| 111 | + ) |
| 112 | + ) |
| 113 | + |
| 114 | + def _get_uuids(self, data_ids): |
| 115 | + uuid_list = [] |
| 116 | + |
| 117 | + for data_id in data_ids: |
| 118 | + res = ( |
| 119 | + self.client.query.get( |
| 120 | + class_name=self.class_name, properties=["data_id"] |
| 121 | + ) |
| 122 | + .with_where( |
| 123 | + {"path": ["data_id"], "operator": "Equal", "valueInt": data_id} |
| 124 | + ) |
| 125 | + .with_additional(["id"]) |
| 126 | + .do() |
| 127 | + ) |
| 128 | + |
| 129 | + uuid_list.append( |
| 130 | + res["data"]["Get"][self.class_name][0]["_additional"]["id"] |
| 131 | + ) |
| 132 | + |
| 133 | + return uuid_list |
| 134 | + |
| 135 | + def delete(self, ids): |
| 136 | + uuids = self._get_uuids(ids) |
| 137 | + |
| 138 | + for uuid in uuids: |
| 139 | + self.client.data_object.delete(class_name=self.class_name, uuid=uuid) |
| 140 | + |
| 141 | + def rebuild(self, ids=None): |
| 142 | + return |
| 143 | + |
| 144 | + def flush(self): |
| 145 | + self.client.batch.flush() |
| 146 | + |
| 147 | + def close(self): |
| 148 | + self.flush() |
| 149 | + |
| 150 | + def get_embeddings(self, data_id: int): |
| 151 | + results = ( |
| 152 | + self.client.query.get(class_name=self.class_name, properties=["data_id"]) |
| 153 | + .with_where( |
| 154 | + { |
| 155 | + "path": ["data_id"], |
| 156 | + "operator": "Equal", |
| 157 | + "valueInt": data_id, |
| 158 | + } |
| 159 | + ) |
| 160 | + .with_additional(["vector"]) |
| 161 | + .with_limit(1) |
| 162 | + .do() |
| 163 | + ) |
| 164 | + |
| 165 | + results = results["data"]["Get"][self.class_name] |
| 166 | + |
| 167 | + if len(results) < 1: |
| 168 | + return None |
| 169 | + |
| 170 | + vec_emb = np.asarray(results[0]["_additional"]["vector"], dtype="float32") |
| 171 | + return vec_emb |
| 172 | + |
| 173 | + def update_embeddings(self, data_id: int, emb: np.ndarray): |
| 174 | + self.delete([data_id]) |
| 175 | + |
| 176 | + properties = { |
| 177 | + "data_id": data_id, |
| 178 | + } |
| 179 | + |
| 180 | + self.client.data_object.create( |
| 181 | + data_object=properties, class_name=self.class_name, vector=emb |
| 182 | + ) |
0 commit comments