render-lab-tasks-pinecone 0.1.0__tar.gz

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.
Files changed (24) hide show
  1. render_lab_tasks_pinecone-0.1.0/.gitignore +11 -0
  2. render_lab_tasks_pinecone-0.1.0/LICENSE +21 -0
  3. render_lab_tasks_pinecone-0.1.0/PKG-INFO +45 -0
  4. render_lab_tasks_pinecone-0.1.0/README.md +32 -0
  5. render_lab_tasks_pinecone-0.1.0/pyproject.toml +22 -0
  6. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/__init__.py +1 -0
  7. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/_app.py +3 -0
  8. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/await_import.py +18 -0
  9. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/cancel_import.py +18 -0
  10. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/client.py +410 -0
  11. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/create_namespace.py +18 -0
  12. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/delete_index.py +18 -0
  13. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/delete_namespace.py +18 -0
  14. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/delete_vectors.py +18 -0
  15. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/fetch_vectors.py +18 -0
  16. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/list_namespaces.py +18 -0
  17. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/provision_index.py +18 -0
  18. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/py.typed +0 -0
  19. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/retry.py +6 -0
  20. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/search.py +18 -0
  21. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/start_import.py +18 -0
  22. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/tasks.py +41 -0
  23. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/types.py +238 -0
  24. render_lab_tasks_pinecone-0.1.0/src/render_lab_tasks_pinecone/upsert_vectors.py +18 -0
@@ -0,0 +1,11 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ dist/
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Render Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,45 @@
1
+ Metadata-Version: 2.5
2
+ Name: render-lab-tasks-pinecone
3
+ Version: 0.1.0
4
+ Summary: pinecone tasks for Render Workflows
5
+ Project-URL: Repository, https://github.com/render-lab/render-tasks-python
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Requires-Dist: httpx<0.29,>=0.28
10
+ Requires-Dist: render-lab-tasks-core<0.2,>=0.1.1
11
+ Requires-Dist: render==1.0.1
12
+ Description-Content-Type: text/markdown
13
+
14
+ # render-lab-tasks-pinecone
15
+
16
+ Twelve tasks for index provisioning, namespaces, vectors, search, and bulk imports.
17
+ Import `render_lab_tasks_pinecone.tasks` for registration; each operation exports
18
+ an injectable async `*_impl(ctx, input, *, deps=...)` alongside the wrapped task.
19
+
20
+ `PINECONE_API_KEY` is required at first use. Data-plane calls first describe the
21
+ index to resolve its HTTPS host. REST requests use API version 2026-04, matching
22
+ the pinned TypeScript SDK 8.0.0. There are no transport retry loops. Stable vector
23
+ IDs support convergent upserts; startImport has no automatic durable retries.
24
+
25
+ Provisioning checks immutable dimension/metric/cloud/region fields. Search takes
26
+ exactly one vector or ID. Delete requires exactly one ids/filter/deleteAll mode.
27
+ Upsert/fetch are capped at 1,000 records; list/search/fetch DTOs are rejected at
28
+ 4 MiB. Namespace record counts that arrive as strings remain null, matching the
29
+ source mapping; this inherited loss is tracked for live validation.
30
+
31
+ Bulk import options map to errorMode.onError and integrationId. Await operations
32
+ poll by throwing. Terminal exceptions still follow the source durable policy.
33
+ The source provision error embeds undefined status because its message is built
34
+ before the first read; Python preserves it for source parity.
35
+
36
+ The hermetic fixtures run through the actual TS SDK with an injected fetch and
37
+ compare wire requests and DTO results. No live indexes, imports, or vector writes
38
+ have been performed. Account/region availability, namespace schema enforcement,
39
+ imports, bounds, and conflict recovery remain in the live-testing backlog.
40
+
41
+ ## Installation
42
+
43
+ ```sh
44
+ pip install render-lab-tasks-pinecone==0.1.0
45
+ ```
@@ -0,0 +1,32 @@
1
+ # render-lab-tasks-pinecone
2
+
3
+ Twelve tasks for index provisioning, namespaces, vectors, search, and bulk imports.
4
+ Import `render_lab_tasks_pinecone.tasks` for registration; each operation exports
5
+ an injectable async `*_impl(ctx, input, *, deps=...)` alongside the wrapped task.
6
+
7
+ `PINECONE_API_KEY` is required at first use. Data-plane calls first describe the
8
+ index to resolve its HTTPS host. REST requests use API version 2026-04, matching
9
+ the pinned TypeScript SDK 8.0.0. There are no transport retry loops. Stable vector
10
+ IDs support convergent upserts; startImport has no automatic durable retries.
11
+
12
+ Provisioning checks immutable dimension/metric/cloud/region fields. Search takes
13
+ exactly one vector or ID. Delete requires exactly one ids/filter/deleteAll mode.
14
+ Upsert/fetch are capped at 1,000 records; list/search/fetch DTOs are rejected at
15
+ 4 MiB. Namespace record counts that arrive as strings remain null, matching the
16
+ source mapping; this inherited loss is tracked for live validation.
17
+
18
+ Bulk import options map to errorMode.onError and integrationId. Await operations
19
+ poll by throwing. Terminal exceptions still follow the source durable policy.
20
+ The source provision error embeds undefined status because its message is built
21
+ before the first read; Python preserves it for source parity.
22
+
23
+ The hermetic fixtures run through the actual TS SDK with an injected fetch and
24
+ compare wire requests and DTO results. No live indexes, imports, or vector writes
25
+ have been performed. Account/region availability, namespace schema enforcement,
26
+ imports, bounds, and conflict recovery remain in the live-testing backlog.
27
+
28
+ ## Installation
29
+
30
+ ```sh
31
+ pip install render-lab-tasks-pinecone==0.1.0
32
+ ```
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27,<2"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "render-lab-tasks-pinecone"
7
+ version = "0.1.0"
8
+ description = "pinecone tasks for Render Workflows"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.12"
13
+ dependencies = ["render==1.0.1", "httpx>=0.28,<0.29", "render-lab-tasks-core>=0.1.1,<0.2"]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/render-lab/render-tasks-python"
17
+
18
+ [tool.uv.sources]
19
+ render-lab-tasks-core = { workspace = true }
20
+
21
+ [tool.hatch.build.targets.wheel]
22
+ packages = ["src/render_lab_tasks_pinecone"]
@@ -0,0 +1 @@
1
+ """Import .tasks explicitly to register durable tasks."""
@@ -0,0 +1,3 @@
1
+ from render import Workflows
2
+
3
+ app = Workflows()
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_IMPORT_RETRY
6
+ from .types import AwaitImportInput, ImportDTO
7
+
8
+
9
+ async def await_import_impl(
10
+ ctx: TaskContext, input: AwaitImportInput, *, deps: Deps | None = None
11
+ ) -> ImportDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.await_import(input)
14
+
15
+
16
+ @app.task(name="pinecone.awaitImport", retry=PINECONE_IMPORT_RETRY)
17
+ async def await_import(ctx: TaskContext, input: AwaitImportInput) -> ImportDTO:
18
+ return await await_import_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import CancelImportInput, CancelImportResult
7
+
8
+
9
+ async def cancel_import_impl(
10
+ ctx: TaskContext, input: CancelImportInput, *, deps: Deps | None = None
11
+ ) -> CancelImportResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.cancel_import(input)
14
+
15
+
16
+ @app.task(name="pinecone.cancelImport", retry=PINECONE_RETRY)
17
+ async def cancel_import(ctx: TaskContext, input: CancelImportInput) -> CancelImportResult:
18
+ return await cancel_import_impl(ctx, input)
@@ -0,0 +1,410 @@
1
+ """Injected vendor interface and one-attempt async HTTP adapter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from collections.abc import AsyncIterator, Mapping
8
+ from contextlib import asynccontextmanager
9
+ from dataclasses import dataclass
10
+ from datetime import UTC, datetime
11
+ from typing import Any, Protocol, cast
12
+ from urllib.parse import urlencode, urlsplit
13
+
14
+ import httpx
15
+ from render_lab_tasks_core.http import (
16
+ ApiError,
17
+ HttpClient,
18
+ enc,
19
+ js_string,
20
+ nullish,
21
+ pick,
22
+ query,
23
+ )
24
+
25
+ from . import types as t
26
+
27
+
28
+ def number(value: Any) -> float | None:
29
+ return value if isinstance(value, (int, float)) and not isinstance(value, bool) else None
30
+
31
+
32
+ def iso(value: str | None) -> str | None:
33
+ return (
34
+ None
35
+ if value is None
36
+ else datetime.fromisoformat(value.replace("Z", "+00:00"))
37
+ .astimezone(UTC)
38
+ .isoformat(timespec="milliseconds")
39
+ .replace("+00:00", "Z")
40
+ )
41
+
42
+
43
+ def enforce(value: Any, operation: str) -> None:
44
+ size = len(
45
+ json.dumps(value, ensure_ascii=False, allow_nan=False, separators=(",", ":")).encode()
46
+ )
47
+ if size >= 4194304:
48
+ raise ValueError(
49
+ f"{operation} returned {size} bytes, at or above the 4 MB task-result limit. "
50
+ "Lower the limit (fewer IDs, a smaller topK, or a tighter page) and retry."
51
+ )
52
+
53
+
54
+ def index_dto(raw: Any) -> dict[str, Any]:
55
+ spec = (raw.get("spec") or {}).get("serverless") or {}
56
+ status = raw["status"]["state"]
57
+ status = {"ScalingUpPodSize": "ScalingUp", "ScalingDownPodSize": "ScalingDown"}.get(
58
+ status, status
59
+ )
60
+ if status not in ("Ready", "Initializing", "ScalingUp", "ScalingDown", "Terminating"):
61
+ status = "Unknown"
62
+ return {
63
+ "name": raw["name"],
64
+ "host": raw["host"],
65
+ "dimension": raw.get("dimension", 0),
66
+ "metric": raw["metric"] if raw["metric"] in ("dotproduct", "euclidean") else "cosine",
67
+ "cloud": spec.get("cloud") if spec.get("cloud") in ("aws", "gcp", "azure") else None,
68
+ "region": spec.get("region"),
69
+ "status": status,
70
+ "ready": raw["status"]["ready"],
71
+ }
72
+
73
+
74
+ def namespace_dto(raw: Any) -> t.NamespaceDTO:
75
+ return {
76
+ "name": raw.get("name", ""),
77
+ "recordCount": number(raw.get("record_count")),
78
+ "schema": raw.get("schema"),
79
+ }
80
+
81
+
82
+ class Port(Protocol):
83
+ async def await_import(self, input: t.AwaitImportInput) -> t.ImportDTO: ...
84
+ async def cancel_import(self, input: t.CancelImportInput) -> t.CancelImportResult: ...
85
+ async def create_namespace(self, input: t.CreateNamespaceInput) -> t.NamespaceDTO: ...
86
+ async def delete_index(self, input: t.DeleteIndexInput) -> t.DeleteIndexResult: ...
87
+ async def delete_namespace(self, input: t.DeleteNamespaceInput) -> t.DeleteNamespaceResult: ...
88
+ async def delete_vectors(self, input: t.DeleteVectorsInput) -> t.DeleteVectorsResult: ...
89
+ async def fetch_vectors(self, input: t.FetchVectorsInput) -> t.FetchVectorsResult: ...
90
+ async def list_namespaces(self, input: t.ListNamespacesInput) -> t.ListNamespacesResult: ...
91
+ async def provision_index(self, input: t.ProvisionIndexInput) -> t.IndexDTO: ...
92
+ async def search(self, input: t.SearchInput) -> t.SearchResult: ...
93
+ async def start_import(self, input: t.StartImportInput) -> t.ImportDTO: ...
94
+ async def upsert_vectors(self, input: t.UpsertVectorsInput) -> t.UpsertVectorsResult: ...
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class Deps:
99
+ pinecone: Port
100
+
101
+
102
+ class Client:
103
+ def __init__(self, http: httpx.AsyncClient, env: Mapping[str, str] | None = None) -> None:
104
+ self.env = os.environ if env is None else env
105
+ self.http = http
106
+ self.api = HttpClient(
107
+ http, "https://api.pinecone.io", auth=self._auth, label="Pinecone API"
108
+ )
109
+
110
+ def _auth(self) -> dict[str, str]:
111
+ key = self.env.get("PINECONE_API_KEY")
112
+ if not key:
113
+ raise ValueError(
114
+ "PINECONE_API_KEY is not set. Pinecone tasks read it lazily on "
115
+ "first use; set it in the environment."
116
+ )
117
+ return {"Api-Key": key, "X-Pinecone-API-Version": "2026-04"}
118
+
119
+ async def _index(self, name: str) -> Any:
120
+ return await self.api.call(f"/indexes/{enc(name)}")
121
+
122
+ async def _data(self, name: str) -> HttpClient:
123
+ model = await self._index(name)
124
+ host = model["host"]
125
+ base = host if "://" in host else "https://" + host
126
+ parsed = urlsplit(base)
127
+ if parsed.scheme != "https" or not parsed.hostname or parsed.username or parsed.password:
128
+ raise ValueError(
129
+ "Pinecone index host must be an HTTPS host without embedded credentials"
130
+ )
131
+ return HttpClient(self.http, base.rstrip("/"), auth=self._auth, label="Pinecone data API")
132
+
133
+ async def provision_index(self, input: t.ProvisionIndexInput) -> t.IndexDTO:
134
+ try:
135
+ dto = index_dto(await self._index(input["name"]))
136
+ mismatches = [
137
+ f"{k} {js_string(dto[k])} != {js_string(input[k])}"
138
+ for k in ("dimension", "metric", "cloud", "region")
139
+ if dto[k] != input[k]
140
+ ]
141
+ if mismatches:
142
+ raise ValueError(
143
+ f'Pinecone index "{input["name"]}" exists with incompatible '
144
+ f"immutable settings: {', '.join(mismatches)}"
145
+ )
146
+ except ApiError as error:
147
+ if error.status != 404:
148
+ raise
149
+ await self.api.call(
150
+ "/indexes",
151
+ method="POST",
152
+ body={
153
+ **pick(input, "name", "dimension", "metric", "tags"),
154
+ "spec": {"serverless": {"cloud": input["cloud"], "region": input["region"]}},
155
+ "deletion_protection": input.get("deletionProtection", "disabled"),
156
+ },
157
+ )
158
+ dto = index_dto(await self._index(input["name"]))
159
+ if dto["status"] == "Terminating":
160
+ raise ValueError(f'Pinecone index "{input["name"]}" entered terminal status undefined')
161
+ if dto["status"] != "Ready":
162
+ raise ValueError(f'Pinecone index "{input["name"]}" is still provisioning')
163
+ return cast(t.IndexDTO, dto)
164
+
165
+ async def _convergent(
166
+ self, api: HttpClient, path: str, *, method: str = "DELETE", body: Any = None
167
+ ) -> None:
168
+ try:
169
+ if body is None:
170
+ await api.call(path, method=method)
171
+ else:
172
+ await api.call(path, method=method, body=body)
173
+ except ApiError as error:
174
+ if error.status not in (404, 409):
175
+ raise
176
+
177
+ async def delete_index(self, input: t.DeleteIndexInput) -> t.DeleteIndexResult:
178
+ await self._convergent(self.api, f"/indexes/{enc(input['name'])}")
179
+ return {"name": input["name"], "deleted": True}
180
+
181
+ async def create_namespace(self, input: t.CreateNamespaceInput) -> t.NamespaceDTO:
182
+ if not input["name"].strip():
183
+ raise ValueError("pinecone.createNamespace requires a nonempty namespace name.")
184
+ api = await self._data(input["indexName"])
185
+ try:
186
+ result = await api.call(
187
+ "/namespaces", method="POST", body=pick(input, "name", "schema")
188
+ )
189
+ except ApiError as error:
190
+ if error.status != 409:
191
+ raise
192
+ result = await api.call(f"/namespaces/{enc(input['name'])}")
193
+ return namespace_dto(result)
194
+
195
+ async def list_namespaces(self, input: t.ListNamespacesInput) -> t.ListNamespacesResult:
196
+ if input.get("limit", 0) > 1000:
197
+ raise ValueError(
198
+ f"pinecone.listNamespaces limit {input['limit']} exceeds the "
199
+ f"1,000-item maximum. Lower the limit and page with paginationToken."
200
+ )
201
+ api = await self._data(input["indexName"])
202
+ params = pick(input, "limit", "prefix")
203
+ if input.get("paginationToken"):
204
+ params["paginationToken"] = input["paginationToken"]
205
+ raw = await api.call("/namespaces" + ("?" + query(params) if params else ""))
206
+ result: t.ListNamespacesResult = {
207
+ "namespaces": [namespace_dto(n) for n in raw.get("namespaces", [])],
208
+ "nextPaginationToken": (raw.get("pagination") or {}).get("next"),
209
+ "totalCount": number(raw.get("total_count")),
210
+ }
211
+ enforce(result, "pinecone.listNamespaces")
212
+ return result
213
+
214
+ async def delete_namespace(self, input: t.DeleteNamespaceInput) -> t.DeleteNamespaceResult:
215
+ api = await self._data(input["indexName"])
216
+ await self._convergent(api, f"/namespaces/{enc(input['name'])}")
217
+ return {"indexName": input["indexName"], "name": input["name"], "deleted": True}
218
+
219
+ async def upsert_vectors(self, input: t.UpsertVectorsInput) -> t.UpsertVectorsResult:
220
+ vectors = input["vectors"]
221
+ if not vectors:
222
+ raise ValueError("pinecone.upsertVectors requires at least one vector.")
223
+ if len(vectors) > 1000:
224
+ raise ValueError(
225
+ f"pinecone.upsertVectors accepts at most 1,000 vectors per call; "
226
+ f"got {len(vectors)}. Split the batch."
227
+ )
228
+ seen = set()
229
+ dimension = len(vectors[0]["values"])
230
+ for vector in vectors:
231
+ identifier = vector["id"]
232
+ if not identifier.strip():
233
+ raise ValueError("pinecone.upsertVectors requires a nonempty id on every vector.")
234
+ if identifier in seen:
235
+ raise ValueError(
236
+ f'pinecone.upsertVectors received duplicate vector id "{identifier}".'
237
+ )
238
+ seen.add(identifier)
239
+ if not vector["values"]:
240
+ raise ValueError(f'pinecone.upsertVectors vector "{identifier}" has empty values.')
241
+ if len(vector["values"]) != dimension:
242
+ raise ValueError(
243
+ f'pinecone.upsertVectors vector "{identifier}" has dimension '
244
+ f"{len(vector['values'])}, expected {dimension}."
245
+ )
246
+ sparse = vector.get("sparseValues")
247
+ if sparse is not None and len(sparse["indices"]) != len(sparse["values"]):
248
+ raise ValueError(
249
+ f'pinecone.upsertVectors vector "{identifier}" sparse indices/values '
250
+ f"length mismatch."
251
+ )
252
+ api = await self._data(input["indexName"])
253
+ await api.call(
254
+ "/vectors/upsert",
255
+ method="POST",
256
+ body={"vectors": vectors, "namespace": input.get("namespace") or "__default__"},
257
+ )
258
+ return {"upsertedCount": len(vectors)}
259
+
260
+ async def fetch_vectors(self, input: t.FetchVectorsInput) -> t.FetchVectorsResult:
261
+ if not input["ids"]:
262
+ raise ValueError("pinecone.fetchVectors requires at least one id.")
263
+ if len(input["ids"]) > 1000:
264
+ raise ValueError(
265
+ f"pinecone.fetchVectors accepts at most 1,000 ids per call; got "
266
+ f"{len(input['ids'])}. Split the batch."
267
+ )
268
+ api = await self._data(input["indexName"])
269
+ params = [("ids", identifier) for identifier in input["ids"]] + [
270
+ ("namespace", input.get("namespace") or "__default__")
271
+ ]
272
+ raw = await api.call("/vectors/fetch?" + urlencode(params))
273
+ vectors: dict[str, t.VectorDTO] = {}
274
+ for key, record in raw.get("vectors", {}).items():
275
+ item: t.VectorDTO = {"id": record["id"], "values": record.get("values") or []}
276
+ if "sparseValues" in record:
277
+ item["sparseValues"] = record["sparseValues"]
278
+ if "metadata" in record:
279
+ item["metadata"] = (
280
+ record["metadata"] if isinstance(record["metadata"], dict) else {}
281
+ )
282
+ vectors[key] = item
283
+ result: t.FetchVectorsResult = {
284
+ "namespace": nullish(raw.get("namespace"), input.get("namespace", "")),
285
+ "vectors": vectors,
286
+ }
287
+ enforce(result, "pinecone.fetchVectors")
288
+ return result
289
+
290
+ async def delete_vectors(self, input: t.DeleteVectorsInput) -> t.DeleteVectorsResult:
291
+ modes = [k for k in ("ids", "deleteAll", "filter") if k in input]
292
+ if len(modes) != 1:
293
+ raise ValueError(
294
+ f"pinecone.deleteVectors requires exactly one of ids, deleteAll, "
295
+ f"or filter; got {', '.join(modes) if modes else 'none'}."
296
+ )
297
+ api = await self._data(input["indexName"])
298
+ body = {
299
+ **pick(input, "ids", "filter"),
300
+ "namespace": input.get("namespace") or "__default__",
301
+ }
302
+ if "deleteAll" in input:
303
+ body["deleteAll"] = True
304
+ await self._convergent(api, "/vectors/delete", method="POST", body=body)
305
+ return {"deleted": True}
306
+
307
+ async def search(self, input: t.SearchInput) -> t.SearchResult:
308
+ if ("vector" in input) == ("id" in input):
309
+ raise ValueError(
310
+ "pinecone.search requires exactly one of vector or id as the query selector."
311
+ )
312
+ if input["topK"] < 1 or input["topK"] > 1000:
313
+ raise ValueError(f"pinecone.search topK {input['topK']} must be between 1 and 1,000.")
314
+ api = await self._data(input["indexName"])
315
+ raw = await api.call(
316
+ "/query",
317
+ method="POST",
318
+ body={
319
+ **pick(input, "vector", "id", "topK", "filter", "includeValues", "includeMetadata"),
320
+ "namespace": input.get("namespace") or "__default__",
321
+ },
322
+ )
323
+ matches: list[t.SearchMatchDTO] = []
324
+ for row in raw.get("matches", []):
325
+ match: t.SearchMatchDTO = {
326
+ "id": row["id"],
327
+ "score": nullish(number(row.get("score")), 0),
328
+ }
329
+ if "values" in row:
330
+ match["values"] = row["values"]
331
+ if "metadata" in row:
332
+ match["metadata"] = row["metadata"] if isinstance(row["metadata"], dict) else {}
333
+ matches.append(match)
334
+ result: t.SearchResult = {
335
+ "namespace": nullish(raw.get("namespace"), input.get("namespace") or "__default__"),
336
+ "matches": matches,
337
+ }
338
+ enforce(result, "pinecone.search")
339
+ return result
340
+
341
+ async def start_import(self, input: t.StartImportInput) -> t.ImportDTO:
342
+ api = await self._data(input["indexName"])
343
+ if not input["uri"]:
344
+ raise ValueError(
345
+ "`uri` field is required and must start with the scheme of a "
346
+ "supported storage provider."
347
+ )
348
+ body: dict[str, Any] = {
349
+ "uri": input["uri"],
350
+ "errorMode": {"onError": input.get("errorMode") or "continue"},
351
+ }
352
+ if input.get("integration"):
353
+ body["integrationId"] = input["integration"]
354
+ result = await api.call("/bulk/imports", method="POST", body=body)
355
+ return {
356
+ "id": result.get("id", ""),
357
+ "uri": input["uri"],
358
+ "status": "Pending",
359
+ "createdAt": None,
360
+ "finishedAt": None,
361
+ "percentComplete": None,
362
+ "error": None,
363
+ }
364
+
365
+ async def await_import(self, input: t.AwaitImportInput) -> t.ImportDTO:
366
+ api = await self._data(input["indexName"])
367
+ raw = await api.call(f"/bulk/imports/{enc(input['importId'])}")
368
+ status = raw.get("status")
369
+ if status not in ("Pending", "InProgress", "Completed", "Failed", "Cancelled"):
370
+ status = "Unknown"
371
+ result: t.ImportDTO = {
372
+ "id": raw.get("id", input["importId"]),
373
+ "uri": raw.get("uri", ""),
374
+ "status": status,
375
+ "createdAt": iso(raw.get("createdAt")),
376
+ "finishedAt": iso(raw.get("finishedAt")),
377
+ "percentComplete": number(raw.get("percentComplete")),
378
+ "error": raw.get("error"),
379
+ }
380
+ if status == "Completed":
381
+ return result
382
+ if status in ("Pending", "InProgress", "Unknown"):
383
+ raise ValueError(
384
+ f"Pinecone import {input['importId']} is still in progress ({status})."
385
+ )
386
+ suffix = f": {result['error']}" if status == "Failed" and result["error"] else ""
387
+ raise ValueError(
388
+ f"Pinecone import {input['importId']} entered terminal status {status}{suffix}."
389
+ )
390
+
391
+ async def cancel_import(self, input: t.CancelImportInput) -> t.CancelImportResult:
392
+ api = await self._data(input["indexName"])
393
+ await self._convergent(api, f"/bulk/imports/{enc(input['importId'])}")
394
+ return {"indexName": input["indexName"], "importId": input["importId"], "cancelled": True}
395
+
396
+
397
+ @asynccontextmanager
398
+ async def dependencies(deps: Deps | None) -> AsyncIterator[Deps]:
399
+ if deps is not None:
400
+ yield deps
401
+ else:
402
+ async with httpx.AsyncClient(
403
+ timeout=30, transport=httpx.AsyncHTTPTransport(retries=0)
404
+ ) as http:
405
+ yield Deps(pinecone=Client(http))
406
+
407
+
408
+ PineconePort = Port
409
+ PineconeClient = Client
410
+ PineconeDeps = Deps
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import CreateNamespaceInput, NamespaceDTO
7
+
8
+
9
+ async def create_namespace_impl(
10
+ ctx: TaskContext, input: CreateNamespaceInput, *, deps: Deps | None = None
11
+ ) -> NamespaceDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.create_namespace(input)
14
+
15
+
16
+ @app.task(name="pinecone.createNamespace", retry=PINECONE_RETRY)
17
+ async def create_namespace(ctx: TaskContext, input: CreateNamespaceInput) -> NamespaceDTO:
18
+ return await create_namespace_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import DeleteIndexInput, DeleteIndexResult
7
+
8
+
9
+ async def delete_index_impl(
10
+ ctx: TaskContext, input: DeleteIndexInput, *, deps: Deps | None = None
11
+ ) -> DeleteIndexResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.delete_index(input)
14
+
15
+
16
+ @app.task(name="pinecone.deleteIndex", retry=PINECONE_RETRY)
17
+ async def delete_index(ctx: TaskContext, input: DeleteIndexInput) -> DeleteIndexResult:
18
+ return await delete_index_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import DeleteNamespaceInput, DeleteNamespaceResult
7
+
8
+
9
+ async def delete_namespace_impl(
10
+ ctx: TaskContext, input: DeleteNamespaceInput, *, deps: Deps | None = None
11
+ ) -> DeleteNamespaceResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.delete_namespace(input)
14
+
15
+
16
+ @app.task(name="pinecone.deleteNamespace", retry=PINECONE_RETRY)
17
+ async def delete_namespace(ctx: TaskContext, input: DeleteNamespaceInput) -> DeleteNamespaceResult:
18
+ return await delete_namespace_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import DeleteVectorsInput, DeleteVectorsResult
7
+
8
+
9
+ async def delete_vectors_impl(
10
+ ctx: TaskContext, input: DeleteVectorsInput, *, deps: Deps | None = None
11
+ ) -> DeleteVectorsResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.delete_vectors(input)
14
+
15
+
16
+ @app.task(name="pinecone.deleteVectors", retry=PINECONE_RETRY)
17
+ async def delete_vectors(ctx: TaskContext, input: DeleteVectorsInput) -> DeleteVectorsResult:
18
+ return await delete_vectors_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import FetchVectorsInput, FetchVectorsResult
7
+
8
+
9
+ async def fetch_vectors_impl(
10
+ ctx: TaskContext, input: FetchVectorsInput, *, deps: Deps | None = None
11
+ ) -> FetchVectorsResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.fetch_vectors(input)
14
+
15
+
16
+ @app.task(name="pinecone.fetchVectors", retry=PINECONE_RETRY)
17
+ async def fetch_vectors(ctx: TaskContext, input: FetchVectorsInput) -> FetchVectorsResult:
18
+ return await fetch_vectors_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import ListNamespacesInput, ListNamespacesResult
7
+
8
+
9
+ async def list_namespaces_impl(
10
+ ctx: TaskContext, input: ListNamespacesInput, *, deps: Deps | None = None
11
+ ) -> ListNamespacesResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.list_namespaces(input)
14
+
15
+
16
+ @app.task(name="pinecone.listNamespaces", retry=PINECONE_RETRY)
17
+ async def list_namespaces(ctx: TaskContext, input: ListNamespacesInput) -> ListNamespacesResult:
18
+ return await list_namespaces_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_PROVISION_RETRY
6
+ from .types import IndexDTO, ProvisionIndexInput
7
+
8
+
9
+ async def provision_index_impl(
10
+ ctx: TaskContext, input: ProvisionIndexInput, *, deps: Deps | None = None
11
+ ) -> IndexDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.provision_index(input)
14
+
15
+
16
+ @app.task(name="pinecone.provisionIndex", retry=PINECONE_PROVISION_RETRY)
17
+ async def provision_index(ctx: TaskContext, input: ProvisionIndexInput) -> IndexDTO:
18
+ return await provision_index_impl(ctx, input)
@@ -0,0 +1,6 @@
1
+ from render import Retry
2
+
3
+ PINECONE_IMPORT_RETRY = Retry(max_retries=2880, wait_duration_ms=30000, backoff_scaling=1)
4
+ PINECONE_RETRY = Retry(max_retries=3, wait_duration_ms=1000, backoff_scaling=2)
5
+ PINECONE_PROVISION_RETRY = Retry(max_retries=80, wait_duration_ms=15000, backoff_scaling=1)
6
+ PINECONE_NO_RETRY = Retry(max_retries=0, wait_duration_ms=0, backoff_scaling=1)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import SearchInput, SearchResult
7
+
8
+
9
+ async def search_impl(
10
+ ctx: TaskContext, input: SearchInput, *, deps: Deps | None = None
11
+ ) -> SearchResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.search(input)
14
+
15
+
16
+ @app.task(name="pinecone.search", retry=PINECONE_RETRY)
17
+ async def search(ctx: TaskContext, input: SearchInput) -> SearchResult:
18
+ return await search_impl(ctx, input)
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_NO_RETRY
6
+ from .types import ImportDTO, StartImportInput
7
+
8
+
9
+ async def start_import_impl(
10
+ ctx: TaskContext, input: StartImportInput, *, deps: Deps | None = None
11
+ ) -> ImportDTO:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.start_import(input)
14
+
15
+
16
+ @app.task(name="pinecone.startImport", retry=PINECONE_NO_RETRY)
17
+ async def start_import(ctx: TaskContext, input: StartImportInput) -> ImportDTO:
18
+ return await start_import_impl(ctx, input)
@@ -0,0 +1,41 @@
1
+ from ._app import app
2
+ from .await_import import await_import, await_import_impl
3
+ from .cancel_import import cancel_import, cancel_import_impl
4
+ from .create_namespace import create_namespace, create_namespace_impl
5
+ from .delete_index import delete_index, delete_index_impl
6
+ from .delete_namespace import delete_namespace, delete_namespace_impl
7
+ from .delete_vectors import delete_vectors, delete_vectors_impl
8
+ from .fetch_vectors import fetch_vectors, fetch_vectors_impl
9
+ from .list_namespaces import list_namespaces, list_namespaces_impl
10
+ from .provision_index import provision_index, provision_index_impl
11
+ from .search import search, search_impl
12
+ from .start_import import start_import, start_import_impl
13
+ from .upsert_vectors import upsert_vectors, upsert_vectors_impl
14
+
15
+ __all__ = [
16
+ "app",
17
+ "await_import",
18
+ "await_import_impl",
19
+ "cancel_import",
20
+ "cancel_import_impl",
21
+ "create_namespace",
22
+ "create_namespace_impl",
23
+ "delete_index",
24
+ "delete_index_impl",
25
+ "delete_namespace",
26
+ "delete_namespace_impl",
27
+ "delete_vectors",
28
+ "delete_vectors_impl",
29
+ "fetch_vectors",
30
+ "fetch_vectors_impl",
31
+ "list_namespaces",
32
+ "list_namespaces_impl",
33
+ "provision_index",
34
+ "provision_index_impl",
35
+ "search",
36
+ "search_impl",
37
+ "start_import",
38
+ "start_import_impl",
39
+ "upsert_vectors",
40
+ "upsert_vectors_impl",
41
+ ]
@@ -0,0 +1,238 @@
1
+ """JSON contracts ported from the pinned TypeScript pack."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal, NotRequired, TypedDict
6
+
7
+
8
+ class SearchInputValueVariant2(TypedDict):
9
+ indexName: str
10
+ namespace: NotRequired[str]
11
+ id: str
12
+ topK: float
13
+ filter: NotRequired[JsonObject]
14
+ includeValues: NotRequired[bool]
15
+ includeMetadata: NotRequired[bool]
16
+
17
+
18
+ class SearchInputValueVariant1(TypedDict):
19
+ indexName: str
20
+ namespace: NotRequired[str]
21
+ vector: list[float]
22
+ topK: float
23
+ filter: NotRequired[JsonObject]
24
+ includeValues: NotRequired[bool]
25
+ includeMetadata: NotRequired[bool]
26
+
27
+
28
+ class DeleteVectorsInputValueVariant3(TypedDict):
29
+ indexName: str
30
+ namespace: NotRequired[str]
31
+ filter: JsonObject
32
+
33
+
34
+ class DeleteVectorsInputValueVariant2(TypedDict):
35
+ indexName: str
36
+ namespace: NotRequired[str]
37
+ deleteAll: Literal[True]
38
+
39
+
40
+ class DeleteVectorsInputValueVariant1(TypedDict):
41
+ indexName: str
42
+ namespace: NotRequired[str]
43
+ ids: list[str]
44
+
45
+
46
+ type JsonPrimitive = str | float | bool | None
47
+
48
+ type JsonValue = JsonPrimitive | list[JsonValue] | dict[str, JsonValue]
49
+
50
+ type JsonObject = dict[str, JsonValue]
51
+
52
+ type PineconeMetric = Literal["cosine"] | Literal["dotproduct"] | Literal["euclidean"]
53
+
54
+ type PineconeCloud = Literal["aws"] | Literal["gcp"] | Literal["azure"]
55
+
56
+ type IndexStatus = (
57
+ Literal["Initializing"]
58
+ | Literal["ScalingUp"]
59
+ | Literal["ScalingDown"]
60
+ | Literal["Ready"]
61
+ | Literal["Terminating"]
62
+ | Literal["Unknown"]
63
+ )
64
+
65
+ type ImportStatus = (
66
+ Literal["Pending"]
67
+ | Literal["InProgress"]
68
+ | Literal["Completed"]
69
+ | Literal["Failed"]
70
+ | Literal["Cancelled"]
71
+ | Literal["Unknown"]
72
+ )
73
+
74
+
75
+ class MetadataFieldSchema(TypedDict):
76
+ filterable: Literal[True]
77
+
78
+
79
+ class MetadataSchema(TypedDict):
80
+ fields: dict[str, MetadataFieldSchema]
81
+
82
+
83
+ class ProvisionIndexInput(TypedDict):
84
+ name: str
85
+ dimension: float
86
+ metric: PineconeMetric
87
+ cloud: PineconeCloud
88
+ region: str
89
+ deletionProtection: NotRequired[Literal["enabled"] | Literal["disabled"]]
90
+ tags: NotRequired[dict[str, str]]
91
+
92
+
93
+ class IndexDTO(TypedDict):
94
+ name: str
95
+ host: str
96
+ dimension: float
97
+ metric: PineconeMetric
98
+ cloud: PineconeCloud | None
99
+ region: str | None
100
+ status: IndexStatus
101
+ ready: bool
102
+
103
+
104
+ class DeleteIndexInput(TypedDict):
105
+ name: str
106
+
107
+
108
+ class DeleteIndexResult(TypedDict):
109
+ name: str
110
+ deleted: Literal[True]
111
+
112
+
113
+ class CreateNamespaceInput(TypedDict):
114
+ indexName: str
115
+ name: str
116
+ schema: NotRequired[MetadataSchema]
117
+
118
+
119
+ class NamespaceDTO(TypedDict):
120
+ name: str
121
+ recordCount: float | None
122
+ schema: MetadataSchema | None
123
+
124
+
125
+ class ListNamespacesInput(TypedDict):
126
+ indexName: str
127
+ prefix: NotRequired[str]
128
+ limit: NotRequired[float]
129
+ paginationToken: NotRequired[str]
130
+
131
+
132
+ class ListNamespacesResult(TypedDict):
133
+ namespaces: list[NamespaceDTO]
134
+ nextPaginationToken: str | None
135
+ totalCount: float | None
136
+
137
+
138
+ class DeleteNamespaceInput(TypedDict):
139
+ indexName: str
140
+ name: str
141
+
142
+
143
+ class DeleteNamespaceResult(TypedDict):
144
+ indexName: str
145
+ name: str
146
+ deleted: Literal[True]
147
+
148
+
149
+ class SparseValues(TypedDict):
150
+ indices: list[float]
151
+ values: list[float]
152
+
153
+
154
+ class VectorDTO(TypedDict):
155
+ id: str
156
+ values: list[float]
157
+ sparseValues: NotRequired[SparseValues]
158
+ metadata: NotRequired[JsonObject]
159
+
160
+
161
+ class UpsertVectorsInput(TypedDict):
162
+ indexName: str
163
+ namespace: NotRequired[str]
164
+ vectors: list[VectorDTO]
165
+
166
+
167
+ class UpsertVectorsResult(TypedDict):
168
+ upsertedCount: float
169
+
170
+
171
+ class FetchVectorsInput(TypedDict):
172
+ indexName: str
173
+ namespace: NotRequired[str]
174
+ ids: list[str]
175
+
176
+
177
+ class FetchVectorsResult(TypedDict):
178
+ namespace: str
179
+ vectors: dict[str, VectorDTO]
180
+
181
+
182
+ type DeleteVectorsInput = (
183
+ DeleteVectorsInputValueVariant1
184
+ | DeleteVectorsInputValueVariant2
185
+ | DeleteVectorsInputValueVariant3
186
+ )
187
+
188
+
189
+ class DeleteVectorsResult(TypedDict):
190
+ deleted: Literal[True]
191
+
192
+
193
+ type SearchInput = SearchInputValueVariant1 | SearchInputValueVariant2
194
+
195
+
196
+ class SearchMatchDTO(TypedDict):
197
+ id: str
198
+ score: float
199
+ values: NotRequired[list[float]]
200
+ metadata: NotRequired[JsonObject]
201
+
202
+
203
+ class SearchResult(TypedDict):
204
+ namespace: str
205
+ matches: list[SearchMatchDTO]
206
+
207
+
208
+ class StartImportInput(TypedDict):
209
+ indexName: str
210
+ uri: str
211
+ errorMode: NotRequired[Literal["abort"] | Literal["continue"]]
212
+ integration: NotRequired[str]
213
+
214
+
215
+ class ImportDTO(TypedDict):
216
+ id: str
217
+ uri: str
218
+ status: ImportStatus
219
+ createdAt: str | None
220
+ finishedAt: str | None
221
+ percentComplete: float | None
222
+ error: str | None
223
+
224
+
225
+ class AwaitImportInput(TypedDict):
226
+ indexName: str
227
+ importId: str
228
+
229
+
230
+ class CancelImportInput(TypedDict):
231
+ indexName: str
232
+ importId: str
233
+
234
+
235
+ class CancelImportResult(TypedDict):
236
+ indexName: str
237
+ importId: str
238
+ cancelled: Literal[True]
@@ -0,0 +1,18 @@
1
+ from render import TaskContext
2
+
3
+ from ._app import app
4
+ from .client import Deps, dependencies
5
+ from .retry import PINECONE_RETRY
6
+ from .types import UpsertVectorsInput, UpsertVectorsResult
7
+
8
+
9
+ async def upsert_vectors_impl(
10
+ ctx: TaskContext, input: UpsertVectorsInput, *, deps: Deps | None = None
11
+ ) -> UpsertVectorsResult:
12
+ async with dependencies(deps) as resolved:
13
+ return await resolved.pinecone.upsert_vectors(input)
14
+
15
+
16
+ @app.task(name="pinecone.upsertVectors", retry=PINECONE_RETRY)
17
+ async def upsert_vectors(ctx: TaskContext, input: UpsertVectorsInput) -> UpsertVectorsResult:
18
+ return await upsert_vectors_impl(ctx, input)