File size: 24,583 Bytes
b3d711f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 | from typing import Optional, Sequence
from types import TracebackType
from uuid import UUID
from overrides import override
import httpx
from chromadb.api import AdminAPI, ClientAPI, ServerAPI
from chromadb.api.collection_configuration import (
CreateCollectionConfiguration,
UpdateCollectionConfiguration,
validate_embedding_function_conflict_on_create,
validate_embedding_function_conflict_on_get,
)
from chromadb.api.shared_system_client import SharedSystemClient
from chromadb.api.types import (
CollectionMetadata,
DataLoader,
Documents,
Embeddable,
EmbeddingFunction,
Embeddings,
GetResult,
IDs,
Include,
Loadable,
Metadatas,
QueryResult,
Schema,
URIs,
IncludeMetadataDocuments,
IncludeMetadataDocumentsDistances,
DefaultEmbeddingFunction,
DeleteResult,
)
from chromadb.auth import UserIdentity
from chromadb.auth.utils import maybe_set_tenant_and_database
from chromadb.config import Settings, System
from chromadb.config import DEFAULT_TENANT, DEFAULT_DATABASE
from chromadb.api.models.Collection import Collection
from chromadb.errors import ChromaAuthError, ChromaError
from chromadb.types import Database, Tenant, Where, WhereDocument
class Client(SharedSystemClient, ClientAPI):
"""A client for Chroma. This is the main entrypoint for interacting with Chroma.
A client internally stores its tenant and database and proxies calls to a
Server API instance of Chroma. It treats the Server API and corresponding System
as a singleton, so multiple clients connecting to the same resource will share the
same API instance.
Client implementations should be implement their own API-caching strategies.
"""
tenant: str = DEFAULT_TENANT
database: str = DEFAULT_DATABASE
_server: ServerAPI
# An internal admin client for verifying that databases and tenants exist
_admin_client: AdminAPI
_closed: bool = False
# region Initialization
def __init__(
self,
tenant: Optional[str] = DEFAULT_TENANT,
database: Optional[str] = DEFAULT_DATABASE,
settings: Settings = Settings(),
) -> None:
super().__init__(settings=settings)
try:
if tenant is not None:
self.tenant = tenant
if database is not None:
self.database = database
# Get the root system component we want to interact with
self._server = self._system.instance(ServerAPI)
user_identity = self.get_user_identity()
maybe_tenant, maybe_database = maybe_set_tenant_and_database(
user_identity,
overwrite_singleton_tenant_database_access_from_auth=settings.chroma_overwrite_singleton_tenant_database_access_from_auth,
user_provided_tenant=tenant,
user_provided_database=database,
)
# this should not happen unless types are invalidated
if maybe_tenant is None and tenant is None:
raise ChromaAuthError(
"Could not determine a tenant from the current authentication method. Please provide a tenant."
)
if maybe_database is None and database is None:
raise ChromaAuthError(
"Could not determine a database name from the current authentication method. Please provide a database name."
)
if maybe_tenant:
self.tenant = maybe_tenant
if maybe_database:
self.database = maybe_database
# Create an admin client for verifying that databases and tenants exist
self._admin_client = AdminClient.from_system(self._system)
self._validate_tenant_database(tenant=self.tenant, database=self.database)
self._submit_client_start_event()
except Exception:
# If init fails after refcount was incremented, release references
# to avoid a resource leak (the caller never receives the object to
# call close() on it).
if hasattr(self, "_admin_client"):
SharedSystemClient._release_system(self._admin_client._identifier)
SharedSystemClient._release_system(self._identifier)
raise
@classmethod
@override
def from_system(
cls,
system: System,
tenant: str = DEFAULT_TENANT,
database: str = DEFAULT_DATABASE,
) -> "Client":
SharedSystemClient._populate_data_from_system(system)
instance = cls(tenant=tenant, database=database, settings=system.settings)
return instance
# endregion
@override
def get_user_identity(self) -> UserIdentity:
try:
return self._server.get_user_identity()
except httpx.ConnectError:
raise ValueError(
"Could not connect to a Chroma server. Are you sure it is running?"
)
# Propagate ChromaErrors
except ChromaError as e:
raise e
except Exception as e:
raise ValueError(str(e))
# region BaseAPI Methods
# Note - we could do this in less verbose ways, but they break type checking
@override
def heartbeat(self) -> int:
"""Return the server time in nanoseconds since epoch."""
return self._server.heartbeat()
@override
def list_collections(
self, limit: Optional[int] = None, offset: Optional[int] = None
) -> Sequence[Collection]:
"""List collections for the current tenant and database, with pagination.
Returns:
Sequence[Collection]: Collection objects for the current tenant.
"""
return [
Collection(client=self._server, model=model)
for model in self._server.list_collections(
limit, offset, tenant=self.tenant, database=self.database
)
]
@override
def count_collections(self) -> int:
"""Return the number of collections in the current database."""
return self._server.count_collections(
tenant=self.tenant, database=self.database
)
@override
def create_collection(
self,
name: str,
schema: Optional[Schema] = None,
configuration: Optional[CreateCollectionConfiguration] = None,
metadata: Optional[CollectionMetadata] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
get_or_create: bool = False,
) -> Collection:
"""Create a collection with optional configuration and metadata.
If using a schema, do not provide `embedding_function`. Instead,
provide the `embedding_function` as part of the schema.
Args:
name: Collection name.
schema: Optional collection schema for indexes and encryption.
configuration: Optional collection configuration.
metadata: Optional collection metadata.
embedding_function: Optional embedding function for the collection.
data_loader: Optional data loader for documents with URIs.
get_or_create: Whether to return an existing collection if present.
Returns:
Collection: The created collection.
Raises:
ValueError: If the embedding function conflicts with configuration.
"""
if configuration is None:
configuration = {}
configuration_ef = configuration.get("embedding_function")
validate_embedding_function_conflict_on_create(
embedding_function, configuration_ef
)
# If ef provided in function params and collection config ef is None,
# set the collection config ef to the function params
if embedding_function is not None and configuration_ef is None:
configuration["embedding_function"] = embedding_function
model = self._server.create_collection(
name=name,
schema=schema,
metadata=metadata,
tenant=self.tenant,
database=self.database,
get_or_create=get_or_create,
configuration=configuration,
)
return Collection(
client=self._server,
model=model,
embedding_function=embedding_function,
data_loader=data_loader,
)
@override
def get_collection(
self,
name: str,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
"""Get a collection by name.
Args:
name: Collection name.
embedding_function: Optional embedding function for the collection.
data_loader: Optional data loader for documents with URIs.
Returns:
Collection: The requested collection.
Raises:
ValueError: If the embedding function conflicts with configuration.
"""
model = self._server.get_collection(
name=name,
tenant=self.tenant,
database=self.database,
)
persisted_ef_config = model.configuration_json.get("embedding_function")
validate_embedding_function_conflict_on_get(
embedding_function, persisted_ef_config
)
return Collection(
client=self._server,
model=model,
embedding_function=embedding_function,
data_loader=data_loader,
)
@override
def get_collection_by_id(
self,
id: UUID,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
"""Get a collection by its ID.
Args:
id: The UUID of the collection.
embedding_function: Optional embedding function for the collection.
data_loader: Optional data loader for documents with URIs.
Returns:
Collection: The requested collection.
Raises:
ValueError: If the embedding function conflicts with configuration.
"""
model = self._server.get_collection_by_id(
collection_id=id,
tenant=self.tenant,
database=self.database,
)
persisted_ef_config = model.configuration_json.get("embedding_function")
validate_embedding_function_conflict_on_get(
embedding_function, persisted_ef_config
)
return Collection(
client=self._server,
model=model,
embedding_function=embedding_function,
data_loader=data_loader,
)
@override
def get_or_create_collection(
self,
name: str,
schema: Optional[Schema] = None,
configuration: Optional[CreateCollectionConfiguration] = None,
metadata: Optional[CollectionMetadata] = None,
embedding_function: Optional[
EmbeddingFunction[Embeddable]
] = DefaultEmbeddingFunction(), # type: ignore
data_loader: Optional[DataLoader[Loadable]] = None,
) -> Collection:
"""Get an existing collection or create a new one.
If the collection does not exist, it will be created. If the collection
already exists, the schema, configuration, and metadata arguments
will be ignored.
Args:
name: Collection name.
schema: Optional collection schema for indexes and encryption.
configuration: Optional collection configuration.
metadata: Optional collection metadata.
embedding_function: Optional embedding function for the collection.
data_loader: Optional data loader for URI-backed data.
Returns:
Collection: The existing or newly created collection.
Raises:
ValueError: If the embedding function does not match the collection's embedding function.
"""
if configuration is None:
configuration = {}
configuration_ef = configuration.get("embedding_function")
validate_embedding_function_conflict_on_create(
embedding_function, configuration_ef
)
if embedding_function is not None and configuration_ef is None:
configuration["embedding_function"] = embedding_function
model = self._server.get_or_create_collection(
name=name,
schema=schema,
metadata=metadata,
tenant=self.tenant,
database=self.database,
configuration=configuration,
)
persisted_ef_config = model.configuration_json.get("embedding_function")
validate_embedding_function_conflict_on_get(
embedding_function, persisted_ef_config
)
return Collection(
client=self._server,
model=model,
embedding_function=embedding_function,
data_loader=data_loader,
)
@override
def _modify(
self,
id: UUID,
new_name: Optional[str] = None,
new_metadata: Optional[CollectionMetadata] = None,
new_configuration: Optional[UpdateCollectionConfiguration] = None,
) -> None:
return self._server._modify(
id=id,
tenant=self.tenant,
database=self.database,
new_name=new_name,
new_metadata=new_metadata,
new_configuration=new_configuration,
)
@override
def delete_collection(
self,
name: str,
) -> None:
return self._server.delete_collection(
name=name,
tenant=self.tenant,
database=self.database,
)
#
# ITEM METHODS
#
@override
def _add(
self,
ids: IDs,
collection_id: UUID,
embeddings: Embeddings,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._add(
ids=ids,
tenant=self.tenant,
database=self.database,
collection_id=collection_id,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
@override
def _update(
self,
collection_id: UUID,
ids: IDs,
embeddings: Optional[Embeddings] = None,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._update(
collection_id=collection_id,
tenant=self.tenant,
database=self.database,
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
@override
def _upsert(
self,
collection_id: UUID,
ids: IDs,
embeddings: Embeddings,
metadatas: Optional[Metadatas] = None,
documents: Optional[Documents] = None,
uris: Optional[URIs] = None,
) -> bool:
return self._server._upsert(
collection_id=collection_id,
tenant=self.tenant,
database=self.database,
ids=ids,
embeddings=embeddings,
metadatas=metadatas,
documents=documents,
uris=uris,
)
@override
def _count(self, collection_id: UUID) -> int:
return self._server._count(
collection_id=collection_id,
tenant=self.tenant,
database=self.database,
)
@override
def _peek(self, collection_id: UUID, n: int = 10) -> GetResult:
return self._server._peek(
collection_id=collection_id,
n=n,
tenant=self.tenant,
database=self.database,
)
@override
def _get(
self,
collection_id: UUID,
ids: Optional[IDs] = None,
where: Optional[Where] = None,
limit: Optional[int] = None,
offset: Optional[int] = None,
where_document: Optional[WhereDocument] = None,
include: Include = IncludeMetadataDocuments,
) -> GetResult:
return self._server._get(
collection_id=collection_id,
tenant=self.tenant,
database=self.database,
ids=ids,
where=where,
limit=limit,
offset=offset,
where_document=where_document,
include=include,
)
def _delete(
self,
collection_id: UUID,
ids: Optional[IDs],
where: Optional[Where] = None,
where_document: Optional[WhereDocument] = None,
limit: Optional[int] = None,
) -> DeleteResult:
return self._server._delete(
collection_id=collection_id,
tenant=self.tenant,
database=self.database,
ids=ids,
where=where,
where_document=where_document,
limit=limit,
)
@override
def _query(
self,
collection_id: UUID,
query_embeddings: Embeddings,
ids: Optional[IDs] = None,
n_results: int = 10,
where: Optional[Where] = None,
where_document: Optional[WhereDocument] = None,
include: Include = IncludeMetadataDocumentsDistances,
) -> QueryResult:
return self._server._query(
collection_id=collection_id,
ids=ids,
tenant=self.tenant,
database=self.database,
query_embeddings=query_embeddings,
n_results=n_results,
where=where,
where_document=where_document,
include=include,
)
@override
def reset(self) -> bool:
return self._server.reset()
@override
def get_version(self) -> str:
return self._server.get_version()
@override
def get_settings(self) -> Settings:
return self._server.get_settings()
@override
def get_max_batch_size(self) -> int:
return self._server.get_max_batch_size()
# endregion
# region ClientAPI Methods
@override
def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
self._validate_tenant_database(tenant=tenant, database=database)
self.tenant = tenant
self.database = database
@override
def set_database(self, database: str) -> None:
self._validate_tenant_database(tenant=self.tenant, database=database)
self.database = database
def close(self) -> None:
"""Close the client and release all resources.
This method decrements the reference count for the underlying System.
When the last client using a shared System calls close(), the System
is stopped and all resources (database connections, etc.) are released.
This is particularly important for PersistentClient to avoid SQLite
file locking issues.
Note: If multiple clients share the same System (e.g., multiple PersistentClient
instances with the same path), the System will only be stopped when the last
client is closed. This allows safe use of context managers with multiple clients.
Example:
>>> client = chromadb.PersistentClient(path="./chroma_db")
>>> # ... use client ...
>>> client.close()
Or using context manager:
>>> with chromadb.PersistentClient(path="./chroma_db") as client:
... # ... use client ...
"""
# Make close() idempotent - a second call is a safe no-op
if self._closed:
return
self._closed = True
# Release the internal admin client's reference first, since it also
# incremented the refcount for the shared system on creation.
if hasattr(self, "_admin_client"):
SharedSystemClient._release_system(self._admin_client._identifier)
# Release our own reference; stops system if this was the last client
SharedSystemClient._release_system(self._identifier)
def __enter__(self) -> "Client":
"""Context manager entry."""
return self
def __exit__(
self,
exc_type: Optional[type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
"""Context manager exit."""
self.close()
def _validate_tenant_database(self, tenant: str, database: str) -> None:
try:
self._admin_client.get_tenant(name=tenant)
except httpx.ConnectError:
raise ValueError(
"Could not connect to a Chroma server. Are you sure it is running?"
)
# Propagate ChromaErrors
except ChromaError as e:
raise e
except Exception:
raise ValueError(
f"Could not connect to tenant {tenant}. Are you sure it exists?"
)
try:
self._admin_client.get_database(name=database, tenant=tenant)
except httpx.ConnectError:
raise ValueError(
"Could not connect to a Chroma server. Are you sure it is running?"
)
# endregion
class AdminClient(SharedSystemClient, AdminAPI):
"""Admin client for managing tenants and databases."""
_server: ServerAPI
def __init__(self, settings: Settings = Settings()) -> None:
super().__init__(settings)
self._server = self._system.instance(ServerAPI)
@override
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
"""Create a database in a tenant.
Args:
name: Database name.
tenant: Tenant that owns the database.
"""
return self._server.create_database(name=name, tenant=tenant)
@override
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
"""Get a database by name.
Args:
name: Database name.
tenant: Tenant that owns the database.
Returns:
Database: The database record.
"""
return self._server.get_database(name=name, tenant=tenant)
@override
def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
"""Delete a database by name.
Args:
name: Database name.
tenant: Tenant that owns the database.
"""
return self._server.delete_database(name=name, tenant=tenant)
@override
def list_databases(
self,
limit: Optional[int] = None,
offset: Optional[int] = None,
tenant: str = DEFAULT_TENANT,
) -> Sequence[Database]:
return self._server.list_databases(limit, offset, tenant=tenant)
@override
def create_tenant(self, name: str) -> None:
return self._server.create_tenant(name=name)
@override
def get_tenant(self, name: str) -> Tenant:
return self._server.get_tenant(name=name)
@classmethod
@override
def from_system(
cls,
system: System,
) -> "AdminClient":
SharedSystemClient._populate_data_from_system(system)
instance = cls(settings=system.settings)
return instance
|