nucliadb-utils 6.8.1.post4945__py3-none-any.whl → 6.9.5.post5434__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nucliadb_utils/const.py +1 -1
- nucliadb_utils/featureflagging.py +1 -4
- nucliadb_utils/settings.py +6 -0
- nucliadb_utils/storages/azure.py +47 -24
- nucliadb_utils/storages/exceptions.py +0 -6
- nucliadb_utils/storages/s3.py +1 -1
- nucliadb_utils/storages/settings.py +3 -0
- nucliadb_utils/storages/storage.py +1 -0
- nucliadb_utils/tests/azure.py +12 -3
- nucliadb_utils/tests/fixtures.py +4 -2
- nucliadb_utils/tests/nats.py +13 -2
- nucliadb_utils/utilities.py +8 -15
- {nucliadb_utils-6.8.1.post4945.dist-info → nucliadb_utils-6.9.5.post5434.dist-info}/METADATA +5 -5
- {nucliadb_utils-6.8.1.post4945.dist-info → nucliadb_utils-6.9.5.post5434.dist-info}/RECORD +16 -20
- nucliadb_utils/aiopynecone/__init__.py +0 -19
- nucliadb_utils/aiopynecone/client.py +0 -636
- nucliadb_utils/aiopynecone/exceptions.py +0 -131
- nucliadb_utils/aiopynecone/models.py +0 -139
- {nucliadb_utils-6.8.1.post4945.dist-info → nucliadb_utils-6.9.5.post5434.dist-info}/WHEEL +0 -0
- {nucliadb_utils-6.8.1.post4945.dist-info → nucliadb_utils-6.9.5.post5434.dist-info}/top_level.txt +0 -0
|
@@ -1,636 +0,0 @@
|
|
|
1
|
-
# Copyright (C) 2021 Bosutech XXI S.L.
|
|
2
|
-
#
|
|
3
|
-
# nucliadb is offered under the AGPL v3.0 and as commercial software.
|
|
4
|
-
# For commercial licensing, contact us at info@nuclia.com.
|
|
5
|
-
#
|
|
6
|
-
# AGPL:
|
|
7
|
-
# This program is free software: you can redistribute it and/or modify
|
|
8
|
-
# it under the terms of the GNU Affero General Public License as
|
|
9
|
-
# published by the Free Software Foundation, either version 3 of the
|
|
10
|
-
# License, or (at your option) any later version.
|
|
11
|
-
#
|
|
12
|
-
# This program is distributed in the hope that it will be useful,
|
|
13
|
-
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
-
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
-
# GNU Affero General Public License for more details.
|
|
16
|
-
#
|
|
17
|
-
# You should have received a copy of the GNU Affero General Public License
|
|
18
|
-
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
19
|
-
#
|
|
20
|
-
import asyncio
|
|
21
|
-
import json
|
|
22
|
-
import logging
|
|
23
|
-
import random
|
|
24
|
-
from collections.abc import AsyncIterable, Iterable
|
|
25
|
-
from itertools import islice
|
|
26
|
-
from typing import Any, AsyncGenerator, Optional
|
|
27
|
-
|
|
28
|
-
import backoff
|
|
29
|
-
import httpx
|
|
30
|
-
|
|
31
|
-
from nucliadb_telemetry.metrics import INF, Histogram, Observer
|
|
32
|
-
from nucliadb_utils.aiopynecone.exceptions import (
|
|
33
|
-
PineconeAPIError,
|
|
34
|
-
PineconeRateLimitError,
|
|
35
|
-
RetriablePineconeAPIError,
|
|
36
|
-
raise_for_status,
|
|
37
|
-
)
|
|
38
|
-
from nucliadb_utils.aiopynecone.models import (
|
|
39
|
-
CreateIndexRequest,
|
|
40
|
-
CreateIndexResponse,
|
|
41
|
-
IndexDescription,
|
|
42
|
-
IndexStats,
|
|
43
|
-
ListResponse,
|
|
44
|
-
QueryResponse,
|
|
45
|
-
UpsertRequest,
|
|
46
|
-
Vector,
|
|
47
|
-
)
|
|
48
|
-
|
|
49
|
-
logger = logging.getLogger(__name__)
|
|
50
|
-
|
|
51
|
-
upsert_batch_size_histogram = Histogram(
|
|
52
|
-
"pinecone_upsert_batch_size",
|
|
53
|
-
buckets=[10.0, 100.0, 200.0, 500.0, 1000.0, 5000.0, INF],
|
|
54
|
-
)
|
|
55
|
-
upsert_batch_count_histogram = Histogram(
|
|
56
|
-
"pinecone_upsert_batch_count",
|
|
57
|
-
buckets=[0.0, 1.0, 2.0, 3.0, 5.0, 10.0, 15.0, 20.0, 30.0, 50.0, INF],
|
|
58
|
-
)
|
|
59
|
-
|
|
60
|
-
delete_batch_size_histogram = Histogram(
|
|
61
|
-
"pinecone_delete_batch_size",
|
|
62
|
-
buckets=[1.0, 5.0, 10.0, 20.0, 50.0, 100.0, 150.0, INF],
|
|
63
|
-
)
|
|
64
|
-
|
|
65
|
-
delete_batch_count_histogram = Histogram(
|
|
66
|
-
"pinecone_delete_batch_count",
|
|
67
|
-
buckets=[0.0, 1.0, 2.0, 3.0, 5.0, 10.0, 15.0, 20.0, 30.0, 50.0, INF],
|
|
68
|
-
)
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
pinecone_observer = Observer(
|
|
72
|
-
"pinecone_client",
|
|
73
|
-
labels={"type": ""},
|
|
74
|
-
error_mappings={
|
|
75
|
-
"rate_limit": PineconeRateLimitError,
|
|
76
|
-
},
|
|
77
|
-
)
|
|
78
|
-
|
|
79
|
-
DEFAULT_TIMEOUT = 30
|
|
80
|
-
CONTROL_PLANE_BASE_URL = "https://api.pinecone.io/"
|
|
81
|
-
BASE_API_HEADERS = {
|
|
82
|
-
"Content-Type": "application/json",
|
|
83
|
-
"Accept": "application/json",
|
|
84
|
-
# This is needed so that it is easier for Pinecone to track which api requests
|
|
85
|
-
# are coming from the Nuclia integration:
|
|
86
|
-
# https://docs.pinecone.io/integrations/build-integration/attribute-usage-to-your-integration
|
|
87
|
-
"User-Agent": "source_tag=nuclia",
|
|
88
|
-
"X-Pinecone-API-Version": "2024-10",
|
|
89
|
-
}
|
|
90
|
-
MEGA_BYTE = 1024 * 1024
|
|
91
|
-
MAX_UPSERT_PAYLOAD_SIZE = 2 * MEGA_BYTE
|
|
92
|
-
MAX_DELETE_BATCH_SIZE = 1000
|
|
93
|
-
MAX_LIST_PAGE_SIZE = 100
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
RETRIABLE_EXCEPTIONS = (
|
|
97
|
-
PineconeRateLimitError,
|
|
98
|
-
RetriablePineconeAPIError,
|
|
99
|
-
httpx.ConnectError,
|
|
100
|
-
httpx.NetworkError,
|
|
101
|
-
httpx.WriteTimeout,
|
|
102
|
-
httpx.ReadTimeout,
|
|
103
|
-
)
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
class ControlPlane:
|
|
107
|
-
"""
|
|
108
|
-
Client for interacting with the Pinecone control plane API.
|
|
109
|
-
https://docs.pinecone.io/reference/api/control-plane
|
|
110
|
-
"""
|
|
111
|
-
|
|
112
|
-
def __init__(self, api_key: str, http_session: httpx.AsyncClient):
|
|
113
|
-
self.api_key = api_key
|
|
114
|
-
self.http_session = http_session
|
|
115
|
-
|
|
116
|
-
@pinecone_observer.wrap({"type": "create_index"})
|
|
117
|
-
async def create_index(
|
|
118
|
-
self,
|
|
119
|
-
name: str,
|
|
120
|
-
dimension: int,
|
|
121
|
-
metric: str = "dotproduct",
|
|
122
|
-
serverless_cloud: Optional[dict[str, str]] = None,
|
|
123
|
-
) -> str:
|
|
124
|
-
"""
|
|
125
|
-
Create a new index in Pinecone. It can only create serverless indexes on the AWS us-east-1 region.
|
|
126
|
-
Params:
|
|
127
|
-
- `name`: The name of the index.
|
|
128
|
-
- `dimension`: The dimension of the vectors in the index.
|
|
129
|
-
- `metric`: The similarity metric to use. Default is "dotproduct".
|
|
130
|
-
- `serverless_cloud`: The serverless provider to use. Default is AWS us-east-1.
|
|
131
|
-
Returns:
|
|
132
|
-
- The index host to be used for data plane operations.
|
|
133
|
-
"""
|
|
134
|
-
serverless_cloud = serverless_cloud or {"cloud": "aws", "region": "us-east-1"}
|
|
135
|
-
payload = CreateIndexRequest(
|
|
136
|
-
name=name,
|
|
137
|
-
dimension=dimension,
|
|
138
|
-
metric=metric,
|
|
139
|
-
spec={"serverless": serverless_cloud},
|
|
140
|
-
)
|
|
141
|
-
headers = {"Api-Key": self.api_key}
|
|
142
|
-
http_response = await self.http_session.post(
|
|
143
|
-
"/indexes", json=payload.model_dump(), headers=headers
|
|
144
|
-
)
|
|
145
|
-
raise_for_status("create_index", http_response)
|
|
146
|
-
response = CreateIndexResponse.model_validate(http_response.json())
|
|
147
|
-
return response.host
|
|
148
|
-
|
|
149
|
-
@pinecone_observer.wrap({"type": "delete_index"})
|
|
150
|
-
async def delete_index(self, name: str) -> None:
|
|
151
|
-
"""
|
|
152
|
-
Delete an index in Pinecone.
|
|
153
|
-
Params:
|
|
154
|
-
- `name`: The name of the index to delete.
|
|
155
|
-
"""
|
|
156
|
-
headers = {"Api-Key": self.api_key}
|
|
157
|
-
response = await self.http_session.delete(f"/indexes/{name}", headers=headers)
|
|
158
|
-
if response.status_code == 404: # pragma: no cover
|
|
159
|
-
logger.warning("Pinecone index not found.", extra={"index_name": name})
|
|
160
|
-
return
|
|
161
|
-
raise_for_status("delete_index", response)
|
|
162
|
-
|
|
163
|
-
@pinecone_observer.wrap({"type": "describe_index"})
|
|
164
|
-
async def describe_index(self, name: str) -> IndexDescription:
|
|
165
|
-
"""
|
|
166
|
-
Describe an index in Pinecone.
|
|
167
|
-
Params:
|
|
168
|
-
- `name`: The name of the index to describe.
|
|
169
|
-
"""
|
|
170
|
-
headers = {"Api-Key": self.api_key}
|
|
171
|
-
response = await self.http_session.get(f"/indexes/{name}", headers=headers)
|
|
172
|
-
raise_for_status("describe_index", response)
|
|
173
|
-
return IndexDescription.model_validate(response.json())
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
class DataPlane:
|
|
177
|
-
"""
|
|
178
|
-
Client for interacting with the Pinecone data plane API, hosted by an index host.
|
|
179
|
-
https://docs.pinecone.io/reference/api/data-plane
|
|
180
|
-
"""
|
|
181
|
-
|
|
182
|
-
def __init__(
|
|
183
|
-
self, api_key: str, index_host_session: httpx.AsyncClient, timeout: Optional[float] = None
|
|
184
|
-
):
|
|
185
|
-
"""
|
|
186
|
-
Params:
|
|
187
|
-
- `api_key`: The Pinecone API key.
|
|
188
|
-
- `index_host_session`: The http session for the index host.
|
|
189
|
-
- `timeout`: The default timeout for all requests. If not set, the default timeout from httpx.AsyncClient is used.
|
|
190
|
-
"""
|
|
191
|
-
self.api_key = api_key
|
|
192
|
-
self.http_session = index_host_session
|
|
193
|
-
self.client_timeout = timeout
|
|
194
|
-
self._upsert_batch_size: Optional[int] = None
|
|
195
|
-
|
|
196
|
-
def _get_request_timeout(self, timeout: Optional[float] = None) -> Optional[float]:
|
|
197
|
-
return timeout or self.client_timeout
|
|
198
|
-
|
|
199
|
-
@pinecone_observer.wrap({"type": "stats"})
|
|
200
|
-
async def stats(self, filter: Optional[dict[str, Any]] = None) -> IndexStats:
|
|
201
|
-
"""
|
|
202
|
-
Get the index stats.
|
|
203
|
-
Params:
|
|
204
|
-
- `filter`: to filter the stats by their metadata. See:
|
|
205
|
-
https://docs.pinecone.io/reference/api/2024-07/data-plane/describeindexstats
|
|
206
|
-
"""
|
|
207
|
-
post_kwargs: dict[str, Any] = {
|
|
208
|
-
"headers": {"Api-Key": self.api_key},
|
|
209
|
-
}
|
|
210
|
-
if filter is not None:
|
|
211
|
-
post_kwargs["json"] = {
|
|
212
|
-
"filter": filter,
|
|
213
|
-
}
|
|
214
|
-
response = await self.http_session.post("/describe_index_stats", **post_kwargs)
|
|
215
|
-
raise_for_status("stats", response)
|
|
216
|
-
return IndexStats.model_validate(response.json())
|
|
217
|
-
|
|
218
|
-
@backoff.on_exception(
|
|
219
|
-
backoff.expo,
|
|
220
|
-
RETRIABLE_EXCEPTIONS,
|
|
221
|
-
jitter=backoff.random_jitter,
|
|
222
|
-
max_tries=4,
|
|
223
|
-
)
|
|
224
|
-
@pinecone_observer.wrap({"type": "upsert"})
|
|
225
|
-
async def upsert(self, vectors: list[Vector], timeout: Optional[float] = None) -> None:
|
|
226
|
-
"""
|
|
227
|
-
Upsert vectors into the index.
|
|
228
|
-
Params:
|
|
229
|
-
- `vectors`: The vectors to upsert.
|
|
230
|
-
- `timeout`: to control the request timeout. If not set, the default timeout is used.
|
|
231
|
-
"""
|
|
232
|
-
if len(vectors) == 0:
|
|
233
|
-
# Nothing to upsert.
|
|
234
|
-
return
|
|
235
|
-
upsert_batch_size_histogram.observe(len(vectors))
|
|
236
|
-
headers = {"Api-Key": self.api_key}
|
|
237
|
-
payload = UpsertRequest(vectors=vectors)
|
|
238
|
-
post_kwargs: dict[str, Any] = {
|
|
239
|
-
"headers": headers,
|
|
240
|
-
"json": payload.model_dump(),
|
|
241
|
-
}
|
|
242
|
-
request_timeout = self._get_request_timeout(timeout)
|
|
243
|
-
if request_timeout is not None:
|
|
244
|
-
post_kwargs["timeout"] = timeout
|
|
245
|
-
response = await self.http_session.post("/vectors/upsert", **post_kwargs)
|
|
246
|
-
raise_for_status("upsert", response)
|
|
247
|
-
|
|
248
|
-
def _estimate_upsert_batch_size(self, vectors: list[Vector]) -> int:
|
|
249
|
-
"""
|
|
250
|
-
Estimate a batch size so that the upsert payload does not exceed the hard limit.
|
|
251
|
-
https://docs.pinecone.io/reference/quotas-and-limits#hard-limits
|
|
252
|
-
"""
|
|
253
|
-
if self._upsert_batch_size is not None:
|
|
254
|
-
# Return the cached value.
|
|
255
|
-
return self._upsert_batch_size
|
|
256
|
-
# Take the dimension of the first vector as the vector dimension.
|
|
257
|
-
# Assumes all vectors have the same dimension.
|
|
258
|
-
vector_dimension = len(vectors[0].values)
|
|
259
|
-
# Estimate the metadata size by taking the average of 20 random vectors.
|
|
260
|
-
metadata_sizes = []
|
|
261
|
-
for _ in range(20):
|
|
262
|
-
metadata_sizes.append(len(json.dumps(random.choice(vectors).metadata)))
|
|
263
|
-
average_metadata_size = sum(metadata_sizes) / len(metadata_sizes)
|
|
264
|
-
# Estimate the size of the vector payload. 4 bytes per float.
|
|
265
|
-
vector_size = 4 * vector_dimension + average_metadata_size
|
|
266
|
-
# Cache the value.
|
|
267
|
-
self._upsert_batch_size = max(int(MAX_UPSERT_PAYLOAD_SIZE // vector_size), 1)
|
|
268
|
-
return self._upsert_batch_size
|
|
269
|
-
|
|
270
|
-
@pinecone_observer.wrap({"type": "upsert_in_batches"})
|
|
271
|
-
async def upsert_in_batches(
|
|
272
|
-
self,
|
|
273
|
-
vectors: list[Vector],
|
|
274
|
-
batch_size: Optional[int] = None,
|
|
275
|
-
max_parallel_batches: int = 1,
|
|
276
|
-
batch_timeout: Optional[float] = None,
|
|
277
|
-
) -> None:
|
|
278
|
-
"""
|
|
279
|
-
Upsert vectors in batches.
|
|
280
|
-
Params:
|
|
281
|
-
- `vectors`: The vectors to upsert.
|
|
282
|
-
- `batch_size`: to control the number of vectors in each batch.
|
|
283
|
-
- `max_parallel_batches`: to control the number of batches sent concurrently.
|
|
284
|
-
- `batch_timeout`: to control the request timeout for each batch.
|
|
285
|
-
"""
|
|
286
|
-
if batch_size is None:
|
|
287
|
-
batch_size = self._estimate_upsert_batch_size(vectors)
|
|
288
|
-
|
|
289
|
-
semaphore = asyncio.Semaphore(max_parallel_batches)
|
|
290
|
-
|
|
291
|
-
async def _upsert_batch(batch):
|
|
292
|
-
async with semaphore:
|
|
293
|
-
await self.upsert(vectors=batch, timeout=batch_timeout)
|
|
294
|
-
|
|
295
|
-
tasks = []
|
|
296
|
-
for batch in batchify(vectors, batch_size):
|
|
297
|
-
tasks.append(asyncio.create_task(_upsert_batch(batch)))
|
|
298
|
-
|
|
299
|
-
upsert_batch_count_histogram.observe(len(tasks))
|
|
300
|
-
|
|
301
|
-
if len(tasks) > 0:
|
|
302
|
-
await asyncio.gather(*tasks)
|
|
303
|
-
|
|
304
|
-
@backoff.on_exception(
|
|
305
|
-
backoff.expo,
|
|
306
|
-
RETRIABLE_EXCEPTIONS,
|
|
307
|
-
jitter=backoff.random_jitter,
|
|
308
|
-
max_tries=4,
|
|
309
|
-
)
|
|
310
|
-
@pinecone_observer.wrap({"type": "delete"})
|
|
311
|
-
async def delete(self, ids: list[str], timeout: Optional[float] = None) -> None:
|
|
312
|
-
"""
|
|
313
|
-
Delete vectors by their ids.
|
|
314
|
-
Maximum number of ids in a single request is 1000.
|
|
315
|
-
Params:
|
|
316
|
-
- `ids`: The ids of the vectors to delete.
|
|
317
|
-
- `timeout`: to control the request timeout. If not set, the default timeout is used.
|
|
318
|
-
"""
|
|
319
|
-
if len(ids) > MAX_DELETE_BATCH_SIZE:
|
|
320
|
-
raise ValueError(f"Maximum number of ids in a single request is {MAX_DELETE_BATCH_SIZE}.")
|
|
321
|
-
if len(ids) == 0: # pragma: no cover
|
|
322
|
-
return
|
|
323
|
-
|
|
324
|
-
delete_batch_size_histogram.observe(len(ids))
|
|
325
|
-
headers = {"Api-Key": self.api_key}
|
|
326
|
-
|
|
327
|
-
# This is a temporary log info to hunt down a bug.
|
|
328
|
-
rids = {vid.split("/")[0] for vid in ids}
|
|
329
|
-
logger.info(f"Deleting vectors from resources: {list(rids)}")
|
|
330
|
-
|
|
331
|
-
payload = {"ids": ids}
|
|
332
|
-
post_kwargs: dict[str, Any] = {
|
|
333
|
-
"headers": headers,
|
|
334
|
-
"json": payload,
|
|
335
|
-
}
|
|
336
|
-
request_timeout = self._get_request_timeout(timeout)
|
|
337
|
-
if request_timeout is not None:
|
|
338
|
-
post_kwargs["timeout"] = timeout
|
|
339
|
-
response = await self.http_session.post("/vectors/delete", **post_kwargs)
|
|
340
|
-
raise_for_status("delete", response)
|
|
341
|
-
|
|
342
|
-
@backoff.on_exception(
|
|
343
|
-
backoff.expo,
|
|
344
|
-
RETRIABLE_EXCEPTIONS,
|
|
345
|
-
jitter=backoff.random_jitter,
|
|
346
|
-
max_tries=4,
|
|
347
|
-
)
|
|
348
|
-
@pinecone_observer.wrap({"type": "list_page"})
|
|
349
|
-
async def list_page(
|
|
350
|
-
self,
|
|
351
|
-
id_prefix: Optional[str] = None,
|
|
352
|
-
limit: int = MAX_LIST_PAGE_SIZE,
|
|
353
|
-
pagination_token: Optional[str] = None,
|
|
354
|
-
timeout: Optional[float] = None,
|
|
355
|
-
) -> ListResponse:
|
|
356
|
-
"""
|
|
357
|
-
List vectors in a paginated manner.
|
|
358
|
-
Params:
|
|
359
|
-
- `id_prefix`: to filter vectors by their id prefix.
|
|
360
|
-
- `limit`: to control the number of vectors fetched in each page.
|
|
361
|
-
- `pagination_token`: to fetch the next page. The token is provided in the response
|
|
362
|
-
if there are more pages to fetch.
|
|
363
|
-
- `timeout`: to control the request timeout. If not set, the default timeout is used.
|
|
364
|
-
"""
|
|
365
|
-
if limit > MAX_LIST_PAGE_SIZE: # pragma: no cover
|
|
366
|
-
raise ValueError(f"Maximum limit is {MAX_LIST_PAGE_SIZE}.")
|
|
367
|
-
headers = {"Api-Key": self.api_key}
|
|
368
|
-
params = {"limit": str(limit)}
|
|
369
|
-
if id_prefix is not None:
|
|
370
|
-
params["prefix"] = id_prefix
|
|
371
|
-
if pagination_token is not None:
|
|
372
|
-
params["paginationToken"] = pagination_token
|
|
373
|
-
|
|
374
|
-
post_kwargs: dict[str, Any] = {
|
|
375
|
-
"headers": headers,
|
|
376
|
-
"params": params,
|
|
377
|
-
}
|
|
378
|
-
request_timeout = self._get_request_timeout(timeout)
|
|
379
|
-
if request_timeout is not None:
|
|
380
|
-
post_kwargs["timeout"] = timeout
|
|
381
|
-
response = await self.http_session.get(
|
|
382
|
-
"/vectors/list",
|
|
383
|
-
**post_kwargs,
|
|
384
|
-
)
|
|
385
|
-
raise_for_status("list_page", response)
|
|
386
|
-
return ListResponse.model_validate(response.json())
|
|
387
|
-
|
|
388
|
-
async def list_all(
|
|
389
|
-
self,
|
|
390
|
-
id_prefix: Optional[str] = None,
|
|
391
|
-
page_size: int = MAX_LIST_PAGE_SIZE,
|
|
392
|
-
page_timeout: Optional[float] = None,
|
|
393
|
-
) -> AsyncGenerator[str, None]:
|
|
394
|
-
"""
|
|
395
|
-
Iterate over all vector ids from the index in a paginated manner.
|
|
396
|
-
Params:
|
|
397
|
-
- `id_prefix`: to filter vectors by their id prefix.
|
|
398
|
-
- `page_size`: to control the number of vectors fetched in each page.
|
|
399
|
-
- `page_timeout`: to control the request timeout for each page. If not set, the default timeout is used.
|
|
400
|
-
"""
|
|
401
|
-
pagination_token = None
|
|
402
|
-
while True:
|
|
403
|
-
response = await self.list_page(
|
|
404
|
-
id_prefix=id_prefix,
|
|
405
|
-
limit=page_size,
|
|
406
|
-
pagination_token=pagination_token,
|
|
407
|
-
timeout=page_timeout,
|
|
408
|
-
)
|
|
409
|
-
for vector_id in response.vectors:
|
|
410
|
-
yield vector_id.id
|
|
411
|
-
if response.pagination is None:
|
|
412
|
-
break
|
|
413
|
-
pagination_token = response.pagination.next
|
|
414
|
-
|
|
415
|
-
@backoff.on_exception(
|
|
416
|
-
backoff.expo,
|
|
417
|
-
RETRIABLE_EXCEPTIONS,
|
|
418
|
-
jitter=backoff.random_jitter,
|
|
419
|
-
max_tries=4,
|
|
420
|
-
)
|
|
421
|
-
@pinecone_observer.wrap({"type": "delete_all"})
|
|
422
|
-
async def delete_all(self, timeout: Optional[float] = None):
|
|
423
|
-
"""
|
|
424
|
-
Delete all vectors in the index.
|
|
425
|
-
Params:
|
|
426
|
-
- `timeout`: to control the request timeout. If not set, the default timeout is used.
|
|
427
|
-
"""
|
|
428
|
-
headers = {"Api-Key": self.api_key}
|
|
429
|
-
payload = {"deleteAll": True, "ids": [], "namespace": ""}
|
|
430
|
-
post_kwargs: dict[str, Any] = {
|
|
431
|
-
"headers": headers,
|
|
432
|
-
"json": payload,
|
|
433
|
-
}
|
|
434
|
-
request_timeout = self._get_request_timeout(timeout)
|
|
435
|
-
if request_timeout is not None:
|
|
436
|
-
post_kwargs["timeout"] = timeout
|
|
437
|
-
response = await self.http_session.post("/vectors/delete", **post_kwargs)
|
|
438
|
-
try:
|
|
439
|
-
raise_for_status("delete_all", response)
|
|
440
|
-
except PineconeAPIError as err:
|
|
441
|
-
if err.http_status_code == 404 and err.code == 5: # pragma: no cover
|
|
442
|
-
# Namespace not found. No vectors to delete.
|
|
443
|
-
return
|
|
444
|
-
raise
|
|
445
|
-
|
|
446
|
-
@pinecone_observer.wrap({"type": "delete_by_id_prefix"})
|
|
447
|
-
async def delete_by_id_prefix(
|
|
448
|
-
self,
|
|
449
|
-
id_prefix: str,
|
|
450
|
-
batch_size: int = MAX_DELETE_BATCH_SIZE,
|
|
451
|
-
max_parallel_batches: int = 1,
|
|
452
|
-
batch_timeout: Optional[float] = None,
|
|
453
|
-
) -> None:
|
|
454
|
-
"""
|
|
455
|
-
Delete vectors by their id prefix. It lists all vectors with the given prefix and deletes them in batches.
|
|
456
|
-
Params:
|
|
457
|
-
- `id_prefix`: to filter vectors by their id prefix.
|
|
458
|
-
- `batch_size`: to control the number of vectors deleted in each batch. Maximum is 1000.
|
|
459
|
-
- `max_parallel_batches`: to control the number of batches sent concurrently.
|
|
460
|
-
- `batch_timeout`: to control the request timeout for each batch.
|
|
461
|
-
"""
|
|
462
|
-
if batch_size > MAX_DELETE_BATCH_SIZE:
|
|
463
|
-
logger.warning(f"Batch size {batch_size} is too large. Limiting to {MAX_DELETE_BATCH_SIZE}.")
|
|
464
|
-
batch_size = MAX_DELETE_BATCH_SIZE
|
|
465
|
-
|
|
466
|
-
semaphore = asyncio.Semaphore(max_parallel_batches)
|
|
467
|
-
|
|
468
|
-
async def _delete_batch(batch):
|
|
469
|
-
async with semaphore:
|
|
470
|
-
await self.delete(ids=batch, timeout=batch_timeout)
|
|
471
|
-
|
|
472
|
-
tasks = []
|
|
473
|
-
async_iterable = self.list_all(id_prefix=id_prefix, page_timeout=batch_timeout)
|
|
474
|
-
async for batch in async_batchify(async_iterable, batch_size):
|
|
475
|
-
tasks.append(asyncio.create_task(_delete_batch(batch)))
|
|
476
|
-
|
|
477
|
-
delete_batch_count_histogram.observe(len(tasks))
|
|
478
|
-
|
|
479
|
-
if len(tasks) > 0:
|
|
480
|
-
await asyncio.gather(*tasks)
|
|
481
|
-
|
|
482
|
-
@backoff.on_exception(
|
|
483
|
-
backoff.expo,
|
|
484
|
-
RETRIABLE_EXCEPTIONS,
|
|
485
|
-
jitter=backoff.random_jitter,
|
|
486
|
-
max_tries=4,
|
|
487
|
-
)
|
|
488
|
-
@pinecone_observer.wrap({"type": "query"})
|
|
489
|
-
async def query(
|
|
490
|
-
self,
|
|
491
|
-
vector: list[float],
|
|
492
|
-
top_k: int = 20,
|
|
493
|
-
include_values: bool = False,
|
|
494
|
-
include_metadata: bool = False,
|
|
495
|
-
filter: Optional[dict[str, Any]] = None,
|
|
496
|
-
timeout: Optional[float] = None,
|
|
497
|
-
) -> QueryResponse:
|
|
498
|
-
"""
|
|
499
|
-
Query the index for similar vectors to the given vector.
|
|
500
|
-
Params:
|
|
501
|
-
- `vector`: The query vector.
|
|
502
|
-
- `top_k`: to control the number of similar vectors to return.
|
|
503
|
-
- `include_values`: to include the vector values in the response.
|
|
504
|
-
- `include_metadata`: to include the vector metadata in the response.
|
|
505
|
-
- `filter`: to filter the vectors by their metadata. See:
|
|
506
|
-
https://docs.pinecone.io/guides/data/filter-with-metadata#metadata-query-language
|
|
507
|
-
- `timeout`: to control the request timeout. If not set, the default timeout is used.
|
|
508
|
-
"""
|
|
509
|
-
headers = {"Api-Key": self.api_key}
|
|
510
|
-
payload = {
|
|
511
|
-
"vector": vector,
|
|
512
|
-
"topK": top_k,
|
|
513
|
-
"includeValues": include_values,
|
|
514
|
-
"includeMetadata": include_metadata,
|
|
515
|
-
}
|
|
516
|
-
if filter:
|
|
517
|
-
payload["filter"] = filter
|
|
518
|
-
post_kwargs: dict[str, Any] = {
|
|
519
|
-
"headers": headers,
|
|
520
|
-
"json": payload,
|
|
521
|
-
}
|
|
522
|
-
request_timeout = self._get_request_timeout(timeout)
|
|
523
|
-
if request_timeout is not None:
|
|
524
|
-
post_kwargs["timeout"] = timeout
|
|
525
|
-
response = await self.http_session.post("/query", **post_kwargs)
|
|
526
|
-
raise_for_status("query", response)
|
|
527
|
-
return QueryResponse.model_validate(response.json())
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
class PineconeSession:
|
|
531
|
-
"""
|
|
532
|
-
Wrapper class that manages the sessions around all Pinecone http api interactions.
|
|
533
|
-
Holds a single control plane session and multiple data plane sessions, one for each index host.
|
|
534
|
-
"""
|
|
535
|
-
|
|
536
|
-
def __init__(self):
|
|
537
|
-
self.control_plane_session = httpx.AsyncClient(
|
|
538
|
-
base_url=CONTROL_PLANE_BASE_URL, headers=BASE_API_HEADERS, timeout=DEFAULT_TIMEOUT
|
|
539
|
-
)
|
|
540
|
-
self.index_host_sessions = {}
|
|
541
|
-
|
|
542
|
-
async def __aenter__(self):
|
|
543
|
-
return self
|
|
544
|
-
|
|
545
|
-
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
|
546
|
-
await self.finalize()
|
|
547
|
-
|
|
548
|
-
async def finalize(self):
|
|
549
|
-
if not self.control_plane_session.is_closed:
|
|
550
|
-
await self.control_plane_session.aclose()
|
|
551
|
-
for session in self.index_host_sessions.values():
|
|
552
|
-
if not session.is_closed:
|
|
553
|
-
await session.aclose()
|
|
554
|
-
self.index_host_sessions.clear()
|
|
555
|
-
|
|
556
|
-
def control_plane(self, api_key: str) -> ControlPlane:
|
|
557
|
-
return ControlPlane(api_key=api_key, http_session=self.control_plane_session)
|
|
558
|
-
|
|
559
|
-
def _get_index_host_session(self, index_host: str) -> httpx.AsyncClient:
|
|
560
|
-
"""
|
|
561
|
-
Get a session for the given index host.
|
|
562
|
-
Cache http sessions so that they are reused for the same index host.
|
|
563
|
-
"""
|
|
564
|
-
session = self.index_host_sessions.get(index_host, None)
|
|
565
|
-
if session is not None:
|
|
566
|
-
return session
|
|
567
|
-
|
|
568
|
-
base_url = index_host
|
|
569
|
-
if not index_host.startswith("https://"):
|
|
570
|
-
base_url = f"https://{index_host}/"
|
|
571
|
-
|
|
572
|
-
session = httpx.AsyncClient(
|
|
573
|
-
base_url=base_url,
|
|
574
|
-
headers=BASE_API_HEADERS,
|
|
575
|
-
timeout=DEFAULT_TIMEOUT,
|
|
576
|
-
)
|
|
577
|
-
self.index_host_sessions[index_host] = session
|
|
578
|
-
return session
|
|
579
|
-
|
|
580
|
-
def data_plane(self, api_key: str, index_host: str, timeout: Optional[float] = None) -> DataPlane:
|
|
581
|
-
index_host_session = self._get_index_host_session(index_host)
|
|
582
|
-
return DataPlane(api_key=api_key, index_host_session=index_host_session, timeout=timeout)
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
def batchify(iterable: Iterable, batch_size: int):
|
|
586
|
-
"""
|
|
587
|
-
Split an iterable into batches of batch_size
|
|
588
|
-
"""
|
|
589
|
-
iterator = iter(iterable)
|
|
590
|
-
while True:
|
|
591
|
-
batch = list(islice(iterator, batch_size))
|
|
592
|
-
if not batch:
|
|
593
|
-
break
|
|
594
|
-
yield batch
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
async def async_batchify(async_iterable: AsyncIterable, batch_size: int):
|
|
598
|
-
"""
|
|
599
|
-
Split an async iterable into batches of batch_size
|
|
600
|
-
"""
|
|
601
|
-
batch = []
|
|
602
|
-
async for item in async_iterable:
|
|
603
|
-
batch.append(item)
|
|
604
|
-
if len(batch) == batch_size:
|
|
605
|
-
yield batch
|
|
606
|
-
batch = []
|
|
607
|
-
if batch:
|
|
608
|
-
yield batch
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
class FilterOperator:
|
|
612
|
-
"""
|
|
613
|
-
Filter operators for metadata queries.
|
|
614
|
-
https://docs.pinecone.io/guides/data/filter-with-metadata#metadata-query-language
|
|
615
|
-
"""
|
|
616
|
-
|
|
617
|
-
EQUALS = "$eq"
|
|
618
|
-
NOT_EQUALS = "$ne"
|
|
619
|
-
GREATER_THAN = "$gt"
|
|
620
|
-
GREATER_THAN_OR_EQUAL = "$gte"
|
|
621
|
-
LESS_THAN = "$lt"
|
|
622
|
-
LESS_THAN_OR_EQUAL = "$lte"
|
|
623
|
-
IN = "$in"
|
|
624
|
-
NOT_IN = "$nin"
|
|
625
|
-
EXISTS = "$exists"
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
class LogicalOperator:
|
|
629
|
-
"""
|
|
630
|
-
Logical operators for metadata queries.
|
|
631
|
-
https://docs.pinecone.io/guides/data/filter-with-metadata#metadata-query-language
|
|
632
|
-
"""
|
|
633
|
-
|
|
634
|
-
AND = "$and"
|
|
635
|
-
OR = "$or"
|
|
636
|
-
NOT = "$not"
|