|
| 1 | +# !/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# |
| 4 | +# Copyright (c) 2023 Intel Corporation |
| 5 | +# |
| 6 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | +# you may not use this file except in compliance with the License. |
| 8 | +# You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, software |
| 13 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | +# See the License for the specific language governing permissions and |
| 16 | +# limitations under the License. |
| 17 | + |
| 18 | +"""The wrapper for Chroma retriever based on langchain""" |
| 19 | +from __future__ import annotations |
| 20 | +import base64 |
| 21 | +import logging, os |
| 22 | +import uuid |
| 23 | +from typing import ( |
| 24 | + TYPE_CHECKING, |
| 25 | + Any, |
| 26 | + Callable, |
| 27 | + Dict, |
| 28 | + Iterable, |
| 29 | + List, |
| 30 | + Optional, |
| 31 | + Tuple, |
| 32 | + Type, |
| 33 | +) |
| 34 | +import numpy as np |
| 35 | +from langchain_core.documents import Document |
| 36 | +from langchain.vectorstores.chroma import Chroma as Chroma_origin |
| 37 | +from langchain_core.embeddings import Embeddings |
| 38 | +from langchain_core.utils import xor_args |
| 39 | +from langchain_core.vectorstores import VectorStore |
| 40 | +import chromadb |
| 41 | +import chromadb.config |
| 42 | +_DEFAULT_PERSIST_DIR = './output' |
| 43 | +_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain" |
| 44 | +logging.basicConfig( |
| 45 | + format="%(asctime)s %(name)s:%(levelname)s:%(message)s", |
| 46 | + datefmt="%d-%M-%Y %H:%M:%S", |
| 47 | + level=logging.INFO |
| 48 | +) |
| 49 | + |
| 50 | + |
| 51 | +class Chroma(Chroma_origin): |
| 52 | + def __init__(self, **kwargs): |
| 53 | + super().__init__(**kwargs) |
| 54 | + |
| 55 | + @classmethod |
| 56 | + def from_texts( |
| 57 | + cls: Type[Chroma], |
| 58 | + texts: List[str], |
| 59 | + embedding: Optional[Embeddings] = None, |
| 60 | + metadatas: Optional[List[dict]] = None, |
| 61 | + ids: Optional[List[str]] = None, |
| 62 | + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, |
| 63 | + persist_directory: Optional[str] = None, |
| 64 | + client_settings: Optional[chromadb.config.Settings] = None, |
| 65 | + client: Optional[chromadb.Client] = None, |
| 66 | + collection_metadata: Optional[Dict] = None, |
| 67 | + **kwargs: Any, |
| 68 | + ) -> Chroma: |
| 69 | + """Create a Chroma vectorstore from a raw documents. |
| 70 | +
|
| 71 | + If a persist_directory is specified, the collection will be persisted there. |
| 72 | + Otherwise, the data will be ephemeral in-memory. |
| 73 | +
|
| 74 | + Args: |
| 75 | + texts (List[str]): List of texts to add to the collection. |
| 76 | + collection_name (str): Name of the collection to create. |
| 77 | + persist_directory (Optional[str]): Directory to persist the collection. |
| 78 | + embedding (Optional[Embeddings]): Embedding function. Defaults to None. |
| 79 | + metadatas (Optional[List[dict]]): List of metadatas. Defaults to None. |
| 80 | + ids (Optional[List[str]]): List of document IDs. Defaults to None. |
| 81 | + client_settings (Optional[chromadb.config.Settings]): Chroma client settings |
| 82 | + collection_metadata (Optional[Dict]): Collection configurations. |
| 83 | + Defaults to None. |
| 84 | +
|
| 85 | + Returns: |
| 86 | + Chroma: Chroma vectorstore. |
| 87 | + """ |
| 88 | + chroma_collection = cls( |
| 89 | + collection_name=collection_name, |
| 90 | + embedding_function=embedding, |
| 91 | + persist_directory=persist_directory, |
| 92 | + client_settings=client_settings, |
| 93 | + client=client, |
| 94 | + collection_metadata=collection_metadata, |
| 95 | + ) |
| 96 | + if ids is None: |
| 97 | + ids = [str(uuid.uuid1()) for _ in texts] |
| 98 | + if hasattr( |
| 99 | + chroma_collection._client, "max_batch_size" |
| 100 | + ): # for Chroma 0.4.10 and above |
| 101 | + from chromadb.utils.batch_utils import create_batches |
| 102 | + |
| 103 | + for batch in create_batches( |
| 104 | + api=chroma_collection._client, |
| 105 | + ids=ids, |
| 106 | + metadatas=metadatas, |
| 107 | + documents=texts, |
| 108 | + ): |
| 109 | + chroma_collection.add_texts( |
| 110 | + texts=batch[3] if batch[3] else [], |
| 111 | + metadatas=batch[2] if batch[2] else None, |
| 112 | + ids=batch[0], |
| 113 | + ) |
| 114 | + else: |
| 115 | + chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids) |
| 116 | + return chroma_collection |
| 117 | + |
| 118 | + @classmethod |
| 119 | + def from_documents( |
| 120 | + cls: Type[Chroma], |
| 121 | + documents: List[Document], |
| 122 | + sign: str = None, |
| 123 | + embedding: Optional[Embeddings] = None, |
| 124 | + ids: Optional[List[str]] = None, |
| 125 | + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, |
| 126 | + persist_directory: Optional[str] = _DEFAULT_PERSIST_DIR, |
| 127 | + client_settings: Optional[chromadb.config.Settings] = None, |
| 128 | + client: Optional[chromadb.Client] = None, # Add this line |
| 129 | + collection_metadata: Optional[Dict] = None, |
| 130 | + **kwargs: Any, |
| 131 | + ) -> Chroma: |
| 132 | + """Create a Chroma vectorstore from a list of documents. |
| 133 | +
|
| 134 | + If a persist_directory is specified, the collection will be persisted there. |
| 135 | + Otherwise, the data will be ephemeral in-memory. |
| 136 | +
|
| 137 | + Args: |
| 138 | + collection_name (str): Name of the collection to create. |
| 139 | + persist_directory (Optional[str]): Directory to persist the collection. |
| 140 | + ids (Optional[List[str]]): List of document IDs. Defaults to None. |
| 141 | + documents (List[Document]): List of documents to add to the vectorstore. |
| 142 | + embedding (Optional[Embeddings]): Embedding function. Defaults to None. |
| 143 | + client_settings (Optional[chromadb.config.Settings]): Chroma client settings |
| 144 | + collection_metadata (Optional[Dict]): Collection configurations. |
| 145 | + Defaults to None. |
| 146 | +
|
| 147 | + Returns: |
| 148 | + Chroma: Chroma vectorstore. |
| 149 | + """ |
| 150 | + texts = [doc.page_content for doc in documents] |
| 151 | + metadatas = [doc.metadata for doc in documents] |
| 152 | + if 'doc_id' in metadatas[0]: |
| 153 | + ids = [doc.metadata['doc_id'] for doc in documents] |
| 154 | + if sign == 'child': |
| 155 | + persist_directory = persist_directory + "_child" |
| 156 | + return cls.from_texts( |
| 157 | + texts=texts, |
| 158 | + embedding=embedding, |
| 159 | + metadatas=metadatas, |
| 160 | + ids=ids, |
| 161 | + collection_name=collection_name, |
| 162 | + persist_directory=persist_directory, |
| 163 | + client_settings=client_settings, |
| 164 | + client=client, |
| 165 | + collection_metadata=collection_metadata, |
| 166 | + **kwargs, |
| 167 | + ) |
| 168 | + |
| 169 | + |
| 170 | + @classmethod |
| 171 | + def build( |
| 172 | + cls: Type[Chroma], |
| 173 | + documents: List[Document], |
| 174 | + sign: Optional[str] = None, |
| 175 | + embedding: Optional[Embeddings] = None, |
| 176 | + metadatas: Optional[List[dict]] = None, |
| 177 | + ids: Optional[List[str]] = None, |
| 178 | + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, |
| 179 | + persist_directory: Optional[str] = None, |
| 180 | + client_settings: Optional[chromadb.config.Settings] = None, |
| 181 | + client: Optional[chromadb.Client] = None, |
| 182 | + collection_metadata: Optional[Dict] = None, |
| 183 | + **kwargs: Any, |
| 184 | + ) -> Chroma: |
| 185 | + if not persist_directory: |
| 186 | + persist_directory = _DEFAULT_PERSIST_DIR |
| 187 | + if sign == "child": |
| 188 | + persist_directory = persist_directory + "_child" |
| 189 | + if os.path.exists(persist_directory): |
| 190 | + if bool(os.listdir(persist_directory)): |
| 191 | + logging.info("Load the existing database!") |
| 192 | + chroma_collection = cls( |
| 193 | + collection_name=collection_name, |
| 194 | + embedding_function=embedding, |
| 195 | + persist_directory=persist_directory, |
| 196 | + client_settings=client_settings, |
| 197 | + client=client, |
| 198 | + collection_metadata=collection_metadata, |
| 199 | + **kwargs, |
| 200 | + ) |
| 201 | + return chroma_collection |
| 202 | + else: |
| 203 | + logging.info("Create a new knowledge base...") |
| 204 | + chroma_collection = cls.from_documents( |
| 205 | + documents=documents, |
| 206 | + embedding=embedding, |
| 207 | + ids=ids, |
| 208 | + collection_name=collection_name, |
| 209 | + persist_directory=persist_directory, |
| 210 | + client_settings=client_settings, |
| 211 | + client=client, |
| 212 | + collection_metadata=collection_metadata, |
| 213 | + **kwargs, |
| 214 | + ) |
| 215 | + return chroma_collection |
| 216 | + |
| 217 | + |
| 218 | + @classmethod |
| 219 | + def reload( |
| 220 | + cls: Type[Chroma], |
| 221 | + collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME, |
| 222 | + embedding: Optional[Embeddings] = None, |
| 223 | + persist_directory: Optional[str] = None, |
| 224 | + client_settings: Optional[chromadb.config.Settings] = None, |
| 225 | + collection_metadata: Optional[Dict] = None, |
| 226 | + client: Optional[chromadb.Client] = None, |
| 227 | + relevance_score_fn: Optional[Callable[[float], float]] = None, |
| 228 | + ) -> Chroma: |
| 229 | + |
| 230 | + if not persist_directory: |
| 231 | + persist_directory = _DEFAULT_PERSIST_DIR |
| 232 | + chroma_collection = cls( |
| 233 | + collection_name=collection_name, |
| 234 | + embedding_function=embedding, |
| 235 | + persist_directory=persist_directory, |
| 236 | + client_settings=client_settings, |
| 237 | + client=client, |
| 238 | + collection_metadata=collection_metadata, |
| 239 | + ) |
| 240 | + return chroma_collection |
| 241 | + |
0 commit comments