Spaces:
Running
on
Zero
Running
on
Zero
jedick
commited on
Commit
·
77b89d7
1
Parent(s):
d17d568
Apply fix for ChromaDB ValueError
Browse files- mods/langchain_chroma.py +1402 -0
- prompts.py +2 -2
- retriever.py +3 -1
mods/langchain_chroma.py
ADDED
|
@@ -0,0 +1,1402 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This is the langchain_chroma.vectorstores module.
|
| 2 |
+
|
| 3 |
+
It contains the Chroma class which is a vector store for handling various tasks.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import base64
|
| 9 |
+
import logging
|
| 10 |
+
import uuid
|
| 11 |
+
from collections.abc import Iterable, Sequence
|
| 12 |
+
from typing import (
|
| 13 |
+
TYPE_CHECKING,
|
| 14 |
+
Any,
|
| 15 |
+
Callable,
|
| 16 |
+
Optional,
|
| 17 |
+
Union,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
import chromadb
|
| 21 |
+
import chromadb.config
|
| 22 |
+
import numpy as np
|
| 23 |
+
from chromadb import Settings
|
| 24 |
+
from chromadb.api import CreateCollectionConfiguration
|
| 25 |
+
from langchain_core.documents import Document
|
| 26 |
+
from langchain_core.embeddings import Embeddings
|
| 27 |
+
from langchain_core.utils import xor_args
|
| 28 |
+
from langchain_core.vectorstores import VectorStore
|
| 29 |
+
|
| 30 |
+
if TYPE_CHECKING:
|
| 31 |
+
from chromadb.api.types import Where, WhereDocument
|
| 32 |
+
|
| 33 |
+
logger = logging.getLogger()
|
| 34 |
+
DEFAULT_K = 4 # Number of Documents to return.
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _results_to_docs(results: Any) -> list[Document]:
|
| 38 |
+
return [doc for doc, _ in _results_to_docs_and_scores(results)]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _results_to_docs_and_scores(results: Any) -> list[tuple[Document, float]]:
|
| 42 |
+
return [
|
| 43 |
+
# TODO: Chroma can do batch querying,
|
| 44 |
+
# we shouldn't hard code to the 1st result
|
| 45 |
+
(
|
| 46 |
+
Document(page_content=result[0], metadata=result[1] or {}, id=result[2]),
|
| 47 |
+
result[3],
|
| 48 |
+
)
|
| 49 |
+
for result in zip(
|
| 50 |
+
results["documents"][0],
|
| 51 |
+
results["metadatas"][0],
|
| 52 |
+
results["ids"][0],
|
| 53 |
+
results["distances"][0],
|
| 54 |
+
)
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _results_to_docs_and_vectors(results: Any) -> list[tuple[Document, np.ndarray]]:
|
| 59 |
+
return [
|
| 60 |
+
(Document(page_content=result[0], metadata=result[1] or {}), result[2])
|
| 61 |
+
for result in zip(
|
| 62 |
+
results["documents"][0],
|
| 63 |
+
results["metadatas"][0],
|
| 64 |
+
results["embeddings"][0],
|
| 65 |
+
)
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
Matrix = Union[list[list[float]], list[np.ndarray], np.ndarray]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
|
| 73 |
+
"""Row-wise cosine similarity between two equal-width matrices.
|
| 74 |
+
|
| 75 |
+
Raises:
|
| 76 |
+
ValueError: If the number of columns in X and Y are not the same.
|
| 77 |
+
"""
|
| 78 |
+
if len(X) == 0 or len(Y) == 0:
|
| 79 |
+
return np.array([])
|
| 80 |
+
|
| 81 |
+
X = np.array(X)
|
| 82 |
+
Y = np.array(Y)
|
| 83 |
+
if X.shape[1] != Y.shape[1]:
|
| 84 |
+
msg = (
|
| 85 |
+
"Number of columns in X and Y must be the same. X has shape"
|
| 86 |
+
f"{X.shape} "
|
| 87 |
+
f"and Y has shape {Y.shape}."
|
| 88 |
+
)
|
| 89 |
+
raise ValueError(
|
| 90 |
+
msg,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
X_norm = np.linalg.norm(X, axis=1)
|
| 94 |
+
Y_norm = np.linalg.norm(Y, axis=1)
|
| 95 |
+
# Ignore divide by zero errors run time warnings as those are handled below.
|
| 96 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 97 |
+
similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)
|
| 98 |
+
similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0
|
| 99 |
+
return similarity
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def maximal_marginal_relevance(
|
| 103 |
+
query_embedding: np.ndarray,
|
| 104 |
+
embedding_list: list,
|
| 105 |
+
lambda_mult: float = 0.5,
|
| 106 |
+
k: int = 4,
|
| 107 |
+
) -> list[int]:
|
| 108 |
+
"""Calculate maximal marginal relevance.
|
| 109 |
+
|
| 110 |
+
Args:
|
| 111 |
+
query_embedding: Query embedding.
|
| 112 |
+
embedding_list: List of embeddings to select from.
|
| 113 |
+
lambda_mult: Number between 0 and 1 that determines the degree
|
| 114 |
+
of diversity among the results with 0 corresponding
|
| 115 |
+
to maximum diversity and 1 to minimum diversity.
|
| 116 |
+
Defaults to 0.5.
|
| 117 |
+
k: Number of Documents to return. Defaults to 4.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
List of indices of embeddings selected by maximal marginal relevance.
|
| 121 |
+
"""
|
| 122 |
+
if min(k, len(embedding_list)) <= 0:
|
| 123 |
+
return []
|
| 124 |
+
if query_embedding.ndim == 1:
|
| 125 |
+
query_embedding = np.expand_dims(query_embedding, axis=0)
|
| 126 |
+
similarity_to_query = cosine_similarity(query_embedding, embedding_list)[0]
|
| 127 |
+
most_similar = int(np.argmax(similarity_to_query))
|
| 128 |
+
idxs = [most_similar]
|
| 129 |
+
selected = np.array([embedding_list[most_similar]])
|
| 130 |
+
while len(idxs) < min(k, len(embedding_list)):
|
| 131 |
+
best_score = -np.inf
|
| 132 |
+
idx_to_add = -1
|
| 133 |
+
similarity_to_selected = cosine_similarity(embedding_list, selected)
|
| 134 |
+
for i, query_score in enumerate(similarity_to_query):
|
| 135 |
+
if i in idxs:
|
| 136 |
+
continue
|
| 137 |
+
redundant_score = max(similarity_to_selected[i])
|
| 138 |
+
equation_score = (
|
| 139 |
+
lambda_mult * query_score - (1 - lambda_mult) * redundant_score
|
| 140 |
+
)
|
| 141 |
+
if equation_score > best_score:
|
| 142 |
+
best_score = equation_score
|
| 143 |
+
idx_to_add = i
|
| 144 |
+
idxs.append(idx_to_add)
|
| 145 |
+
selected = np.append(selected, [embedding_list[idx_to_add]], axis=0)
|
| 146 |
+
return idxs
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class Chroma(VectorStore):
|
| 150 |
+
"""Chroma vector store integration.
|
| 151 |
+
|
| 152 |
+
Setup:
|
| 153 |
+
Install ``chromadb``, ``langchain-chroma`` packages:
|
| 154 |
+
|
| 155 |
+
.. code-block:: bash
|
| 156 |
+
|
| 157 |
+
pip install -qU chromadb langchain-chroma
|
| 158 |
+
|
| 159 |
+
Key init args — indexing params:
|
| 160 |
+
collection_name: str
|
| 161 |
+
Name of the collection.
|
| 162 |
+
embedding_function: Embeddings
|
| 163 |
+
Embedding function to use.
|
| 164 |
+
|
| 165 |
+
Key init args — client params:
|
| 166 |
+
client: Optional[Client]
|
| 167 |
+
Chroma client to use.
|
| 168 |
+
client_settings: Optional[chromadb.config.Settings]
|
| 169 |
+
Chroma client settings.
|
| 170 |
+
persist_directory: Optional[str]
|
| 171 |
+
Directory to persist the collection.
|
| 172 |
+
host: Optional[str]
|
| 173 |
+
Hostname of a deployed Chroma server.
|
| 174 |
+
port: Optional[int]
|
| 175 |
+
Connection port for a deployed Chroma server. Default is 8000.
|
| 176 |
+
ssl: Optional[bool]
|
| 177 |
+
Whether to establish an SSL connection with a deployed Chroma server. Default is False.
|
| 178 |
+
headers: Optional[dict[str, str]]
|
| 179 |
+
HTTP headers to send to a deployed Chroma server.
|
| 180 |
+
chroma_cloud_api_key: Optional[str]
|
| 181 |
+
Chroma Cloud API key.
|
| 182 |
+
tenant: Optional[str]
|
| 183 |
+
Tenant ID. Required for Chroma Cloud connections. Default is 'default_tenant' for local Chroma servers.
|
| 184 |
+
database: Optional[str]
|
| 185 |
+
Database name. Required for Chroma Cloud connections. Default is 'default_database'.
|
| 186 |
+
|
| 187 |
+
Instantiate:
|
| 188 |
+
.. code-block:: python
|
| 189 |
+
|
| 190 |
+
from langchain_chroma import Chroma
|
| 191 |
+
from langchain_openai import OpenAIEmbeddings
|
| 192 |
+
|
| 193 |
+
vector_store = Chroma(
|
| 194 |
+
collection_name="foo",
|
| 195 |
+
embedding_function=OpenAIEmbeddings(),
|
| 196 |
+
# other params...
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
Add Documents:
|
| 200 |
+
.. code-block:: python
|
| 201 |
+
|
| 202 |
+
from langchain_core.documents import Document
|
| 203 |
+
|
| 204 |
+
document_1 = Document(page_content="foo", metadata={"baz": "bar"})
|
| 205 |
+
document_2 = Document(page_content="thud", metadata={"bar": "baz"})
|
| 206 |
+
document_3 = Document(page_content="i will be deleted :(")
|
| 207 |
+
|
| 208 |
+
documents = [document_1, document_2, document_3]
|
| 209 |
+
ids = ["1", "2", "3"]
|
| 210 |
+
vector_store.add_documents(documents=documents, ids=ids)
|
| 211 |
+
|
| 212 |
+
Update Documents:
|
| 213 |
+
.. code-block:: python
|
| 214 |
+
|
| 215 |
+
updated_document = Document(
|
| 216 |
+
page_content="qux",
|
| 217 |
+
metadata={"bar": "baz"}
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
vector_store.update_documents(ids=["1"],documents=[updated_document])
|
| 221 |
+
|
| 222 |
+
Delete Documents:
|
| 223 |
+
.. code-block:: python
|
| 224 |
+
|
| 225 |
+
vector_store.delete(ids=["3"])
|
| 226 |
+
|
| 227 |
+
Search:
|
| 228 |
+
.. code-block:: python
|
| 229 |
+
|
| 230 |
+
results = vector_store.similarity_search(query="thud",k=1)
|
| 231 |
+
for doc in results:
|
| 232 |
+
print(f"* {doc.page_content} [{doc.metadata}]")
|
| 233 |
+
|
| 234 |
+
.. code-block:: python
|
| 235 |
+
|
| 236 |
+
* thud [{'baz': 'bar'}]
|
| 237 |
+
|
| 238 |
+
Search with filter:
|
| 239 |
+
.. code-block:: python
|
| 240 |
+
|
| 241 |
+
results = vector_store.similarity_search(query="thud",k=1,filter={"baz": "bar"})
|
| 242 |
+
for doc in results:
|
| 243 |
+
print(f"* {doc.page_content} [{doc.metadata}]")
|
| 244 |
+
|
| 245 |
+
.. code-block:: python
|
| 246 |
+
|
| 247 |
+
* foo [{'baz': 'bar'}]
|
| 248 |
+
|
| 249 |
+
Search with score:
|
| 250 |
+
.. code-block:: python
|
| 251 |
+
|
| 252 |
+
results = vector_store.similarity_search_with_score(query="qux",k=1)
|
| 253 |
+
for doc, score in results:
|
| 254 |
+
print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
|
| 255 |
+
|
| 256 |
+
.. code-block:: python
|
| 257 |
+
|
| 258 |
+
* [SIM=0.000000] qux [{'bar': 'baz', 'baz': 'bar'}]
|
| 259 |
+
|
| 260 |
+
Async:
|
| 261 |
+
.. code-block:: python
|
| 262 |
+
|
| 263 |
+
# add documents
|
| 264 |
+
# await vector_store.aadd_documents(documents=documents, ids=ids)
|
| 265 |
+
|
| 266 |
+
# delete documents
|
| 267 |
+
# await vector_store.adelete(ids=["3"])
|
| 268 |
+
|
| 269 |
+
# search
|
| 270 |
+
# results = vector_store.asimilarity_search(query="thud",k=1)
|
| 271 |
+
|
| 272 |
+
# search with score
|
| 273 |
+
results = await vector_store.asimilarity_search_with_score(query="qux",k=1)
|
| 274 |
+
for doc,score in results:
|
| 275 |
+
print(f"* [SIM={score:3f}] {doc.page_content} [{doc.metadata}]")
|
| 276 |
+
|
| 277 |
+
.. code-block:: python
|
| 278 |
+
|
| 279 |
+
* [SIM=0.335463] foo [{'baz': 'bar'}]
|
| 280 |
+
|
| 281 |
+
Use as Retriever:
|
| 282 |
+
.. code-block:: python
|
| 283 |
+
|
| 284 |
+
retriever = vector_store.as_retriever(
|
| 285 |
+
search_type="mmr",
|
| 286 |
+
search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5},
|
| 287 |
+
)
|
| 288 |
+
retriever.invoke("thud")
|
| 289 |
+
|
| 290 |
+
.. code-block:: python
|
| 291 |
+
|
| 292 |
+
[Document(metadata={'baz': 'bar'}, page_content='thud')]
|
| 293 |
+
|
| 294 |
+
""" # noqa: E501
|
| 295 |
+
|
| 296 |
+
_LANGCHAIN_DEFAULT_COLLECTION_NAME = "langchain"
|
| 297 |
+
|
| 298 |
+
def __init__(
|
| 299 |
+
self,
|
| 300 |
+
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
|
| 301 |
+
embedding_function: Optional[Embeddings] = None,
|
| 302 |
+
persist_directory: Optional[str] = None,
|
| 303 |
+
host: Optional[str] = None,
|
| 304 |
+
port: Optional[int] = None,
|
| 305 |
+
headers: Optional[dict[str, str]] = None,
|
| 306 |
+
chroma_cloud_api_key: Optional[str] = None,
|
| 307 |
+
tenant: Optional[str] = None,
|
| 308 |
+
database: Optional[str] = None,
|
| 309 |
+
client_settings: Optional[chromadb.config.Settings] = None,
|
| 310 |
+
collection_metadata: Optional[dict] = None,
|
| 311 |
+
collection_configuration: Optional[CreateCollectionConfiguration] = None,
|
| 312 |
+
client: Optional[chromadb.ClientAPI] = None,
|
| 313 |
+
relevance_score_fn: Optional[Callable[[float], float]] = None,
|
| 314 |
+
create_collection_if_not_exists: Optional[bool] = True, # noqa: FBT001, FBT002
|
| 315 |
+
*,
|
| 316 |
+
ssl: bool = False,
|
| 317 |
+
) -> None:
|
| 318 |
+
"""Initialize with a Chroma client.
|
| 319 |
+
|
| 320 |
+
Args:
|
| 321 |
+
collection_name: Name of the collection to create.
|
| 322 |
+
embedding_function: Embedding class object. Used to embed texts.
|
| 323 |
+
persist_directory: Directory to persist the collection.
|
| 324 |
+
host: Hostname of a deployed Chroma server.
|
| 325 |
+
port: Connection port for a deployed Chroma server. Default is 8000.
|
| 326 |
+
ssl: Whether to establish an SSL connection with a deployed Chroma server.
|
| 327 |
+
Default is False.
|
| 328 |
+
headers: HTTP headers to send to a deployed Chroma server.
|
| 329 |
+
chroma_cloud_api_key: Chroma Cloud API key.
|
| 330 |
+
tenant: Tenant ID. Required for Chroma Cloud connections.
|
| 331 |
+
Default is 'default_tenant' for local Chroma servers.
|
| 332 |
+
database: Database name. Required for Chroma Cloud connections.
|
| 333 |
+
Default is 'default_database'.
|
| 334 |
+
client_settings: Chroma client settings
|
| 335 |
+
collection_metadata: Collection configurations.
|
| 336 |
+
collection_configuration: Index configuration for the collection.
|
| 337 |
+
Defaults to None.
|
| 338 |
+
client: Chroma client. Documentation:
|
| 339 |
+
https://docs.trychroma.com/reference/python/client
|
| 340 |
+
relevance_score_fn: Function to calculate relevance score from distance.
|
| 341 |
+
Used only in `similarity_search_with_relevance_scores`
|
| 342 |
+
create_collection_if_not_exists: Whether to create collection
|
| 343 |
+
if it doesn't exist. Defaults to True.
|
| 344 |
+
"""
|
| 345 |
+
_tenant = tenant or chromadb.DEFAULT_TENANT
|
| 346 |
+
_database = database or chromadb.DEFAULT_DATABASE
|
| 347 |
+
_settings = client_settings or Settings()
|
| 348 |
+
|
| 349 |
+
client_args = {
|
| 350 |
+
"persist_directory": persist_directory,
|
| 351 |
+
"host": host,
|
| 352 |
+
"chroma_cloud_api_key": chroma_cloud_api_key,
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
if sum(arg is not None for arg in client_args.values()) > 1:
|
| 356 |
+
provided = [
|
| 357 |
+
name for name, value in client_args.items() if value is not None
|
| 358 |
+
]
|
| 359 |
+
msg = (
|
| 360 |
+
f"Only one of 'persist_directory', 'host' and 'chroma_cloud_api_key' "
|
| 361 |
+
f"is allowed, but got {','.join(provided)}"
|
| 362 |
+
)
|
| 363 |
+
raise ValueError(msg)
|
| 364 |
+
|
| 365 |
+
if client is not None:
|
| 366 |
+
self._client = client
|
| 367 |
+
|
| 368 |
+
# PersistentClient
|
| 369 |
+
elif persist_directory is not None:
|
| 370 |
+
self._client = chromadb.PersistentClient(
|
| 371 |
+
path=persist_directory,
|
| 372 |
+
settings=_settings,
|
| 373 |
+
tenant=_tenant,
|
| 374 |
+
database=_database,
|
| 375 |
+
)
|
| 376 |
+
|
| 377 |
+
# HttpClient
|
| 378 |
+
elif host is not None:
|
| 379 |
+
_port = port or 8000
|
| 380 |
+
self._client = chromadb.HttpClient(
|
| 381 |
+
host=host,
|
| 382 |
+
port=_port,
|
| 383 |
+
ssl=ssl,
|
| 384 |
+
headers=headers,
|
| 385 |
+
settings=_settings,
|
| 386 |
+
tenant=_tenant,
|
| 387 |
+
database=_database,
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
# CloudClient
|
| 391 |
+
elif chroma_cloud_api_key is not None:
|
| 392 |
+
if not tenant or not database:
|
| 393 |
+
msg = (
|
| 394 |
+
"Must provide tenant and database values to connect to Chroma Cloud"
|
| 395 |
+
)
|
| 396 |
+
raise ValueError(msg)
|
| 397 |
+
self._client = chromadb.CloudClient(
|
| 398 |
+
tenant=tenant,
|
| 399 |
+
database=database,
|
| 400 |
+
api_key=chroma_cloud_api_key,
|
| 401 |
+
settings=_settings,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
else:
|
| 405 |
+
self._client = chromadb.Client(settings=_settings)
|
| 406 |
+
|
| 407 |
+
self._embedding_function = embedding_function
|
| 408 |
+
self._chroma_collection: Optional[chromadb.Collection] = None
|
| 409 |
+
self._collection_name = collection_name
|
| 410 |
+
self._collection_metadata = collection_metadata
|
| 411 |
+
self._collection_configuration = collection_configuration
|
| 412 |
+
if create_collection_if_not_exists:
|
| 413 |
+
self.__ensure_collection()
|
| 414 |
+
else:
|
| 415 |
+
self._chroma_collection = self._client.get_collection(name=collection_name)
|
| 416 |
+
self.override_relevance_score_fn = relevance_score_fn
|
| 417 |
+
|
| 418 |
+
def __ensure_collection(self) -> None:
|
| 419 |
+
"""Ensure that the collection exists or create it."""
|
| 420 |
+
self._chroma_collection = self._client.get_or_create_collection(
|
| 421 |
+
name=self._collection_name,
|
| 422 |
+
embedding_function=None,
|
| 423 |
+
metadata=self._collection_metadata,
|
| 424 |
+
configuration=self._collection_configuration,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
@property
|
| 428 |
+
def _collection(self) -> chromadb.Collection:
|
| 429 |
+
"""Returns the underlying Chroma collection or throws an exception."""
|
| 430 |
+
if self._chroma_collection is None:
|
| 431 |
+
msg = (
|
| 432 |
+
"Chroma collection not initialized. "
|
| 433 |
+
"Use `reset_collection` to re-create and initialize the collection. "
|
| 434 |
+
)
|
| 435 |
+
raise ValueError(
|
| 436 |
+
msg,
|
| 437 |
+
)
|
| 438 |
+
return self._chroma_collection
|
| 439 |
+
|
| 440 |
+
@property
|
| 441 |
+
def embeddings(self) -> Optional[Embeddings]:
|
| 442 |
+
"""Access the query embedding object."""
|
| 443 |
+
return self._embedding_function
|
| 444 |
+
|
| 445 |
+
@xor_args(("query_texts", "query_embeddings"))
|
| 446 |
+
def __query_collection(
|
| 447 |
+
self,
|
| 448 |
+
query_texts: Optional[list[str]] = None,
|
| 449 |
+
query_embeddings: Optional[list[list[float]]] = None,
|
| 450 |
+
n_results: int = 4,
|
| 451 |
+
where: Optional[dict[str, str]] = None,
|
| 452 |
+
where_document: Optional[dict[str, str]] = None,
|
| 453 |
+
**kwargs: Any,
|
| 454 |
+
) -> Union[list[Document], chromadb.QueryResult]:
|
| 455 |
+
"""Query the chroma collection.
|
| 456 |
+
|
| 457 |
+
Args:
|
| 458 |
+
query_texts: List of query texts.
|
| 459 |
+
query_embeddings: List of query embeddings.
|
| 460 |
+
n_results: Number of results to return. Defaults to 4.
|
| 461 |
+
where: dict used to filter results by metadata.
|
| 462 |
+
E.g. {"color" : "red"}.
|
| 463 |
+
where_document: dict used to filter by the document contents.
|
| 464 |
+
E.g. {"$contains": "hello"}.
|
| 465 |
+
kwargs: Additional keyword arguments to pass to Chroma collection query.
|
| 466 |
+
|
| 467 |
+
Returns:
|
| 468 |
+
List of `n_results` nearest neighbor embeddings for provided
|
| 469 |
+
query_embeddings or query_texts.
|
| 470 |
+
|
| 471 |
+
See more: https://docs.trychroma.com/reference/py-collection#query
|
| 472 |
+
"""
|
| 473 |
+
# Fix for ValueError('Could not connect to tenant default_tenant. Are you sure it exists?')
|
| 474 |
+
# https://github.com/langchain-ai/langchain/issues/26884
|
| 475 |
+
chromadb.api.client.SharedSystemClient.clear_system_cache()
|
| 476 |
+
return self._collection.query(
|
| 477 |
+
query_texts=query_texts,
|
| 478 |
+
query_embeddings=query_embeddings, # type: ignore[arg-type]
|
| 479 |
+
n_results=n_results,
|
| 480 |
+
where=where, # type: ignore[arg-type]
|
| 481 |
+
where_document=where_document, # type: ignore[arg-type]
|
| 482 |
+
**kwargs,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
@staticmethod
|
| 486 |
+
def encode_image(uri: str) -> str:
|
| 487 |
+
"""Get base64 string from image URI."""
|
| 488 |
+
with open(uri, "rb") as image_file:
|
| 489 |
+
return base64.b64encode(image_file.read()).decode("utf-8")
|
| 490 |
+
|
| 491 |
+
def add_images(
|
| 492 |
+
self,
|
| 493 |
+
uris: list[str],
|
| 494 |
+
metadatas: Optional[list[dict]] = None,
|
| 495 |
+
ids: Optional[list[str]] = None,
|
| 496 |
+
) -> list[str]:
|
| 497 |
+
"""Run more images through the embeddings and add to the vectorstore.
|
| 498 |
+
|
| 499 |
+
Args:
|
| 500 |
+
uris: File path to the image.
|
| 501 |
+
metadatas: Optional list of metadatas.
|
| 502 |
+
When querying, you can filter on this metadata.
|
| 503 |
+
ids: Optional list of IDs. (Items without IDs will be assigned UUIDs)
|
| 504 |
+
|
| 505 |
+
Returns:
|
| 506 |
+
List of IDs of the added images.
|
| 507 |
+
|
| 508 |
+
Raises:
|
| 509 |
+
ValueError: When metadata is incorrect.
|
| 510 |
+
"""
|
| 511 |
+
# Map from uris to b64 encoded strings
|
| 512 |
+
b64_texts = [self.encode_image(uri=uri) for uri in uris]
|
| 513 |
+
# Populate IDs
|
| 514 |
+
if ids is None:
|
| 515 |
+
ids = [str(uuid.uuid4()) for _ in uris]
|
| 516 |
+
else:
|
| 517 |
+
ids = [id_ if id_ is not None else str(uuid.uuid4()) for id_ in ids]
|
| 518 |
+
embeddings = None
|
| 519 |
+
# Set embeddings
|
| 520 |
+
if self._embedding_function is not None and hasattr(
|
| 521 |
+
self._embedding_function,
|
| 522 |
+
"embed_image",
|
| 523 |
+
):
|
| 524 |
+
embeddings = self._embedding_function.embed_image(uris=uris)
|
| 525 |
+
if metadatas:
|
| 526 |
+
# fill metadatas with empty dicts if somebody
|
| 527 |
+
# did not specify metadata for all images
|
| 528 |
+
length_diff = len(uris) - len(metadatas)
|
| 529 |
+
if length_diff:
|
| 530 |
+
metadatas = metadatas + [{}] * length_diff
|
| 531 |
+
empty_ids = []
|
| 532 |
+
non_empty_ids = []
|
| 533 |
+
for idx, m in enumerate(metadatas):
|
| 534 |
+
if m:
|
| 535 |
+
non_empty_ids.append(idx)
|
| 536 |
+
else:
|
| 537 |
+
empty_ids.append(idx)
|
| 538 |
+
if non_empty_ids:
|
| 539 |
+
metadatas = [metadatas[idx] for idx in non_empty_ids]
|
| 540 |
+
images_with_metadatas = [b64_texts[idx] for idx in non_empty_ids]
|
| 541 |
+
embeddings_with_metadatas = (
|
| 542 |
+
[embeddings[idx] for idx in non_empty_ids] if embeddings else None
|
| 543 |
+
)
|
| 544 |
+
ids_with_metadata = [ids[idx] for idx in non_empty_ids]
|
| 545 |
+
try:
|
| 546 |
+
self._collection.upsert(
|
| 547 |
+
metadatas=metadatas, # type: ignore[arg-type]
|
| 548 |
+
embeddings=embeddings_with_metadatas, # type: ignore[arg-type]
|
| 549 |
+
documents=images_with_metadatas,
|
| 550 |
+
ids=ids_with_metadata,
|
| 551 |
+
)
|
| 552 |
+
except ValueError as e:
|
| 553 |
+
if "Expected metadata value to be" in str(e):
|
| 554 |
+
msg = (
|
| 555 |
+
"Try filtering complex metadata using "
|
| 556 |
+
"langchain_community.vectorstores.utils.filter_complex_metadata."
|
| 557 |
+
)
|
| 558 |
+
raise ValueError(e.args[0] + "\n\n" + msg) from e
|
| 559 |
+
raise e
|
| 560 |
+
if empty_ids:
|
| 561 |
+
images_without_metadatas = [b64_texts[j] for j in empty_ids]
|
| 562 |
+
embeddings_without_metadatas = (
|
| 563 |
+
[embeddings[j] for j in empty_ids] if embeddings else None
|
| 564 |
+
)
|
| 565 |
+
ids_without_metadatas = [ids[j] for j in empty_ids]
|
| 566 |
+
self._collection.upsert(
|
| 567 |
+
embeddings=embeddings_without_metadatas,
|
| 568 |
+
documents=images_without_metadatas,
|
| 569 |
+
ids=ids_without_metadatas,
|
| 570 |
+
)
|
| 571 |
+
else:
|
| 572 |
+
self._collection.upsert(
|
| 573 |
+
embeddings=embeddings,
|
| 574 |
+
documents=b64_texts,
|
| 575 |
+
ids=ids,
|
| 576 |
+
)
|
| 577 |
+
return ids
|
| 578 |
+
|
| 579 |
+
def add_texts(
|
| 580 |
+
self,
|
| 581 |
+
texts: Iterable[str],
|
| 582 |
+
metadatas: Optional[list[dict]] = None,
|
| 583 |
+
ids: Optional[list[str]] = None,
|
| 584 |
+
**kwargs: Any,
|
| 585 |
+
) -> list[str]:
|
| 586 |
+
"""Run more texts through the embeddings and add to the vectorstore.
|
| 587 |
+
|
| 588 |
+
Args:
|
| 589 |
+
texts: Texts to add to the vectorstore.
|
| 590 |
+
metadatas: Optional list of metadatas.
|
| 591 |
+
When querying, you can filter on this metadata.
|
| 592 |
+
ids: Optional list of IDs. (Items without IDs will be assigned UUIDs)
|
| 593 |
+
kwargs: Additional keyword arguments.
|
| 594 |
+
|
| 595 |
+
Returns:
|
| 596 |
+
List of IDs of the added texts.
|
| 597 |
+
|
| 598 |
+
Raises:
|
| 599 |
+
ValueError: When metadata is incorrect.
|
| 600 |
+
"""
|
| 601 |
+
if ids is None:
|
| 602 |
+
ids = [str(uuid.uuid4()) for _ in texts]
|
| 603 |
+
else:
|
| 604 |
+
ids = [id_ if id_ is not None else str(uuid.uuid4()) for id_ in ids]
|
| 605 |
+
|
| 606 |
+
embeddings = None
|
| 607 |
+
texts = list(texts)
|
| 608 |
+
if self._embedding_function is not None:
|
| 609 |
+
embeddings = self._embedding_function.embed_documents(texts)
|
| 610 |
+
if metadatas:
|
| 611 |
+
# fill metadatas with empty dicts if somebody
|
| 612 |
+
# did not specify metadata for all texts
|
| 613 |
+
length_diff = len(texts) - len(metadatas)
|
| 614 |
+
if length_diff:
|
| 615 |
+
metadatas = metadatas + [{}] * length_diff
|
| 616 |
+
empty_ids = []
|
| 617 |
+
non_empty_ids = []
|
| 618 |
+
for idx, m in enumerate(metadatas):
|
| 619 |
+
if m:
|
| 620 |
+
non_empty_ids.append(idx)
|
| 621 |
+
else:
|
| 622 |
+
empty_ids.append(idx)
|
| 623 |
+
if non_empty_ids:
|
| 624 |
+
metadatas = [metadatas[idx] for idx in non_empty_ids]
|
| 625 |
+
texts_with_metadatas = [texts[idx] for idx in non_empty_ids]
|
| 626 |
+
embeddings_with_metadatas = (
|
| 627 |
+
[embeddings[idx] for idx in non_empty_ids]
|
| 628 |
+
if embeddings is not None and len(embeddings) > 0
|
| 629 |
+
else None
|
| 630 |
+
)
|
| 631 |
+
ids_with_metadata = [ids[idx] for idx in non_empty_ids]
|
| 632 |
+
try:
|
| 633 |
+
self._collection.upsert(
|
| 634 |
+
metadatas=metadatas, # type: ignore[arg-type]
|
| 635 |
+
embeddings=embeddings_with_metadatas, # type: ignore[arg-type]
|
| 636 |
+
documents=texts_with_metadatas,
|
| 637 |
+
ids=ids_with_metadata,
|
| 638 |
+
)
|
| 639 |
+
except ValueError as e:
|
| 640 |
+
if "Expected metadata value to be" in str(e):
|
| 641 |
+
msg = (
|
| 642 |
+
"Try filtering complex metadata from the document using "
|
| 643 |
+
"langchain_community.vectorstores.utils.filter_complex_metadata."
|
| 644 |
+
)
|
| 645 |
+
raise ValueError(e.args[0] + "\n\n" + msg) from e
|
| 646 |
+
raise e
|
| 647 |
+
if empty_ids:
|
| 648 |
+
texts_without_metadatas = [texts[j] for j in empty_ids]
|
| 649 |
+
embeddings_without_metadatas = (
|
| 650 |
+
[embeddings[j] for j in empty_ids] if embeddings else None
|
| 651 |
+
)
|
| 652 |
+
ids_without_metadatas = [ids[j] for j in empty_ids]
|
| 653 |
+
self._collection.upsert(
|
| 654 |
+
embeddings=embeddings_without_metadatas, # type: ignore[arg-type]
|
| 655 |
+
documents=texts_without_metadatas,
|
| 656 |
+
ids=ids_without_metadatas,
|
| 657 |
+
)
|
| 658 |
+
else:
|
| 659 |
+
self._collection.upsert(
|
| 660 |
+
embeddings=embeddings, # type: ignore[arg-type]
|
| 661 |
+
documents=texts,
|
| 662 |
+
ids=ids,
|
| 663 |
+
)
|
| 664 |
+
return ids
|
| 665 |
+
|
| 666 |
+
def similarity_search(
|
| 667 |
+
self,
|
| 668 |
+
query: str,
|
| 669 |
+
k: int = DEFAULT_K,
|
| 670 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 671 |
+
**kwargs: Any,
|
| 672 |
+
) -> list[Document]:
|
| 673 |
+
"""Run similarity search with Chroma.
|
| 674 |
+
|
| 675 |
+
Args:
|
| 676 |
+
query: Query text to search for.
|
| 677 |
+
k: Number of results to return. Defaults to 4.
|
| 678 |
+
filter: Filter by metadata. Defaults to None.
|
| 679 |
+
kwargs: Additional keyword arguments to pass to Chroma collection query.
|
| 680 |
+
|
| 681 |
+
Returns:
|
| 682 |
+
List of documents most similar to the query text.
|
| 683 |
+
"""
|
| 684 |
+
docs_and_scores = self.similarity_search_with_score(
|
| 685 |
+
query,
|
| 686 |
+
k,
|
| 687 |
+
filter=filter,
|
| 688 |
+
**kwargs,
|
| 689 |
+
)
|
| 690 |
+
return [doc for doc, _ in docs_and_scores]
|
| 691 |
+
|
| 692 |
+
def similarity_search_by_vector(
|
| 693 |
+
self,
|
| 694 |
+
embedding: list[float],
|
| 695 |
+
k: int = DEFAULT_K,
|
| 696 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 697 |
+
where_document: Optional[dict[str, str]] = None,
|
| 698 |
+
**kwargs: Any,
|
| 699 |
+
) -> list[Document]:
|
| 700 |
+
"""Return docs most similar to embedding vector.
|
| 701 |
+
|
| 702 |
+
Args:
|
| 703 |
+
embedding: Embedding to look up documents similar to.
|
| 704 |
+
k: Number of Documents to return. Defaults to 4.
|
| 705 |
+
filter: Filter by metadata. Defaults to None.
|
| 706 |
+
where_document: dict used to filter by the document contents.
|
| 707 |
+
E.g. {"$contains": "hello"}.
|
| 708 |
+
kwargs: Additional keyword arguments to pass to Chroma collection query.
|
| 709 |
+
|
| 710 |
+
Returns:
|
| 711 |
+
List of Documents most similar to the query vector.
|
| 712 |
+
"""
|
| 713 |
+
results = self.__query_collection(
|
| 714 |
+
query_embeddings=[embedding],
|
| 715 |
+
n_results=k,
|
| 716 |
+
where=filter,
|
| 717 |
+
where_document=where_document,
|
| 718 |
+
**kwargs,
|
| 719 |
+
)
|
| 720 |
+
return _results_to_docs(results)
|
| 721 |
+
|
| 722 |
+
def similarity_search_by_vector_with_relevance_scores(
|
| 723 |
+
self,
|
| 724 |
+
embedding: list[float],
|
| 725 |
+
k: int = DEFAULT_K,
|
| 726 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 727 |
+
where_document: Optional[dict[str, str]] = None,
|
| 728 |
+
**kwargs: Any,
|
| 729 |
+
) -> list[tuple[Document, float]]:
|
| 730 |
+
"""Return docs most similar to embedding vector and similarity score.
|
| 731 |
+
|
| 732 |
+
Args:
|
| 733 |
+
embedding (List[float]): Embedding to look up documents similar to.
|
| 734 |
+
k: Number of Documents to return. Defaults to 4.
|
| 735 |
+
filter: Filter by metadata. Defaults to None.
|
| 736 |
+
where_document: dict used to filter by the documents.
|
| 737 |
+
E.g. {"$contains": "hello"}.
|
| 738 |
+
kwargs: Additional keyword arguments to pass to Chroma collection query.
|
| 739 |
+
|
| 740 |
+
Returns:
|
| 741 |
+
List of documents most similar to the query text and relevance score
|
| 742 |
+
in float for each. Lower score represents more similarity.
|
| 743 |
+
"""
|
| 744 |
+
results = self.__query_collection(
|
| 745 |
+
query_embeddings=[embedding],
|
| 746 |
+
n_results=k,
|
| 747 |
+
where=filter,
|
| 748 |
+
where_document=where_document,
|
| 749 |
+
**kwargs,
|
| 750 |
+
)
|
| 751 |
+
return _results_to_docs_and_scores(results)
|
| 752 |
+
|
| 753 |
+
def similarity_search_with_score(
|
| 754 |
+
self,
|
| 755 |
+
query: str,
|
| 756 |
+
k: int = DEFAULT_K,
|
| 757 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 758 |
+
where_document: Optional[dict[str, str]] = None,
|
| 759 |
+
**kwargs: Any,
|
| 760 |
+
) -> list[tuple[Document, float]]:
|
| 761 |
+
"""Run similarity search with Chroma with distance.
|
| 762 |
+
|
| 763 |
+
Args:
|
| 764 |
+
query: Query text to search for.
|
| 765 |
+
k: Number of results to return. Defaults to 4.
|
| 766 |
+
filter: Filter by metadata. Defaults to None.
|
| 767 |
+
where_document: dict used to filter by document contents.
|
| 768 |
+
E.g. {"$contains": "hello"}.
|
| 769 |
+
kwargs: Additional keyword arguments to pass to Chroma collection query.
|
| 770 |
+
|
| 771 |
+
Returns:
|
| 772 |
+
List of documents most similar to the query text and
|
| 773 |
+
distance in float for each. Lower score represents more similarity.
|
| 774 |
+
"""
|
| 775 |
+
if self._embedding_function is None:
|
| 776 |
+
results = self.__query_collection(
|
| 777 |
+
query_texts=[query],
|
| 778 |
+
n_results=k,
|
| 779 |
+
where=filter,
|
| 780 |
+
where_document=where_document,
|
| 781 |
+
**kwargs,
|
| 782 |
+
)
|
| 783 |
+
else:
|
| 784 |
+
query_embedding = self._embedding_function.embed_query(query)
|
| 785 |
+
results = self.__query_collection(
|
| 786 |
+
query_embeddings=[query_embedding],
|
| 787 |
+
n_results=k,
|
| 788 |
+
where=filter,
|
| 789 |
+
where_document=where_document,
|
| 790 |
+
**kwargs,
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
return _results_to_docs_and_scores(results)
|
| 794 |
+
|
| 795 |
+
def similarity_search_with_vectors(
|
| 796 |
+
self,
|
| 797 |
+
query: str,
|
| 798 |
+
k: int = DEFAULT_K,
|
| 799 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 800 |
+
where_document: Optional[dict[str, str]] = None,
|
| 801 |
+
**kwargs: Any,
|
| 802 |
+
) -> list[tuple[Document, np.ndarray]]:
|
| 803 |
+
"""Run similarity search with Chroma with vectors.
|
| 804 |
+
|
| 805 |
+
Args:
|
| 806 |
+
query: Query text to search for.
|
| 807 |
+
k: Number of results to return. Defaults to 4.
|
| 808 |
+
filter: Filter by metadata. Defaults to None.
|
| 809 |
+
where_document: dict used to filter by the document contents.
|
| 810 |
+
E.g. {"$contains": "hello"}.
|
| 811 |
+
kwargs: Additional keyword arguments to pass to Chroma collection query.
|
| 812 |
+
|
| 813 |
+
Returns:
|
| 814 |
+
List of documents most similar to the query text and
|
| 815 |
+
embedding vectors for each.
|
| 816 |
+
"""
|
| 817 |
+
include = ["documents", "metadatas", "embeddings"]
|
| 818 |
+
if self._embedding_function is None:
|
| 819 |
+
results = self.__query_collection(
|
| 820 |
+
query_texts=[query],
|
| 821 |
+
n_results=k,
|
| 822 |
+
where=filter,
|
| 823 |
+
where_document=where_document,
|
| 824 |
+
include=include,
|
| 825 |
+
**kwargs,
|
| 826 |
+
)
|
| 827 |
+
else:
|
| 828 |
+
query_embedding = self._embedding_function.embed_query(query)
|
| 829 |
+
results = self.__query_collection(
|
| 830 |
+
query_embeddings=[query_embedding],
|
| 831 |
+
n_results=k,
|
| 832 |
+
where=filter,
|
| 833 |
+
where_document=where_document,
|
| 834 |
+
include=include,
|
| 835 |
+
**kwargs,
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
return _results_to_docs_and_vectors(results)
|
| 839 |
+
|
| 840 |
+
def _select_relevance_score_fn(self) -> Callable[[float], float]:
|
| 841 |
+
"""Select the relevance score function based on collections distance metric.
|
| 842 |
+
|
| 843 |
+
The most similar documents will have the lowest relevance score. Default
|
| 844 |
+
relevance score function is Euclidean distance. Distance metric must be
|
| 845 |
+
provided in `collection_configuration` during initialization of Chroma object.
|
| 846 |
+
Example: collection_configuration={"hnsw": {"space": "cosine"}}.
|
| 847 |
+
Available distance metrics are: 'cosine', 'l2' and 'ip'.
|
| 848 |
+
|
| 849 |
+
Returns:
|
| 850 |
+
The relevance score function.
|
| 851 |
+
|
| 852 |
+
Raises:
|
| 853 |
+
ValueError: If the distance metric is not supported.
|
| 854 |
+
"""
|
| 855 |
+
if self.override_relevance_score_fn:
|
| 856 |
+
return self.override_relevance_score_fn
|
| 857 |
+
|
| 858 |
+
hnsw_config = self._collection.configuration.get("hnsw")
|
| 859 |
+
hnsw_distance: Optional[str] = hnsw_config.get("space") if hnsw_config else None
|
| 860 |
+
|
| 861 |
+
spann_config = self._collection.configuration.get("spann")
|
| 862 |
+
spann_distance: Optional[str] = (
|
| 863 |
+
spann_config.get("space") if spann_config else None
|
| 864 |
+
)
|
| 865 |
+
|
| 866 |
+
distance = hnsw_distance or spann_distance
|
| 867 |
+
|
| 868 |
+
if distance == "cosine":
|
| 869 |
+
return self._cosine_relevance_score_fn
|
| 870 |
+
if distance == "l2":
|
| 871 |
+
return self._euclidean_relevance_score_fn
|
| 872 |
+
if distance == "ip":
|
| 873 |
+
return self._max_inner_product_relevance_score_fn
|
| 874 |
+
msg = (
|
| 875 |
+
"No supported normalization function"
|
| 876 |
+
f" for distance metric of type: {distance}."
|
| 877 |
+
"Consider providing relevance_score_fn to Chroma constructor."
|
| 878 |
+
)
|
| 879 |
+
raise ValueError(
|
| 880 |
+
msg,
|
| 881 |
+
)
|
| 882 |
+
|
| 883 |
+
def similarity_search_by_image(
|
| 884 |
+
self,
|
| 885 |
+
uri: str,
|
| 886 |
+
k: int = DEFAULT_K,
|
| 887 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 888 |
+
**kwargs: Any,
|
| 889 |
+
) -> list[Document]:
|
| 890 |
+
"""Search for similar images based on the given image URI.
|
| 891 |
+
|
| 892 |
+
Args:
|
| 893 |
+
uri (str): URI of the image to search for.
|
| 894 |
+
k (int, optional): Number of results to return. Defaults to DEFAULT_K.
|
| 895 |
+
filter (Optional[Dict[str, str]], optional): Filter by metadata.
|
| 896 |
+
**kwargs (Any): Additional arguments to pass to function.
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
Returns:
|
| 900 |
+
List of Images most similar to the provided image.
|
| 901 |
+
Each element in list is a Langchain Document Object.
|
| 902 |
+
The page content is b64 encoded image, metadata is default or
|
| 903 |
+
as defined by user.
|
| 904 |
+
|
| 905 |
+
Raises:
|
| 906 |
+
ValueError: If the embedding function does not support image embeddings.
|
| 907 |
+
"""
|
| 908 |
+
if self._embedding_function is not None and hasattr(
|
| 909 |
+
self._embedding_function, "embed_image"
|
| 910 |
+
):
|
| 911 |
+
# Obtain image embedding
|
| 912 |
+
# Assuming embed_image returns a single embedding
|
| 913 |
+
image_embedding = self._embedding_function.embed_image(uris=[uri])
|
| 914 |
+
|
| 915 |
+
# Perform similarity search based on the obtained embedding
|
| 916 |
+
return self.similarity_search_by_vector(
|
| 917 |
+
embedding=image_embedding,
|
| 918 |
+
k=k,
|
| 919 |
+
filter=filter,
|
| 920 |
+
**kwargs,
|
| 921 |
+
)
|
| 922 |
+
msg = "The embedding function must support image embedding."
|
| 923 |
+
raise ValueError(msg)
|
| 924 |
+
|
| 925 |
+
def similarity_search_by_image_with_relevance_score(
|
| 926 |
+
self,
|
| 927 |
+
uri: str,
|
| 928 |
+
k: int = DEFAULT_K,
|
| 929 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 930 |
+
**kwargs: Any,
|
| 931 |
+
) -> list[tuple[Document, float]]:
|
| 932 |
+
"""Search for similar images based on the given image URI.
|
| 933 |
+
|
| 934 |
+
Args:
|
| 935 |
+
uri (str): URI of the image to search for.
|
| 936 |
+
k (int, optional): Number of results to return.
|
| 937 |
+
Defaults to DEFAULT_K.
|
| 938 |
+
filter (Optional[Dict[str, str]], optional): Filter by metadata.
|
| 939 |
+
**kwargs (Any): Additional arguments to pass to function.
|
| 940 |
+
|
| 941 |
+
Returns:
|
| 942 |
+
List[Tuple[Document, float]]: List of tuples containing documents similar
|
| 943 |
+
to the query image and their similarity scores.
|
| 944 |
+
0th element in each tuple is a Langchain Document Object.
|
| 945 |
+
The page content is b64 encoded img, metadata is default or defined by user.
|
| 946 |
+
|
| 947 |
+
Raises:
|
| 948 |
+
ValueError: If the embedding function does not support image embeddings.
|
| 949 |
+
"""
|
| 950 |
+
if self._embedding_function is not None and hasattr(
|
| 951 |
+
self._embedding_function, "embed_image"
|
| 952 |
+
):
|
| 953 |
+
# Obtain image embedding
|
| 954 |
+
# Assuming embed_image returns a single embedding
|
| 955 |
+
image_embedding = self._embedding_function.embed_image(uris=[uri])
|
| 956 |
+
|
| 957 |
+
# Perform similarity search based on the obtained embedding
|
| 958 |
+
return self.similarity_search_by_vector_with_relevance_scores(
|
| 959 |
+
embedding=image_embedding,
|
| 960 |
+
k=k,
|
| 961 |
+
filter=filter,
|
| 962 |
+
**kwargs,
|
| 963 |
+
)
|
| 964 |
+
msg = "The embedding function must support image embedding."
|
| 965 |
+
raise ValueError(msg)
|
| 966 |
+
|
| 967 |
+
def max_marginal_relevance_search_by_vector(
|
| 968 |
+
self,
|
| 969 |
+
embedding: list[float],
|
| 970 |
+
k: int = DEFAULT_K,
|
| 971 |
+
fetch_k: int = 20,
|
| 972 |
+
lambda_mult: float = 0.5,
|
| 973 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 974 |
+
where_document: Optional[dict[str, str]] = None,
|
| 975 |
+
**kwargs: Any,
|
| 976 |
+
) -> list[Document]:
|
| 977 |
+
"""Return docs selected using the maximal marginal relevance.
|
| 978 |
+
|
| 979 |
+
Maximal marginal relevance optimizes for similarity to query AND diversity
|
| 980 |
+
among selected documents.
|
| 981 |
+
|
| 982 |
+
Args:
|
| 983 |
+
embedding: Embedding to look up documents similar to.
|
| 984 |
+
k: Number of Documents to return. Defaults to 4.
|
| 985 |
+
fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to
|
| 986 |
+
20.
|
| 987 |
+
lambda_mult: Number between 0 and 1 that determines the degree
|
| 988 |
+
of diversity among the results with 0 corresponding
|
| 989 |
+
to maximum diversity and 1 to minimum diversity.
|
| 990 |
+
Defaults to 0.5.
|
| 991 |
+
filter: Filter by metadata. Defaults to None.
|
| 992 |
+
where_document: dict used to filter by the document contents.
|
| 993 |
+
E.g. {"$contains": "hello"}.
|
| 994 |
+
kwargs: Additional keyword arguments to pass to Chroma collection query.
|
| 995 |
+
|
| 996 |
+
Returns:
|
| 997 |
+
List of Documents selected by maximal marginal relevance.
|
| 998 |
+
"""
|
| 999 |
+
results = self.__query_collection(
|
| 1000 |
+
query_embeddings=[embedding],
|
| 1001 |
+
n_results=fetch_k,
|
| 1002 |
+
where=filter,
|
| 1003 |
+
where_document=where_document,
|
| 1004 |
+
include=["metadatas", "documents", "distances", "embeddings"],
|
| 1005 |
+
**kwargs,
|
| 1006 |
+
)
|
| 1007 |
+
mmr_selected = maximal_marginal_relevance(
|
| 1008 |
+
np.array(embedding, dtype=np.float32),
|
| 1009 |
+
results["embeddings"][0],
|
| 1010 |
+
k=k,
|
| 1011 |
+
lambda_mult=lambda_mult,
|
| 1012 |
+
)
|
| 1013 |
+
|
| 1014 |
+
candidates = _results_to_docs(results)
|
| 1015 |
+
|
| 1016 |
+
return [r for i, r in enumerate(candidates) if i in mmr_selected]
|
| 1017 |
+
|
| 1018 |
+
def max_marginal_relevance_search(
|
| 1019 |
+
self,
|
| 1020 |
+
query: str,
|
| 1021 |
+
k: int = DEFAULT_K,
|
| 1022 |
+
fetch_k: int = 20,
|
| 1023 |
+
lambda_mult: float = 0.5,
|
| 1024 |
+
filter: Optional[dict[str, str]] = None, # noqa: A002
|
| 1025 |
+
where_document: Optional[dict[str, str]] = None,
|
| 1026 |
+
**kwargs: Any,
|
| 1027 |
+
) -> list[Document]:
|
| 1028 |
+
"""Return docs selected using the maximal marginal relevance.
|
| 1029 |
+
|
| 1030 |
+
Maximal marginal relevance optimizes for similarity to query AND diversity
|
| 1031 |
+
among selected documents.
|
| 1032 |
+
|
| 1033 |
+
Args:
|
| 1034 |
+
query: Text to look up documents similar to.
|
| 1035 |
+
k: Number of Documents to return. Defaults to 4.
|
| 1036 |
+
fetch_k: Number of Documents to fetch to pass to MMR algorithm.
|
| 1037 |
+
lambda_mult: Number between 0 and 1 that determines the degree
|
| 1038 |
+
of diversity among the results with 0 corresponding
|
| 1039 |
+
to maximum diversity and 1 to minimum diversity.
|
| 1040 |
+
Defaults to 0.5.
|
| 1041 |
+
filter: Filter by metadata. Defaults to None.
|
| 1042 |
+
where_document: dict used to filter by the document contents.
|
| 1043 |
+
E.g. {"$contains": "hello"}.
|
| 1044 |
+
kwargs: Additional keyword arguments to pass to Chroma collection query.
|
| 1045 |
+
|
| 1046 |
+
Returns:
|
| 1047 |
+
List of Documents selected by maximal marginal relevance.
|
| 1048 |
+
|
| 1049 |
+
Raises:
|
| 1050 |
+
ValueError: If the embedding function is not provided.
|
| 1051 |
+
"""
|
| 1052 |
+
if self._embedding_function is None:
|
| 1053 |
+
msg = "For MMR search, you must specify an embedding function on creation."
|
| 1054 |
+
raise ValueError(
|
| 1055 |
+
msg,
|
| 1056 |
+
)
|
| 1057 |
+
|
| 1058 |
+
embedding = self._embedding_function.embed_query(query)
|
| 1059 |
+
return self.max_marginal_relevance_search_by_vector(
|
| 1060 |
+
embedding,
|
| 1061 |
+
k,
|
| 1062 |
+
fetch_k,
|
| 1063 |
+
lambda_mult=lambda_mult,
|
| 1064 |
+
filter=filter,
|
| 1065 |
+
where_document=where_document,
|
| 1066 |
+
)
|
| 1067 |
+
|
| 1068 |
+
def delete_collection(self) -> None:
|
| 1069 |
+
"""Delete the collection."""
|
| 1070 |
+
self._client.delete_collection(self._collection.name)
|
| 1071 |
+
self._chroma_collection = None
|
| 1072 |
+
|
| 1073 |
+
def reset_collection(self) -> None:
|
| 1074 |
+
"""Resets the collection.
|
| 1075 |
+
|
| 1076 |
+
Resets the collection by deleting the collection and recreating an empty one.
|
| 1077 |
+
"""
|
| 1078 |
+
self.delete_collection()
|
| 1079 |
+
self.__ensure_collection()
|
| 1080 |
+
|
| 1081 |
+
def get(
|
| 1082 |
+
self,
|
| 1083 |
+
ids: Optional[Union[str, list[str]]] = None,
|
| 1084 |
+
where: Optional[Where] = None,
|
| 1085 |
+
limit: Optional[int] = None,
|
| 1086 |
+
offset: Optional[int] = None,
|
| 1087 |
+
where_document: Optional[WhereDocument] = None,
|
| 1088 |
+
include: Optional[list[str]] = None,
|
| 1089 |
+
) -> dict[str, Any]:
|
| 1090 |
+
"""Gets the collection.
|
| 1091 |
+
|
| 1092 |
+
Args:
|
| 1093 |
+
ids: The ids of the embeddings to get. Optional.
|
| 1094 |
+
where: A Where type dict used to filter results by.
|
| 1095 |
+
E.g. `{"$and": [{"color": "red"}, {"price": 4.20}]}` Optional.
|
| 1096 |
+
limit: The number of documents to return. Optional.
|
| 1097 |
+
offset: The offset to start returning results from.
|
| 1098 |
+
Useful for paging results with limit. Optional.
|
| 1099 |
+
where_document: A WhereDocument type dict used to filter by the documents.
|
| 1100 |
+
E.g. `{"$contains": "hello"}`. Optional.
|
| 1101 |
+
include: A list of what to include in the results.
|
| 1102 |
+
Can contain `"embeddings"`, `"metadatas"`, `"documents"`.
|
| 1103 |
+
Ids are always included.
|
| 1104 |
+
Defaults to `["metadatas", "documents"]`. Optional.
|
| 1105 |
+
|
| 1106 |
+
Return:
|
| 1107 |
+
A dict with the keys `"ids"`, `"embeddings"`, `"metadatas"`, `"documents"`.
|
| 1108 |
+
"""
|
| 1109 |
+
kwargs = {
|
| 1110 |
+
"ids": ids,
|
| 1111 |
+
"where": where,
|
| 1112 |
+
"limit": limit,
|
| 1113 |
+
"offset": offset,
|
| 1114 |
+
"where_document": where_document,
|
| 1115 |
+
}
|
| 1116 |
+
|
| 1117 |
+
if include is not None:
|
| 1118 |
+
kwargs["include"] = include
|
| 1119 |
+
|
| 1120 |
+
return self._collection.get(**kwargs) # type: ignore[arg-type, return-value]
|
| 1121 |
+
|
| 1122 |
+
def get_by_ids(self, ids: Sequence[str], /) -> list[Document]:
|
| 1123 |
+
"""Get documents by their IDs.
|
| 1124 |
+
|
| 1125 |
+
The returned documents are expected to have the ID field set to the ID of the
|
| 1126 |
+
document in the vector store.
|
| 1127 |
+
|
| 1128 |
+
Fewer documents may be returned than requested if some IDs are not found or
|
| 1129 |
+
if there are duplicated IDs.
|
| 1130 |
+
|
| 1131 |
+
Users should not assume that the order of the returned documents matches
|
| 1132 |
+
the order of the input IDs. Instead, users should rely on the ID field of the
|
| 1133 |
+
returned documents.
|
| 1134 |
+
|
| 1135 |
+
This method should **NOT** raise exceptions if no documents are found for
|
| 1136 |
+
some IDs.
|
| 1137 |
+
|
| 1138 |
+
Args:
|
| 1139 |
+
ids: List of ids to retrieve.
|
| 1140 |
+
|
| 1141 |
+
Returns:
|
| 1142 |
+
List of Documents.
|
| 1143 |
+
|
| 1144 |
+
... versionadded:: 0.2.1
|
| 1145 |
+
"""
|
| 1146 |
+
results = self.get(ids=list(ids))
|
| 1147 |
+
return [
|
| 1148 |
+
Document(page_content=doc, metadata=meta, id=doc_id)
|
| 1149 |
+
for doc, meta, doc_id in zip(
|
| 1150 |
+
results["documents"],
|
| 1151 |
+
results["metadatas"],
|
| 1152 |
+
results["ids"],
|
| 1153 |
+
)
|
| 1154 |
+
]
|
| 1155 |
+
|
| 1156 |
+
def update_document(self, document_id: str, document: Document) -> None:
|
| 1157 |
+
"""Update a document in the collection.
|
| 1158 |
+
|
| 1159 |
+
Args:
|
| 1160 |
+
document_id: ID of the document to update.
|
| 1161 |
+
document: Document to update.
|
| 1162 |
+
"""
|
| 1163 |
+
return self.update_documents([document_id], [document])
|
| 1164 |
+
|
| 1165 |
+
def update_documents(self, ids: list[str], documents: list[Document]) -> None:
|
| 1166 |
+
"""Update a document in the collection.
|
| 1167 |
+
|
| 1168 |
+
Args:
|
| 1169 |
+
ids: List of ids of the document to update.
|
| 1170 |
+
documents: List of documents to update.
|
| 1171 |
+
|
| 1172 |
+
Raises:
|
| 1173 |
+
ValueError: If the embedding function is not provided.
|
| 1174 |
+
"""
|
| 1175 |
+
text = [document.page_content for document in documents]
|
| 1176 |
+
metadata = [document.metadata for document in documents]
|
| 1177 |
+
if self._embedding_function is None:
|
| 1178 |
+
msg = "For update, you must specify an embedding function on creation."
|
| 1179 |
+
raise ValueError(
|
| 1180 |
+
msg,
|
| 1181 |
+
)
|
| 1182 |
+
embeddings = self._embedding_function.embed_documents(text)
|
| 1183 |
+
|
| 1184 |
+
if hasattr(
|
| 1185 |
+
self._client,
|
| 1186 |
+
"get_max_batch_size",
|
| 1187 |
+
) or hasattr( # for Chroma 0.5.1 and above
|
| 1188 |
+
self._client,
|
| 1189 |
+
"max_batch_size",
|
| 1190 |
+
): # for Chroma 0.4.10 and above
|
| 1191 |
+
from chromadb.utils.batch_utils import create_batches
|
| 1192 |
+
|
| 1193 |
+
for batch in create_batches(
|
| 1194 |
+
api=self._client,
|
| 1195 |
+
ids=ids,
|
| 1196 |
+
metadatas=metadata, # type: ignore[arg-type]
|
| 1197 |
+
documents=text,
|
| 1198 |
+
embeddings=embeddings, # type: ignore[arg-type]
|
| 1199 |
+
):
|
| 1200 |
+
self._collection.update(
|
| 1201 |
+
ids=batch[0],
|
| 1202 |
+
embeddings=batch[1],
|
| 1203 |
+
documents=batch[3],
|
| 1204 |
+
metadatas=batch[2],
|
| 1205 |
+
)
|
| 1206 |
+
else:
|
| 1207 |
+
self._collection.update(
|
| 1208 |
+
ids=ids,
|
| 1209 |
+
embeddings=embeddings, # type: ignore[arg-type]
|
| 1210 |
+
documents=text,
|
| 1211 |
+
metadatas=metadata, # type: ignore[arg-type]
|
| 1212 |
+
)
|
| 1213 |
+
|
| 1214 |
+
@classmethod
|
| 1215 |
+
def from_texts(
|
| 1216 |
+
cls: type[Chroma],
|
| 1217 |
+
texts: list[str],
|
| 1218 |
+
embedding: Optional[Embeddings] = None,
|
| 1219 |
+
metadatas: Optional[list[dict]] = None,
|
| 1220 |
+
ids: Optional[list[str]] = None,
|
| 1221 |
+
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
|
| 1222 |
+
persist_directory: Optional[str] = None,
|
| 1223 |
+
host: Optional[str] = None,
|
| 1224 |
+
port: Optional[int] = None,
|
| 1225 |
+
headers: Optional[dict[str, str]] = None,
|
| 1226 |
+
chroma_cloud_api_key: Optional[str] = None,
|
| 1227 |
+
tenant: Optional[str] = None,
|
| 1228 |
+
database: Optional[str] = None,
|
| 1229 |
+
client_settings: Optional[chromadb.config.Settings] = None,
|
| 1230 |
+
client: Optional[chromadb.ClientAPI] = None,
|
| 1231 |
+
collection_metadata: Optional[dict] = None,
|
| 1232 |
+
collection_configuration: Optional[CreateCollectionConfiguration] = None,
|
| 1233 |
+
*,
|
| 1234 |
+
ssl: bool = False,
|
| 1235 |
+
**kwargs: Any,
|
| 1236 |
+
) -> Chroma:
|
| 1237 |
+
"""Create a Chroma vectorstore from a raw documents.
|
| 1238 |
+
|
| 1239 |
+
If a persist_directory is specified, the collection will be persisted there.
|
| 1240 |
+
Otherwise, the data will be ephemeral in-memory.
|
| 1241 |
+
|
| 1242 |
+
Args:
|
| 1243 |
+
texts: List of texts to add to the collection.
|
| 1244 |
+
collection_name: Name of the collection to create.
|
| 1245 |
+
persist_directory: Directory to persist the collection.
|
| 1246 |
+
host: Hostname of a deployed Chroma server.
|
| 1247 |
+
port: Connection port for a deployed Chroma server.
|
| 1248 |
+
Default is 8000.
|
| 1249 |
+
ssl: Whether to establish an SSL connection with a deployed Chroma server.
|
| 1250 |
+
Default is False.
|
| 1251 |
+
headers: HTTP headers to send to a deployed Chroma server.
|
| 1252 |
+
chroma_cloud_api_key: Chroma Cloud API key.
|
| 1253 |
+
tenant: Tenant ID. Required for Chroma Cloud connections.
|
| 1254 |
+
Default is 'default_tenant' for local Chroma servers.
|
| 1255 |
+
database: Database name. Required for Chroma Cloud connections.
|
| 1256 |
+
Default is 'default_database'.
|
| 1257 |
+
embedding: Embedding function. Defaults to None.
|
| 1258 |
+
metadatas: List of metadatas. Defaults to None.
|
| 1259 |
+
ids: List of document IDs. Defaults to None.
|
| 1260 |
+
client_settings: Chroma client settings.
|
| 1261 |
+
client: Chroma client. Documentation:
|
| 1262 |
+
https://docs.trychroma.com/reference/python/client
|
| 1263 |
+
collection_metadata: Collection configurations. Defaults to None.
|
| 1264 |
+
collection_configuration: Index configuration for the collection.
|
| 1265 |
+
Defaults to None.
|
| 1266 |
+
kwargs: Additional keyword arguments to initialize a Chroma client.
|
| 1267 |
+
|
| 1268 |
+
Returns:
|
| 1269 |
+
Chroma: Chroma vectorstore.
|
| 1270 |
+
"""
|
| 1271 |
+
chroma_collection = cls(
|
| 1272 |
+
collection_name=collection_name,
|
| 1273 |
+
embedding_function=embedding,
|
| 1274 |
+
persist_directory=persist_directory,
|
| 1275 |
+
host=host,
|
| 1276 |
+
port=port,
|
| 1277 |
+
ssl=ssl,
|
| 1278 |
+
headers=headers,
|
| 1279 |
+
chroma_cloud_api_key=chroma_cloud_api_key,
|
| 1280 |
+
tenant=tenant,
|
| 1281 |
+
database=database,
|
| 1282 |
+
client_settings=client_settings,
|
| 1283 |
+
client=client,
|
| 1284 |
+
collection_metadata=collection_metadata,
|
| 1285 |
+
collection_configuration=collection_configuration,
|
| 1286 |
+
**kwargs,
|
| 1287 |
+
)
|
| 1288 |
+
if ids is None:
|
| 1289 |
+
ids = [str(uuid.uuid4()) for _ in texts]
|
| 1290 |
+
else:
|
| 1291 |
+
ids = [id_ if id_ is not None else str(uuid.uuid4()) for id_ in ids]
|
| 1292 |
+
if hasattr(
|
| 1293 |
+
chroma_collection._client,
|
| 1294 |
+
"get_max_batch_size",
|
| 1295 |
+
) or hasattr( # for Chroma 0.5.1 and above
|
| 1296 |
+
chroma_collection._client,
|
| 1297 |
+
"max_batch_size",
|
| 1298 |
+
): # for Chroma 0.4.10 and above
|
| 1299 |
+
from chromadb.utils.batch_utils import create_batches
|
| 1300 |
+
|
| 1301 |
+
for batch in create_batches(
|
| 1302 |
+
api=chroma_collection._client,
|
| 1303 |
+
ids=ids,
|
| 1304 |
+
metadatas=metadatas, # type: ignore[arg-type]
|
| 1305 |
+
documents=texts,
|
| 1306 |
+
):
|
| 1307 |
+
chroma_collection.add_texts(
|
| 1308 |
+
texts=batch[3] if batch[3] else [],
|
| 1309 |
+
metadatas=batch[2] if batch[2] else None, # type: ignore[arg-type]
|
| 1310 |
+
ids=batch[0],
|
| 1311 |
+
)
|
| 1312 |
+
else:
|
| 1313 |
+
chroma_collection.add_texts(texts=texts, metadatas=metadatas, ids=ids)
|
| 1314 |
+
return chroma_collection
|
| 1315 |
+
|
| 1316 |
+
@classmethod
|
| 1317 |
+
def from_documents(
|
| 1318 |
+
cls: type[Chroma],
|
| 1319 |
+
documents: list[Document],
|
| 1320 |
+
embedding: Optional[Embeddings] = None,
|
| 1321 |
+
ids: Optional[list[str]] = None,
|
| 1322 |
+
collection_name: str = _LANGCHAIN_DEFAULT_COLLECTION_NAME,
|
| 1323 |
+
persist_directory: Optional[str] = None,
|
| 1324 |
+
host: Optional[str] = None,
|
| 1325 |
+
port: Optional[int] = None,
|
| 1326 |
+
headers: Optional[dict[str, str]] = None,
|
| 1327 |
+
chroma_cloud_api_key: Optional[str] = None,
|
| 1328 |
+
tenant: Optional[str] = None,
|
| 1329 |
+
database: Optional[str] = None,
|
| 1330 |
+
client_settings: Optional[chromadb.config.Settings] = None,
|
| 1331 |
+
client: Optional[chromadb.ClientAPI] = None, # Add this line
|
| 1332 |
+
collection_metadata: Optional[dict] = None,
|
| 1333 |
+
collection_configuration: Optional[CreateCollectionConfiguration] = None,
|
| 1334 |
+
*,
|
| 1335 |
+
ssl: bool = False,
|
| 1336 |
+
**kwargs: Any,
|
| 1337 |
+
) -> Chroma:
|
| 1338 |
+
"""Create a Chroma vectorstore from a list of documents.
|
| 1339 |
+
|
| 1340 |
+
If a persist_directory is specified, the collection will be persisted there.
|
| 1341 |
+
Otherwise, the data will be ephemeral in-memory.
|
| 1342 |
+
|
| 1343 |
+
Args:
|
| 1344 |
+
collection_name: Name of the collection to create.
|
| 1345 |
+
persist_directory: Directory to persist the collection.
|
| 1346 |
+
host: Hostname of a deployed Chroma server.
|
| 1347 |
+
port: Connection port for a deployed Chroma server. Default is 8000.
|
| 1348 |
+
ssl: Whether to establish an SSL connection with a deployed Chroma server.
|
| 1349 |
+
Default is False.
|
| 1350 |
+
headers: HTTP headers to send to a deployed Chroma server.
|
| 1351 |
+
chroma_cloud_api_key: Chroma Cloud API key.
|
| 1352 |
+
tenant: Tenant ID. Required for Chroma Cloud connections.
|
| 1353 |
+
Default is 'default_tenant' for local Chroma servers.
|
| 1354 |
+
database: Database name. Required for Chroma Cloud connections.
|
| 1355 |
+
Default is 'default_database'.
|
| 1356 |
+
ids : List of document IDs. Defaults to None.
|
| 1357 |
+
documents: List of documents to add to the vectorstore.
|
| 1358 |
+
embedding: Embedding function. Defaults to None.
|
| 1359 |
+
client_settings: Chroma client settings.
|
| 1360 |
+
client: Chroma client. Documentation:
|
| 1361 |
+
https://docs.trychroma.com/reference/python/client
|
| 1362 |
+
collection_metadata: Collection configurations. Defaults to None.
|
| 1363 |
+
collection_configuration: Index configuration for the collection.
|
| 1364 |
+
Defaults to None.
|
| 1365 |
+
kwargs: Additional keyword arguments to initialize a Chroma client.
|
| 1366 |
+
|
| 1367 |
+
Returns:
|
| 1368 |
+
Chroma: Chroma vectorstore.
|
| 1369 |
+
"""
|
| 1370 |
+
texts = [doc.page_content for doc in documents]
|
| 1371 |
+
metadatas = [doc.metadata for doc in documents]
|
| 1372 |
+
if ids is None:
|
| 1373 |
+
ids = [doc.id if doc.id else str(uuid.uuid4()) for doc in documents]
|
| 1374 |
+
return cls.from_texts(
|
| 1375 |
+
texts=texts,
|
| 1376 |
+
embedding=embedding,
|
| 1377 |
+
metadatas=metadatas,
|
| 1378 |
+
ids=ids,
|
| 1379 |
+
collection_name=collection_name,
|
| 1380 |
+
persist_directory=persist_directory,
|
| 1381 |
+
host=host,
|
| 1382 |
+
port=port,
|
| 1383 |
+
ssl=ssl,
|
| 1384 |
+
headers=headers,
|
| 1385 |
+
chroma_cloud_api_key=chroma_cloud_api_key,
|
| 1386 |
+
tenant=tenant,
|
| 1387 |
+
database=database,
|
| 1388 |
+
client_settings=client_settings,
|
| 1389 |
+
client=client,
|
| 1390 |
+
collection_metadata=collection_metadata,
|
| 1391 |
+
collection_configuration=collection_configuration,
|
| 1392 |
+
**kwargs,
|
| 1393 |
+
)
|
| 1394 |
+
|
| 1395 |
+
def delete(self, ids: Optional[list[str]] = None, **kwargs: Any) -> None:
|
| 1396 |
+
"""Delete by vector IDs.
|
| 1397 |
+
|
| 1398 |
+
Args:
|
| 1399 |
+
ids: List of ids to delete.
|
| 1400 |
+
kwargs: Additional keyword arguments.
|
| 1401 |
+
"""
|
| 1402 |
+
self._collection.delete(ids=ids, **kwargs)
|
prompts.py
CHANGED
|
@@ -32,9 +32,9 @@ def query_prompt(chat_model, think=False):
|
|
| 32 |
# gpt-4o-mini thinks last two months aren't available with this: "Emails from from {start} to {end} are available for retrieval. "
|
| 33 |
f"The emails available for retrieval are from {start} to {end}. "
|
| 34 |
"For questions about differences, changes, or comparisons between X and Y, retrieve emails about X and Y using separate tool calls. "
|
|
|
|
| 35 |
"For general summaries, use retrieve_emails(search_query='R'). "
|
| 36 |
-
"For
|
| 37 |
-
"For questions about years, use retrieve_emails(search_query=<topic>, start_year=, end_year=) (this month is this year). "
|
| 38 |
"For questions about months, use 3-letter abbreviations (Jan...Dec) for the 'month' argument. "
|
| 39 |
"Even if retrieved emails are available, you should retrieve more emails to answer the most recent question. " # Qwen
|
| 40 |
# "You must perform the search yourself. Do not tell the user how to retrieve emails. " # Qwen
|
|
|
|
| 32 |
# gpt-4o-mini thinks last two months aren't available with this: "Emails from from {start} to {end} are available for retrieval. "
|
| 33 |
f"The emails available for retrieval are from {start} to {end}. "
|
| 34 |
"For questions about differences, changes, or comparisons between X and Y, retrieve emails about X and Y using separate tool calls. "
|
| 35 |
+
"Always use retrieve_emails with a non-empty query string for search_query. "
|
| 36 |
"For general summaries, use retrieve_emails(search_query='R'). "
|
| 37 |
+
"For questions about years, use retrieve_emails(search_query=<query>, start_year=, end_year=) (this month is this year). "
|
|
|
|
| 38 |
"For questions about months, use 3-letter abbreviations (Jan...Dec) for the 'month' argument. "
|
| 39 |
"Even if retrieved emails are available, you should retrieve more emails to answer the most recent question. " # Qwen
|
| 40 |
# "You must perform the search yourself. Do not tell the user how to retrieve emails. " # Qwen
|
retriever.py
CHANGED
|
@@ -1,7 +1,9 @@
|
|
| 1 |
# Main retriever modules
|
| 2 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 3 |
from langchain_community.document_loaders import TextLoader
|
| 4 |
-
|
|
|
|
|
|
|
| 5 |
from langchain.retrievers import ParentDocumentRetriever, EnsembleRetriever
|
| 6 |
from langchain_core.documents import Document
|
| 7 |
from langchain_core.retrievers import BaseRetriever, RetrieverLike
|
|
|
|
| 1 |
# Main retriever modules
|
| 2 |
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 3 |
from langchain_community.document_loaders import TextLoader
|
| 4 |
+
|
| 5 |
+
# from langchain_chroma import Chroma
|
| 6 |
+
from mods.langchain_chroma import Chroma
|
| 7 |
from langchain.retrievers import ParentDocumentRetriever, EnsembleRetriever
|
| 8 |
from langchain_core.documents import Document
|
| 9 |
from langchain_core.retrievers import BaseRetriever, RetrieverLike
|