Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/licenses/LICENSE +201 -0
- python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/sboms/chromadb_rust_bindings.cyclonedx.json +0 -0
- python/user_packages/Python313/site-packages/chromadb/__pycache__/__init__.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/__pycache__/app.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/__pycache__/base_types.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/__pycache__/config.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/__pycache__/errors.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/__pycache__/serde.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/__pycache__/types.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/api/__init__.py +973 -0
- python/user_packages/Python313/site-packages/chromadb/api/async_api.py +850 -0
- python/user_packages/Python313/site-packages/chromadb/api/async_client.py +569 -0
- python/user_packages/Python313/site-packages/chromadb/api/async_fastapi.py +848 -0
- python/user_packages/Python313/site-packages/chromadb/api/base_http_client.py +145 -0
- python/user_packages/Python313/site-packages/chromadb/api/client.py +731 -0
- python/user_packages/Python313/site-packages/chromadb/api/collection_configuration.py +882 -0
- python/user_packages/Python313/site-packages/chromadb/api/configuration.py +410 -0
- python/user_packages/Python313/site-packages/chromadb/api/fastapi.py +915 -0
- python/user_packages/Python313/site-packages/chromadb/api/functions.py +33 -0
- python/user_packages/Python313/site-packages/chromadb/api/rust.py +704 -0
- python/user_packages/Python313/site-packages/chromadb/api/segment.py +1127 -0
- python/user_packages/Python313/site-packages/chromadb/api/shared_system_client.py +193 -0
- python/user_packages/Python313/site-packages/chromadb/api/types.py +0 -0
- python/user_packages/Python313/site-packages/chromadb/auth/__init__.py +237 -0
- python/user_packages/Python313/site-packages/chromadb/cli/__init__.py +0 -0
- python/user_packages/Python313/site-packages/chromadb/cli/cli.py +56 -0
- python/user_packages/Python313/site-packages/chromadb/cli/utils.py +40 -0
- python/user_packages/Python313/site-packages/chromadb/db/__init__.py +122 -0
- python/user_packages/Python313/site-packages/chromadb/db/base.py +180 -0
- python/user_packages/Python313/site-packages/chromadb/db/migrations.py +276 -0
- python/user_packages/Python313/site-packages/chromadb/db/system.py +189 -0
- python/user_packages/Python313/site-packages/chromadb/execution/__init__.py +0 -0
- python/user_packages/Python313/site-packages/chromadb/experimental/density_relevance.ipynb +0 -0
- python/user_packages/Python313/site-packages/chromadb/ingest/__init__.py +121 -0
- python/user_packages/Python313/site-packages/chromadb/logservice/logservice.py +181 -0
- python/user_packages/Python313/site-packages/chromadb/migrations/__init__.py +0 -0
- python/user_packages/Python313/site-packages/chromadb/proto/.gitignore +2 -0
- python/user_packages/Python313/site-packages/chromadb/proto/__init__.py +0 -0
- python/user_packages/Python313/site-packages/chromadb/proto/convert.py +688 -0
- python/user_packages/Python313/site-packages/chromadb/proto/utils.py +68 -0
- python/user_packages/Python313/site-packages/chromadb/quota/__init__.py +71 -0
- python/user_packages/Python313/site-packages/chromadb/rate_limit/__init__.py +36 -0
- python/user_packages/Python313/site-packages/chromadb/segment/__init__.py +125 -0
- python/user_packages/Python313/site-packages/chromadb/server/__init__.py +9 -0
- python/user_packages/Python313/site-packages/chromadb/telemetry/README.md +10 -0
- python/user_packages/Python313/site-packages/chromadb/telemetry/__init__.py +0 -0
- python/user_packages/Python313/site-packages/chromadb/test/__init__.py +0 -0
- python/user_packages/Python313/site-packages/chromadb/test/__pycache__/__init__.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/test/__pycache__/conftest.cpython-313.pyc +0 -0
- python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_chroma.cpython-313.pyc +0 -0
python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/licenses/LICENSE
ADDED
|
@@ -0,0 +1,201 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
python/user_packages/Python313/site-packages/chromadb-1.5.9.dist-info/sboms/chromadb_rust_bindings.cyclonedx.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
python/user_packages/Python313/site-packages/chromadb/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (14.6 kB). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/__pycache__/app.cpython-313.pyc
ADDED
|
Binary file (466 Bytes). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/__pycache__/base_types.cpython-313.pyc
ADDED
|
Binary file (7.67 kB). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/__pycache__/config.cpython-313.pyc
ADDED
|
Binary file (20.6 kB). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/__pycache__/errors.cpython-313.pyc
ADDED
|
Binary file (8.84 kB). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/__pycache__/serde.cpython-313.pyc
ADDED
|
Binary file (2.94 kB). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/__pycache__/types.cpython-313.pyc
ADDED
|
Binary file (13.9 kB). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/api/__init__.py
ADDED
|
@@ -0,0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 |
+
NotRegex,
|
| 19 |
+
Contains,
|
| 20 |
+
NotContains,
|
| 21 |
+
Limit,
|
| 22 |
+
Select,
|
| 23 |
+
Rank,
|
| 24 |
+
Abs,
|
| 25 |
+
Div,
|
| 26 |
+
Exp,
|
| 27 |
+
Log,
|
| 28 |
+
Max,
|
| 29 |
+
Min,
|
| 30 |
+
Mul,
|
| 31 |
+
Knn,
|
| 32 |
+
Rrf,
|
| 33 |
+
Sub,
|
| 34 |
+
Sum,
|
| 35 |
+
Val,
|
| 36 |
+
Aggregate,
|
| 37 |
+
MinK,
|
| 38 |
+
MaxK,
|
| 39 |
+
GroupBy,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
from abc import ABC, abstractmethod
|
| 43 |
+
from typing import Sequence, Optional, List, Dict, Any, Tuple
|
| 44 |
+
from uuid import UUID
|
| 45 |
+
|
| 46 |
+
from overrides import override
|
| 47 |
+
from chromadb.api.collection_configuration import (
|
| 48 |
+
CreateCollectionConfiguration,
|
| 49 |
+
UpdateCollectionConfiguration,
|
| 50 |
+
)
|
| 51 |
+
from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT
|
| 52 |
+
from chromadb.api.types import (
|
| 53 |
+
CollectionMetadata,
|
| 54 |
+
DeleteResult,
|
| 55 |
+
Documents,
|
| 56 |
+
Embeddable,
|
| 57 |
+
EmbeddingFunction,
|
| 58 |
+
DataLoader,
|
| 59 |
+
Embeddings,
|
| 60 |
+
IDs,
|
| 61 |
+
Include,
|
| 62 |
+
IncludeMetadataDocumentsDistances,
|
| 63 |
+
IncludeMetadataDocuments,
|
| 64 |
+
Loadable,
|
| 65 |
+
Metadatas,
|
| 66 |
+
ReadLevel,
|
| 67 |
+
Schema,
|
| 68 |
+
URIs,
|
| 69 |
+
Where,
|
| 70 |
+
QueryResult,
|
| 71 |
+
GetResult,
|
| 72 |
+
WhereDocument,
|
| 73 |
+
SearchResult,
|
| 74 |
+
DefaultEmbeddingFunction,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
from chromadb.auth import UserIdentity
|
| 78 |
+
from chromadb.config import Component, Settings
|
| 79 |
+
from chromadb.types import Database, Tenant, Collection as CollectionModel
|
| 80 |
+
from chromadb.api.models.Collection import Collection
|
| 81 |
+
from chromadb.api.models.AttachedFunction import AttachedFunction
|
| 82 |
+
|
| 83 |
+
# Re-export the async version
|
| 84 |
+
from chromadb.api.async_api import ( # noqa: F401
|
| 85 |
+
AsyncBaseAPI as AsyncBaseAPI,
|
| 86 |
+
AsyncClientAPI as AsyncClientAPI,
|
| 87 |
+
AsyncAdminAPI as AsyncAdminAPI,
|
| 88 |
+
AsyncServerAPI as AsyncServerAPI,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class BaseAPI(ABC):
|
| 93 |
+
@abstractmethod
|
| 94 |
+
def heartbeat(self) -> int:
|
| 95 |
+
"""Get the current time in nanoseconds since epoch.
|
| 96 |
+
Used to check if the server is alive.
|
| 97 |
+
|
| 98 |
+
Returns:
|
| 99 |
+
int: The current time in nanoseconds since epoch
|
| 100 |
+
|
| 101 |
+
"""
|
| 102 |
+
pass
|
| 103 |
+
|
| 104 |
+
#
|
| 105 |
+
# COLLECTION METHODS
|
| 106 |
+
#
|
| 107 |
+
@abstractmethod
|
| 108 |
+
def count_collections(self) -> int:
|
| 109 |
+
"""Count the number of collections.
|
| 110 |
+
|
| 111 |
+
Returns:
|
| 112 |
+
int: The number of collections.
|
| 113 |
+
|
| 114 |
+
Examples:
|
| 115 |
+
```python
|
| 116 |
+
client.count_collections()
|
| 117 |
+
# 1
|
| 118 |
+
```
|
| 119 |
+
"""
|
| 120 |
+
pass
|
| 121 |
+
|
| 122 |
+
def _modify(
|
| 123 |
+
self,
|
| 124 |
+
id: UUID,
|
| 125 |
+
new_name: Optional[str] = None,
|
| 126 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 127 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 128 |
+
) -> None:
|
| 129 |
+
"""[Internal] Modify a collection by UUID. Can update the name and/or metadata.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
id: The internal UUID of the collection to modify.
|
| 133 |
+
new_name: The new name of the collection.
|
| 134 |
+
If None, the existing name will remain. Defaults to None.
|
| 135 |
+
new_metadata: The new metadata to associate with the collection.
|
| 136 |
+
Defaults to None.
|
| 137 |
+
new_configuration: The new configuration to associate with the collection.
|
| 138 |
+
Defaults to None.
|
| 139 |
+
"""
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
@abstractmethod
|
| 143 |
+
def delete_collection(
|
| 144 |
+
self,
|
| 145 |
+
name: str,
|
| 146 |
+
) -> None:
|
| 147 |
+
"""Delete a collection with the given name.
|
| 148 |
+
Args:
|
| 149 |
+
name: The name of the collection to delete.
|
| 150 |
+
|
| 151 |
+
Raises:
|
| 152 |
+
ValueError: If the collection does not exist.
|
| 153 |
+
|
| 154 |
+
Examples:
|
| 155 |
+
```python
|
| 156 |
+
client.delete_collection("my_collection")
|
| 157 |
+
```
|
| 158 |
+
"""
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
#
|
| 162 |
+
# ITEM METHODS
|
| 163 |
+
#
|
| 164 |
+
|
| 165 |
+
@abstractmethod
|
| 166 |
+
def _add(
|
| 167 |
+
self,
|
| 168 |
+
ids: IDs,
|
| 169 |
+
collection_id: UUID,
|
| 170 |
+
embeddings: Embeddings,
|
| 171 |
+
metadatas: Optional[Metadatas] = None,
|
| 172 |
+
documents: Optional[Documents] = None,
|
| 173 |
+
uris: Optional[URIs] = None,
|
| 174 |
+
) -> bool:
|
| 175 |
+
"""[Internal] Add embeddings to a collection specified by UUID.
|
| 176 |
+
If (some) ids already exist, only the new embeddings will be added.
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
ids: The ids to associate with the embeddings.
|
| 180 |
+
collection_id: The UUID of the collection to add the embeddings to.
|
| 181 |
+
embedding: The sequence of embeddings to add.
|
| 182 |
+
metadata: The metadata to associate with the embeddings. Defaults to None.
|
| 183 |
+
documents: The documents to associate with the embeddings. Defaults to None.
|
| 184 |
+
uris: URIs of data sources for each embedding. Defaults to None.
|
| 185 |
+
|
| 186 |
+
Returns:
|
| 187 |
+
True if the embeddings were added successfully.
|
| 188 |
+
"""
|
| 189 |
+
pass
|
| 190 |
+
|
| 191 |
+
@abstractmethod
|
| 192 |
+
def _update(
|
| 193 |
+
self,
|
| 194 |
+
collection_id: UUID,
|
| 195 |
+
ids: IDs,
|
| 196 |
+
embeddings: Optional[Embeddings] = None,
|
| 197 |
+
metadatas: Optional[Metadatas] = None,
|
| 198 |
+
documents: Optional[Documents] = None,
|
| 199 |
+
uris: Optional[URIs] = None,
|
| 200 |
+
) -> bool:
|
| 201 |
+
"""[Internal] Update entries in a collection specified by UUID.
|
| 202 |
+
|
| 203 |
+
Args:
|
| 204 |
+
collection_id: The UUID of the collection to update the embeddings in.
|
| 205 |
+
ids: The IDs of the entries to update.
|
| 206 |
+
embeddings: The sequence of embeddings to update. Defaults to None.
|
| 207 |
+
metadatas: The metadata to associate with the embeddings. Defaults to None.
|
| 208 |
+
documents: The documents to associate with the embeddings. Defaults to None.
|
| 209 |
+
uris: URIs of data sources for each embedding. Defaults to None.
|
| 210 |
+
Returns:
|
| 211 |
+
True if the embeddings were updated successfully.
|
| 212 |
+
"""
|
| 213 |
+
pass
|
| 214 |
+
|
| 215 |
+
@abstractmethod
|
| 216 |
+
def _upsert(
|
| 217 |
+
self,
|
| 218 |
+
collection_id: UUID,
|
| 219 |
+
ids: IDs,
|
| 220 |
+
embeddings: Embeddings,
|
| 221 |
+
metadatas: Optional[Metadatas] = None,
|
| 222 |
+
documents: Optional[Documents] = None,
|
| 223 |
+
uris: Optional[URIs] = None,
|
| 224 |
+
) -> bool:
|
| 225 |
+
"""[Internal] Add or update entries in the a collection specified by UUID.
|
| 226 |
+
If an entry with the same id already exists, it will be updated,
|
| 227 |
+
otherwise it will be added.
|
| 228 |
+
|
| 229 |
+
Args:
|
| 230 |
+
collection_id: The collection to add the embeddings to
|
| 231 |
+
ids: The ids to associate with the embeddings. Defaults to None.
|
| 232 |
+
embeddings: The sequence of embeddings to add
|
| 233 |
+
metadatas: The metadata to associate with the embeddings. Defaults to None.
|
| 234 |
+
documents: The documents to associate with the embeddings. Defaults to None.
|
| 235 |
+
uris: URIs of data sources for each embedding. Defaults to None.
|
| 236 |
+
"""
|
| 237 |
+
pass
|
| 238 |
+
|
| 239 |
+
@abstractmethod
|
| 240 |
+
def _count(self, collection_id: UUID) -> int:
|
| 241 |
+
"""[Internal] Returns the number of entries in a collection specified by UUID.
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
collection_id: The UUID of the collection to count the embeddings in.
|
| 245 |
+
|
| 246 |
+
Returns:
|
| 247 |
+
int: The number of embeddings in the collection
|
| 248 |
+
|
| 249 |
+
"""
|
| 250 |
+
pass
|
| 251 |
+
|
| 252 |
+
@abstractmethod
|
| 253 |
+
def _peek(self, collection_id: UUID, n: int = 10) -> GetResult:
|
| 254 |
+
"""[Internal] Returns the first n entries in a collection specified by UUID.
|
| 255 |
+
|
| 256 |
+
Args:
|
| 257 |
+
collection_id: The UUID of the collection to peek into.
|
| 258 |
+
n: The number of entries to peek. Defaults to 10.
|
| 259 |
+
|
| 260 |
+
Returns:
|
| 261 |
+
GetResult: The first n entries in the collection.
|
| 262 |
+
|
| 263 |
+
"""
|
| 264 |
+
|
| 265 |
+
pass
|
| 266 |
+
|
| 267 |
+
@abstractmethod
|
| 268 |
+
def _get(
|
| 269 |
+
self,
|
| 270 |
+
collection_id: UUID,
|
| 271 |
+
ids: Optional[IDs] = None,
|
| 272 |
+
where: Optional[Where] = None,
|
| 273 |
+
limit: Optional[int] = None,
|
| 274 |
+
offset: Optional[int] = None,
|
| 275 |
+
where_document: Optional[WhereDocument] = None,
|
| 276 |
+
include: Include = IncludeMetadataDocuments,
|
| 277 |
+
) -> GetResult:
|
| 278 |
+
"""[Internal] Returns entries from a collection specified by UUID.
|
| 279 |
+
|
| 280 |
+
Args:
|
| 281 |
+
ids: The IDs of the entries to get. Defaults to None.
|
| 282 |
+
where: Conditional filtering on metadata. Defaults to None.
|
| 283 |
+
limit: The maximum number of entries to return. Defaults to None.
|
| 284 |
+
offset: The number of entries to skip before returning. Defaults to None.
|
| 285 |
+
where_document: Conditional filtering on documents. Defaults to None.
|
| 286 |
+
include: The fields to include in the response.
|
| 287 |
+
Defaults to ["metadatas", "documents"].
|
| 288 |
+
Returns:
|
| 289 |
+
GetResult: The entries in the collection that match the query.
|
| 290 |
+
|
| 291 |
+
"""
|
| 292 |
+
pass
|
| 293 |
+
|
| 294 |
+
@abstractmethod
|
| 295 |
+
def _delete(
|
| 296 |
+
self,
|
| 297 |
+
collection_id: UUID,
|
| 298 |
+
ids: Optional[IDs],
|
| 299 |
+
where: Optional[Where] = None,
|
| 300 |
+
where_document: Optional[WhereDocument] = None,
|
| 301 |
+
limit: Optional[int] = None,
|
| 302 |
+
) -> DeleteResult:
|
| 303 |
+
"""[Internal] Deletes entries from a collection specified by UUID.
|
| 304 |
+
|
| 305 |
+
Args:
|
| 306 |
+
collection_id: The UUID of the collection to delete the entries from.
|
| 307 |
+
ids: The IDs of the entries to delete. Defaults to None.
|
| 308 |
+
where: Conditional filtering on metadata. Defaults to None.
|
| 309 |
+
where_document: Conditional filtering on documents. Defaults to None.
|
| 310 |
+
limit: Maximum number of records to delete. Can only be used with
|
| 311 |
+
where or where_document. Defaults to None (no limit).
|
| 312 |
+
|
| 313 |
+
Returns:
|
| 314 |
+
DeleteResult: A dict containing the number of records deleted.
|
| 315 |
+
"""
|
| 316 |
+
pass
|
| 317 |
+
|
| 318 |
+
@abstractmethod
|
| 319 |
+
def _query(
|
| 320 |
+
self,
|
| 321 |
+
collection_id: UUID,
|
| 322 |
+
query_embeddings: Embeddings,
|
| 323 |
+
ids: Optional[IDs] = None,
|
| 324 |
+
n_results: int = 10,
|
| 325 |
+
where: Optional[Where] = None,
|
| 326 |
+
where_document: Optional[WhereDocument] = None,
|
| 327 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 328 |
+
) -> QueryResult:
|
| 329 |
+
"""[Internal] Performs a nearest neighbors query on a collection specified by UUID.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
collection_id: The UUID of the collection to query.
|
| 333 |
+
query_embeddings: The embeddings to use as the query.
|
| 334 |
+
ids: The IDs to filter by during the query. Defaults to None.
|
| 335 |
+
n_results: The number of results to return. Defaults to 10.
|
| 336 |
+
where: Conditional filtering on metadata. Defaults to None.
|
| 337 |
+
where_document: Conditional filtering on documents. Defaults to None.
|
| 338 |
+
include: The fields to include in the response.
|
| 339 |
+
Defaults to ["metadatas", "documents", "distances"].
|
| 340 |
+
|
| 341 |
+
Returns:
|
| 342 |
+
QueryResult: The results of the query.
|
| 343 |
+
"""
|
| 344 |
+
pass
|
| 345 |
+
|
| 346 |
+
@abstractmethod
|
| 347 |
+
def reset(self) -> bool:
|
| 348 |
+
"""Resets the database. This will delete all collections and entries.
|
| 349 |
+
|
| 350 |
+
Returns:
|
| 351 |
+
bool: True if the database was reset successfully.
|
| 352 |
+
"""
|
| 353 |
+
pass
|
| 354 |
+
|
| 355 |
+
@abstractmethod
|
| 356 |
+
def get_version(self) -> str:
|
| 357 |
+
"""Get the version of Chroma.
|
| 358 |
+
|
| 359 |
+
Returns:
|
| 360 |
+
str: The version of Chroma
|
| 361 |
+
|
| 362 |
+
"""
|
| 363 |
+
pass
|
| 364 |
+
|
| 365 |
+
@abstractmethod
|
| 366 |
+
def get_settings(self) -> Settings:
|
| 367 |
+
"""Get the settings used to initialize.
|
| 368 |
+
|
| 369 |
+
Returns:
|
| 370 |
+
Settings: The settings used to initialize.
|
| 371 |
+
|
| 372 |
+
"""
|
| 373 |
+
pass
|
| 374 |
+
|
| 375 |
+
@abstractmethod
|
| 376 |
+
def get_max_batch_size(self) -> int:
|
| 377 |
+
"""Return the maximum number of records that can be created or mutated in a single call."""
|
| 378 |
+
pass
|
| 379 |
+
|
| 380 |
+
@abstractmethod
|
| 381 |
+
def get_user_identity(self) -> UserIdentity:
|
| 382 |
+
"""Resolve the tenant and databases for the client. Returns the default
|
| 383 |
+
values if can't be resolved.
|
| 384 |
+
|
| 385 |
+
"""
|
| 386 |
+
pass
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class ClientAPI(BaseAPI, ABC):
|
| 390 |
+
tenant: str
|
| 391 |
+
database: str
|
| 392 |
+
|
| 393 |
+
@abstractmethod
|
| 394 |
+
def list_collections(
|
| 395 |
+
self,
|
| 396 |
+
limit: Optional[int] = None,
|
| 397 |
+
offset: Optional[int] = None,
|
| 398 |
+
) -> Sequence[Collection]:
|
| 399 |
+
"""List all collections.
|
| 400 |
+
Args:
|
| 401 |
+
limit: The maximum number of entries to return. Defaults to None.
|
| 402 |
+
offset: The number of entries to skip before returning. Defaults to None.
|
| 403 |
+
|
| 404 |
+
Returns:
|
| 405 |
+
Sequence[Collection]: A list of collections
|
| 406 |
+
|
| 407 |
+
Examples:
|
| 408 |
+
```python
|
| 409 |
+
client.list_collections()
|
| 410 |
+
# [collection(name="my_collection", metadata={})]
|
| 411 |
+
```
|
| 412 |
+
"""
|
| 413 |
+
pass
|
| 414 |
+
|
| 415 |
+
@abstractmethod
|
| 416 |
+
def create_collection(
|
| 417 |
+
self,
|
| 418 |
+
name: str,
|
| 419 |
+
schema: Optional[Schema] = None,
|
| 420 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 421 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 422 |
+
embedding_function: Optional[
|
| 423 |
+
EmbeddingFunction[Embeddable]
|
| 424 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 425 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 426 |
+
get_or_create: bool = False,
|
| 427 |
+
) -> Collection:
|
| 428 |
+
"""Create a new collection with the given name and metadata.
|
| 429 |
+
Args:
|
| 430 |
+
name: The name of the collection to create.
|
| 431 |
+
metadata: Optional metadata to associate with the collection.
|
| 432 |
+
embedding_function: Optional function to use to embed documents.
|
| 433 |
+
Uses the default embedding function if not provided.
|
| 434 |
+
get_or_create: If True, return the existing collection if it exists.
|
| 435 |
+
data_loader: Optional function to use to load records (documents, images, etc.)
|
| 436 |
+
|
| 437 |
+
Returns:
|
| 438 |
+
Collection: The newly created collection.
|
| 439 |
+
|
| 440 |
+
Raises:
|
| 441 |
+
ValueError: If the collection already exists and get_or_create is False.
|
| 442 |
+
ValueError: If the collection name is invalid.
|
| 443 |
+
|
| 444 |
+
Examples:
|
| 445 |
+
```python
|
| 446 |
+
client.create_collection("my_collection")
|
| 447 |
+
# collection(name="my_collection", metadata={})
|
| 448 |
+
|
| 449 |
+
client.create_collection("my_collection", metadata={"foo": "bar"})
|
| 450 |
+
# collection(name="my_collection", metadata={"foo": "bar"})
|
| 451 |
+
```
|
| 452 |
+
"""
|
| 453 |
+
pass
|
| 454 |
+
|
| 455 |
+
@abstractmethod
|
| 456 |
+
def get_collection(
|
| 457 |
+
self,
|
| 458 |
+
name: str,
|
| 459 |
+
embedding_function: Optional[
|
| 460 |
+
EmbeddingFunction[Embeddable]
|
| 461 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 462 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 463 |
+
) -> Collection:
|
| 464 |
+
"""Get a collection with the given name.
|
| 465 |
+
Args:
|
| 466 |
+
name: The name of the collection to get
|
| 467 |
+
embedding_function: Optional function to use to embed documents.
|
| 468 |
+
Uses the default embedding function if not provided.
|
| 469 |
+
data_loader: Optional function to use to load records (documents, images, etc.)
|
| 470 |
+
|
| 471 |
+
Returns:
|
| 472 |
+
Collection: The collection
|
| 473 |
+
|
| 474 |
+
Raises:
|
| 475 |
+
ValueError: If the collection does not exist
|
| 476 |
+
|
| 477 |
+
Examples:
|
| 478 |
+
```python
|
| 479 |
+
client.get_collection("my_collection")
|
| 480 |
+
# collection(name="my_collection", metadata={})
|
| 481 |
+
```
|
| 482 |
+
"""
|
| 483 |
+
pass
|
| 484 |
+
|
| 485 |
+
@abstractmethod
|
| 486 |
+
def get_collection_by_id(
|
| 487 |
+
self,
|
| 488 |
+
id: UUID,
|
| 489 |
+
embedding_function: Optional[
|
| 490 |
+
EmbeddingFunction[Embeddable]
|
| 491 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 492 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 493 |
+
) -> Collection:
|
| 494 |
+
"""Get a collection by its ID.
|
| 495 |
+
|
| 496 |
+
Args:
|
| 497 |
+
id: The UUID of the collection to get.
|
| 498 |
+
embedding_function: Optional function to use to embed documents.
|
| 499 |
+
Uses the default embedding function if not provided.
|
| 500 |
+
data_loader: Optional function to use to load records (documents, images, etc.)
|
| 501 |
+
|
| 502 |
+
Returns:
|
| 503 |
+
Collection: The collection
|
| 504 |
+
|
| 505 |
+
Raises:
|
| 506 |
+
NotFoundError: If no collection with the given ID exists.
|
| 507 |
+
|
| 508 |
+
Examples:
|
| 509 |
+
```python
|
| 510 |
+
client.get_collection_by_id(uuid.UUID("..."))
|
| 511 |
+
# collection(name="my_collection", metadata={})
|
| 512 |
+
```
|
| 513 |
+
"""
|
| 514 |
+
pass
|
| 515 |
+
|
| 516 |
+
@abstractmethod
|
| 517 |
+
def get_or_create_collection(
|
| 518 |
+
self,
|
| 519 |
+
name: str,
|
| 520 |
+
schema: Optional[Schema] = None,
|
| 521 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 522 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 523 |
+
embedding_function: Optional[
|
| 524 |
+
EmbeddingFunction[Embeddable]
|
| 525 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 526 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 527 |
+
) -> Collection:
|
| 528 |
+
"""Get or create a collection with the given name and metadata.
|
| 529 |
+
Args:
|
| 530 |
+
name: The name of the collection to get or create
|
| 531 |
+
metadata: Optional metadata to associate with the collection. If
|
| 532 |
+
the collection already exists, the metadata provided is ignored.
|
| 533 |
+
If the collection does not exist, the new collection will be created
|
| 534 |
+
with the provided metadata.
|
| 535 |
+
embedding_function: Optional function to use to embed documents
|
| 536 |
+
data_loader: Optional function to use to load records (documents, images, etc.)
|
| 537 |
+
|
| 538 |
+
Returns:
|
| 539 |
+
The collection
|
| 540 |
+
|
| 541 |
+
Examples:
|
| 542 |
+
```python
|
| 543 |
+
client.get_or_create_collection("my_collection")
|
| 544 |
+
# collection(name="my_collection", metadata={})
|
| 545 |
+
```
|
| 546 |
+
"""
|
| 547 |
+
pass
|
| 548 |
+
|
| 549 |
+
@abstractmethod
|
| 550 |
+
def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
|
| 551 |
+
"""Set the tenant and database for the client. Raises an error if the tenant or
|
| 552 |
+
database does not exist.
|
| 553 |
+
|
| 554 |
+
Args:
|
| 555 |
+
tenant: The tenant to set.
|
| 556 |
+
database: The database to set.
|
| 557 |
+
|
| 558 |
+
"""
|
| 559 |
+
pass
|
| 560 |
+
|
| 561 |
+
@abstractmethod
|
| 562 |
+
def set_database(self, database: str) -> None:
|
| 563 |
+
"""Set the database for the client. Raises an error if the database does not exist.
|
| 564 |
+
|
| 565 |
+
Args:
|
| 566 |
+
database: The database to set.
|
| 567 |
+
|
| 568 |
+
"""
|
| 569 |
+
pass
|
| 570 |
+
|
| 571 |
+
@staticmethod
|
| 572 |
+
@abstractmethod
|
| 573 |
+
def clear_system_cache() -> None:
|
| 574 |
+
"""Clear the system cache so that new systems can be created for an existing path.
|
| 575 |
+
This should only be used for testing purposes."""
|
| 576 |
+
pass
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
class AdminAPI(ABC):
|
| 580 |
+
@abstractmethod
|
| 581 |
+
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 582 |
+
"""Create a new database. Raises an error if the database already exists.
|
| 583 |
+
|
| 584 |
+
Args:
|
| 585 |
+
database: The name of the database to create.
|
| 586 |
+
|
| 587 |
+
"""
|
| 588 |
+
pass
|
| 589 |
+
|
| 590 |
+
@abstractmethod
|
| 591 |
+
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
|
| 592 |
+
"""Get a database. Raises an error if the database does not exist.
|
| 593 |
+
|
| 594 |
+
Args:
|
| 595 |
+
database: The name of the database to get.
|
| 596 |
+
tenant: The tenant of the database to get.
|
| 597 |
+
|
| 598 |
+
"""
|
| 599 |
+
pass
|
| 600 |
+
|
| 601 |
+
@abstractmethod
|
| 602 |
+
def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 603 |
+
"""Delete a database. Raises an error if the database does not exist.
|
| 604 |
+
|
| 605 |
+
Args:
|
| 606 |
+
database: The name of the database to delete.
|
| 607 |
+
tenant: The tenant of the database to delete.
|
| 608 |
+
|
| 609 |
+
"""
|
| 610 |
+
pass
|
| 611 |
+
|
| 612 |
+
@abstractmethod
|
| 613 |
+
def list_databases(
|
| 614 |
+
self,
|
| 615 |
+
limit: Optional[int] = None,
|
| 616 |
+
offset: Optional[int] = None,
|
| 617 |
+
tenant: str = DEFAULT_TENANT,
|
| 618 |
+
) -> Sequence[Database]:
|
| 619 |
+
"""List all databases for a tenant. Raises an error if the tenant does not exist.
|
| 620 |
+
|
| 621 |
+
Args:
|
| 622 |
+
tenant: The tenant to list databases for.
|
| 623 |
+
|
| 624 |
+
"""
|
| 625 |
+
pass
|
| 626 |
+
|
| 627 |
+
@abstractmethod
|
| 628 |
+
def create_tenant(self, name: str) -> None:
|
| 629 |
+
"""Create a new tenant. Raises an error if the tenant already exists.
|
| 630 |
+
|
| 631 |
+
Args:
|
| 632 |
+
tenant: The name of the tenant to create.
|
| 633 |
+
|
| 634 |
+
"""
|
| 635 |
+
pass
|
| 636 |
+
|
| 637 |
+
@abstractmethod
|
| 638 |
+
def get_tenant(self, name: str) -> Tenant:
|
| 639 |
+
"""Get a tenant. Raises an error if the tenant does not exist.
|
| 640 |
+
|
| 641 |
+
Args:
|
| 642 |
+
tenant: The name of the tenant to get.
|
| 643 |
+
|
| 644 |
+
"""
|
| 645 |
+
pass
|
| 646 |
+
|
| 647 |
+
|
| 648 |
+
class ServerAPI(BaseAPI, AdminAPI, Component):
|
| 649 |
+
"""An API instance that extends the relevant Base API methods by passing
|
| 650 |
+
in a tenant and database. This is the root component of the Chroma System"""
|
| 651 |
+
|
| 652 |
+
@abstractmethod
|
| 653 |
+
@override
|
| 654 |
+
def count_collections(
|
| 655 |
+
self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE
|
| 656 |
+
) -> int:
|
| 657 |
+
pass
|
| 658 |
+
|
| 659 |
+
@abstractmethod
|
| 660 |
+
def list_collections(
|
| 661 |
+
self,
|
| 662 |
+
limit: Optional[int] = None,
|
| 663 |
+
offset: Optional[int] = None,
|
| 664 |
+
tenant: str = DEFAULT_TENANT,
|
| 665 |
+
database: str = DEFAULT_DATABASE,
|
| 666 |
+
) -> Sequence[CollectionModel]:
|
| 667 |
+
pass
|
| 668 |
+
|
| 669 |
+
@abstractmethod
|
| 670 |
+
def create_collection(
|
| 671 |
+
self,
|
| 672 |
+
name: str,
|
| 673 |
+
schema: Optional[Schema] = None,
|
| 674 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 675 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 676 |
+
get_or_create: bool = False,
|
| 677 |
+
tenant: str = DEFAULT_TENANT,
|
| 678 |
+
database: str = DEFAULT_DATABASE,
|
| 679 |
+
) -> CollectionModel:
|
| 680 |
+
pass
|
| 681 |
+
|
| 682 |
+
@abstractmethod
|
| 683 |
+
def get_collection(
|
| 684 |
+
self,
|
| 685 |
+
name: str,
|
| 686 |
+
tenant: str = DEFAULT_TENANT,
|
| 687 |
+
database: str = DEFAULT_DATABASE,
|
| 688 |
+
) -> CollectionModel:
|
| 689 |
+
pass
|
| 690 |
+
|
| 691 |
+
@abstractmethod
|
| 692 |
+
def get_collection_by_id(
|
| 693 |
+
self,
|
| 694 |
+
collection_id: UUID,
|
| 695 |
+
tenant: str = DEFAULT_TENANT,
|
| 696 |
+
database: str = DEFAULT_DATABASE,
|
| 697 |
+
) -> CollectionModel:
|
| 698 |
+
"""Get a collection by its ID.
|
| 699 |
+
|
| 700 |
+
Args:
|
| 701 |
+
collection_id: The UUID of the collection to retrieve.
|
| 702 |
+
tenant: The tenant to search within.
|
| 703 |
+
database: The database to search within.
|
| 704 |
+
|
| 705 |
+
Returns:
|
| 706 |
+
CollectionModel: The collection with the given ID.
|
| 707 |
+
|
| 708 |
+
Raises:
|
| 709 |
+
NotFoundError: If no collection with the given ID exists.
|
| 710 |
+
"""
|
| 711 |
+
pass
|
| 712 |
+
|
| 713 |
+
@abstractmethod
|
| 714 |
+
def get_or_create_collection(
|
| 715 |
+
self,
|
| 716 |
+
name: str,
|
| 717 |
+
schema: Optional[Schema] = None,
|
| 718 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 719 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 720 |
+
tenant: str = DEFAULT_TENANT,
|
| 721 |
+
database: str = DEFAULT_DATABASE,
|
| 722 |
+
) -> CollectionModel:
|
| 723 |
+
pass
|
| 724 |
+
|
| 725 |
+
@abstractmethod
|
| 726 |
+
@override
|
| 727 |
+
def delete_collection(
|
| 728 |
+
self,
|
| 729 |
+
name: str,
|
| 730 |
+
tenant: str = DEFAULT_TENANT,
|
| 731 |
+
database: str = DEFAULT_DATABASE,
|
| 732 |
+
) -> None:
|
| 733 |
+
pass
|
| 734 |
+
|
| 735 |
+
@abstractmethod
|
| 736 |
+
@override
|
| 737 |
+
def _modify(
|
| 738 |
+
self,
|
| 739 |
+
id: UUID,
|
| 740 |
+
new_name: Optional[str] = None,
|
| 741 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 742 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 743 |
+
tenant: str = DEFAULT_TENANT,
|
| 744 |
+
database: str = DEFAULT_DATABASE,
|
| 745 |
+
) -> None:
|
| 746 |
+
pass
|
| 747 |
+
|
| 748 |
+
@abstractmethod
|
| 749 |
+
def _fork(
|
| 750 |
+
self,
|
| 751 |
+
collection_id: UUID,
|
| 752 |
+
new_name: str,
|
| 753 |
+
tenant: str = DEFAULT_TENANT,
|
| 754 |
+
database: str = DEFAULT_DATABASE,
|
| 755 |
+
) -> CollectionModel:
|
| 756 |
+
pass
|
| 757 |
+
|
| 758 |
+
@abstractmethod
|
| 759 |
+
def _fork_count(
|
| 760 |
+
self,
|
| 761 |
+
collection_id: UUID,
|
| 762 |
+
tenant: str = DEFAULT_TENANT,
|
| 763 |
+
database: str = DEFAULT_DATABASE,
|
| 764 |
+
) -> int:
|
| 765 |
+
pass
|
| 766 |
+
|
| 767 |
+
@abstractmethod
|
| 768 |
+
def _get_indexing_status(
|
| 769 |
+
self,
|
| 770 |
+
collection_id: UUID,
|
| 771 |
+
tenant: str = DEFAULT_TENANT,
|
| 772 |
+
database: str = DEFAULT_DATABASE,
|
| 773 |
+
) -> "IndexingStatus":
|
| 774 |
+
pass
|
| 775 |
+
|
| 776 |
+
@abstractmethod
|
| 777 |
+
def _search(
|
| 778 |
+
self,
|
| 779 |
+
collection_id: UUID,
|
| 780 |
+
searches: List[Search],
|
| 781 |
+
tenant: str = DEFAULT_TENANT,
|
| 782 |
+
database: str = DEFAULT_DATABASE,
|
| 783 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 784 |
+
) -> SearchResult:
|
| 785 |
+
pass
|
| 786 |
+
|
| 787 |
+
@abstractmethod
|
| 788 |
+
@override
|
| 789 |
+
def _count(
|
| 790 |
+
self,
|
| 791 |
+
collection_id: UUID,
|
| 792 |
+
tenant: str = DEFAULT_TENANT,
|
| 793 |
+
database: str = DEFAULT_DATABASE,
|
| 794 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 795 |
+
) -> int:
|
| 796 |
+
pass
|
| 797 |
+
|
| 798 |
+
@abstractmethod
|
| 799 |
+
@override
|
| 800 |
+
def _peek(
|
| 801 |
+
self,
|
| 802 |
+
collection_id: UUID,
|
| 803 |
+
n: int = 10,
|
| 804 |
+
tenant: str = DEFAULT_TENANT,
|
| 805 |
+
database: str = DEFAULT_DATABASE,
|
| 806 |
+
) -> GetResult:
|
| 807 |
+
pass
|
| 808 |
+
|
| 809 |
+
@abstractmethod
|
| 810 |
+
@override
|
| 811 |
+
def _get(
|
| 812 |
+
self,
|
| 813 |
+
collection_id: UUID,
|
| 814 |
+
ids: Optional[IDs] = None,
|
| 815 |
+
where: Optional[Where] = None,
|
| 816 |
+
limit: Optional[int] = None,
|
| 817 |
+
offset: Optional[int] = None,
|
| 818 |
+
where_document: Optional[WhereDocument] = None,
|
| 819 |
+
include: Include = IncludeMetadataDocuments,
|
| 820 |
+
tenant: str = DEFAULT_TENANT,
|
| 821 |
+
database: str = DEFAULT_DATABASE,
|
| 822 |
+
) -> GetResult:
|
| 823 |
+
pass
|
| 824 |
+
|
| 825 |
+
@abstractmethod
|
| 826 |
+
@override
|
| 827 |
+
def _add(
|
| 828 |
+
self,
|
| 829 |
+
ids: IDs,
|
| 830 |
+
collection_id: UUID,
|
| 831 |
+
embeddings: Embeddings,
|
| 832 |
+
metadatas: Optional[Metadatas] = None,
|
| 833 |
+
documents: Optional[Documents] = None,
|
| 834 |
+
uris: Optional[URIs] = None,
|
| 835 |
+
tenant: str = DEFAULT_TENANT,
|
| 836 |
+
database: str = DEFAULT_DATABASE,
|
| 837 |
+
) -> bool:
|
| 838 |
+
pass
|
| 839 |
+
|
| 840 |
+
@abstractmethod
|
| 841 |
+
@override
|
| 842 |
+
def _update(
|
| 843 |
+
self,
|
| 844 |
+
collection_id: UUID,
|
| 845 |
+
ids: IDs,
|
| 846 |
+
embeddings: Optional[Embeddings] = None,
|
| 847 |
+
metadatas: Optional[Metadatas] = None,
|
| 848 |
+
documents: Optional[Documents] = None,
|
| 849 |
+
uris: Optional[URIs] = None,
|
| 850 |
+
tenant: str = DEFAULT_TENANT,
|
| 851 |
+
database: str = DEFAULT_DATABASE,
|
| 852 |
+
) -> bool:
|
| 853 |
+
pass
|
| 854 |
+
|
| 855 |
+
@abstractmethod
|
| 856 |
+
@override
|
| 857 |
+
def _upsert(
|
| 858 |
+
self,
|
| 859 |
+
collection_id: UUID,
|
| 860 |
+
ids: IDs,
|
| 861 |
+
embeddings: Embeddings,
|
| 862 |
+
metadatas: Optional[Metadatas] = None,
|
| 863 |
+
documents: Optional[Documents] = None,
|
| 864 |
+
uris: Optional[URIs] = None,
|
| 865 |
+
tenant: str = DEFAULT_TENANT,
|
| 866 |
+
database: str = DEFAULT_DATABASE,
|
| 867 |
+
) -> bool:
|
| 868 |
+
pass
|
| 869 |
+
|
| 870 |
+
@abstractmethod
|
| 871 |
+
@override
|
| 872 |
+
def _query(
|
| 873 |
+
self,
|
| 874 |
+
collection_id: UUID,
|
| 875 |
+
query_embeddings: Embeddings,
|
| 876 |
+
ids: Optional[IDs] = None,
|
| 877 |
+
n_results: int = 10,
|
| 878 |
+
where: Optional[Where] = None,
|
| 879 |
+
where_document: Optional[WhereDocument] = None,
|
| 880 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 881 |
+
tenant: str = DEFAULT_TENANT,
|
| 882 |
+
database: str = DEFAULT_DATABASE,
|
| 883 |
+
) -> QueryResult:
|
| 884 |
+
pass
|
| 885 |
+
|
| 886 |
+
@abstractmethod
|
| 887 |
+
@override
|
| 888 |
+
def _delete(
|
| 889 |
+
self,
|
| 890 |
+
collection_id: UUID,
|
| 891 |
+
ids: Optional[IDs] = None,
|
| 892 |
+
where: Optional[Where] = None,
|
| 893 |
+
where_document: Optional[WhereDocument] = None,
|
| 894 |
+
limit: Optional[int] = None,
|
| 895 |
+
tenant: str = DEFAULT_TENANT,
|
| 896 |
+
database: str = DEFAULT_DATABASE,
|
| 897 |
+
) -> DeleteResult:
|
| 898 |
+
pass
|
| 899 |
+
|
| 900 |
+
@abstractmethod
|
| 901 |
+
def attach_function(
|
| 902 |
+
self,
|
| 903 |
+
function_id: str,
|
| 904 |
+
name: str,
|
| 905 |
+
input_collection_id: UUID,
|
| 906 |
+
output_collection: str,
|
| 907 |
+
params: Optional[Dict[str, Any]] = None,
|
| 908 |
+
tenant: str = DEFAULT_TENANT,
|
| 909 |
+
database: str = DEFAULT_DATABASE,
|
| 910 |
+
) -> Tuple["AttachedFunction", bool]:
|
| 911 |
+
"""Attach a function to a collection.
|
| 912 |
+
|
| 913 |
+
Args:
|
| 914 |
+
function_id: Built-in function identifier
|
| 915 |
+
name: Unique name for this attached function
|
| 916 |
+
input_collection_id: Source collection that triggers the function
|
| 917 |
+
output_collection: Target collection where function output is stored
|
| 918 |
+
params: Optional dictionary with function-specific parameters
|
| 919 |
+
tenant: The tenant name
|
| 920 |
+
database: The database name
|
| 921 |
+
|
| 922 |
+
Returns:
|
| 923 |
+
Tuple of (AttachedFunction, created) where created is True if newly created,
|
| 924 |
+
False if already existed (idempotent request)
|
| 925 |
+
"""
|
| 926 |
+
pass
|
| 927 |
+
|
| 928 |
+
@abstractmethod
|
| 929 |
+
def get_attached_function(
|
| 930 |
+
self,
|
| 931 |
+
name: str,
|
| 932 |
+
input_collection_id: UUID,
|
| 933 |
+
tenant: str = DEFAULT_TENANT,
|
| 934 |
+
database: str = DEFAULT_DATABASE,
|
| 935 |
+
) -> "AttachedFunction":
|
| 936 |
+
"""Get an attached function by name for a specific collection.
|
| 937 |
+
|
| 938 |
+
Args:
|
| 939 |
+
name: Name of the attached function
|
| 940 |
+
input_collection_id: The collection ID
|
| 941 |
+
tenant: The tenant name
|
| 942 |
+
database: The database name
|
| 943 |
+
|
| 944 |
+
Returns:
|
| 945 |
+
AttachedFunction: The attached function object
|
| 946 |
+
|
| 947 |
+
Raises:
|
| 948 |
+
NotFoundError: If the attached function doesn't exist
|
| 949 |
+
"""
|
| 950 |
+
pass
|
| 951 |
+
|
| 952 |
+
@abstractmethod
|
| 953 |
+
def detach_function(
|
| 954 |
+
self,
|
| 955 |
+
name: str,
|
| 956 |
+
input_collection_id: UUID,
|
| 957 |
+
delete_output: bool = False,
|
| 958 |
+
tenant: str = DEFAULT_TENANT,
|
| 959 |
+
database: str = DEFAULT_DATABASE,
|
| 960 |
+
) -> bool:
|
| 961 |
+
"""Detach a function and prevent any further runs.
|
| 962 |
+
|
| 963 |
+
Args:
|
| 964 |
+
name: Name of the attached function to remove
|
| 965 |
+
input_collection_id: ID of the input collection
|
| 966 |
+
delete_output: Whether to also delete the output collection
|
| 967 |
+
tenant: The tenant name
|
| 968 |
+
database: The database name
|
| 969 |
+
|
| 970 |
+
Returns:
|
| 971 |
+
bool: True if successful
|
| 972 |
+
"""
|
| 973 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/api/async_api.py
ADDED
|
@@ -0,0 +1,850 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from typing import Sequence, Optional, List
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
|
| 5 |
+
from overrides import override
|
| 6 |
+
from chromadb.api.collection_configuration import (
|
| 7 |
+
CreateCollectionConfiguration,
|
| 8 |
+
UpdateCollectionConfiguration,
|
| 9 |
+
)
|
| 10 |
+
from chromadb.auth import UserIdentity
|
| 11 |
+
from chromadb.api.models.AsyncCollection import AsyncCollection
|
| 12 |
+
from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT
|
| 13 |
+
from chromadb.api.types import (
|
| 14 |
+
CollectionMetadata,
|
| 15 |
+
DeleteResult,
|
| 16 |
+
Documents,
|
| 17 |
+
Embeddable,
|
| 18 |
+
EmbeddingFunction,
|
| 19 |
+
DataLoader,
|
| 20 |
+
Embeddings,
|
| 21 |
+
IDs,
|
| 22 |
+
Include,
|
| 23 |
+
IndexingStatus,
|
| 24 |
+
Loadable,
|
| 25 |
+
Metadatas,
|
| 26 |
+
ReadLevel,
|
| 27 |
+
Schema,
|
| 28 |
+
URIs,
|
| 29 |
+
Where,
|
| 30 |
+
QueryResult,
|
| 31 |
+
GetResult,
|
| 32 |
+
WhereDocument,
|
| 33 |
+
IncludeMetadataDocuments,
|
| 34 |
+
IncludeMetadataDocumentsDistances,
|
| 35 |
+
SearchResult,
|
| 36 |
+
DefaultEmbeddingFunction,
|
| 37 |
+
)
|
| 38 |
+
from chromadb.execution.expression.plan import Search
|
| 39 |
+
from chromadb.config import Component, Settings
|
| 40 |
+
from chromadb.types import Database, Tenant, Collection as CollectionModel
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class AsyncBaseAPI(ABC):
|
| 44 |
+
@abstractmethod
|
| 45 |
+
async def heartbeat(self) -> int:
|
| 46 |
+
"""Get the current time in nanoseconds since epoch.
|
| 47 |
+
Used to check if the server is alive.
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
int: The current time in nanoseconds since epoch
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
pass
|
| 54 |
+
|
| 55 |
+
#
|
| 56 |
+
# COLLECTION METHODS
|
| 57 |
+
#
|
| 58 |
+
|
| 59 |
+
@abstractmethod
|
| 60 |
+
async def count_collections(self) -> int:
|
| 61 |
+
"""Count the number of collections.
|
| 62 |
+
|
| 63 |
+
Returns:
|
| 64 |
+
int: The number of collections.
|
| 65 |
+
|
| 66 |
+
Examples:
|
| 67 |
+
```python
|
| 68 |
+
await client.count_collections()
|
| 69 |
+
# 1
|
| 70 |
+
```
|
| 71 |
+
"""
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
@abstractmethod
|
| 75 |
+
async def _modify(
|
| 76 |
+
self,
|
| 77 |
+
id: UUID,
|
| 78 |
+
new_name: Optional[str] = None,
|
| 79 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 80 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 81 |
+
) -> None:
|
| 82 |
+
"""[Internal] Modify a collection by UUID. Can update the name and/or metadata.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
id: The internal UUID of the collection to modify.
|
| 86 |
+
new_name: The new name of the collection.
|
| 87 |
+
If None, the existing name will remain. Defaults to None.
|
| 88 |
+
new_metadata: The new metadata to associate with the collection.
|
| 89 |
+
Defaults to None.
|
| 90 |
+
new_configuration: The new configuration to associate with the collection.
|
| 91 |
+
Defaults to None.
|
| 92 |
+
"""
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
@abstractmethod
|
| 96 |
+
async def delete_collection(
|
| 97 |
+
self,
|
| 98 |
+
name: str,
|
| 99 |
+
) -> None:
|
| 100 |
+
"""Delete a collection with the given name.
|
| 101 |
+
Args:
|
| 102 |
+
name: The name of the collection to delete.
|
| 103 |
+
|
| 104 |
+
Raises:
|
| 105 |
+
ValueError: If the collection does not exist.
|
| 106 |
+
|
| 107 |
+
Examples:
|
| 108 |
+
```python
|
| 109 |
+
await client.delete_collection("my_collection")
|
| 110 |
+
```
|
| 111 |
+
"""
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
#
|
| 115 |
+
# ITEM METHODS
|
| 116 |
+
#
|
| 117 |
+
|
| 118 |
+
@abstractmethod
|
| 119 |
+
async def _add(
|
| 120 |
+
self,
|
| 121 |
+
ids: IDs,
|
| 122 |
+
collection_id: UUID,
|
| 123 |
+
embeddings: Embeddings,
|
| 124 |
+
metadatas: Optional[Metadatas] = None,
|
| 125 |
+
documents: Optional[Documents] = None,
|
| 126 |
+
uris: Optional[URIs] = None,
|
| 127 |
+
) -> bool:
|
| 128 |
+
"""[Internal] Add embeddings to a collection specified by UUID.
|
| 129 |
+
If (some) ids already exist, only the new embeddings will be added.
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
ids: The ids to associate with the embeddings.
|
| 133 |
+
collection_id: The UUID of the collection to add the embeddings to.
|
| 134 |
+
embedding: The sequence of embeddings to add.
|
| 135 |
+
metadata: The metadata to associate with the embeddings. Defaults to None.
|
| 136 |
+
documents: The documents to associate with the embeddings. Defaults to None.
|
| 137 |
+
uris: URIs of data sources for each embedding. Defaults to None.
|
| 138 |
+
|
| 139 |
+
Returns:
|
| 140 |
+
True if the embeddings were added successfully.
|
| 141 |
+
"""
|
| 142 |
+
pass
|
| 143 |
+
|
| 144 |
+
@abstractmethod
|
| 145 |
+
async def _update(
|
| 146 |
+
self,
|
| 147 |
+
collection_id: UUID,
|
| 148 |
+
ids: IDs,
|
| 149 |
+
embeddings: Optional[Embeddings] = None,
|
| 150 |
+
metadatas: Optional[Metadatas] = None,
|
| 151 |
+
documents: Optional[Documents] = None,
|
| 152 |
+
uris: Optional[URIs] = None,
|
| 153 |
+
) -> bool:
|
| 154 |
+
"""[Internal] Update entries in a collection specified by UUID.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
collection_id: The UUID of the collection to update the embeddings in.
|
| 158 |
+
ids: The IDs of the entries to update.
|
| 159 |
+
embeddings: The sequence of embeddings to update. Defaults to None.
|
| 160 |
+
metadatas: The metadata to associate with the embeddings. Defaults to None.
|
| 161 |
+
documents: The documents to associate with the embeddings. Defaults to None.
|
| 162 |
+
uris: URIs of data sources for each embedding. Defaults to None.
|
| 163 |
+
Returns:
|
| 164 |
+
True if the embeddings were updated successfully.
|
| 165 |
+
"""
|
| 166 |
+
pass
|
| 167 |
+
|
| 168 |
+
@abstractmethod
|
| 169 |
+
async def _upsert(
|
| 170 |
+
self,
|
| 171 |
+
collection_id: UUID,
|
| 172 |
+
ids: IDs,
|
| 173 |
+
embeddings: Embeddings,
|
| 174 |
+
metadatas: Optional[Metadatas] = None,
|
| 175 |
+
documents: Optional[Documents] = None,
|
| 176 |
+
uris: Optional[URIs] = None,
|
| 177 |
+
) -> bool:
|
| 178 |
+
"""[Internal] Add or update entries in the a collection specified by UUID.
|
| 179 |
+
If an entry with the same id already exists, it will be updated,
|
| 180 |
+
otherwise it will be added.
|
| 181 |
+
|
| 182 |
+
Args:
|
| 183 |
+
collection_id: The collection to add the embeddings to
|
| 184 |
+
ids: The ids to associate with the embeddings. Defaults to None.
|
| 185 |
+
embeddings: The sequence of embeddings to add
|
| 186 |
+
metadatas: The metadata to associate with the embeddings. Defaults to None.
|
| 187 |
+
documents: The documents to associate with the embeddings. Defaults to None.
|
| 188 |
+
uris: URIs of data sources for each embedding. Defaults to None.
|
| 189 |
+
"""
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
@abstractmethod
|
| 193 |
+
async def _count(self, collection_id: UUID) -> int:
|
| 194 |
+
"""[Internal] Returns the number of entries in a collection specified by UUID.
|
| 195 |
+
|
| 196 |
+
Args:
|
| 197 |
+
collection_id: The UUID of the collection to count the embeddings in.
|
| 198 |
+
|
| 199 |
+
Returns:
|
| 200 |
+
int: The number of embeddings in the collection
|
| 201 |
+
|
| 202 |
+
"""
|
| 203 |
+
pass
|
| 204 |
+
|
| 205 |
+
@abstractmethod
|
| 206 |
+
async def _peek(self, collection_id: UUID, n: int = 10) -> GetResult:
|
| 207 |
+
"""[Internal] Returns the first n entries in a collection specified by UUID.
|
| 208 |
+
|
| 209 |
+
Args:
|
| 210 |
+
collection_id: The UUID of the collection to peek into.
|
| 211 |
+
n: The number of entries to peek. Defaults to 10.
|
| 212 |
+
|
| 213 |
+
Returns:
|
| 214 |
+
GetResult: The first n entries in the collection.
|
| 215 |
+
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
pass
|
| 219 |
+
|
| 220 |
+
@abstractmethod
|
| 221 |
+
async def _get(
|
| 222 |
+
self,
|
| 223 |
+
collection_id: UUID,
|
| 224 |
+
ids: Optional[IDs] = None,
|
| 225 |
+
where: Optional[Where] = None,
|
| 226 |
+
limit: Optional[int] = None,
|
| 227 |
+
offset: Optional[int] = None,
|
| 228 |
+
where_document: Optional[WhereDocument] = None,
|
| 229 |
+
include: Include = IncludeMetadataDocuments,
|
| 230 |
+
) -> GetResult:
|
| 231 |
+
"""[Internal] Returns entries from a collection specified by UUID.
|
| 232 |
+
|
| 233 |
+
Args:
|
| 234 |
+
ids: The IDs of the entries to get. Defaults to None.
|
| 235 |
+
where: Conditional filtering on metadata. Defaults to None.
|
| 236 |
+
limit: The maximum number of entries to return. Defaults to None.
|
| 237 |
+
offset: The number of entries to skip before returning. Defaults to None.
|
| 238 |
+
where_document: Conditional filtering on documents. Defaults to None.
|
| 239 |
+
include: The fields to include in the response.
|
| 240 |
+
Defaults to ["embeddings", "metadatas", "documents"].
|
| 241 |
+
Returns:
|
| 242 |
+
GetResult: The entries in the collection that match the query.
|
| 243 |
+
|
| 244 |
+
"""
|
| 245 |
+
pass
|
| 246 |
+
|
| 247 |
+
@abstractmethod
|
| 248 |
+
async def _delete(
|
| 249 |
+
self,
|
| 250 |
+
collection_id: UUID,
|
| 251 |
+
ids: Optional[IDs],
|
| 252 |
+
where: Optional[Where] = None,
|
| 253 |
+
where_document: Optional[WhereDocument] = None,
|
| 254 |
+
limit: Optional[int] = None,
|
| 255 |
+
) -> DeleteResult:
|
| 256 |
+
"""[Internal] Deletes entries from a collection specified by UUID.
|
| 257 |
+
|
| 258 |
+
Args:
|
| 259 |
+
collection_id: The UUID of the collection to delete the entries from.
|
| 260 |
+
ids: The IDs of the entries to delete. Defaults to None.
|
| 261 |
+
where: Conditional filtering on metadata. Defaults to None.
|
| 262 |
+
where_document: Conditional filtering on documents. Defaults to None.
|
| 263 |
+
limit: Maximum number of records to delete. Can only be used with
|
| 264 |
+
where or where_document. Defaults to None (no limit).
|
| 265 |
+
|
| 266 |
+
Returns:
|
| 267 |
+
DeleteResult: A dict containing the number of records deleted.
|
| 268 |
+
"""
|
| 269 |
+
pass
|
| 270 |
+
|
| 271 |
+
@abstractmethod
|
| 272 |
+
async def _query(
|
| 273 |
+
self,
|
| 274 |
+
collection_id: UUID,
|
| 275 |
+
query_embeddings: Embeddings,
|
| 276 |
+
ids: Optional[IDs] = None,
|
| 277 |
+
n_results: int = 10,
|
| 278 |
+
where: Optional[Where] = None,
|
| 279 |
+
where_document: Optional[WhereDocument] = None,
|
| 280 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 281 |
+
) -> QueryResult:
|
| 282 |
+
"""[Internal] Performs a nearest neighbors query on a collection specified by UUID.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
collection_id: The UUID of the collection to query.
|
| 286 |
+
query_embeddings: The embeddings to use as the query.
|
| 287 |
+
n_results: The number of results to return. Defaults to 10.
|
| 288 |
+
where: Conditional filtering on metadata. Defaults to None.
|
| 289 |
+
where_document: Conditional filtering on documents. Defaults to None.
|
| 290 |
+
include: The fields to include in the response.
|
| 291 |
+
Defaults to ["embeddings", "metadatas", "documents", "distances"].
|
| 292 |
+
|
| 293 |
+
Returns:
|
| 294 |
+
QueryResult: The results of the query.
|
| 295 |
+
"""
|
| 296 |
+
pass
|
| 297 |
+
|
| 298 |
+
@abstractmethod
|
| 299 |
+
async def reset(self) -> bool:
|
| 300 |
+
"""Resets the database. This will delete all collections and entries.
|
| 301 |
+
|
| 302 |
+
Returns:
|
| 303 |
+
bool: True if the database was reset successfully.
|
| 304 |
+
"""
|
| 305 |
+
pass
|
| 306 |
+
|
| 307 |
+
@abstractmethod
|
| 308 |
+
async def get_version(self) -> str:
|
| 309 |
+
"""Get the version of Chroma.
|
| 310 |
+
|
| 311 |
+
Returns:
|
| 312 |
+
str: The version of Chroma
|
| 313 |
+
|
| 314 |
+
"""
|
| 315 |
+
pass
|
| 316 |
+
|
| 317 |
+
@abstractmethod
|
| 318 |
+
def get_settings(self) -> Settings:
|
| 319 |
+
"""Get the settings used to initialize.
|
| 320 |
+
|
| 321 |
+
Returns:
|
| 322 |
+
Settings: The settings used to initialize.
|
| 323 |
+
|
| 324 |
+
"""
|
| 325 |
+
pass
|
| 326 |
+
|
| 327 |
+
@abstractmethod
|
| 328 |
+
async def get_max_batch_size(self) -> int:
|
| 329 |
+
"""Return the maximum number of records that can be created or mutated in a single call."""
|
| 330 |
+
pass
|
| 331 |
+
|
| 332 |
+
@abstractmethod
|
| 333 |
+
async def get_user_identity(self) -> UserIdentity:
|
| 334 |
+
"""Resolve the tenant and databases for the client. Returns the default
|
| 335 |
+
values if can't be resolved.
|
| 336 |
+
|
| 337 |
+
"""
|
| 338 |
+
pass
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class AsyncClientAPI(AsyncBaseAPI, ABC):
|
| 342 |
+
tenant: str
|
| 343 |
+
database: str
|
| 344 |
+
|
| 345 |
+
@abstractmethod
|
| 346 |
+
async def list_collections(
|
| 347 |
+
self,
|
| 348 |
+
limit: Optional[int] = None,
|
| 349 |
+
offset: Optional[int] = None,
|
| 350 |
+
) -> Sequence[AsyncCollection]:
|
| 351 |
+
"""List all collections.
|
| 352 |
+
Args:
|
| 353 |
+
limit: The maximum number of entries to return. Defaults to None.
|
| 354 |
+
offset: The number of entries to skip before returning. Defaults to None.
|
| 355 |
+
|
| 356 |
+
Returns:
|
| 357 |
+
Sequence[AsyncCollection]: A list of collections.
|
| 358 |
+
|
| 359 |
+
Examples:
|
| 360 |
+
```python
|
| 361 |
+
await client.list_collections()
|
| 362 |
+
# [collection(name="my_collection", metadata={})]
|
| 363 |
+
```
|
| 364 |
+
"""
|
| 365 |
+
pass
|
| 366 |
+
|
| 367 |
+
@abstractmethod
|
| 368 |
+
async def create_collection(
|
| 369 |
+
self,
|
| 370 |
+
name: str,
|
| 371 |
+
schema: Optional[Schema] = None,
|
| 372 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 373 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 374 |
+
embedding_function: Optional[
|
| 375 |
+
EmbeddingFunction[Embeddable]
|
| 376 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 377 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 378 |
+
get_or_create: bool = False,
|
| 379 |
+
) -> AsyncCollection:
|
| 380 |
+
"""Create a new collection with the given name and metadata.
|
| 381 |
+
Args:
|
| 382 |
+
name: The name of the collection to create.
|
| 383 |
+
metadata: Optional metadata to associate with the collection.
|
| 384 |
+
embedding_function: Optional function to use to embed documents.
|
| 385 |
+
Uses the default embedding function if not provided.
|
| 386 |
+
get_or_create: If True, return the existing collection if it exists.
|
| 387 |
+
data_loader: Optional function to use to load records (documents, images, etc.)
|
| 388 |
+
|
| 389 |
+
Returns:
|
| 390 |
+
Collection: The newly created collection.
|
| 391 |
+
|
| 392 |
+
Raises:
|
| 393 |
+
ValueError: If the collection already exists and get_or_create is False.
|
| 394 |
+
ValueError: If the collection name is invalid.
|
| 395 |
+
|
| 396 |
+
Examples:
|
| 397 |
+
```python
|
| 398 |
+
await client.create_collection("my_collection")
|
| 399 |
+
# collection(name="my_collection", metadata={})
|
| 400 |
+
|
| 401 |
+
await client.create_collection("my_collection", metadata={"foo": "bar"})
|
| 402 |
+
# collection(name="my_collection", metadata={"foo": "bar"})
|
| 403 |
+
```
|
| 404 |
+
"""
|
| 405 |
+
pass
|
| 406 |
+
|
| 407 |
+
@abstractmethod
|
| 408 |
+
async def get_collection(
|
| 409 |
+
self,
|
| 410 |
+
name: str,
|
| 411 |
+
embedding_function: Optional[
|
| 412 |
+
EmbeddingFunction[Embeddable]
|
| 413 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 414 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 415 |
+
) -> AsyncCollection:
|
| 416 |
+
"""Get a collection with the given name.
|
| 417 |
+
Args:
|
| 418 |
+
name: The name of the collection to get
|
| 419 |
+
embedding_function: Optional function to use to embed documents.
|
| 420 |
+
Uses the default embedding function if not provided.
|
| 421 |
+
data_loader: Optional function to use to load records (documents, images, etc.)
|
| 422 |
+
|
| 423 |
+
Returns:
|
| 424 |
+
Collection: The collection
|
| 425 |
+
|
| 426 |
+
Raises:
|
| 427 |
+
ValueError: If the collection does not exist
|
| 428 |
+
|
| 429 |
+
Examples:
|
| 430 |
+
```python
|
| 431 |
+
await client.get_collection("my_collection")
|
| 432 |
+
# collection(name="my_collection", metadata={})
|
| 433 |
+
```
|
| 434 |
+
"""
|
| 435 |
+
pass
|
| 436 |
+
|
| 437 |
+
@abstractmethod
|
| 438 |
+
async def get_collection_by_id(
|
| 439 |
+
self,
|
| 440 |
+
id: UUID,
|
| 441 |
+
embedding_function: Optional[
|
| 442 |
+
EmbeddingFunction[Embeddable]
|
| 443 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 444 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 445 |
+
) -> AsyncCollection:
|
| 446 |
+
"""Get a collection by its ID.
|
| 447 |
+
|
| 448 |
+
Args:
|
| 449 |
+
id: The UUID of the collection to get.
|
| 450 |
+
embedding_function: Optional function to use to embed documents.
|
| 451 |
+
Uses the default embedding function if not provided.
|
| 452 |
+
data_loader: Optional function to use to load records (documents, images, etc.)
|
| 453 |
+
|
| 454 |
+
Returns:
|
| 455 |
+
Collection: The collection
|
| 456 |
+
|
| 457 |
+
Raises:
|
| 458 |
+
NotFoundError: If no collection with the given ID exists.
|
| 459 |
+
|
| 460 |
+
Examples:
|
| 461 |
+
```python
|
| 462 |
+
await client.get_collection_by_id(uuid.UUID("..."))
|
| 463 |
+
# collection(name="my_collection", metadata={})
|
| 464 |
+
```
|
| 465 |
+
"""
|
| 466 |
+
pass
|
| 467 |
+
|
| 468 |
+
@abstractmethod
|
| 469 |
+
async def get_or_create_collection(
|
| 470 |
+
self,
|
| 471 |
+
name: str,
|
| 472 |
+
schema: Optional[Schema] = None,
|
| 473 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 474 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 475 |
+
embedding_function: Optional[
|
| 476 |
+
EmbeddingFunction[Embeddable]
|
| 477 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 478 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 479 |
+
) -> AsyncCollection:
|
| 480 |
+
"""Get or create a collection with the given name and metadata.
|
| 481 |
+
Args:
|
| 482 |
+
name: The name of the collection to get or create
|
| 483 |
+
metadata: Optional metadata to associate with the collection. If
|
| 484 |
+
the collection already exists, the metadata provided is ignored.
|
| 485 |
+
If the collection does not exist, the new collection will be created
|
| 486 |
+
with the provided metadata.
|
| 487 |
+
embedding_function: Optional function to use to embed documents
|
| 488 |
+
data_loader: Optional function to use to load records (documents, images, etc.)
|
| 489 |
+
|
| 490 |
+
Returns:
|
| 491 |
+
The collection
|
| 492 |
+
|
| 493 |
+
Examples:
|
| 494 |
+
```python
|
| 495 |
+
await client.get_or_create_collection("my_collection")
|
| 496 |
+
# collection(name="my_collection", metadata={})
|
| 497 |
+
```
|
| 498 |
+
"""
|
| 499 |
+
pass
|
| 500 |
+
|
| 501 |
+
@abstractmethod
|
| 502 |
+
async def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
|
| 503 |
+
"""Set the tenant and database for the client. Raises an error if the tenant or
|
| 504 |
+
database does not exist.
|
| 505 |
+
|
| 506 |
+
Args:
|
| 507 |
+
tenant: The tenant to set.
|
| 508 |
+
database: The database to set.
|
| 509 |
+
|
| 510 |
+
"""
|
| 511 |
+
pass
|
| 512 |
+
|
| 513 |
+
@abstractmethod
|
| 514 |
+
async def set_database(self, database: str) -> None:
|
| 515 |
+
"""Set the database for the client. Raises an error if the database does not exist.
|
| 516 |
+
|
| 517 |
+
Args:
|
| 518 |
+
database: The database to set.
|
| 519 |
+
|
| 520 |
+
"""
|
| 521 |
+
pass
|
| 522 |
+
|
| 523 |
+
@staticmethod
|
| 524 |
+
@abstractmethod
|
| 525 |
+
def clear_system_cache() -> None:
|
| 526 |
+
"""Clear the system cache so that new systems can be created for an existing path.
|
| 527 |
+
This should only be used for testing purposes."""
|
| 528 |
+
pass
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
class AsyncAdminAPI(ABC):
|
| 532 |
+
@abstractmethod
|
| 533 |
+
async def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 534 |
+
"""Create a new database. Raises an error if the database already exists.
|
| 535 |
+
|
| 536 |
+
Args:
|
| 537 |
+
database: The name of the database to create.
|
| 538 |
+
|
| 539 |
+
"""
|
| 540 |
+
pass
|
| 541 |
+
|
| 542 |
+
@abstractmethod
|
| 543 |
+
async def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
|
| 544 |
+
"""Get a database. Raises an error if the database does not exist.
|
| 545 |
+
|
| 546 |
+
Args:
|
| 547 |
+
database: The name of the database to get.
|
| 548 |
+
tenant: The tenant of the database to get.
|
| 549 |
+
|
| 550 |
+
"""
|
| 551 |
+
pass
|
| 552 |
+
|
| 553 |
+
@abstractmethod
|
| 554 |
+
async def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 555 |
+
"""Delete a database. Raises an error if the database does not exist.
|
| 556 |
+
|
| 557 |
+
Args:
|
| 558 |
+
database: The name of the database to delete.
|
| 559 |
+
tenant: The tenant of the database to delete.
|
| 560 |
+
|
| 561 |
+
"""
|
| 562 |
+
pass
|
| 563 |
+
|
| 564 |
+
@abstractmethod
|
| 565 |
+
async def list_databases(
|
| 566 |
+
self,
|
| 567 |
+
limit: Optional[int] = None,
|
| 568 |
+
offset: Optional[int] = None,
|
| 569 |
+
tenant: str = DEFAULT_TENANT,
|
| 570 |
+
) -> Sequence[Database]:
|
| 571 |
+
"""List all databases for a tenant. Raises an error if the tenant does not exist.
|
| 572 |
+
|
| 573 |
+
Args:
|
| 574 |
+
tenant: The tenant to list databases for.
|
| 575 |
+
|
| 576 |
+
"""
|
| 577 |
+
pass
|
| 578 |
+
|
| 579 |
+
@abstractmethod
|
| 580 |
+
async def create_tenant(self, name: str) -> None:
|
| 581 |
+
"""Create a new tenant. Raises an error if the tenant already exists.
|
| 582 |
+
|
| 583 |
+
Args:
|
| 584 |
+
tenant: The name of the tenant to create.
|
| 585 |
+
|
| 586 |
+
"""
|
| 587 |
+
pass
|
| 588 |
+
|
| 589 |
+
@abstractmethod
|
| 590 |
+
async def get_tenant(self, name: str) -> Tenant:
|
| 591 |
+
"""Get a tenant. Raises an error if the tenant does not exist.
|
| 592 |
+
|
| 593 |
+
Args:
|
| 594 |
+
tenant: The name of the tenant to get.
|
| 595 |
+
|
| 596 |
+
"""
|
| 597 |
+
pass
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
class AsyncServerAPI(AsyncBaseAPI, AsyncAdminAPI, Component):
|
| 601 |
+
"""An API instance that extends the relevant Base API methods by passing
|
| 602 |
+
in a tenant and database. This is the root component of the Chroma System"""
|
| 603 |
+
|
| 604 |
+
@abstractmethod
|
| 605 |
+
async def list_collections(
|
| 606 |
+
self,
|
| 607 |
+
limit: Optional[int] = None,
|
| 608 |
+
offset: Optional[int] = None,
|
| 609 |
+
tenant: str = DEFAULT_TENANT,
|
| 610 |
+
database: str = DEFAULT_DATABASE,
|
| 611 |
+
) -> Sequence[CollectionModel]:
|
| 612 |
+
pass
|
| 613 |
+
|
| 614 |
+
@abstractmethod
|
| 615 |
+
@override
|
| 616 |
+
async def count_collections(
|
| 617 |
+
self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE
|
| 618 |
+
) -> int:
|
| 619 |
+
pass
|
| 620 |
+
|
| 621 |
+
@abstractmethod
|
| 622 |
+
async def create_collection(
|
| 623 |
+
self,
|
| 624 |
+
name: str,
|
| 625 |
+
schema: Optional[Schema] = None,
|
| 626 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 627 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 628 |
+
get_or_create: bool = False,
|
| 629 |
+
tenant: str = DEFAULT_TENANT,
|
| 630 |
+
database: str = DEFAULT_DATABASE,
|
| 631 |
+
) -> CollectionModel:
|
| 632 |
+
pass
|
| 633 |
+
|
| 634 |
+
@abstractmethod
|
| 635 |
+
async def get_collection(
|
| 636 |
+
self,
|
| 637 |
+
name: str,
|
| 638 |
+
tenant: str = DEFAULT_TENANT,
|
| 639 |
+
database: str = DEFAULT_DATABASE,
|
| 640 |
+
) -> CollectionModel:
|
| 641 |
+
pass
|
| 642 |
+
|
| 643 |
+
@abstractmethod
|
| 644 |
+
async def get_collection_by_id(
|
| 645 |
+
self,
|
| 646 |
+
collection_id: UUID,
|
| 647 |
+
tenant: str = DEFAULT_TENANT,
|
| 648 |
+
database: str = DEFAULT_DATABASE,
|
| 649 |
+
) -> CollectionModel:
|
| 650 |
+
"""Get a collection by its ID.
|
| 651 |
+
|
| 652 |
+
Args:
|
| 653 |
+
collection_id: The UUID of the collection to retrieve.
|
| 654 |
+
tenant: The tenant to search within.
|
| 655 |
+
database: The database to search within.
|
| 656 |
+
|
| 657 |
+
Returns:
|
| 658 |
+
CollectionModel: The collection with the given ID.
|
| 659 |
+
|
| 660 |
+
Raises:
|
| 661 |
+
NotFoundError: If no collection with the given ID exists.
|
| 662 |
+
"""
|
| 663 |
+
pass
|
| 664 |
+
|
| 665 |
+
@abstractmethod
|
| 666 |
+
async def get_or_create_collection(
|
| 667 |
+
self,
|
| 668 |
+
name: str,
|
| 669 |
+
schema: Optional[Schema] = None,
|
| 670 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 671 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 672 |
+
tenant: str = DEFAULT_TENANT,
|
| 673 |
+
database: str = DEFAULT_DATABASE,
|
| 674 |
+
) -> CollectionModel:
|
| 675 |
+
pass
|
| 676 |
+
|
| 677 |
+
@abstractmethod
|
| 678 |
+
@override
|
| 679 |
+
async def delete_collection(
|
| 680 |
+
self,
|
| 681 |
+
name: str,
|
| 682 |
+
tenant: str = DEFAULT_TENANT,
|
| 683 |
+
database: str = DEFAULT_DATABASE,
|
| 684 |
+
) -> None:
|
| 685 |
+
pass
|
| 686 |
+
|
| 687 |
+
@abstractmethod
|
| 688 |
+
@override
|
| 689 |
+
async def _modify(
|
| 690 |
+
self,
|
| 691 |
+
id: UUID,
|
| 692 |
+
new_name: Optional[str] = None,
|
| 693 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 694 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 695 |
+
tenant: str = DEFAULT_TENANT,
|
| 696 |
+
database: str = DEFAULT_DATABASE,
|
| 697 |
+
) -> None:
|
| 698 |
+
pass
|
| 699 |
+
|
| 700 |
+
@abstractmethod
|
| 701 |
+
async def _fork(
|
| 702 |
+
self,
|
| 703 |
+
collection_id: UUID,
|
| 704 |
+
new_name: str,
|
| 705 |
+
tenant: str = DEFAULT_TENANT,
|
| 706 |
+
database: str = DEFAULT_DATABASE,
|
| 707 |
+
) -> CollectionModel:
|
| 708 |
+
pass
|
| 709 |
+
|
| 710 |
+
@abstractmethod
|
| 711 |
+
async def _fork_count(
|
| 712 |
+
self,
|
| 713 |
+
collection_id: UUID,
|
| 714 |
+
tenant: str = DEFAULT_TENANT,
|
| 715 |
+
database: str = DEFAULT_DATABASE,
|
| 716 |
+
) -> int:
|
| 717 |
+
pass
|
| 718 |
+
|
| 719 |
+
@abstractmethod
|
| 720 |
+
async def _get_indexing_status(
|
| 721 |
+
self,
|
| 722 |
+
collection_id: UUID,
|
| 723 |
+
tenant: str = DEFAULT_TENANT,
|
| 724 |
+
database: str = DEFAULT_DATABASE,
|
| 725 |
+
) -> "IndexingStatus":
|
| 726 |
+
pass
|
| 727 |
+
|
| 728 |
+
@abstractmethod
|
| 729 |
+
async def _search(
|
| 730 |
+
self,
|
| 731 |
+
collection_id: UUID,
|
| 732 |
+
searches: List[Search],
|
| 733 |
+
tenant: str = DEFAULT_TENANT,
|
| 734 |
+
database: str = DEFAULT_DATABASE,
|
| 735 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 736 |
+
) -> SearchResult:
|
| 737 |
+
pass
|
| 738 |
+
|
| 739 |
+
@abstractmethod
|
| 740 |
+
@override
|
| 741 |
+
async def _count(
|
| 742 |
+
self,
|
| 743 |
+
collection_id: UUID,
|
| 744 |
+
tenant: str = DEFAULT_TENANT,
|
| 745 |
+
database: str = DEFAULT_DATABASE,
|
| 746 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 747 |
+
) -> int:
|
| 748 |
+
pass
|
| 749 |
+
|
| 750 |
+
@abstractmethod
|
| 751 |
+
@override
|
| 752 |
+
async def _peek(
|
| 753 |
+
self,
|
| 754 |
+
collection_id: UUID,
|
| 755 |
+
n: int = 10,
|
| 756 |
+
tenant: str = DEFAULT_TENANT,
|
| 757 |
+
database: str = DEFAULT_DATABASE,
|
| 758 |
+
) -> GetResult:
|
| 759 |
+
pass
|
| 760 |
+
|
| 761 |
+
@abstractmethod
|
| 762 |
+
@override
|
| 763 |
+
async def _get(
|
| 764 |
+
self,
|
| 765 |
+
collection_id: UUID,
|
| 766 |
+
ids: Optional[IDs] = None,
|
| 767 |
+
where: Optional[Where] = None,
|
| 768 |
+
limit: Optional[int] = None,
|
| 769 |
+
offset: Optional[int] = None,
|
| 770 |
+
where_document: Optional[WhereDocument] = None,
|
| 771 |
+
include: Include = IncludeMetadataDocuments,
|
| 772 |
+
tenant: str = DEFAULT_TENANT,
|
| 773 |
+
database: str = DEFAULT_DATABASE,
|
| 774 |
+
) -> GetResult:
|
| 775 |
+
pass
|
| 776 |
+
|
| 777 |
+
@abstractmethod
|
| 778 |
+
@override
|
| 779 |
+
async def _add(
|
| 780 |
+
self,
|
| 781 |
+
ids: IDs,
|
| 782 |
+
collection_id: UUID,
|
| 783 |
+
embeddings: Embeddings,
|
| 784 |
+
metadatas: Optional[Metadatas] = None,
|
| 785 |
+
documents: Optional[Documents] = None,
|
| 786 |
+
uris: Optional[URIs] = None,
|
| 787 |
+
tenant: str = DEFAULT_TENANT,
|
| 788 |
+
database: str = DEFAULT_DATABASE,
|
| 789 |
+
) -> bool:
|
| 790 |
+
pass
|
| 791 |
+
|
| 792 |
+
@abstractmethod
|
| 793 |
+
@override
|
| 794 |
+
async def _update(
|
| 795 |
+
self,
|
| 796 |
+
collection_id: UUID,
|
| 797 |
+
ids: IDs,
|
| 798 |
+
embeddings: Optional[Embeddings] = None,
|
| 799 |
+
metadatas: Optional[Metadatas] = None,
|
| 800 |
+
documents: Optional[Documents] = None,
|
| 801 |
+
uris: Optional[URIs] = None,
|
| 802 |
+
tenant: str = DEFAULT_TENANT,
|
| 803 |
+
database: str = DEFAULT_DATABASE,
|
| 804 |
+
) -> bool:
|
| 805 |
+
pass
|
| 806 |
+
|
| 807 |
+
@abstractmethod
|
| 808 |
+
@override
|
| 809 |
+
async def _upsert(
|
| 810 |
+
self,
|
| 811 |
+
collection_id: UUID,
|
| 812 |
+
ids: IDs,
|
| 813 |
+
embeddings: Embeddings,
|
| 814 |
+
metadatas: Optional[Metadatas] = None,
|
| 815 |
+
documents: Optional[Documents] = None,
|
| 816 |
+
uris: Optional[URIs] = None,
|
| 817 |
+
tenant: str = DEFAULT_TENANT,
|
| 818 |
+
database: str = DEFAULT_DATABASE,
|
| 819 |
+
) -> bool:
|
| 820 |
+
pass
|
| 821 |
+
|
| 822 |
+
@abstractmethod
|
| 823 |
+
@override
|
| 824 |
+
async def _query(
|
| 825 |
+
self,
|
| 826 |
+
collection_id: UUID,
|
| 827 |
+
query_embeddings: Embeddings,
|
| 828 |
+
ids: Optional[IDs] = None,
|
| 829 |
+
n_results: int = 10,
|
| 830 |
+
where: Optional[Where] = None,
|
| 831 |
+
where_document: Optional[WhereDocument] = None,
|
| 832 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 833 |
+
tenant: str = DEFAULT_TENANT,
|
| 834 |
+
database: str = DEFAULT_DATABASE,
|
| 835 |
+
) -> QueryResult:
|
| 836 |
+
pass
|
| 837 |
+
|
| 838 |
+
@abstractmethod
|
| 839 |
+
@override
|
| 840 |
+
async def _delete(
|
| 841 |
+
self,
|
| 842 |
+
collection_id: UUID,
|
| 843 |
+
ids: Optional[IDs] = None,
|
| 844 |
+
where: Optional[Where] = None,
|
| 845 |
+
where_document: Optional[WhereDocument] = None,
|
| 846 |
+
limit: Optional[int] = None,
|
| 847 |
+
tenant: str = DEFAULT_TENANT,
|
| 848 |
+
database: str = DEFAULT_DATABASE,
|
| 849 |
+
) -> DeleteResult:
|
| 850 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/api/async_client.py
ADDED
|
@@ -0,0 +1,569 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import httpx
|
| 2 |
+
from typing import Optional, Sequence
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
from overrides import override
|
| 5 |
+
|
| 6 |
+
from chromadb.auth import UserIdentity
|
| 7 |
+
from chromadb.auth.utils import maybe_set_tenant_and_database
|
| 8 |
+
from chromadb.api import AsyncAdminAPI, AsyncClientAPI, AsyncServerAPI
|
| 9 |
+
from chromadb.api.collection_configuration import (
|
| 10 |
+
CreateCollectionConfiguration,
|
| 11 |
+
UpdateCollectionConfiguration,
|
| 12 |
+
validate_embedding_function_conflict_on_create,
|
| 13 |
+
validate_embedding_function_conflict_on_get,
|
| 14 |
+
)
|
| 15 |
+
from chromadb.api.models.AsyncCollection import AsyncCollection
|
| 16 |
+
from chromadb.api.shared_system_client import SharedSystemClient
|
| 17 |
+
from chromadb.api.types import (
|
| 18 |
+
CollectionMetadata,
|
| 19 |
+
DataLoader,
|
| 20 |
+
Documents,
|
| 21 |
+
Embeddable,
|
| 22 |
+
EmbeddingFunction,
|
| 23 |
+
Embeddings,
|
| 24 |
+
GetResult,
|
| 25 |
+
IDs,
|
| 26 |
+
Include,
|
| 27 |
+
IncludeMetadataDocuments,
|
| 28 |
+
IncludeMetadataDocumentsDistances,
|
| 29 |
+
Loadable,
|
| 30 |
+
Metadatas,
|
| 31 |
+
QueryResult,
|
| 32 |
+
Schema,
|
| 33 |
+
URIs,
|
| 34 |
+
DefaultEmbeddingFunction,
|
| 35 |
+
DeleteResult,
|
| 36 |
+
)
|
| 37 |
+
from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System
|
| 38 |
+
from chromadb.errors import ChromaError
|
| 39 |
+
from chromadb.types import Database, Tenant, Where, WhereDocument
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class AsyncClient(SharedSystemClient, AsyncClientAPI):
|
| 43 |
+
"""A client for Chroma. This is the main entrypoint for interacting with Chroma.
|
| 44 |
+
A client internally stores its tenant and database and proxies calls to a
|
| 45 |
+
Server API instance of Chroma. It treats the Server API and corresponding System
|
| 46 |
+
as a singleton, so multiple clients connecting to the same resource will share the
|
| 47 |
+
same API instance.
|
| 48 |
+
|
| 49 |
+
Client implementations should be implement their own API-caching strategies.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
# An internal admin client for verifying that databases and tenants exist
|
| 53 |
+
_admin_client: AsyncAdminAPI
|
| 54 |
+
|
| 55 |
+
tenant: str = DEFAULT_TENANT
|
| 56 |
+
database: str = DEFAULT_DATABASE
|
| 57 |
+
|
| 58 |
+
_server: AsyncServerAPI
|
| 59 |
+
|
| 60 |
+
@classmethod
|
| 61 |
+
async def create(
|
| 62 |
+
cls,
|
| 63 |
+
tenant: str = DEFAULT_TENANT,
|
| 64 |
+
database: str = DEFAULT_DATABASE,
|
| 65 |
+
settings: Settings = Settings(),
|
| 66 |
+
) -> "AsyncClient":
|
| 67 |
+
# Create an admin client for verifying that databases and tenants exist
|
| 68 |
+
self = cls(settings=settings)
|
| 69 |
+
SharedSystemClient._populate_data_from_system(self._system)
|
| 70 |
+
|
| 71 |
+
self.tenant = tenant
|
| 72 |
+
self.database = database
|
| 73 |
+
|
| 74 |
+
# Get the root system component we want to interact with
|
| 75 |
+
self._server = self._system.instance(AsyncServerAPI)
|
| 76 |
+
|
| 77 |
+
user_identity = await self.get_user_identity()
|
| 78 |
+
|
| 79 |
+
maybe_tenant, maybe_database = maybe_set_tenant_and_database(
|
| 80 |
+
user_identity,
|
| 81 |
+
overwrite_singleton_tenant_database_access_from_auth=settings.chroma_overwrite_singleton_tenant_database_access_from_auth,
|
| 82 |
+
user_provided_tenant=tenant,
|
| 83 |
+
user_provided_database=database,
|
| 84 |
+
)
|
| 85 |
+
if maybe_tenant:
|
| 86 |
+
self.tenant = maybe_tenant
|
| 87 |
+
if maybe_database:
|
| 88 |
+
self.database = maybe_database
|
| 89 |
+
|
| 90 |
+
self._admin_client = AsyncAdminClient.from_system(self._system)
|
| 91 |
+
await self._validate_tenant_database(tenant=self.tenant, database=self.database)
|
| 92 |
+
|
| 93 |
+
self._submit_client_start_event()
|
| 94 |
+
|
| 95 |
+
return self
|
| 96 |
+
|
| 97 |
+
@classmethod
|
| 98 |
+
# (we can't override and use from_system() because it's synchronous)
|
| 99 |
+
async def from_system_async(
|
| 100 |
+
cls,
|
| 101 |
+
system: System,
|
| 102 |
+
tenant: str = DEFAULT_TENANT,
|
| 103 |
+
database: str = DEFAULT_DATABASE,
|
| 104 |
+
) -> "AsyncClient":
|
| 105 |
+
"""Create a client from an existing system. This is useful for testing and debugging."""
|
| 106 |
+
return await AsyncClient.create(tenant, database, system.settings)
|
| 107 |
+
|
| 108 |
+
@classmethod
|
| 109 |
+
@override
|
| 110 |
+
def from_system(
|
| 111 |
+
cls,
|
| 112 |
+
system: System,
|
| 113 |
+
) -> "SharedSystemClient":
|
| 114 |
+
"""AsyncClient cannot be created synchronously. Use .from_system_async() instead."""
|
| 115 |
+
raise NotImplementedError(
|
| 116 |
+
"AsyncClient cannot be created synchronously. Use .from_system_async() instead."
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
@override
|
| 120 |
+
async def get_user_identity(self) -> UserIdentity:
|
| 121 |
+
return await self._server.get_user_identity()
|
| 122 |
+
|
| 123 |
+
@override
|
| 124 |
+
async def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
|
| 125 |
+
await self._validate_tenant_database(tenant=tenant, database=database)
|
| 126 |
+
self.tenant = tenant
|
| 127 |
+
self.database = database
|
| 128 |
+
|
| 129 |
+
@override
|
| 130 |
+
async def set_database(self, database: str) -> None:
|
| 131 |
+
await self._validate_tenant_database(tenant=self.tenant, database=database)
|
| 132 |
+
self.database = database
|
| 133 |
+
|
| 134 |
+
async def _validate_tenant_database(self, tenant: str, database: str) -> None:
|
| 135 |
+
try:
|
| 136 |
+
await self._admin_client.get_tenant(name=tenant)
|
| 137 |
+
except httpx.ConnectError:
|
| 138 |
+
raise ValueError(
|
| 139 |
+
"Could not connect to a Chroma server. Are you sure it is running?"
|
| 140 |
+
)
|
| 141 |
+
# Propagate ChromaErrors
|
| 142 |
+
except ChromaError as e:
|
| 143 |
+
raise e
|
| 144 |
+
except Exception:
|
| 145 |
+
raise ValueError(
|
| 146 |
+
f"Could not connect to tenant {tenant}. Are you sure it exists?"
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
await self._admin_client.get_database(name=database, tenant=tenant)
|
| 151 |
+
except httpx.ConnectError:
|
| 152 |
+
raise ValueError(
|
| 153 |
+
"Could not connect to a Chroma server. Are you sure it is running?"
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# region BaseAPI Methods
|
| 157 |
+
# Note - we could do this in less verbose ways, but they break type checking
|
| 158 |
+
@override
|
| 159 |
+
async def heartbeat(self) -> int:
|
| 160 |
+
return await self._server.heartbeat()
|
| 161 |
+
|
| 162 |
+
@override
|
| 163 |
+
async def list_collections(
|
| 164 |
+
self, limit: Optional[int] = None, offset: Optional[int] = None
|
| 165 |
+
) -> Sequence[AsyncCollection]:
|
| 166 |
+
models = await self._server.list_collections(
|
| 167 |
+
limit, offset, tenant=self.tenant, database=self.database
|
| 168 |
+
)
|
| 169 |
+
return [AsyncCollection(client=self._server, model=model) for model in models]
|
| 170 |
+
|
| 171 |
+
@override
|
| 172 |
+
async def count_collections(self) -> int:
|
| 173 |
+
return await self._server.count_collections(
|
| 174 |
+
tenant=self.tenant, database=self.database
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
@override
|
| 178 |
+
async def create_collection(
|
| 179 |
+
self,
|
| 180 |
+
name: str,
|
| 181 |
+
schema: Optional[Schema] = None,
|
| 182 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 183 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 184 |
+
embedding_function: Optional[
|
| 185 |
+
EmbeddingFunction[Embeddable]
|
| 186 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 187 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 188 |
+
get_or_create: bool = False,
|
| 189 |
+
) -> AsyncCollection:
|
| 190 |
+
if configuration is None:
|
| 191 |
+
configuration = {}
|
| 192 |
+
|
| 193 |
+
configuration_ef = configuration.get("embedding_function")
|
| 194 |
+
|
| 195 |
+
validate_embedding_function_conflict_on_create(
|
| 196 |
+
embedding_function, configuration_ef
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
# If ef provided in function params and collection config ef is None,
|
| 200 |
+
# set the collection config ef to the function params
|
| 201 |
+
if embedding_function is not None and configuration_ef is None:
|
| 202 |
+
configuration["embedding_function"] = embedding_function
|
| 203 |
+
|
| 204 |
+
model = await self._server.create_collection(
|
| 205 |
+
name=name,
|
| 206 |
+
schema=schema,
|
| 207 |
+
configuration=configuration,
|
| 208 |
+
metadata=metadata,
|
| 209 |
+
tenant=self.tenant,
|
| 210 |
+
database=self.database,
|
| 211 |
+
get_or_create=get_or_create,
|
| 212 |
+
)
|
| 213 |
+
return AsyncCollection(
|
| 214 |
+
client=self._server,
|
| 215 |
+
model=model,
|
| 216 |
+
embedding_function=embedding_function,
|
| 217 |
+
data_loader=data_loader,
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
@override
|
| 221 |
+
async def get_collection(
|
| 222 |
+
self,
|
| 223 |
+
name: str,
|
| 224 |
+
embedding_function: Optional[
|
| 225 |
+
EmbeddingFunction[Embeddable]
|
| 226 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 227 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 228 |
+
) -> AsyncCollection:
|
| 229 |
+
model = await self._server.get_collection(
|
| 230 |
+
name=name,
|
| 231 |
+
tenant=self.tenant,
|
| 232 |
+
database=self.database,
|
| 233 |
+
)
|
| 234 |
+
persisted_ef_config = model.configuration_json.get("embedding_function")
|
| 235 |
+
|
| 236 |
+
validate_embedding_function_conflict_on_get(
|
| 237 |
+
embedding_function, persisted_ef_config
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
return AsyncCollection(
|
| 241 |
+
client=self._server,
|
| 242 |
+
model=model,
|
| 243 |
+
embedding_function=embedding_function,
|
| 244 |
+
data_loader=data_loader,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
@override
|
| 248 |
+
async def get_collection_by_id(
|
| 249 |
+
self,
|
| 250 |
+
id: UUID,
|
| 251 |
+
embedding_function: Optional[
|
| 252 |
+
EmbeddingFunction[Embeddable]
|
| 253 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 254 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 255 |
+
) -> AsyncCollection:
|
| 256 |
+
"""Get a collection by its ID.
|
| 257 |
+
|
| 258 |
+
Args:
|
| 259 |
+
id: The UUID of the collection.
|
| 260 |
+
embedding_function: Optional embedding function for the collection.
|
| 261 |
+
data_loader: Optional data loader for documents with URIs.
|
| 262 |
+
|
| 263 |
+
Returns:
|
| 264 |
+
AsyncCollection: The requested collection.
|
| 265 |
+
|
| 266 |
+
Raises:
|
| 267 |
+
ValueError: If the embedding function conflicts with configuration.
|
| 268 |
+
"""
|
| 269 |
+
model = await self._server.get_collection_by_id(
|
| 270 |
+
collection_id=id,
|
| 271 |
+
tenant=self.tenant,
|
| 272 |
+
database=self.database,
|
| 273 |
+
)
|
| 274 |
+
persisted_ef_config = model.configuration_json.get("embedding_function")
|
| 275 |
+
|
| 276 |
+
validate_embedding_function_conflict_on_get(
|
| 277 |
+
embedding_function, persisted_ef_config
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
return AsyncCollection(
|
| 281 |
+
client=self._server,
|
| 282 |
+
model=model,
|
| 283 |
+
embedding_function=embedding_function,
|
| 284 |
+
data_loader=data_loader,
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
@override
|
| 288 |
+
async def get_or_create_collection(
|
| 289 |
+
self,
|
| 290 |
+
name: str,
|
| 291 |
+
schema: Optional[Schema] = None,
|
| 292 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 293 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 294 |
+
embedding_function: Optional[
|
| 295 |
+
EmbeddingFunction[Embeddable]
|
| 296 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 297 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 298 |
+
) -> AsyncCollection:
|
| 299 |
+
if configuration is None:
|
| 300 |
+
configuration = {}
|
| 301 |
+
|
| 302 |
+
configuration_ef = configuration.get("embedding_function")
|
| 303 |
+
|
| 304 |
+
validate_embedding_function_conflict_on_create(
|
| 305 |
+
embedding_function, configuration_ef
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
if embedding_function is not None and configuration_ef is None:
|
| 309 |
+
configuration["embedding_function"] = embedding_function
|
| 310 |
+
model = await self._server.get_or_create_collection(
|
| 311 |
+
name=name,
|
| 312 |
+
schema=schema,
|
| 313 |
+
configuration=configuration,
|
| 314 |
+
metadata=metadata,
|
| 315 |
+
tenant=self.tenant,
|
| 316 |
+
database=self.database,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
persisted_ef_config = model.configuration_json.get("embedding_function")
|
| 320 |
+
|
| 321 |
+
validate_embedding_function_conflict_on_get(
|
| 322 |
+
embedding_function, persisted_ef_config
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
return AsyncCollection(
|
| 326 |
+
client=self._server,
|
| 327 |
+
model=model,
|
| 328 |
+
embedding_function=embedding_function,
|
| 329 |
+
data_loader=data_loader,
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
@override
|
| 333 |
+
async def _modify(
|
| 334 |
+
self,
|
| 335 |
+
id: UUID,
|
| 336 |
+
new_name: Optional[str] = None,
|
| 337 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 338 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 339 |
+
) -> None:
|
| 340 |
+
return await self._server._modify(
|
| 341 |
+
id=id,
|
| 342 |
+
new_name=new_name,
|
| 343 |
+
new_metadata=new_metadata,
|
| 344 |
+
new_configuration=new_configuration,
|
| 345 |
+
tenant=self.tenant,
|
| 346 |
+
database=self.database,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
@override
|
| 350 |
+
async def delete_collection(
|
| 351 |
+
self,
|
| 352 |
+
name: str,
|
| 353 |
+
) -> None:
|
| 354 |
+
return await self._server.delete_collection(
|
| 355 |
+
name=name,
|
| 356 |
+
tenant=self.tenant,
|
| 357 |
+
database=self.database,
|
| 358 |
+
)
|
| 359 |
+
|
| 360 |
+
#
|
| 361 |
+
# ITEM METHODS
|
| 362 |
+
#
|
| 363 |
+
|
| 364 |
+
@override
|
| 365 |
+
async def _add(
|
| 366 |
+
self,
|
| 367 |
+
ids: IDs,
|
| 368 |
+
collection_id: UUID,
|
| 369 |
+
embeddings: Embeddings,
|
| 370 |
+
metadatas: Optional[Metadatas] = None,
|
| 371 |
+
documents: Optional[Documents] = None,
|
| 372 |
+
uris: Optional[URIs] = None,
|
| 373 |
+
) -> bool:
|
| 374 |
+
return await self._server._add(
|
| 375 |
+
ids=ids,
|
| 376 |
+
collection_id=collection_id,
|
| 377 |
+
embeddings=embeddings,
|
| 378 |
+
metadatas=metadatas,
|
| 379 |
+
documents=documents,
|
| 380 |
+
uris=uris,
|
| 381 |
+
tenant=self.tenant,
|
| 382 |
+
database=self.database,
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
@override
|
| 386 |
+
async def _update(
|
| 387 |
+
self,
|
| 388 |
+
collection_id: UUID,
|
| 389 |
+
ids: IDs,
|
| 390 |
+
embeddings: Optional[Embeddings] = None,
|
| 391 |
+
metadatas: Optional[Metadatas] = None,
|
| 392 |
+
documents: Optional[Documents] = None,
|
| 393 |
+
uris: Optional[URIs] = None,
|
| 394 |
+
) -> bool:
|
| 395 |
+
return await self._server._update(
|
| 396 |
+
collection_id=collection_id,
|
| 397 |
+
ids=ids,
|
| 398 |
+
embeddings=embeddings,
|
| 399 |
+
metadatas=metadatas,
|
| 400 |
+
documents=documents,
|
| 401 |
+
uris=uris,
|
| 402 |
+
tenant=self.tenant,
|
| 403 |
+
database=self.database,
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
@override
|
| 407 |
+
async def _upsert(
|
| 408 |
+
self,
|
| 409 |
+
collection_id: UUID,
|
| 410 |
+
ids: IDs,
|
| 411 |
+
embeddings: Embeddings,
|
| 412 |
+
metadatas: Optional[Metadatas] = None,
|
| 413 |
+
documents: Optional[Documents] = None,
|
| 414 |
+
uris: Optional[URIs] = None,
|
| 415 |
+
) -> bool:
|
| 416 |
+
return await self._server._upsert(
|
| 417 |
+
collection_id=collection_id,
|
| 418 |
+
ids=ids,
|
| 419 |
+
embeddings=embeddings,
|
| 420 |
+
metadatas=metadatas,
|
| 421 |
+
documents=documents,
|
| 422 |
+
uris=uris,
|
| 423 |
+
tenant=self.tenant,
|
| 424 |
+
database=self.database,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
@override
|
| 428 |
+
async def _count(self, collection_id: UUID) -> int:
|
| 429 |
+
return await self._server._count(
|
| 430 |
+
collection_id=collection_id,
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
@override
|
| 434 |
+
async def _peek(self, collection_id: UUID, n: int = 10) -> GetResult:
|
| 435 |
+
return await self._server._peek(
|
| 436 |
+
collection_id=collection_id,
|
| 437 |
+
n=n,
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
@override
|
| 441 |
+
async def _get(
|
| 442 |
+
self,
|
| 443 |
+
collection_id: UUID,
|
| 444 |
+
ids: Optional[IDs] = None,
|
| 445 |
+
where: Optional[Where] = None,
|
| 446 |
+
limit: Optional[int] = None,
|
| 447 |
+
offset: Optional[int] = None,
|
| 448 |
+
where_document: Optional[WhereDocument] = None,
|
| 449 |
+
include: Include = IncludeMetadataDocuments,
|
| 450 |
+
) -> GetResult:
|
| 451 |
+
return await self._server._get(
|
| 452 |
+
collection_id=collection_id,
|
| 453 |
+
ids=ids,
|
| 454 |
+
where=where,
|
| 455 |
+
limit=limit,
|
| 456 |
+
offset=offset,
|
| 457 |
+
where_document=where_document,
|
| 458 |
+
include=include,
|
| 459 |
+
tenant=self.tenant,
|
| 460 |
+
database=self.database,
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
async def _delete(
|
| 464 |
+
self,
|
| 465 |
+
collection_id: UUID,
|
| 466 |
+
ids: Optional[IDs],
|
| 467 |
+
where: Optional[Where] = None,
|
| 468 |
+
where_document: Optional[WhereDocument] = None,
|
| 469 |
+
limit: Optional[int] = None,
|
| 470 |
+
) -> DeleteResult:
|
| 471 |
+
return await self._server._delete(
|
| 472 |
+
collection_id=collection_id,
|
| 473 |
+
ids=ids,
|
| 474 |
+
where=where,
|
| 475 |
+
where_document=where_document,
|
| 476 |
+
limit=limit,
|
| 477 |
+
tenant=self.tenant,
|
| 478 |
+
database=self.database,
|
| 479 |
+
)
|
| 480 |
+
|
| 481 |
+
@override
|
| 482 |
+
async def _query(
|
| 483 |
+
self,
|
| 484 |
+
collection_id: UUID,
|
| 485 |
+
query_embeddings: Embeddings,
|
| 486 |
+
ids: Optional[IDs] = None,
|
| 487 |
+
n_results: int = 10,
|
| 488 |
+
where: Optional[Where] = None,
|
| 489 |
+
where_document: Optional[WhereDocument] = None,
|
| 490 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 491 |
+
) -> QueryResult:
|
| 492 |
+
return await self._server._query(
|
| 493 |
+
collection_id=collection_id,
|
| 494 |
+
query_embeddings=query_embeddings,
|
| 495 |
+
ids=ids,
|
| 496 |
+
n_results=n_results,
|
| 497 |
+
where=where,
|
| 498 |
+
where_document=where_document,
|
| 499 |
+
include=include,
|
| 500 |
+
tenant=self.tenant,
|
| 501 |
+
database=self.database,
|
| 502 |
+
)
|
| 503 |
+
|
| 504 |
+
@override
|
| 505 |
+
async def reset(self) -> bool:
|
| 506 |
+
return await self._server.reset()
|
| 507 |
+
|
| 508 |
+
@override
|
| 509 |
+
async def get_version(self) -> str:
|
| 510 |
+
return await self._server.get_version()
|
| 511 |
+
|
| 512 |
+
@override
|
| 513 |
+
def get_settings(self) -> Settings:
|
| 514 |
+
return self._server.get_settings()
|
| 515 |
+
|
| 516 |
+
@override
|
| 517 |
+
async def get_max_batch_size(self) -> int:
|
| 518 |
+
return await self._server.get_max_batch_size()
|
| 519 |
+
|
| 520 |
+
# endregion
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class AsyncAdminClient(SharedSystemClient, AsyncAdminAPI):
|
| 524 |
+
_server: AsyncServerAPI
|
| 525 |
+
|
| 526 |
+
def __init__(self, settings: Settings = Settings()) -> None:
|
| 527 |
+
super().__init__(settings)
|
| 528 |
+
self._server = self._system.instance(AsyncServerAPI)
|
| 529 |
+
|
| 530 |
+
@override
|
| 531 |
+
async def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 532 |
+
return await self._server.create_database(name=name, tenant=tenant)
|
| 533 |
+
|
| 534 |
+
@override
|
| 535 |
+
async def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
|
| 536 |
+
return await self._server.get_database(name=name, tenant=tenant)
|
| 537 |
+
|
| 538 |
+
@override
|
| 539 |
+
async def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 540 |
+
return await self._server.delete_database(name=name, tenant=tenant)
|
| 541 |
+
|
| 542 |
+
@override
|
| 543 |
+
async def list_databases(
|
| 544 |
+
self,
|
| 545 |
+
limit: Optional[int] = None,
|
| 546 |
+
offset: Optional[int] = None,
|
| 547 |
+
tenant: str = DEFAULT_TENANT,
|
| 548 |
+
) -> Sequence[Database]:
|
| 549 |
+
return await self._server.list_databases(
|
| 550 |
+
limit=limit, offset=offset, tenant=tenant
|
| 551 |
+
)
|
| 552 |
+
|
| 553 |
+
@override
|
| 554 |
+
async def create_tenant(self, name: str) -> None:
|
| 555 |
+
return await self._server.create_tenant(name=name)
|
| 556 |
+
|
| 557 |
+
@override
|
| 558 |
+
async def get_tenant(self, name: str) -> Tenant:
|
| 559 |
+
return await self._server.get_tenant(name=name)
|
| 560 |
+
|
| 561 |
+
@classmethod
|
| 562 |
+
@override
|
| 563 |
+
def from_system(
|
| 564 |
+
cls,
|
| 565 |
+
system: System,
|
| 566 |
+
) -> "AsyncAdminClient":
|
| 567 |
+
SharedSystemClient._populate_data_from_system(system)
|
| 568 |
+
instance = cls(settings=system.settings)
|
| 569 |
+
return instance
|
python/user_packages/Python313/site-packages/chromadb/api/async_fastapi.py
ADDED
|
@@ -0,0 +1,848 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
from uuid import UUID
|
| 3 |
+
import urllib.parse
|
| 4 |
+
import orjson
|
| 5 |
+
from typing import Any, Mapping, Optional, cast, Tuple, Sequence, Dict, List
|
| 6 |
+
import logging
|
| 7 |
+
import httpx
|
| 8 |
+
from overrides import override
|
| 9 |
+
from chromadb import __version__
|
| 10 |
+
from chromadb.auth import UserIdentity
|
| 11 |
+
from chromadb.api.async_api import AsyncServerAPI
|
| 12 |
+
from chromadb.api.base_http_client import BaseHTTPClient
|
| 13 |
+
from chromadb.api.collection_configuration import (
|
| 14 |
+
CreateCollectionConfiguration,
|
| 15 |
+
UpdateCollectionConfiguration,
|
| 16 |
+
create_collection_configuration_to_json,
|
| 17 |
+
update_collection_configuration_to_json,
|
| 18 |
+
)
|
| 19 |
+
from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, System, Settings
|
| 20 |
+
from chromadb.telemetry.opentelemetry import (
|
| 21 |
+
OpenTelemetryClient,
|
| 22 |
+
OpenTelemetryGranularity,
|
| 23 |
+
trace_method,
|
| 24 |
+
)
|
| 25 |
+
from chromadb.telemetry.product import ProductTelemetryClient
|
| 26 |
+
from chromadb.utils.async_to_sync import async_to_sync
|
| 27 |
+
from chromadb.types import Database, Tenant, Collection as CollectionModel
|
| 28 |
+
from chromadb.execution.expression.plan import Search
|
| 29 |
+
|
| 30 |
+
from chromadb.api.types import (
|
| 31 |
+
DeleteResult,
|
| 32 |
+
Documents,
|
| 33 |
+
Embeddings,
|
| 34 |
+
IDs,
|
| 35 |
+
Include,
|
| 36 |
+
IndexingStatus,
|
| 37 |
+
Schema,
|
| 38 |
+
Metadatas,
|
| 39 |
+
ReadLevel,
|
| 40 |
+
URIs,
|
| 41 |
+
Where,
|
| 42 |
+
WhereDocument,
|
| 43 |
+
GetResult,
|
| 44 |
+
QueryResult,
|
| 45 |
+
SearchResult,
|
| 46 |
+
CollectionMetadata,
|
| 47 |
+
optional_embeddings_to_base64_strings,
|
| 48 |
+
validate_batch,
|
| 49 |
+
convert_np_embeddings_to_list,
|
| 50 |
+
IncludeMetadataDocuments,
|
| 51 |
+
IncludeMetadataDocumentsDistances,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
from chromadb.api.types import (
|
| 55 |
+
IncludeMetadataDocumentsEmbeddings,
|
| 56 |
+
serialize_metadata,
|
| 57 |
+
deserialize_metadata,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
logger = logging.getLogger(__name__)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class AsyncFastAPI(BaseHTTPClient, AsyncServerAPI):
|
| 65 |
+
# We make one client per event loop to avoid unexpected issues if a client
|
| 66 |
+
# is shared between event loops.
|
| 67 |
+
# For example, if a client is constructed in the main thread, then passed
|
| 68 |
+
# (or a returned Collection is passed) to a new thread, the client would
|
| 69 |
+
# normally throw an obscure asyncio error.
|
| 70 |
+
# Mixing asyncio and threading in this manner usually discouraged, but
|
| 71 |
+
# this gives a better user experience with practically no downsides.
|
| 72 |
+
# https://github.com/encode/httpx/issues/2058
|
| 73 |
+
_clients: Dict[int, httpx.AsyncClient] = {}
|
| 74 |
+
|
| 75 |
+
def __init__(self, system: System):
|
| 76 |
+
super().__init__(system)
|
| 77 |
+
|
| 78 |
+
system.settings.require("chroma_server_host")
|
| 79 |
+
system.settings.require("chroma_server_http_port")
|
| 80 |
+
|
| 81 |
+
self._opentelemetry_client = self.require(OpenTelemetryClient)
|
| 82 |
+
self._product_telemetry_client = self.require(ProductTelemetryClient)
|
| 83 |
+
self._settings = system.settings
|
| 84 |
+
|
| 85 |
+
self._api_url = AsyncFastAPI.resolve_url(
|
| 86 |
+
chroma_server_host=str(system.settings.chroma_server_host),
|
| 87 |
+
chroma_server_http_port=system.settings.chroma_server_http_port,
|
| 88 |
+
chroma_server_ssl_enabled=system.settings.chroma_server_ssl_enabled,
|
| 89 |
+
default_api_path=system.settings.chroma_server_api_default_path,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
async def __aenter__(self) -> "AsyncFastAPI":
|
| 93 |
+
self._get_client()
|
| 94 |
+
return self
|
| 95 |
+
|
| 96 |
+
async def _cleanup(self) -> None:
|
| 97 |
+
while len(self._clients) > 0:
|
| 98 |
+
(_, client) = self._clients.popitem()
|
| 99 |
+
await client.aclose()
|
| 100 |
+
|
| 101 |
+
async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
|
| 102 |
+
await self._cleanup()
|
| 103 |
+
|
| 104 |
+
@override
|
| 105 |
+
def stop(self) -> None:
|
| 106 |
+
super().stop()
|
| 107 |
+
|
| 108 |
+
@async_to_sync
|
| 109 |
+
async def sync_cleanup() -> None:
|
| 110 |
+
await self._cleanup()
|
| 111 |
+
|
| 112 |
+
sync_cleanup()
|
| 113 |
+
|
| 114 |
+
def _get_client(self) -> httpx.AsyncClient:
|
| 115 |
+
# Ideally this would use anyio to be compatible with both
|
| 116 |
+
# asyncio and trio, but anyio does not expose any way to identify
|
| 117 |
+
# the current event loop.
|
| 118 |
+
# We attempt to get the loop assuming the environment is asyncio, and
|
| 119 |
+
# otherwise gracefully fall back to using a singleton client.
|
| 120 |
+
loop_hash = None
|
| 121 |
+
try:
|
| 122 |
+
loop = asyncio.get_event_loop()
|
| 123 |
+
loop_hash = loop.__hash__()
|
| 124 |
+
except RuntimeError:
|
| 125 |
+
loop_hash = 0
|
| 126 |
+
|
| 127 |
+
if loop_hash not in self._clients:
|
| 128 |
+
headers = (self._settings.chroma_server_headers or {}).copy()
|
| 129 |
+
headers["Content-Type"] = "application/json"
|
| 130 |
+
headers["User-Agent"] = (
|
| 131 |
+
"Chroma Python Client v"
|
| 132 |
+
+ __version__
|
| 133 |
+
+ " (https://github.com/chroma-core/chroma)"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
self._clients[loop_hash] = httpx.AsyncClient(
|
| 137 |
+
timeout=None,
|
| 138 |
+
headers=headers,
|
| 139 |
+
verify=self._settings.chroma_server_ssl_verify or False,
|
| 140 |
+
limits=self.http_limits,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
return self._clients[loop_hash]
|
| 144 |
+
|
| 145 |
+
@override
|
| 146 |
+
def get_request_headers(self) -> Mapping[str, str]:
|
| 147 |
+
return dict(self._get_client().headers)
|
| 148 |
+
|
| 149 |
+
@override
|
| 150 |
+
def get_api_url(self) -> str:
|
| 151 |
+
return self._api_url
|
| 152 |
+
|
| 153 |
+
async def _make_request(
|
| 154 |
+
self, method: str, path: str, **kwargs: Dict[str, Any]
|
| 155 |
+
) -> Any:
|
| 156 |
+
# If the request has json in kwargs, use orjson to serialize it,
|
| 157 |
+
# remove it from kwargs, and add it to the content parameter
|
| 158 |
+
# This is because httpx uses a slower json serializer
|
| 159 |
+
if "json" in kwargs:
|
| 160 |
+
data = orjson.dumps(kwargs.pop("json"), option=orjson.OPT_SERIALIZE_NUMPY)
|
| 161 |
+
kwargs["content"] = data
|
| 162 |
+
|
| 163 |
+
# Unlike requests, httpx does not automatically escape the path
|
| 164 |
+
escaped_path = urllib.parse.quote(path, safe="/", encoding=None, errors=None)
|
| 165 |
+
url = self._api_url + escaped_path
|
| 166 |
+
|
| 167 |
+
response = await self._get_client().request(method, url, **cast(Any, kwargs))
|
| 168 |
+
BaseHTTPClient._raise_chroma_error(response)
|
| 169 |
+
return orjson.loads(response.text)
|
| 170 |
+
|
| 171 |
+
@trace_method("AsyncFastAPI.heartbeat", OpenTelemetryGranularity.OPERATION)
|
| 172 |
+
@override
|
| 173 |
+
async def heartbeat(self) -> int:
|
| 174 |
+
response = await self._make_request("get", "")
|
| 175 |
+
return int(response["nanosecond heartbeat"])
|
| 176 |
+
|
| 177 |
+
@trace_method("AsyncFastAPI.create_database", OpenTelemetryGranularity.OPERATION)
|
| 178 |
+
@override
|
| 179 |
+
async def create_database(
|
| 180 |
+
self,
|
| 181 |
+
name: str,
|
| 182 |
+
tenant: str = DEFAULT_TENANT,
|
| 183 |
+
) -> None:
|
| 184 |
+
await self._make_request(
|
| 185 |
+
"post",
|
| 186 |
+
f"/tenants/{tenant}/databases",
|
| 187 |
+
json={"name": name},
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
@trace_method("AsyncFastAPI.get_database", OpenTelemetryGranularity.OPERATION)
|
| 191 |
+
@override
|
| 192 |
+
async def get_database(
|
| 193 |
+
self,
|
| 194 |
+
name: str,
|
| 195 |
+
tenant: str = DEFAULT_TENANT,
|
| 196 |
+
) -> Database:
|
| 197 |
+
response = await self._make_request(
|
| 198 |
+
"get",
|
| 199 |
+
f"/tenants/{tenant}/databases/{name}",
|
| 200 |
+
params={"tenant": tenant},
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
return Database(
|
| 204 |
+
id=response["id"], name=response["name"], tenant=response["tenant"]
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
@trace_method("AsyncFastAPI.delete_database", OpenTelemetryGranularity.OPERATION)
|
| 208 |
+
@override
|
| 209 |
+
async def delete_database(
|
| 210 |
+
self,
|
| 211 |
+
name: str,
|
| 212 |
+
tenant: str = DEFAULT_TENANT,
|
| 213 |
+
) -> None:
|
| 214 |
+
await self._make_request(
|
| 215 |
+
"delete",
|
| 216 |
+
f"/tenants/{tenant}/databases/{name}",
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
@trace_method("AsyncFastAPI.list_databases", OpenTelemetryGranularity.OPERATION)
|
| 220 |
+
@override
|
| 221 |
+
async def list_databases(
|
| 222 |
+
self,
|
| 223 |
+
limit: Optional[int] = None,
|
| 224 |
+
offset: Optional[int] = None,
|
| 225 |
+
tenant: str = DEFAULT_TENANT,
|
| 226 |
+
) -> Sequence[Database]:
|
| 227 |
+
response = await self._make_request(
|
| 228 |
+
"get",
|
| 229 |
+
f"/tenants/{tenant}/databases",
|
| 230 |
+
params=BaseHTTPClient._clean_params(
|
| 231 |
+
{
|
| 232 |
+
"limit": limit,
|
| 233 |
+
"offset": offset,
|
| 234 |
+
}
|
| 235 |
+
),
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
return [
|
| 239 |
+
Database(id=db["id"], name=db["name"], tenant=db["tenant"])
|
| 240 |
+
for db in response
|
| 241 |
+
]
|
| 242 |
+
|
| 243 |
+
@trace_method("AsyncFastAPI.create_tenant", OpenTelemetryGranularity.OPERATION)
|
| 244 |
+
@override
|
| 245 |
+
async def create_tenant(self, name: str) -> None:
|
| 246 |
+
await self._make_request(
|
| 247 |
+
"post",
|
| 248 |
+
"/tenants",
|
| 249 |
+
json={"name": name},
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
@trace_method("AsyncFastAPI.get_tenant", OpenTelemetryGranularity.OPERATION)
|
| 253 |
+
@override
|
| 254 |
+
async def get_tenant(self, name: str) -> Tenant:
|
| 255 |
+
resp_json = await self._make_request(
|
| 256 |
+
"get",
|
| 257 |
+
"/tenants/" + name,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
return Tenant(name=resp_json["name"])
|
| 261 |
+
|
| 262 |
+
@trace_method("AsyncFastAPI.get_user_identity", OpenTelemetryGranularity.OPERATION)
|
| 263 |
+
@override
|
| 264 |
+
async def get_user_identity(self) -> UserIdentity:
|
| 265 |
+
return UserIdentity(**(await self._make_request("get", "/auth/identity")))
|
| 266 |
+
|
| 267 |
+
@trace_method("AsyncFastAPI.list_collections", OpenTelemetryGranularity.OPERATION)
|
| 268 |
+
@override
|
| 269 |
+
async def list_collections(
|
| 270 |
+
self,
|
| 271 |
+
limit: Optional[int] = None,
|
| 272 |
+
offset: Optional[int] = None,
|
| 273 |
+
tenant: str = DEFAULT_TENANT,
|
| 274 |
+
database: str = DEFAULT_DATABASE,
|
| 275 |
+
) -> Sequence[CollectionModel]:
|
| 276 |
+
resp_json = await self._make_request(
|
| 277 |
+
"get",
|
| 278 |
+
f"/tenants/{tenant}/databases/{database}/collections",
|
| 279 |
+
params=BaseHTTPClient._clean_params(
|
| 280 |
+
{
|
| 281 |
+
"limit": limit,
|
| 282 |
+
"offset": offset,
|
| 283 |
+
}
|
| 284 |
+
),
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
models = [
|
| 288 |
+
CollectionModel.from_json(json_collection) for json_collection in resp_json
|
| 289 |
+
]
|
| 290 |
+
return models
|
| 291 |
+
|
| 292 |
+
@trace_method("AsyncFastAPI.count_collections", OpenTelemetryGranularity.OPERATION)
|
| 293 |
+
@override
|
| 294 |
+
async def count_collections(
|
| 295 |
+
self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE
|
| 296 |
+
) -> int:
|
| 297 |
+
resp_json = await self._make_request(
|
| 298 |
+
"get",
|
| 299 |
+
f"/tenants/{tenant}/databases/{database}/collections_count",
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
return cast(int, resp_json)
|
| 303 |
+
|
| 304 |
+
@trace_method("AsyncFastAPI.create_collection", OpenTelemetryGranularity.OPERATION)
|
| 305 |
+
@override
|
| 306 |
+
async def create_collection(
|
| 307 |
+
self,
|
| 308 |
+
name: str,
|
| 309 |
+
schema: Optional[Schema] = None,
|
| 310 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 311 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 312 |
+
get_or_create: bool = False,
|
| 313 |
+
tenant: str = DEFAULT_TENANT,
|
| 314 |
+
database: str = DEFAULT_DATABASE,
|
| 315 |
+
) -> CollectionModel:
|
| 316 |
+
"""Creates a collection"""
|
| 317 |
+
config_json = (
|
| 318 |
+
create_collection_configuration_to_json(configuration, metadata)
|
| 319 |
+
if configuration
|
| 320 |
+
else None
|
| 321 |
+
)
|
| 322 |
+
serialized_schema = schema.serialize_to_json() if schema else None
|
| 323 |
+
resp_json = await self._make_request(
|
| 324 |
+
"post",
|
| 325 |
+
f"/tenants/{tenant}/databases/{database}/collections",
|
| 326 |
+
json={
|
| 327 |
+
"name": name,
|
| 328 |
+
"metadata": metadata,
|
| 329 |
+
"configuration": config_json,
|
| 330 |
+
"schema": serialized_schema,
|
| 331 |
+
"get_or_create": get_or_create,
|
| 332 |
+
},
|
| 333 |
+
)
|
| 334 |
+
model = CollectionModel.from_json(resp_json)
|
| 335 |
+
|
| 336 |
+
return model
|
| 337 |
+
|
| 338 |
+
@trace_method("AsyncFastAPI.get_collection", OpenTelemetryGranularity.OPERATION)
|
| 339 |
+
@override
|
| 340 |
+
async def get_collection(
|
| 341 |
+
self,
|
| 342 |
+
name: str,
|
| 343 |
+
tenant: str = DEFAULT_TENANT,
|
| 344 |
+
database: str = DEFAULT_DATABASE,
|
| 345 |
+
) -> CollectionModel:
|
| 346 |
+
resp_json = await self._make_request(
|
| 347 |
+
"get",
|
| 348 |
+
f"/tenants/{tenant}/databases/{database}/collections/{name}",
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
model = CollectionModel.from_json(resp_json)
|
| 352 |
+
|
| 353 |
+
return model
|
| 354 |
+
|
| 355 |
+
@trace_method(
|
| 356 |
+
"AsyncFastAPI.get_collection_by_id", OpenTelemetryGranularity.OPERATION
|
| 357 |
+
)
|
| 358 |
+
@override
|
| 359 |
+
async def get_collection_by_id(
|
| 360 |
+
self,
|
| 361 |
+
collection_id: UUID,
|
| 362 |
+
tenant: str = DEFAULT_TENANT,
|
| 363 |
+
database: str = DEFAULT_DATABASE,
|
| 364 |
+
) -> CollectionModel:
|
| 365 |
+
"""Returns a collection by its ID"""
|
| 366 |
+
resp_json = await self._make_request(
|
| 367 |
+
"get",
|
| 368 |
+
f"/tenants/{tenant}/databases/{database}/collections/by-id/{collection_id}",
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
model = CollectionModel.from_json(resp_json)
|
| 372 |
+
|
| 373 |
+
return model
|
| 374 |
+
|
| 375 |
+
@trace_method(
|
| 376 |
+
"AsyncFastAPI.get_or_create_collection", OpenTelemetryGranularity.OPERATION
|
| 377 |
+
)
|
| 378 |
+
@override
|
| 379 |
+
async def get_or_create_collection(
|
| 380 |
+
self,
|
| 381 |
+
name: str,
|
| 382 |
+
schema: Optional[Schema] = None,
|
| 383 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 384 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 385 |
+
tenant: str = DEFAULT_TENANT,
|
| 386 |
+
database: str = DEFAULT_DATABASE,
|
| 387 |
+
) -> CollectionModel:
|
| 388 |
+
return await self.create_collection(
|
| 389 |
+
name=name,
|
| 390 |
+
schema=schema,
|
| 391 |
+
configuration=configuration,
|
| 392 |
+
metadata=metadata,
|
| 393 |
+
get_or_create=True,
|
| 394 |
+
tenant=tenant,
|
| 395 |
+
database=database,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
@trace_method("AsyncFastAPI._modify", OpenTelemetryGranularity.OPERATION)
|
| 399 |
+
@override
|
| 400 |
+
async def _modify(
|
| 401 |
+
self,
|
| 402 |
+
id: UUID,
|
| 403 |
+
new_name: Optional[str] = None,
|
| 404 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 405 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 406 |
+
tenant: str = DEFAULT_TENANT,
|
| 407 |
+
database: str = DEFAULT_DATABASE,
|
| 408 |
+
) -> None:
|
| 409 |
+
await self._make_request(
|
| 410 |
+
"put",
|
| 411 |
+
f"/tenants/{tenant}/databases/{database}/collections/{id}",
|
| 412 |
+
json={
|
| 413 |
+
"new_metadata": new_metadata,
|
| 414 |
+
"new_name": new_name,
|
| 415 |
+
"new_configuration": update_collection_configuration_to_json(
|
| 416 |
+
new_configuration
|
| 417 |
+
)
|
| 418 |
+
if new_configuration
|
| 419 |
+
else None,
|
| 420 |
+
},
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
@trace_method("AsyncFastAPI._fork", OpenTelemetryGranularity.OPERATION)
|
| 424 |
+
@override
|
| 425 |
+
async def _fork(
|
| 426 |
+
self,
|
| 427 |
+
collection_id: UUID,
|
| 428 |
+
new_name: str,
|
| 429 |
+
tenant: str = DEFAULT_TENANT,
|
| 430 |
+
database: str = DEFAULT_DATABASE,
|
| 431 |
+
) -> CollectionModel:
|
| 432 |
+
resp_json = await self._make_request(
|
| 433 |
+
"post",
|
| 434 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/fork",
|
| 435 |
+
json={"new_name": new_name},
|
| 436 |
+
)
|
| 437 |
+
model = CollectionModel.from_json(resp_json)
|
| 438 |
+
return model
|
| 439 |
+
|
| 440 |
+
@trace_method("AsyncFastAPI._fork_count", OpenTelemetryGranularity.OPERATION)
|
| 441 |
+
@override
|
| 442 |
+
async def _fork_count(
|
| 443 |
+
self,
|
| 444 |
+
collection_id: UUID,
|
| 445 |
+
tenant: str = DEFAULT_TENANT,
|
| 446 |
+
database: str = DEFAULT_DATABASE,
|
| 447 |
+
) -> int:
|
| 448 |
+
resp_json = await self._make_request(
|
| 449 |
+
"get",
|
| 450 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/fork_count",
|
| 451 |
+
)
|
| 452 |
+
return int(resp_json["count"])
|
| 453 |
+
|
| 454 |
+
@trace_method(
|
| 455 |
+
"AsyncFastAPI._get_indexing_status", OpenTelemetryGranularity.OPERATION
|
| 456 |
+
)
|
| 457 |
+
@override
|
| 458 |
+
async def _get_indexing_status(
|
| 459 |
+
self,
|
| 460 |
+
collection_id: UUID,
|
| 461 |
+
tenant: str = DEFAULT_TENANT,
|
| 462 |
+
database: str = DEFAULT_DATABASE,
|
| 463 |
+
) -> IndexingStatus:
|
| 464 |
+
resp_json = await self._make_request(
|
| 465 |
+
"get",
|
| 466 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/indexing_status",
|
| 467 |
+
)
|
| 468 |
+
return IndexingStatus(
|
| 469 |
+
num_indexed_ops=resp_json["num_indexed_ops"],
|
| 470 |
+
num_unindexed_ops=resp_json["num_unindexed_ops"],
|
| 471 |
+
total_ops=resp_json["total_ops"],
|
| 472 |
+
op_indexing_progress=resp_json["op_indexing_progress"],
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
@trace_method("AsyncFastAPI._search", OpenTelemetryGranularity.OPERATION)
|
| 476 |
+
@override
|
| 477 |
+
async def _search(
|
| 478 |
+
self,
|
| 479 |
+
collection_id: UUID,
|
| 480 |
+
searches: List[Search],
|
| 481 |
+
tenant: str = DEFAULT_TENANT,
|
| 482 |
+
database: str = DEFAULT_DATABASE,
|
| 483 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 484 |
+
) -> SearchResult:
|
| 485 |
+
"""Performs hybrid search on a collection"""
|
| 486 |
+
payload = {
|
| 487 |
+
"searches": [s.to_dict() for s in searches],
|
| 488 |
+
"read_level": read_level,
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
resp_json = await self._make_request(
|
| 492 |
+
"post",
|
| 493 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/search",
|
| 494 |
+
json=payload,
|
| 495 |
+
)
|
| 496 |
+
|
| 497 |
+
metadata_batches = resp_json.get("metadatas", None)
|
| 498 |
+
if metadata_batches is not None:
|
| 499 |
+
resp_json["metadatas"] = [
|
| 500 |
+
[
|
| 501 |
+
deserialize_metadata(metadata) if metadata is not None else None
|
| 502 |
+
for metadata in metadatas
|
| 503 |
+
]
|
| 504 |
+
if metadatas is not None
|
| 505 |
+
else None
|
| 506 |
+
for metadatas in metadata_batches
|
| 507 |
+
]
|
| 508 |
+
|
| 509 |
+
return SearchResult(resp_json)
|
| 510 |
+
|
| 511 |
+
@trace_method("AsyncFastAPI.delete_collection", OpenTelemetryGranularity.OPERATION)
|
| 512 |
+
@override
|
| 513 |
+
async def delete_collection(
|
| 514 |
+
self,
|
| 515 |
+
name: str,
|
| 516 |
+
tenant: str = DEFAULT_TENANT,
|
| 517 |
+
database: str = DEFAULT_DATABASE,
|
| 518 |
+
) -> None:
|
| 519 |
+
await self._make_request(
|
| 520 |
+
"delete",
|
| 521 |
+
f"/tenants/{tenant}/databases/{database}/collections/{name}",
|
| 522 |
+
)
|
| 523 |
+
|
| 524 |
+
@trace_method("AsyncFastAPI._count", OpenTelemetryGranularity.OPERATION)
|
| 525 |
+
@override
|
| 526 |
+
async def _count(
|
| 527 |
+
self,
|
| 528 |
+
collection_id: UUID,
|
| 529 |
+
tenant: str = DEFAULT_TENANT,
|
| 530 |
+
database: str = DEFAULT_DATABASE,
|
| 531 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 532 |
+
) -> int:
|
| 533 |
+
"""Returns the number of embeddings in the database"""
|
| 534 |
+
resp_json = await self._make_request(
|
| 535 |
+
"get",
|
| 536 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/count",
|
| 537 |
+
params={"read_level": read_level.value},
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
return cast(int, resp_json)
|
| 541 |
+
|
| 542 |
+
@trace_method("AsyncFastAPI._peek", OpenTelemetryGranularity.OPERATION)
|
| 543 |
+
@override
|
| 544 |
+
async def _peek(
|
| 545 |
+
self,
|
| 546 |
+
collection_id: UUID,
|
| 547 |
+
n: int = 10,
|
| 548 |
+
tenant: str = DEFAULT_TENANT,
|
| 549 |
+
database: str = DEFAULT_DATABASE,
|
| 550 |
+
) -> GetResult:
|
| 551 |
+
resp = await self._get(
|
| 552 |
+
collection_id,
|
| 553 |
+
tenant=tenant,
|
| 554 |
+
database=database,
|
| 555 |
+
limit=n,
|
| 556 |
+
include=IncludeMetadataDocumentsEmbeddings,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
return resp
|
| 560 |
+
|
| 561 |
+
@trace_method("AsyncFastAPI._get", OpenTelemetryGranularity.OPERATION)
|
| 562 |
+
@override
|
| 563 |
+
async def _get(
|
| 564 |
+
self,
|
| 565 |
+
collection_id: UUID,
|
| 566 |
+
ids: Optional[IDs] = None,
|
| 567 |
+
where: Optional[Where] = None,
|
| 568 |
+
limit: Optional[int] = None,
|
| 569 |
+
offset: Optional[int] = None,
|
| 570 |
+
where_document: Optional[WhereDocument] = None,
|
| 571 |
+
include: Include = IncludeMetadataDocuments,
|
| 572 |
+
tenant: str = DEFAULT_TENANT,
|
| 573 |
+
database: str = DEFAULT_DATABASE,
|
| 574 |
+
) -> GetResult:
|
| 575 |
+
# Servers do not support the "data" include, as that is hydrated on the client side
|
| 576 |
+
filtered_include = [i for i in include if i != "data"]
|
| 577 |
+
|
| 578 |
+
resp_json = await self._make_request(
|
| 579 |
+
"post",
|
| 580 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/get",
|
| 581 |
+
json={
|
| 582 |
+
"ids": ids,
|
| 583 |
+
"where": where,
|
| 584 |
+
"limit": limit,
|
| 585 |
+
"offset": offset,
|
| 586 |
+
"where_document": where_document,
|
| 587 |
+
"include": filtered_include,
|
| 588 |
+
},
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
metadatas = resp_json.get("metadatas", None)
|
| 592 |
+
if metadatas is not None:
|
| 593 |
+
metadatas = [
|
| 594 |
+
deserialize_metadata(metadata) if metadata is not None else None
|
| 595 |
+
for metadata in metadatas
|
| 596 |
+
]
|
| 597 |
+
|
| 598 |
+
return GetResult(
|
| 599 |
+
ids=resp_json["ids"],
|
| 600 |
+
embeddings=resp_json.get("embeddings", None),
|
| 601 |
+
metadatas=metadatas,
|
| 602 |
+
documents=resp_json.get("documents", None),
|
| 603 |
+
data=None,
|
| 604 |
+
uris=resp_json.get("uris", None),
|
| 605 |
+
included=include,
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
@trace_method("AsyncFastAPI._delete", OpenTelemetryGranularity.OPERATION)
|
| 609 |
+
@override
|
| 610 |
+
async def _delete(
|
| 611 |
+
self,
|
| 612 |
+
collection_id: UUID,
|
| 613 |
+
ids: Optional[IDs] = None,
|
| 614 |
+
where: Optional[Where] = None,
|
| 615 |
+
where_document: Optional[WhereDocument] = None,
|
| 616 |
+
limit: Optional[int] = None,
|
| 617 |
+
tenant: str = DEFAULT_TENANT,
|
| 618 |
+
database: str = DEFAULT_DATABASE,
|
| 619 |
+
) -> DeleteResult:
|
| 620 |
+
body: dict = {"where": where, "ids": ids, "where_document": where_document}
|
| 621 |
+
if limit is not None:
|
| 622 |
+
body["limit"] = limit
|
| 623 |
+
resp = await self._make_request(
|
| 624 |
+
"post",
|
| 625 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/delete",
|
| 626 |
+
json=body,
|
| 627 |
+
)
|
| 628 |
+
return DeleteResult(deleted=resp.get("deleted", 0) if resp else 0)
|
| 629 |
+
|
| 630 |
+
@trace_method("AsyncFastAPI._submit_batch", OpenTelemetryGranularity.ALL)
|
| 631 |
+
async def _submit_batch(
|
| 632 |
+
self,
|
| 633 |
+
batch: Tuple[
|
| 634 |
+
IDs,
|
| 635 |
+
Optional[Embeddings],
|
| 636 |
+
Optional[Metadatas],
|
| 637 |
+
Optional[Documents],
|
| 638 |
+
Optional[URIs],
|
| 639 |
+
],
|
| 640 |
+
url: str,
|
| 641 |
+
) -> Any:
|
| 642 |
+
"""
|
| 643 |
+
Submits a batch of embeddings to the database
|
| 644 |
+
"""
|
| 645 |
+
supports_base64_encoding = await self.supports_base64_encoding()
|
| 646 |
+
|
| 647 |
+
serialized_metadatas = None
|
| 648 |
+
if batch[2] is not None:
|
| 649 |
+
serialized_metadatas = [
|
| 650 |
+
serialize_metadata(metadata) if metadata is not None else None
|
| 651 |
+
for metadata in batch[2]
|
| 652 |
+
]
|
| 653 |
+
|
| 654 |
+
data = {
|
| 655 |
+
"ids": batch[0],
|
| 656 |
+
"embeddings": optional_embeddings_to_base64_strings(batch[1])
|
| 657 |
+
if supports_base64_encoding
|
| 658 |
+
else batch[1],
|
| 659 |
+
"metadatas": serialized_metadatas,
|
| 660 |
+
"documents": batch[3],
|
| 661 |
+
"uris": batch[4],
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
return await self._make_request(
|
| 665 |
+
"post",
|
| 666 |
+
url,
|
| 667 |
+
json=data,
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
@trace_method("AsyncFastAPI._add", OpenTelemetryGranularity.ALL)
|
| 671 |
+
@override
|
| 672 |
+
async def _add(
|
| 673 |
+
self,
|
| 674 |
+
ids: IDs,
|
| 675 |
+
collection_id: UUID,
|
| 676 |
+
embeddings: Embeddings,
|
| 677 |
+
metadatas: Optional[Metadatas] = None,
|
| 678 |
+
documents: Optional[Documents] = None,
|
| 679 |
+
uris: Optional[URIs] = None,
|
| 680 |
+
tenant: str = DEFAULT_TENANT,
|
| 681 |
+
database: str = DEFAULT_DATABASE,
|
| 682 |
+
) -> bool:
|
| 683 |
+
batch = (
|
| 684 |
+
ids,
|
| 685 |
+
embeddings,
|
| 686 |
+
metadatas,
|
| 687 |
+
documents,
|
| 688 |
+
uris,
|
| 689 |
+
)
|
| 690 |
+
validate_batch(batch, {"max_batch_size": await self.get_max_batch_size()})
|
| 691 |
+
await self._submit_batch(
|
| 692 |
+
batch,
|
| 693 |
+
f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/add",
|
| 694 |
+
)
|
| 695 |
+
return True
|
| 696 |
+
|
| 697 |
+
@trace_method("AsyncFastAPI._update", OpenTelemetryGranularity.ALL)
|
| 698 |
+
@override
|
| 699 |
+
async def _update(
|
| 700 |
+
self,
|
| 701 |
+
collection_id: UUID,
|
| 702 |
+
ids: IDs,
|
| 703 |
+
embeddings: Optional[Embeddings] = None,
|
| 704 |
+
metadatas: Optional[Metadatas] = None,
|
| 705 |
+
documents: Optional[Documents] = None,
|
| 706 |
+
uris: Optional[URIs] = None,
|
| 707 |
+
tenant: str = DEFAULT_TENANT,
|
| 708 |
+
database: str = DEFAULT_DATABASE,
|
| 709 |
+
) -> bool:
|
| 710 |
+
batch = (
|
| 711 |
+
ids,
|
| 712 |
+
embeddings if embeddings is not None else None,
|
| 713 |
+
metadatas,
|
| 714 |
+
documents,
|
| 715 |
+
uris,
|
| 716 |
+
)
|
| 717 |
+
validate_batch(batch, {"max_batch_size": await self.get_max_batch_size()})
|
| 718 |
+
|
| 719 |
+
await self._submit_batch(
|
| 720 |
+
batch,
|
| 721 |
+
f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/update",
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
return True
|
| 725 |
+
|
| 726 |
+
@trace_method("AsyncFastAPI._upsert", OpenTelemetryGranularity.ALL)
|
| 727 |
+
@override
|
| 728 |
+
async def _upsert(
|
| 729 |
+
self,
|
| 730 |
+
collection_id: UUID,
|
| 731 |
+
ids: IDs,
|
| 732 |
+
embeddings: Embeddings,
|
| 733 |
+
metadatas: Optional[Metadatas] = None,
|
| 734 |
+
documents: Optional[Documents] = None,
|
| 735 |
+
uris: Optional[URIs] = None,
|
| 736 |
+
tenant: str = DEFAULT_TENANT,
|
| 737 |
+
database: str = DEFAULT_DATABASE,
|
| 738 |
+
) -> bool:
|
| 739 |
+
batch = (
|
| 740 |
+
ids,
|
| 741 |
+
embeddings,
|
| 742 |
+
metadatas,
|
| 743 |
+
documents,
|
| 744 |
+
uris,
|
| 745 |
+
)
|
| 746 |
+
validate_batch(batch, {"max_batch_size": await self.get_max_batch_size()})
|
| 747 |
+
await self._submit_batch(
|
| 748 |
+
batch,
|
| 749 |
+
f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/upsert",
|
| 750 |
+
)
|
| 751 |
+
return True
|
| 752 |
+
|
| 753 |
+
@trace_method("AsyncFastAPI._query", OpenTelemetryGranularity.ALL)
|
| 754 |
+
@override
|
| 755 |
+
async def _query(
|
| 756 |
+
self,
|
| 757 |
+
collection_id: UUID,
|
| 758 |
+
query_embeddings: Embeddings,
|
| 759 |
+
ids: Optional[IDs] = None,
|
| 760 |
+
n_results: int = 10,
|
| 761 |
+
where: Optional[Where] = None,
|
| 762 |
+
where_document: Optional[WhereDocument] = None,
|
| 763 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 764 |
+
tenant: str = DEFAULT_TENANT,
|
| 765 |
+
database: str = DEFAULT_DATABASE,
|
| 766 |
+
) -> QueryResult:
|
| 767 |
+
# Servers do not support the "data" include, as that is hydrated on the client side
|
| 768 |
+
filtered_include = [i for i in include if i != "data"]
|
| 769 |
+
|
| 770 |
+
resp_json = await self._make_request(
|
| 771 |
+
"post",
|
| 772 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/query",
|
| 773 |
+
json={
|
| 774 |
+
"ids": ids,
|
| 775 |
+
"query_embeddings": convert_np_embeddings_to_list(query_embeddings)
|
| 776 |
+
if query_embeddings is not None
|
| 777 |
+
else None,
|
| 778 |
+
"n_results": n_results,
|
| 779 |
+
"where": where,
|
| 780 |
+
"where_document": where_document,
|
| 781 |
+
"include": filtered_include,
|
| 782 |
+
},
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
metadata_batches = resp_json.get("metadatas", None)
|
| 786 |
+
if metadata_batches is not None:
|
| 787 |
+
metadata_batches = [
|
| 788 |
+
[
|
| 789 |
+
deserialize_metadata(metadata) if metadata is not None else None
|
| 790 |
+
for metadata in metadatas
|
| 791 |
+
]
|
| 792 |
+
if metadatas is not None
|
| 793 |
+
else None
|
| 794 |
+
for metadatas in metadata_batches
|
| 795 |
+
]
|
| 796 |
+
|
| 797 |
+
return QueryResult(
|
| 798 |
+
ids=resp_json["ids"],
|
| 799 |
+
distances=resp_json.get("distances", None),
|
| 800 |
+
embeddings=resp_json.get("embeddings", None),
|
| 801 |
+
metadatas=metadata_batches,
|
| 802 |
+
documents=resp_json.get("documents", None),
|
| 803 |
+
uris=resp_json.get("uris", None),
|
| 804 |
+
data=None,
|
| 805 |
+
included=include,
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
+
@trace_method("AsyncFastAPI.reset", OpenTelemetryGranularity.ALL)
|
| 809 |
+
@override
|
| 810 |
+
async def reset(self) -> bool:
|
| 811 |
+
resp_json = await self._make_request("post", "/reset")
|
| 812 |
+
return cast(bool, resp_json)
|
| 813 |
+
|
| 814 |
+
@trace_method("AsyncFastAPI.get_version", OpenTelemetryGranularity.OPERATION)
|
| 815 |
+
@override
|
| 816 |
+
async def get_version(self) -> str:
|
| 817 |
+
resp_json = await self._make_request("get", "/version")
|
| 818 |
+
return cast(str, resp_json)
|
| 819 |
+
|
| 820 |
+
@override
|
| 821 |
+
def get_settings(self) -> Settings:
|
| 822 |
+
return self._settings
|
| 823 |
+
|
| 824 |
+
@trace_method(
|
| 825 |
+
"AsyncFastAPI.get_pre_flight_checks", OpenTelemetryGranularity.OPERATION
|
| 826 |
+
)
|
| 827 |
+
async def get_pre_flight_checks(self) -> Any:
|
| 828 |
+
if self.pre_flight_checks is None:
|
| 829 |
+
resp_json = await self._make_request("get", "/pre-flight-checks")
|
| 830 |
+
self.pre_flight_checks = resp_json
|
| 831 |
+
return self.pre_flight_checks
|
| 832 |
+
|
| 833 |
+
@trace_method(
|
| 834 |
+
"AsyncFastAPI.supports_base64_encoding", OpenTelemetryGranularity.OPERATION
|
| 835 |
+
)
|
| 836 |
+
async def supports_base64_encoding(self) -> bool:
|
| 837 |
+
pre_flight_checks = await self.get_pre_flight_checks()
|
| 838 |
+
b64_encoding_enabled = cast(
|
| 839 |
+
bool, pre_flight_checks.get("supports_base64_encoding", False)
|
| 840 |
+
)
|
| 841 |
+
return b64_encoding_enabled
|
| 842 |
+
|
| 843 |
+
@trace_method("AsyncFastAPI.get_max_batch_size", OpenTelemetryGranularity.OPERATION)
|
| 844 |
+
@override
|
| 845 |
+
async def get_max_batch_size(self) -> int:
|
| 846 |
+
pre_flight_checks = await self.get_pre_flight_checks()
|
| 847 |
+
max_batch_size = cast(int, pre_flight_checks.get("max_batch_size", -1))
|
| 848 |
+
return max_batch_size
|
python/user_packages/Python313/site-packages/chromadb/api/base_http_client.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, Mapping, Optional, TypeVar
|
| 2 |
+
from urllib.parse import quote, urlparse, urlunparse
|
| 3 |
+
import logging
|
| 4 |
+
import orjson as json
|
| 5 |
+
import httpx
|
| 6 |
+
|
| 7 |
+
import chromadb.errors as errors
|
| 8 |
+
from chromadb.config import Component, Settings, System
|
| 9 |
+
|
| 10 |
+
logger = logging.getLogger(__name__)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# inherits from Component so that it can create an init function to use system
|
| 14 |
+
# this way it can build limits from the settings in System
|
| 15 |
+
class BaseHTTPClient(Component):
|
| 16 |
+
_settings: Settings
|
| 17 |
+
pre_flight_checks: Any = None
|
| 18 |
+
DEFAULT_KEEPALIVE_SECS: float = 40.0
|
| 19 |
+
|
| 20 |
+
def __init__(self, system: System):
|
| 21 |
+
super().__init__(system)
|
| 22 |
+
self._settings = system.settings
|
| 23 |
+
keepalive_setting = self._settings.chroma_http_keepalive_secs
|
| 24 |
+
self.keepalive_secs: Optional[float] = (
|
| 25 |
+
keepalive_setting
|
| 26 |
+
if keepalive_setting is not None
|
| 27 |
+
else BaseHTTPClient.DEFAULT_KEEPALIVE_SECS
|
| 28 |
+
)
|
| 29 |
+
self._http_limits = self._build_limits()
|
| 30 |
+
|
| 31 |
+
def _build_limits(self) -> httpx.Limits:
|
| 32 |
+
limit_kwargs: Dict[str, Any] = {}
|
| 33 |
+
if self.keepalive_secs is not None:
|
| 34 |
+
limit_kwargs["keepalive_expiry"] = self.keepalive_secs
|
| 35 |
+
|
| 36 |
+
max_connections = self._settings.chroma_http_max_connections
|
| 37 |
+
if max_connections is not None:
|
| 38 |
+
limit_kwargs["max_connections"] = max_connections
|
| 39 |
+
|
| 40 |
+
max_keepalive_connections = self._settings.chroma_http_max_keepalive_connections
|
| 41 |
+
if max_keepalive_connections is not None:
|
| 42 |
+
limit_kwargs["max_keepalive_connections"] = max_keepalive_connections
|
| 43 |
+
|
| 44 |
+
return httpx.Limits(**limit_kwargs)
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def http_limits(self) -> httpx.Limits:
|
| 48 |
+
return self._http_limits
|
| 49 |
+
|
| 50 |
+
@staticmethod
|
| 51 |
+
def _validate_host(host: str) -> None:
|
| 52 |
+
parsed = urlparse(host)
|
| 53 |
+
if "/" in host and parsed.scheme not in {"http", "https"}:
|
| 54 |
+
raise ValueError(
|
| 55 |
+
"Invalid URL. " f"Unrecognized protocol - {parsed.scheme}."
|
| 56 |
+
)
|
| 57 |
+
if "/" in host and (not host.startswith("http")):
|
| 58 |
+
raise ValueError(
|
| 59 |
+
"Invalid URL. "
|
| 60 |
+
"Seems that you are trying to pass URL as a host but without \
|
| 61 |
+
specifying the protocol. "
|
| 62 |
+
"Please add http:// or https:// to the host."
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
@staticmethod
|
| 66 |
+
def resolve_url(
|
| 67 |
+
chroma_server_host: str,
|
| 68 |
+
chroma_server_ssl_enabled: Optional[bool] = False,
|
| 69 |
+
default_api_path: Optional[str] = "",
|
| 70 |
+
chroma_server_http_port: Optional[int] = 8000,
|
| 71 |
+
) -> str:
|
| 72 |
+
_skip_port = False
|
| 73 |
+
_chroma_server_host = chroma_server_host
|
| 74 |
+
BaseHTTPClient._validate_host(_chroma_server_host)
|
| 75 |
+
if _chroma_server_host.startswith("http"):
|
| 76 |
+
logger.debug("Skipping port as the user is passing a full URL")
|
| 77 |
+
_skip_port = True
|
| 78 |
+
parsed = urlparse(_chroma_server_host)
|
| 79 |
+
|
| 80 |
+
scheme = "https" if chroma_server_ssl_enabled else parsed.scheme or "http"
|
| 81 |
+
net_loc = parsed.netloc or parsed.hostname or chroma_server_host
|
| 82 |
+
port = (
|
| 83 |
+
":" + str(parsed.port or chroma_server_http_port) if not _skip_port else ""
|
| 84 |
+
)
|
| 85 |
+
path = parsed.path or default_api_path
|
| 86 |
+
|
| 87 |
+
if not path or path == net_loc:
|
| 88 |
+
path = default_api_path if default_api_path else ""
|
| 89 |
+
if not path.endswith(default_api_path or ""):
|
| 90 |
+
path = path + default_api_path if default_api_path else ""
|
| 91 |
+
full_url = urlunparse(
|
| 92 |
+
(scheme, f"{net_loc}{port}", quote(path.replace("//", "/")), "", "", "")
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
return full_url
|
| 96 |
+
|
| 97 |
+
# requests removes None values from the built query string, but httpx includes it as an empty value
|
| 98 |
+
T = TypeVar("T", bound=Dict[Any, Any])
|
| 99 |
+
|
| 100 |
+
@staticmethod
|
| 101 |
+
def _clean_params(params: T) -> T:
|
| 102 |
+
"""Remove None values from provided dict."""
|
| 103 |
+
return {k: v for k, v in params.items() if v is not None} # type: ignore
|
| 104 |
+
|
| 105 |
+
@staticmethod
|
| 106 |
+
def _raise_chroma_error(resp: httpx.Response) -> None:
|
| 107 |
+
"""Raises an error if the response is not ok, using a ChromaError if possible."""
|
| 108 |
+
try:
|
| 109 |
+
resp.raise_for_status()
|
| 110 |
+
return
|
| 111 |
+
except httpx.HTTPStatusError:
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
chroma_error = None
|
| 115 |
+
try:
|
| 116 |
+
body = json.loads(resp.text)
|
| 117 |
+
if "error" in body:
|
| 118 |
+
if body["error"] in errors.error_types:
|
| 119 |
+
chroma_error = errors.error_types[body["error"]](body["message"])
|
| 120 |
+
|
| 121 |
+
trace_id = resp.headers.get("chroma-trace-id")
|
| 122 |
+
if trace_id:
|
| 123 |
+
chroma_error.trace_id = trace_id
|
| 124 |
+
|
| 125 |
+
except BaseException:
|
| 126 |
+
pass
|
| 127 |
+
|
| 128 |
+
if chroma_error:
|
| 129 |
+
raise chroma_error
|
| 130 |
+
|
| 131 |
+
try:
|
| 132 |
+
resp.raise_for_status()
|
| 133 |
+
except httpx.HTTPStatusError:
|
| 134 |
+
trace_id = resp.headers.get("chroma-trace-id")
|
| 135 |
+
if trace_id:
|
| 136 |
+
raise Exception(f"{resp.text} (trace ID: {trace_id})")
|
| 137 |
+
raise (Exception(resp.text))
|
| 138 |
+
|
| 139 |
+
def get_request_headers(self) -> Mapping[str, str]:
|
| 140 |
+
"""Return headers used for HTTP requests."""
|
| 141 |
+
return {}
|
| 142 |
+
|
| 143 |
+
def get_api_url(self) -> str:
|
| 144 |
+
"""Return the API URL for this client."""
|
| 145 |
+
return ""
|
python/user_packages/Python313/site-packages/chromadb/api/client.py
ADDED
|
@@ -0,0 +1,731 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Sequence
|
| 2 |
+
from types import TracebackType
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
|
| 5 |
+
from overrides import override
|
| 6 |
+
import httpx
|
| 7 |
+
from chromadb.api import AdminAPI, ClientAPI, ServerAPI
|
| 8 |
+
from chromadb.api.collection_configuration import (
|
| 9 |
+
CreateCollectionConfiguration,
|
| 10 |
+
UpdateCollectionConfiguration,
|
| 11 |
+
validate_embedding_function_conflict_on_create,
|
| 12 |
+
validate_embedding_function_conflict_on_get,
|
| 13 |
+
)
|
| 14 |
+
from chromadb.api.shared_system_client import SharedSystemClient
|
| 15 |
+
from chromadb.api.types import (
|
| 16 |
+
CollectionMetadata,
|
| 17 |
+
DataLoader,
|
| 18 |
+
Documents,
|
| 19 |
+
Embeddable,
|
| 20 |
+
EmbeddingFunction,
|
| 21 |
+
Embeddings,
|
| 22 |
+
GetResult,
|
| 23 |
+
IDs,
|
| 24 |
+
Include,
|
| 25 |
+
Loadable,
|
| 26 |
+
Metadatas,
|
| 27 |
+
QueryResult,
|
| 28 |
+
Schema,
|
| 29 |
+
URIs,
|
| 30 |
+
IncludeMetadataDocuments,
|
| 31 |
+
IncludeMetadataDocumentsDistances,
|
| 32 |
+
DefaultEmbeddingFunction,
|
| 33 |
+
DeleteResult,
|
| 34 |
+
)
|
| 35 |
+
from chromadb.auth import UserIdentity
|
| 36 |
+
from chromadb.auth.utils import maybe_set_tenant_and_database
|
| 37 |
+
from chromadb.config import Settings, System
|
| 38 |
+
from chromadb.config import DEFAULT_TENANT, DEFAULT_DATABASE
|
| 39 |
+
from chromadb.api.models.Collection import Collection
|
| 40 |
+
from chromadb.errors import ChromaAuthError, ChromaError
|
| 41 |
+
from chromadb.types import Database, Tenant, Where, WhereDocument
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Client(SharedSystemClient, ClientAPI):
|
| 45 |
+
"""A client for Chroma. This is the main entrypoint for interacting with Chroma.
|
| 46 |
+
A client internally stores its tenant and database and proxies calls to a
|
| 47 |
+
Server API instance of Chroma. It treats the Server API and corresponding System
|
| 48 |
+
as a singleton, so multiple clients connecting to the same resource will share the
|
| 49 |
+
same API instance.
|
| 50 |
+
|
| 51 |
+
Client implementations should be implement their own API-caching strategies.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
tenant: str = DEFAULT_TENANT
|
| 55 |
+
database: str = DEFAULT_DATABASE
|
| 56 |
+
|
| 57 |
+
_server: ServerAPI
|
| 58 |
+
# An internal admin client for verifying that databases and tenants exist
|
| 59 |
+
_admin_client: AdminAPI
|
| 60 |
+
_closed: bool = False
|
| 61 |
+
|
| 62 |
+
# region Initialization
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
tenant: Optional[str] = DEFAULT_TENANT,
|
| 66 |
+
database: Optional[str] = DEFAULT_DATABASE,
|
| 67 |
+
settings: Settings = Settings(),
|
| 68 |
+
) -> None:
|
| 69 |
+
super().__init__(settings=settings)
|
| 70 |
+
try:
|
| 71 |
+
if tenant is not None:
|
| 72 |
+
self.tenant = tenant
|
| 73 |
+
if database is not None:
|
| 74 |
+
self.database = database
|
| 75 |
+
|
| 76 |
+
# Get the root system component we want to interact with
|
| 77 |
+
self._server = self._system.instance(ServerAPI)
|
| 78 |
+
|
| 79 |
+
user_identity = self.get_user_identity()
|
| 80 |
+
|
| 81 |
+
maybe_tenant, maybe_database = maybe_set_tenant_and_database(
|
| 82 |
+
user_identity,
|
| 83 |
+
overwrite_singleton_tenant_database_access_from_auth=settings.chroma_overwrite_singleton_tenant_database_access_from_auth,
|
| 84 |
+
user_provided_tenant=tenant,
|
| 85 |
+
user_provided_database=database,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
# this should not happen unless types are invalidated
|
| 89 |
+
if maybe_tenant is None and tenant is None:
|
| 90 |
+
raise ChromaAuthError(
|
| 91 |
+
"Could not determine a tenant from the current authentication method. Please provide a tenant."
|
| 92 |
+
)
|
| 93 |
+
if maybe_database is None and database is None:
|
| 94 |
+
raise ChromaAuthError(
|
| 95 |
+
"Could not determine a database name from the current authentication method. Please provide a database name."
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
if maybe_tenant:
|
| 99 |
+
self.tenant = maybe_tenant
|
| 100 |
+
if maybe_database:
|
| 101 |
+
self.database = maybe_database
|
| 102 |
+
|
| 103 |
+
# Create an admin client for verifying that databases and tenants exist
|
| 104 |
+
self._admin_client = AdminClient.from_system(self._system)
|
| 105 |
+
self._validate_tenant_database(tenant=self.tenant, database=self.database)
|
| 106 |
+
|
| 107 |
+
self._submit_client_start_event()
|
| 108 |
+
except Exception:
|
| 109 |
+
# If init fails after refcount was incremented, release references
|
| 110 |
+
# to avoid a resource leak (the caller never receives the object to
|
| 111 |
+
# call close() on it).
|
| 112 |
+
if hasattr(self, "_admin_client"):
|
| 113 |
+
SharedSystemClient._release_system(self._admin_client._identifier)
|
| 114 |
+
SharedSystemClient._release_system(self._identifier)
|
| 115 |
+
raise
|
| 116 |
+
|
| 117 |
+
@classmethod
|
| 118 |
+
@override
|
| 119 |
+
def from_system(
|
| 120 |
+
cls,
|
| 121 |
+
system: System,
|
| 122 |
+
tenant: str = DEFAULT_TENANT,
|
| 123 |
+
database: str = DEFAULT_DATABASE,
|
| 124 |
+
) -> "Client":
|
| 125 |
+
SharedSystemClient._populate_data_from_system(system)
|
| 126 |
+
instance = cls(tenant=tenant, database=database, settings=system.settings)
|
| 127 |
+
return instance
|
| 128 |
+
|
| 129 |
+
# endregion
|
| 130 |
+
|
| 131 |
+
@override
|
| 132 |
+
def get_user_identity(self) -> UserIdentity:
|
| 133 |
+
try:
|
| 134 |
+
return self._server.get_user_identity()
|
| 135 |
+
except httpx.ConnectError:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
"Could not connect to a Chroma server. Are you sure it is running?"
|
| 138 |
+
)
|
| 139 |
+
# Propagate ChromaErrors
|
| 140 |
+
except ChromaError as e:
|
| 141 |
+
raise e
|
| 142 |
+
except Exception as e:
|
| 143 |
+
raise ValueError(str(e))
|
| 144 |
+
|
| 145 |
+
# region BaseAPI Methods
|
| 146 |
+
# Note - we could do this in less verbose ways, but they break type checking
|
| 147 |
+
@override
|
| 148 |
+
def heartbeat(self) -> int:
|
| 149 |
+
"""Return the server time in nanoseconds since epoch."""
|
| 150 |
+
return self._server.heartbeat()
|
| 151 |
+
|
| 152 |
+
@override
|
| 153 |
+
def list_collections(
|
| 154 |
+
self, limit: Optional[int] = None, offset: Optional[int] = None
|
| 155 |
+
) -> Sequence[Collection]:
|
| 156 |
+
"""List collections for the current tenant and database, with pagination.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
Sequence[Collection]: Collection objects for the current tenant.
|
| 160 |
+
"""
|
| 161 |
+
return [
|
| 162 |
+
Collection(client=self._server, model=model)
|
| 163 |
+
for model in self._server.list_collections(
|
| 164 |
+
limit, offset, tenant=self.tenant, database=self.database
|
| 165 |
+
)
|
| 166 |
+
]
|
| 167 |
+
|
| 168 |
+
@override
|
| 169 |
+
def count_collections(self) -> int:
|
| 170 |
+
"""Return the number of collections in the current database."""
|
| 171 |
+
return self._server.count_collections(
|
| 172 |
+
tenant=self.tenant, database=self.database
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
@override
|
| 176 |
+
def create_collection(
|
| 177 |
+
self,
|
| 178 |
+
name: str,
|
| 179 |
+
schema: Optional[Schema] = None,
|
| 180 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 181 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 182 |
+
embedding_function: Optional[
|
| 183 |
+
EmbeddingFunction[Embeddable]
|
| 184 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 185 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 186 |
+
get_or_create: bool = False,
|
| 187 |
+
) -> Collection:
|
| 188 |
+
"""Create a collection with optional configuration and metadata.
|
| 189 |
+
|
| 190 |
+
If using a schema, do not provide `embedding_function`. Instead,
|
| 191 |
+
provide the `embedding_function` as part of the schema.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
name: Collection name.
|
| 195 |
+
schema: Optional collection schema for indexes and encryption.
|
| 196 |
+
configuration: Optional collection configuration.
|
| 197 |
+
metadata: Optional collection metadata.
|
| 198 |
+
embedding_function: Optional embedding function for the collection.
|
| 199 |
+
data_loader: Optional data loader for documents with URIs.
|
| 200 |
+
get_or_create: Whether to return an existing collection if present.
|
| 201 |
+
|
| 202 |
+
Returns:
|
| 203 |
+
Collection: The created collection.
|
| 204 |
+
|
| 205 |
+
Raises:
|
| 206 |
+
ValueError: If the embedding function conflicts with configuration.
|
| 207 |
+
"""
|
| 208 |
+
if configuration is None:
|
| 209 |
+
configuration = {}
|
| 210 |
+
|
| 211 |
+
configuration_ef = configuration.get("embedding_function")
|
| 212 |
+
|
| 213 |
+
validate_embedding_function_conflict_on_create(
|
| 214 |
+
embedding_function, configuration_ef
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
# If ef provided in function params and collection config ef is None,
|
| 218 |
+
# set the collection config ef to the function params
|
| 219 |
+
if embedding_function is not None and configuration_ef is None:
|
| 220 |
+
configuration["embedding_function"] = embedding_function
|
| 221 |
+
|
| 222 |
+
model = self._server.create_collection(
|
| 223 |
+
name=name,
|
| 224 |
+
schema=schema,
|
| 225 |
+
metadata=metadata,
|
| 226 |
+
tenant=self.tenant,
|
| 227 |
+
database=self.database,
|
| 228 |
+
get_or_create=get_or_create,
|
| 229 |
+
configuration=configuration,
|
| 230 |
+
)
|
| 231 |
+
return Collection(
|
| 232 |
+
client=self._server,
|
| 233 |
+
model=model,
|
| 234 |
+
embedding_function=embedding_function,
|
| 235 |
+
data_loader=data_loader,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
@override
|
| 239 |
+
def get_collection(
|
| 240 |
+
self,
|
| 241 |
+
name: str,
|
| 242 |
+
embedding_function: Optional[
|
| 243 |
+
EmbeddingFunction[Embeddable]
|
| 244 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 245 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 246 |
+
) -> Collection:
|
| 247 |
+
"""Get a collection by name.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
name: Collection name.
|
| 251 |
+
embedding_function: Optional embedding function for the collection.
|
| 252 |
+
data_loader: Optional data loader for documents with URIs.
|
| 253 |
+
|
| 254 |
+
Returns:
|
| 255 |
+
Collection: The requested collection.
|
| 256 |
+
|
| 257 |
+
Raises:
|
| 258 |
+
ValueError: If the embedding function conflicts with configuration.
|
| 259 |
+
"""
|
| 260 |
+
model = self._server.get_collection(
|
| 261 |
+
name=name,
|
| 262 |
+
tenant=self.tenant,
|
| 263 |
+
database=self.database,
|
| 264 |
+
)
|
| 265 |
+
persisted_ef_config = model.configuration_json.get("embedding_function")
|
| 266 |
+
|
| 267 |
+
validate_embedding_function_conflict_on_get(
|
| 268 |
+
embedding_function, persisted_ef_config
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
return Collection(
|
| 272 |
+
client=self._server,
|
| 273 |
+
model=model,
|
| 274 |
+
embedding_function=embedding_function,
|
| 275 |
+
data_loader=data_loader,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
@override
|
| 279 |
+
def get_collection_by_id(
|
| 280 |
+
self,
|
| 281 |
+
id: UUID,
|
| 282 |
+
embedding_function: Optional[
|
| 283 |
+
EmbeddingFunction[Embeddable]
|
| 284 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 285 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 286 |
+
) -> Collection:
|
| 287 |
+
"""Get a collection by its ID.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
id: The UUID of the collection.
|
| 291 |
+
embedding_function: Optional embedding function for the collection.
|
| 292 |
+
data_loader: Optional data loader for documents with URIs.
|
| 293 |
+
|
| 294 |
+
Returns:
|
| 295 |
+
Collection: The requested collection.
|
| 296 |
+
|
| 297 |
+
Raises:
|
| 298 |
+
ValueError: If the embedding function conflicts with configuration.
|
| 299 |
+
"""
|
| 300 |
+
model = self._server.get_collection_by_id(
|
| 301 |
+
collection_id=id,
|
| 302 |
+
tenant=self.tenant,
|
| 303 |
+
database=self.database,
|
| 304 |
+
)
|
| 305 |
+
persisted_ef_config = model.configuration_json.get("embedding_function")
|
| 306 |
+
|
| 307 |
+
validate_embedding_function_conflict_on_get(
|
| 308 |
+
embedding_function, persisted_ef_config
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
return Collection(
|
| 312 |
+
client=self._server,
|
| 313 |
+
model=model,
|
| 314 |
+
embedding_function=embedding_function,
|
| 315 |
+
data_loader=data_loader,
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
@override
|
| 319 |
+
def get_or_create_collection(
|
| 320 |
+
self,
|
| 321 |
+
name: str,
|
| 322 |
+
schema: Optional[Schema] = None,
|
| 323 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 324 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 325 |
+
embedding_function: Optional[
|
| 326 |
+
EmbeddingFunction[Embeddable]
|
| 327 |
+
] = DefaultEmbeddingFunction(), # type: ignore
|
| 328 |
+
data_loader: Optional[DataLoader[Loadable]] = None,
|
| 329 |
+
) -> Collection:
|
| 330 |
+
"""Get an existing collection or create a new one.
|
| 331 |
+
|
| 332 |
+
If the collection does not exist, it will be created. If the collection
|
| 333 |
+
already exists, the schema, configuration, and metadata arguments
|
| 334 |
+
will be ignored.
|
| 335 |
+
|
| 336 |
+
Args:
|
| 337 |
+
name: Collection name.
|
| 338 |
+
schema: Optional collection schema for indexes and encryption.
|
| 339 |
+
configuration: Optional collection configuration.
|
| 340 |
+
metadata: Optional collection metadata.
|
| 341 |
+
embedding_function: Optional embedding function for the collection.
|
| 342 |
+
data_loader: Optional data loader for URI-backed data.
|
| 343 |
+
|
| 344 |
+
Returns:
|
| 345 |
+
Collection: The existing or newly created collection.
|
| 346 |
+
|
| 347 |
+
Raises:
|
| 348 |
+
ValueError: If the embedding function does not match the collection's embedding function.
|
| 349 |
+
"""
|
| 350 |
+
if configuration is None:
|
| 351 |
+
configuration = {}
|
| 352 |
+
|
| 353 |
+
configuration_ef = configuration.get("embedding_function")
|
| 354 |
+
|
| 355 |
+
validate_embedding_function_conflict_on_create(
|
| 356 |
+
embedding_function, configuration_ef
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
if embedding_function is not None and configuration_ef is None:
|
| 360 |
+
configuration["embedding_function"] = embedding_function
|
| 361 |
+
model = self._server.get_or_create_collection(
|
| 362 |
+
name=name,
|
| 363 |
+
schema=schema,
|
| 364 |
+
metadata=metadata,
|
| 365 |
+
tenant=self.tenant,
|
| 366 |
+
database=self.database,
|
| 367 |
+
configuration=configuration,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
persisted_ef_config = model.configuration_json.get("embedding_function")
|
| 371 |
+
|
| 372 |
+
validate_embedding_function_conflict_on_get(
|
| 373 |
+
embedding_function, persisted_ef_config
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
return Collection(
|
| 377 |
+
client=self._server,
|
| 378 |
+
model=model,
|
| 379 |
+
embedding_function=embedding_function,
|
| 380 |
+
data_loader=data_loader,
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
@override
|
| 384 |
+
def _modify(
|
| 385 |
+
self,
|
| 386 |
+
id: UUID,
|
| 387 |
+
new_name: Optional[str] = None,
|
| 388 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 389 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 390 |
+
) -> None:
|
| 391 |
+
return self._server._modify(
|
| 392 |
+
id=id,
|
| 393 |
+
tenant=self.tenant,
|
| 394 |
+
database=self.database,
|
| 395 |
+
new_name=new_name,
|
| 396 |
+
new_metadata=new_metadata,
|
| 397 |
+
new_configuration=new_configuration,
|
| 398 |
+
)
|
| 399 |
+
|
| 400 |
+
@override
|
| 401 |
+
def delete_collection(
|
| 402 |
+
self,
|
| 403 |
+
name: str,
|
| 404 |
+
) -> None:
|
| 405 |
+
return self._server.delete_collection(
|
| 406 |
+
name=name,
|
| 407 |
+
tenant=self.tenant,
|
| 408 |
+
database=self.database,
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
#
|
| 412 |
+
# ITEM METHODS
|
| 413 |
+
#
|
| 414 |
+
|
| 415 |
+
@override
|
| 416 |
+
def _add(
|
| 417 |
+
self,
|
| 418 |
+
ids: IDs,
|
| 419 |
+
collection_id: UUID,
|
| 420 |
+
embeddings: Embeddings,
|
| 421 |
+
metadatas: Optional[Metadatas] = None,
|
| 422 |
+
documents: Optional[Documents] = None,
|
| 423 |
+
uris: Optional[URIs] = None,
|
| 424 |
+
) -> bool:
|
| 425 |
+
return self._server._add(
|
| 426 |
+
ids=ids,
|
| 427 |
+
tenant=self.tenant,
|
| 428 |
+
database=self.database,
|
| 429 |
+
collection_id=collection_id,
|
| 430 |
+
embeddings=embeddings,
|
| 431 |
+
metadatas=metadatas,
|
| 432 |
+
documents=documents,
|
| 433 |
+
uris=uris,
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
@override
|
| 437 |
+
def _update(
|
| 438 |
+
self,
|
| 439 |
+
collection_id: UUID,
|
| 440 |
+
ids: IDs,
|
| 441 |
+
embeddings: Optional[Embeddings] = None,
|
| 442 |
+
metadatas: Optional[Metadatas] = None,
|
| 443 |
+
documents: Optional[Documents] = None,
|
| 444 |
+
uris: Optional[URIs] = None,
|
| 445 |
+
) -> bool:
|
| 446 |
+
return self._server._update(
|
| 447 |
+
collection_id=collection_id,
|
| 448 |
+
tenant=self.tenant,
|
| 449 |
+
database=self.database,
|
| 450 |
+
ids=ids,
|
| 451 |
+
embeddings=embeddings,
|
| 452 |
+
metadatas=metadatas,
|
| 453 |
+
documents=documents,
|
| 454 |
+
uris=uris,
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
@override
|
| 458 |
+
def _upsert(
|
| 459 |
+
self,
|
| 460 |
+
collection_id: UUID,
|
| 461 |
+
ids: IDs,
|
| 462 |
+
embeddings: Embeddings,
|
| 463 |
+
metadatas: Optional[Metadatas] = None,
|
| 464 |
+
documents: Optional[Documents] = None,
|
| 465 |
+
uris: Optional[URIs] = None,
|
| 466 |
+
) -> bool:
|
| 467 |
+
return self._server._upsert(
|
| 468 |
+
collection_id=collection_id,
|
| 469 |
+
tenant=self.tenant,
|
| 470 |
+
database=self.database,
|
| 471 |
+
ids=ids,
|
| 472 |
+
embeddings=embeddings,
|
| 473 |
+
metadatas=metadatas,
|
| 474 |
+
documents=documents,
|
| 475 |
+
uris=uris,
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
@override
|
| 479 |
+
def _count(self, collection_id: UUID) -> int:
|
| 480 |
+
return self._server._count(
|
| 481 |
+
collection_id=collection_id,
|
| 482 |
+
tenant=self.tenant,
|
| 483 |
+
database=self.database,
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
@override
|
| 487 |
+
def _peek(self, collection_id: UUID, n: int = 10) -> GetResult:
|
| 488 |
+
return self._server._peek(
|
| 489 |
+
collection_id=collection_id,
|
| 490 |
+
n=n,
|
| 491 |
+
tenant=self.tenant,
|
| 492 |
+
database=self.database,
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
@override
|
| 496 |
+
def _get(
|
| 497 |
+
self,
|
| 498 |
+
collection_id: UUID,
|
| 499 |
+
ids: Optional[IDs] = None,
|
| 500 |
+
where: Optional[Where] = None,
|
| 501 |
+
limit: Optional[int] = None,
|
| 502 |
+
offset: Optional[int] = None,
|
| 503 |
+
where_document: Optional[WhereDocument] = None,
|
| 504 |
+
include: Include = IncludeMetadataDocuments,
|
| 505 |
+
) -> GetResult:
|
| 506 |
+
return self._server._get(
|
| 507 |
+
collection_id=collection_id,
|
| 508 |
+
tenant=self.tenant,
|
| 509 |
+
database=self.database,
|
| 510 |
+
ids=ids,
|
| 511 |
+
where=where,
|
| 512 |
+
limit=limit,
|
| 513 |
+
offset=offset,
|
| 514 |
+
where_document=where_document,
|
| 515 |
+
include=include,
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
def _delete(
|
| 519 |
+
self,
|
| 520 |
+
collection_id: UUID,
|
| 521 |
+
ids: Optional[IDs],
|
| 522 |
+
where: Optional[Where] = None,
|
| 523 |
+
where_document: Optional[WhereDocument] = None,
|
| 524 |
+
limit: Optional[int] = None,
|
| 525 |
+
) -> DeleteResult:
|
| 526 |
+
return self._server._delete(
|
| 527 |
+
collection_id=collection_id,
|
| 528 |
+
tenant=self.tenant,
|
| 529 |
+
database=self.database,
|
| 530 |
+
ids=ids,
|
| 531 |
+
where=where,
|
| 532 |
+
where_document=where_document,
|
| 533 |
+
limit=limit,
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
@override
|
| 537 |
+
def _query(
|
| 538 |
+
self,
|
| 539 |
+
collection_id: UUID,
|
| 540 |
+
query_embeddings: Embeddings,
|
| 541 |
+
ids: Optional[IDs] = None,
|
| 542 |
+
n_results: int = 10,
|
| 543 |
+
where: Optional[Where] = None,
|
| 544 |
+
where_document: Optional[WhereDocument] = None,
|
| 545 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 546 |
+
) -> QueryResult:
|
| 547 |
+
return self._server._query(
|
| 548 |
+
collection_id=collection_id,
|
| 549 |
+
ids=ids,
|
| 550 |
+
tenant=self.tenant,
|
| 551 |
+
database=self.database,
|
| 552 |
+
query_embeddings=query_embeddings,
|
| 553 |
+
n_results=n_results,
|
| 554 |
+
where=where,
|
| 555 |
+
where_document=where_document,
|
| 556 |
+
include=include,
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
@override
|
| 560 |
+
def reset(self) -> bool:
|
| 561 |
+
return self._server.reset()
|
| 562 |
+
|
| 563 |
+
@override
|
| 564 |
+
def get_version(self) -> str:
|
| 565 |
+
return self._server.get_version()
|
| 566 |
+
|
| 567 |
+
@override
|
| 568 |
+
def get_settings(self) -> Settings:
|
| 569 |
+
return self._server.get_settings()
|
| 570 |
+
|
| 571 |
+
@override
|
| 572 |
+
def get_max_batch_size(self) -> int:
|
| 573 |
+
return self._server.get_max_batch_size()
|
| 574 |
+
|
| 575 |
+
# endregion
|
| 576 |
+
|
| 577 |
+
# region ClientAPI Methods
|
| 578 |
+
|
| 579 |
+
@override
|
| 580 |
+
def set_tenant(self, tenant: str, database: str = DEFAULT_DATABASE) -> None:
|
| 581 |
+
self._validate_tenant_database(tenant=tenant, database=database)
|
| 582 |
+
self.tenant = tenant
|
| 583 |
+
self.database = database
|
| 584 |
+
|
| 585 |
+
@override
|
| 586 |
+
def set_database(self, database: str) -> None:
|
| 587 |
+
self._validate_tenant_database(tenant=self.tenant, database=database)
|
| 588 |
+
self.database = database
|
| 589 |
+
|
| 590 |
+
def close(self) -> None:
|
| 591 |
+
"""Close the client and release all resources.
|
| 592 |
+
|
| 593 |
+
This method decrements the reference count for the underlying System.
|
| 594 |
+
When the last client using a shared System calls close(), the System
|
| 595 |
+
is stopped and all resources (database connections, etc.) are released.
|
| 596 |
+
|
| 597 |
+
This is particularly important for PersistentClient to avoid SQLite
|
| 598 |
+
file locking issues.
|
| 599 |
+
|
| 600 |
+
Note: If multiple clients share the same System (e.g., multiple PersistentClient
|
| 601 |
+
instances with the same path), the System will only be stopped when the last
|
| 602 |
+
client is closed. This allows safe use of context managers with multiple clients.
|
| 603 |
+
|
| 604 |
+
Example:
|
| 605 |
+
>>> client = chromadb.PersistentClient(path="./chroma_db")
|
| 606 |
+
>>> # ... use client ...
|
| 607 |
+
>>> client.close()
|
| 608 |
+
|
| 609 |
+
Or using context manager:
|
| 610 |
+
>>> with chromadb.PersistentClient(path="./chroma_db") as client:
|
| 611 |
+
... # ... use client ...
|
| 612 |
+
"""
|
| 613 |
+
# Make close() idempotent - a second call is a safe no-op
|
| 614 |
+
if self._closed:
|
| 615 |
+
return
|
| 616 |
+
self._closed = True
|
| 617 |
+
|
| 618 |
+
# Release the internal admin client's reference first, since it also
|
| 619 |
+
# incremented the refcount for the shared system on creation.
|
| 620 |
+
if hasattr(self, "_admin_client"):
|
| 621 |
+
SharedSystemClient._release_system(self._admin_client._identifier)
|
| 622 |
+
|
| 623 |
+
# Release our own reference; stops system if this was the last client
|
| 624 |
+
SharedSystemClient._release_system(self._identifier)
|
| 625 |
+
|
| 626 |
+
def __enter__(self) -> "Client":
|
| 627 |
+
"""Context manager entry."""
|
| 628 |
+
return self
|
| 629 |
+
|
| 630 |
+
def __exit__(
|
| 631 |
+
self,
|
| 632 |
+
exc_type: Optional[type[BaseException]],
|
| 633 |
+
exc_val: Optional[BaseException],
|
| 634 |
+
exc_tb: Optional[TracebackType],
|
| 635 |
+
) -> None:
|
| 636 |
+
"""Context manager exit."""
|
| 637 |
+
self.close()
|
| 638 |
+
|
| 639 |
+
def _validate_tenant_database(self, tenant: str, database: str) -> None:
|
| 640 |
+
try:
|
| 641 |
+
self._admin_client.get_tenant(name=tenant)
|
| 642 |
+
except httpx.ConnectError:
|
| 643 |
+
raise ValueError(
|
| 644 |
+
"Could not connect to a Chroma server. Are you sure it is running?"
|
| 645 |
+
)
|
| 646 |
+
# Propagate ChromaErrors
|
| 647 |
+
except ChromaError as e:
|
| 648 |
+
raise e
|
| 649 |
+
except Exception:
|
| 650 |
+
raise ValueError(
|
| 651 |
+
f"Could not connect to tenant {tenant}. Are you sure it exists?"
|
| 652 |
+
)
|
| 653 |
+
|
| 654 |
+
try:
|
| 655 |
+
self._admin_client.get_database(name=database, tenant=tenant)
|
| 656 |
+
except httpx.ConnectError:
|
| 657 |
+
raise ValueError(
|
| 658 |
+
"Could not connect to a Chroma server. Are you sure it is running?"
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
# endregion
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class AdminClient(SharedSystemClient, AdminAPI):
|
| 665 |
+
"""Admin client for managing tenants and databases."""
|
| 666 |
+
|
| 667 |
+
_server: ServerAPI
|
| 668 |
+
|
| 669 |
+
def __init__(self, settings: Settings = Settings()) -> None:
|
| 670 |
+
super().__init__(settings)
|
| 671 |
+
self._server = self._system.instance(ServerAPI)
|
| 672 |
+
|
| 673 |
+
@override
|
| 674 |
+
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 675 |
+
"""Create a database in a tenant.
|
| 676 |
+
|
| 677 |
+
Args:
|
| 678 |
+
name: Database name.
|
| 679 |
+
tenant: Tenant that owns the database.
|
| 680 |
+
"""
|
| 681 |
+
return self._server.create_database(name=name, tenant=tenant)
|
| 682 |
+
|
| 683 |
+
@override
|
| 684 |
+
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
|
| 685 |
+
"""Get a database by name.
|
| 686 |
+
|
| 687 |
+
Args:
|
| 688 |
+
name: Database name.
|
| 689 |
+
tenant: Tenant that owns the database.
|
| 690 |
+
|
| 691 |
+
Returns:
|
| 692 |
+
Database: The database record.
|
| 693 |
+
"""
|
| 694 |
+
return self._server.get_database(name=name, tenant=tenant)
|
| 695 |
+
|
| 696 |
+
@override
|
| 697 |
+
def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 698 |
+
"""Delete a database by name.
|
| 699 |
+
|
| 700 |
+
Args:
|
| 701 |
+
name: Database name.
|
| 702 |
+
tenant: Tenant that owns the database.
|
| 703 |
+
"""
|
| 704 |
+
return self._server.delete_database(name=name, tenant=tenant)
|
| 705 |
+
|
| 706 |
+
@override
|
| 707 |
+
def list_databases(
|
| 708 |
+
self,
|
| 709 |
+
limit: Optional[int] = None,
|
| 710 |
+
offset: Optional[int] = None,
|
| 711 |
+
tenant: str = DEFAULT_TENANT,
|
| 712 |
+
) -> Sequence[Database]:
|
| 713 |
+
return self._server.list_databases(limit, offset, tenant=tenant)
|
| 714 |
+
|
| 715 |
+
@override
|
| 716 |
+
def create_tenant(self, name: str) -> None:
|
| 717 |
+
return self._server.create_tenant(name=name)
|
| 718 |
+
|
| 719 |
+
@override
|
| 720 |
+
def get_tenant(self, name: str) -> Tenant:
|
| 721 |
+
return self._server.get_tenant(name=name)
|
| 722 |
+
|
| 723 |
+
@classmethod
|
| 724 |
+
@override
|
| 725 |
+
def from_system(
|
| 726 |
+
cls,
|
| 727 |
+
system: System,
|
| 728 |
+
) -> "AdminClient":
|
| 729 |
+
SharedSystemClient._populate_data_from_system(system)
|
| 730 |
+
instance = cls(settings=system.settings)
|
| 731 |
+
return instance
|
python/user_packages/Python313/site-packages/chromadb/api/collection_configuration.py
ADDED
|
@@ -0,0 +1,882 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TypedDict, Dict, Any, Optional, cast, get_args
|
| 2 |
+
import json
|
| 3 |
+
from chromadb.api.types import (
|
| 4 |
+
Space,
|
| 5 |
+
CollectionMetadata,
|
| 6 |
+
UpdateMetadata,
|
| 7 |
+
EmbeddingFunction,
|
| 8 |
+
)
|
| 9 |
+
from chromadb.utils.embedding_functions import (
|
| 10 |
+
known_embedding_functions,
|
| 11 |
+
register_embedding_function,
|
| 12 |
+
)
|
| 13 |
+
from multiprocessing import cpu_count
|
| 14 |
+
import warnings
|
| 15 |
+
|
| 16 |
+
from chromadb.api.types import Schema
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class HNSWConfiguration(TypedDict, total=False):
|
| 20 |
+
space: Space
|
| 21 |
+
ef_construction: int
|
| 22 |
+
max_neighbors: int
|
| 23 |
+
ef_search: int
|
| 24 |
+
num_threads: int
|
| 25 |
+
batch_size: int
|
| 26 |
+
sync_threshold: int
|
| 27 |
+
resize_factor: float
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class SpannConfiguration(TypedDict, total=False):
|
| 31 |
+
search_nprobe: int
|
| 32 |
+
write_nprobe: int
|
| 33 |
+
space: Space
|
| 34 |
+
ef_construction: int
|
| 35 |
+
ef_search: int
|
| 36 |
+
max_neighbors: int
|
| 37 |
+
reassign_neighbor_count: int
|
| 38 |
+
split_threshold: int
|
| 39 |
+
merge_threshold: int
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class CollectionConfiguration(TypedDict, total=True):
|
| 43 |
+
hnsw: Optional[HNSWConfiguration]
|
| 44 |
+
spann: Optional[SpannConfiguration]
|
| 45 |
+
embedding_function: Optional[EmbeddingFunction] # type: ignore
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def load_collection_configuration_from_json_str(
|
| 49 |
+
config_json_str: str,
|
| 50 |
+
) -> CollectionConfiguration:
|
| 51 |
+
config_json_map = json.loads(config_json_str)
|
| 52 |
+
return load_collection_configuration_from_json(config_json_map)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# TODO: make warnings prettier and add link to migration docs
|
| 56 |
+
def load_collection_configuration_from_json(
|
| 57 |
+
config_json_map: Dict[str, Any]
|
| 58 |
+
) -> CollectionConfiguration:
|
| 59 |
+
if (
|
| 60 |
+
config_json_map.get("spann") is not None
|
| 61 |
+
and config_json_map.get("hnsw") is not None
|
| 62 |
+
):
|
| 63 |
+
raise ValueError("hnsw and spann cannot both be provided")
|
| 64 |
+
|
| 65 |
+
hnsw_config = None
|
| 66 |
+
spann_config = None
|
| 67 |
+
ef_config = None
|
| 68 |
+
|
| 69 |
+
# Process vector index configuration (HNSW or SPANN)
|
| 70 |
+
if config_json_map.get("hnsw") is not None:
|
| 71 |
+
hnsw_config = cast(HNSWConfiguration, config_json_map["hnsw"])
|
| 72 |
+
if config_json_map.get("spann") is not None:
|
| 73 |
+
spann_config = cast(SpannConfiguration, config_json_map["spann"])
|
| 74 |
+
|
| 75 |
+
# Process embedding function configuration
|
| 76 |
+
if config_json_map.get("embedding_function") is not None:
|
| 77 |
+
ef_config = config_json_map["embedding_function"]
|
| 78 |
+
if ef_config["type"] == "legacy":
|
| 79 |
+
warnings.warn(
|
| 80 |
+
"legacy embedding function config",
|
| 81 |
+
DeprecationWarning,
|
| 82 |
+
stacklevel=2,
|
| 83 |
+
)
|
| 84 |
+
ef = None
|
| 85 |
+
else:
|
| 86 |
+
try:
|
| 87 |
+
ef_name = ef_config["name"]
|
| 88 |
+
except KeyError:
|
| 89 |
+
raise ValueError(
|
| 90 |
+
f"Embedding function name not found in config: {ef_config}"
|
| 91 |
+
)
|
| 92 |
+
try:
|
| 93 |
+
ef = known_embedding_functions[ef_name]
|
| 94 |
+
except KeyError:
|
| 95 |
+
raise ValueError(
|
| 96 |
+
f"Embedding function {ef_name} not found. Add @register_embedding_function decorator to the class definition."
|
| 97 |
+
)
|
| 98 |
+
try:
|
| 99 |
+
ef = ef.build_from_config(ef_config["config"]) # type: ignore
|
| 100 |
+
except Exception as e:
|
| 101 |
+
raise ValueError(
|
| 102 |
+
f"Could not build embedding function {ef_config['name']} from config {ef_config['config']}: {e}"
|
| 103 |
+
)
|
| 104 |
+
else:
|
| 105 |
+
ef = None
|
| 106 |
+
|
| 107 |
+
return CollectionConfiguration(
|
| 108 |
+
hnsw=hnsw_config,
|
| 109 |
+
spann=spann_config,
|
| 110 |
+
embedding_function=ef, # type: ignore
|
| 111 |
+
)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def collection_configuration_to_json_str(config: CollectionConfiguration) -> str:
|
| 115 |
+
return json.dumps(collection_configuration_to_json(config))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def collection_configuration_to_json(config: CollectionConfiguration) -> Dict[str, Any]:
|
| 119 |
+
if isinstance(config, dict):
|
| 120 |
+
hnsw_config = config.get("hnsw")
|
| 121 |
+
spann_config = config.get("spann")
|
| 122 |
+
ef = config.get("embedding_function")
|
| 123 |
+
else:
|
| 124 |
+
try:
|
| 125 |
+
hnsw_config = config.get_parameter("hnsw").value
|
| 126 |
+
except ValueError:
|
| 127 |
+
hnsw_config = None
|
| 128 |
+
try:
|
| 129 |
+
spann_config = config.get_parameter("spann").value
|
| 130 |
+
except ValueError:
|
| 131 |
+
spann_config = None
|
| 132 |
+
try:
|
| 133 |
+
ef = config.get_parameter("embedding_function").value
|
| 134 |
+
except ValueError:
|
| 135 |
+
ef = None
|
| 136 |
+
|
| 137 |
+
ef_config: Dict[str, Any] | None = None
|
| 138 |
+
if hnsw_config is not None:
|
| 139 |
+
try:
|
| 140 |
+
hnsw_config = cast(HNSWConfiguration, hnsw_config)
|
| 141 |
+
except Exception as e:
|
| 142 |
+
raise ValueError(f"not a valid hnsw config: {e}")
|
| 143 |
+
if spann_config is not None:
|
| 144 |
+
try:
|
| 145 |
+
spann_config = cast(SpannConfiguration, spann_config)
|
| 146 |
+
except Exception as e:
|
| 147 |
+
raise ValueError(f"not a valid spann config: {e}")
|
| 148 |
+
|
| 149 |
+
if ef is None:
|
| 150 |
+
ef = None
|
| 151 |
+
ef_config = {"type": "legacy"}
|
| 152 |
+
|
| 153 |
+
if ef is not None:
|
| 154 |
+
try:
|
| 155 |
+
if ef.is_legacy():
|
| 156 |
+
ef_config = {"type": "legacy"}
|
| 157 |
+
else:
|
| 158 |
+
ef_config = {
|
| 159 |
+
"name": ef.name(),
|
| 160 |
+
"type": "known",
|
| 161 |
+
"config": ef.get_config(),
|
| 162 |
+
}
|
| 163 |
+
register_embedding_function(type(ef)) # type: ignore
|
| 164 |
+
except Exception as e:
|
| 165 |
+
warnings.warn(
|
| 166 |
+
f"legacy embedding function config: {e}",
|
| 167 |
+
DeprecationWarning,
|
| 168 |
+
stacklevel=2,
|
| 169 |
+
)
|
| 170 |
+
ef = None
|
| 171 |
+
ef_config = {"type": "legacy"}
|
| 172 |
+
|
| 173 |
+
return {
|
| 174 |
+
"hnsw": hnsw_config,
|
| 175 |
+
"spann": spann_config,
|
| 176 |
+
"embedding_function": ef_config,
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
class CreateHNSWConfiguration(TypedDict, total=False):
|
| 181 |
+
space: Space
|
| 182 |
+
ef_construction: int
|
| 183 |
+
max_neighbors: int
|
| 184 |
+
ef_search: int
|
| 185 |
+
num_threads: int
|
| 186 |
+
batch_size: int
|
| 187 |
+
sync_threshold: int
|
| 188 |
+
resize_factor: float
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def json_to_create_hnsw_configuration(
|
| 192 |
+
json_map: Dict[str, Any]
|
| 193 |
+
) -> CreateHNSWConfiguration:
|
| 194 |
+
config: CreateHNSWConfiguration = {}
|
| 195 |
+
if "space" in json_map:
|
| 196 |
+
space_value = json_map["space"]
|
| 197 |
+
if space_value in get_args(Space):
|
| 198 |
+
config["space"] = space_value
|
| 199 |
+
else:
|
| 200 |
+
raise ValueError(f"not a valid space: {space_value}")
|
| 201 |
+
if "ef_construction" in json_map:
|
| 202 |
+
config["ef_construction"] = json_map["ef_construction"]
|
| 203 |
+
if "max_neighbors" in json_map:
|
| 204 |
+
config["max_neighbors"] = json_map["max_neighbors"]
|
| 205 |
+
if "ef_search" in json_map:
|
| 206 |
+
config["ef_search"] = json_map["ef_search"]
|
| 207 |
+
if "num_threads" in json_map:
|
| 208 |
+
config["num_threads"] = json_map["num_threads"]
|
| 209 |
+
if "batch_size" in json_map:
|
| 210 |
+
config["batch_size"] = json_map["batch_size"]
|
| 211 |
+
if "sync_threshold" in json_map:
|
| 212 |
+
config["sync_threshold"] = json_map["sync_threshold"]
|
| 213 |
+
if "resize_factor" in json_map:
|
| 214 |
+
config["resize_factor"] = json_map["resize_factor"]
|
| 215 |
+
return config
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class CreateSpannConfiguration(TypedDict, total=False):
|
| 219 |
+
search_nprobe: int
|
| 220 |
+
write_nprobe: int
|
| 221 |
+
space: Space
|
| 222 |
+
ef_construction: int
|
| 223 |
+
ef_search: int
|
| 224 |
+
max_neighbors: int
|
| 225 |
+
reassign_neighbor_count: int
|
| 226 |
+
split_threshold: int
|
| 227 |
+
merge_threshold: int
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def json_to_create_spann_configuration(
|
| 231 |
+
json_map: Dict[str, Any]
|
| 232 |
+
) -> CreateSpannConfiguration:
|
| 233 |
+
config: CreateSpannConfiguration = {}
|
| 234 |
+
if "search_nprobe" in json_map:
|
| 235 |
+
config["search_nprobe"] = json_map["search_nprobe"]
|
| 236 |
+
if "write_nprobe" in json_map:
|
| 237 |
+
config["write_nprobe"] = json_map["write_nprobe"]
|
| 238 |
+
if "space" in json_map:
|
| 239 |
+
space_value = json_map["space"]
|
| 240 |
+
if space_value in get_args(Space):
|
| 241 |
+
config["space"] = space_value
|
| 242 |
+
else:
|
| 243 |
+
raise ValueError(f"not a valid space: {space_value}")
|
| 244 |
+
if "ef_construction" in json_map:
|
| 245 |
+
config["ef_construction"] = json_map["ef_construction"]
|
| 246 |
+
if "ef_search" in json_map:
|
| 247 |
+
config["ef_search"] = json_map["ef_search"]
|
| 248 |
+
if "max_neighbors" in json_map:
|
| 249 |
+
config["max_neighbors"] = json_map["max_neighbors"]
|
| 250 |
+
return config
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class CreateCollectionConfiguration(TypedDict, total=False):
|
| 254 |
+
hnsw: Optional[CreateHNSWConfiguration]
|
| 255 |
+
spann: Optional[CreateSpannConfiguration]
|
| 256 |
+
embedding_function: Optional[EmbeddingFunction] # type: ignore
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def create_collection_configuration_from_legacy_collection_metadata(
|
| 260 |
+
metadata: CollectionMetadata,
|
| 261 |
+
) -> CreateCollectionConfiguration:
|
| 262 |
+
"""Create a CreateCollectionConfiguration from legacy collection metadata"""
|
| 263 |
+
return create_collection_configuration_from_legacy_metadata_dict(metadata)
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def create_collection_configuration_from_legacy_metadata_dict(
|
| 267 |
+
metadata: Dict[str, Any],
|
| 268 |
+
) -> CreateCollectionConfiguration:
|
| 269 |
+
"""Create a CreateCollectionConfiguration from legacy collection metadata"""
|
| 270 |
+
old_to_new = {
|
| 271 |
+
"hnsw:space": "space",
|
| 272 |
+
"hnsw:construction_ef": "ef_construction",
|
| 273 |
+
"hnsw:M": "max_neighbors",
|
| 274 |
+
"hnsw:search_ef": "ef_search",
|
| 275 |
+
"hnsw:num_threads": "num_threads",
|
| 276 |
+
"hnsw:batch_size": "batch_size",
|
| 277 |
+
"hnsw:sync_threshold": "sync_threshold",
|
| 278 |
+
"hnsw:resize_factor": "resize_factor",
|
| 279 |
+
}
|
| 280 |
+
json_map = {}
|
| 281 |
+
for name, value in metadata.items():
|
| 282 |
+
if name in old_to_new:
|
| 283 |
+
json_map[old_to_new[name]] = value
|
| 284 |
+
hnsw_config = json_to_create_hnsw_configuration(json_map)
|
| 285 |
+
hnsw_config = populate_create_hnsw_defaults(hnsw_config)
|
| 286 |
+
|
| 287 |
+
return CreateCollectionConfiguration(hnsw=hnsw_config)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
# TODO: make warnings prettier and add link to migration docs
|
| 291 |
+
def load_create_collection_configuration_from_json(
|
| 292 |
+
json_map: Dict[str, Any]
|
| 293 |
+
) -> CreateCollectionConfiguration:
|
| 294 |
+
if json_map.get("hnsw") is not None and json_map.get("spann") is not None:
|
| 295 |
+
raise ValueError("hnsw and spann cannot both be provided")
|
| 296 |
+
|
| 297 |
+
result = CreateCollectionConfiguration()
|
| 298 |
+
|
| 299 |
+
# Handle vector index configuration
|
| 300 |
+
if json_map.get("hnsw") is not None:
|
| 301 |
+
result["hnsw"] = json_to_create_hnsw_configuration(json_map["hnsw"])
|
| 302 |
+
|
| 303 |
+
if json_map.get("spann") is not None:
|
| 304 |
+
result["spann"] = json_to_create_spann_configuration(json_map["spann"])
|
| 305 |
+
|
| 306 |
+
# Handle embedding function configuration
|
| 307 |
+
if json_map.get("embedding_function") is not None:
|
| 308 |
+
ef_config = json_map["embedding_function"]
|
| 309 |
+
if ef_config["type"] == "legacy":
|
| 310 |
+
warnings.warn(
|
| 311 |
+
"legacy embedding function config",
|
| 312 |
+
DeprecationWarning,
|
| 313 |
+
stacklevel=2,
|
| 314 |
+
)
|
| 315 |
+
else:
|
| 316 |
+
ef = known_embedding_functions[ef_config["name"]]
|
| 317 |
+
result["embedding_function"] = ef.build_from_config(ef_config["config"])
|
| 318 |
+
|
| 319 |
+
return result
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def create_collection_configuration_to_json_str(
|
| 323 |
+
config: CreateCollectionConfiguration,
|
| 324 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 325 |
+
) -> str:
|
| 326 |
+
"""Convert a CreateCollection configuration to a JSON-serializable string"""
|
| 327 |
+
return json.dumps(create_collection_configuration_to_json(config, metadata))
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
# TODO: make warnings prettier and add link to migration docs
|
| 331 |
+
def create_collection_configuration_to_json(
|
| 332 |
+
config: CreateCollectionConfiguration,
|
| 333 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 334 |
+
) -> Dict[str, Any]:
|
| 335 |
+
"""Convert a CreateCollection configuration to a JSON-serializable dict"""
|
| 336 |
+
ef_config: Dict[str, Any] | None = None
|
| 337 |
+
hnsw_config = config.get("hnsw")
|
| 338 |
+
spann_config = config.get("spann")
|
| 339 |
+
if hnsw_config is not None:
|
| 340 |
+
try:
|
| 341 |
+
hnsw_config = cast(CreateHNSWConfiguration, hnsw_config)
|
| 342 |
+
except Exception as e:
|
| 343 |
+
raise ValueError(f"not a valid hnsw config: {e}")
|
| 344 |
+
if spann_config is not None:
|
| 345 |
+
try:
|
| 346 |
+
spann_config = cast(CreateSpannConfiguration, spann_config)
|
| 347 |
+
except Exception as e:
|
| 348 |
+
raise ValueError(f"not a valid spann config: {e}")
|
| 349 |
+
|
| 350 |
+
if hnsw_config is not None and spann_config is not None:
|
| 351 |
+
raise ValueError("hnsw and spann cannot both be provided")
|
| 352 |
+
|
| 353 |
+
if config.get("embedding_function") is None:
|
| 354 |
+
ef = None
|
| 355 |
+
ef_config = {"type": "legacy"}
|
| 356 |
+
return {
|
| 357 |
+
"hnsw": hnsw_config,
|
| 358 |
+
"spann": spann_config,
|
| 359 |
+
"embedding_function": ef_config,
|
| 360 |
+
}
|
| 361 |
+
|
| 362 |
+
try:
|
| 363 |
+
ef = cast(EmbeddingFunction, config.get("embedding_function")) # type: ignore
|
| 364 |
+
if ef.is_legacy():
|
| 365 |
+
ef_config = {"type": "legacy"}
|
| 366 |
+
else:
|
| 367 |
+
# default space logic: if neither hnsw nor spann config is provided and metadata doesn't have space,
|
| 368 |
+
# then populate space from ef
|
| 369 |
+
# otherwise dont use default space from ef
|
| 370 |
+
|
| 371 |
+
# then validate the space afterwards based on the supported spaces of the embedding function,
|
| 372 |
+
# warn if space is not supported
|
| 373 |
+
|
| 374 |
+
if hnsw_config is None and spann_config is None:
|
| 375 |
+
if metadata is None or metadata.get("hnsw:space") is None:
|
| 376 |
+
# this populates space from ef if not provided in either config
|
| 377 |
+
hnsw_config = CreateHNSWConfiguration(space=ef.default_space())
|
| 378 |
+
|
| 379 |
+
# if hnsw config or spann config exists but space is not provided, populate it from ef
|
| 380 |
+
if hnsw_config is not None and hnsw_config.get("space") is None:
|
| 381 |
+
hnsw_config["space"] = ef.default_space()
|
| 382 |
+
if spann_config is not None and spann_config.get("space") is None:
|
| 383 |
+
spann_config["space"] = ef.default_space()
|
| 384 |
+
|
| 385 |
+
# Validate space compatibility with embedding function
|
| 386 |
+
if hnsw_config is not None:
|
| 387 |
+
if hnsw_config.get("space") not in ef.supported_spaces():
|
| 388 |
+
warnings.warn(
|
| 389 |
+
f"space {hnsw_config.get('space')} is not supported by {ef.name()}. Supported spaces: {ef.supported_spaces()}",
|
| 390 |
+
UserWarning,
|
| 391 |
+
stacklevel=2,
|
| 392 |
+
)
|
| 393 |
+
if spann_config is not None:
|
| 394 |
+
if spann_config.get("space") not in ef.supported_spaces():
|
| 395 |
+
warnings.warn(
|
| 396 |
+
f"space {spann_config.get('space')} is not supported by {ef.name()}. Supported spaces: {ef.supported_spaces()}",
|
| 397 |
+
UserWarning,
|
| 398 |
+
stacklevel=2,
|
| 399 |
+
)
|
| 400 |
+
|
| 401 |
+
# only validate space from metadata if config is not provided
|
| 402 |
+
if (
|
| 403 |
+
hnsw_config is None
|
| 404 |
+
and spann_config is None
|
| 405 |
+
and metadata is not None
|
| 406 |
+
and metadata.get("hnsw:space") is not None
|
| 407 |
+
):
|
| 408 |
+
if metadata.get("hnsw:space") not in ef.supported_spaces():
|
| 409 |
+
warnings.warn(
|
| 410 |
+
f"space {metadata.get('hnsw:space')} is not supported by {ef.name()}. Supported spaces: {ef.supported_spaces()}",
|
| 411 |
+
UserWarning,
|
| 412 |
+
stacklevel=2,
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
ef_config = {
|
| 416 |
+
"name": ef.name(),
|
| 417 |
+
"type": "known",
|
| 418 |
+
"config": ef.get_config(),
|
| 419 |
+
}
|
| 420 |
+
register_embedding_function(type(ef)) # type: ignore
|
| 421 |
+
except Exception as e:
|
| 422 |
+
warnings.warn(
|
| 423 |
+
f"legacy embedding function config: {e}",
|
| 424 |
+
DeprecationWarning,
|
| 425 |
+
stacklevel=2,
|
| 426 |
+
)
|
| 427 |
+
ef = None
|
| 428 |
+
ef_config = {"type": "legacy"}
|
| 429 |
+
|
| 430 |
+
return {
|
| 431 |
+
"hnsw": hnsw_config,
|
| 432 |
+
"spann": spann_config,
|
| 433 |
+
"embedding_function": ef_config,
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def populate_create_hnsw_defaults(
|
| 438 |
+
config: CreateHNSWConfiguration, ef: Optional[EmbeddingFunction] = None # type: ignore
|
| 439 |
+
) -> CreateHNSWConfiguration:
|
| 440 |
+
"""Populate a CreateHNSW configuration with default values"""
|
| 441 |
+
if config.get("space") is None:
|
| 442 |
+
config["space"] = ef.default_space() if ef else "l2"
|
| 443 |
+
if config.get("ef_construction") is None:
|
| 444 |
+
config["ef_construction"] = 100
|
| 445 |
+
if config.get("max_neighbors") is None:
|
| 446 |
+
config["max_neighbors"] = 16
|
| 447 |
+
if config.get("ef_search") is None:
|
| 448 |
+
config["ef_search"] = 100
|
| 449 |
+
if config.get("num_threads") is None:
|
| 450 |
+
config["num_threads"] = cpu_count()
|
| 451 |
+
if config.get("batch_size") is None:
|
| 452 |
+
config["batch_size"] = 100
|
| 453 |
+
if config.get("sync_threshold") is None:
|
| 454 |
+
config["sync_threshold"] = 1000
|
| 455 |
+
if config.get("resize_factor") is None:
|
| 456 |
+
config["resize_factor"] = 1.2
|
| 457 |
+
return config
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class UpdateHNSWConfiguration(TypedDict, total=False):
|
| 461 |
+
ef_search: int
|
| 462 |
+
num_threads: int
|
| 463 |
+
batch_size: int
|
| 464 |
+
sync_threshold: int
|
| 465 |
+
resize_factor: float
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def json_to_update_hnsw_configuration(
|
| 469 |
+
json_map: Dict[str, Any]
|
| 470 |
+
) -> UpdateHNSWConfiguration:
|
| 471 |
+
config: UpdateHNSWConfiguration = {}
|
| 472 |
+
if "ef_search" in json_map:
|
| 473 |
+
config["ef_search"] = json_map["ef_search"]
|
| 474 |
+
if "num_threads" in json_map:
|
| 475 |
+
config["num_threads"] = json_map["num_threads"]
|
| 476 |
+
if "batch_size" in json_map:
|
| 477 |
+
config["batch_size"] = json_map["batch_size"]
|
| 478 |
+
if "sync_threshold" in json_map:
|
| 479 |
+
config["sync_threshold"] = json_map["sync_threshold"]
|
| 480 |
+
if "resize_factor" in json_map:
|
| 481 |
+
config["resize_factor"] = json_map["resize_factor"]
|
| 482 |
+
return config
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
class UpdateSpannConfiguration(TypedDict, total=False):
|
| 486 |
+
search_nprobe: int
|
| 487 |
+
ef_search: int
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def json_to_update_spann_configuration(
|
| 491 |
+
json_map: Dict[str, Any]
|
| 492 |
+
) -> UpdateSpannConfiguration:
|
| 493 |
+
config: UpdateSpannConfiguration = {}
|
| 494 |
+
if "search_nprobe" in json_map:
|
| 495 |
+
config["search_nprobe"] = json_map["search_nprobe"]
|
| 496 |
+
if "ef_search" in json_map:
|
| 497 |
+
config["ef_search"] = json_map["ef_search"]
|
| 498 |
+
return config
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
class UpdateCollectionConfiguration(TypedDict, total=False):
|
| 502 |
+
hnsw: Optional[UpdateHNSWConfiguration]
|
| 503 |
+
spann: Optional[UpdateSpannConfiguration]
|
| 504 |
+
embedding_function: Optional[EmbeddingFunction] # type: ignore
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def update_collection_configuration_from_legacy_collection_metadata(
|
| 508 |
+
metadata: CollectionMetadata,
|
| 509 |
+
) -> UpdateCollectionConfiguration:
|
| 510 |
+
"""Create an UpdateCollectionConfiguration from legacy collection metadata"""
|
| 511 |
+
old_to_new = {
|
| 512 |
+
"hnsw:search_ef": "ef_search",
|
| 513 |
+
"hnsw:num_threads": "num_threads",
|
| 514 |
+
"hnsw:batch_size": "batch_size",
|
| 515 |
+
"hnsw:sync_threshold": "sync_threshold",
|
| 516 |
+
"hnsw:resize_factor": "resize_factor",
|
| 517 |
+
}
|
| 518 |
+
json_map = {}
|
| 519 |
+
for name, value in metadata.items():
|
| 520 |
+
if name in old_to_new:
|
| 521 |
+
json_map[old_to_new[name]] = value
|
| 522 |
+
hnsw_config = json_to_update_hnsw_configuration(json_map)
|
| 523 |
+
return UpdateCollectionConfiguration(hnsw=hnsw_config)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def update_collection_configuration_from_legacy_update_metadata(
|
| 527 |
+
metadata: UpdateMetadata,
|
| 528 |
+
) -> UpdateCollectionConfiguration:
|
| 529 |
+
"""Create an UpdateCollectionConfiguration from legacy update metadata"""
|
| 530 |
+
old_to_new = {
|
| 531 |
+
"hnsw:search_ef": "ef_search",
|
| 532 |
+
"hnsw:num_threads": "num_threads",
|
| 533 |
+
"hnsw:batch_size": "batch_size",
|
| 534 |
+
"hnsw:sync_threshold": "sync_threshold",
|
| 535 |
+
"hnsw:resize_factor": "resize_factor",
|
| 536 |
+
}
|
| 537 |
+
json_map = {}
|
| 538 |
+
for name, value in metadata.items():
|
| 539 |
+
if name in old_to_new:
|
| 540 |
+
json_map[old_to_new[name]] = value
|
| 541 |
+
hnsw_config = json_to_update_hnsw_configuration(json_map)
|
| 542 |
+
return UpdateCollectionConfiguration(hnsw=hnsw_config)
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def update_collection_configuration_to_json_str(
|
| 546 |
+
config: UpdateCollectionConfiguration,
|
| 547 |
+
) -> str:
|
| 548 |
+
"""Convert an UpdateCollectionConfiguration to a JSON-serializable string"""
|
| 549 |
+
json_dict = update_collection_configuration_to_json(config)
|
| 550 |
+
return json.dumps(json_dict)
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def update_collection_configuration_to_json(
|
| 554 |
+
config: UpdateCollectionConfiguration,
|
| 555 |
+
) -> Dict[str, Any]:
|
| 556 |
+
"""Convert an UpdateCollectionConfiguration to a JSON-serializable dict"""
|
| 557 |
+
hnsw_config = config.get("hnsw")
|
| 558 |
+
spann_config = config.get("spann")
|
| 559 |
+
ef = config.get("embedding_function")
|
| 560 |
+
if hnsw_config is None and spann_config is None and ef is None:
|
| 561 |
+
return {}
|
| 562 |
+
|
| 563 |
+
if hnsw_config is not None:
|
| 564 |
+
try:
|
| 565 |
+
hnsw_config = cast(UpdateHNSWConfiguration, hnsw_config)
|
| 566 |
+
except Exception as e:
|
| 567 |
+
raise ValueError(f"not a valid hnsw config: {e}")
|
| 568 |
+
|
| 569 |
+
if spann_config is not None:
|
| 570 |
+
try:
|
| 571 |
+
spann_config = cast(UpdateSpannConfiguration, spann_config)
|
| 572 |
+
except Exception as e:
|
| 573 |
+
raise ValueError(f"not a valid spann config: {e}")
|
| 574 |
+
|
| 575 |
+
ef_config: Dict[str, Any] | None = None
|
| 576 |
+
if ef is not None:
|
| 577 |
+
if ef.is_legacy():
|
| 578 |
+
ef_config = {"type": "legacy"}
|
| 579 |
+
else:
|
| 580 |
+
ef.validate_config(ef.get_config())
|
| 581 |
+
ef_config = {
|
| 582 |
+
"name": ef.name(),
|
| 583 |
+
"type": "known",
|
| 584 |
+
"config": ef.get_config(),
|
| 585 |
+
}
|
| 586 |
+
register_embedding_function(type(ef)) # type: ignore
|
| 587 |
+
else:
|
| 588 |
+
ef_config = None
|
| 589 |
+
|
| 590 |
+
return {
|
| 591 |
+
"hnsw": hnsw_config,
|
| 592 |
+
"spann": spann_config,
|
| 593 |
+
"embedding_function": ef_config,
|
| 594 |
+
}
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def load_update_collection_configuration_from_json_str(
|
| 598 |
+
json_str: str,
|
| 599 |
+
) -> UpdateCollectionConfiguration:
|
| 600 |
+
json_map = json.loads(json_str)
|
| 601 |
+
return load_update_collection_configuration_from_json(json_map)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
# TODO: make warnings prettier and add link to migration docs
|
| 605 |
+
def load_update_collection_configuration_from_json(
|
| 606 |
+
json_map: Dict[str, Any]
|
| 607 |
+
) -> UpdateCollectionConfiguration:
|
| 608 |
+
"""Convert a JSON dict to an UpdateCollectionConfiguration"""
|
| 609 |
+
if json_map.get("hnsw") is not None and json_map.get("spann") is not None:
|
| 610 |
+
raise ValueError("hnsw and spann cannot both be provided")
|
| 611 |
+
|
| 612 |
+
result = UpdateCollectionConfiguration()
|
| 613 |
+
|
| 614 |
+
# Handle vector index configurations
|
| 615 |
+
if json_map.get("hnsw") is not None:
|
| 616 |
+
result["hnsw"] = json_to_update_hnsw_configuration(json_map["hnsw"])
|
| 617 |
+
|
| 618 |
+
if json_map.get("spann") is not None:
|
| 619 |
+
result["spann"] = json_to_update_spann_configuration(json_map["spann"])
|
| 620 |
+
|
| 621 |
+
# Handle embedding function
|
| 622 |
+
if json_map.get("embedding_function") is not None:
|
| 623 |
+
if json_map["embedding_function"]["type"] == "legacy":
|
| 624 |
+
warnings.warn(
|
| 625 |
+
"legacy embedding function config",
|
| 626 |
+
DeprecationWarning,
|
| 627 |
+
stacklevel=2,
|
| 628 |
+
)
|
| 629 |
+
else:
|
| 630 |
+
ef = known_embedding_functions[json_map["embedding_function"]["name"]]
|
| 631 |
+
result["embedding_function"] = ef.build_from_config(
|
| 632 |
+
json_map["embedding_function"]["config"]
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
return result
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def overwrite_hnsw_configuration(
|
| 639 |
+
existing_hnsw_config: HNSWConfiguration, update_hnsw_config: UpdateHNSWConfiguration
|
| 640 |
+
) -> HNSWConfiguration:
|
| 641 |
+
"""Overwrite a HNSWConfiguration with a new configuration"""
|
| 642 |
+
# Create a copy of the existing config and update with new values
|
| 643 |
+
result = dict(existing_hnsw_config)
|
| 644 |
+
update_fields = [
|
| 645 |
+
"ef_search",
|
| 646 |
+
"num_threads",
|
| 647 |
+
"batch_size",
|
| 648 |
+
"sync_threshold",
|
| 649 |
+
"resize_factor",
|
| 650 |
+
]
|
| 651 |
+
|
| 652 |
+
for field in update_fields:
|
| 653 |
+
if field in update_hnsw_config:
|
| 654 |
+
result[field] = update_hnsw_config[field] # type: ignore
|
| 655 |
+
|
| 656 |
+
return cast(HNSWConfiguration, result)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def overwrite_spann_configuration(
|
| 660 |
+
existing_spann_config: SpannConfiguration,
|
| 661 |
+
update_spann_config: UpdateSpannConfiguration,
|
| 662 |
+
) -> SpannConfiguration:
|
| 663 |
+
"""Overwrite a SpannConfiguration with a new configuration"""
|
| 664 |
+
result = dict(existing_spann_config)
|
| 665 |
+
update_fields = [
|
| 666 |
+
"search_nprobe",
|
| 667 |
+
"ef_search",
|
| 668 |
+
]
|
| 669 |
+
|
| 670 |
+
for field in update_fields:
|
| 671 |
+
if field in update_spann_config:
|
| 672 |
+
result[field] = update_spann_config[field] # type: ignore
|
| 673 |
+
|
| 674 |
+
return cast(SpannConfiguration, result)
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
# TODO: make warnings prettier and add link to migration docs
|
| 678 |
+
def overwrite_embedding_function(
|
| 679 |
+
existing_embedding_function: EmbeddingFunction, # type: ignore
|
| 680 |
+
update_embedding_function: EmbeddingFunction, # type: ignore
|
| 681 |
+
) -> EmbeddingFunction: # type: ignore
|
| 682 |
+
"""Overwrite an EmbeddingFunction with a new configuration"""
|
| 683 |
+
# Check for legacy embedding functions
|
| 684 |
+
if existing_embedding_function.is_legacy() or update_embedding_function.is_legacy():
|
| 685 |
+
warnings.warn(
|
| 686 |
+
"cannot update legacy embedding function config",
|
| 687 |
+
DeprecationWarning,
|
| 688 |
+
stacklevel=2,
|
| 689 |
+
)
|
| 690 |
+
return existing_embedding_function
|
| 691 |
+
|
| 692 |
+
# Validate function compatibility
|
| 693 |
+
if existing_embedding_function.name() != update_embedding_function.name():
|
| 694 |
+
raise ValueError(
|
| 695 |
+
f"Cannot update embedding function: incompatible types "
|
| 696 |
+
f"({existing_embedding_function.name()} vs {update_embedding_function.name()})"
|
| 697 |
+
)
|
| 698 |
+
|
| 699 |
+
# Validate and apply the configuration update
|
| 700 |
+
update_embedding_function.validate_config_update(
|
| 701 |
+
existing_embedding_function.get_config(), update_embedding_function.get_config()
|
| 702 |
+
)
|
| 703 |
+
return update_embedding_function
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def overwrite_collection_configuration(
|
| 707 |
+
existing_config: CollectionConfiguration,
|
| 708 |
+
update_config: UpdateCollectionConfiguration,
|
| 709 |
+
) -> CollectionConfiguration:
|
| 710 |
+
"""Overwrite a CollectionConfiguration with a new configuration"""
|
| 711 |
+
update_spann = update_config.get("spann")
|
| 712 |
+
update_hnsw = update_config.get("hnsw")
|
| 713 |
+
if update_spann is not None and update_hnsw is not None:
|
| 714 |
+
raise ValueError("hnsw and spann cannot both be provided")
|
| 715 |
+
|
| 716 |
+
# Handle HNSW configuration update
|
| 717 |
+
|
| 718 |
+
updated_hnsw_config = existing_config.get("hnsw")
|
| 719 |
+
if updated_hnsw_config is not None and update_hnsw is not None:
|
| 720 |
+
updated_hnsw_config = overwrite_hnsw_configuration(
|
| 721 |
+
updated_hnsw_config, update_hnsw
|
| 722 |
+
)
|
| 723 |
+
|
| 724 |
+
# Handle SPANN configuration update
|
| 725 |
+
updated_spann_config = existing_config.get("spann")
|
| 726 |
+
if updated_spann_config is not None and update_spann is not None:
|
| 727 |
+
updated_spann_config = overwrite_spann_configuration(
|
| 728 |
+
updated_spann_config, update_spann
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
# Handle embedding function update
|
| 732 |
+
updated_embedding_function = existing_config.get("embedding_function")
|
| 733 |
+
update_ef = update_config.get("embedding_function")
|
| 734 |
+
if update_ef is not None:
|
| 735 |
+
if updated_embedding_function is not None:
|
| 736 |
+
updated_embedding_function = overwrite_embedding_function(
|
| 737 |
+
updated_embedding_function, update_ef
|
| 738 |
+
)
|
| 739 |
+
else:
|
| 740 |
+
updated_embedding_function = update_ef
|
| 741 |
+
|
| 742 |
+
return CollectionConfiguration(
|
| 743 |
+
hnsw=updated_hnsw_config,
|
| 744 |
+
spann=updated_spann_config,
|
| 745 |
+
embedding_function=updated_embedding_function,
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
def validate_embedding_function_conflict_on_create(
|
| 750 |
+
embedding_function: Optional[EmbeddingFunction], # type: ignore
|
| 751 |
+
configuration_ef: Optional[EmbeddingFunction], # type: ignore
|
| 752 |
+
) -> None:
|
| 753 |
+
"""
|
| 754 |
+
Validates that there are no conflicting embedding functions between function parameter
|
| 755 |
+
and collection configuration.
|
| 756 |
+
|
| 757 |
+
Args:
|
| 758 |
+
embedding_function: The embedding function provided as a parameter
|
| 759 |
+
configuration_ef: The embedding function from collection configuration
|
| 760 |
+
|
| 761 |
+
Returns:
|
| 762 |
+
bool: True if there is a conflict, False otherwise
|
| 763 |
+
"""
|
| 764 |
+
# If ef provided in function params and collection config, check if they are the same
|
| 765 |
+
# If not, there's a conflict
|
| 766 |
+
# ef is by default "default" if not provided, so ignore that case.
|
| 767 |
+
if embedding_function is not None and configuration_ef is not None:
|
| 768 |
+
if (
|
| 769 |
+
embedding_function.name() != "default"
|
| 770 |
+
and embedding_function.name() != configuration_ef.name()
|
| 771 |
+
):
|
| 772 |
+
raise ValueError(
|
| 773 |
+
f"Multiple embedding functions provided. Please provide only one. Embedding function conflict: {embedding_function.name()} vs {configuration_ef.name()}"
|
| 774 |
+
)
|
| 775 |
+
return None
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
# The reason to use the config on get, rather than build the ef is because
|
| 779 |
+
# if there is an issue with deserializing the config, an error shouldn't be raised
|
| 780 |
+
# at get time. CollectionCommon.py will raise an error at _embed time if there is an issue deserializing.
|
| 781 |
+
def validate_embedding_function_conflict_on_get(
|
| 782 |
+
embedding_function: Optional[EmbeddingFunction], # type: ignore
|
| 783 |
+
persisted_ef_config: Optional[Dict[str, Any]],
|
| 784 |
+
) -> None:
|
| 785 |
+
"""
|
| 786 |
+
Validates that there are no conflicting embedding functions between function parameter
|
| 787 |
+
and collection configuration.
|
| 788 |
+
"""
|
| 789 |
+
if persisted_ef_config is not None and embedding_function is not None:
|
| 790 |
+
if (
|
| 791 |
+
embedding_function.name() != "default"
|
| 792 |
+
and persisted_ef_config.get("name") is not None
|
| 793 |
+
and persisted_ef_config.get("name") != embedding_function.name()
|
| 794 |
+
):
|
| 795 |
+
raise ValueError(
|
| 796 |
+
f"An embedding function already exists in the collection configuration, and a new one is provided. If this is intentional, please embed documents separately. Embedding function conflict: new: {embedding_function.name()} vs persisted: {persisted_ef_config.get('name')}"
|
| 797 |
+
)
|
| 798 |
+
return None
|
| 799 |
+
|
| 800 |
+
|
| 801 |
+
def update_schema_from_collection_configuration(
|
| 802 |
+
schema: "Schema", configuration: "UpdateCollectionConfiguration"
|
| 803 |
+
) -> "Schema":
|
| 804 |
+
"""
|
| 805 |
+
Updates a schema with configuration changes.
|
| 806 |
+
Only updates fields that are present in the configuration update.
|
| 807 |
+
|
| 808 |
+
Args:
|
| 809 |
+
schema: The existing Schema object
|
| 810 |
+
configuration: The configuration updates to apply
|
| 811 |
+
|
| 812 |
+
Returns:
|
| 813 |
+
Updated Schema object
|
| 814 |
+
"""
|
| 815 |
+
|
| 816 |
+
# Get the vector index from defaults and #embedding key
|
| 817 |
+
if (
|
| 818 |
+
schema.defaults.float_list is None
|
| 819 |
+
or schema.defaults.float_list.vector_index is None
|
| 820 |
+
):
|
| 821 |
+
raise ValueError("Schema is missing defaults.float_list.vector_index")
|
| 822 |
+
|
| 823 |
+
embedding_key = "#embedding"
|
| 824 |
+
if embedding_key not in schema.keys:
|
| 825 |
+
raise ValueError(f"Schema is missing keys[{embedding_key}]")
|
| 826 |
+
|
| 827 |
+
embedding_value_types = schema.keys[embedding_key]
|
| 828 |
+
if (
|
| 829 |
+
embedding_value_types.float_list is None
|
| 830 |
+
or embedding_value_types.float_list.vector_index is None
|
| 831 |
+
):
|
| 832 |
+
raise ValueError(
|
| 833 |
+
f"Schema is missing keys[{embedding_key}].float_list.vector_index"
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
# Update vector index config in both locations
|
| 837 |
+
for vector_index in [
|
| 838 |
+
schema.defaults.float_list.vector_index,
|
| 839 |
+
embedding_value_types.float_list.vector_index,
|
| 840 |
+
]:
|
| 841 |
+
if "hnsw" in configuration and configuration["hnsw"] is not None:
|
| 842 |
+
# Update HNSW config
|
| 843 |
+
if vector_index.config.hnsw is None:
|
| 844 |
+
raise ValueError("Trying to update HNSW config but schema has SPANN")
|
| 845 |
+
|
| 846 |
+
hnsw_config = vector_index.config.hnsw
|
| 847 |
+
update_hnsw = configuration["hnsw"]
|
| 848 |
+
|
| 849 |
+
# Only update fields that are present in the update
|
| 850 |
+
if "ef_search" in update_hnsw:
|
| 851 |
+
hnsw_config.ef_search = update_hnsw["ef_search"]
|
| 852 |
+
if "num_threads" in update_hnsw:
|
| 853 |
+
hnsw_config.num_threads = update_hnsw["num_threads"]
|
| 854 |
+
if "batch_size" in update_hnsw:
|
| 855 |
+
hnsw_config.batch_size = update_hnsw["batch_size"]
|
| 856 |
+
if "sync_threshold" in update_hnsw:
|
| 857 |
+
hnsw_config.sync_threshold = update_hnsw["sync_threshold"]
|
| 858 |
+
if "resize_factor" in update_hnsw:
|
| 859 |
+
hnsw_config.resize_factor = update_hnsw["resize_factor"]
|
| 860 |
+
|
| 861 |
+
elif "spann" in configuration and configuration["spann"] is not None:
|
| 862 |
+
# Update SPANN config
|
| 863 |
+
if vector_index.config.spann is None:
|
| 864 |
+
raise ValueError("Trying to update SPANN config but schema has HNSW")
|
| 865 |
+
|
| 866 |
+
spann_config = vector_index.config.spann
|
| 867 |
+
update_spann = configuration["spann"]
|
| 868 |
+
|
| 869 |
+
# Only update fields that are present in the update
|
| 870 |
+
if "search_nprobe" in update_spann:
|
| 871 |
+
spann_config.search_nprobe = update_spann["search_nprobe"]
|
| 872 |
+
if "ef_search" in update_spann:
|
| 873 |
+
spann_config.ef_search = update_spann["ef_search"]
|
| 874 |
+
|
| 875 |
+
# Update embedding function if present
|
| 876 |
+
if (
|
| 877 |
+
"embedding_function" in configuration
|
| 878 |
+
and configuration["embedding_function"] is not None
|
| 879 |
+
):
|
| 880 |
+
vector_index.config.embedding_function = configuration["embedding_function"]
|
| 881 |
+
|
| 882 |
+
return schema
|
python/user_packages/Python313/site-packages/chromadb/api/configuration.py
ADDED
|
@@ -0,0 +1,410 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 12 |
+
TypeVar,
|
| 13 |
+
cast,
|
| 14 |
+
)
|
| 15 |
+
from typing_extensions import Self
|
| 16 |
+
from multiprocessing import cpu_count
|
| 17 |
+
|
| 18 |
+
from chromadb.serde import JSONSerializable
|
| 19 |
+
|
| 20 |
+
# TODO: move out of API
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class StaticParameterError(Exception):
|
| 24 |
+
"""Represents an error that occurs when a static parameter is set."""
|
| 25 |
+
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class InvalidConfigurationError(ValueError):
|
| 30 |
+
"""Represents an error that occurs when a configuration is invalid."""
|
| 31 |
+
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
ParameterValue = Union[str, int, float, bool, "ConfigurationInternal"]
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class ParameterValidator(Protocol):
|
| 39 |
+
"""Represents an abstract parameter validator."""
|
| 40 |
+
|
| 41 |
+
@abstractmethod
|
| 42 |
+
def __call__(self, value: ParameterValue) -> bool:
|
| 43 |
+
"""Returns whether the given value is valid."""
|
| 44 |
+
raise NotImplementedError()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class ConfigurationDefinition:
|
| 48 |
+
"""Represents the definition of a configuration."""
|
| 49 |
+
|
| 50 |
+
name: str
|
| 51 |
+
validator: ParameterValidator
|
| 52 |
+
is_static: bool
|
| 53 |
+
default_value: ParameterValue
|
| 54 |
+
|
| 55 |
+
def __init__(
|
| 56 |
+
self,
|
| 57 |
+
name: str,
|
| 58 |
+
validator: ParameterValidator,
|
| 59 |
+
is_static: bool,
|
| 60 |
+
default_value: ParameterValue,
|
| 61 |
+
):
|
| 62 |
+
self.name = name
|
| 63 |
+
self.validator = validator
|
| 64 |
+
self.is_static = is_static
|
| 65 |
+
self.default_value = default_value
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class ConfigurationParameter:
|
| 69 |
+
"""Represents a parameter of a configuration."""
|
| 70 |
+
|
| 71 |
+
name: str
|
| 72 |
+
value: ParameterValue
|
| 73 |
+
|
| 74 |
+
def __init__(self, name: str, value: ParameterValue):
|
| 75 |
+
self.name = name
|
| 76 |
+
self.value = value
|
| 77 |
+
|
| 78 |
+
def __repr__(self) -> str:
|
| 79 |
+
return f"ConfigurationParameter({self.name}, {self.value})"
|
| 80 |
+
|
| 81 |
+
def __eq__(self, __value: object) -> bool:
|
| 82 |
+
if not isinstance(__value, ConfigurationParameter):
|
| 83 |
+
return NotImplemented
|
| 84 |
+
return self.name == __value.name and self.value == __value.value
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
T = TypeVar("T", bound="ConfigurationInternal")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class ConfigurationInternal(JSONSerializable["ConfigurationInternal"]):
|
| 91 |
+
"""Represents an abstract configuration, used internally by Chroma."""
|
| 92 |
+
|
| 93 |
+
# The internal data structure used to store the parameters
|
| 94 |
+
# All expected parameters must be present with defaults or None values at initialization
|
| 95 |
+
parameter_map: Dict[str, ConfigurationParameter]
|
| 96 |
+
definitions: ClassVar[Dict[str, ConfigurationDefinition]]
|
| 97 |
+
|
| 98 |
+
def __init__(self, parameters: Optional[List[ConfigurationParameter]] = None):
|
| 99 |
+
"""Initializes a new instance of the Configuration class. Respecting defaults and
|
| 100 |
+
validators."""
|
| 101 |
+
self.parameter_map = {}
|
| 102 |
+
if parameters is not None:
|
| 103 |
+
for parameter in parameters:
|
| 104 |
+
if parameter.name not in self.definitions:
|
| 105 |
+
raise ValueError(f"Invalid parameter name: {parameter.name}")
|
| 106 |
+
|
| 107 |
+
definition = self.definitions[parameter.name]
|
| 108 |
+
# Handle the case where we have a recursive configuration definition
|
| 109 |
+
if isinstance(parameter.value, dict):
|
| 110 |
+
child_type = globals().get(parameter.value.get("_type", None))
|
| 111 |
+
if child_type is None:
|
| 112 |
+
raise ValueError(
|
| 113 |
+
f"Invalid configuration type: {parameter.value}"
|
| 114 |
+
)
|
| 115 |
+
parameter.value = child_type.from_json(parameter.value)
|
| 116 |
+
if not isinstance(parameter.value, type(definition.default_value)):
|
| 117 |
+
raise ValueError(f"Invalid parameter value: {parameter.value}")
|
| 118 |
+
|
| 119 |
+
parameter_validator = definition.validator
|
| 120 |
+
if not parameter_validator(parameter.value):
|
| 121 |
+
raise ValueError(f"Invalid parameter value: {parameter.value}")
|
| 122 |
+
self.parameter_map[parameter.name] = parameter
|
| 123 |
+
# Apply the defaults for any missing parameters
|
| 124 |
+
for name, definition in self.definitions.items():
|
| 125 |
+
if name not in self.parameter_map:
|
| 126 |
+
self.parameter_map[name] = ConfigurationParameter(
|
| 127 |
+
name=name, value=definition.default_value
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
self.configuration_validator()
|
| 131 |
+
|
| 132 |
+
def __repr__(self) -> str:
|
| 133 |
+
return f"Configuration({self.parameter_map.values()})"
|
| 134 |
+
|
| 135 |
+
def __eq__(self, __value: object) -> bool:
|
| 136 |
+
if not isinstance(__value, ConfigurationInternal):
|
| 137 |
+
return NotImplemented
|
| 138 |
+
return self.parameter_map == __value.parameter_map
|
| 139 |
+
|
| 140 |
+
@abstractmethod
|
| 141 |
+
def configuration_validator(self) -> None:
|
| 142 |
+
"""Perform custom validation when parameters are dependent on each other.
|
| 143 |
+
|
| 144 |
+
Raises an InvalidConfigurationError if the configuration is invalid.
|
| 145 |
+
"""
|
| 146 |
+
pass
|
| 147 |
+
|
| 148 |
+
def get_parameters(self) -> List[ConfigurationParameter]:
|
| 149 |
+
"""Returns the parameters of the configuration."""
|
| 150 |
+
return list(self.parameter_map.values())
|
| 151 |
+
|
| 152 |
+
def get_parameter(self, name: str) -> ConfigurationParameter:
|
| 153 |
+
"""Returns the parameter with the given name, or except if it doesn't exist."""
|
| 154 |
+
if name not in self.parameter_map:
|
| 155 |
+
raise ValueError(
|
| 156 |
+
f"Invalid parameter name: {name} for configuration {self.__class__.__name__}"
|
| 157 |
+
)
|
| 158 |
+
param_value = cast(ConfigurationParameter, self.parameter_map.get(name))
|
| 159 |
+
return param_value
|
| 160 |
+
|
| 161 |
+
def set_parameter(self, name: str, value: Union[str, int, float, bool]) -> None:
|
| 162 |
+
"""Sets the parameter with the given name to the given value."""
|
| 163 |
+
if name not in self.definitions:
|
| 164 |
+
raise ValueError(f"Invalid parameter name: {name}")
|
| 165 |
+
definition = self.definitions[name]
|
| 166 |
+
parameter = self.parameter_map[name]
|
| 167 |
+
if definition.is_static:
|
| 168 |
+
raise StaticParameterError(f"Cannot set static parameter: {name}")
|
| 169 |
+
if not definition.validator(value):
|
| 170 |
+
raise ValueError(f"Invalid value for parameter {name}: {value}")
|
| 171 |
+
parameter.value = value
|
| 172 |
+
|
| 173 |
+
@override
|
| 174 |
+
def to_json_str(self) -> str:
|
| 175 |
+
"""Returns the JSON representation of the configuration."""
|
| 176 |
+
return json.dumps(self.to_json())
|
| 177 |
+
|
| 178 |
+
@classmethod
|
| 179 |
+
@override
|
| 180 |
+
def from_json_str(cls, json_str: str) -> Self:
|
| 181 |
+
"""Returns a configuration from the given JSON string."""
|
| 182 |
+
try:
|
| 183 |
+
config_json = json.loads(json_str)
|
| 184 |
+
except json.JSONDecodeError:
|
| 185 |
+
raise ValueError(
|
| 186 |
+
f"Unable to decode configuration from JSON string: {json_str}"
|
| 187 |
+
)
|
| 188 |
+
return cls.from_json(config_json) if config_json else cls()
|
| 189 |
+
|
| 190 |
+
@override
|
| 191 |
+
def to_json(self) -> Dict[str, Any]:
|
| 192 |
+
"""Returns the JSON compatible dictionary representation of the configuration."""
|
| 193 |
+
json_dict = {
|
| 194 |
+
name: parameter.value.to_json()
|
| 195 |
+
if isinstance(parameter.value, ConfigurationInternal)
|
| 196 |
+
else parameter.value
|
| 197 |
+
for name, parameter in self.parameter_map.items()
|
| 198 |
+
}
|
| 199 |
+
# What kind of configuration is this?
|
| 200 |
+
json_dict["_type"] = self.__class__.__name__
|
| 201 |
+
return json_dict
|
| 202 |
+
|
| 203 |
+
@classmethod
|
| 204 |
+
@override
|
| 205 |
+
def from_json(cls, json_map: Dict[str, Any]) -> Self:
|
| 206 |
+
"""Returns a configuration from the given JSON string."""
|
| 207 |
+
if cls.__name__ != json_map.get("_type", None):
|
| 208 |
+
raise ValueError(
|
| 209 |
+
f"Trying to instantiate configuration of type {cls.__name__} from JSON with type {json_map['_type']}"
|
| 210 |
+
)
|
| 211 |
+
parameters = []
|
| 212 |
+
for name, value in json_map.items():
|
| 213 |
+
# Type value is only for storage
|
| 214 |
+
if name == "_type":
|
| 215 |
+
continue
|
| 216 |
+
parameters.append(ConfigurationParameter(name=name, value=value))
|
| 217 |
+
return cls(parameters=parameters)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class HNSWConfigurationInternal(ConfigurationInternal):
|
| 221 |
+
"""Internal representation of the HNSW configuration.
|
| 222 |
+
Used for validation, defaults, serialization and deserialization."""
|
| 223 |
+
|
| 224 |
+
definitions = {
|
| 225 |
+
"space": ConfigurationDefinition(
|
| 226 |
+
name="space",
|
| 227 |
+
validator=lambda value: isinstance(value, str)
|
| 228 |
+
and value in ["l2", "ip", "cosine"],
|
| 229 |
+
is_static=True,
|
| 230 |
+
default_value="l2",
|
| 231 |
+
),
|
| 232 |
+
"ef_construction": ConfigurationDefinition(
|
| 233 |
+
name="ef_construction",
|
| 234 |
+
validator=lambda value: isinstance(value, int) and value >= 1,
|
| 235 |
+
is_static=True,
|
| 236 |
+
default_value=100,
|
| 237 |
+
),
|
| 238 |
+
"ef_search": ConfigurationDefinition(
|
| 239 |
+
name="ef_search",
|
| 240 |
+
validator=lambda value: isinstance(value, int) and value >= 1,
|
| 241 |
+
is_static=False,
|
| 242 |
+
default_value=100,
|
| 243 |
+
),
|
| 244 |
+
"num_threads": ConfigurationDefinition(
|
| 245 |
+
name="num_threads",
|
| 246 |
+
validator=lambda value: isinstance(value, int) and value >= 1,
|
| 247 |
+
is_static=False,
|
| 248 |
+
default_value=cpu_count(), # By default use all cores available
|
| 249 |
+
),
|
| 250 |
+
"M": ConfigurationDefinition(
|
| 251 |
+
name="M",
|
| 252 |
+
validator=lambda value: isinstance(value, int) and value >= 1,
|
| 253 |
+
is_static=True,
|
| 254 |
+
default_value=16,
|
| 255 |
+
),
|
| 256 |
+
"resize_factor": ConfigurationDefinition(
|
| 257 |
+
name="resize_factor",
|
| 258 |
+
validator=lambda value: isinstance(value, float) and value >= 1,
|
| 259 |
+
is_static=True,
|
| 260 |
+
default_value=1.2,
|
| 261 |
+
),
|
| 262 |
+
"batch_size": ConfigurationDefinition(
|
| 263 |
+
name="batch_size",
|
| 264 |
+
validator=lambda value: isinstance(value, int) and value >= 1,
|
| 265 |
+
is_static=True,
|
| 266 |
+
default_value=100,
|
| 267 |
+
),
|
| 268 |
+
"sync_threshold": ConfigurationDefinition(
|
| 269 |
+
name="sync_threshold",
|
| 270 |
+
validator=lambda value: isinstance(value, int) and value >= 1,
|
| 271 |
+
is_static=True,
|
| 272 |
+
default_value=1000,
|
| 273 |
+
),
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
@override
|
| 277 |
+
def configuration_validator(self) -> None:
|
| 278 |
+
batch_size = self.parameter_map.get("batch_size")
|
| 279 |
+
sync_threshold = self.parameter_map.get("sync_threshold")
|
| 280 |
+
|
| 281 |
+
if (
|
| 282 |
+
batch_size
|
| 283 |
+
and sync_threshold
|
| 284 |
+
and cast(int, batch_size.value) > cast(int, sync_threshold.value)
|
| 285 |
+
):
|
| 286 |
+
raise InvalidConfigurationError(
|
| 287 |
+
"batch_size must be less than or equal to sync_threshold"
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
@classmethod
|
| 291 |
+
def from_legacy_params(cls, params: Dict[str, Any]) -> Self:
|
| 292 |
+
"""Returns an HNSWConfiguration from a metadata dict containing legacy HNSW parameters. Used for migration."""
|
| 293 |
+
|
| 294 |
+
# We maintain this map to avoid a circular import with HnswParams, and
|
| 295 |
+
# because then names won't change since we intend to deprecate HNSWParams
|
| 296 |
+
# in favor of this type of configuration.
|
| 297 |
+
old_to_new = {
|
| 298 |
+
"hnsw:space": "space",
|
| 299 |
+
"hnsw:construction_ef": "ef_construction",
|
| 300 |
+
"hnsw:search_ef": "ef_search",
|
| 301 |
+
"hnsw:M": "M",
|
| 302 |
+
"hnsw:num_threads": "num_threads",
|
| 303 |
+
"hnsw:resize_factor": "resize_factor",
|
| 304 |
+
"hnsw:batch_size": "batch_size",
|
| 305 |
+
"hnsw:sync_threshold": "sync_threshold",
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
parameters = []
|
| 309 |
+
for name, value in params.items():
|
| 310 |
+
if name not in old_to_new:
|
| 311 |
+
raise ValueError(f"Invalid legacy HNSW parameter name: {name}")
|
| 312 |
+
parameters.append(
|
| 313 |
+
ConfigurationParameter(name=old_to_new[name], value=value)
|
| 314 |
+
)
|
| 315 |
+
return cls(parameters)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# This is the user-facing interface for HNSW index configuration parameters.
|
| 319 |
+
# Internally, we pass around HNSWConfigurationInternal objects, which perform
|
| 320 |
+
# validation, serialization and deserialization. Users don't need to know
|
| 321 |
+
# about that and instead get a clean constructor with default arguments.
|
| 322 |
+
class HNSWConfigurationInterface(HNSWConfigurationInternal):
|
| 323 |
+
"""HNSW index configuration parameters.
|
| 324 |
+
See https://docs.trychroma.com/guides#changing-the-distance-function for more information.
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
def __init__(
|
| 328 |
+
self,
|
| 329 |
+
space: str = "l2",
|
| 330 |
+
ef_construction: int = 100,
|
| 331 |
+
ef_search: int = 100,
|
| 332 |
+
num_threads: int = cpu_count(),
|
| 333 |
+
M: int = 16,
|
| 334 |
+
resize_factor: float = 1.2,
|
| 335 |
+
batch_size: int = 100,
|
| 336 |
+
sync_threshold: int = 1000,
|
| 337 |
+
):
|
| 338 |
+
parameters = [
|
| 339 |
+
ConfigurationParameter(name="space", value=space),
|
| 340 |
+
ConfigurationParameter(name="ef_construction", value=ef_construction),
|
| 341 |
+
ConfigurationParameter(name="ef_search", value=ef_search),
|
| 342 |
+
ConfigurationParameter(name="num_threads", value=num_threads),
|
| 343 |
+
ConfigurationParameter(name="M", value=M),
|
| 344 |
+
ConfigurationParameter(name="resize_factor", value=resize_factor),
|
| 345 |
+
ConfigurationParameter(name="batch_size", value=batch_size),
|
| 346 |
+
ConfigurationParameter(name="sync_threshold", value=sync_threshold),
|
| 347 |
+
]
|
| 348 |
+
|
| 349 |
+
super().__init__(parameters=parameters)
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
# Alias for user convenience - the user doesn't need to know this is an 'Interface'
|
| 353 |
+
HNSWConfiguration = HNSWConfigurationInterface
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
class CollectionConfigurationInternal(ConfigurationInternal):
|
| 357 |
+
"""Internal representation of the collection configuration.
|
| 358 |
+
Used for validation, defaults, and serialization / deserialization."""
|
| 359 |
+
|
| 360 |
+
definitions = {
|
| 361 |
+
"hnsw_configuration": ConfigurationDefinition(
|
| 362 |
+
name="hnsw_configuration",
|
| 363 |
+
validator=lambda value: isinstance(value, HNSWConfigurationInternal),
|
| 364 |
+
is_static=True,
|
| 365 |
+
default_value=HNSWConfigurationInternal(),
|
| 366 |
+
),
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
@override
|
| 370 |
+
def configuration_validator(self) -> None:
|
| 371 |
+
pass
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
# This is the user-facing interface for HNSW index configuration parameters.
|
| 375 |
+
# Internally, we pass around HNSWConfigurationInternal objects, which perform
|
| 376 |
+
# validation, serialization and deserialization. Users don't need to know
|
| 377 |
+
# about that and instead get a clean constructor with default arguments.
|
| 378 |
+
class CollectionConfigurationInterface(CollectionConfigurationInternal):
|
| 379 |
+
"""Configuration parameters for creating a collection."""
|
| 380 |
+
|
| 381 |
+
def __init__(self, hnsw_configuration: Optional[HNSWConfigurationInternal]):
|
| 382 |
+
"""Initializes a new instance of the CollectionConfiguration class.
|
| 383 |
+
Args:
|
| 384 |
+
hnsw_configuration: The HNSW configuration to use for the collection.
|
| 385 |
+
"""
|
| 386 |
+
if hnsw_configuration is None:
|
| 387 |
+
hnsw_configuration = HNSWConfigurationInternal()
|
| 388 |
+
parameters = [
|
| 389 |
+
ConfigurationParameter(name="hnsw_configuration", value=hnsw_configuration)
|
| 390 |
+
]
|
| 391 |
+
super().__init__(parameters=parameters)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
# Alias for user convenience - the user doesn't need to know this is an 'Interface'.
|
| 395 |
+
CollectionConfiguration = CollectionConfigurationInterface
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class EmbeddingsQueueConfigurationInternal(ConfigurationInternal):
|
| 399 |
+
definitions = {
|
| 400 |
+
"automatically_purge": ConfigurationDefinition(
|
| 401 |
+
name="automatically_purge",
|
| 402 |
+
validator=lambda value: isinstance(value, bool),
|
| 403 |
+
is_static=False,
|
| 404 |
+
default_value=True,
|
| 405 |
+
),
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
@override
|
| 409 |
+
def configuration_validator(self) -> None:
|
| 410 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/api/fastapi.py
ADDED
|
@@ -0,0 +1,915 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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3 |
+
from typing import Any, Dict, Mapping, Optional, cast, Tuple, List
|
| 4 |
+
from typing import Sequence
|
| 5 |
+
from uuid import UUID
|
| 6 |
+
import httpx
|
| 7 |
+
import urllib.parse
|
| 8 |
+
from overrides import override
|
| 9 |
+
|
| 10 |
+
from chromadb.api.models.AttachedFunction import AttachedFunction
|
| 11 |
+
|
| 12 |
+
from chromadb.api.collection_configuration import (
|
| 13 |
+
CreateCollectionConfiguration,
|
| 14 |
+
UpdateCollectionConfiguration,
|
| 15 |
+
update_collection_configuration_to_json,
|
| 16 |
+
create_collection_configuration_to_json,
|
| 17 |
+
)
|
| 18 |
+
from chromadb import __version__
|
| 19 |
+
from chromadb.api.base_http_client import BaseHTTPClient
|
| 20 |
+
from chromadb.types import Database, Tenant, Collection as CollectionModel
|
| 21 |
+
from chromadb.api import ServerAPI
|
| 22 |
+
from chromadb.execution.expression.plan import Search
|
| 23 |
+
|
| 24 |
+
from chromadb.api.types import (
|
| 25 |
+
DeleteResult,
|
| 26 |
+
Documents,
|
| 27 |
+
Embeddings,
|
| 28 |
+
IDs,
|
| 29 |
+
Include,
|
| 30 |
+
IndexingStatus,
|
| 31 |
+
Schema,
|
| 32 |
+
Metadatas,
|
| 33 |
+
ReadLevel,
|
| 34 |
+
URIs,
|
| 35 |
+
Where,
|
| 36 |
+
WhereDocument,
|
| 37 |
+
GetResult,
|
| 38 |
+
QueryResult,
|
| 39 |
+
SearchResult,
|
| 40 |
+
CollectionMetadata,
|
| 41 |
+
validate_batch,
|
| 42 |
+
convert_np_embeddings_to_list,
|
| 43 |
+
IncludeMetadataDocuments,
|
| 44 |
+
IncludeMetadataDocumentsDistances,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
from chromadb.api.types import (
|
| 48 |
+
IncludeMetadataDocumentsEmbeddings,
|
| 49 |
+
optional_embeddings_to_base64_strings,
|
| 50 |
+
serialize_metadata,
|
| 51 |
+
deserialize_metadata,
|
| 52 |
+
)
|
| 53 |
+
from chromadb.auth import UserIdentity
|
| 54 |
+
from chromadb.auth import (
|
| 55 |
+
ClientAuthProvider,
|
| 56 |
+
)
|
| 57 |
+
from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System
|
| 58 |
+
from chromadb.telemetry.opentelemetry import (
|
| 59 |
+
OpenTelemetryClient,
|
| 60 |
+
OpenTelemetryGranularity,
|
| 61 |
+
trace_method,
|
| 62 |
+
)
|
| 63 |
+
from chromadb.telemetry.product import ProductTelemetryClient
|
| 64 |
+
|
| 65 |
+
logger = logging.getLogger(__name__)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class FastAPI(BaseHTTPClient, ServerAPI):
|
| 69 |
+
def __init__(self, system: System):
|
| 70 |
+
super().__init__(system)
|
| 71 |
+
system.settings.require("chroma_server_host")
|
| 72 |
+
system.settings.require("chroma_server_http_port")
|
| 73 |
+
|
| 74 |
+
self._opentelemetry_client = self.require(OpenTelemetryClient)
|
| 75 |
+
self._product_telemetry_client = self.require(ProductTelemetryClient)
|
| 76 |
+
self._settings = system.settings
|
| 77 |
+
|
| 78 |
+
self._api_url = FastAPI.resolve_url(
|
| 79 |
+
chroma_server_host=str(system.settings.chroma_server_host),
|
| 80 |
+
chroma_server_http_port=system.settings.chroma_server_http_port,
|
| 81 |
+
chroma_server_ssl_enabled=system.settings.chroma_server_ssl_enabled,
|
| 82 |
+
default_api_path=system.settings.chroma_server_api_default_path,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
if self._settings.chroma_server_ssl_verify is not None:
|
| 86 |
+
self._session = httpx.Client(
|
| 87 |
+
timeout=None,
|
| 88 |
+
limits=self.http_limits,
|
| 89 |
+
verify=self._settings.chroma_server_ssl_verify,
|
| 90 |
+
)
|
| 91 |
+
else:
|
| 92 |
+
self._session = httpx.Client(timeout=None, limits=self.http_limits)
|
| 93 |
+
|
| 94 |
+
self._header = system.settings.chroma_server_headers or {}
|
| 95 |
+
self._header["Content-Type"] = "application/json"
|
| 96 |
+
self._header["User-Agent"] = (
|
| 97 |
+
"Chroma Python Client v"
|
| 98 |
+
+ __version__
|
| 99 |
+
+ " (https://github.com/chroma-core/chroma)"
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if self._header is not None:
|
| 103 |
+
self._session.headers.update(self._header)
|
| 104 |
+
|
| 105 |
+
if system.settings.chroma_client_auth_provider:
|
| 106 |
+
self._auth_provider = self.require(ClientAuthProvider)
|
| 107 |
+
_headers = self._auth_provider.authenticate()
|
| 108 |
+
for header, value in _headers.items():
|
| 109 |
+
self._session.headers[header] = value.get_secret_value()
|
| 110 |
+
|
| 111 |
+
@override
|
| 112 |
+
def get_request_headers(self) -> Mapping[str, str]:
|
| 113 |
+
return dict(self._session.headers)
|
| 114 |
+
|
| 115 |
+
@override
|
| 116 |
+
def get_api_url(self) -> str:
|
| 117 |
+
return self._api_url
|
| 118 |
+
|
| 119 |
+
def _make_request(self, method: str, path: str, **kwargs: Dict[str, Any]) -> Any:
|
| 120 |
+
# If the request has json in kwargs, use orjson to serialize it,
|
| 121 |
+
# remove it from kwargs, and add it to the content parameter
|
| 122 |
+
# This is because httpx uses a slower json serializer
|
| 123 |
+
if "json" in kwargs:
|
| 124 |
+
data = orjson.dumps(kwargs.pop("json"), option=orjson.OPT_SERIALIZE_NUMPY)
|
| 125 |
+
kwargs["content"] = data
|
| 126 |
+
|
| 127 |
+
# Unlike requests, httpx does not automatically escape the path
|
| 128 |
+
escaped_path = urllib.parse.quote(path, safe="/", encoding=None, errors=None)
|
| 129 |
+
url = self._api_url + escaped_path
|
| 130 |
+
|
| 131 |
+
response = self._session.request(method, url, **cast(Any, kwargs))
|
| 132 |
+
BaseHTTPClient._raise_chroma_error(response)
|
| 133 |
+
return orjson.loads(response.text)
|
| 134 |
+
|
| 135 |
+
@trace_method("FastAPI.heartbeat", OpenTelemetryGranularity.OPERATION)
|
| 136 |
+
@override
|
| 137 |
+
def heartbeat(self) -> int:
|
| 138 |
+
"""Returns the current server time in nanoseconds to check if the server is alive"""
|
| 139 |
+
resp_json = self._make_request("get", "/heartbeat")
|
| 140 |
+
return int(resp_json["nanosecond heartbeat"])
|
| 141 |
+
|
| 142 |
+
# Migrated to rust in distributed.
|
| 143 |
+
@trace_method("FastAPI.create_database", OpenTelemetryGranularity.OPERATION)
|
| 144 |
+
@override
|
| 145 |
+
def create_database(
|
| 146 |
+
self,
|
| 147 |
+
name: str,
|
| 148 |
+
tenant: str = DEFAULT_TENANT,
|
| 149 |
+
) -> None:
|
| 150 |
+
"""Creates a database"""
|
| 151 |
+
self._make_request(
|
| 152 |
+
"post",
|
| 153 |
+
f"/tenants/{tenant}/databases",
|
| 154 |
+
json={"name": name},
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Migrated to rust in distributed.
|
| 158 |
+
@trace_method("FastAPI.get_database", OpenTelemetryGranularity.OPERATION)
|
| 159 |
+
@override
|
| 160 |
+
def get_database(
|
| 161 |
+
self,
|
| 162 |
+
name: str,
|
| 163 |
+
tenant: str = DEFAULT_TENANT,
|
| 164 |
+
) -> Database:
|
| 165 |
+
"""Returns a database"""
|
| 166 |
+
resp_json = self._make_request(
|
| 167 |
+
"get",
|
| 168 |
+
f"/tenants/{tenant}/databases/{name}",
|
| 169 |
+
)
|
| 170 |
+
return Database(
|
| 171 |
+
id=resp_json["id"], name=resp_json["name"], tenant=resp_json["tenant"]
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
@trace_method("FastAPI.delete_database", OpenTelemetryGranularity.OPERATION)
|
| 175 |
+
@override
|
| 176 |
+
def delete_database(
|
| 177 |
+
self,
|
| 178 |
+
name: str,
|
| 179 |
+
tenant: str = DEFAULT_TENANT,
|
| 180 |
+
) -> None:
|
| 181 |
+
"""Deletes a database"""
|
| 182 |
+
self._make_request(
|
| 183 |
+
"delete",
|
| 184 |
+
f"/tenants/{tenant}/databases/{name}",
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
@trace_method("FastAPI.list_databases", OpenTelemetryGranularity.OPERATION)
|
| 188 |
+
@override
|
| 189 |
+
def list_databases(
|
| 190 |
+
self,
|
| 191 |
+
limit: Optional[int] = None,
|
| 192 |
+
offset: Optional[int] = None,
|
| 193 |
+
tenant: str = DEFAULT_TENANT,
|
| 194 |
+
) -> Sequence[Database]:
|
| 195 |
+
"""Returns a list of all databases"""
|
| 196 |
+
json_databases = self._make_request(
|
| 197 |
+
"get",
|
| 198 |
+
f"/tenants/{tenant}/databases",
|
| 199 |
+
params=BaseHTTPClient._clean_params(
|
| 200 |
+
{
|
| 201 |
+
"limit": limit,
|
| 202 |
+
"offset": offset,
|
| 203 |
+
}
|
| 204 |
+
),
|
| 205 |
+
)
|
| 206 |
+
databases = [
|
| 207 |
+
Database(id=db["id"], name=db["name"], tenant=db["tenant"])
|
| 208 |
+
for db in json_databases
|
| 209 |
+
]
|
| 210 |
+
return databases
|
| 211 |
+
|
| 212 |
+
@trace_method("FastAPI.create_tenant", OpenTelemetryGranularity.OPERATION)
|
| 213 |
+
@override
|
| 214 |
+
def create_tenant(self, name: str) -> None:
|
| 215 |
+
self._make_request("post", "/tenants", json={"name": name})
|
| 216 |
+
|
| 217 |
+
@trace_method("FastAPI.get_tenant", OpenTelemetryGranularity.OPERATION)
|
| 218 |
+
@override
|
| 219 |
+
def get_tenant(self, name: str) -> Tenant:
|
| 220 |
+
resp_json = self._make_request("get", "/tenants/" + name)
|
| 221 |
+
return Tenant(name=resp_json["name"])
|
| 222 |
+
|
| 223 |
+
@trace_method("FastAPI.get_user_identity", OpenTelemetryGranularity.OPERATION)
|
| 224 |
+
@override
|
| 225 |
+
def get_user_identity(self) -> UserIdentity:
|
| 226 |
+
return UserIdentity(**self._make_request("get", "/auth/identity"))
|
| 227 |
+
|
| 228 |
+
@trace_method("FastAPI.list_collections", OpenTelemetryGranularity.OPERATION)
|
| 229 |
+
@override
|
| 230 |
+
def list_collections(
|
| 231 |
+
self,
|
| 232 |
+
limit: Optional[int] = None,
|
| 233 |
+
offset: Optional[int] = None,
|
| 234 |
+
tenant: str = DEFAULT_TENANT,
|
| 235 |
+
database: str = DEFAULT_DATABASE,
|
| 236 |
+
) -> Sequence[CollectionModel]:
|
| 237 |
+
"""Returns a list of all collections"""
|
| 238 |
+
json_collections = self._make_request(
|
| 239 |
+
"get",
|
| 240 |
+
f"/tenants/{tenant}/databases/{database}/collections",
|
| 241 |
+
params=BaseHTTPClient._clean_params(
|
| 242 |
+
{
|
| 243 |
+
"limit": limit,
|
| 244 |
+
"offset": offset,
|
| 245 |
+
}
|
| 246 |
+
),
|
| 247 |
+
)
|
| 248 |
+
collection_models = [
|
| 249 |
+
CollectionModel.from_json(json_collection)
|
| 250 |
+
for json_collection in json_collections
|
| 251 |
+
]
|
| 252 |
+
|
| 253 |
+
return collection_models
|
| 254 |
+
|
| 255 |
+
@trace_method("FastAPI.count_collections", OpenTelemetryGranularity.OPERATION)
|
| 256 |
+
@override
|
| 257 |
+
def count_collections(
|
| 258 |
+
self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE
|
| 259 |
+
) -> int:
|
| 260 |
+
"""Returns a count of collections"""
|
| 261 |
+
resp_json = self._make_request(
|
| 262 |
+
"get",
|
| 263 |
+
f"/tenants/{tenant}/databases/{database}/collections_count",
|
| 264 |
+
)
|
| 265 |
+
return cast(int, resp_json)
|
| 266 |
+
|
| 267 |
+
@trace_method("FastAPI.create_collection", OpenTelemetryGranularity.OPERATION)
|
| 268 |
+
@override
|
| 269 |
+
def create_collection(
|
| 270 |
+
self,
|
| 271 |
+
name: str,
|
| 272 |
+
schema: Optional[Schema] = None,
|
| 273 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 274 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 275 |
+
get_or_create: bool = False,
|
| 276 |
+
tenant: str = DEFAULT_TENANT,
|
| 277 |
+
database: str = DEFAULT_DATABASE,
|
| 278 |
+
) -> CollectionModel:
|
| 279 |
+
"""Creates a collection"""
|
| 280 |
+
config_json = (
|
| 281 |
+
create_collection_configuration_to_json(configuration, metadata)
|
| 282 |
+
if configuration
|
| 283 |
+
else None
|
| 284 |
+
)
|
| 285 |
+
serialized_schema = schema.serialize_to_json() if schema else None
|
| 286 |
+
resp_json = self._make_request(
|
| 287 |
+
"post",
|
| 288 |
+
f"/tenants/{tenant}/databases/{database}/collections",
|
| 289 |
+
json={
|
| 290 |
+
"name": name,
|
| 291 |
+
"metadata": metadata,
|
| 292 |
+
"configuration": config_json,
|
| 293 |
+
"schema": serialized_schema,
|
| 294 |
+
"get_or_create": get_or_create,
|
| 295 |
+
},
|
| 296 |
+
)
|
| 297 |
+
model = CollectionModel.from_json(resp_json)
|
| 298 |
+
|
| 299 |
+
return model
|
| 300 |
+
|
| 301 |
+
@trace_method("FastAPI.get_collection", OpenTelemetryGranularity.OPERATION)
|
| 302 |
+
@override
|
| 303 |
+
def get_collection(
|
| 304 |
+
self,
|
| 305 |
+
name: str,
|
| 306 |
+
tenant: str = DEFAULT_TENANT,
|
| 307 |
+
database: str = DEFAULT_DATABASE,
|
| 308 |
+
) -> CollectionModel:
|
| 309 |
+
"""Returns a collection"""
|
| 310 |
+
resp_json = self._make_request(
|
| 311 |
+
"get",
|
| 312 |
+
f"/tenants/{tenant}/databases/{database}/collections/{name}",
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
model = CollectionModel.from_json(resp_json)
|
| 316 |
+
return model
|
| 317 |
+
|
| 318 |
+
@trace_method("FastAPI.get_collection_by_id", OpenTelemetryGranularity.OPERATION)
|
| 319 |
+
@override
|
| 320 |
+
def get_collection_by_id(
|
| 321 |
+
self,
|
| 322 |
+
collection_id: UUID,
|
| 323 |
+
tenant: str = DEFAULT_TENANT,
|
| 324 |
+
database: str = DEFAULT_DATABASE,
|
| 325 |
+
) -> CollectionModel:
|
| 326 |
+
"""Returns a collection by its ID"""
|
| 327 |
+
resp_json = self._make_request(
|
| 328 |
+
"get",
|
| 329 |
+
f"/tenants/{tenant}/databases/{database}/collections/by-id/{collection_id}",
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
model = CollectionModel.from_json(resp_json)
|
| 333 |
+
return model
|
| 334 |
+
|
| 335 |
+
@trace_method(
|
| 336 |
+
"FastAPI.get_or_create_collection", OpenTelemetryGranularity.OPERATION
|
| 337 |
+
)
|
| 338 |
+
@override
|
| 339 |
+
def get_or_create_collection(
|
| 340 |
+
self,
|
| 341 |
+
name: str,
|
| 342 |
+
schema: Optional[Schema] = None,
|
| 343 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 344 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 345 |
+
tenant: str = DEFAULT_TENANT,
|
| 346 |
+
database: str = DEFAULT_DATABASE,
|
| 347 |
+
) -> CollectionModel:
|
| 348 |
+
return self.create_collection(
|
| 349 |
+
name=name,
|
| 350 |
+
metadata=metadata,
|
| 351 |
+
configuration=configuration,
|
| 352 |
+
schema=schema,
|
| 353 |
+
get_or_create=True,
|
| 354 |
+
tenant=tenant,
|
| 355 |
+
database=database,
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
@trace_method("FastAPI._modify", OpenTelemetryGranularity.OPERATION)
|
| 359 |
+
@override
|
| 360 |
+
def _modify(
|
| 361 |
+
self,
|
| 362 |
+
id: UUID,
|
| 363 |
+
new_name: Optional[str] = None,
|
| 364 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 365 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 366 |
+
tenant: str = DEFAULT_TENANT,
|
| 367 |
+
database: str = DEFAULT_DATABASE,
|
| 368 |
+
) -> None:
|
| 369 |
+
"""Updates a collection"""
|
| 370 |
+
self._make_request(
|
| 371 |
+
"put",
|
| 372 |
+
f"/tenants/{tenant}/databases/{database}/collections/{id}",
|
| 373 |
+
json={
|
| 374 |
+
"new_metadata": new_metadata,
|
| 375 |
+
"new_name": new_name,
|
| 376 |
+
"new_configuration": update_collection_configuration_to_json(
|
| 377 |
+
new_configuration
|
| 378 |
+
)
|
| 379 |
+
if new_configuration
|
| 380 |
+
else None,
|
| 381 |
+
},
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
@trace_method("FastAPI._fork", OpenTelemetryGranularity.OPERATION)
|
| 385 |
+
@override
|
| 386 |
+
def _fork(
|
| 387 |
+
self,
|
| 388 |
+
collection_id: UUID,
|
| 389 |
+
new_name: str,
|
| 390 |
+
tenant: str = DEFAULT_TENANT,
|
| 391 |
+
database: str = DEFAULT_DATABASE,
|
| 392 |
+
) -> CollectionModel:
|
| 393 |
+
"""Forks a collection"""
|
| 394 |
+
resp_json = self._make_request(
|
| 395 |
+
"post",
|
| 396 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/fork",
|
| 397 |
+
json={"new_name": new_name},
|
| 398 |
+
)
|
| 399 |
+
model = CollectionModel.from_json(resp_json)
|
| 400 |
+
return model
|
| 401 |
+
|
| 402 |
+
@trace_method("FastAPI._fork_count", OpenTelemetryGranularity.OPERATION)
|
| 403 |
+
@override
|
| 404 |
+
def _fork_count(
|
| 405 |
+
self,
|
| 406 |
+
collection_id: UUID,
|
| 407 |
+
tenant: str = DEFAULT_TENANT,
|
| 408 |
+
database: str = DEFAULT_DATABASE,
|
| 409 |
+
) -> int:
|
| 410 |
+
"""Gets the number of forks for a collection"""
|
| 411 |
+
resp_json = self._make_request(
|
| 412 |
+
"get",
|
| 413 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/fork_count",
|
| 414 |
+
)
|
| 415 |
+
return int(resp_json["count"])
|
| 416 |
+
|
| 417 |
+
@trace_method("FastAPI._get_indexing_status", OpenTelemetryGranularity.OPERATION)
|
| 418 |
+
@override
|
| 419 |
+
def _get_indexing_status(
|
| 420 |
+
self,
|
| 421 |
+
collection_id: UUID,
|
| 422 |
+
tenant: str = DEFAULT_TENANT,
|
| 423 |
+
database: str = DEFAULT_DATABASE,
|
| 424 |
+
) -> IndexingStatus:
|
| 425 |
+
resp_json = self._make_request(
|
| 426 |
+
"get",
|
| 427 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/indexing_status",
|
| 428 |
+
)
|
| 429 |
+
return IndexingStatus(
|
| 430 |
+
num_indexed_ops=resp_json["num_indexed_ops"],
|
| 431 |
+
num_unindexed_ops=resp_json["num_unindexed_ops"],
|
| 432 |
+
total_ops=resp_json["total_ops"],
|
| 433 |
+
op_indexing_progress=resp_json["op_indexing_progress"],
|
| 434 |
+
)
|
| 435 |
+
|
| 436 |
+
@trace_method("FastAPI._search", OpenTelemetryGranularity.OPERATION)
|
| 437 |
+
@override
|
| 438 |
+
def _search(
|
| 439 |
+
self,
|
| 440 |
+
collection_id: UUID,
|
| 441 |
+
searches: List[Search],
|
| 442 |
+
tenant: str = DEFAULT_TENANT,
|
| 443 |
+
database: str = DEFAULT_DATABASE,
|
| 444 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 445 |
+
) -> SearchResult:
|
| 446 |
+
"""Performs hybrid search on a collection"""
|
| 447 |
+
# Convert Search objects to dictionaries
|
| 448 |
+
payload = {
|
| 449 |
+
"searches": [s.to_dict() for s in searches],
|
| 450 |
+
"read_level": read_level,
|
| 451 |
+
}
|
| 452 |
+
|
| 453 |
+
resp_json = self._make_request(
|
| 454 |
+
"post",
|
| 455 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/search",
|
| 456 |
+
json=payload,
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
# Deserialize metadatas: convert transport format to SparseVector instances
|
| 460 |
+
metadata_batches = resp_json.get("metadatas", None)
|
| 461 |
+
if metadata_batches is not None:
|
| 462 |
+
# SearchResult has nested structure: List[Optional[List[Optional[Metadata]]]]
|
| 463 |
+
resp_json["metadatas"] = [
|
| 464 |
+
[
|
| 465 |
+
deserialize_metadata(metadata) if metadata is not None else None
|
| 466 |
+
for metadata in metadatas
|
| 467 |
+
]
|
| 468 |
+
if metadatas is not None
|
| 469 |
+
else None
|
| 470 |
+
for metadatas in metadata_batches
|
| 471 |
+
]
|
| 472 |
+
|
| 473 |
+
return SearchResult(resp_json)
|
| 474 |
+
|
| 475 |
+
@trace_method("FastAPI.delete_collection", OpenTelemetryGranularity.OPERATION)
|
| 476 |
+
@override
|
| 477 |
+
def delete_collection(
|
| 478 |
+
self,
|
| 479 |
+
name: str,
|
| 480 |
+
tenant: str = DEFAULT_TENANT,
|
| 481 |
+
database: str = DEFAULT_DATABASE,
|
| 482 |
+
) -> None:
|
| 483 |
+
"""Deletes a collection"""
|
| 484 |
+
self._make_request(
|
| 485 |
+
"delete",
|
| 486 |
+
f"/tenants/{tenant}/databases/{database}/collections/{name}",
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
@trace_method("FastAPI._count", OpenTelemetryGranularity.OPERATION)
|
| 490 |
+
@override
|
| 491 |
+
def _count(
|
| 492 |
+
self,
|
| 493 |
+
collection_id: UUID,
|
| 494 |
+
tenant: str = DEFAULT_TENANT,
|
| 495 |
+
database: str = DEFAULT_DATABASE,
|
| 496 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 497 |
+
) -> int:
|
| 498 |
+
"""Returns the number of embeddings in the database"""
|
| 499 |
+
resp_json = self._make_request(
|
| 500 |
+
"get",
|
| 501 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/count",
|
| 502 |
+
params={"read_level": read_level.value},
|
| 503 |
+
)
|
| 504 |
+
return cast(int, resp_json)
|
| 505 |
+
|
| 506 |
+
@trace_method("FastAPI._peek", OpenTelemetryGranularity.OPERATION)
|
| 507 |
+
@override
|
| 508 |
+
def _peek(
|
| 509 |
+
self,
|
| 510 |
+
collection_id: UUID,
|
| 511 |
+
n: int = 10,
|
| 512 |
+
tenant: str = DEFAULT_TENANT,
|
| 513 |
+
database: str = DEFAULT_DATABASE,
|
| 514 |
+
) -> GetResult:
|
| 515 |
+
return cast(
|
| 516 |
+
GetResult,
|
| 517 |
+
self._get(
|
| 518 |
+
collection_id,
|
| 519 |
+
tenant=tenant,
|
| 520 |
+
database=database,
|
| 521 |
+
limit=n,
|
| 522 |
+
include=IncludeMetadataDocumentsEmbeddings,
|
| 523 |
+
),
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
@trace_method("FastAPI._get", OpenTelemetryGranularity.OPERATION)
|
| 527 |
+
@override
|
| 528 |
+
def _get(
|
| 529 |
+
self,
|
| 530 |
+
collection_id: UUID,
|
| 531 |
+
ids: Optional[IDs] = None,
|
| 532 |
+
where: Optional[Where] = None,
|
| 533 |
+
limit: Optional[int] = None,
|
| 534 |
+
offset: Optional[int] = None,
|
| 535 |
+
where_document: Optional[WhereDocument] = None,
|
| 536 |
+
include: Include = IncludeMetadataDocuments,
|
| 537 |
+
tenant: str = DEFAULT_TENANT,
|
| 538 |
+
database: str = DEFAULT_DATABASE,
|
| 539 |
+
) -> GetResult:
|
| 540 |
+
# Servers do not support receiving "data", as that is hydrated by the client as a loadable
|
| 541 |
+
filtered_include = [i for i in include if i != "data"]
|
| 542 |
+
|
| 543 |
+
resp_json = self._make_request(
|
| 544 |
+
"post",
|
| 545 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/get",
|
| 546 |
+
json={
|
| 547 |
+
"ids": ids,
|
| 548 |
+
"where": where,
|
| 549 |
+
"limit": limit,
|
| 550 |
+
"offset": offset,
|
| 551 |
+
"where_document": where_document,
|
| 552 |
+
"include": filtered_include,
|
| 553 |
+
},
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
# Deserialize metadatas: convert transport format to SparseVector instances
|
| 557 |
+
metadatas = resp_json.get("metadatas", None)
|
| 558 |
+
if metadatas is not None:
|
| 559 |
+
metadatas = [
|
| 560 |
+
deserialize_metadata(metadata) if metadata is not None else None
|
| 561 |
+
for metadata in metadatas
|
| 562 |
+
]
|
| 563 |
+
|
| 564 |
+
return GetResult(
|
| 565 |
+
ids=resp_json["ids"],
|
| 566 |
+
embeddings=resp_json.get("embeddings", None),
|
| 567 |
+
metadatas=metadatas,
|
| 568 |
+
documents=resp_json.get("documents", None),
|
| 569 |
+
data=None,
|
| 570 |
+
uris=resp_json.get("uris", None),
|
| 571 |
+
included=include,
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
@trace_method("FastAPI._delete", OpenTelemetryGranularity.OPERATION)
|
| 575 |
+
@override
|
| 576 |
+
def _delete(
|
| 577 |
+
self,
|
| 578 |
+
collection_id: UUID,
|
| 579 |
+
ids: Optional[IDs] = None,
|
| 580 |
+
where: Optional[Where] = None,
|
| 581 |
+
where_document: Optional[WhereDocument] = None,
|
| 582 |
+
limit: Optional[int] = None,
|
| 583 |
+
tenant: str = DEFAULT_TENANT,
|
| 584 |
+
database: str = DEFAULT_DATABASE,
|
| 585 |
+
) -> DeleteResult:
|
| 586 |
+
"""Deletes embeddings from the database"""
|
| 587 |
+
body: dict = {
|
| 588 |
+
"ids": ids,
|
| 589 |
+
"where": where,
|
| 590 |
+
"where_document": where_document,
|
| 591 |
+
}
|
| 592 |
+
if limit is not None:
|
| 593 |
+
body["limit"] = limit
|
| 594 |
+
resp = self._make_request(
|
| 595 |
+
"post",
|
| 596 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/delete",
|
| 597 |
+
json=body,
|
| 598 |
+
)
|
| 599 |
+
return DeleteResult(deleted=resp.get("deleted", 0) if resp else 0)
|
| 600 |
+
|
| 601 |
+
@trace_method("FastAPI._submit_batch", OpenTelemetryGranularity.ALL)
|
| 602 |
+
def _submit_batch(
|
| 603 |
+
self,
|
| 604 |
+
batch: Tuple[
|
| 605 |
+
IDs,
|
| 606 |
+
Optional[Embeddings],
|
| 607 |
+
Optional[Metadatas],
|
| 608 |
+
Optional[Documents],
|
| 609 |
+
Optional[URIs],
|
| 610 |
+
],
|
| 611 |
+
url: str,
|
| 612 |
+
) -> None:
|
| 613 |
+
"""
|
| 614 |
+
Submits a batch of embeddings to the database
|
| 615 |
+
"""
|
| 616 |
+
# Serialize metadatas: convert SparseVector instances to transport format
|
| 617 |
+
serialized_metadatas = None
|
| 618 |
+
if batch[2] is not None:
|
| 619 |
+
serialized_metadatas = [
|
| 620 |
+
serialize_metadata(metadata) if metadata is not None else None
|
| 621 |
+
for metadata in batch[2]
|
| 622 |
+
]
|
| 623 |
+
|
| 624 |
+
data = {
|
| 625 |
+
"ids": batch[0],
|
| 626 |
+
"embeddings": optional_embeddings_to_base64_strings(batch[1])
|
| 627 |
+
if self.supports_base64_encoding()
|
| 628 |
+
else batch[1],
|
| 629 |
+
"metadatas": serialized_metadatas,
|
| 630 |
+
"documents": batch[3],
|
| 631 |
+
"uris": batch[4],
|
| 632 |
+
}
|
| 633 |
+
|
| 634 |
+
self._make_request("post", url, json=data)
|
| 635 |
+
|
| 636 |
+
@trace_method("FastAPI._add", OpenTelemetryGranularity.ALL)
|
| 637 |
+
@override
|
| 638 |
+
def _add(
|
| 639 |
+
self,
|
| 640 |
+
ids: IDs,
|
| 641 |
+
collection_id: UUID,
|
| 642 |
+
embeddings: Embeddings,
|
| 643 |
+
metadatas: Optional[Metadatas] = None,
|
| 644 |
+
documents: Optional[Documents] = None,
|
| 645 |
+
uris: Optional[URIs] = None,
|
| 646 |
+
tenant: str = DEFAULT_TENANT,
|
| 647 |
+
database: str = DEFAULT_DATABASE,
|
| 648 |
+
) -> bool:
|
| 649 |
+
"""
|
| 650 |
+
Adds a batch of embeddings to the database
|
| 651 |
+
- pass in column oriented data lists
|
| 652 |
+
"""
|
| 653 |
+
batch = (
|
| 654 |
+
ids,
|
| 655 |
+
embeddings,
|
| 656 |
+
metadatas,
|
| 657 |
+
documents,
|
| 658 |
+
uris,
|
| 659 |
+
)
|
| 660 |
+
validate_batch(batch, {"max_batch_size": self.get_max_batch_size()})
|
| 661 |
+
self._submit_batch(
|
| 662 |
+
batch,
|
| 663 |
+
f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/add",
|
| 664 |
+
)
|
| 665 |
+
return True
|
| 666 |
+
|
| 667 |
+
@trace_method("FastAPI._update", OpenTelemetryGranularity.ALL)
|
| 668 |
+
@override
|
| 669 |
+
def _update(
|
| 670 |
+
self,
|
| 671 |
+
collection_id: UUID,
|
| 672 |
+
ids: IDs,
|
| 673 |
+
embeddings: Optional[Embeddings] = None,
|
| 674 |
+
metadatas: Optional[Metadatas] = None,
|
| 675 |
+
documents: Optional[Documents] = None,
|
| 676 |
+
uris: Optional[URIs] = None,
|
| 677 |
+
tenant: str = DEFAULT_TENANT,
|
| 678 |
+
database: str = DEFAULT_DATABASE,
|
| 679 |
+
) -> bool:
|
| 680 |
+
"""
|
| 681 |
+
Updates a batch of embeddings in the database
|
| 682 |
+
- pass in column oriented data lists
|
| 683 |
+
"""
|
| 684 |
+
batch = (
|
| 685 |
+
ids,
|
| 686 |
+
embeddings if embeddings is not None else None,
|
| 687 |
+
metadatas,
|
| 688 |
+
documents,
|
| 689 |
+
uris,
|
| 690 |
+
)
|
| 691 |
+
validate_batch(batch, {"max_batch_size": self.get_max_batch_size()})
|
| 692 |
+
self._submit_batch(
|
| 693 |
+
batch,
|
| 694 |
+
f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/update",
|
| 695 |
+
)
|
| 696 |
+
return True
|
| 697 |
+
|
| 698 |
+
@trace_method("FastAPI._upsert", OpenTelemetryGranularity.ALL)
|
| 699 |
+
@override
|
| 700 |
+
def _upsert(
|
| 701 |
+
self,
|
| 702 |
+
collection_id: UUID,
|
| 703 |
+
ids: IDs,
|
| 704 |
+
embeddings: Embeddings,
|
| 705 |
+
metadatas: Optional[Metadatas] = None,
|
| 706 |
+
documents: Optional[Documents] = None,
|
| 707 |
+
uris: Optional[URIs] = None,
|
| 708 |
+
tenant: str = DEFAULT_TENANT,
|
| 709 |
+
database: str = DEFAULT_DATABASE,
|
| 710 |
+
) -> bool:
|
| 711 |
+
"""
|
| 712 |
+
Upserts a batch of embeddings in the database
|
| 713 |
+
- pass in column oriented data lists
|
| 714 |
+
"""
|
| 715 |
+
batch = (
|
| 716 |
+
ids,
|
| 717 |
+
embeddings,
|
| 718 |
+
metadatas,
|
| 719 |
+
documents,
|
| 720 |
+
uris,
|
| 721 |
+
)
|
| 722 |
+
validate_batch(batch, {"max_batch_size": self.get_max_batch_size()})
|
| 723 |
+
self._submit_batch(
|
| 724 |
+
batch,
|
| 725 |
+
f"/tenants/{tenant}/databases/{database}/collections/{str(collection_id)}/upsert",
|
| 726 |
+
)
|
| 727 |
+
return True
|
| 728 |
+
|
| 729 |
+
@trace_method("FastAPI._query", OpenTelemetryGranularity.ALL)
|
| 730 |
+
@override
|
| 731 |
+
def _query(
|
| 732 |
+
self,
|
| 733 |
+
collection_id: UUID,
|
| 734 |
+
query_embeddings: Embeddings,
|
| 735 |
+
ids: Optional[IDs] = None,
|
| 736 |
+
n_results: int = 10,
|
| 737 |
+
where: Optional[Where] = None,
|
| 738 |
+
where_document: Optional[WhereDocument] = None,
|
| 739 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 740 |
+
tenant: str = DEFAULT_TENANT,
|
| 741 |
+
database: str = DEFAULT_DATABASE,
|
| 742 |
+
) -> QueryResult:
|
| 743 |
+
# Clients do not support receiving "data", as that is hydrated by the client as a loadable
|
| 744 |
+
filtered_include = [i for i in include if i != "data"]
|
| 745 |
+
|
| 746 |
+
"""Gets the nearest neighbors of a single embedding"""
|
| 747 |
+
resp_json = self._make_request(
|
| 748 |
+
"post",
|
| 749 |
+
f"/tenants/{tenant}/databases/{database}/collections/{collection_id}/query",
|
| 750 |
+
json={
|
| 751 |
+
"ids": ids,
|
| 752 |
+
"query_embeddings": convert_np_embeddings_to_list(query_embeddings)
|
| 753 |
+
if query_embeddings is not None
|
| 754 |
+
else None,
|
| 755 |
+
"n_results": n_results,
|
| 756 |
+
"where": where,
|
| 757 |
+
"where_document": where_document,
|
| 758 |
+
"include": filtered_include,
|
| 759 |
+
},
|
| 760 |
+
)
|
| 761 |
+
|
| 762 |
+
# Deserialize metadatas: convert transport format to SparseVector instances
|
| 763 |
+
metadata_batches = resp_json.get("metadatas", None)
|
| 764 |
+
if metadata_batches is not None:
|
| 765 |
+
metadata_batches = [
|
| 766 |
+
[
|
| 767 |
+
deserialize_metadata(metadata) if metadata is not None else None
|
| 768 |
+
for metadata in metadatas
|
| 769 |
+
]
|
| 770 |
+
if metadatas is not None
|
| 771 |
+
else None
|
| 772 |
+
for metadatas in metadata_batches
|
| 773 |
+
]
|
| 774 |
+
|
| 775 |
+
return QueryResult(
|
| 776 |
+
ids=resp_json["ids"],
|
| 777 |
+
distances=resp_json.get("distances", None),
|
| 778 |
+
embeddings=resp_json.get("embeddings", None),
|
| 779 |
+
metadatas=metadata_batches,
|
| 780 |
+
documents=resp_json.get("documents", None),
|
| 781 |
+
uris=resp_json.get("uris", None),
|
| 782 |
+
data=None,
|
| 783 |
+
included=include,
|
| 784 |
+
)
|
| 785 |
+
|
| 786 |
+
@trace_method("FastAPI.reset", OpenTelemetryGranularity.ALL)
|
| 787 |
+
@override
|
| 788 |
+
def reset(self) -> bool:
|
| 789 |
+
"""Resets the database"""
|
| 790 |
+
resp_json = self._make_request("post", "/reset")
|
| 791 |
+
return cast(bool, resp_json)
|
| 792 |
+
|
| 793 |
+
@trace_method("FastAPI.get_version", OpenTelemetryGranularity.OPERATION)
|
| 794 |
+
@override
|
| 795 |
+
def get_version(self) -> str:
|
| 796 |
+
"""Returns the version of the server"""
|
| 797 |
+
resp_json = self._make_request("get", "/version")
|
| 798 |
+
return cast(str, resp_json)
|
| 799 |
+
|
| 800 |
+
@override
|
| 801 |
+
def get_settings(self) -> Settings:
|
| 802 |
+
"""Returns the settings of the client"""
|
| 803 |
+
return self._settings
|
| 804 |
+
|
| 805 |
+
@trace_method("FastAPI.get_pre_flight_checks", OpenTelemetryGranularity.OPERATION)
|
| 806 |
+
def get_pre_flight_checks(self) -> Any:
|
| 807 |
+
if self.pre_flight_checks is None:
|
| 808 |
+
resp_json = self._make_request("get", "/pre-flight-checks")
|
| 809 |
+
self.pre_flight_checks = resp_json
|
| 810 |
+
return self.pre_flight_checks
|
| 811 |
+
|
| 812 |
+
@trace_method(
|
| 813 |
+
"FastAPI.supports_base64_encoding", OpenTelemetryGranularity.OPERATION
|
| 814 |
+
)
|
| 815 |
+
def supports_base64_encoding(self) -> bool:
|
| 816 |
+
pre_flight_checks = self.get_pre_flight_checks()
|
| 817 |
+
b64_encoding_enabled = cast(
|
| 818 |
+
bool, pre_flight_checks.get("supports_base64_encoding", False)
|
| 819 |
+
)
|
| 820 |
+
return b64_encoding_enabled
|
| 821 |
+
|
| 822 |
+
@trace_method("FastAPI.get_max_batch_size", OpenTelemetryGranularity.OPERATION)
|
| 823 |
+
@override
|
| 824 |
+
def get_max_batch_size(self) -> int:
|
| 825 |
+
pre_flight_checks = self.get_pre_flight_checks()
|
| 826 |
+
max_batch_size = cast(int, pre_flight_checks.get("max_batch_size", -1))
|
| 827 |
+
return max_batch_size
|
| 828 |
+
|
| 829 |
+
@trace_method("FastAPI.attach_function", OpenTelemetryGranularity.ALL)
|
| 830 |
+
@override
|
| 831 |
+
def attach_function(
|
| 832 |
+
self,
|
| 833 |
+
function_id: str,
|
| 834 |
+
name: str,
|
| 835 |
+
input_collection_id: UUID,
|
| 836 |
+
output_collection: str,
|
| 837 |
+
params: Optional[Dict[str, Any]] = None,
|
| 838 |
+
tenant: str = DEFAULT_TENANT,
|
| 839 |
+
database: str = DEFAULT_DATABASE,
|
| 840 |
+
) -> Tuple["AttachedFunction", bool]:
|
| 841 |
+
"""Attach a function to a collection."""
|
| 842 |
+
resp_json = self._make_request(
|
| 843 |
+
"post",
|
| 844 |
+
f"/tenants/{tenant}/databases/{database}/collections/{input_collection_id}/functions/attach",
|
| 845 |
+
json={
|
| 846 |
+
"name": name,
|
| 847 |
+
"function_id": function_id,
|
| 848 |
+
"output_collection": output_collection,
|
| 849 |
+
"params": params,
|
| 850 |
+
},
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
attached_function = AttachedFunction(
|
| 854 |
+
client=self,
|
| 855 |
+
id=UUID(resp_json["attached_function"]["id"]),
|
| 856 |
+
name=resp_json["attached_function"]["name"],
|
| 857 |
+
function_name=resp_json["attached_function"]["function_name"],
|
| 858 |
+
input_collection_id=input_collection_id,
|
| 859 |
+
output_collection=output_collection,
|
| 860 |
+
params=params,
|
| 861 |
+
tenant=tenant,
|
| 862 |
+
database=database,
|
| 863 |
+
)
|
| 864 |
+
created = resp_json.get(
|
| 865 |
+
"created", True
|
| 866 |
+
) # Default to True for backwards compatibility
|
| 867 |
+
return (attached_function, created)
|
| 868 |
+
|
| 869 |
+
@trace_method("FastAPI.get_attached_function", OpenTelemetryGranularity.ALL)
|
| 870 |
+
@override
|
| 871 |
+
def get_attached_function(
|
| 872 |
+
self,
|
| 873 |
+
name: str,
|
| 874 |
+
input_collection_id: UUID,
|
| 875 |
+
tenant: str = DEFAULT_TENANT,
|
| 876 |
+
database: str = DEFAULT_DATABASE,
|
| 877 |
+
) -> "AttachedFunction":
|
| 878 |
+
"""Get an attached function by name for a specific collection."""
|
| 879 |
+
resp_json = self._make_request(
|
| 880 |
+
"get",
|
| 881 |
+
f"/tenants/{tenant}/databases/{database}/collections/{input_collection_id}/functions/{name}",
|
| 882 |
+
)
|
| 883 |
+
|
| 884 |
+
af = resp_json["attached_function"]
|
| 885 |
+
return AttachedFunction(
|
| 886 |
+
client=self,
|
| 887 |
+
id=UUID(af["id"]),
|
| 888 |
+
name=af["name"],
|
| 889 |
+
function_name=af["function_name"],
|
| 890 |
+
input_collection_id=input_collection_id,
|
| 891 |
+
output_collection=af["output_collection"],
|
| 892 |
+
params=af.get("params"),
|
| 893 |
+
tenant=tenant,
|
| 894 |
+
database=database,
|
| 895 |
+
)
|
| 896 |
+
|
| 897 |
+
@trace_method("FastAPI.detach_function", OpenTelemetryGranularity.ALL)
|
| 898 |
+
@override
|
| 899 |
+
def detach_function(
|
| 900 |
+
self,
|
| 901 |
+
name: str,
|
| 902 |
+
input_collection_id: UUID,
|
| 903 |
+
delete_output: bool = False,
|
| 904 |
+
tenant: str = DEFAULT_TENANT,
|
| 905 |
+
database: str = DEFAULT_DATABASE,
|
| 906 |
+
) -> bool:
|
| 907 |
+
"""Detach a function and prevent any further runs."""
|
| 908 |
+
resp_json = self._make_request(
|
| 909 |
+
"post",
|
| 910 |
+
f"/tenants/{tenant}/databases/{database}/collections/{input_collection_id}/attached_functions/{name}/detach",
|
| 911 |
+
json={
|
| 912 |
+
"delete_output": delete_output,
|
| 913 |
+
},
|
| 914 |
+
)
|
| 915 |
+
return cast(bool, resp_json["success"])
|
python/user_packages/Python313/site-packages/chromadb/api/functions.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Attachable function definitions for ChromaDB collections.
|
| 2 |
+
|
| 3 |
+
This module provides function constants that can be attached to collections
|
| 4 |
+
to perform automatic computations on collection data.
|
| 5 |
+
|
| 6 |
+
Example:
|
| 7 |
+
>>> from chromadb.api.functions import STATISTICS_FUNCTION
|
| 8 |
+
>>> attached_fn = collection.attach_function(
|
| 9 |
+
... function=STATISTICS_FUNCTION,
|
| 10 |
+
... name="my_stats",
|
| 11 |
+
... output_collection="my_stats_output"
|
| 12 |
+
... )
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from enum import Enum
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Function(str, Enum):
|
| 19 |
+
"""Available functions that can be attached to collections."""
|
| 20 |
+
|
| 21 |
+
STATISTICS = "statistics"
|
| 22 |
+
"""Computes metadata value frequencies for a collection."""
|
| 23 |
+
|
| 24 |
+
RECORD_COUNTER = "record_counter"
|
| 25 |
+
"""Counts records in a collection."""
|
| 26 |
+
|
| 27 |
+
# Used only for failure testing - not a real function
|
| 28 |
+
_NONEXISTENT_TEST_ONLY = "nonexistent_function"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# Convenience aliases for cleaner imports
|
| 32 |
+
STATISTICS_FUNCTION = Function.STATISTICS
|
| 33 |
+
RECORD_COUNTER_FUNCTION = Function.RECORD_COUNTER
|
python/user_packages/Python313/site-packages/chromadb/api/rust.py
ADDED
|
@@ -0,0 +1,704 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from chromadb import (
|
| 4 |
+
CollectionMetadata,
|
| 5 |
+
Embeddings,
|
| 6 |
+
GetResult,
|
| 7 |
+
IDs,
|
| 8 |
+
Where,
|
| 9 |
+
WhereDocument,
|
| 10 |
+
Include,
|
| 11 |
+
Documents,
|
| 12 |
+
Metadatas,
|
| 13 |
+
QueryResult,
|
| 14 |
+
URIs,
|
| 15 |
+
)
|
| 16 |
+
from chromadb.api import ServerAPI
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
from chromadb.api.models.AttachedFunction import AttachedFunction
|
| 20 |
+
from chromadb.api.collection_configuration import (
|
| 21 |
+
CreateCollectionConfiguration,
|
| 22 |
+
UpdateCollectionConfiguration,
|
| 23 |
+
create_collection_configuration_to_json_str,
|
| 24 |
+
update_collection_configuration_to_json_str,
|
| 25 |
+
)
|
| 26 |
+
from chromadb.auth import UserIdentity
|
| 27 |
+
from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System
|
| 28 |
+
from chromadb.telemetry.product import ProductTelemetryClient
|
| 29 |
+
from chromadb.telemetry.product.events import (
|
| 30 |
+
CollectionAddEvent,
|
| 31 |
+
CollectionDeleteEvent,
|
| 32 |
+
CollectionGetEvent,
|
| 33 |
+
CollectionUpdateEvent,
|
| 34 |
+
CollectionQueryEvent,
|
| 35 |
+
ClientCreateCollectionEvent,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
from chromadb.api.types import (
|
| 39 |
+
DeleteResult,
|
| 40 |
+
IncludeMetadataDocuments,
|
| 41 |
+
IncludeMetadataDocumentsDistances,
|
| 42 |
+
IncludeMetadataDocumentsEmbeddings,
|
| 43 |
+
ReadLevel,
|
| 44 |
+
Schema,
|
| 45 |
+
SearchResult,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# TODO(hammadb): Unify imports across types vs root __init__.py
|
| 49 |
+
from chromadb.types import Database, Tenant, Collection as CollectionModel
|
| 50 |
+
from chromadb.execution.expression.plan import Search
|
| 51 |
+
import chromadb_rust_bindings
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
from typing import Optional, Sequence, List, Dict, Any, Tuple
|
| 55 |
+
from overrides import override
|
| 56 |
+
from uuid import UUID
|
| 57 |
+
import json
|
| 58 |
+
import platform
|
| 59 |
+
|
| 60 |
+
if platform.system() != "Windows":
|
| 61 |
+
import resource
|
| 62 |
+
elif platform.system() == "Windows":
|
| 63 |
+
import ctypes
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# RustBindingsAPI is an implementation of ServerAPI which shims
|
| 67 |
+
# the Rust bindings to the Python API, providing a full implementation
|
| 68 |
+
# of the API. It could be that bindings was a direct implementation of
|
| 69 |
+
# ServerAPI, but in order to prevent propagating the bindings types
|
| 70 |
+
# into the Python API, we have to shim it here so we can convert into
|
| 71 |
+
# the legacy Python types.
|
| 72 |
+
# TODO(hammadb): Propagate the types from the bindings into the Python API
|
| 73 |
+
# and remove the python-level types entirely.
|
| 74 |
+
class RustBindingsAPI(ServerAPI):
|
| 75 |
+
bindings: chromadb_rust_bindings.Bindings
|
| 76 |
+
hnsw_cache_size: int
|
| 77 |
+
product_telemetry_client: ProductTelemetryClient
|
| 78 |
+
|
| 79 |
+
def __init__(self, system: System):
|
| 80 |
+
super().__init__(system)
|
| 81 |
+
self.product_telemetry_client = self.require(ProductTelemetryClient)
|
| 82 |
+
|
| 83 |
+
if platform.system() != "Windows":
|
| 84 |
+
max_file_handles = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
|
| 85 |
+
else:
|
| 86 |
+
max_file_handles = ctypes.windll.msvcrt._getmaxstdio() # type: ignore
|
| 87 |
+
self.hnsw_cache_size = (
|
| 88 |
+
max_file_handles
|
| 89 |
+
# This is integer division in Python 3, and not a comment.
|
| 90 |
+
# Each HNSW index has 4 data files and 1 metadata file
|
| 91 |
+
// 5
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
@override
|
| 95 |
+
def start(self) -> None:
|
| 96 |
+
# Construct the SqliteConfig
|
| 97 |
+
# TOOD: We should add a "config converter"
|
| 98 |
+
if self._system.settings.require("is_persistent"):
|
| 99 |
+
persist_path = self._system.settings.require("persist_directory")
|
| 100 |
+
sqlite_persist_path = persist_path + "/chroma.sqlite3"
|
| 101 |
+
else:
|
| 102 |
+
persist_path = None
|
| 103 |
+
sqlite_persist_path = None
|
| 104 |
+
hash_type = self._system.settings.require("migrations_hash_algorithm")
|
| 105 |
+
hash_type_bindings = (
|
| 106 |
+
chromadb_rust_bindings.MigrationHash.MD5
|
| 107 |
+
if hash_type == "md5"
|
| 108 |
+
else chromadb_rust_bindings.MigrationHash.SHA256
|
| 109 |
+
)
|
| 110 |
+
migration_mode = self._system.settings.require("migrations")
|
| 111 |
+
migration_mode_bindings = (
|
| 112 |
+
chromadb_rust_bindings.MigrationMode.Apply
|
| 113 |
+
if migration_mode == "apply"
|
| 114 |
+
else chromadb_rust_bindings.MigrationMode.Validate
|
| 115 |
+
)
|
| 116 |
+
sqlite_config = chromadb_rust_bindings.SqliteDBConfig(
|
| 117 |
+
hash_type=hash_type_bindings,
|
| 118 |
+
migration_mode=migration_mode_bindings,
|
| 119 |
+
url=sqlite_persist_path,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
self.bindings = chromadb_rust_bindings.Bindings(
|
| 123 |
+
allow_reset=self._system.settings.require("allow_reset"),
|
| 124 |
+
sqlite_db_config=sqlite_config,
|
| 125 |
+
persist_path=persist_path,
|
| 126 |
+
hnsw_cache_size=self.hnsw_cache_size,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
@override
|
| 130 |
+
def stop(self) -> None:
|
| 131 |
+
del self.bindings
|
| 132 |
+
|
| 133 |
+
# ////////////////////////////// Admin API //////////////////////////////
|
| 134 |
+
|
| 135 |
+
@override
|
| 136 |
+
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 137 |
+
return self.bindings.create_database(name, tenant)
|
| 138 |
+
|
| 139 |
+
@override
|
| 140 |
+
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
|
| 141 |
+
database = self.bindings.get_database(name, tenant)
|
| 142 |
+
return {
|
| 143 |
+
"id": database.id,
|
| 144 |
+
"name": database.name,
|
| 145 |
+
"tenant": database.tenant,
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
@override
|
| 149 |
+
def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 150 |
+
return self.bindings.delete_database(name, tenant)
|
| 151 |
+
|
| 152 |
+
@override
|
| 153 |
+
def list_databases(
|
| 154 |
+
self,
|
| 155 |
+
limit: Optional[int] = None,
|
| 156 |
+
offset: Optional[int] = None,
|
| 157 |
+
tenant: str = DEFAULT_TENANT,
|
| 158 |
+
) -> Sequence[Database]:
|
| 159 |
+
databases = self.bindings.list_databases(limit, offset, tenant)
|
| 160 |
+
return [
|
| 161 |
+
{
|
| 162 |
+
"id": database.id,
|
| 163 |
+
"name": database.name,
|
| 164 |
+
"tenant": database.tenant,
|
| 165 |
+
}
|
| 166 |
+
for database in databases
|
| 167 |
+
]
|
| 168 |
+
|
| 169 |
+
@override
|
| 170 |
+
def create_tenant(self, name: str) -> None:
|
| 171 |
+
return self.bindings.create_tenant(name)
|
| 172 |
+
|
| 173 |
+
@override
|
| 174 |
+
def get_tenant(self, name: str) -> Tenant:
|
| 175 |
+
tenant = self.bindings.get_tenant(name)
|
| 176 |
+
return Tenant(name=tenant.name)
|
| 177 |
+
|
| 178 |
+
# ////////////////////////////// Base API //////////////////////////////
|
| 179 |
+
|
| 180 |
+
@override
|
| 181 |
+
def heartbeat(self) -> int:
|
| 182 |
+
return self.bindings.heartbeat()
|
| 183 |
+
|
| 184 |
+
@override
|
| 185 |
+
def count_collections(
|
| 186 |
+
self, tenant: str = DEFAULT_TENANT, database: str = DEFAULT_DATABASE
|
| 187 |
+
) -> int:
|
| 188 |
+
return self.bindings.count_collections(tenant, database)
|
| 189 |
+
|
| 190 |
+
@override
|
| 191 |
+
def list_collections(
|
| 192 |
+
self,
|
| 193 |
+
limit: Optional[int] = None,
|
| 194 |
+
offset: Optional[int] = None,
|
| 195 |
+
tenant: str = DEFAULT_TENANT,
|
| 196 |
+
database: str = DEFAULT_DATABASE,
|
| 197 |
+
) -> Sequence[CollectionModel]:
|
| 198 |
+
collections = self.bindings.list_collections(limit, offset, tenant, database)
|
| 199 |
+
return [
|
| 200 |
+
CollectionModel(
|
| 201 |
+
id=collection.id,
|
| 202 |
+
name=collection.name,
|
| 203 |
+
serialized_schema=collection.schema,
|
| 204 |
+
configuration_json=collection.configuration,
|
| 205 |
+
metadata=collection.metadata,
|
| 206 |
+
dimension=collection.dimension,
|
| 207 |
+
tenant=collection.tenant,
|
| 208 |
+
database=collection.database,
|
| 209 |
+
)
|
| 210 |
+
for collection in collections
|
| 211 |
+
]
|
| 212 |
+
|
| 213 |
+
@override
|
| 214 |
+
def create_collection(
|
| 215 |
+
self,
|
| 216 |
+
name: str,
|
| 217 |
+
schema: Optional[Schema] = None,
|
| 218 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 219 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 220 |
+
get_or_create: bool = False,
|
| 221 |
+
tenant: str = DEFAULT_TENANT,
|
| 222 |
+
database: str = DEFAULT_DATABASE,
|
| 223 |
+
) -> CollectionModel:
|
| 224 |
+
# TODO: This event doesn't capture the get_or_create case appropriately
|
| 225 |
+
# TODO: Re-enable embedding function tracking in create_collection
|
| 226 |
+
self.product_telemetry_client.capture(
|
| 227 |
+
ClientCreateCollectionEvent(
|
| 228 |
+
collection_uuid=str(id),
|
| 229 |
+
# embedding_function=embedding_function.__class__.__name__,
|
| 230 |
+
)
|
| 231 |
+
)
|
| 232 |
+
if configuration:
|
| 233 |
+
configuration_json_str = create_collection_configuration_to_json_str(
|
| 234 |
+
configuration, metadata
|
| 235 |
+
)
|
| 236 |
+
else:
|
| 237 |
+
configuration_json_str = None
|
| 238 |
+
|
| 239 |
+
if schema:
|
| 240 |
+
schema_str = json.dumps(schema.serialize_to_json())
|
| 241 |
+
else:
|
| 242 |
+
schema_str = None
|
| 243 |
+
|
| 244 |
+
collection = self.bindings.create_collection(
|
| 245 |
+
name,
|
| 246 |
+
configuration_json_str,
|
| 247 |
+
schema_str,
|
| 248 |
+
metadata,
|
| 249 |
+
get_or_create,
|
| 250 |
+
tenant,
|
| 251 |
+
database,
|
| 252 |
+
)
|
| 253 |
+
collection_model = CollectionModel(
|
| 254 |
+
id=collection.id,
|
| 255 |
+
name=collection.name,
|
| 256 |
+
configuration_json=collection.configuration,
|
| 257 |
+
serialized_schema=collection.schema,
|
| 258 |
+
metadata=collection.metadata,
|
| 259 |
+
dimension=collection.dimension,
|
| 260 |
+
tenant=collection.tenant,
|
| 261 |
+
database=collection.database,
|
| 262 |
+
)
|
| 263 |
+
return collection_model
|
| 264 |
+
|
| 265 |
+
@override
|
| 266 |
+
def get_collection(
|
| 267 |
+
self,
|
| 268 |
+
name: str,
|
| 269 |
+
tenant: str = DEFAULT_TENANT,
|
| 270 |
+
database: str = DEFAULT_DATABASE,
|
| 271 |
+
) -> CollectionModel:
|
| 272 |
+
collection = self.bindings.get_collection(name, tenant, database)
|
| 273 |
+
return CollectionModel(
|
| 274 |
+
id=collection.id,
|
| 275 |
+
name=collection.name,
|
| 276 |
+
configuration_json=collection.configuration,
|
| 277 |
+
serialized_schema=collection.schema,
|
| 278 |
+
metadata=collection.metadata,
|
| 279 |
+
dimension=collection.dimension,
|
| 280 |
+
tenant=collection.tenant,
|
| 281 |
+
database=collection.database,
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
@override
|
| 285 |
+
def get_collection_by_id(
|
| 286 |
+
self,
|
| 287 |
+
collection_id: UUID,
|
| 288 |
+
tenant: str = DEFAULT_TENANT,
|
| 289 |
+
database: str = DEFAULT_DATABASE,
|
| 290 |
+
) -> CollectionModel:
|
| 291 |
+
collection = self.bindings.get_collection_by_id(str(collection_id), tenant, database)
|
| 292 |
+
return CollectionModel(
|
| 293 |
+
id=collection.id,
|
| 294 |
+
name=collection.name,
|
| 295 |
+
configuration_json=collection.configuration,
|
| 296 |
+
serialized_schema=collection.schema,
|
| 297 |
+
metadata=collection.metadata,
|
| 298 |
+
dimension=collection.dimension,
|
| 299 |
+
tenant=collection.tenant,
|
| 300 |
+
database=collection.database,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
@override
|
| 304 |
+
def get_or_create_collection(
|
| 305 |
+
self,
|
| 306 |
+
name: str,
|
| 307 |
+
schema: Optional[Schema] = None,
|
| 308 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 309 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 310 |
+
tenant: str = DEFAULT_TENANT,
|
| 311 |
+
database: str = DEFAULT_DATABASE,
|
| 312 |
+
) -> CollectionModel:
|
| 313 |
+
return self.create_collection(
|
| 314 |
+
name, schema, configuration, metadata, True, tenant, database
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
@override
|
| 318 |
+
def delete_collection(
|
| 319 |
+
self,
|
| 320 |
+
name: str,
|
| 321 |
+
tenant: str = DEFAULT_TENANT,
|
| 322 |
+
database: str = DEFAULT_DATABASE,
|
| 323 |
+
) -> None:
|
| 324 |
+
self.bindings.delete_collection(name, tenant, database)
|
| 325 |
+
|
| 326 |
+
@override
|
| 327 |
+
def _modify(
|
| 328 |
+
self,
|
| 329 |
+
id: UUID,
|
| 330 |
+
new_name: Optional[str] = None,
|
| 331 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 332 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 333 |
+
tenant: str = DEFAULT_TENANT,
|
| 334 |
+
database: str = DEFAULT_DATABASE,
|
| 335 |
+
) -> None:
|
| 336 |
+
if new_configuration:
|
| 337 |
+
new_configuration_json_str = update_collection_configuration_to_json_str(
|
| 338 |
+
new_configuration
|
| 339 |
+
)
|
| 340 |
+
else:
|
| 341 |
+
new_configuration_json_str = None
|
| 342 |
+
self.bindings.update_collection(
|
| 343 |
+
str(id), new_name, new_metadata, new_configuration_json_str
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
@override
|
| 347 |
+
def _fork(
|
| 348 |
+
self,
|
| 349 |
+
collection_id: UUID,
|
| 350 |
+
new_name: str,
|
| 351 |
+
tenant: str = DEFAULT_TENANT,
|
| 352 |
+
database: str = DEFAULT_DATABASE,
|
| 353 |
+
) -> CollectionModel:
|
| 354 |
+
raise NotImplementedError(
|
| 355 |
+
"Collection forking is not implemented for Local Chroma"
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
@override
|
| 359 |
+
def _fork_count(
|
| 360 |
+
self,
|
| 361 |
+
collection_id: UUID,
|
| 362 |
+
tenant: str = DEFAULT_TENANT,
|
| 363 |
+
database: str = DEFAULT_DATABASE,
|
| 364 |
+
) -> int:
|
| 365 |
+
raise NotImplementedError(
|
| 366 |
+
"Fork count is not implemented for Local Chroma"
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
@override
|
| 370 |
+
def _get_indexing_status(
|
| 371 |
+
self,
|
| 372 |
+
collection_id: UUID,
|
| 373 |
+
tenant: str = DEFAULT_TENANT,
|
| 374 |
+
database: str = DEFAULT_DATABASE,
|
| 375 |
+
) -> "IndexingStatus":
|
| 376 |
+
raise NotImplementedError("Indexing status is not implemented for Local Chroma")
|
| 377 |
+
|
| 378 |
+
@override
|
| 379 |
+
def _search(
|
| 380 |
+
self,
|
| 381 |
+
collection_id: UUID,
|
| 382 |
+
searches: List[Search],
|
| 383 |
+
tenant: str = DEFAULT_TENANT,
|
| 384 |
+
database: str = DEFAULT_DATABASE,
|
| 385 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 386 |
+
) -> SearchResult:
|
| 387 |
+
raise NotImplementedError("Search is not implemented for Local Chroma")
|
| 388 |
+
|
| 389 |
+
@override
|
| 390 |
+
def _count(
|
| 391 |
+
self,
|
| 392 |
+
collection_id: UUID,
|
| 393 |
+
tenant: str = DEFAULT_TENANT,
|
| 394 |
+
database: str = DEFAULT_DATABASE,
|
| 395 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 396 |
+
) -> int:
|
| 397 |
+
return self.bindings.count(str(collection_id), tenant, database)
|
| 398 |
+
|
| 399 |
+
@override
|
| 400 |
+
def _peek(
|
| 401 |
+
self,
|
| 402 |
+
collection_id: UUID,
|
| 403 |
+
n: int = 10,
|
| 404 |
+
tenant: str = DEFAULT_TENANT,
|
| 405 |
+
database: str = DEFAULT_DATABASE,
|
| 406 |
+
) -> GetResult:
|
| 407 |
+
return self._get(
|
| 408 |
+
collection_id,
|
| 409 |
+
limit=n,
|
| 410 |
+
tenant=tenant,
|
| 411 |
+
database=database,
|
| 412 |
+
include=IncludeMetadataDocumentsEmbeddings,
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
@override
|
| 416 |
+
def _get(
|
| 417 |
+
self,
|
| 418 |
+
collection_id: UUID,
|
| 419 |
+
ids: Optional[IDs] = None,
|
| 420 |
+
where: Optional[Where] = None,
|
| 421 |
+
limit: Optional[int] = None,
|
| 422 |
+
offset: Optional[int] = None,
|
| 423 |
+
where_document: Optional[WhereDocument] = None,
|
| 424 |
+
include: Include = IncludeMetadataDocuments,
|
| 425 |
+
tenant: str = DEFAULT_TENANT,
|
| 426 |
+
database: str = DEFAULT_DATABASE,
|
| 427 |
+
) -> GetResult:
|
| 428 |
+
ids_amount = len(ids) if ids else 0
|
| 429 |
+
self.product_telemetry_client.capture(
|
| 430 |
+
CollectionGetEvent(
|
| 431 |
+
collection_uuid=str(collection_id),
|
| 432 |
+
ids_count=ids_amount,
|
| 433 |
+
limit=limit if limit else 0,
|
| 434 |
+
include_metadata=ids_amount if "metadatas" in include else 0,
|
| 435 |
+
include_documents=ids_amount if "documents" in include else 0,
|
| 436 |
+
include_uris=ids_amount if "uris" in include else 0,
|
| 437 |
+
)
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
rust_response = self.bindings.get(
|
| 441 |
+
str(collection_id),
|
| 442 |
+
ids,
|
| 443 |
+
json.dumps(where) if where else None,
|
| 444 |
+
limit,
|
| 445 |
+
offset or 0,
|
| 446 |
+
json.dumps(where_document) if where_document else None,
|
| 447 |
+
include,
|
| 448 |
+
tenant,
|
| 449 |
+
database,
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
return GetResult(
|
| 453 |
+
ids=rust_response.ids,
|
| 454 |
+
embeddings=rust_response.embeddings,
|
| 455 |
+
documents=rust_response.documents,
|
| 456 |
+
uris=rust_response.uris,
|
| 457 |
+
included=include,
|
| 458 |
+
data=None,
|
| 459 |
+
metadatas=rust_response.metadatas,
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
@override
|
| 463 |
+
def _add(
|
| 464 |
+
self,
|
| 465 |
+
ids: IDs,
|
| 466 |
+
collection_id: UUID,
|
| 467 |
+
embeddings: Embeddings,
|
| 468 |
+
metadatas: Optional[Metadatas] = None,
|
| 469 |
+
documents: Optional[Documents] = None,
|
| 470 |
+
uris: Optional[URIs] = None,
|
| 471 |
+
tenant: str = DEFAULT_TENANT,
|
| 472 |
+
database: str = DEFAULT_DATABASE,
|
| 473 |
+
) -> bool:
|
| 474 |
+
self.product_telemetry_client.capture(
|
| 475 |
+
CollectionAddEvent(
|
| 476 |
+
collection_uuid=str(collection_id),
|
| 477 |
+
add_amount=len(ids),
|
| 478 |
+
with_metadata=len(ids) if metadatas is not None else 0,
|
| 479 |
+
with_documents=len(ids) if documents is not None else 0,
|
| 480 |
+
with_uris=len(ids) if uris is not None else 0,
|
| 481 |
+
)
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
return self.bindings.add(
|
| 485 |
+
ids,
|
| 486 |
+
str(collection_id),
|
| 487 |
+
embeddings,
|
| 488 |
+
metadatas,
|
| 489 |
+
documents,
|
| 490 |
+
uris,
|
| 491 |
+
tenant,
|
| 492 |
+
database,
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
@override
|
| 496 |
+
def _update(
|
| 497 |
+
self,
|
| 498 |
+
collection_id: UUID,
|
| 499 |
+
ids: IDs,
|
| 500 |
+
embeddings: Optional[Embeddings] = None,
|
| 501 |
+
metadatas: Optional[Metadatas] = None,
|
| 502 |
+
documents: Optional[Documents] = None,
|
| 503 |
+
uris: Optional[URIs] = None,
|
| 504 |
+
tenant: str = DEFAULT_TENANT,
|
| 505 |
+
database: str = DEFAULT_DATABASE,
|
| 506 |
+
) -> bool:
|
| 507 |
+
self.product_telemetry_client.capture(
|
| 508 |
+
CollectionUpdateEvent(
|
| 509 |
+
collection_uuid=str(collection_id),
|
| 510 |
+
update_amount=len(ids),
|
| 511 |
+
with_embeddings=len(embeddings) if embeddings else 0,
|
| 512 |
+
with_metadata=len(metadatas) if metadatas else 0,
|
| 513 |
+
with_documents=len(documents) if documents else 0,
|
| 514 |
+
with_uris=len(uris) if uris else 0,
|
| 515 |
+
)
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
return self.bindings.update(
|
| 519 |
+
str(collection_id),
|
| 520 |
+
ids,
|
| 521 |
+
embeddings,
|
| 522 |
+
metadatas,
|
| 523 |
+
documents,
|
| 524 |
+
uris,
|
| 525 |
+
tenant,
|
| 526 |
+
database,
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
@override
|
| 530 |
+
def _upsert(
|
| 531 |
+
self,
|
| 532 |
+
collection_id: UUID,
|
| 533 |
+
ids: IDs,
|
| 534 |
+
embeddings: Embeddings,
|
| 535 |
+
metadatas: Optional[Metadatas] = None,
|
| 536 |
+
documents: Optional[Documents] = None,
|
| 537 |
+
uris: Optional[URIs] = None,
|
| 538 |
+
tenant: str = DEFAULT_TENANT,
|
| 539 |
+
database: str = DEFAULT_DATABASE,
|
| 540 |
+
) -> bool:
|
| 541 |
+
return self.bindings.upsert(
|
| 542 |
+
str(collection_id),
|
| 543 |
+
ids,
|
| 544 |
+
embeddings,
|
| 545 |
+
metadatas,
|
| 546 |
+
documents,
|
| 547 |
+
uris,
|
| 548 |
+
tenant,
|
| 549 |
+
database,
|
| 550 |
+
)
|
| 551 |
+
|
| 552 |
+
@override
|
| 553 |
+
def _query(
|
| 554 |
+
self,
|
| 555 |
+
collection_id: UUID,
|
| 556 |
+
query_embeddings: Embeddings,
|
| 557 |
+
ids: Optional[IDs] = None,
|
| 558 |
+
n_results: int = 10,
|
| 559 |
+
where: Optional[Where] = None,
|
| 560 |
+
where_document: Optional[WhereDocument] = None,
|
| 561 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 562 |
+
tenant: str = DEFAULT_TENANT,
|
| 563 |
+
database: str = DEFAULT_DATABASE,
|
| 564 |
+
) -> QueryResult:
|
| 565 |
+
query_amount = len(query_embeddings)
|
| 566 |
+
filtered_ids_amount = len(ids) if ids else 0
|
| 567 |
+
self.product_telemetry_client.capture(
|
| 568 |
+
CollectionQueryEvent(
|
| 569 |
+
collection_uuid=str(collection_id),
|
| 570 |
+
query_amount=query_amount,
|
| 571 |
+
filtered_ids_amount=filtered_ids_amount,
|
| 572 |
+
n_results=n_results,
|
| 573 |
+
with_metadata_filter=query_amount if where is not None else 0,
|
| 574 |
+
with_document_filter=query_amount if where_document is not None else 0,
|
| 575 |
+
include_metadatas=query_amount if "metadatas" in include else 0,
|
| 576 |
+
include_documents=query_amount if "documents" in include else 0,
|
| 577 |
+
include_uris=query_amount if "uris" in include else 0,
|
| 578 |
+
include_distances=query_amount if "distances" in include else 0,
|
| 579 |
+
)
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
rust_response = self.bindings.query(
|
| 583 |
+
str(collection_id),
|
| 584 |
+
ids,
|
| 585 |
+
query_embeddings,
|
| 586 |
+
n_results,
|
| 587 |
+
json.dumps(where) if where else None,
|
| 588 |
+
json.dumps(where_document) if where_document else None,
|
| 589 |
+
include,
|
| 590 |
+
tenant,
|
| 591 |
+
database,
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
return QueryResult(
|
| 595 |
+
ids=rust_response.ids,
|
| 596 |
+
embeddings=rust_response.embeddings,
|
| 597 |
+
documents=rust_response.documents,
|
| 598 |
+
uris=rust_response.uris,
|
| 599 |
+
included=include,
|
| 600 |
+
data=None,
|
| 601 |
+
metadatas=rust_response.metadatas,
|
| 602 |
+
distances=rust_response.distances,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
@override
|
| 606 |
+
def _delete(
|
| 607 |
+
self,
|
| 608 |
+
collection_id: UUID,
|
| 609 |
+
ids: Optional[IDs] = None,
|
| 610 |
+
where: Optional[Where] = None,
|
| 611 |
+
where_document: Optional[WhereDocument] = None,
|
| 612 |
+
limit: Optional[int] = None,
|
| 613 |
+
tenant: str = DEFAULT_TENANT,
|
| 614 |
+
database: str = DEFAULT_DATABASE,
|
| 615 |
+
) -> DeleteResult:
|
| 616 |
+
deleted = self.bindings.delete(
|
| 617 |
+
str(collection_id),
|
| 618 |
+
ids,
|
| 619 |
+
json.dumps(where) if where else None,
|
| 620 |
+
json.dumps(where_document) if where_document else None,
|
| 621 |
+
limit,
|
| 622 |
+
tenant,
|
| 623 |
+
database,
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
self.product_telemetry_client.capture(
|
| 627 |
+
CollectionDeleteEvent(
|
| 628 |
+
collection_uuid=str(collection_id),
|
| 629 |
+
delete_amount=deleted,
|
| 630 |
+
)
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
return DeleteResult(deleted=deleted)
|
| 634 |
+
|
| 635 |
+
@override
|
| 636 |
+
def reset(self) -> bool:
|
| 637 |
+
return self.bindings.reset()
|
| 638 |
+
|
| 639 |
+
@override
|
| 640 |
+
def get_version(self) -> str:
|
| 641 |
+
return self.bindings.get_version()
|
| 642 |
+
|
| 643 |
+
@override
|
| 644 |
+
def get_settings(self) -> Settings:
|
| 645 |
+
return self._system.settings
|
| 646 |
+
|
| 647 |
+
@override
|
| 648 |
+
def get_max_batch_size(self) -> int:
|
| 649 |
+
return self.bindings.get_max_batch_size()
|
| 650 |
+
|
| 651 |
+
@override
|
| 652 |
+
def attach_function(
|
| 653 |
+
self,
|
| 654 |
+
function_id: str,
|
| 655 |
+
name: str,
|
| 656 |
+
input_collection_id: UUID,
|
| 657 |
+
output_collection: str,
|
| 658 |
+
params: Optional[Dict[str, Any]] = None,
|
| 659 |
+
tenant: str = DEFAULT_TENANT,
|
| 660 |
+
database: str = DEFAULT_DATABASE,
|
| 661 |
+
) -> Tuple["AttachedFunction", bool]:
|
| 662 |
+
"""Attached functions are not supported in the Rust bindings (local embedded mode)."""
|
| 663 |
+
raise NotImplementedError(
|
| 664 |
+
"Attached functions are only supported when connecting to a Chroma server via HttpClient. "
|
| 665 |
+
"The Rust bindings (embedded mode) do not support attached function operations."
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
@override
|
| 669 |
+
def get_attached_function(
|
| 670 |
+
self,
|
| 671 |
+
name: str,
|
| 672 |
+
input_collection_id: UUID,
|
| 673 |
+
tenant: str = DEFAULT_TENANT,
|
| 674 |
+
database: str = DEFAULT_DATABASE,
|
| 675 |
+
) -> "AttachedFunction":
|
| 676 |
+
"""Attached functions are not supported in the Rust bindings (local embedded mode)."""
|
| 677 |
+
raise NotImplementedError(
|
| 678 |
+
"Attached functions are only supported when connecting to a Chroma server via HttpClient. "
|
| 679 |
+
"The Rust bindings (embedded mode) do not support attached function operations."
|
| 680 |
+
)
|
| 681 |
+
|
| 682 |
+
@override
|
| 683 |
+
def detach_function(
|
| 684 |
+
self,
|
| 685 |
+
name: str,
|
| 686 |
+
input_collection_id: UUID,
|
| 687 |
+
delete_output: bool = False,
|
| 688 |
+
tenant: str = DEFAULT_TENANT,
|
| 689 |
+
database: str = DEFAULT_DATABASE,
|
| 690 |
+
) -> bool:
|
| 691 |
+
"""Attached functions are not supported in the Rust bindings (local embedded mode)."""
|
| 692 |
+
raise NotImplementedError(
|
| 693 |
+
"Attached functions are only supported when connecting to a Chroma server via HttpClient. "
|
| 694 |
+
"The Rust bindings (embedded mode) do not support attached function operations."
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
# TODO: Remove this if it's not planned to be used
|
| 698 |
+
@override
|
| 699 |
+
def get_user_identity(self) -> UserIdentity:
|
| 700 |
+
return UserIdentity(
|
| 701 |
+
user_id="",
|
| 702 |
+
tenant=DEFAULT_TENANT,
|
| 703 |
+
databases=[DEFAULT_DATABASE],
|
| 704 |
+
)
|
python/user_packages/Python313/site-packages/chromadb/api/segment.py
ADDED
|
@@ -0,0 +1,1127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import TYPE_CHECKING
|
| 2 |
+
|
| 3 |
+
from tenacity import retry, stop_after_attempt, retry_if_exception, wait_fixed
|
| 4 |
+
from chromadb.api import ServerAPI
|
| 5 |
+
|
| 6 |
+
if TYPE_CHECKING:
|
| 7 |
+
from chromadb.api.models.AttachedFunction import AttachedFunction
|
| 8 |
+
from chromadb.api.collection_configuration import (
|
| 9 |
+
CreateCollectionConfiguration,
|
| 10 |
+
UpdateCollectionConfiguration,
|
| 11 |
+
create_collection_configuration_to_json,
|
| 12 |
+
)
|
| 13 |
+
from chromadb.auth import UserIdentity
|
| 14 |
+
from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Settings, System
|
| 15 |
+
from chromadb.db.system import SysDB
|
| 16 |
+
from chromadb.quota import QuotaEnforcer, Action
|
| 17 |
+
from chromadb.rate_limit import RateLimitEnforcer
|
| 18 |
+
from chromadb.segment import SegmentManager
|
| 19 |
+
from chromadb.execution.executor.abstract import Executor
|
| 20 |
+
from chromadb.execution.expression.operator import Scan, Filter, Limit, KNN, Projection
|
| 21 |
+
from chromadb.execution.expression.plan import CountPlan, GetPlan, KNNPlan
|
| 22 |
+
from chromadb.telemetry.opentelemetry import (
|
| 23 |
+
add_attributes_to_current_span,
|
| 24 |
+
OpenTelemetryClient,
|
| 25 |
+
OpenTelemetryGranularity,
|
| 26 |
+
trace_method,
|
| 27 |
+
)
|
| 28 |
+
from chromadb.telemetry.product import ProductTelemetryClient
|
| 29 |
+
from chromadb.ingest import Producer
|
| 30 |
+
from chromadb.types import Collection as CollectionModel
|
| 31 |
+
from chromadb import __version__
|
| 32 |
+
from chromadb.errors import (
|
| 33 |
+
InvalidDimensionException,
|
| 34 |
+
NotFoundError,
|
| 35 |
+
VersionMismatchError,
|
| 36 |
+
)
|
| 37 |
+
from chromadb.api.types import (
|
| 38 |
+
CollectionMetadata,
|
| 39 |
+
IDs,
|
| 40 |
+
Embeddings,
|
| 41 |
+
Metadatas,
|
| 42 |
+
Documents,
|
| 43 |
+
ReadLevel,
|
| 44 |
+
Schema,
|
| 45 |
+
URIs,
|
| 46 |
+
Where,
|
| 47 |
+
WhereDocument,
|
| 48 |
+
Include,
|
| 49 |
+
GetResult,
|
| 50 |
+
QueryResult,
|
| 51 |
+
SearchResult,
|
| 52 |
+
validate_metadata,
|
| 53 |
+
validate_update_metadata,
|
| 54 |
+
validate_where,
|
| 55 |
+
validate_where_document,
|
| 56 |
+
validate_batch,
|
| 57 |
+
IncludeMetadataDocuments,
|
| 58 |
+
IncludeMetadataDocumentsDistances,
|
| 59 |
+
DeleteResult,
|
| 60 |
+
)
|
| 61 |
+
from chromadb.telemetry.product.events import (
|
| 62 |
+
CollectionAddEvent,
|
| 63 |
+
CollectionDeleteEvent,
|
| 64 |
+
CollectionGetEvent,
|
| 65 |
+
CollectionUpdateEvent,
|
| 66 |
+
CollectionQueryEvent,
|
| 67 |
+
ClientCreateCollectionEvent,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
import chromadb.types as t
|
| 71 |
+
from typing import (
|
| 72 |
+
Optional,
|
| 73 |
+
Sequence,
|
| 74 |
+
Generator,
|
| 75 |
+
List,
|
| 76 |
+
Any,
|
| 77 |
+
Dict,
|
| 78 |
+
Callable,
|
| 79 |
+
TypeVar,
|
| 80 |
+
Tuple,
|
| 81 |
+
)
|
| 82 |
+
from overrides import override
|
| 83 |
+
from uuid import UUID, uuid4
|
| 84 |
+
from functools import wraps
|
| 85 |
+
import time
|
| 86 |
+
import logging
|
| 87 |
+
import re
|
| 88 |
+
from chromadb.execution.expression.plan import Search
|
| 89 |
+
|
| 90 |
+
T = TypeVar("T", bound=Callable[..., Any])
|
| 91 |
+
|
| 92 |
+
logger = logging.getLogger(__name__)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# mimics s3 bucket requirements for naming
|
| 96 |
+
def check_index_name(index_name: str) -> None:
|
| 97 |
+
msg = (
|
| 98 |
+
"Expected collection name that "
|
| 99 |
+
"(1) contains 3-63 characters, "
|
| 100 |
+
"(2) starts and ends with an alphanumeric character, "
|
| 101 |
+
"(3) otherwise contains only alphanumeric characters, underscores or hyphens (-), "
|
| 102 |
+
"(4) contains no two consecutive periods (..) and "
|
| 103 |
+
"(5) is not a valid IPv4 address, "
|
| 104 |
+
f"got {index_name}"
|
| 105 |
+
)
|
| 106 |
+
if len(index_name) < 3 or len(index_name) > 63:
|
| 107 |
+
raise ValueError(msg)
|
| 108 |
+
if not re.match("^[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9]$", index_name):
|
| 109 |
+
raise ValueError(msg)
|
| 110 |
+
if ".." in index_name:
|
| 111 |
+
raise ValueError(msg)
|
| 112 |
+
if re.match("^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$", index_name):
|
| 113 |
+
raise ValueError(msg)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def rate_limit(func: T) -> T:
|
| 117 |
+
@wraps(func)
|
| 118 |
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
| 119 |
+
self = args[0]
|
| 120 |
+
return self._rate_limit_enforcer.rate_limit(func)(*args, **kwargs)
|
| 121 |
+
|
| 122 |
+
return wrapper # type: ignore
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class SegmentAPI(ServerAPI):
|
| 126 |
+
"""API implementation utilizing the new segment-based internal architecture"""
|
| 127 |
+
|
| 128 |
+
_settings: Settings
|
| 129 |
+
_sysdb: SysDB
|
| 130 |
+
_manager: SegmentManager
|
| 131 |
+
_executor: Executor
|
| 132 |
+
_producer: Producer
|
| 133 |
+
_product_telemetry_client: ProductTelemetryClient
|
| 134 |
+
_opentelemetry_client: OpenTelemetryClient
|
| 135 |
+
_tenant_id: str
|
| 136 |
+
_topic_ns: str
|
| 137 |
+
_rate_limit_enforcer: RateLimitEnforcer
|
| 138 |
+
|
| 139 |
+
def __init__(self, system: System):
|
| 140 |
+
super().__init__(system)
|
| 141 |
+
self._settings = system.settings
|
| 142 |
+
self._sysdb = self.require(SysDB)
|
| 143 |
+
self._manager = self.require(SegmentManager)
|
| 144 |
+
self._executor = self.require(Executor)
|
| 145 |
+
self._quota_enforcer = self.require(QuotaEnforcer)
|
| 146 |
+
self._product_telemetry_client = self.require(ProductTelemetryClient)
|
| 147 |
+
self._opentelemetry_client = self.require(OpenTelemetryClient)
|
| 148 |
+
self._producer = self.require(Producer)
|
| 149 |
+
self._rate_limit_enforcer = self._system.require(RateLimitEnforcer)
|
| 150 |
+
|
| 151 |
+
@override
|
| 152 |
+
def heartbeat(self) -> int:
|
| 153 |
+
return int(time.time_ns())
|
| 154 |
+
|
| 155 |
+
@trace_method("SegmentAPI.create_database", OpenTelemetryGranularity.OPERATION)
|
| 156 |
+
@override
|
| 157 |
+
def create_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 158 |
+
if len(name) < 3:
|
| 159 |
+
raise ValueError("Database name must be at least 3 characters long")
|
| 160 |
+
|
| 161 |
+
self._quota_enforcer.enforce(
|
| 162 |
+
action=Action.CREATE_DATABASE,
|
| 163 |
+
tenant=tenant,
|
| 164 |
+
name=name,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
self._sysdb.create_database(
|
| 168 |
+
id=uuid4(),
|
| 169 |
+
name=name,
|
| 170 |
+
tenant=tenant,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
@trace_method("SegmentAPI.get_database", OpenTelemetryGranularity.OPERATION)
|
| 174 |
+
@override
|
| 175 |
+
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> t.Database:
|
| 176 |
+
return self._sysdb.get_database(name=name, tenant=tenant)
|
| 177 |
+
|
| 178 |
+
@trace_method("SegmentAPI.delete_database", OpenTelemetryGranularity.OPERATION)
|
| 179 |
+
@override
|
| 180 |
+
def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 181 |
+
self._sysdb.delete_database(name=name, tenant=tenant)
|
| 182 |
+
|
| 183 |
+
@trace_method("SegmentAPI.list_databases", OpenTelemetryGranularity.OPERATION)
|
| 184 |
+
@override
|
| 185 |
+
def list_databases(
|
| 186 |
+
self,
|
| 187 |
+
limit: Optional[int] = None,
|
| 188 |
+
offset: Optional[int] = None,
|
| 189 |
+
tenant: str = DEFAULT_TENANT,
|
| 190 |
+
) -> Sequence[t.Database]:
|
| 191 |
+
return self._sysdb.list_databases(limit=limit, offset=offset, tenant=tenant)
|
| 192 |
+
|
| 193 |
+
@trace_method("SegmentAPI.create_tenant", OpenTelemetryGranularity.OPERATION)
|
| 194 |
+
@override
|
| 195 |
+
def create_tenant(self, name: str) -> None:
|
| 196 |
+
if len(name) < 3:
|
| 197 |
+
raise ValueError("Tenant name must be at least 3 characters long")
|
| 198 |
+
|
| 199 |
+
self._sysdb.create_tenant(
|
| 200 |
+
name=name,
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
@override
|
| 204 |
+
def get_user_identity(self) -> UserIdentity:
|
| 205 |
+
return UserIdentity(
|
| 206 |
+
user_id="",
|
| 207 |
+
tenant=DEFAULT_TENANT,
|
| 208 |
+
databases=[DEFAULT_DATABASE],
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
@trace_method("SegmentAPI.get_tenant", OpenTelemetryGranularity.OPERATION)
|
| 212 |
+
@override
|
| 213 |
+
def get_tenant(self, name: str) -> t.Tenant:
|
| 214 |
+
return self._sysdb.get_tenant(name=name)
|
| 215 |
+
|
| 216 |
+
# TODO: Actually fix CollectionMetadata type to remove type: ignore flags. This is
|
| 217 |
+
# necessary because changing the value type from `Any` to`` `Union[str, int, float]`
|
| 218 |
+
# causes the system to somehow convert all values to strings.
|
| 219 |
+
@trace_method("SegmentAPI.create_collection", OpenTelemetryGranularity.OPERATION)
|
| 220 |
+
@override
|
| 221 |
+
@rate_limit
|
| 222 |
+
def create_collection(
|
| 223 |
+
self,
|
| 224 |
+
name: str,
|
| 225 |
+
schema: Optional[Schema] = None,
|
| 226 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 227 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 228 |
+
get_or_create: bool = False,
|
| 229 |
+
tenant: str = DEFAULT_TENANT,
|
| 230 |
+
database: str = DEFAULT_DATABASE,
|
| 231 |
+
) -> CollectionModel:
|
| 232 |
+
if metadata is not None:
|
| 233 |
+
validate_metadata(metadata)
|
| 234 |
+
|
| 235 |
+
# TODO: remove backwards compatibility in naming requirements
|
| 236 |
+
check_index_name(name)
|
| 237 |
+
|
| 238 |
+
self._quota_enforcer.enforce(
|
| 239 |
+
action=Action.CREATE_COLLECTION,
|
| 240 |
+
tenant=tenant,
|
| 241 |
+
name=name,
|
| 242 |
+
metadata=metadata,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
id = uuid4()
|
| 246 |
+
|
| 247 |
+
model = CollectionModel(
|
| 248 |
+
id=id,
|
| 249 |
+
name=name,
|
| 250 |
+
metadata=metadata,
|
| 251 |
+
serialized_schema=None,
|
| 252 |
+
configuration_json=create_collection_configuration_to_json(
|
| 253 |
+
configuration or CreateCollectionConfiguration(), metadata
|
| 254 |
+
),
|
| 255 |
+
tenant=tenant,
|
| 256 |
+
database=database,
|
| 257 |
+
dimension=None,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
# TODO: Let sysdb create the collection directly from the model
|
| 261 |
+
coll, created = self._sysdb.create_collection(
|
| 262 |
+
id=model.id,
|
| 263 |
+
name=model.name,
|
| 264 |
+
schema=schema,
|
| 265 |
+
configuration=configuration or CreateCollectionConfiguration(),
|
| 266 |
+
segments=[], # Passing empty till backend changes are deployed.
|
| 267 |
+
metadata=model.metadata,
|
| 268 |
+
dimension=None, # This is lazily populated on the first add
|
| 269 |
+
get_or_create=get_or_create,
|
| 270 |
+
tenant=tenant,
|
| 271 |
+
database=database,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
if created:
|
| 275 |
+
segments = self._manager.prepare_segments_for_new_collection(coll)
|
| 276 |
+
for segment in segments:
|
| 277 |
+
self._sysdb.create_segment(segment)
|
| 278 |
+
else:
|
| 279 |
+
logger.debug(
|
| 280 |
+
f"Collection {name} already exists, returning existing collection."
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
# TODO: This event doesn't capture the get_or_create case appropriately
|
| 284 |
+
# TODO: Re-enable embedding function tracking in create_collection
|
| 285 |
+
self._product_telemetry_client.capture(
|
| 286 |
+
ClientCreateCollectionEvent(
|
| 287 |
+
collection_uuid=str(id),
|
| 288 |
+
# embedding_function=embedding_function.__class__.__name__,
|
| 289 |
+
)
|
| 290 |
+
)
|
| 291 |
+
add_attributes_to_current_span({"collection_uuid": str(id)})
|
| 292 |
+
|
| 293 |
+
return coll
|
| 294 |
+
|
| 295 |
+
@trace_method(
|
| 296 |
+
"SegmentAPI.get_or_create_collection", OpenTelemetryGranularity.OPERATION
|
| 297 |
+
)
|
| 298 |
+
@override
|
| 299 |
+
@rate_limit
|
| 300 |
+
def get_or_create_collection(
|
| 301 |
+
self,
|
| 302 |
+
name: str,
|
| 303 |
+
schema: Optional[Schema] = None,
|
| 304 |
+
configuration: Optional[CreateCollectionConfiguration] = None,
|
| 305 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 306 |
+
tenant: str = DEFAULT_TENANT,
|
| 307 |
+
database: str = DEFAULT_DATABASE,
|
| 308 |
+
) -> CollectionModel:
|
| 309 |
+
return self.create_collection(
|
| 310 |
+
name=name,
|
| 311 |
+
schema=schema,
|
| 312 |
+
metadata=metadata,
|
| 313 |
+
configuration=configuration,
|
| 314 |
+
get_or_create=True,
|
| 315 |
+
tenant=tenant,
|
| 316 |
+
database=database,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
# TODO: Actually fix CollectionMetadata type to remove type: ignore flags. This is
|
| 320 |
+
# necessary because changing the value type from `Any` to`` `Union[str, int, float]`
|
| 321 |
+
# causes the system to somehow convert all values to strings
|
| 322 |
+
@trace_method("SegmentAPI.get_collection", OpenTelemetryGranularity.OPERATION)
|
| 323 |
+
@override
|
| 324 |
+
@rate_limit
|
| 325 |
+
def get_collection(
|
| 326 |
+
self,
|
| 327 |
+
name: Optional[str] = None,
|
| 328 |
+
tenant: str = DEFAULT_TENANT,
|
| 329 |
+
database: str = DEFAULT_DATABASE,
|
| 330 |
+
) -> CollectionModel:
|
| 331 |
+
existing = self._sysdb.get_collections(
|
| 332 |
+
name=name, tenant=tenant, database=database
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
if existing:
|
| 336 |
+
return existing[0]
|
| 337 |
+
else:
|
| 338 |
+
raise NotFoundError(f"Collection {name} does not exist.")
|
| 339 |
+
|
| 340 |
+
@trace_method("SegmentAPI.get_collection_by_id", OpenTelemetryGranularity.OPERATION)
|
| 341 |
+
@override
|
| 342 |
+
@rate_limit
|
| 343 |
+
def get_collection_by_id(
|
| 344 |
+
self,
|
| 345 |
+
collection_id: UUID,
|
| 346 |
+
tenant: str = DEFAULT_TENANT,
|
| 347 |
+
database: str = DEFAULT_DATABASE,
|
| 348 |
+
) -> CollectionModel:
|
| 349 |
+
existing = self._sysdb.get_collections(
|
| 350 |
+
id=collection_id, tenant=tenant, database=database
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
if existing:
|
| 354 |
+
return existing[0]
|
| 355 |
+
else:
|
| 356 |
+
raise NotFoundError(f"Collection {collection_id} does not exist.")
|
| 357 |
+
|
| 358 |
+
@trace_method("SegmentAPI.list_collection", OpenTelemetryGranularity.OPERATION)
|
| 359 |
+
@override
|
| 360 |
+
@rate_limit
|
| 361 |
+
def list_collections(
|
| 362 |
+
self,
|
| 363 |
+
limit: Optional[int] = None,
|
| 364 |
+
offset: Optional[int] = None,
|
| 365 |
+
tenant: str = DEFAULT_TENANT,
|
| 366 |
+
database: str = DEFAULT_DATABASE,
|
| 367 |
+
) -> Sequence[CollectionModel]:
|
| 368 |
+
self._quota_enforcer.enforce(
|
| 369 |
+
action=Action.LIST_COLLECTIONS,
|
| 370 |
+
tenant=tenant,
|
| 371 |
+
limit=limit,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
return self._sysdb.get_collections(
|
| 375 |
+
limit=limit, offset=offset, tenant=tenant, database=database
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
@trace_method("SegmentAPI.count_collections", OpenTelemetryGranularity.OPERATION)
|
| 379 |
+
@override
|
| 380 |
+
@rate_limit
|
| 381 |
+
def count_collections(
|
| 382 |
+
self,
|
| 383 |
+
tenant: str = DEFAULT_TENANT,
|
| 384 |
+
database: str = DEFAULT_DATABASE,
|
| 385 |
+
) -> int:
|
| 386 |
+
return self._sysdb.count_collections(tenant=tenant, database=database)
|
| 387 |
+
|
| 388 |
+
@trace_method("SegmentAPI._modify", OpenTelemetryGranularity.OPERATION)
|
| 389 |
+
@override
|
| 390 |
+
@rate_limit
|
| 391 |
+
def _modify(
|
| 392 |
+
self,
|
| 393 |
+
id: UUID,
|
| 394 |
+
new_name: Optional[str] = None,
|
| 395 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 396 |
+
new_configuration: Optional[UpdateCollectionConfiguration] = None,
|
| 397 |
+
tenant: str = DEFAULT_TENANT,
|
| 398 |
+
database: str = DEFAULT_DATABASE,
|
| 399 |
+
) -> None:
|
| 400 |
+
if new_name:
|
| 401 |
+
# backwards compatibility in naming requirements (for now)
|
| 402 |
+
check_index_name(new_name)
|
| 403 |
+
|
| 404 |
+
if new_metadata:
|
| 405 |
+
validate_update_metadata(new_metadata)
|
| 406 |
+
|
| 407 |
+
# Ensure the collection exists
|
| 408 |
+
_ = self._get_collection(id)
|
| 409 |
+
|
| 410 |
+
self._quota_enforcer.enforce(
|
| 411 |
+
action=Action.UPDATE_COLLECTION,
|
| 412 |
+
tenant=tenant,
|
| 413 |
+
name=new_name,
|
| 414 |
+
metadata=new_metadata,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
# TODO eventually we'll want to use OptionalArgument and Unspecified in the
|
| 418 |
+
# signature of `_modify` but not changing the API right now.
|
| 419 |
+
if new_name and new_metadata and new_configuration:
|
| 420 |
+
self._sysdb.update_collection(
|
| 421 |
+
id,
|
| 422 |
+
name=new_name,
|
| 423 |
+
metadata=new_metadata,
|
| 424 |
+
configuration=new_configuration,
|
| 425 |
+
)
|
| 426 |
+
elif new_name and new_metadata:
|
| 427 |
+
self._sysdb.update_collection(id, name=new_name, metadata=new_metadata)
|
| 428 |
+
elif new_name and new_configuration:
|
| 429 |
+
self._sysdb.update_collection(
|
| 430 |
+
id, name=new_name, configuration=new_configuration
|
| 431 |
+
)
|
| 432 |
+
elif new_metadata and new_configuration:
|
| 433 |
+
self._sysdb.update_collection(
|
| 434 |
+
id, metadata=new_metadata, configuration=new_configuration
|
| 435 |
+
)
|
| 436 |
+
elif new_name:
|
| 437 |
+
self._sysdb.update_collection(id, name=new_name)
|
| 438 |
+
elif new_metadata:
|
| 439 |
+
self._sysdb.update_collection(id, metadata=new_metadata)
|
| 440 |
+
elif new_configuration:
|
| 441 |
+
self._sysdb.update_collection(id, configuration=new_configuration)
|
| 442 |
+
|
| 443 |
+
@override
|
| 444 |
+
def _fork(
|
| 445 |
+
self,
|
| 446 |
+
collection_id: UUID,
|
| 447 |
+
new_name: str,
|
| 448 |
+
tenant: str = DEFAULT_TENANT,
|
| 449 |
+
database: str = DEFAULT_DATABASE,
|
| 450 |
+
) -> CollectionModel:
|
| 451 |
+
raise NotImplementedError(
|
| 452 |
+
"Collection forking is not implemented for SegmentAPI"
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
@override
|
| 456 |
+
def _fork_count(
|
| 457 |
+
self,
|
| 458 |
+
collection_id: UUID,
|
| 459 |
+
tenant: str = DEFAULT_TENANT,
|
| 460 |
+
database: str = DEFAULT_DATABASE,
|
| 461 |
+
) -> int:
|
| 462 |
+
raise NotImplementedError(
|
| 463 |
+
"Fork count is not implemented for SegmentAPI"
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
@override
|
| 467 |
+
def _get_indexing_status(
|
| 468 |
+
self,
|
| 469 |
+
collection_id: UUID,
|
| 470 |
+
tenant: str = DEFAULT_TENANT,
|
| 471 |
+
database: str = DEFAULT_DATABASE,
|
| 472 |
+
) -> "IndexingStatus":
|
| 473 |
+
raise NotImplementedError("Indexing status is not implemented for SegmentAPI")
|
| 474 |
+
|
| 475 |
+
@override
|
| 476 |
+
def _search(
|
| 477 |
+
self,
|
| 478 |
+
collection_id: UUID,
|
| 479 |
+
searches: List[Search],
|
| 480 |
+
tenant: str = DEFAULT_TENANT,
|
| 481 |
+
database: str = DEFAULT_DATABASE,
|
| 482 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 483 |
+
) -> SearchResult:
|
| 484 |
+
raise NotImplementedError("Search is not implemented for SegmentAPI")
|
| 485 |
+
|
| 486 |
+
@trace_method("SegmentAPI.delete_collection", OpenTelemetryGranularity.OPERATION)
|
| 487 |
+
@override
|
| 488 |
+
@rate_limit
|
| 489 |
+
def delete_collection(
|
| 490 |
+
self,
|
| 491 |
+
name: str,
|
| 492 |
+
tenant: str = DEFAULT_TENANT,
|
| 493 |
+
database: str = DEFAULT_DATABASE,
|
| 494 |
+
) -> None:
|
| 495 |
+
existing = self._sysdb.get_collections(
|
| 496 |
+
name=name, tenant=tenant, database=database
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
if existing:
|
| 500 |
+
self._manager.delete_segments(existing[0].id)
|
| 501 |
+
self._sysdb.delete_collection(
|
| 502 |
+
existing[0].id, tenant=tenant, database=database
|
| 503 |
+
)
|
| 504 |
+
else:
|
| 505 |
+
raise ValueError(f"Collection {name} does not exist.")
|
| 506 |
+
|
| 507 |
+
@trace_method("SegmentAPI._add", OpenTelemetryGranularity.OPERATION)
|
| 508 |
+
@override
|
| 509 |
+
@rate_limit
|
| 510 |
+
def _add(
|
| 511 |
+
self,
|
| 512 |
+
ids: IDs,
|
| 513 |
+
collection_id: UUID,
|
| 514 |
+
embeddings: Embeddings,
|
| 515 |
+
metadatas: Optional[Metadatas] = None,
|
| 516 |
+
documents: Optional[Documents] = None,
|
| 517 |
+
uris: Optional[URIs] = None,
|
| 518 |
+
tenant: str = DEFAULT_TENANT,
|
| 519 |
+
database: str = DEFAULT_DATABASE,
|
| 520 |
+
) -> bool:
|
| 521 |
+
coll = self._get_collection(collection_id)
|
| 522 |
+
self._manager.hint_use_collection(collection_id, t.Operation.ADD)
|
| 523 |
+
validate_batch(
|
| 524 |
+
(ids, embeddings, metadatas, documents, uris),
|
| 525 |
+
{"max_batch_size": self.get_max_batch_size()},
|
| 526 |
+
)
|
| 527 |
+
records_to_submit = list(
|
| 528 |
+
_records(
|
| 529 |
+
t.Operation.ADD,
|
| 530 |
+
ids=ids,
|
| 531 |
+
embeddings=embeddings,
|
| 532 |
+
metadatas=metadatas,
|
| 533 |
+
documents=documents,
|
| 534 |
+
uris=uris,
|
| 535 |
+
)
|
| 536 |
+
)
|
| 537 |
+
self._validate_embedding_record_set(coll, records_to_submit)
|
| 538 |
+
|
| 539 |
+
self._quota_enforcer.enforce(
|
| 540 |
+
action=Action.ADD,
|
| 541 |
+
tenant=tenant,
|
| 542 |
+
ids=ids,
|
| 543 |
+
embeddings=embeddings,
|
| 544 |
+
metadatas=metadatas,
|
| 545 |
+
documents=documents,
|
| 546 |
+
uris=uris,
|
| 547 |
+
collection_id=collection_id,
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
self._producer.submit_embeddings(collection_id, records_to_submit)
|
| 551 |
+
|
| 552 |
+
self._product_telemetry_client.capture(
|
| 553 |
+
CollectionAddEvent(
|
| 554 |
+
collection_uuid=str(collection_id),
|
| 555 |
+
add_amount=len(ids),
|
| 556 |
+
with_metadata=len(ids) if metadatas is not None else 0,
|
| 557 |
+
with_documents=len(ids) if documents is not None else 0,
|
| 558 |
+
with_uris=len(ids) if uris is not None else 0,
|
| 559 |
+
)
|
| 560 |
+
)
|
| 561 |
+
return True
|
| 562 |
+
|
| 563 |
+
@trace_method("SegmentAPI._update", OpenTelemetryGranularity.OPERATION)
|
| 564 |
+
@override
|
| 565 |
+
@rate_limit
|
| 566 |
+
def _update(
|
| 567 |
+
self,
|
| 568 |
+
collection_id: UUID,
|
| 569 |
+
ids: IDs,
|
| 570 |
+
embeddings: Optional[Embeddings] = None,
|
| 571 |
+
metadatas: Optional[Metadatas] = None,
|
| 572 |
+
documents: Optional[Documents] = None,
|
| 573 |
+
uris: Optional[URIs] = None,
|
| 574 |
+
tenant: str = DEFAULT_TENANT,
|
| 575 |
+
database: str = DEFAULT_DATABASE,
|
| 576 |
+
) -> bool:
|
| 577 |
+
coll = self._get_collection(collection_id)
|
| 578 |
+
self._manager.hint_use_collection(collection_id, t.Operation.UPDATE)
|
| 579 |
+
validate_batch(
|
| 580 |
+
(ids, embeddings, metadatas, documents, uris),
|
| 581 |
+
{"max_batch_size": self.get_max_batch_size()},
|
| 582 |
+
)
|
| 583 |
+
records_to_submit = list(
|
| 584 |
+
_records(
|
| 585 |
+
t.Operation.UPDATE,
|
| 586 |
+
ids=ids,
|
| 587 |
+
embeddings=embeddings,
|
| 588 |
+
metadatas=metadatas,
|
| 589 |
+
documents=documents,
|
| 590 |
+
uris=uris,
|
| 591 |
+
)
|
| 592 |
+
)
|
| 593 |
+
self._validate_embedding_record_set(coll, records_to_submit)
|
| 594 |
+
|
| 595 |
+
self._quota_enforcer.enforce(
|
| 596 |
+
action=Action.UPDATE,
|
| 597 |
+
tenant=tenant,
|
| 598 |
+
ids=ids,
|
| 599 |
+
embeddings=embeddings,
|
| 600 |
+
metadatas=metadatas,
|
| 601 |
+
documents=documents,
|
| 602 |
+
uris=uris,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
self._producer.submit_embeddings(collection_id, records_to_submit)
|
| 606 |
+
|
| 607 |
+
self._product_telemetry_client.capture(
|
| 608 |
+
CollectionUpdateEvent(
|
| 609 |
+
collection_uuid=str(collection_id),
|
| 610 |
+
update_amount=len(ids),
|
| 611 |
+
with_embeddings=len(embeddings) if embeddings else 0,
|
| 612 |
+
with_metadata=len(metadatas) if metadatas else 0,
|
| 613 |
+
with_documents=len(documents) if documents else 0,
|
| 614 |
+
with_uris=len(uris) if uris else 0,
|
| 615 |
+
)
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
return True
|
| 619 |
+
|
| 620 |
+
@trace_method("SegmentAPI._upsert", OpenTelemetryGranularity.OPERATION)
|
| 621 |
+
@override
|
| 622 |
+
@rate_limit
|
| 623 |
+
def _upsert(
|
| 624 |
+
self,
|
| 625 |
+
collection_id: UUID,
|
| 626 |
+
ids: IDs,
|
| 627 |
+
embeddings: Embeddings,
|
| 628 |
+
metadatas: Optional[Metadatas] = None,
|
| 629 |
+
documents: Optional[Documents] = None,
|
| 630 |
+
uris: Optional[URIs] = None,
|
| 631 |
+
tenant: str = DEFAULT_TENANT,
|
| 632 |
+
database: str = DEFAULT_DATABASE,
|
| 633 |
+
) -> bool:
|
| 634 |
+
coll = self._get_collection(collection_id)
|
| 635 |
+
self._manager.hint_use_collection(collection_id, t.Operation.UPSERT)
|
| 636 |
+
validate_batch(
|
| 637 |
+
(ids, embeddings, metadatas, documents, uris),
|
| 638 |
+
{"max_batch_size": self.get_max_batch_size()},
|
| 639 |
+
)
|
| 640 |
+
records_to_submit = list(
|
| 641 |
+
_records(
|
| 642 |
+
t.Operation.UPSERT,
|
| 643 |
+
ids=ids,
|
| 644 |
+
embeddings=embeddings,
|
| 645 |
+
metadatas=metadatas,
|
| 646 |
+
documents=documents,
|
| 647 |
+
uris=uris,
|
| 648 |
+
)
|
| 649 |
+
)
|
| 650 |
+
self._validate_embedding_record_set(coll, records_to_submit)
|
| 651 |
+
|
| 652 |
+
self._quota_enforcer.enforce(
|
| 653 |
+
action=Action.UPSERT,
|
| 654 |
+
tenant=tenant,
|
| 655 |
+
ids=ids,
|
| 656 |
+
embeddings=embeddings,
|
| 657 |
+
metadatas=metadatas,
|
| 658 |
+
documents=documents,
|
| 659 |
+
uris=uris,
|
| 660 |
+
collection_id=collection_id,
|
| 661 |
+
)
|
| 662 |
+
|
| 663 |
+
self._producer.submit_embeddings(collection_id, records_to_submit)
|
| 664 |
+
|
| 665 |
+
return True
|
| 666 |
+
|
| 667 |
+
@trace_method("SegmentAPI._get", OpenTelemetryGranularity.OPERATION)
|
| 668 |
+
@retry( # type: ignore[misc]
|
| 669 |
+
retry=retry_if_exception(lambda e: isinstance(e, VersionMismatchError)),
|
| 670 |
+
wait=wait_fixed(2),
|
| 671 |
+
stop=stop_after_attempt(5),
|
| 672 |
+
reraise=True,
|
| 673 |
+
)
|
| 674 |
+
@override
|
| 675 |
+
@rate_limit
|
| 676 |
+
def _get(
|
| 677 |
+
self,
|
| 678 |
+
collection_id: UUID,
|
| 679 |
+
ids: Optional[IDs] = None,
|
| 680 |
+
where: Optional[Where] = None,
|
| 681 |
+
limit: Optional[int] = None,
|
| 682 |
+
offset: Optional[int] = None,
|
| 683 |
+
where_document: Optional[WhereDocument] = None,
|
| 684 |
+
include: Include = IncludeMetadataDocuments,
|
| 685 |
+
tenant: str = DEFAULT_TENANT,
|
| 686 |
+
database: str = DEFAULT_DATABASE,
|
| 687 |
+
) -> GetResult:
|
| 688 |
+
add_attributes_to_current_span(
|
| 689 |
+
{
|
| 690 |
+
"collection_id": str(collection_id),
|
| 691 |
+
"ids_count": len(ids) if ids else 0,
|
| 692 |
+
}
|
| 693 |
+
)
|
| 694 |
+
|
| 695 |
+
scan = self._scan(collection_id)
|
| 696 |
+
|
| 697 |
+
# TODO: Replace with unified validation
|
| 698 |
+
if where is not None:
|
| 699 |
+
validate_where(where)
|
| 700 |
+
|
| 701 |
+
if where_document is not None:
|
| 702 |
+
validate_where_document(where_document)
|
| 703 |
+
|
| 704 |
+
self._quota_enforcer.enforce(
|
| 705 |
+
action=Action.GET,
|
| 706 |
+
tenant=tenant,
|
| 707 |
+
ids=ids,
|
| 708 |
+
where=where,
|
| 709 |
+
where_document=where_document,
|
| 710 |
+
limit=limit,
|
| 711 |
+
)
|
| 712 |
+
|
| 713 |
+
ids_amount = len(ids) if ids else 0
|
| 714 |
+
self._product_telemetry_client.capture(
|
| 715 |
+
CollectionGetEvent(
|
| 716 |
+
collection_uuid=str(collection_id),
|
| 717 |
+
ids_count=ids_amount,
|
| 718 |
+
limit=limit if limit else 0,
|
| 719 |
+
include_metadata=ids_amount if "metadatas" in include else 0,
|
| 720 |
+
include_documents=ids_amount if "documents" in include else 0,
|
| 721 |
+
include_uris=ids_amount if "uris" in include else 0,
|
| 722 |
+
)
|
| 723 |
+
)
|
| 724 |
+
|
| 725 |
+
return self._executor.get(
|
| 726 |
+
GetPlan(
|
| 727 |
+
scan,
|
| 728 |
+
Filter(ids, where, where_document),
|
| 729 |
+
Limit(offset or 0, limit),
|
| 730 |
+
Projection(
|
| 731 |
+
"documents" in include,
|
| 732 |
+
"embeddings" in include,
|
| 733 |
+
"metadatas" in include,
|
| 734 |
+
False,
|
| 735 |
+
"uris" in include,
|
| 736 |
+
),
|
| 737 |
+
)
|
| 738 |
+
)
|
| 739 |
+
|
| 740 |
+
@trace_method("SegmentAPI._delete", OpenTelemetryGranularity.OPERATION)
|
| 741 |
+
@override
|
| 742 |
+
@rate_limit
|
| 743 |
+
def _delete(
|
| 744 |
+
self,
|
| 745 |
+
collection_id: UUID,
|
| 746 |
+
ids: Optional[IDs] = None,
|
| 747 |
+
where: Optional[Where] = None,
|
| 748 |
+
where_document: Optional[WhereDocument] = None,
|
| 749 |
+
limit: Optional[int] = None,
|
| 750 |
+
tenant: str = DEFAULT_TENANT,
|
| 751 |
+
database: str = DEFAULT_DATABASE,
|
| 752 |
+
) -> DeleteResult:
|
| 753 |
+
add_attributes_to_current_span(
|
| 754 |
+
{
|
| 755 |
+
"collection_id": str(collection_id),
|
| 756 |
+
"ids_count": len(ids) if ids else 0,
|
| 757 |
+
}
|
| 758 |
+
)
|
| 759 |
+
|
| 760 |
+
# TODO: Replace with unified validation
|
| 761 |
+
if where is not None:
|
| 762 |
+
validate_where(where)
|
| 763 |
+
|
| 764 |
+
if where_document is not None:
|
| 765 |
+
validate_where_document(where_document)
|
| 766 |
+
|
| 767 |
+
# You must have at least one of non-empty ids, where, or where_document.
|
| 768 |
+
if (
|
| 769 |
+
(ids is None or (ids is not None and len(ids) == 0))
|
| 770 |
+
and (where is None or (where is not None and len(where) == 0))
|
| 771 |
+
and (
|
| 772 |
+
where_document is None
|
| 773 |
+
or (where_document is not None and len(where_document) == 0)
|
| 774 |
+
)
|
| 775 |
+
):
|
| 776 |
+
raise ValueError(
|
| 777 |
+
"""
|
| 778 |
+
You must provide either ids, where, or where_document to delete. If
|
| 779 |
+
you want to delete all data in a collection you can delete the
|
| 780 |
+
collection itself using the delete_collection method. Or alternatively,
|
| 781 |
+
you can get() all the relevant ids and then delete them.
|
| 782 |
+
"""
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
scan = self._scan(collection_id)
|
| 786 |
+
|
| 787 |
+
self._quota_enforcer.enforce(
|
| 788 |
+
action=Action.DELETE,
|
| 789 |
+
tenant=tenant,
|
| 790 |
+
ids=ids,
|
| 791 |
+
where=where,
|
| 792 |
+
where_document=where_document,
|
| 793 |
+
)
|
| 794 |
+
|
| 795 |
+
self._manager.hint_use_collection(collection_id, t.Operation.DELETE)
|
| 796 |
+
|
| 797 |
+
if (where or where_document) or not ids:
|
| 798 |
+
ids_to_delete = self._executor.get(
|
| 799 |
+
GetPlan(scan, Filter(ids, where, where_document))
|
| 800 |
+
)["ids"]
|
| 801 |
+
else:
|
| 802 |
+
ids_to_delete = ids
|
| 803 |
+
|
| 804 |
+
# Apply limit if specified (validated upstream, but enforce defensively)
|
| 805 |
+
if limit is not None:
|
| 806 |
+
if not isinstance(limit, int) or isinstance(limit, bool) or limit < 0:
|
| 807 |
+
raise ValueError("limit must be a non-negative integer")
|
| 808 |
+
if where is None and where_document is None:
|
| 809 |
+
raise ValueError(
|
| 810 |
+
"limit can only be specified when a where or where_document clause is provided"
|
| 811 |
+
)
|
| 812 |
+
ids_to_delete = ids_to_delete[:limit]
|
| 813 |
+
|
| 814 |
+
if len(ids_to_delete) == 0:
|
| 815 |
+
return DeleteResult(deleted=0)
|
| 816 |
+
|
| 817 |
+
records_to_submit = list(
|
| 818 |
+
_records(operation=t.Operation.DELETE, ids=ids_to_delete)
|
| 819 |
+
)
|
| 820 |
+
self._validate_embedding_record_set(scan.collection, records_to_submit)
|
| 821 |
+
self._producer.submit_embeddings(collection_id, records_to_submit)
|
| 822 |
+
|
| 823 |
+
deleted_count = len(ids_to_delete)
|
| 824 |
+
|
| 825 |
+
self._product_telemetry_client.capture(
|
| 826 |
+
CollectionDeleteEvent(
|
| 827 |
+
collection_uuid=str(collection_id), delete_amount=deleted_count
|
| 828 |
+
)
|
| 829 |
+
)
|
| 830 |
+
|
| 831 |
+
return DeleteResult(deleted=deleted_count)
|
| 832 |
+
|
| 833 |
+
@trace_method("SegmentAPI._count", OpenTelemetryGranularity.OPERATION)
|
| 834 |
+
@retry( # type: ignore[misc]
|
| 835 |
+
retry=retry_if_exception(lambda e: isinstance(e, VersionMismatchError)),
|
| 836 |
+
wait=wait_fixed(2),
|
| 837 |
+
stop=stop_after_attempt(5),
|
| 838 |
+
reraise=True,
|
| 839 |
+
)
|
| 840 |
+
@override
|
| 841 |
+
@rate_limit
|
| 842 |
+
def _count(
|
| 843 |
+
self,
|
| 844 |
+
collection_id: UUID,
|
| 845 |
+
tenant: str = DEFAULT_TENANT,
|
| 846 |
+
database: str = DEFAULT_DATABASE,
|
| 847 |
+
read_level: ReadLevel = ReadLevel.INDEX_AND_WAL,
|
| 848 |
+
) -> int:
|
| 849 |
+
add_attributes_to_current_span({"collection_id": str(collection_id)})
|
| 850 |
+
return self._executor.count(CountPlan(self._scan(collection_id)))
|
| 851 |
+
|
| 852 |
+
@trace_method("SegmentAPI._query", OpenTelemetryGranularity.OPERATION)
|
| 853 |
+
# We retry on version mismatch errors because the version of the collection
|
| 854 |
+
# may have changed between the time we got the version and the time we
|
| 855 |
+
# actually query the collection on the FE. We are fine with fixed
|
| 856 |
+
# wait time because the version mismatch error is not a error due to
|
| 857 |
+
# network issues or other transient issues. It is a result of the
|
| 858 |
+
# collection being updated between the time we got the version and
|
| 859 |
+
# the time we actually query the collection on the FE.
|
| 860 |
+
@retry( # type: ignore[misc]
|
| 861 |
+
retry=retry_if_exception(lambda e: isinstance(e, VersionMismatchError)),
|
| 862 |
+
wait=wait_fixed(2),
|
| 863 |
+
stop=stop_after_attempt(5),
|
| 864 |
+
reraise=True,
|
| 865 |
+
)
|
| 866 |
+
@override
|
| 867 |
+
@rate_limit
|
| 868 |
+
def _query(
|
| 869 |
+
self,
|
| 870 |
+
collection_id: UUID,
|
| 871 |
+
query_embeddings: Embeddings,
|
| 872 |
+
ids: Optional[IDs] = None,
|
| 873 |
+
n_results: int = 10,
|
| 874 |
+
where: Optional[Where] = None,
|
| 875 |
+
where_document: Optional[WhereDocument] = None,
|
| 876 |
+
include: Include = IncludeMetadataDocumentsDistances,
|
| 877 |
+
tenant: str = DEFAULT_TENANT,
|
| 878 |
+
database: str = DEFAULT_DATABASE,
|
| 879 |
+
) -> QueryResult:
|
| 880 |
+
add_attributes_to_current_span(
|
| 881 |
+
{
|
| 882 |
+
"collection_id": str(collection_id),
|
| 883 |
+
"n_results": n_results,
|
| 884 |
+
"where": str(where),
|
| 885 |
+
}
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
query_amount = len(query_embeddings)
|
| 889 |
+
ids_amount = len(ids) if ids else 0
|
| 890 |
+
self._product_telemetry_client.capture(
|
| 891 |
+
CollectionQueryEvent(
|
| 892 |
+
collection_uuid=str(collection_id),
|
| 893 |
+
query_amount=query_amount,
|
| 894 |
+
filtered_ids_amount=ids_amount,
|
| 895 |
+
n_results=n_results,
|
| 896 |
+
with_metadata_filter=query_amount if where is not None else 0,
|
| 897 |
+
with_document_filter=query_amount if where_document is not None else 0,
|
| 898 |
+
include_metadatas=query_amount if "metadatas" in include else 0,
|
| 899 |
+
include_documents=query_amount if "documents" in include else 0,
|
| 900 |
+
include_uris=query_amount if "uris" in include else 0,
|
| 901 |
+
include_distances=query_amount if "distances" in include else 0,
|
| 902 |
+
)
|
| 903 |
+
)
|
| 904 |
+
|
| 905 |
+
# TODO: Replace with unified validation
|
| 906 |
+
if where is not None:
|
| 907 |
+
validate_where(where)
|
| 908 |
+
if where_document is not None:
|
| 909 |
+
validate_where_document(where_document)
|
| 910 |
+
|
| 911 |
+
scan = self._scan(collection_id)
|
| 912 |
+
for embedding in query_embeddings:
|
| 913 |
+
self._validate_dimension(scan.collection, len(embedding), update=False)
|
| 914 |
+
|
| 915 |
+
self._quota_enforcer.enforce(
|
| 916 |
+
action=Action.QUERY,
|
| 917 |
+
tenant=tenant,
|
| 918 |
+
where=where,
|
| 919 |
+
where_document=where_document,
|
| 920 |
+
query_embeddings=query_embeddings,
|
| 921 |
+
n_results=n_results,
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
return self._executor.knn(
|
| 925 |
+
KNNPlan(
|
| 926 |
+
scan,
|
| 927 |
+
KNN(query_embeddings, n_results),
|
| 928 |
+
Filter(None, where, where_document),
|
| 929 |
+
Projection(
|
| 930 |
+
"documents" in include,
|
| 931 |
+
"embeddings" in include,
|
| 932 |
+
"metadatas" in include,
|
| 933 |
+
"distances" in include,
|
| 934 |
+
"uris" in include,
|
| 935 |
+
),
|
| 936 |
+
)
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
@trace_method("SegmentAPI._peek", OpenTelemetryGranularity.OPERATION)
|
| 940 |
+
@override
|
| 941 |
+
@rate_limit
|
| 942 |
+
def _peek(
|
| 943 |
+
self,
|
| 944 |
+
collection_id: UUID,
|
| 945 |
+
n: int = 10,
|
| 946 |
+
tenant: str = DEFAULT_TENANT,
|
| 947 |
+
database: str = DEFAULT_DATABASE,
|
| 948 |
+
) -> GetResult:
|
| 949 |
+
add_attributes_to_current_span({"collection_id": str(collection_id)})
|
| 950 |
+
return self._get(collection_id, limit=n) # type: ignore
|
| 951 |
+
|
| 952 |
+
@override
|
| 953 |
+
def get_version(self) -> str:
|
| 954 |
+
return __version__
|
| 955 |
+
|
| 956 |
+
@override
|
| 957 |
+
def reset_state(self) -> None:
|
| 958 |
+
pass
|
| 959 |
+
|
| 960 |
+
@override
|
| 961 |
+
def reset(self) -> bool:
|
| 962 |
+
self._system.reset_state()
|
| 963 |
+
return True
|
| 964 |
+
|
| 965 |
+
@override
|
| 966 |
+
def get_settings(self) -> Settings:
|
| 967 |
+
return self._settings
|
| 968 |
+
|
| 969 |
+
@override
|
| 970 |
+
def get_max_batch_size(self) -> int:
|
| 971 |
+
return self._producer.max_batch_size
|
| 972 |
+
|
| 973 |
+
@override
|
| 974 |
+
def attach_function(
|
| 975 |
+
self,
|
| 976 |
+
function_id: str,
|
| 977 |
+
name: str,
|
| 978 |
+
input_collection_id: UUID,
|
| 979 |
+
output_collection: str,
|
| 980 |
+
params: Optional[Dict[str, Any]] = None,
|
| 981 |
+
tenant: str = DEFAULT_TENANT,
|
| 982 |
+
database: str = DEFAULT_DATABASE,
|
| 983 |
+
) -> Tuple["AttachedFunction", bool]:
|
| 984 |
+
"""Attached functions are not supported in the Segment API (local embedded mode)."""
|
| 985 |
+
raise NotImplementedError(
|
| 986 |
+
"Attached functions are only supported when connecting to a Chroma server via HttpClient. "
|
| 987 |
+
"The Segment API (embedded mode) does not support attached function operations."
|
| 988 |
+
)
|
| 989 |
+
|
| 990 |
+
@override
|
| 991 |
+
def get_attached_function(
|
| 992 |
+
self,
|
| 993 |
+
name: str,
|
| 994 |
+
input_collection_id: UUID,
|
| 995 |
+
tenant: str = DEFAULT_TENANT,
|
| 996 |
+
database: str = DEFAULT_DATABASE,
|
| 997 |
+
) -> "AttachedFunction":
|
| 998 |
+
"""Attached functions are not supported in the Segment API (local embedded mode)."""
|
| 999 |
+
raise NotImplementedError(
|
| 1000 |
+
"Attached functions are only supported when connecting to a Chroma server via HttpClient. "
|
| 1001 |
+
"The Segment API (embedded mode) does not support attached function operations."
|
| 1002 |
+
)
|
| 1003 |
+
|
| 1004 |
+
@override
|
| 1005 |
+
def detach_function(
|
| 1006 |
+
self,
|
| 1007 |
+
name: str,
|
| 1008 |
+
input_collection_id: UUID,
|
| 1009 |
+
delete_output: bool = False,
|
| 1010 |
+
tenant: str = DEFAULT_TENANT,
|
| 1011 |
+
database: str = DEFAULT_DATABASE,
|
| 1012 |
+
) -> bool:
|
| 1013 |
+
"""Attached functions are not supported in the Segment API (local embedded mode)."""
|
| 1014 |
+
raise NotImplementedError(
|
| 1015 |
+
"Attached functions are only supported when connecting to a Chroma server via HttpClient. "
|
| 1016 |
+
"The Segment API (embedded mode) does not support attached function operations."
|
| 1017 |
+
)
|
| 1018 |
+
|
| 1019 |
+
# TODO: This could potentially cause race conditions in a distributed version of the
|
| 1020 |
+
# system, since the cache is only local.
|
| 1021 |
+
# TODO: promote collection -> topic to a base class method so that it can be
|
| 1022 |
+
# used for channel assignment in the distributed version of the system.
|
| 1023 |
+
@trace_method(
|
| 1024 |
+
"SegmentAPI._validate_embedding_record_set", OpenTelemetryGranularity.ALL
|
| 1025 |
+
)
|
| 1026 |
+
def _validate_embedding_record_set(
|
| 1027 |
+
self, collection: t.Collection, records: List[t.OperationRecord]
|
| 1028 |
+
) -> None:
|
| 1029 |
+
"""Validate the dimension of an embedding record before submitting it to the system."""
|
| 1030 |
+
add_attributes_to_current_span({"collection_id": str(collection["id"])})
|
| 1031 |
+
for record in records:
|
| 1032 |
+
if record["embedding"] is not None:
|
| 1033 |
+
self._validate_dimension(
|
| 1034 |
+
collection, len(record["embedding"]), update=True
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
# This method is intentionally left untraced because otherwise it can emit thousands of spans for requests containing many embeddings.
|
| 1038 |
+
def _validate_dimension(
|
| 1039 |
+
self, collection: t.Collection, dim: int, update: bool
|
| 1040 |
+
) -> None:
|
| 1041 |
+
"""Validate that a collection supports records of the given dimension. If update
|
| 1042 |
+
is true, update the collection if the collection doesn't already have a
|
| 1043 |
+
dimension."""
|
| 1044 |
+
if collection["dimension"] is None:
|
| 1045 |
+
if update:
|
| 1046 |
+
id = collection.id
|
| 1047 |
+
self._sysdb.update_collection(id=id, dimension=dim)
|
| 1048 |
+
collection["dimension"] = dim
|
| 1049 |
+
elif collection["dimension"] != dim:
|
| 1050 |
+
raise InvalidDimensionException(
|
| 1051 |
+
f"Embedding dimension {dim} does not match collection dimensionality {collection['dimension']}"
|
| 1052 |
+
)
|
| 1053 |
+
else:
|
| 1054 |
+
return # all is well
|
| 1055 |
+
|
| 1056 |
+
@trace_method("SegmentAPI._get_collection", OpenTelemetryGranularity.ALL)
|
| 1057 |
+
def _get_collection(self, collection_id: UUID) -> t.Collection:
|
| 1058 |
+
collections = self._sysdb.get_collections(id=collection_id)
|
| 1059 |
+
if not collections or len(collections) == 0:
|
| 1060 |
+
raise NotFoundError(f"Collection {collection_id} does not exist.")
|
| 1061 |
+
return collections[0]
|
| 1062 |
+
|
| 1063 |
+
@trace_method("SegmentAPI._scan", OpenTelemetryGranularity.OPERATION)
|
| 1064 |
+
def _scan(self, collection_id: UUID) -> Scan:
|
| 1065 |
+
collection_and_segments = self._sysdb.get_collection_with_segments(
|
| 1066 |
+
collection_id
|
| 1067 |
+
)
|
| 1068 |
+
# For now collection should have exactly one segment per scope:
|
| 1069 |
+
# - Local scopes: vector, metadata
|
| 1070 |
+
# - Distributed scopes: vector, metadata, record
|
| 1071 |
+
scope_to_segment = {
|
| 1072 |
+
segment["scope"]: segment for segment in collection_and_segments["segments"]
|
| 1073 |
+
}
|
| 1074 |
+
return Scan(
|
| 1075 |
+
collection=collection_and_segments["collection"],
|
| 1076 |
+
knn=scope_to_segment[t.SegmentScope.VECTOR],
|
| 1077 |
+
metadata=scope_to_segment[t.SegmentScope.METADATA],
|
| 1078 |
+
# Local chroma do not have record segment, and this is not used by the local executor
|
| 1079 |
+
record=scope_to_segment.get(t.SegmentScope.RECORD, None), # type: ignore[arg-type]
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
|
| 1083 |
+
def _records(
|
| 1084 |
+
operation: t.Operation,
|
| 1085 |
+
ids: IDs,
|
| 1086 |
+
embeddings: Optional[Embeddings] = None,
|
| 1087 |
+
metadatas: Optional[Metadatas] = None,
|
| 1088 |
+
documents: Optional[Documents] = None,
|
| 1089 |
+
uris: Optional[URIs] = None,
|
| 1090 |
+
) -> Generator[t.OperationRecord, None, None]:
|
| 1091 |
+
"""Convert parallel lists of embeddings, metadatas and documents to a sequence of
|
| 1092 |
+
SubmitEmbeddingRecords"""
|
| 1093 |
+
|
| 1094 |
+
# Presumes that callers were invoked via Collection model, which means
|
| 1095 |
+
# that we know that the embeddings, metadatas and documents have already been
|
| 1096 |
+
# normalized and are guaranteed to be consistently named lists.
|
| 1097 |
+
|
| 1098 |
+
if embeddings == []:
|
| 1099 |
+
embeddings = None
|
| 1100 |
+
|
| 1101 |
+
for i, id in enumerate(ids):
|
| 1102 |
+
metadata = None
|
| 1103 |
+
if metadatas:
|
| 1104 |
+
metadata = metadatas[i]
|
| 1105 |
+
|
| 1106 |
+
if documents:
|
| 1107 |
+
document = documents[i]
|
| 1108 |
+
if metadata:
|
| 1109 |
+
metadata = {**metadata, "chroma:document": document}
|
| 1110 |
+
else:
|
| 1111 |
+
metadata = {"chroma:document": document}
|
| 1112 |
+
|
| 1113 |
+
if uris:
|
| 1114 |
+
uri = uris[i]
|
| 1115 |
+
if metadata:
|
| 1116 |
+
metadata = {**metadata, "chroma:uri": uri}
|
| 1117 |
+
else:
|
| 1118 |
+
metadata = {"chroma:uri": uri}
|
| 1119 |
+
|
| 1120 |
+
record = t.OperationRecord(
|
| 1121 |
+
id=id,
|
| 1122 |
+
embedding=embeddings[i] if embeddings is not None else None,
|
| 1123 |
+
encoding=t.ScalarEncoding.FLOAT32, # Hardcode for now
|
| 1124 |
+
metadata=metadata,
|
| 1125 |
+
operation=operation,
|
| 1126 |
+
)
|
| 1127 |
+
yield record
|
python/user_packages/Python313/site-packages/chromadb/api/shared_system_client.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import ClassVar, Dict, Optional
|
| 2 |
+
import logging
|
| 3 |
+
import threading
|
| 4 |
+
import uuid
|
| 5 |
+
from chromadb.api import ServerAPI
|
| 6 |
+
from chromadb.api.base_http_client import BaseHTTPClient
|
| 7 |
+
from chromadb.config import Settings, System
|
| 8 |
+
from chromadb.telemetry.product import ProductTelemetryClient
|
| 9 |
+
from chromadb.telemetry.product.events import ClientStartEvent
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class SharedSystemClient:
|
| 15 |
+
_identifier_to_system: ClassVar[Dict[str, System]] = {}
|
| 16 |
+
_identifier_to_refcount: ClassVar[Dict[str, int]] = {}
|
| 17 |
+
_refcount_lock: ClassVar[threading.Lock] = threading.Lock()
|
| 18 |
+
_identifier: str
|
| 19 |
+
|
| 20 |
+
def __init__(
|
| 21 |
+
self,
|
| 22 |
+
settings: Settings = Settings(),
|
| 23 |
+
) -> None:
|
| 24 |
+
self._identifier = SharedSystemClient._get_identifier_from_settings(settings)
|
| 25 |
+
SharedSystemClient._create_system_if_not_exists(self._identifier, settings)
|
| 26 |
+
SharedSystemClient._increment_refcount(self._identifier)
|
| 27 |
+
|
| 28 |
+
@classmethod
|
| 29 |
+
def _create_system_if_not_exists(
|
| 30 |
+
cls, identifier: str, settings: Settings
|
| 31 |
+
) -> System:
|
| 32 |
+
if identifier not in cls._identifier_to_system:
|
| 33 |
+
new_system = System(settings)
|
| 34 |
+
cls._identifier_to_system[identifier] = new_system
|
| 35 |
+
|
| 36 |
+
new_system.instance(ProductTelemetryClient)
|
| 37 |
+
new_system.instance(ServerAPI)
|
| 38 |
+
|
| 39 |
+
new_system.start()
|
| 40 |
+
else:
|
| 41 |
+
previous_system = cls._identifier_to_system[identifier]
|
| 42 |
+
|
| 43 |
+
# For now, the settings must match
|
| 44 |
+
if previous_system.settings != settings:
|
| 45 |
+
raise ValueError(
|
| 46 |
+
f"An instance of Chroma already exists for {identifier} with different settings"
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
return cls._identifier_to_system[identifier]
|
| 50 |
+
|
| 51 |
+
@staticmethod
|
| 52 |
+
def _get_identifier_from_settings(settings: Settings) -> str:
|
| 53 |
+
identifier = ""
|
| 54 |
+
api_impl = settings.chroma_api_impl
|
| 55 |
+
|
| 56 |
+
if api_impl is None:
|
| 57 |
+
raise ValueError("Chroma API implementation must be set in settings")
|
| 58 |
+
elif api_impl in [
|
| 59 |
+
"chromadb.api.segment.SegmentAPI",
|
| 60 |
+
"chromadb.api.rust.RustBindingsAPI",
|
| 61 |
+
]:
|
| 62 |
+
if settings.is_persistent:
|
| 63 |
+
identifier = settings.persist_directory
|
| 64 |
+
else:
|
| 65 |
+
identifier = (
|
| 66 |
+
"ephemeral" # TODO: support pathing and multiple ephemeral clients
|
| 67 |
+
)
|
| 68 |
+
elif api_impl in [
|
| 69 |
+
"chromadb.api.fastapi.FastAPI",
|
| 70 |
+
"chromadb.api.async_fastapi.AsyncFastAPI",
|
| 71 |
+
]:
|
| 72 |
+
# FastAPI clients can all use unique system identifiers since their configurations can be independent, e.g. different auth tokens
|
| 73 |
+
identifier = str(uuid.uuid4())
|
| 74 |
+
else:
|
| 75 |
+
raise ValueError(f"Unsupported Chroma API implementation {api_impl}")
|
| 76 |
+
|
| 77 |
+
return identifier
|
| 78 |
+
|
| 79 |
+
@staticmethod
|
| 80 |
+
def _populate_data_from_system(system: System) -> str:
|
| 81 |
+
identifier = SharedSystemClient._get_identifier_from_settings(system.settings)
|
| 82 |
+
SharedSystemClient._identifier_to_system[identifier] = system
|
| 83 |
+
return identifier
|
| 84 |
+
|
| 85 |
+
@classmethod
|
| 86 |
+
def from_system(cls, system: System) -> "SharedSystemClient":
|
| 87 |
+
"""Create a client from an existing system. This is useful for testing and debugging."""
|
| 88 |
+
|
| 89 |
+
SharedSystemClient._populate_data_from_system(system)
|
| 90 |
+
instance = cls(system.settings)
|
| 91 |
+
return instance
|
| 92 |
+
|
| 93 |
+
@classmethod
|
| 94 |
+
def _increment_refcount(cls, identifier: str) -> None:
|
| 95 |
+
"""Increment the reference count for a system identifier."""
|
| 96 |
+
with cls._refcount_lock:
|
| 97 |
+
if identifier not in cls._identifier_to_refcount:
|
| 98 |
+
cls._identifier_to_refcount[identifier] = 0
|
| 99 |
+
cls._identifier_to_refcount[identifier] += 1
|
| 100 |
+
|
| 101 |
+
@classmethod
|
| 102 |
+
def _decrement_refcount(cls, identifier: str) -> int:
|
| 103 |
+
"""Decrement the reference count for a system identifier and return the new count."""
|
| 104 |
+
with cls._refcount_lock:
|
| 105 |
+
if identifier in cls._identifier_to_refcount:
|
| 106 |
+
cls._identifier_to_refcount[identifier] -= 1
|
| 107 |
+
count = cls._identifier_to_refcount[identifier]
|
| 108 |
+
if count <= 0:
|
| 109 |
+
del cls._identifier_to_refcount[identifier]
|
| 110 |
+
return count
|
| 111 |
+
return 0
|
| 112 |
+
|
| 113 |
+
@classmethod
|
| 114 |
+
def _release_system(cls, identifier: str) -> None:
|
| 115 |
+
"""Decrement refcount and stop the system if this was the last reference.
|
| 116 |
+
|
| 117 |
+
This consolidates the "decrement + conditional stop" pattern used in
|
| 118 |
+
both Client.close() and the Client.__init__ exception handler.
|
| 119 |
+
"""
|
| 120 |
+
refcount = cls._decrement_refcount(identifier)
|
| 121 |
+
if refcount <= 0:
|
| 122 |
+
system = cls._identifier_to_system.pop(identifier, None)
|
| 123 |
+
if system is not None:
|
| 124 |
+
system.stop()
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def clear_system_cache() -> None:
|
| 128 |
+
SharedSystemClient._identifier_to_system = {}
|
| 129 |
+
SharedSystemClient._identifier_to_refcount = {}
|
| 130 |
+
|
| 131 |
+
@property
|
| 132 |
+
def _system(self) -> System:
|
| 133 |
+
return SharedSystemClient._identifier_to_system[self._identifier]
|
| 134 |
+
|
| 135 |
+
def _submit_client_start_event(self) -> None:
|
| 136 |
+
telemetry_client = self._system.instance(ProductTelemetryClient)
|
| 137 |
+
telemetry_client.capture(ClientStartEvent())
|
| 138 |
+
|
| 139 |
+
@staticmethod
|
| 140 |
+
def get_chroma_cloud_api_key_from_clients() -> Optional[str]:
|
| 141 |
+
"""
|
| 142 |
+
Try to extract api key from existing client instances by checking httpx session headers.
|
| 143 |
+
|
| 144 |
+
Requirements to pull api key:
|
| 145 |
+
- must be a BaseHTTPClient instance (ignore RustBindingsAPI and SegmentAPI)
|
| 146 |
+
- must have "api.trychroma.com" or "gcp.trychroma.com" in the _api_url (ignore local/self-hosted instances)
|
| 147 |
+
- must have "x-chroma-token" or "X-Chroma-Token" in the headers
|
| 148 |
+
|
| 149 |
+
Returns:
|
| 150 |
+
The first api key found, or None if no client instances have api keys set.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
api_keys: list[str] = []
|
| 154 |
+
systems_snapshot = list(SharedSystemClient._identifier_to_system.values())
|
| 155 |
+
for system in systems_snapshot:
|
| 156 |
+
try:
|
| 157 |
+
server_api = system.instance(ServerAPI)
|
| 158 |
+
|
| 159 |
+
if not isinstance(server_api, BaseHTTPClient):
|
| 160 |
+
# RustBindingsAPI and SegmentAPI don't have HTTP headers
|
| 161 |
+
continue
|
| 162 |
+
|
| 163 |
+
# Only pull api key if the url contains the chroma cloud url
|
| 164 |
+
api_url = server_api.get_api_url()
|
| 165 |
+
if (
|
| 166 |
+
"api.trychroma.com" not in api_url
|
| 167 |
+
and "gcp.trychroma.com" not in api_url
|
| 168 |
+
):
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
headers = server_api.get_request_headers()
|
| 172 |
+
api_key = None
|
| 173 |
+
for key, value in headers.items():
|
| 174 |
+
if key.lower() == "x-chroma-token":
|
| 175 |
+
api_key = value
|
| 176 |
+
break
|
| 177 |
+
|
| 178 |
+
if api_key:
|
| 179 |
+
api_keys.append(api_key)
|
| 180 |
+
except Exception:
|
| 181 |
+
# If we can't access the ServerAPI instance, continue to the next
|
| 182 |
+
continue
|
| 183 |
+
|
| 184 |
+
if not api_keys:
|
| 185 |
+
return None
|
| 186 |
+
|
| 187 |
+
# log if multiple viable api keys found
|
| 188 |
+
if len(api_keys) > 1:
|
| 189 |
+
logger.info(
|
| 190 |
+
f"Multiple Chroma Cloud clients found, using API key starting with {api_keys[0][:8]}..."
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
return api_keys[0]
|
python/user_packages/Python313/site-packages/chromadb/api/types.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
python/user_packages/Python313/site-packages/chromadb/auth/__init__.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from abc import abstractmethod
|
| 4 |
+
from enum import Enum
|
| 5 |
+
from typing import (
|
| 6 |
+
Any,
|
| 7 |
+
List,
|
| 8 |
+
Optional,
|
| 9 |
+
Dict,
|
| 10 |
+
Tuple,
|
| 11 |
+
TypeVar,
|
| 12 |
+
)
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
|
| 15 |
+
from pydantic import SecretStr
|
| 16 |
+
|
| 17 |
+
from chromadb.config import (
|
| 18 |
+
Component,
|
| 19 |
+
System,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
T = TypeVar("T")
|
| 23 |
+
S = TypeVar("S")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class AuthError(Exception):
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
ClientAuthHeaders = Dict[str, SecretStr]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ClientAuthProvider(Component):
|
| 34 |
+
"""
|
| 35 |
+
ClientAuthProvider is responsible for providing authentication headers for
|
| 36 |
+
client requests. Client implementations (in our case, just the FastAPI
|
| 37 |
+
client) must inject these headers into their requests.
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, system: System) -> None:
|
| 41 |
+
super().__init__(system)
|
| 42 |
+
|
| 43 |
+
@abstractmethod
|
| 44 |
+
def authenticate(self) -> ClientAuthHeaders:
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass
|
| 49 |
+
class UserIdentity:
|
| 50 |
+
"""
|
| 51 |
+
UserIdentity represents the identity of a user. In general, not all fields
|
| 52 |
+
will be populated, and the fields that are populated will depend on the
|
| 53 |
+
authentication provider.
|
| 54 |
+
|
| 55 |
+
The idea is that the AuthenticationProvider is responsible for populating
|
| 56 |
+
_all_ information known about the user, and the AuthorizationProvider is
|
| 57 |
+
responsible for making decisions based on that information.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
user_id: str
|
| 61 |
+
tenant: Optional[str] = None
|
| 62 |
+
databases: Optional[List[str]] = None
|
| 63 |
+
# This can be used for any additional auth context which needs to be
|
| 64 |
+
# propagated from the authentication provider to the authorization
|
| 65 |
+
# provider.
|
| 66 |
+
attributes: Optional[Dict[str, Any]] = None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ServerAuthenticationProvider(Component):
|
| 70 |
+
"""
|
| 71 |
+
ServerAuthenticationProvider is responsible for authenticating requests. If
|
| 72 |
+
a ServerAuthenticationProvider is configured, it will be called by the
|
| 73 |
+
server to authenticate requests. If no ServerAuthenticationProvider is
|
| 74 |
+
configured, all requests will be authenticated.
|
| 75 |
+
|
| 76 |
+
The ServerAuthenticationProvider should return a UserIdentity object if the
|
| 77 |
+
request is authenticated for use by the ServerAuthorizationProvider.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def __init__(self, system: System) -> None:
|
| 81 |
+
super().__init__(system)
|
| 82 |
+
self._ignore_auth_paths: Dict[
|
| 83 |
+
str, List[str]
|
| 84 |
+
] = system.settings.chroma_server_auth_ignore_paths
|
| 85 |
+
self.overwrite_singleton_tenant_database_access_from_auth = (
|
| 86 |
+
system.settings.chroma_overwrite_singleton_tenant_database_access_from_auth
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
@abstractmethod
|
| 90 |
+
def authenticate_or_raise(self, headers: Dict[str, str]) -> UserIdentity:
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
def ignore_operation(self, verb: str, path: str) -> bool:
|
| 94 |
+
if (
|
| 95 |
+
path in self._ignore_auth_paths.keys()
|
| 96 |
+
and verb.upper() in self._ignore_auth_paths[path]
|
| 97 |
+
):
|
| 98 |
+
return True
|
| 99 |
+
return False
|
| 100 |
+
|
| 101 |
+
def read_creds_or_creds_file(self) -> List[str]:
|
| 102 |
+
_creds_file = None
|
| 103 |
+
_creds = None
|
| 104 |
+
|
| 105 |
+
if self._system.settings.chroma_server_authn_credentials_file:
|
| 106 |
+
_creds_file = str(
|
| 107 |
+
self._system.settings["chroma_server_authn_credentials_file"]
|
| 108 |
+
)
|
| 109 |
+
if self._system.settings.chroma_server_authn_credentials:
|
| 110 |
+
_creds = str(self._system.settings["chroma_server_authn_credentials"])
|
| 111 |
+
if not _creds_file and not _creds:
|
| 112 |
+
raise ValueError(
|
| 113 |
+
"No credentials file or credentials found in "
|
| 114 |
+
"[chroma_server_authn_credentials]."
|
| 115 |
+
)
|
| 116 |
+
if _creds_file and _creds:
|
| 117 |
+
raise ValueError(
|
| 118 |
+
"Both credentials file and credentials found."
|
| 119 |
+
"Please provide only one."
|
| 120 |
+
)
|
| 121 |
+
if _creds:
|
| 122 |
+
return [c for c in _creds.split("\n") if c]
|
| 123 |
+
elif _creds_file:
|
| 124 |
+
with open(_creds_file, "r") as f:
|
| 125 |
+
return f.readlines()
|
| 126 |
+
raise ValueError("Should never happen")
|
| 127 |
+
|
| 128 |
+
def singleton_tenant_database_if_applicable(
|
| 129 |
+
self, user: Optional[UserIdentity]
|
| 130 |
+
) -> Tuple[Optional[str], Optional[str]]:
|
| 131 |
+
"""
|
| 132 |
+
If settings.chroma_overwrite_singleton_tenant_database_access_from_auth
|
| 133 |
+
is False, this function always returns (None, None).
|
| 134 |
+
|
| 135 |
+
If settings.chroma_overwrite_singleton_tenant_database_access_from_auth
|
| 136 |
+
is True, follows the following logic:
|
| 137 |
+
- If the user only has access to a single tenant, this function will
|
| 138 |
+
return that tenant as its first return value.
|
| 139 |
+
- If the user only has access to a single database, this function will
|
| 140 |
+
return that database as its second return value. If the user has
|
| 141 |
+
access to multiple tenants and/or databases, including "*", this
|
| 142 |
+
function will return None for the corresponding value(s).
|
| 143 |
+
- If the user has access to multiple tenants and/or databases this
|
| 144 |
+
function will return None for the corresponding value(s).
|
| 145 |
+
"""
|
| 146 |
+
if not self.overwrite_singleton_tenant_database_access_from_auth or not user:
|
| 147 |
+
return None, None
|
| 148 |
+
tenant = None
|
| 149 |
+
database = None
|
| 150 |
+
if user.tenant and user.tenant != "*":
|
| 151 |
+
tenant = user.tenant
|
| 152 |
+
if user.databases and len(user.databases) == 1 and user.databases[0] != "*":
|
| 153 |
+
database = user.databases[0]
|
| 154 |
+
return tenant, database
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
class AuthzAction(str, Enum):
|
| 158 |
+
"""
|
| 159 |
+
The set of actions that can be authorized by the authorization provider.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
RESET = "system:reset"
|
| 163 |
+
CREATE_TENANT = "tenant:create_tenant"
|
| 164 |
+
GET_TENANT = "tenant:get_tenant"
|
| 165 |
+
CREATE_DATABASE = "db:create_database"
|
| 166 |
+
GET_DATABASE = "db:get_database"
|
| 167 |
+
DELETE_DATABASE = "db:delete_database"
|
| 168 |
+
LIST_DATABASES = "db:list_databases"
|
| 169 |
+
LIST_COLLECTIONS = "db:list_collections"
|
| 170 |
+
COUNT_COLLECTIONS = "db:count_collections"
|
| 171 |
+
CREATE_COLLECTION = "db:create_collection"
|
| 172 |
+
GET_OR_CREATE_COLLECTION = "db:get_or_create_collection"
|
| 173 |
+
GET_COLLECTION = "collection:get_collection"
|
| 174 |
+
DELETE_COLLECTION = "collection:delete_collection"
|
| 175 |
+
UPDATE_COLLECTION = "collection:update_collection"
|
| 176 |
+
ADD = "collection:add"
|
| 177 |
+
DELETE = "collection:delete"
|
| 178 |
+
GET = "collection:get"
|
| 179 |
+
QUERY = "collection:query"
|
| 180 |
+
COUNT = "collection:count"
|
| 181 |
+
UPDATE = "collection:update"
|
| 182 |
+
UPSERT = "collection:upsert"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@dataclass
|
| 186 |
+
class AuthzResource:
|
| 187 |
+
"""
|
| 188 |
+
The resource being accessed in an authorization request.
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
tenant: Optional[str]
|
| 192 |
+
database: Optional[str]
|
| 193 |
+
collection: Optional[str]
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
class ServerAuthorizationProvider(Component):
|
| 197 |
+
"""
|
| 198 |
+
ServerAuthorizationProvider is responsible for authorizing requests. If a
|
| 199 |
+
ServerAuthorizationProvider is configured, it will be called by the server
|
| 200 |
+
to authorize requests. If no ServerAuthorizationProvider is configured, all
|
| 201 |
+
requests will be authorized.
|
| 202 |
+
|
| 203 |
+
ServerAuthorizationProvider should raise an exception if the request is not
|
| 204 |
+
authorized.
|
| 205 |
+
"""
|
| 206 |
+
|
| 207 |
+
def __init__(self, system: System) -> None:
|
| 208 |
+
super().__init__(system)
|
| 209 |
+
|
| 210 |
+
@abstractmethod
|
| 211 |
+
def authorize_or_raise(
|
| 212 |
+
self, user: UserIdentity, action: AuthzAction, resource: AuthzResource
|
| 213 |
+
) -> None:
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
def read_config_or_config_file(self) -> List[str]:
|
| 217 |
+
_config_file = None
|
| 218 |
+
_config = None
|
| 219 |
+
if self._system.settings.chroma_server_authz_config_file:
|
| 220 |
+
_config_file = self._system.settings["chroma_server_authz_config_file"]
|
| 221 |
+
if self._system.settings.chroma_server_authz_config:
|
| 222 |
+
_config = str(self._system.settings["chroma_server_authz_config"])
|
| 223 |
+
if not _config_file and not _config:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
"No authz configuration file or authz configuration found."
|
| 226 |
+
)
|
| 227 |
+
if _config_file and _config:
|
| 228 |
+
raise ValueError(
|
| 229 |
+
"Both authz configuration file and authz configuration found."
|
| 230 |
+
"Please provide only one."
|
| 231 |
+
)
|
| 232 |
+
if _config:
|
| 233 |
+
return [c for c in _config.split("\n") if c]
|
| 234 |
+
elif _config_file:
|
| 235 |
+
with open(_config_file, "r") as f:
|
| 236 |
+
return f.readlines()
|
| 237 |
+
raise ValueError("Should never happen")
|
python/user_packages/Python313/site-packages/chromadb/cli/__init__.py
ADDED
|
File without changes
|
python/user_packages/Python313/site-packages/chromadb/cli/cli.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import chromadb_rust_bindings
|
| 5 |
+
import requests
|
| 6 |
+
from packaging.version import parse
|
| 7 |
+
|
| 8 |
+
import chromadb
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def build_cli_args(**kwargs):
|
| 12 |
+
args = []
|
| 13 |
+
for key, value in kwargs.items():
|
| 14 |
+
if isinstance(value, bool):
|
| 15 |
+
if value:
|
| 16 |
+
args.append(f"--{key}")
|
| 17 |
+
elif value is not None:
|
| 18 |
+
args.extend([f"--{key}", str(value)])
|
| 19 |
+
return args
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def update():
|
| 23 |
+
try:
|
| 24 |
+
url = f"https://api.github.com/repos/chroma-core/chroma/releases"
|
| 25 |
+
response = requests.get(url)
|
| 26 |
+
response.raise_for_status()
|
| 27 |
+
releases = response.json()
|
| 28 |
+
|
| 29 |
+
version_pattern = re.compile(r'^\d+\.\d+\.\d+$')
|
| 30 |
+
numeric_releases = [r["tag_name"] for r in releases if version_pattern.fullmatch(r["tag_name"])]
|
| 31 |
+
|
| 32 |
+
if not numeric_releases:
|
| 33 |
+
print("Couldn't fetch the latest Chroma version")
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
latest = max(numeric_releases, key=parse)
|
| 37 |
+
if latest == chromadb.__version__:
|
| 38 |
+
print("Your Chroma version is up-to-date")
|
| 39 |
+
return
|
| 40 |
+
|
| 41 |
+
print(
|
| 42 |
+
f"A new version of Chroma is available!\nIf you're using pip, run 'pip install --upgrade chromadb' to upgrade to version {latest}")
|
| 43 |
+
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print("Couldn't fetch the latest Chroma version")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def app():
|
| 49 |
+
args = sys.argv
|
| 50 |
+
if ["chroma", "update"] in args:
|
| 51 |
+
update()
|
| 52 |
+
return
|
| 53 |
+
try:
|
| 54 |
+
chromadb_rust_bindings.cli(args)
|
| 55 |
+
except KeyboardInterrupt:
|
| 56 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/cli/utils.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import yaml
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def set_log_file_path(
|
| 8 |
+
log_config_path: str, new_filename: str = "chroma.log"
|
| 9 |
+
) -> Dict[str, Any]:
|
| 10 |
+
"""This works with the standard log_config.yml file.
|
| 11 |
+
It will not work with custom log configs that may use different handlers"""
|
| 12 |
+
with open(f"{log_config_path}", "r") as file:
|
| 13 |
+
log_config = yaml.safe_load(file)
|
| 14 |
+
for handler in log_config["handlers"].values():
|
| 15 |
+
if handler.get("class") == "logging.handlers.RotatingFileHandler":
|
| 16 |
+
handler["filename"] = new_filename
|
| 17 |
+
|
| 18 |
+
return log_config
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_directory_size(directory: str) -> int:
|
| 22 |
+
"""Get the size of a directory in bytes"""
|
| 23 |
+
total = 0
|
| 24 |
+
with os.scandir(directory) as it:
|
| 25 |
+
for entry in it:
|
| 26 |
+
if entry.is_file():
|
| 27 |
+
total += entry.stat().st_size
|
| 28 |
+
elif entry.is_dir():
|
| 29 |
+
total += get_directory_size(entry.path)
|
| 30 |
+
return total
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# https://stackoverflow.com/a/1094933
|
| 34 |
+
def sizeof_fmt(num: int, suffix: str = "B") -> str:
|
| 35 |
+
n: float = float(num)
|
| 36 |
+
for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
|
| 37 |
+
if abs(n) < 1024.0:
|
| 38 |
+
return f"{n:3.1f}{unit}{suffix}"
|
| 39 |
+
n /= 1024.0
|
| 40 |
+
return f"{n:.1f}Yi{suffix}"
|
python/user_packages/Python313/site-packages/chromadb/db/__init__.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractmethod
|
| 2 |
+
from typing import List, Sequence, Optional, Tuple
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
from chromadb.api.types import (
|
| 5 |
+
Embeddings,
|
| 6 |
+
Documents,
|
| 7 |
+
IDs,
|
| 8 |
+
Metadatas,
|
| 9 |
+
Metadata,
|
| 10 |
+
Where,
|
| 11 |
+
WhereDocument,
|
| 12 |
+
)
|
| 13 |
+
from chromadb.config import Component
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class DB(Component):
|
| 17 |
+
@abstractmethod
|
| 18 |
+
def create_collection(
|
| 19 |
+
self,
|
| 20 |
+
name: str,
|
| 21 |
+
metadata: Optional[Metadata] = None,
|
| 22 |
+
get_or_create: bool = False,
|
| 23 |
+
) -> Sequence: # type: ignore
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
@abstractmethod
|
| 27 |
+
def get_collection(self, name: str) -> Sequence: # type: ignore
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
@abstractmethod
|
| 31 |
+
def list_collections(
|
| 32 |
+
self, limit: Optional[int] = None, offset: Optional[int] = None
|
| 33 |
+
) -> Sequence: # type: ignore
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
@abstractmethod
|
| 37 |
+
def count_collections(self) -> int:
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
@abstractmethod
|
| 41 |
+
def update_collection(
|
| 42 |
+
self,
|
| 43 |
+
id: UUID,
|
| 44 |
+
new_name: Optional[str] = None,
|
| 45 |
+
new_metadata: Optional[Metadata] = None,
|
| 46 |
+
) -> None:
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
@abstractmethod
|
| 50 |
+
def delete_collection(self, name: str) -> None:
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
@abstractmethod
|
| 54 |
+
def get_collection_uuid_from_name(self, collection_name: str) -> UUID:
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
@abstractmethod
|
| 58 |
+
def add(
|
| 59 |
+
self,
|
| 60 |
+
collection_uuid: UUID,
|
| 61 |
+
embeddings: Embeddings,
|
| 62 |
+
metadatas: Optional[Metadatas],
|
| 63 |
+
documents: Optional[Documents],
|
| 64 |
+
ids: List[str],
|
| 65 |
+
) -> List[UUID]:
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
+
@abstractmethod
|
| 69 |
+
def get(
|
| 70 |
+
self,
|
| 71 |
+
where: Optional[Where] = None,
|
| 72 |
+
collection_name: Optional[str] = None,
|
| 73 |
+
collection_uuid: Optional[UUID] = None,
|
| 74 |
+
ids: Optional[IDs] = None,
|
| 75 |
+
limit: Optional[int] = None,
|
| 76 |
+
offset: Optional[int] = None,
|
| 77 |
+
where_document: Optional[WhereDocument] = None,
|
| 78 |
+
columns: Optional[List[str]] = None,
|
| 79 |
+
) -> Sequence: # type: ignore
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
@abstractmethod
|
| 83 |
+
def update(
|
| 84 |
+
self,
|
| 85 |
+
collection_uuid: UUID,
|
| 86 |
+
ids: IDs,
|
| 87 |
+
embeddings: Optional[Embeddings] = None,
|
| 88 |
+
metadatas: Optional[Metadatas] = None,
|
| 89 |
+
documents: Optional[Documents] = None,
|
| 90 |
+
) -> bool:
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
@abstractmethod
|
| 94 |
+
def count(self, collection_id: UUID) -> int:
|
| 95 |
+
pass
|
| 96 |
+
|
| 97 |
+
@abstractmethod
|
| 98 |
+
def delete(
|
| 99 |
+
self,
|
| 100 |
+
where: Optional[Where] = None,
|
| 101 |
+
collection_uuid: Optional[UUID] = None,
|
| 102 |
+
ids: Optional[IDs] = None,
|
| 103 |
+
where_document: Optional[WhereDocument] = None,
|
| 104 |
+
) -> None:
|
| 105 |
+
pass
|
| 106 |
+
|
| 107 |
+
@abstractmethod
|
| 108 |
+
def get_nearest_neighbors(
|
| 109 |
+
self,
|
| 110 |
+
collection_uuid: UUID,
|
| 111 |
+
where: Optional[Where] = None,
|
| 112 |
+
embeddings: Optional[Embeddings] = None,
|
| 113 |
+
n_results: int = 10,
|
| 114 |
+
where_document: Optional[WhereDocument] = None,
|
| 115 |
+
) -> Tuple[List[List[UUID]], List[List[float]]]:
|
| 116 |
+
pass
|
| 117 |
+
|
| 118 |
+
@abstractmethod
|
| 119 |
+
def get_by_ids(
|
| 120 |
+
self, uuids: List[UUID], columns: Optional[List[str]] = None
|
| 121 |
+
) -> Sequence: # type: ignore
|
| 122 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/db/base.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Optional, Sequence, Tuple, Type
|
| 2 |
+
from types import TracebackType
|
| 3 |
+
from typing_extensions import Protocol, Self, Literal
|
| 4 |
+
from abc import ABC, abstractmethod
|
| 5 |
+
from threading import local
|
| 6 |
+
from overrides import override, EnforceOverrides
|
| 7 |
+
import pypika
|
| 8 |
+
import pypika.queries
|
| 9 |
+
from chromadb.config import System, Component
|
| 10 |
+
from uuid import UUID
|
| 11 |
+
from itertools import islice, count
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Cursor(Protocol):
|
| 15 |
+
"""Reifies methods we use from a DBAPI2 Cursor since DBAPI2 is not typed."""
|
| 16 |
+
|
| 17 |
+
def execute(self, sql: str, params: Optional[Tuple[Any, ...]] = None) -> Self:
|
| 18 |
+
...
|
| 19 |
+
|
| 20 |
+
def executescript(self, script: str) -> Self:
|
| 21 |
+
...
|
| 22 |
+
|
| 23 |
+
def executemany(
|
| 24 |
+
self, sql: str, params: Optional[Sequence[Tuple[Any, ...]]] = None
|
| 25 |
+
) -> Self:
|
| 26 |
+
...
|
| 27 |
+
|
| 28 |
+
def fetchone(self) -> Tuple[Any, ...]:
|
| 29 |
+
...
|
| 30 |
+
|
| 31 |
+
def fetchall(self) -> Sequence[Tuple[Any, ...]]:
|
| 32 |
+
...
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class TxWrapper(ABC, EnforceOverrides):
|
| 36 |
+
"""Wrapper class for DBAPI 2.0 Connection objects, with which clients can implement transactions.
|
| 37 |
+
Makes two guarantees that basic DBAPI 2.0 connections do not:
|
| 38 |
+
|
| 39 |
+
- __enter__ returns a Cursor object consistently (instead of a Connection like some do)
|
| 40 |
+
- Always re-raises an exception if one was thrown from the body
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
@abstractmethod
|
| 44 |
+
def __enter__(self) -> Cursor:
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
@abstractmethod
|
| 48 |
+
def __exit__(
|
| 49 |
+
self,
|
| 50 |
+
exc_type: Optional[Type[BaseException]],
|
| 51 |
+
exc_value: Optional[BaseException],
|
| 52 |
+
traceback: Optional[TracebackType],
|
| 53 |
+
) -> Literal[False]:
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class SqlDB(Component):
|
| 58 |
+
"""DBAPI 2.0 interface wrapper to ensure consistent behavior between implementations"""
|
| 59 |
+
|
| 60 |
+
def __init__(self, system: System):
|
| 61 |
+
super().__init__(system)
|
| 62 |
+
|
| 63 |
+
@abstractmethod
|
| 64 |
+
def tx(self) -> TxWrapper:
|
| 65 |
+
"""Return a transaction wrapper"""
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
+
@staticmethod
|
| 69 |
+
@abstractmethod
|
| 70 |
+
def querybuilder() -> Type[pypika.Query]:
|
| 71 |
+
"""Return a PyPika Query builder of an appropriate subtype for this database
|
| 72 |
+
implementation (see
|
| 73 |
+
https://pypika.readthedocs.io/en/latest/3_advanced.html#handling-different-database-platforms)
|
| 74 |
+
"""
|
| 75 |
+
pass
|
| 76 |
+
|
| 77 |
+
@staticmethod
|
| 78 |
+
@abstractmethod
|
| 79 |
+
def parameter_format() -> str:
|
| 80 |
+
"""Return the appropriate parameter format for this database implementation.
|
| 81 |
+
Will be called with str.format(i) where i is the numeric index of the parameter.
|
| 82 |
+
"""
|
| 83 |
+
pass
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
@abstractmethod
|
| 87 |
+
def uuid_to_db(uuid: Optional[UUID]) -> Optional[Any]:
|
| 88 |
+
"""Convert a UUID to a value that can be passed to the DB driver"""
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
@staticmethod
|
| 92 |
+
@abstractmethod
|
| 93 |
+
def uuid_from_db(value: Optional[Any]) -> Optional[UUID]:
|
| 94 |
+
"""Convert a value from the DB driver to a UUID"""
|
| 95 |
+
pass
|
| 96 |
+
|
| 97 |
+
@staticmethod
|
| 98 |
+
@abstractmethod
|
| 99 |
+
def unique_constraint_error() -> Type[BaseException]:
|
| 100 |
+
"""Return the exception type that the DB raises when a unique constraint is
|
| 101 |
+
violated"""
|
| 102 |
+
pass
|
| 103 |
+
|
| 104 |
+
def param(self, idx: int) -> pypika.Parameter:
|
| 105 |
+
"""Return a PyPika Parameter object for the given index"""
|
| 106 |
+
return pypika.Parameter(self.parameter_format().format(idx))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
_context = local()
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class ParameterValue(pypika.Parameter): # type: ignore
|
| 113 |
+
"""
|
| 114 |
+
Wrapper class for PyPika paramters that allows the values for Parameters
|
| 115 |
+
to be expressed inline while building a query. See get_sql() for
|
| 116 |
+
detailed usage information.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
def __init__(self, value: Any):
|
| 120 |
+
self.value = value
|
| 121 |
+
|
| 122 |
+
@override
|
| 123 |
+
def get_sql(self, **kwargs: Any) -> str:
|
| 124 |
+
if isinstance(self.value, (list, tuple)):
|
| 125 |
+
_context.values.extend(self.value)
|
| 126 |
+
indexes = islice(_context.generator, len(self.value))
|
| 127 |
+
placeholders = ", ".join(_context.formatstr.format(i) for i in indexes)
|
| 128 |
+
val = f"({placeholders})"
|
| 129 |
+
else:
|
| 130 |
+
_context.values.append(self.value)
|
| 131 |
+
val = _context.formatstr.format(next(_context.generator))
|
| 132 |
+
|
| 133 |
+
return str(val)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def get_sql(
|
| 137 |
+
query: pypika.queries.QueryBuilder, formatstr: str = "?"
|
| 138 |
+
) -> Tuple[str, Tuple[Any, ...]]:
|
| 139 |
+
"""
|
| 140 |
+
Wrapper for pypika's get_sql method that allows the values for Parameters
|
| 141 |
+
to be expressed inline while building a query, and that returns a tuple of the
|
| 142 |
+
SQL string and parameters. This makes it easier to construct complex queries
|
| 143 |
+
programmatically and automatically matches up the generated SQL with the required
|
| 144 |
+
parameter vector.
|
| 145 |
+
|
| 146 |
+
Doing so requires using the ParameterValue class defined in this module instead
|
| 147 |
+
of the base pypika.Parameter class.
|
| 148 |
+
|
| 149 |
+
Usage Example:
|
| 150 |
+
|
| 151 |
+
q = (
|
| 152 |
+
pypika.Query().from_("table")
|
| 153 |
+
.select("col1")
|
| 154 |
+
.where("col2"==ParameterValue("foo"))
|
| 155 |
+
.where("col3"==ParameterValue("bar"))
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
sql, params = get_sql(q)
|
| 159 |
+
|
| 160 |
+
cursor.execute(sql, params)
|
| 161 |
+
|
| 162 |
+
Note how it is not necessary to construct the parameter vector manually... it
|
| 163 |
+
will always be generated with the parameter values in the same order as emitted
|
| 164 |
+
SQL string.
|
| 165 |
+
|
| 166 |
+
The format string should match the parameter format for the database being used.
|
| 167 |
+
It will be called with str.format(i) where i is the numeric index of the parameter.
|
| 168 |
+
For example, Postgres requires parameters like `:1`, `:2`, etc. so the format string
|
| 169 |
+
should be `":{}"`.
|
| 170 |
+
|
| 171 |
+
See https://pypika.readthedocs.io/en/latest/2_tutorial.html#parametrized-queries for more
|
| 172 |
+
information on parameterized queries in PyPika.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
_context.values = []
|
| 176 |
+
_context.generator = count(1)
|
| 177 |
+
_context.formatstr = formatstr
|
| 178 |
+
sql = query.get_sql()
|
| 179 |
+
params = tuple(_context.values)
|
| 180 |
+
return sql, params
|
python/user_packages/Python313/site-packages/chromadb/db/migrations.py
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from typing import Sequence
|
| 3 |
+
from typing_extensions import TypedDict, NotRequired
|
| 4 |
+
from importlib_resources.abc import Traversable
|
| 5 |
+
import re
|
| 6 |
+
import hashlib
|
| 7 |
+
from chromadb.db.base import SqlDB, Cursor
|
| 8 |
+
from abc import abstractmethod
|
| 9 |
+
from chromadb.config import System, Settings
|
| 10 |
+
from chromadb.telemetry.opentelemetry import (
|
| 11 |
+
OpenTelemetryClient,
|
| 12 |
+
OpenTelemetryGranularity,
|
| 13 |
+
trace_method,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class MigrationFile(TypedDict):
|
| 18 |
+
path: NotRequired[Traversable]
|
| 19 |
+
dir: str
|
| 20 |
+
filename: str
|
| 21 |
+
version: int
|
| 22 |
+
scope: str
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class Migration(MigrationFile):
|
| 26 |
+
hash: str
|
| 27 |
+
sql: str
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class UninitializedMigrationsError(Exception):
|
| 31 |
+
def __init__(self) -> None:
|
| 32 |
+
super().__init__("Migrations have not been initialized")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class UnappliedMigrationsError(Exception):
|
| 36 |
+
def __init__(self, dir: str, version: int):
|
| 37 |
+
self.dir = dir
|
| 38 |
+
self.version = version
|
| 39 |
+
super().__init__(
|
| 40 |
+
f"Unapplied migrations in {dir}, starting with version {version}"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class InconsistentVersionError(Exception):
|
| 45 |
+
def __init__(self, dir: str, db_version: int, source_version: int):
|
| 46 |
+
super().__init__(
|
| 47 |
+
f"Inconsistent migration versions in {dir}:"
|
| 48 |
+
+ f"db version was {db_version}, source version was {source_version}."
|
| 49 |
+
+ " Has the migration sequence been modified since being applied to the DB?"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class InconsistentHashError(Exception):
|
| 54 |
+
def __init__(self, path: str, db_hash: str, source_hash: str):
|
| 55 |
+
super().__init__(
|
| 56 |
+
f"Inconsistent hashes in {path}:"
|
| 57 |
+
+ f"db hash was {db_hash}, source has was {source_hash}."
|
| 58 |
+
+ " Was the migration file modified after being applied to the DB?"
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class InvalidHashError(Exception):
|
| 63 |
+
def __init__(self, alg: str):
|
| 64 |
+
super().__init__(f"Invalid hash algorithm specified: {alg}")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class InvalidMigrationFilename(Exception):
|
| 68 |
+
pass
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class MigratableDB(SqlDB):
|
| 72 |
+
"""Simple base class for databases which support basic migrations.
|
| 73 |
+
|
| 74 |
+
Migrations are SQL files stored as package resources and accessed via
|
| 75 |
+
importlib_resources.
|
| 76 |
+
|
| 77 |
+
All migrations in the same directory are assumed to be dependent on previous
|
| 78 |
+
migrations in the same directory, where "previous" is defined on lexographical
|
| 79 |
+
ordering of filenames.
|
| 80 |
+
|
| 81 |
+
Migrations have a ascending numeric version number and a hash of the file contents.
|
| 82 |
+
When migrations are applied, the hashes of previous migrations are checked to ensure
|
| 83 |
+
that the database is consistent with the source repository. If they are not, an
|
| 84 |
+
error is thrown and no migrations will be applied.
|
| 85 |
+
|
| 86 |
+
Migration files must follow the naming convention:
|
| 87 |
+
<version>.<description>.<scope>.sql, where <version> is a 5-digit zero-padded
|
| 88 |
+
integer, <description> is a short textual description, and <scope> is a short string
|
| 89 |
+
identifying the database implementation.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
_settings: Settings
|
| 93 |
+
|
| 94 |
+
def __init__(self, system: System) -> None:
|
| 95 |
+
self._settings = system.settings
|
| 96 |
+
self._opentelemetry_client = system.require(OpenTelemetryClient)
|
| 97 |
+
super().__init__(system)
|
| 98 |
+
|
| 99 |
+
@staticmethod
|
| 100 |
+
@abstractmethod
|
| 101 |
+
def migration_scope() -> str:
|
| 102 |
+
"""The database implementation to use for migrations (e.g, sqlite, pgsql)"""
|
| 103 |
+
pass
|
| 104 |
+
|
| 105 |
+
@abstractmethod
|
| 106 |
+
def migration_dirs(self) -> Sequence[Traversable]:
|
| 107 |
+
"""Directories containing the migration sequences that should be applied to this
|
| 108 |
+
DB."""
|
| 109 |
+
pass
|
| 110 |
+
|
| 111 |
+
@abstractmethod
|
| 112 |
+
def setup_migrations(self) -> None:
|
| 113 |
+
"""Idempotently creates the migrations table"""
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
@abstractmethod
|
| 117 |
+
def migrations_initialized(self) -> bool:
|
| 118 |
+
"""Return true if the migrations table exists"""
|
| 119 |
+
pass
|
| 120 |
+
|
| 121 |
+
@abstractmethod
|
| 122 |
+
def db_migrations(self, dir: Traversable) -> Sequence[Migration]:
|
| 123 |
+
"""Return a list of all migrations already applied to this database, from the
|
| 124 |
+
given source directory, in ascending order."""
|
| 125 |
+
pass
|
| 126 |
+
|
| 127 |
+
@abstractmethod
|
| 128 |
+
def apply_migration(self, cur: Cursor, migration: Migration) -> None:
|
| 129 |
+
"""Apply a single migration to the database"""
|
| 130 |
+
pass
|
| 131 |
+
|
| 132 |
+
def initialize_migrations(self) -> None:
|
| 133 |
+
"""Initialize migrations for this DB"""
|
| 134 |
+
migrate = self._settings.require("migrations")
|
| 135 |
+
|
| 136 |
+
if migrate == "validate":
|
| 137 |
+
self.validate_migrations()
|
| 138 |
+
|
| 139 |
+
if migrate == "apply":
|
| 140 |
+
self.apply_migrations()
|
| 141 |
+
|
| 142 |
+
@trace_method("MigratableDB.validate_migrations", OpenTelemetryGranularity.ALL)
|
| 143 |
+
def validate_migrations(self) -> None:
|
| 144 |
+
"""Validate all migrations and throw an exception if there are any unapplied
|
| 145 |
+
migrations in the source repo."""
|
| 146 |
+
if not self.migrations_initialized():
|
| 147 |
+
raise UninitializedMigrationsError()
|
| 148 |
+
for dir in self.migration_dirs():
|
| 149 |
+
db_migrations = self.db_migrations(dir)
|
| 150 |
+
source_migrations = find_migrations(
|
| 151 |
+
dir,
|
| 152 |
+
self.migration_scope(),
|
| 153 |
+
self._settings.require("migrations_hash_algorithm"),
|
| 154 |
+
)
|
| 155 |
+
unapplied_migrations = verify_migration_sequence(
|
| 156 |
+
db_migrations, source_migrations
|
| 157 |
+
)
|
| 158 |
+
if len(unapplied_migrations) > 0:
|
| 159 |
+
version = unapplied_migrations[0]["version"]
|
| 160 |
+
raise UnappliedMigrationsError(dir=dir.name, version=version)
|
| 161 |
+
|
| 162 |
+
@trace_method("MigratableDB.apply_migrations", OpenTelemetryGranularity.ALL)
|
| 163 |
+
def apply_migrations(self) -> None:
|
| 164 |
+
"""Validate existing migrations, and apply all new ones."""
|
| 165 |
+
self.setup_migrations()
|
| 166 |
+
for dir in self.migration_dirs():
|
| 167 |
+
db_migrations = self.db_migrations(dir)
|
| 168 |
+
source_migrations = find_migrations(
|
| 169 |
+
dir,
|
| 170 |
+
self.migration_scope(),
|
| 171 |
+
self._settings.require("migrations_hash_algorithm"),
|
| 172 |
+
)
|
| 173 |
+
unapplied_migrations = verify_migration_sequence(
|
| 174 |
+
db_migrations, source_migrations
|
| 175 |
+
)
|
| 176 |
+
with self.tx() as cur:
|
| 177 |
+
for migration in unapplied_migrations:
|
| 178 |
+
self.apply_migration(cur, migration)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
# Format is <version>-<name>.<scope>.sql
|
| 182 |
+
# e.g, 00001-users.sqlite.sql
|
| 183 |
+
filename_regex = re.compile(r"(\d+)-(.+)\.(.+)\.sql")
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def _parse_migration_filename(
|
| 187 |
+
dir: str, filename: str, path: Traversable
|
| 188 |
+
) -> MigrationFile:
|
| 189 |
+
"""Parse a migration filename into a MigrationFile object"""
|
| 190 |
+
match = filename_regex.match(filename)
|
| 191 |
+
if match is None:
|
| 192 |
+
raise InvalidMigrationFilename("Invalid migration filename: " + filename)
|
| 193 |
+
version, _, scope = match.groups()
|
| 194 |
+
return {
|
| 195 |
+
"path": path,
|
| 196 |
+
"dir": dir,
|
| 197 |
+
"filename": filename,
|
| 198 |
+
"version": int(version),
|
| 199 |
+
"scope": scope,
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def verify_migration_sequence(
|
| 204 |
+
db_migrations: Sequence[Migration],
|
| 205 |
+
source_migrations: Sequence[Migration],
|
| 206 |
+
) -> Sequence[Migration]:
|
| 207 |
+
"""Given a list of migrations already applied to a database, and a list of
|
| 208 |
+
migrations from the source code, validate that the applied migrations are correct
|
| 209 |
+
and match the expected migrations.
|
| 210 |
+
|
| 211 |
+
Throws an exception if any migrations are missing, out of order, or if the source
|
| 212 |
+
hash does not match.
|
| 213 |
+
|
| 214 |
+
Returns a list of all unapplied migrations, or an empty list if all migrations are
|
| 215 |
+
applied and the database is up to date."""
|
| 216 |
+
|
| 217 |
+
for db_migration, source_migration in zip(db_migrations, source_migrations):
|
| 218 |
+
if db_migration["version"] != source_migration["version"]:
|
| 219 |
+
raise InconsistentVersionError(
|
| 220 |
+
dir=db_migration["dir"],
|
| 221 |
+
db_version=db_migration["version"],
|
| 222 |
+
source_version=source_migration["version"],
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
if db_migration["hash"] != source_migration["hash"]:
|
| 226 |
+
raise InconsistentHashError(
|
| 227 |
+
path=db_migration["dir"] + "/" + db_migration["filename"],
|
| 228 |
+
db_hash=db_migration["hash"],
|
| 229 |
+
source_hash=source_migration["hash"],
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
return source_migrations[len(db_migrations) :]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def find_migrations(
|
| 236 |
+
dir: Traversable, scope: str, hash_alg: str = "md5"
|
| 237 |
+
) -> Sequence[Migration]:
|
| 238 |
+
"""Return a list of all migration present in the given directory, in ascending
|
| 239 |
+
order. Filter by scope."""
|
| 240 |
+
files = [
|
| 241 |
+
_parse_migration_filename(dir.name, t.name, t)
|
| 242 |
+
for t in dir.iterdir()
|
| 243 |
+
if t.name.endswith(".sql")
|
| 244 |
+
]
|
| 245 |
+
files = list(filter(lambda f: f["scope"] == scope, files))
|
| 246 |
+
files = sorted(files, key=lambda f: f["version"])
|
| 247 |
+
return [_read_migration_file(f, hash_alg) for f in files]
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _read_migration_file(file: MigrationFile, hash_alg: str) -> Migration:
|
| 251 |
+
"""Read a migration file"""
|
| 252 |
+
if "path" not in file or not file["path"].is_file():
|
| 253 |
+
raise FileNotFoundError(
|
| 254 |
+
f"No migration file found for dir {file['dir']} with filename {file['filename']} and scope {file['scope']} at version {file['version']}"
|
| 255 |
+
)
|
| 256 |
+
sql = file["path"].read_text()
|
| 257 |
+
|
| 258 |
+
if hash_alg == "md5":
|
| 259 |
+
hash = (
|
| 260 |
+
hashlib.md5(sql.encode("utf-8"), usedforsecurity=False).hexdigest()
|
| 261 |
+
if sys.version_info >= (3, 9)
|
| 262 |
+
else hashlib.md5(sql.encode("utf-8")).hexdigest()
|
| 263 |
+
)
|
| 264 |
+
elif hash_alg == "sha256":
|
| 265 |
+
hash = hashlib.sha256(sql.encode("utf-8")).hexdigest()
|
| 266 |
+
else:
|
| 267 |
+
raise InvalidHashError(alg=hash_alg)
|
| 268 |
+
|
| 269 |
+
return {
|
| 270 |
+
"hash": hash,
|
| 271 |
+
"sql": sql,
|
| 272 |
+
"dir": file["dir"],
|
| 273 |
+
"filename": file["filename"],
|
| 274 |
+
"version": file["version"],
|
| 275 |
+
"scope": file["scope"],
|
| 276 |
+
}
|
python/user_packages/Python313/site-packages/chromadb/db/system.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractmethod
|
| 2 |
+
from typing import Optional, Sequence, Tuple
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
from chromadb.api.collection_configuration import (
|
| 5 |
+
CreateCollectionConfiguration,
|
| 6 |
+
UpdateCollectionConfiguration,
|
| 7 |
+
)
|
| 8 |
+
from chromadb.api.types import Schema
|
| 9 |
+
from chromadb.types import (
|
| 10 |
+
Collection,
|
| 11 |
+
CollectionAndSegments,
|
| 12 |
+
Database,
|
| 13 |
+
Tenant,
|
| 14 |
+
Metadata,
|
| 15 |
+
Segment,
|
| 16 |
+
SegmentScope,
|
| 17 |
+
OptionalArgument,
|
| 18 |
+
Unspecified,
|
| 19 |
+
UpdateMetadata,
|
| 20 |
+
)
|
| 21 |
+
from chromadb.config import DEFAULT_DATABASE, DEFAULT_TENANT, Component
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class SysDB(Component):
|
| 25 |
+
"""Data interface for Chroma's System database"""
|
| 26 |
+
|
| 27 |
+
@abstractmethod
|
| 28 |
+
def create_database(
|
| 29 |
+
self, id: UUID, name: str, tenant: str = DEFAULT_TENANT
|
| 30 |
+
) -> None:
|
| 31 |
+
"""Create a new database in the System database. Raises an Error if the Database
|
| 32 |
+
already exists."""
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
@abstractmethod
|
| 36 |
+
def get_database(self, name: str, tenant: str = DEFAULT_TENANT) -> Database:
|
| 37 |
+
"""Get a database by name and tenant. Raises an Error if the Database does not
|
| 38 |
+
exist."""
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
@abstractmethod
|
| 42 |
+
def delete_database(self, name: str, tenant: str = DEFAULT_TENANT) -> None:
|
| 43 |
+
"""Delete a database."""
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
@abstractmethod
|
| 47 |
+
def list_databases(
|
| 48 |
+
self,
|
| 49 |
+
limit: Optional[int] = None,
|
| 50 |
+
offset: Optional[int] = None,
|
| 51 |
+
tenant: str = DEFAULT_TENANT,
|
| 52 |
+
) -> Sequence[Database]:
|
| 53 |
+
"""List all databases for a tenant."""
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
@abstractmethod
|
| 57 |
+
def create_tenant(self, name: str) -> None:
|
| 58 |
+
"""Create a new tenant in the System database. The name must be unique.
|
| 59 |
+
Raises an Error if the Tenant already exists."""
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
@abstractmethod
|
| 63 |
+
def get_tenant(self, name: str) -> Tenant:
|
| 64 |
+
"""Get a tenant by name. Raises an Error if the Tenant does not exist."""
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
# TODO: Investigate and remove this method, as segment creation is done as
|
| 68 |
+
# part of collection creation.
|
| 69 |
+
@abstractmethod
|
| 70 |
+
def create_segment(self, segment: Segment) -> None:
|
| 71 |
+
"""Create a new segment in the System database. Raises an Error if the ID
|
| 72 |
+
already exists."""
|
| 73 |
+
pass
|
| 74 |
+
|
| 75 |
+
@abstractmethod
|
| 76 |
+
def delete_segment(self, collection: UUID, id: UUID) -> None:
|
| 77 |
+
"""Delete a segment from the System database."""
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
@abstractmethod
|
| 81 |
+
def get_segments(
|
| 82 |
+
self,
|
| 83 |
+
collection: UUID,
|
| 84 |
+
id: Optional[UUID] = None,
|
| 85 |
+
type: Optional[str] = None,
|
| 86 |
+
scope: Optional[SegmentScope] = None,
|
| 87 |
+
) -> Sequence[Segment]:
|
| 88 |
+
"""Find segments by id, type, scope or collection."""
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
@abstractmethod
|
| 92 |
+
def update_segment(
|
| 93 |
+
self,
|
| 94 |
+
collection: UUID,
|
| 95 |
+
id: UUID,
|
| 96 |
+
metadata: OptionalArgument[Optional[UpdateMetadata]] = Unspecified(),
|
| 97 |
+
) -> None:
|
| 98 |
+
"""Update a segment. Unspecified fields will be left unchanged. For the
|
| 99 |
+
metadata, keys with None values will be removed and keys not present in the
|
| 100 |
+
UpdateMetadata dict will be left unchanged."""
|
| 101 |
+
pass
|
| 102 |
+
|
| 103 |
+
@abstractmethod
|
| 104 |
+
def create_collection(
|
| 105 |
+
self,
|
| 106 |
+
id: UUID,
|
| 107 |
+
name: str,
|
| 108 |
+
schema: Optional[Schema],
|
| 109 |
+
configuration: CreateCollectionConfiguration,
|
| 110 |
+
segments: Sequence[Segment],
|
| 111 |
+
metadata: Optional[Metadata] = None,
|
| 112 |
+
dimension: Optional[int] = None,
|
| 113 |
+
get_or_create: bool = False,
|
| 114 |
+
tenant: str = DEFAULT_TENANT,
|
| 115 |
+
database: str = DEFAULT_DATABASE,
|
| 116 |
+
) -> Tuple[Collection, bool]:
|
| 117 |
+
"""Create a new collection and associated resources
|
| 118 |
+
in the SysDB. If get_or_create is True, the
|
| 119 |
+
collection will be created if one with the same name does not exist.
|
| 120 |
+
The metadata will be updated using the same protocol as update_collection. If get_or_create
|
| 121 |
+
is False and the collection already exists, an error will be raised.
|
| 122 |
+
|
| 123 |
+
Returns a tuple of the created collection and a boolean indicating whether the
|
| 124 |
+
collection was created or not.
|
| 125 |
+
"""
|
| 126 |
+
pass
|
| 127 |
+
|
| 128 |
+
@abstractmethod
|
| 129 |
+
def delete_collection(
|
| 130 |
+
self,
|
| 131 |
+
id: UUID,
|
| 132 |
+
tenant: str = DEFAULT_TENANT,
|
| 133 |
+
database: str = DEFAULT_DATABASE,
|
| 134 |
+
) -> None:
|
| 135 |
+
"""Delete a collection, all associated segments and any associate resources (log stream)
|
| 136 |
+
from the SysDB and the system at large."""
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
@abstractmethod
|
| 140 |
+
def get_collections(
|
| 141 |
+
self,
|
| 142 |
+
id: Optional[UUID] = None,
|
| 143 |
+
name: Optional[str] = None,
|
| 144 |
+
tenant: str = DEFAULT_TENANT,
|
| 145 |
+
database: str = DEFAULT_DATABASE,
|
| 146 |
+
limit: Optional[int] = None,
|
| 147 |
+
offset: Optional[int] = None,
|
| 148 |
+
) -> Sequence[Collection]:
|
| 149 |
+
"""Find collections by id or name. If name is provided, tenant and database must also be provided."""
|
| 150 |
+
pass
|
| 151 |
+
|
| 152 |
+
@abstractmethod
|
| 153 |
+
def count_collections(
|
| 154 |
+
self,
|
| 155 |
+
tenant: str = DEFAULT_TENANT,
|
| 156 |
+
database: Optional[str] = None,
|
| 157 |
+
) -> int:
|
| 158 |
+
"""Gets the number of collections for the (tenant, database) combination."""
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
@abstractmethod
|
| 162 |
+
def get_collection_with_segments(
|
| 163 |
+
self, collection_id: UUID
|
| 164 |
+
) -> CollectionAndSegments:
|
| 165 |
+
"""Get a consistent snapshot of a collection by id. This will return a collection with segment
|
| 166 |
+
information that matches the collection version and log position.
|
| 167 |
+
"""
|
| 168 |
+
pass
|
| 169 |
+
|
| 170 |
+
@abstractmethod
|
| 171 |
+
def update_collection(
|
| 172 |
+
self,
|
| 173 |
+
id: UUID,
|
| 174 |
+
name: OptionalArgument[str] = Unspecified(),
|
| 175 |
+
dimension: OptionalArgument[Optional[int]] = Unspecified(),
|
| 176 |
+
metadata: OptionalArgument[Optional[UpdateMetadata]] = Unspecified(),
|
| 177 |
+
configuration: OptionalArgument[
|
| 178 |
+
Optional[UpdateCollectionConfiguration]
|
| 179 |
+
] = Unspecified(),
|
| 180 |
+
) -> None:
|
| 181 |
+
"""Update a collection. Unspecified fields will be left unchanged. For metadata,
|
| 182 |
+
keys with None values will be removed and keys not present in the UpdateMetadata
|
| 183 |
+
dict will be left unchanged."""
|
| 184 |
+
pass
|
| 185 |
+
|
| 186 |
+
@abstractmethod
|
| 187 |
+
def get_collection_size(self, id: UUID) -> int:
|
| 188 |
+
"""Returns the number of records in a collection."""
|
| 189 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/execution/__init__.py
ADDED
|
File without changes
|
python/user_packages/Python313/site-packages/chromadb/experimental/density_relevance.ipynb
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
python/user_packages/Python313/site-packages/chromadb/ingest/__init__.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractmethod
|
| 2 |
+
from typing import Callable, Optional, Sequence
|
| 3 |
+
from chromadb.types import (
|
| 4 |
+
OperationRecord,
|
| 5 |
+
LogRecord,
|
| 6 |
+
SeqId,
|
| 7 |
+
Vector,
|
| 8 |
+
ScalarEncoding,
|
| 9 |
+
)
|
| 10 |
+
from chromadb.config import Component
|
| 11 |
+
from uuid import UUID
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def encode_vector(vector: Vector, encoding: ScalarEncoding) -> bytes:
|
| 16 |
+
"""Encode a vector into a byte array."""
|
| 17 |
+
|
| 18 |
+
if encoding == ScalarEncoding.FLOAT32:
|
| 19 |
+
return np.array(vector, dtype=np.float32).tobytes()
|
| 20 |
+
elif encoding == ScalarEncoding.INT32:
|
| 21 |
+
return np.array(vector, dtype=np.int32).tobytes()
|
| 22 |
+
else:
|
| 23 |
+
raise ValueError(f"Unsupported encoding: {encoding.value}")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def decode_vector(vector: bytes, encoding: ScalarEncoding) -> Vector:
|
| 27 |
+
"""Decode a byte array into a vector"""
|
| 28 |
+
|
| 29 |
+
if encoding == ScalarEncoding.FLOAT32:
|
| 30 |
+
return np.frombuffer(vector, dtype=np.float32)
|
| 31 |
+
elif encoding == ScalarEncoding.INT32:
|
| 32 |
+
return np.frombuffer(vector, dtype=np.float32)
|
| 33 |
+
else:
|
| 34 |
+
raise ValueError(f"Unsupported encoding: {encoding.value}")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class Producer(Component):
|
| 38 |
+
"""Interface for writing embeddings to an ingest stream"""
|
| 39 |
+
|
| 40 |
+
@abstractmethod
|
| 41 |
+
def delete_log(self, collection_id: UUID) -> None:
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
@abstractmethod
|
| 45 |
+
def purge_log(self, collection_id: UUID) -> None:
|
| 46 |
+
"""Truncates the log for the given collection, removing all seen records."""
|
| 47 |
+
pass
|
| 48 |
+
|
| 49 |
+
@abstractmethod
|
| 50 |
+
def submit_embedding(
|
| 51 |
+
self, collection_id: UUID, embedding: OperationRecord
|
| 52 |
+
) -> SeqId:
|
| 53 |
+
"""Add an embedding record to the given collections log. Returns the SeqID of the record."""
|
| 54 |
+
pass
|
| 55 |
+
|
| 56 |
+
@abstractmethod
|
| 57 |
+
def submit_embeddings(
|
| 58 |
+
self, collection_id: UUID, embeddings: Sequence[OperationRecord]
|
| 59 |
+
) -> Sequence[SeqId]:
|
| 60 |
+
"""Add a batch of embedding records to the given collections log. Returns the SeqIDs of
|
| 61 |
+
the records. The returned SeqIDs will be in the same order as the given
|
| 62 |
+
SubmitEmbeddingRecords. However, it is not guaranteed that the SeqIDs will be
|
| 63 |
+
processed in the same order as the given SubmitEmbeddingRecords. If the number
|
| 64 |
+
of records exceeds the maximum batch size, an exception will be thrown."""
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
@abstractmethod
|
| 69 |
+
def max_batch_size(self) -> int:
|
| 70 |
+
"""Return the maximum number of records that can be submitted in a single call
|
| 71 |
+
to submit_embeddings."""
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
ConsumerCallbackFn = Callable[[Sequence[LogRecord]], None]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class Consumer(Component):
|
| 79 |
+
"""Interface for reading embeddings off an ingest stream"""
|
| 80 |
+
|
| 81 |
+
@abstractmethod
|
| 82 |
+
def subscribe(
|
| 83 |
+
self,
|
| 84 |
+
collection_id: UUID,
|
| 85 |
+
consume_fn: ConsumerCallbackFn,
|
| 86 |
+
start: Optional[SeqId] = None,
|
| 87 |
+
end: Optional[SeqId] = None,
|
| 88 |
+
id: Optional[UUID] = None,
|
| 89 |
+
) -> UUID:
|
| 90 |
+
"""Register a function that will be called to receive embeddings for a given
|
| 91 |
+
collections log stream. The given function may be called any number of times, with any number of
|
| 92 |
+
records, and may be called concurrently.
|
| 93 |
+
|
| 94 |
+
Only records between start (exclusive) and end (inclusive) SeqIDs will be
|
| 95 |
+
returned. If start is None, the first record returned will be the next record
|
| 96 |
+
generated, not including those generated before creating the subscription. If
|
| 97 |
+
end is None, the consumer will consume indefinitely, otherwise it will
|
| 98 |
+
automatically be unsubscribed when the end SeqID is reached.
|
| 99 |
+
|
| 100 |
+
If the function throws an exception, the function may be called again with the
|
| 101 |
+
same or different records.
|
| 102 |
+
|
| 103 |
+
Takes an optional UUID as a unique subscription ID. If no ID is provided, a new
|
| 104 |
+
ID will be generated and returned."""
|
| 105 |
+
pass
|
| 106 |
+
|
| 107 |
+
@abstractmethod
|
| 108 |
+
def unsubscribe(self, subscription_id: UUID) -> None:
|
| 109 |
+
"""Unregister a subscription. The consume function will no longer be invoked,
|
| 110 |
+
and resources associated with the subscription will be released."""
|
| 111 |
+
pass
|
| 112 |
+
|
| 113 |
+
@abstractmethod
|
| 114 |
+
def min_seqid(self) -> SeqId:
|
| 115 |
+
"""Return the minimum possible SeqID in this implementation."""
|
| 116 |
+
pass
|
| 117 |
+
|
| 118 |
+
@abstractmethod
|
| 119 |
+
def max_seqid(self) -> SeqId:
|
| 120 |
+
"""Return the maximum possible SeqID in this implementation."""
|
| 121 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/logservice/logservice.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
|
| 3 |
+
from chromadb.proto.utils import RetryOnRpcErrorClientInterceptor
|
| 4 |
+
import grpc
|
| 5 |
+
import time
|
| 6 |
+
from chromadb.ingest import (
|
| 7 |
+
Producer,
|
| 8 |
+
Consumer,
|
| 9 |
+
ConsumerCallbackFn,
|
| 10 |
+
)
|
| 11 |
+
from chromadb.proto.convert import to_proto_submit
|
| 12 |
+
from chromadb.proto.logservice_pb2 import PushLogsRequest, PullLogsRequest, LogRecord
|
| 13 |
+
from chromadb.proto.logservice_pb2_grpc import LogServiceStub
|
| 14 |
+
from chromadb.telemetry.opentelemetry.grpc import OtelInterceptor
|
| 15 |
+
from chromadb.types import (
|
| 16 |
+
OperationRecord,
|
| 17 |
+
SeqId,
|
| 18 |
+
)
|
| 19 |
+
from chromadb.config import System
|
| 20 |
+
from chromadb.telemetry.opentelemetry import (
|
| 21 |
+
OpenTelemetryClient,
|
| 22 |
+
OpenTelemetryGranularity,
|
| 23 |
+
add_attributes_to_current_span,
|
| 24 |
+
trace_method,
|
| 25 |
+
)
|
| 26 |
+
from overrides import override
|
| 27 |
+
from typing import Sequence, Optional, cast
|
| 28 |
+
from uuid import UUID
|
| 29 |
+
import logging
|
| 30 |
+
|
| 31 |
+
logger = logging.getLogger(__name__)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class LogService(Producer, Consumer):
|
| 35 |
+
"""
|
| 36 |
+
Distributed Chroma Log Service
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
_log_service_stub: LogServiceStub
|
| 40 |
+
_request_timeout_seconds: int
|
| 41 |
+
_channel: grpc.Channel
|
| 42 |
+
_log_service_url: str
|
| 43 |
+
_log_service_port: int
|
| 44 |
+
|
| 45 |
+
def __init__(self, system: System):
|
| 46 |
+
self._log_service_url = system.settings.require("chroma_logservice_host")
|
| 47 |
+
self._log_service_port = system.settings.require("chroma_logservice_port")
|
| 48 |
+
self._request_timeout_seconds = system.settings.require(
|
| 49 |
+
"chroma_logservice_request_timeout_seconds"
|
| 50 |
+
)
|
| 51 |
+
self._opentelemetry_client = system.require(OpenTelemetryClient)
|
| 52 |
+
super().__init__(system)
|
| 53 |
+
|
| 54 |
+
@trace_method("LogService.start", OpenTelemetryGranularity.ALL)
|
| 55 |
+
@override
|
| 56 |
+
def start(self) -> None:
|
| 57 |
+
self._channel = grpc.insecure_channel(
|
| 58 |
+
f"{self._log_service_url}:{self._log_service_port}",
|
| 59 |
+
)
|
| 60 |
+
interceptors = [OtelInterceptor(), RetryOnRpcErrorClientInterceptor()]
|
| 61 |
+
self._channel = grpc.intercept_channel(self._channel, *interceptors)
|
| 62 |
+
self._log_service_stub = LogServiceStub(self._channel) # type: ignore
|
| 63 |
+
super().start()
|
| 64 |
+
|
| 65 |
+
@trace_method("LogService.stop", OpenTelemetryGranularity.ALL)
|
| 66 |
+
@override
|
| 67 |
+
def stop(self) -> None:
|
| 68 |
+
self._channel.close()
|
| 69 |
+
super().stop()
|
| 70 |
+
|
| 71 |
+
@trace_method("LogService.reset_state", OpenTelemetryGranularity.ALL)
|
| 72 |
+
@override
|
| 73 |
+
def reset_state(self) -> None:
|
| 74 |
+
super().reset_state()
|
| 75 |
+
|
| 76 |
+
@trace_method("LogService.delete_log", OpenTelemetryGranularity.ALL)
|
| 77 |
+
@override
|
| 78 |
+
def delete_log(self, collection_id: UUID) -> None:
|
| 79 |
+
raise NotImplementedError("Not implemented")
|
| 80 |
+
|
| 81 |
+
@trace_method("LogService.purge_log", OpenTelemetryGranularity.ALL)
|
| 82 |
+
@override
|
| 83 |
+
def purge_log(self, collection_id: UUID) -> None:
|
| 84 |
+
raise NotImplementedError("Not implemented")
|
| 85 |
+
|
| 86 |
+
@trace_method("LogService.submit_embedding", OpenTelemetryGranularity.ALL)
|
| 87 |
+
@override
|
| 88 |
+
def submit_embedding(
|
| 89 |
+
self, collection_id: UUID, embedding: OperationRecord
|
| 90 |
+
) -> SeqId:
|
| 91 |
+
if not self._running:
|
| 92 |
+
raise RuntimeError("Component not running")
|
| 93 |
+
|
| 94 |
+
return self.submit_embeddings(collection_id, [embedding])[0]
|
| 95 |
+
|
| 96 |
+
@trace_method("LogService.submit_embeddings", OpenTelemetryGranularity.ALL)
|
| 97 |
+
@override
|
| 98 |
+
def submit_embeddings(
|
| 99 |
+
self, collection_id: UUID, embeddings: Sequence[OperationRecord]
|
| 100 |
+
) -> Sequence[SeqId]:
|
| 101 |
+
logger.info(
|
| 102 |
+
f"Submitting {len(embeddings)} embeddings to log for collection {collection_id}"
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
add_attributes_to_current_span(
|
| 106 |
+
{
|
| 107 |
+
"records_count": len(embeddings),
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
if not self._running:
|
| 112 |
+
raise RuntimeError("Component not running")
|
| 113 |
+
|
| 114 |
+
if len(embeddings) == 0:
|
| 115 |
+
return []
|
| 116 |
+
|
| 117 |
+
# push records to the log service
|
| 118 |
+
counts = []
|
| 119 |
+
protos_to_submit = [to_proto_submit(record) for record in embeddings]
|
| 120 |
+
counts.append(
|
| 121 |
+
self.push_logs(
|
| 122 |
+
collection_id,
|
| 123 |
+
cast(Sequence[OperationRecord], protos_to_submit),
|
| 124 |
+
)
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# This returns counts, which is completely incorrect
|
| 128 |
+
# TODO: Fix this
|
| 129 |
+
return counts
|
| 130 |
+
|
| 131 |
+
@trace_method("LogService.subscribe", OpenTelemetryGranularity.ALL)
|
| 132 |
+
@override
|
| 133 |
+
def subscribe(
|
| 134 |
+
self,
|
| 135 |
+
collection_id: UUID,
|
| 136 |
+
consume_fn: ConsumerCallbackFn,
|
| 137 |
+
start: Optional[SeqId] = None,
|
| 138 |
+
end: Optional[SeqId] = None,
|
| 139 |
+
id: Optional[UUID] = None,
|
| 140 |
+
) -> UUID:
|
| 141 |
+
logger.info(f"Subscribing to log for {collection_id}, noop for logservice")
|
| 142 |
+
return UUID(int=0)
|
| 143 |
+
|
| 144 |
+
@trace_method("LogService.unsubscribe", OpenTelemetryGranularity.ALL)
|
| 145 |
+
@override
|
| 146 |
+
def unsubscribe(self, subscription_id: UUID) -> None:
|
| 147 |
+
logger.info(f"Unsubscribing from {subscription_id}, noop for logservice")
|
| 148 |
+
|
| 149 |
+
@override
|
| 150 |
+
def min_seqid(self) -> SeqId:
|
| 151 |
+
return 0
|
| 152 |
+
|
| 153 |
+
@override
|
| 154 |
+
def max_seqid(self) -> SeqId:
|
| 155 |
+
return sys.maxsize
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
@override
|
| 159 |
+
def max_batch_size(self) -> int:
|
| 160 |
+
return 100
|
| 161 |
+
|
| 162 |
+
def push_logs(self, collection_id: UUID, records: Sequence[OperationRecord]) -> int:
|
| 163 |
+
request = PushLogsRequest(collection_id=str(collection_id), records=records)
|
| 164 |
+
response = self._log_service_stub.PushLogs(
|
| 165 |
+
request, timeout=self._request_timeout_seconds
|
| 166 |
+
)
|
| 167 |
+
return response.record_count # type: ignore
|
| 168 |
+
|
| 169 |
+
def pull_logs(
|
| 170 |
+
self, collection_id: UUID, start_offset: int, batch_size: int
|
| 171 |
+
) -> Sequence[LogRecord]:
|
| 172 |
+
request = PullLogsRequest(
|
| 173 |
+
collection_id=str(collection_id),
|
| 174 |
+
start_from_offset=start_offset,
|
| 175 |
+
batch_size=batch_size,
|
| 176 |
+
end_timestamp=time.time_ns(),
|
| 177 |
+
)
|
| 178 |
+
response = self._log_service_stub.PullLogs(
|
| 179 |
+
request, timeout=self._request_timeout_seconds
|
| 180 |
+
)
|
| 181 |
+
return response.records # type: ignore
|
python/user_packages/Python313/site-packages/chromadb/migrations/__init__.py
ADDED
|
File without changes
|
python/user_packages/Python313/site-packages/chromadb/proto/.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*_pb2.py*
|
| 2 |
+
*_pb2_grpc.py
|
python/user_packages/Python313/site-packages/chromadb/proto/__init__.py
ADDED
|
File without changes
|
python/user_packages/Python313/site-packages/chromadb/proto/convert.py
ADDED
|
@@ -0,0 +1,688 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Dict, Optional, Sequence, Tuple, TypedDict, Union, cast
|
| 2 |
+
from uuid import UUID
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from numpy.typing import NDArray
|
| 7 |
+
|
| 8 |
+
import chromadb.proto.chroma_pb2 as chroma_pb
|
| 9 |
+
import chromadb.proto.query_executor_pb2 as query_pb
|
| 10 |
+
from chromadb.api.collection_configuration import (
|
| 11 |
+
collection_configuration_to_json_str,
|
| 12 |
+
)
|
| 13 |
+
from chromadb.api.types import Embedding, Where, WhereDocument
|
| 14 |
+
from chromadb.execution.expression.operator import (
|
| 15 |
+
KNN,
|
| 16 |
+
Filter,
|
| 17 |
+
Limit,
|
| 18 |
+
Projection,
|
| 19 |
+
Scan,
|
| 20 |
+
)
|
| 21 |
+
from chromadb.execution.expression.plan import CountPlan, GetPlan, KNNPlan
|
| 22 |
+
from chromadb.types import (
|
| 23 |
+
Collection,
|
| 24 |
+
LogRecord,
|
| 25 |
+
Metadata,
|
| 26 |
+
Operation,
|
| 27 |
+
OperationRecord,
|
| 28 |
+
RequestVersionContext,
|
| 29 |
+
ScalarEncoding,
|
| 30 |
+
Segment,
|
| 31 |
+
SegmentScope,
|
| 32 |
+
SeqId,
|
| 33 |
+
UpdateMetadata,
|
| 34 |
+
Vector,
|
| 35 |
+
VectorEmbeddingRecord,
|
| 36 |
+
VectorQueryResult,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class ProjectionRecord(TypedDict):
|
| 41 |
+
id: str
|
| 42 |
+
document: Optional[str]
|
| 43 |
+
embedding: Optional[Vector]
|
| 44 |
+
metadata: Optional[Metadata]
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class KNNProjectionRecord(TypedDict):
|
| 48 |
+
record: ProjectionRecord
|
| 49 |
+
distance: Optional[float]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# TODO: Unit tests for this file, handling optional states etc
|
| 53 |
+
def to_proto_vector(vector: Vector, encoding: ScalarEncoding) -> chroma_pb.Vector:
|
| 54 |
+
if encoding == ScalarEncoding.FLOAT32:
|
| 55 |
+
as_bytes = np.array(vector, dtype=np.float32).tobytes()
|
| 56 |
+
proto_encoding = chroma_pb.ScalarEncoding.FLOAT32
|
| 57 |
+
elif encoding == ScalarEncoding.INT32:
|
| 58 |
+
as_bytes = np.array(vector, dtype=np.int32).tobytes()
|
| 59 |
+
proto_encoding = chroma_pb.ScalarEncoding.INT32
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError(
|
| 62 |
+
f"Unknown encoding {encoding}, expected one of {ScalarEncoding.FLOAT32} \
|
| 63 |
+
or {ScalarEncoding.INT32}"
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
return chroma_pb.Vector(
|
| 67 |
+
dimension=vector.size, vector=as_bytes, encoding=proto_encoding
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def from_proto_vector(vector: chroma_pb.Vector) -> Tuple[Embedding, ScalarEncoding]:
|
| 72 |
+
encoding = vector.encoding
|
| 73 |
+
as_array: Union[NDArray[np.int32], NDArray[np.float32]]
|
| 74 |
+
if encoding == chroma_pb.ScalarEncoding.FLOAT32:
|
| 75 |
+
as_array = np.frombuffer(vector.vector, dtype=np.float32)
|
| 76 |
+
out_encoding = ScalarEncoding.FLOAT32
|
| 77 |
+
elif encoding == chroma_pb.ScalarEncoding.INT32:
|
| 78 |
+
as_array = np.frombuffer(vector.vector, dtype=np.int32)
|
| 79 |
+
out_encoding = ScalarEncoding.INT32
|
| 80 |
+
else:
|
| 81 |
+
raise ValueError(
|
| 82 |
+
f"Unknown encoding {encoding}, expected one of \
|
| 83 |
+
{chroma_pb.ScalarEncoding.FLOAT32} or {chroma_pb.ScalarEncoding.INT32}"
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
return (as_array, out_encoding)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def from_proto_operation(operation: chroma_pb.Operation) -> Operation:
|
| 90 |
+
if operation == chroma_pb.Operation.ADD:
|
| 91 |
+
return Operation.ADD
|
| 92 |
+
elif operation == chroma_pb.Operation.UPDATE:
|
| 93 |
+
return Operation.UPDATE
|
| 94 |
+
elif operation == chroma_pb.Operation.UPSERT:
|
| 95 |
+
return Operation.UPSERT
|
| 96 |
+
elif operation == chroma_pb.Operation.DELETE:
|
| 97 |
+
return Operation.DELETE
|
| 98 |
+
else:
|
| 99 |
+
# TODO: full error
|
| 100 |
+
raise RuntimeError(f"Unknown operation {operation}")
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def from_proto_metadata(metadata: chroma_pb.UpdateMetadata) -> Optional[Metadata]:
|
| 104 |
+
return cast(Optional[Metadata], _from_proto_metadata_handle_none(metadata, False))
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def from_proto_update_metadata(
|
| 108 |
+
metadata: chroma_pb.UpdateMetadata,
|
| 109 |
+
) -> Optional[UpdateMetadata]:
|
| 110 |
+
return cast(
|
| 111 |
+
Optional[UpdateMetadata], _from_proto_metadata_handle_none(metadata, True)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _from_proto_metadata_handle_none(
|
| 116 |
+
metadata: chroma_pb.UpdateMetadata, is_update: bool
|
| 117 |
+
) -> Optional[Union[UpdateMetadata, Metadata]]:
|
| 118 |
+
if not metadata.metadata:
|
| 119 |
+
return None
|
| 120 |
+
out_metadata: Dict[str, Union[str, int, float, bool, None]] = {}
|
| 121 |
+
for key, value in metadata.metadata.items():
|
| 122 |
+
if value.HasField("bool_value"):
|
| 123 |
+
out_metadata[key] = value.bool_value
|
| 124 |
+
elif value.HasField("string_value"):
|
| 125 |
+
out_metadata[key] = value.string_value
|
| 126 |
+
elif value.HasField("int_value"):
|
| 127 |
+
out_metadata[key] = value.int_value
|
| 128 |
+
elif value.HasField("float_value"):
|
| 129 |
+
out_metadata[key] = value.float_value
|
| 130 |
+
elif is_update:
|
| 131 |
+
out_metadata[key] = None
|
| 132 |
+
else:
|
| 133 |
+
raise ValueError(f"Metadata key {key} value cannot be None")
|
| 134 |
+
return out_metadata
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def to_proto_update_metadata(metadata: UpdateMetadata) -> chroma_pb.UpdateMetadata:
|
| 138 |
+
return chroma_pb.UpdateMetadata(
|
| 139 |
+
metadata={k: to_proto_metadata_update_value(v) for k, v in metadata.items()}
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def from_proto_submit(
|
| 144 |
+
operation_record: chroma_pb.OperationRecord, seq_id: SeqId
|
| 145 |
+
) -> LogRecord:
|
| 146 |
+
embedding, encoding = from_proto_vector(operation_record.vector)
|
| 147 |
+
record = LogRecord(
|
| 148 |
+
log_offset=seq_id,
|
| 149 |
+
record=OperationRecord(
|
| 150 |
+
id=operation_record.id,
|
| 151 |
+
embedding=embedding,
|
| 152 |
+
encoding=encoding,
|
| 153 |
+
metadata=from_proto_update_metadata(operation_record.metadata),
|
| 154 |
+
operation=from_proto_operation(operation_record.operation),
|
| 155 |
+
),
|
| 156 |
+
)
|
| 157 |
+
return record
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def from_proto_segment(segment: chroma_pb.Segment) -> Segment:
|
| 161 |
+
return Segment(
|
| 162 |
+
id=UUID(hex=segment.id),
|
| 163 |
+
type=segment.type,
|
| 164 |
+
scope=from_proto_segment_scope(segment.scope),
|
| 165 |
+
collection=UUID(hex=segment.collection),
|
| 166 |
+
metadata=from_proto_metadata(segment.metadata)
|
| 167 |
+
if segment.HasField("metadata")
|
| 168 |
+
else None,
|
| 169 |
+
file_paths={
|
| 170 |
+
name: [path for path in paths.paths]
|
| 171 |
+
for name, paths in segment.file_paths.items()
|
| 172 |
+
},
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def to_proto_segment(segment: Segment) -> chroma_pb.Segment:
|
| 177 |
+
return chroma_pb.Segment(
|
| 178 |
+
id=segment["id"].hex,
|
| 179 |
+
type=segment["type"],
|
| 180 |
+
scope=to_proto_segment_scope(segment["scope"]),
|
| 181 |
+
collection=segment["collection"].hex,
|
| 182 |
+
metadata=None
|
| 183 |
+
if segment["metadata"] is None
|
| 184 |
+
else to_proto_update_metadata(segment["metadata"]),
|
| 185 |
+
file_paths={
|
| 186 |
+
name: chroma_pb.FilePaths(paths=paths)
|
| 187 |
+
for name, paths in segment["file_paths"].items()
|
| 188 |
+
},
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def from_proto_segment_scope(segment_scope: chroma_pb.SegmentScope) -> SegmentScope:
|
| 193 |
+
if segment_scope == chroma_pb.SegmentScope.VECTOR:
|
| 194 |
+
return SegmentScope.VECTOR
|
| 195 |
+
elif segment_scope == chroma_pb.SegmentScope.METADATA:
|
| 196 |
+
return SegmentScope.METADATA
|
| 197 |
+
elif segment_scope == chroma_pb.SegmentScope.RECORD:
|
| 198 |
+
return SegmentScope.RECORD
|
| 199 |
+
else:
|
| 200 |
+
raise RuntimeError(f"Unknown segment scope {segment_scope}")
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def to_proto_segment_scope(segment_scope: SegmentScope) -> chroma_pb.SegmentScope:
|
| 204 |
+
if segment_scope == SegmentScope.VECTOR:
|
| 205 |
+
return chroma_pb.SegmentScope.VECTOR
|
| 206 |
+
elif segment_scope == SegmentScope.METADATA:
|
| 207 |
+
return chroma_pb.SegmentScope.METADATA
|
| 208 |
+
elif segment_scope == SegmentScope.RECORD:
|
| 209 |
+
return chroma_pb.SegmentScope.RECORD
|
| 210 |
+
else:
|
| 211 |
+
raise RuntimeError(f"Unknown segment scope {segment_scope}")
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def to_proto_metadata_update_value(
|
| 215 |
+
value: Union[str, int, float, bool, None]
|
| 216 |
+
) -> chroma_pb.UpdateMetadataValue:
|
| 217 |
+
# Be careful with the order here. Since bools are a subtype of int in python,
|
| 218 |
+
# isinstance(value, bool) and isinstance(value, int) both return true
|
| 219 |
+
# for a value of bool type.
|
| 220 |
+
if isinstance(value, bool):
|
| 221 |
+
return chroma_pb.UpdateMetadataValue(bool_value=value)
|
| 222 |
+
elif isinstance(value, str):
|
| 223 |
+
return chroma_pb.UpdateMetadataValue(string_value=value)
|
| 224 |
+
elif isinstance(value, int):
|
| 225 |
+
return chroma_pb.UpdateMetadataValue(int_value=value)
|
| 226 |
+
elif isinstance(value, float):
|
| 227 |
+
return chroma_pb.UpdateMetadataValue(float_value=value)
|
| 228 |
+
# None is used to delete the metadata key.
|
| 229 |
+
elif value is None:
|
| 230 |
+
return chroma_pb.UpdateMetadataValue()
|
| 231 |
+
else:
|
| 232 |
+
raise ValueError(
|
| 233 |
+
f"Unknown metadata value type {type(value)}, expected one of str, int, \
|
| 234 |
+
float, or None"
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def from_proto_collection(collection: chroma_pb.Collection) -> Collection:
|
| 239 |
+
return Collection(
|
| 240 |
+
id=UUID(hex=collection.id),
|
| 241 |
+
name=collection.name,
|
| 242 |
+
configuration_json=json.loads(collection.configuration_json_str),
|
| 243 |
+
metadata=from_proto_metadata(collection.metadata)
|
| 244 |
+
if collection.HasField("metadata")
|
| 245 |
+
else None,
|
| 246 |
+
dimension=collection.dimension
|
| 247 |
+
if collection.HasField("dimension") and collection.dimension
|
| 248 |
+
else None,
|
| 249 |
+
database=collection.database,
|
| 250 |
+
tenant=collection.tenant,
|
| 251 |
+
version=collection.version,
|
| 252 |
+
log_position=collection.log_position,
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def to_proto_collection(collection: Collection) -> chroma_pb.Collection:
|
| 257 |
+
return chroma_pb.Collection(
|
| 258 |
+
id=collection["id"].hex,
|
| 259 |
+
name=collection["name"],
|
| 260 |
+
configuration_json_str=collection_configuration_to_json_str(
|
| 261 |
+
collection.get_configuration()
|
| 262 |
+
),
|
| 263 |
+
metadata=None
|
| 264 |
+
if collection["metadata"] is None
|
| 265 |
+
else to_proto_update_metadata(collection["metadata"]),
|
| 266 |
+
dimension=collection["dimension"],
|
| 267 |
+
tenant=collection["tenant"],
|
| 268 |
+
database=collection["database"],
|
| 269 |
+
log_position=collection["log_position"],
|
| 270 |
+
version=collection["version"],
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def to_proto_operation(operation: Operation) -> chroma_pb.Operation:
|
| 275 |
+
if operation == Operation.ADD:
|
| 276 |
+
return chroma_pb.Operation.ADD
|
| 277 |
+
elif operation == Operation.UPDATE:
|
| 278 |
+
return chroma_pb.Operation.UPDATE
|
| 279 |
+
elif operation == Operation.UPSERT:
|
| 280 |
+
return chroma_pb.Operation.UPSERT
|
| 281 |
+
elif operation == Operation.DELETE:
|
| 282 |
+
return chroma_pb.Operation.DELETE
|
| 283 |
+
else:
|
| 284 |
+
raise ValueError(
|
| 285 |
+
f"Unknown operation {operation}, expected one of {Operation.ADD}, \
|
| 286 |
+
{Operation.UPDATE}, {Operation.UPDATE}, or {Operation.DELETE}"
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def to_proto_submit(
|
| 291 |
+
submit_record: OperationRecord,
|
| 292 |
+
) -> chroma_pb.OperationRecord:
|
| 293 |
+
vector = None
|
| 294 |
+
if submit_record["embedding"] is not None and submit_record["encoding"] is not None:
|
| 295 |
+
vector = to_proto_vector(submit_record["embedding"], submit_record["encoding"])
|
| 296 |
+
|
| 297 |
+
metadata = None
|
| 298 |
+
if submit_record["metadata"] is not None:
|
| 299 |
+
metadata = to_proto_update_metadata(submit_record["metadata"])
|
| 300 |
+
|
| 301 |
+
return chroma_pb.OperationRecord(
|
| 302 |
+
id=submit_record["id"],
|
| 303 |
+
vector=vector,
|
| 304 |
+
metadata=metadata,
|
| 305 |
+
operation=to_proto_operation(submit_record["operation"]),
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def from_proto_vector_embedding_record(
|
| 310 |
+
embedding_record: chroma_pb.VectorEmbeddingRecord,
|
| 311 |
+
) -> VectorEmbeddingRecord:
|
| 312 |
+
return VectorEmbeddingRecord(
|
| 313 |
+
id=embedding_record.id,
|
| 314 |
+
embedding=from_proto_vector(embedding_record.vector)[0],
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
def to_proto_vector_embedding_record(
|
| 319 |
+
embedding_record: VectorEmbeddingRecord,
|
| 320 |
+
encoding: ScalarEncoding,
|
| 321 |
+
) -> chroma_pb.VectorEmbeddingRecord:
|
| 322 |
+
return chroma_pb.VectorEmbeddingRecord(
|
| 323 |
+
id=embedding_record["id"],
|
| 324 |
+
vector=to_proto_vector(embedding_record["embedding"], encoding),
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def from_proto_vector_query_result(
|
| 329 |
+
vector_query_result: chroma_pb.VectorQueryResult,
|
| 330 |
+
) -> VectorQueryResult:
|
| 331 |
+
return VectorQueryResult(
|
| 332 |
+
id=vector_query_result.id,
|
| 333 |
+
distance=vector_query_result.distance,
|
| 334 |
+
embedding=from_proto_vector(vector_query_result.vector)[0],
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def from_proto_request_version_context(
|
| 339 |
+
request_version_context: chroma_pb.RequestVersionContext,
|
| 340 |
+
) -> RequestVersionContext:
|
| 341 |
+
return RequestVersionContext(
|
| 342 |
+
collection_version=request_version_context.collection_version,
|
| 343 |
+
log_position=request_version_context.log_position,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def to_proto_request_version_context(
|
| 348 |
+
request_version_context: RequestVersionContext,
|
| 349 |
+
) -> chroma_pb.RequestVersionContext:
|
| 350 |
+
return chroma_pb.RequestVersionContext(
|
| 351 |
+
collection_version=request_version_context["collection_version"],
|
| 352 |
+
log_position=request_version_context["log_position"],
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def to_proto_where(where: Where) -> chroma_pb.Where:
|
| 357 |
+
response = chroma_pb.Where()
|
| 358 |
+
if len(where) != 1:
|
| 359 |
+
raise ValueError(f"Expected where to have exactly one operator, got {where}")
|
| 360 |
+
|
| 361 |
+
for key, value in where.items():
|
| 362 |
+
if not isinstance(key, str):
|
| 363 |
+
raise ValueError(f"Expected where key to be a str, got {key}")
|
| 364 |
+
|
| 365 |
+
if key == "$and" or key == "$or":
|
| 366 |
+
if not isinstance(value, list):
|
| 367 |
+
raise ValueError(
|
| 368 |
+
f"Expected where value for $and or $or to be a list of where expressions, got {value}"
|
| 369 |
+
)
|
| 370 |
+
children: chroma_pb.WhereChildren = chroma_pb.WhereChildren(
|
| 371 |
+
children=[to_proto_where(w) for w in value]
|
| 372 |
+
)
|
| 373 |
+
if key == "$and":
|
| 374 |
+
children.operator = chroma_pb.BooleanOperator.AND
|
| 375 |
+
else:
|
| 376 |
+
children.operator = chroma_pb.BooleanOperator.OR
|
| 377 |
+
|
| 378 |
+
response.children.CopyFrom(children)
|
| 379 |
+
return response
|
| 380 |
+
|
| 381 |
+
# At this point we know we're at a direct comparison. It can either
|
| 382 |
+
# be of the form {"key": "value"} or {"key": {"$operator": "value"}}.
|
| 383 |
+
|
| 384 |
+
dc = chroma_pb.DirectComparison()
|
| 385 |
+
dc.key = key
|
| 386 |
+
|
| 387 |
+
if not isinstance(value, dict):
|
| 388 |
+
# {'key': 'value'} case
|
| 389 |
+
if type(value) is str:
|
| 390 |
+
ssc = chroma_pb.SingleStringComparison()
|
| 391 |
+
ssc.value = value
|
| 392 |
+
ssc.comparator = chroma_pb.GenericComparator.EQ
|
| 393 |
+
dc.single_string_operand.CopyFrom(ssc)
|
| 394 |
+
elif type(value) is bool:
|
| 395 |
+
sbc = chroma_pb.SingleBoolComparison()
|
| 396 |
+
sbc.value = value
|
| 397 |
+
sbc.comparator = chroma_pb.GenericComparator.EQ
|
| 398 |
+
dc.single_bool_operand.CopyFrom(sbc)
|
| 399 |
+
elif type(value) is int:
|
| 400 |
+
sic = chroma_pb.SingleIntComparison()
|
| 401 |
+
sic.value = value
|
| 402 |
+
sic.generic_comparator = chroma_pb.GenericComparator.EQ
|
| 403 |
+
dc.single_int_operand.CopyFrom(sic)
|
| 404 |
+
elif type(value) is float:
|
| 405 |
+
sdc = chroma_pb.SingleDoubleComparison()
|
| 406 |
+
sdc.value = value
|
| 407 |
+
sdc.generic_comparator = chroma_pb.GenericComparator.EQ
|
| 408 |
+
dc.single_double_operand.CopyFrom(sdc)
|
| 409 |
+
else:
|
| 410 |
+
raise ValueError(
|
| 411 |
+
f"Expected where value to be a string, int, or float, got {value}"
|
| 412 |
+
)
|
| 413 |
+
else:
|
| 414 |
+
for operator, operand in value.items():
|
| 415 |
+
if operator in ["$in", "$nin"]:
|
| 416 |
+
if not isinstance(operand, list):
|
| 417 |
+
raise ValueError(
|
| 418 |
+
f"Expected where value for $in or $nin to be a list of values, got {value}"
|
| 419 |
+
)
|
| 420 |
+
if len(operand) == 0 or not all(
|
| 421 |
+
isinstance(x, type(operand[0])) for x in operand
|
| 422 |
+
):
|
| 423 |
+
raise ValueError(
|
| 424 |
+
f"Expected where operand value to be a non-empty list, and all values to be of the same type "
|
| 425 |
+
f"got {operand}"
|
| 426 |
+
)
|
| 427 |
+
list_operator = None
|
| 428 |
+
if operator == "$in":
|
| 429 |
+
list_operator = chroma_pb.ListOperator.IN
|
| 430 |
+
else:
|
| 431 |
+
list_operator = chroma_pb.ListOperator.NIN
|
| 432 |
+
if type(operand[0]) is str:
|
| 433 |
+
slo = chroma_pb.StringListComparison()
|
| 434 |
+
for x in operand:
|
| 435 |
+
slo.values.extend([x]) # type: ignore
|
| 436 |
+
slo.list_operator = list_operator
|
| 437 |
+
dc.string_list_operand.CopyFrom(slo)
|
| 438 |
+
elif type(operand[0]) is bool:
|
| 439 |
+
blo = chroma_pb.BoolListComparison()
|
| 440 |
+
for x in operand:
|
| 441 |
+
blo.values.extend([x]) # type: ignore
|
| 442 |
+
blo.list_operator = list_operator
|
| 443 |
+
dc.bool_list_operand.CopyFrom(blo)
|
| 444 |
+
elif type(operand[0]) is int:
|
| 445 |
+
ilo = chroma_pb.IntListComparison()
|
| 446 |
+
for x in operand:
|
| 447 |
+
ilo.values.extend([x]) # type: ignore
|
| 448 |
+
ilo.list_operator = list_operator
|
| 449 |
+
dc.int_list_operand.CopyFrom(ilo)
|
| 450 |
+
elif type(operand[0]) is float:
|
| 451 |
+
dlo = chroma_pb.DoubleListComparison()
|
| 452 |
+
for x in operand:
|
| 453 |
+
dlo.values.extend([x]) # type: ignore
|
| 454 |
+
dlo.list_operator = list_operator
|
| 455 |
+
dc.double_list_operand.CopyFrom(dlo)
|
| 456 |
+
else:
|
| 457 |
+
raise ValueError(
|
| 458 |
+
f"Expected where operand value to be a list of strings, ints, or floats, got {operand}"
|
| 459 |
+
)
|
| 460 |
+
elif operator in ["$eq", "$ne", "$gt", "$lt", "$gte", "$lte"]:
|
| 461 |
+
# Direct comparison to a single value.
|
| 462 |
+
if type(operand) is str:
|
| 463 |
+
ssc = chroma_pb.SingleStringComparison()
|
| 464 |
+
ssc.value = operand
|
| 465 |
+
if operator == "$eq":
|
| 466 |
+
ssc.comparator = chroma_pb.GenericComparator.EQ
|
| 467 |
+
elif operator == "$ne":
|
| 468 |
+
ssc.comparator = chroma_pb.GenericComparator.NE
|
| 469 |
+
else:
|
| 470 |
+
raise ValueError(
|
| 471 |
+
f"Expected where operator to be $eq or $ne, got {operator}"
|
| 472 |
+
)
|
| 473 |
+
dc.single_string_operand.CopyFrom(ssc)
|
| 474 |
+
elif type(operand) is bool:
|
| 475 |
+
sbc = chroma_pb.SingleBoolComparison()
|
| 476 |
+
sbc.value = operand
|
| 477 |
+
if operator == "$eq":
|
| 478 |
+
sbc.comparator = chroma_pb.GenericComparator.EQ
|
| 479 |
+
elif operator == "$ne":
|
| 480 |
+
sbc.comparator = chroma_pb.GenericComparator.NE
|
| 481 |
+
else:
|
| 482 |
+
raise ValueError(
|
| 483 |
+
f"Expected where operator to be $eq or $ne, got {operator}"
|
| 484 |
+
)
|
| 485 |
+
dc.single_bool_operand.CopyFrom(sbc)
|
| 486 |
+
elif type(operand) is int:
|
| 487 |
+
sic = chroma_pb.SingleIntComparison()
|
| 488 |
+
sic.value = operand
|
| 489 |
+
if operator == "$eq":
|
| 490 |
+
sic.generic_comparator = chroma_pb.GenericComparator.EQ
|
| 491 |
+
elif operator == "$ne":
|
| 492 |
+
sic.generic_comparator = chroma_pb.GenericComparator.NE
|
| 493 |
+
elif operator == "$gt":
|
| 494 |
+
sic.number_comparator = chroma_pb.NumberComparator.GT
|
| 495 |
+
elif operator == "$lt":
|
| 496 |
+
sic.number_comparator = chroma_pb.NumberComparator.LT
|
| 497 |
+
elif operator == "$gte":
|
| 498 |
+
sic.number_comparator = chroma_pb.NumberComparator.GTE
|
| 499 |
+
elif operator == "$lte":
|
| 500 |
+
sic.number_comparator = chroma_pb.NumberComparator.LTE
|
| 501 |
+
else:
|
| 502 |
+
raise ValueError(
|
| 503 |
+
f"Expected where operator to be one of $eq, $ne, $gt, $lt, $gte, $lte, got {operator}"
|
| 504 |
+
)
|
| 505 |
+
dc.single_int_operand.CopyFrom(sic)
|
| 506 |
+
elif type(operand) is float:
|
| 507 |
+
sfc = chroma_pb.SingleDoubleComparison()
|
| 508 |
+
sfc.value = operand
|
| 509 |
+
if operator == "$eq":
|
| 510 |
+
sfc.generic_comparator = chroma_pb.GenericComparator.EQ
|
| 511 |
+
elif operator == "$ne":
|
| 512 |
+
sfc.generic_comparator = chroma_pb.GenericComparator.NE
|
| 513 |
+
elif operator == "$gt":
|
| 514 |
+
sfc.number_comparator = chroma_pb.NumberComparator.GT
|
| 515 |
+
elif operator == "$lt":
|
| 516 |
+
sfc.number_comparator = chroma_pb.NumberComparator.LT
|
| 517 |
+
elif operator == "$gte":
|
| 518 |
+
sfc.number_comparator = chroma_pb.NumberComparator.GTE
|
| 519 |
+
elif operator == "$lte":
|
| 520 |
+
sfc.number_comparator = chroma_pb.NumberComparator.LTE
|
| 521 |
+
else:
|
| 522 |
+
raise ValueError(
|
| 523 |
+
f"Expected where operator to be one of $eq, $ne, $gt, $lt, $gte, $lte, got {operator}"
|
| 524 |
+
)
|
| 525 |
+
dc.single_double_operand.CopyFrom(sfc)
|
| 526 |
+
else:
|
| 527 |
+
raise ValueError(
|
| 528 |
+
f"Expected where operand value to be a string, int, or float, got {operand}"
|
| 529 |
+
)
|
| 530 |
+
else:
|
| 531 |
+
# This case should never happen, as we've already
|
| 532 |
+
# handled the case for direct comparisons.
|
| 533 |
+
pass
|
| 534 |
+
|
| 535 |
+
response.direct_comparison.CopyFrom(dc)
|
| 536 |
+
return response
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def to_proto_where_document(where_document: WhereDocument) -> chroma_pb.WhereDocument:
|
| 540 |
+
response = chroma_pb.WhereDocument()
|
| 541 |
+
if len(where_document) != 1:
|
| 542 |
+
raise ValueError(
|
| 543 |
+
f"Expected where_document to have exactly one operator, got {where_document}"
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
for operator, operand in where_document.items():
|
| 547 |
+
if operator == "$and" or operator == "$or":
|
| 548 |
+
# Nested "$and" or "$or" expression.
|
| 549 |
+
if not isinstance(operand, list):
|
| 550 |
+
raise ValueError(
|
| 551 |
+
f"Expected where_document value for $and or $or to be a list of where_document expressions, got {operand}"
|
| 552 |
+
)
|
| 553 |
+
children: chroma_pb.WhereDocumentChildren = chroma_pb.WhereDocumentChildren(
|
| 554 |
+
children=[to_proto_where_document(w) for w in operand]
|
| 555 |
+
)
|
| 556 |
+
if operator == "$and":
|
| 557 |
+
children.operator = chroma_pb.BooleanOperator.AND
|
| 558 |
+
else:
|
| 559 |
+
children.operator = chroma_pb.BooleanOperator.OR
|
| 560 |
+
|
| 561 |
+
response.children.CopyFrom(children)
|
| 562 |
+
else:
|
| 563 |
+
# Direct "$contains" or "$not_contains" comparison to a single
|
| 564 |
+
# value.
|
| 565 |
+
if not isinstance(operand, str):
|
| 566 |
+
raise ValueError(
|
| 567 |
+
f"Expected where_document operand to be a string, got {operand}"
|
| 568 |
+
)
|
| 569 |
+
dwd = chroma_pb.DirectWhereDocument()
|
| 570 |
+
dwd.document = operand
|
| 571 |
+
if operator == "$contains":
|
| 572 |
+
dwd.operator = chroma_pb.WhereDocumentOperator.CONTAINS
|
| 573 |
+
elif operator == "$not_contains":
|
| 574 |
+
dwd.operator = chroma_pb.WhereDocumentOperator.NOT_CONTAINS
|
| 575 |
+
else:
|
| 576 |
+
raise ValueError(
|
| 577 |
+
f"Expected where_document operator to be one of $contains, $not_contains, got {operator}"
|
| 578 |
+
)
|
| 579 |
+
response.direct.CopyFrom(dwd)
|
| 580 |
+
|
| 581 |
+
return response
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def to_proto_scan(scan: Scan) -> query_pb.ScanOperator:
|
| 585 |
+
return query_pb.ScanOperator(
|
| 586 |
+
collection=to_proto_collection(scan.collection),
|
| 587 |
+
knn=to_proto_segment(scan.knn),
|
| 588 |
+
metadata=to_proto_segment(scan.metadata),
|
| 589 |
+
record=to_proto_segment(scan.record),
|
| 590 |
+
)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def to_proto_filter(filter: Filter) -> query_pb.FilterOperator:
|
| 594 |
+
return query_pb.FilterOperator(
|
| 595 |
+
ids=chroma_pb.UserIds(ids=filter.user_ids)
|
| 596 |
+
if filter.user_ids is not None
|
| 597 |
+
else None,
|
| 598 |
+
where=to_proto_where(filter.where) if filter.where else None,
|
| 599 |
+
where_document=to_proto_where_document(filter.where_document)
|
| 600 |
+
if filter.where_document
|
| 601 |
+
else None,
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def to_proto_knn(knn: KNN) -> query_pb.KNNOperator:
|
| 606 |
+
return query_pb.KNNOperator(
|
| 607 |
+
embeddings=[
|
| 608 |
+
to_proto_vector(vector=embedding, encoding=ScalarEncoding.FLOAT32)
|
| 609 |
+
for embedding in knn.embeddings
|
| 610 |
+
],
|
| 611 |
+
fetch=knn.fetch,
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def to_proto_limit(limit: Limit) -> query_pb.LimitOperator:
|
| 616 |
+
return query_pb.LimitOperator(offset=limit.offset, limit=limit.limit)
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
def to_proto_projection(projection: Projection) -> query_pb.ProjectionOperator:
|
| 620 |
+
return query_pb.ProjectionOperator(
|
| 621 |
+
document=projection.document,
|
| 622 |
+
embedding=projection.embedding,
|
| 623 |
+
metadata=projection.metadata,
|
| 624 |
+
)
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def to_proto_knn_projection(projection: Projection) -> query_pb.KNNProjectionOperator:
|
| 628 |
+
return query_pb.KNNProjectionOperator(
|
| 629 |
+
projection=to_proto_projection(projection), distance=projection.rank
|
| 630 |
+
)
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
def to_proto_count_plan(count: CountPlan) -> query_pb.CountPlan:
|
| 634 |
+
return query_pb.CountPlan(scan=to_proto_scan(count.scan))
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def from_proto_count_result(result: query_pb.CountResult) -> int:
|
| 638 |
+
return result.count
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
def to_proto_get_plan(get: GetPlan) -> query_pb.GetPlan:
|
| 642 |
+
return query_pb.GetPlan(
|
| 643 |
+
scan=to_proto_scan(get.scan),
|
| 644 |
+
filter=to_proto_filter(get.filter),
|
| 645 |
+
limit=to_proto_limit(get.limit),
|
| 646 |
+
projection=to_proto_projection(get.projection),
|
| 647 |
+
)
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
def from_proto_projection_record(record: query_pb.ProjectionRecord) -> ProjectionRecord:
|
| 651 |
+
return ProjectionRecord(
|
| 652 |
+
id=record.id,
|
| 653 |
+
document=record.document if record.document else None,
|
| 654 |
+
embedding=from_proto_vector(record.embedding)[0]
|
| 655 |
+
if record.embedding is not None
|
| 656 |
+
else None,
|
| 657 |
+
metadata=from_proto_metadata(record.metadata),
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def from_proto_get_result(result: query_pb.GetResult) -> Sequence[ProjectionRecord]:
|
| 662 |
+
return [from_proto_projection_record(record) for record in result.records]
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def to_proto_knn_plan(knn: KNNPlan) -> query_pb.KNNPlan:
|
| 666 |
+
return query_pb.KNNPlan(
|
| 667 |
+
scan=to_proto_scan(knn.scan),
|
| 668 |
+
filter=to_proto_filter(knn.filter),
|
| 669 |
+
knn=to_proto_knn(knn.knn),
|
| 670 |
+
projection=to_proto_knn_projection(knn.projection),
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def from_proto_knn_projection_record(
|
| 675 |
+
record: query_pb.KNNProjectionRecord,
|
| 676 |
+
) -> KNNProjectionRecord:
|
| 677 |
+
return KNNProjectionRecord(
|
| 678 |
+
record=from_proto_projection_record(record.record), distance=record.distance
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def from_proto_knn_batch_result(
|
| 683 |
+
results: query_pb.KNNBatchResult,
|
| 684 |
+
) -> Sequence[Sequence[KNNProjectionRecord]]:
|
| 685 |
+
return [
|
| 686 |
+
[from_proto_knn_projection_record(record) for record in result.records]
|
| 687 |
+
for result in results.results
|
| 688 |
+
]
|
python/user_packages/Python313/site-packages/chromadb/proto/utils.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Set
|
| 2 |
+
import grpc
|
| 3 |
+
from tenacity import retry, stop_after_attempt, wait_exponential_jitter, retry_if_result
|
| 4 |
+
from opentelemetry.trace import Span
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class RetryOnRpcErrorClientInterceptor(
|
| 8 |
+
grpc.UnaryUnaryClientInterceptor, grpc.UnaryStreamClientInterceptor
|
| 9 |
+
):
|
| 10 |
+
"""
|
| 11 |
+
A gRPC client interceptor that retries RPCs on specific status codes. By default, it retries on UNAVAILABLE and UNKNOWN status codes.
|
| 12 |
+
|
| 13 |
+
This interceptor should be placed after the OpenTelemetry interceptor in the interceptor list.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
max_attempts: int
|
| 17 |
+
retryable_status_codes: Set[grpc.StatusCode]
|
| 18 |
+
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
max_attempts: int = 5,
|
| 22 |
+
retryable_status_codes: Set[grpc.StatusCode] = set(
|
| 23 |
+
[grpc.StatusCode.UNAVAILABLE, grpc.StatusCode.UNKNOWN]
|
| 24 |
+
),
|
| 25 |
+
) -> None:
|
| 26 |
+
self.max_attempts = max_attempts
|
| 27 |
+
self.retryable_status_codes = retryable_status_codes
|
| 28 |
+
|
| 29 |
+
def _intercept_call(self, continuation, client_call_details, request_or_iterator):
|
| 30 |
+
sleep_span: Optional[Span] = None
|
| 31 |
+
|
| 32 |
+
def before_sleep(_):
|
| 33 |
+
from chromadb.telemetry.opentelemetry import tracer
|
| 34 |
+
|
| 35 |
+
nonlocal sleep_span
|
| 36 |
+
if tracer is not None:
|
| 37 |
+
sleep_span = tracer.start_span("Waiting to retry RPC")
|
| 38 |
+
|
| 39 |
+
@retry(
|
| 40 |
+
wait=wait_exponential_jitter(0.1, jitter=0.1),
|
| 41 |
+
stop=stop_after_attempt(self.max_attempts),
|
| 42 |
+
retry=retry_if_result(lambda x: x.code() in self.retryable_status_codes),
|
| 43 |
+
before_sleep=before_sleep,
|
| 44 |
+
)
|
| 45 |
+
def wrapped(*args, **kwargs):
|
| 46 |
+
nonlocal sleep_span
|
| 47 |
+
if sleep_span is not None:
|
| 48 |
+
sleep_span.end()
|
| 49 |
+
sleep_span = None
|
| 50 |
+
return continuation(*args, **kwargs)
|
| 51 |
+
|
| 52 |
+
return wrapped(client_call_details, request_or_iterator)
|
| 53 |
+
|
| 54 |
+
def intercept_unary_unary(self, continuation, client_call_details, request):
|
| 55 |
+
return self._intercept_call(continuation, client_call_details, request)
|
| 56 |
+
|
| 57 |
+
def intercept_unary_stream(self, continuation, client_call_details, request):
|
| 58 |
+
return self._intercept_call(continuation, client_call_details, request)
|
| 59 |
+
|
| 60 |
+
def intercept_stream_unary(
|
| 61 |
+
self, continuation, client_call_details, request_iterator
|
| 62 |
+
):
|
| 63 |
+
return self._intercept_call(continuation, client_call_details, request_iterator)
|
| 64 |
+
|
| 65 |
+
def intercept_stream_stream(
|
| 66 |
+
self, continuation, client_call_details, request_iterator
|
| 67 |
+
):
|
| 68 |
+
return self._intercept_call(continuation, client_call_details, request_iterator)
|
python/user_packages/Python313/site-packages/chromadb/quota/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractmethod
|
| 2 |
+
from enum import Enum
|
| 3 |
+
from typing import Dict, Any, Optional
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from chromadb.api.types import (
|
| 7 |
+
Embeddings,
|
| 8 |
+
Metadatas,
|
| 9 |
+
Documents,
|
| 10 |
+
URIs,
|
| 11 |
+
IDs,
|
| 12 |
+
CollectionMetadata,
|
| 13 |
+
Where,
|
| 14 |
+
WhereDocument,
|
| 15 |
+
)
|
| 16 |
+
from chromadb.config import Component, System
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Action(str, Enum):
|
| 20 |
+
CREATE_DATABASE = "create_database"
|
| 21 |
+
CREATE_COLLECTION = "create_collection"
|
| 22 |
+
LIST_COLLECTIONS = "list_collections"
|
| 23 |
+
UPDATE_COLLECTION = "update_collection"
|
| 24 |
+
ADD = "add"
|
| 25 |
+
GET = "get"
|
| 26 |
+
DELETE = "delete"
|
| 27 |
+
UPDATE = "update"
|
| 28 |
+
UPSERT = "upsert"
|
| 29 |
+
QUERY = "query"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class QuotaEnforcer(Component):
|
| 33 |
+
"""
|
| 34 |
+
Exposes hooks to enforce quotas.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
def __init__(self, system: System) -> None:
|
| 38 |
+
super().__init__(system)
|
| 39 |
+
|
| 40 |
+
@abstractmethod
|
| 41 |
+
def set_context(self, context: Dict[str, Any]) -> None:
|
| 42 |
+
"""
|
| 43 |
+
Sets the context for a given request.
|
| 44 |
+
"""
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
@abstractmethod
|
| 48 |
+
def enforce(
|
| 49 |
+
self,
|
| 50 |
+
action: Action,
|
| 51 |
+
tenant: str,
|
| 52 |
+
metadatas: Optional[Metadatas] = None,
|
| 53 |
+
documents: Optional[Documents] = None,
|
| 54 |
+
embeddings: Optional[Embeddings] = None,
|
| 55 |
+
uris: Optional[URIs] = None,
|
| 56 |
+
ids: Optional[IDs] = None,
|
| 57 |
+
name: Optional[str] = None,
|
| 58 |
+
new_name: Optional[str] = None,
|
| 59 |
+
metadata: Optional[CollectionMetadata] = None,
|
| 60 |
+
new_metadata: Optional[CollectionMetadata] = None,
|
| 61 |
+
limit: Optional[int] = None,
|
| 62 |
+
where: Optional[Where] = None,
|
| 63 |
+
where_document: Optional[WhereDocument] = None,
|
| 64 |
+
n_results: Optional[int] = None,
|
| 65 |
+
query_embeddings: Optional[Embeddings] = None,
|
| 66 |
+
collection_id: Optional[UUID] = None,
|
| 67 |
+
) -> None:
|
| 68 |
+
"""
|
| 69 |
+
Enforces a quota.
|
| 70 |
+
"""
|
| 71 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/rate_limit/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import abstractmethod
|
| 2 |
+
from typing import Awaitable, Callable, TypeVar, Any
|
| 3 |
+
from chromadb.config import Component, System
|
| 4 |
+
|
| 5 |
+
T = TypeVar("T", bound=Callable[..., Any])
|
| 6 |
+
A = TypeVar("A", bound=Awaitable[Any])
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class RateLimitEnforcer(Component):
|
| 10 |
+
"""
|
| 11 |
+
Rate limit enforcer.
|
| 12 |
+
|
| 13 |
+
Implemented as a wrapper around server functions to block requests if rate limits are exceeded.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def __init__(self, system: System) -> None:
|
| 17 |
+
super().__init__(system)
|
| 18 |
+
|
| 19 |
+
@abstractmethod
|
| 20 |
+
def rate_limit(self, func: T) -> T:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class AsyncRateLimitEnforcer(Component):
|
| 25 |
+
"""
|
| 26 |
+
Rate limit enforcer.
|
| 27 |
+
|
| 28 |
+
Implemented as a wrapper around async functions to block requests if rate limits are exceeded.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, system: System) -> None:
|
| 32 |
+
super().__init__(system)
|
| 33 |
+
|
| 34 |
+
@abstractmethod
|
| 35 |
+
def rate_limit(self, func: A) -> A:
|
| 36 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/segment/__init__.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional, Sequence, TypeVar
|
| 2 |
+
from abc import abstractmethod
|
| 3 |
+
from chromadb.types import (
|
| 4 |
+
Collection,
|
| 5 |
+
MetadataEmbeddingRecord,
|
| 6 |
+
Operation,
|
| 7 |
+
RequestVersionContext,
|
| 8 |
+
VectorEmbeddingRecord,
|
| 9 |
+
Where,
|
| 10 |
+
WhereDocument,
|
| 11 |
+
VectorQuery,
|
| 12 |
+
VectorQueryResult,
|
| 13 |
+
Segment,
|
| 14 |
+
SeqId,
|
| 15 |
+
Metadata,
|
| 16 |
+
)
|
| 17 |
+
from chromadb.config import Component, System
|
| 18 |
+
from uuid import UUID
|
| 19 |
+
from enum import Enum
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class SegmentType(Enum):
|
| 23 |
+
SQLITE = "urn:chroma:segment/metadata/sqlite"
|
| 24 |
+
HNSW_LOCAL_MEMORY = "urn:chroma:segment/vector/hnsw-local-memory"
|
| 25 |
+
HNSW_LOCAL_PERSISTED = "urn:chroma:segment/vector/hnsw-local-persisted"
|
| 26 |
+
HNSW_DISTRIBUTED = "urn:chroma:segment/vector/hnsw-distributed"
|
| 27 |
+
BLOCKFILE_RECORD = "urn:chroma:segment/record/blockfile"
|
| 28 |
+
BLOCKFILE_METADATA = "urn:chroma:segment/metadata/blockfile"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class SegmentImplementation(Component):
|
| 32 |
+
@abstractmethod
|
| 33 |
+
def __init__(self, sytstem: System, segment: Segment):
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
@abstractmethod
|
| 37 |
+
def count(self, request_version_context: RequestVersionContext) -> int:
|
| 38 |
+
"""Get the number of embeddings in this segment"""
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
@abstractmethod
|
| 42 |
+
def max_seqid(self) -> SeqId:
|
| 43 |
+
"""Get the maximum SeqID currently indexed by this segment"""
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
@staticmethod
|
| 47 |
+
def propagate_collection_metadata(metadata: Metadata) -> Optional[Metadata]:
|
| 48 |
+
"""Given an arbitrary metadata map (e.g, from a collection), validate it and
|
| 49 |
+
return metadata (if any) that is applicable and should be applied to the
|
| 50 |
+
segment. Validation errors will be reported to the user."""
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
@abstractmethod
|
| 54 |
+
def delete(self) -> None:
|
| 55 |
+
"""Delete the segment and all its data"""
|
| 56 |
+
...
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
S = TypeVar("S", bound=SegmentImplementation)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class MetadataReader(SegmentImplementation):
|
| 63 |
+
"""Embedding Metadata segment interface"""
|
| 64 |
+
|
| 65 |
+
@abstractmethod
|
| 66 |
+
def get_metadata(
|
| 67 |
+
self,
|
| 68 |
+
request_version_context: RequestVersionContext,
|
| 69 |
+
where: Optional[Where] = None,
|
| 70 |
+
where_document: Optional[WhereDocument] = None,
|
| 71 |
+
ids: Optional[Sequence[str]] = None,
|
| 72 |
+
limit: Optional[int] = None,
|
| 73 |
+
offset: Optional[int] = None,
|
| 74 |
+
include_metadata: bool = True,
|
| 75 |
+
) -> Sequence[MetadataEmbeddingRecord]:
|
| 76 |
+
"""Query for embedding metadata."""
|
| 77 |
+
pass
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class VectorReader(SegmentImplementation):
|
| 81 |
+
"""Embedding Vector segment interface"""
|
| 82 |
+
|
| 83 |
+
@abstractmethod
|
| 84 |
+
def get_vectors(
|
| 85 |
+
self,
|
| 86 |
+
request_version_context: RequestVersionContext,
|
| 87 |
+
ids: Optional[Sequence[str]] = None,
|
| 88 |
+
) -> Sequence[VectorEmbeddingRecord]:
|
| 89 |
+
"""Get embeddings from the segment. If no IDs are provided, all embeddings are
|
| 90 |
+
returned."""
|
| 91 |
+
pass
|
| 92 |
+
|
| 93 |
+
@abstractmethod
|
| 94 |
+
def query_vectors(
|
| 95 |
+
self, query: VectorQuery
|
| 96 |
+
) -> Sequence[Sequence[VectorQueryResult]]:
|
| 97 |
+
"""Given a vector query, return the top-k nearest neighbors for vector in the
|
| 98 |
+
query."""
|
| 99 |
+
pass
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class SegmentManager(Component):
|
| 103 |
+
"""Interface for a pluggable strategy for creating, retrieving and instantiating
|
| 104 |
+
segments as required"""
|
| 105 |
+
|
| 106 |
+
@abstractmethod
|
| 107 |
+
def prepare_segments_for_new_collection(
|
| 108 |
+
self, collection: Collection
|
| 109 |
+
) -> Sequence[Segment]:
|
| 110 |
+
"""Return the segments required for a new collection. Returns only segment data,
|
| 111 |
+
does not persist to the SysDB"""
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
@abstractmethod
|
| 115 |
+
def delete_segments(self, collection_id: UUID) -> Sequence[UUID]:
|
| 116 |
+
"""Delete any local state for all the segments associated with a collection, and
|
| 117 |
+
returns a sequence of their IDs. Does not update the SysDB."""
|
| 118 |
+
pass
|
| 119 |
+
|
| 120 |
+
@abstractmethod
|
| 121 |
+
def hint_use_collection(self, collection_id: UUID, hint_type: Operation) -> None:
|
| 122 |
+
"""Signal to the segment manager that a collection is about to be used, so that
|
| 123 |
+
it can preload segments as needed. This is only a hint, and implementations are
|
| 124 |
+
free to ignore it."""
|
| 125 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/server/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
|
| 3 |
+
from chromadb.config import Settings
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Server(ABC):
|
| 7 |
+
@abstractmethod
|
| 8 |
+
def __init__(self, settings: Settings):
|
| 9 |
+
pass
|
python/user_packages/Python313/site-packages/chromadb/telemetry/README.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Telemetry
|
| 2 |
+
|
| 3 |
+
This directory holds all the telemetry for Chroma.
|
| 4 |
+
|
| 5 |
+
- `product/` contains anonymized product telemetry which we, Chroma, collect so we can
|
| 6 |
+
understand usage patterns. For more information, see https://docs.trychroma.com/telemetry.
|
| 7 |
+
- `opentelemetry/` contains all of the config for Chroma's [OpenTelemetry](https://opentelemetry.io/docs/instrumentation/python/getting-started/)
|
| 8 |
+
setup. These metrics are *not* sent back to Chroma -- anyone operating a Chroma instance
|
| 9 |
+
can use the OpenTelemetry metrics and traces to understand how their instance of Chroma
|
| 10 |
+
is behaving.
|
python/user_packages/Python313/site-packages/chromadb/telemetry/__init__.py
ADDED
|
File without changes
|
python/user_packages/Python313/site-packages/chromadb/test/__init__.py
ADDED
|
File without changes
|
python/user_packages/Python313/site-packages/chromadb/test/__pycache__/__init__.cpython-313.pyc
ADDED
|
Binary file (189 Bytes). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/test/__pycache__/conftest.cpython-313.pyc
ADDED
|
Binary file (48.4 kB). View file
|
|
|
python/user_packages/Python313/site-packages/chromadb/test/__pycache__/test_chroma.cpython-313.pyc
ADDED
|
Binary file (6.1 kB). View file
|
|
|