@mastra/pinecone 1.1.0 → 1.1.1-alpha.0

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.
package/dist/index.js CHANGED
@@ -1,524 +1,441 @@
1
- import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { createVectorErrorId } from '@mastra/core/storage';
3
- import { MastraVector } from '@mastra/core/vector';
4
- import { Pinecone } from '@pinecone-database/pinecone';
5
- import { BaseFilterTranslator } from '@mastra/core/vector/filter';
6
-
7
- // src/vector/index.ts
1
+ import { ErrorCategory, ErrorDomain, MastraError } from "@mastra/core/error";
2
+ import { createVectorErrorId } from "@mastra/core/storage";
3
+ import { MastraVector } from "@mastra/core/vector";
4
+ import { Pinecone } from "@pinecone-database/pinecone";
5
+ import { BaseFilterTranslator } from "@mastra/core/vector/filter";
6
+ //#region src/vector/filter.ts
8
7
  var PineconeFilterTranslator = class extends BaseFilterTranslator {
9
- getSupportedOperators() {
10
- return {
11
- ...BaseFilterTranslator.DEFAULT_OPERATORS,
12
- logical: ["$and", "$or"],
13
- array: ["$in", "$all", "$nin"],
14
- element: ["$exists"],
15
- regex: [],
16
- custom: []
17
- };
18
- }
19
- translate(filter) {
20
- if (this.isEmpty(filter)) return filter;
21
- this.validateFilter(filter);
22
- return this.translateNode(filter);
23
- }
24
- translateNode(node, currentPath = "") {
25
- if (this.isRegex(node)) {
26
- throw new Error("Regex is not supported in Pinecone");
27
- }
28
- if (this.isPrimitive(node)) return this.normalizeComparisonValue(node);
29
- if (Array.isArray(node)) return { $in: this.normalizeArrayValues(node) };
30
- const entries = Object.entries(node);
31
- const firstEntry = entries[0];
32
- if (entries.length === 1 && firstEntry && this.isOperator(firstEntry[0])) {
33
- const [operator, value] = firstEntry;
34
- const translated = this.translateOperator(operator, value, currentPath);
35
- return this.isLogicalOperator(operator) ? { [operator]: translated } : translated;
36
- }
37
- const result = {};
38
- for (const [key, value] of entries) {
39
- const newPath = currentPath ? `${currentPath}.${key}` : key;
40
- if (this.isOperator(key)) {
41
- result[key] = this.translateOperator(key, value, currentPath);
42
- continue;
43
- }
44
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
45
- if (Object.keys(value).length === 1 && "$all" in value) {
46
- const translated = this.translateNode(value, key);
47
- if (translated.$and) {
48
- return translated;
49
- }
50
- }
51
- if (Object.keys(value).length === 0) {
52
- result[newPath] = this.translateNode(value);
53
- } else {
54
- const hasOperators = Object.keys(value).some((k) => this.isOperator(k));
55
- if (hasOperators) {
56
- const normalizedValue = {};
57
- for (const [op, opValue] of Object.entries(value)) {
58
- normalizedValue[op] = this.isOperator(op) ? this.translateOperator(op, opValue) : opValue;
59
- }
60
- result[newPath] = normalizedValue;
61
- } else {
62
- Object.assign(result, this.translateNode(value, newPath));
63
- }
64
- }
65
- } else {
66
- result[newPath] = this.translateNode(value);
67
- }
68
- }
69
- return result;
70
- }
71
- translateOperator(operator, value, currentPath = "") {
72
- if (operator === "$all") {
73
- if (!Array.isArray(value) || value.length === 0) {
74
- throw new Error("A non-empty array is required for the $all operator");
75
- }
76
- return this.simulateAllOperator(currentPath, value);
77
- }
78
- if (this.isLogicalOperator(operator)) {
79
- return Array.isArray(value) ? value.map((item) => this.translateNode(item)) : this.translateNode(value);
80
- }
81
- return this.normalizeComparisonValue(value);
82
- }
8
+ getSupportedOperators() {
9
+ return {
10
+ ...BaseFilterTranslator.DEFAULT_OPERATORS,
11
+ logical: ["$and", "$or"],
12
+ array: [
13
+ "$in",
14
+ "$all",
15
+ "$nin"
16
+ ],
17
+ element: ["$exists"],
18
+ regex: [],
19
+ custom: []
20
+ };
21
+ }
22
+ translate(filter) {
23
+ if (this.isEmpty(filter)) return filter;
24
+ this.validateFilter(filter);
25
+ return this.translateNode(filter);
26
+ }
27
+ translateNode(node, currentPath = "") {
28
+ if (this.isRegex(node)) throw new Error("Regex is not supported in Pinecone");
29
+ if (this.isPrimitive(node)) return this.normalizeComparisonValue(node);
30
+ if (Array.isArray(node)) return { $in: this.normalizeArrayValues(node) };
31
+ const entries = Object.entries(node);
32
+ const firstEntry = entries[0];
33
+ if (entries.length === 1 && firstEntry && this.isOperator(firstEntry[0])) {
34
+ const [operator, value] = firstEntry;
35
+ const translated = this.translateOperator(operator, value, currentPath);
36
+ return this.isLogicalOperator(operator) ? { [operator]: translated } : translated;
37
+ }
38
+ const result = {};
39
+ for (const [key, value] of entries) {
40
+ const newPath = currentPath ? `${currentPath}.${key}` : key;
41
+ if (this.isOperator(key)) {
42
+ result[key] = this.translateOperator(key, value, currentPath);
43
+ continue;
44
+ }
45
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
46
+ if (Object.keys(value).length === 1 && "$all" in value) {
47
+ const translated = this.translateNode(value, key);
48
+ if (translated.$and) return translated;
49
+ }
50
+ if (Object.keys(value).length === 0) result[newPath] = this.translateNode(value);
51
+ else if (Object.keys(value).some((k) => this.isOperator(k))) {
52
+ const normalizedValue = {};
53
+ for (const [op, opValue] of Object.entries(value)) normalizedValue[op] = this.isOperator(op) ? this.translateOperator(op, opValue) : opValue;
54
+ result[newPath] = normalizedValue;
55
+ } else Object.assign(result, this.translateNode(value, newPath));
56
+ } else result[newPath] = this.translateNode(value);
57
+ }
58
+ return result;
59
+ }
60
+ translateOperator(operator, value, currentPath = "") {
61
+ if (operator === "$all") {
62
+ if (!Array.isArray(value) || value.length === 0) throw new Error("A non-empty array is required for the $all operator");
63
+ return this.simulateAllOperator(currentPath, value);
64
+ }
65
+ if (this.isLogicalOperator(operator)) return Array.isArray(value) ? value.map((item) => this.translateNode(item)) : this.translateNode(value);
66
+ return this.normalizeComparisonValue(value);
67
+ }
83
68
  };
84
-
85
- // src/vector/index.ts
69
+ //#endregion
70
+ //#region src/vector/index.ts
86
71
  var PineconeVector = class extends MastraVector {
87
- client;
88
- cloud;
89
- region;
90
- /**
91
- * Creates a new PineconeVector client.
92
- *
93
- * @param config - Configuration options for the Pinecone client.
94
- * @see {@link PineconeVectorConfig} for all available options.
95
- */
96
- constructor({ id, cloud, region, ...pineconeConfig }) {
97
- super({ id });
98
- this.client = new Pinecone(pineconeConfig);
99
- this.cloud = cloud || "aws";
100
- this.region = region || "us-east-1";
101
- }
102
- get indexSeparator() {
103
- return "-";
104
- }
105
- async createIndex({ indexName, dimension, metric = "cosine" }) {
106
- try {
107
- if (!Number.isInteger(dimension) || dimension <= 0) {
108
- throw new Error("Dimension must be a positive integer");
109
- }
110
- if (metric && !["cosine", "euclidean", "dotproduct"].includes(metric)) {
111
- throw new Error("Metric must be one of: cosine, euclidean, dotproduct");
112
- }
113
- } catch (validationError) {
114
- throw new MastraError(
115
- {
116
- id: createVectorErrorId("PINECONE", "CREATE_INDEX", "INVALID_ARGS"),
117
- domain: ErrorDomain.STORAGE,
118
- category: ErrorCategory.USER,
119
- details: { indexName, dimension, metric }
120
- },
121
- validationError
122
- );
123
- }
124
- try {
125
- await this.client.createIndex({
126
- name: indexName,
127
- dimension,
128
- metric,
129
- spec: {
130
- serverless: {
131
- cloud: this.cloud,
132
- region: this.region
133
- }
134
- }
135
- });
136
- } catch (error) {
137
- const message = error?.errors?.[0]?.message || error?.message;
138
- if (error.status === 409 || typeof message === "string" && (message.toLowerCase().includes("already exists") || message.toLowerCase().includes("duplicate"))) {
139
- await this.validateExistingIndex(indexName, dimension, metric);
140
- return;
141
- }
142
- throw new MastraError(
143
- {
144
- id: createVectorErrorId("PINECONE", "CREATE_INDEX", "FAILED"),
145
- domain: ErrorDomain.STORAGE,
146
- category: ErrorCategory.THIRD_PARTY,
147
- details: { indexName, dimension, metric }
148
- },
149
- error
150
- );
151
- }
152
- }
153
- async upsert({
154
- indexName,
155
- vectors,
156
- metadata,
157
- ids,
158
- namespace,
159
- sparseVectors
160
- }) {
161
- const index = this.client.Index(indexName).namespace(namespace || "");
162
- const vectorIds = ids || vectors.map(() => crypto.randomUUID());
163
- const records = vectors.map((vector, i) => ({
164
- id: vectorIds[i],
165
- values: vector,
166
- ...sparseVectors?.[i] && { sparseValues: sparseVectors?.[i] },
167
- metadata: metadata?.[i] || {}
168
- }));
169
- const batchSize = 100;
170
- try {
171
- for (let i = 0; i < records.length; i += batchSize) {
172
- const batch = records.slice(i, i + batchSize);
173
- await index.upsert(batch);
174
- }
175
- return vectorIds;
176
- } catch (error) {
177
- throw new MastraError(
178
- {
179
- id: createVectorErrorId("PINECONE", "UPSERT", "FAILED"),
180
- domain: ErrorDomain.STORAGE,
181
- category: ErrorCategory.THIRD_PARTY,
182
- details: { indexName, vectorCount: vectors.length }
183
- },
184
- error
185
- );
186
- }
187
- }
188
- transformFilter(filter) {
189
- const translator = new PineconeFilterTranslator();
190
- return translator.translate(filter);
191
- }
192
- async query({
193
- indexName,
194
- queryVector,
195
- topK = 10,
196
- filter,
197
- includeVector = false,
198
- namespace,
199
- sparseVector
200
- }) {
201
- if (!queryVector) {
202
- throw new MastraError({
203
- id: createVectorErrorId("PINECONE", "QUERY", "MISSING_VECTOR"),
204
- text: "queryVector is required for Pinecone queries. Metadata-only queries are not supported by this vector store.",
205
- domain: ErrorDomain.STORAGE,
206
- category: ErrorCategory.USER,
207
- details: { indexName }
208
- });
209
- }
210
- const index = this.client.Index(indexName).namespace(namespace || "");
211
- const translatedFilter = this.transformFilter(filter) ?? void 0;
212
- const queryParams = {
213
- vector: queryVector,
214
- topK,
215
- includeMetadata: true,
216
- includeValues: includeVector,
217
- filter: translatedFilter
218
- };
219
- if (sparseVector) {
220
- queryParams.sparseVector = sparseVector;
221
- }
222
- try {
223
- const results = await index.query(queryParams);
224
- return results.matches.map((match) => ({
225
- id: match.id,
226
- score: match.score || 0,
227
- metadata: match.metadata,
228
- ...includeVector && { vector: match.values || [] }
229
- }));
230
- } catch (error) {
231
- throw new MastraError(
232
- {
233
- id: createVectorErrorId("PINECONE", "QUERY", "FAILED"),
234
- domain: ErrorDomain.STORAGE,
235
- category: ErrorCategory.THIRD_PARTY,
236
- details: { indexName, topK }
237
- },
238
- error
239
- );
240
- }
241
- }
242
- async listIndexes() {
243
- try {
244
- const indexesResult = await this.client.listIndexes();
245
- return indexesResult?.indexes?.map((index) => index.name) || [];
246
- } catch (error) {
247
- throw new MastraError(
248
- {
249
- id: createVectorErrorId("PINECONE", "LIST_INDEXES", "FAILED"),
250
- domain: ErrorDomain.STORAGE,
251
- category: ErrorCategory.THIRD_PARTY
252
- },
253
- error
254
- );
255
- }
256
- }
257
- /**
258
- * Retrieves statistics about a vector index.
259
- *
260
- * @param {string} indexName - The name of the index to describe
261
- * @returns A promise that resolves to the index statistics including dimension, count and metric
262
- */
263
- async describeIndex({ indexName }) {
264
- try {
265
- const index = this.client.Index(indexName);
266
- const stats = await index.describeIndexStats();
267
- const description = await this.client.describeIndex(indexName);
268
- return {
269
- dimension: description.dimension,
270
- count: stats.totalRecordCount || 0,
271
- metric: description.metric,
272
- namespaces: stats.namespaces
273
- };
274
- } catch (error) {
275
- throw new MastraError(
276
- {
277
- id: createVectorErrorId("PINECONE", "DESCRIBE_INDEX", "FAILED"),
278
- domain: ErrorDomain.STORAGE,
279
- category: ErrorCategory.THIRD_PARTY,
280
- details: { indexName }
281
- },
282
- error
283
- );
284
- }
285
- }
286
- async deleteIndex({ indexName }) {
287
- try {
288
- await this.client.deleteIndex(indexName);
289
- } catch (error) {
290
- throw new MastraError(
291
- {
292
- id: createVectorErrorId("PINECONE", "DELETE_INDEX", "FAILED"),
293
- domain: ErrorDomain.STORAGE,
294
- category: ErrorCategory.THIRD_PARTY,
295
- details: { indexName }
296
- },
297
- error
298
- );
299
- }
300
- }
301
- /**
302
- * Updates a vector by its ID with the provided vector and/or metadata.
303
- * Note: Pinecone only supports update by ID, not by filter.
304
- * @param params - Parameters containing the id for targeting the vector to update
305
- * @param params.indexName - The name of the index containing the vector.
306
- * @param params.id - The ID of the vector to update.
307
- * @param params.update - An object containing the vector and/or metadata to update.
308
- * @param namespace - The namespace of the index (optional, Pinecone-specific).
309
- * @returns A promise that resolves when the update is complete.
310
- * @throws Will throw an error if no updates are provided or if the update operation fails.
311
- */
312
- async updateVector(params) {
313
- const { indexName, update } = params;
314
- if ("id" in params && params.id && "filter" in params && params.filter) {
315
- throw new MastraError({
316
- id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "MUTUALLY_EXCLUSIVE"),
317
- text: "Cannot specify both id and filter - they are mutually exclusive",
318
- domain: ErrorDomain.STORAGE,
319
- category: ErrorCategory.USER,
320
- details: { indexName }
321
- });
322
- }
323
- if (!("id" in params && params.id) && !("filter" in params && params.filter)) {
324
- throw new MastraError({
325
- id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "NO_TARGET"),
326
- text: "Either id or filter must be provided",
327
- domain: ErrorDomain.STORAGE,
328
- category: ErrorCategory.USER,
329
- details: { indexName }
330
- });
331
- }
332
- if (!update.vector && !update.metadata) {
333
- throw new MastraError({
334
- id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "NO_PAYLOAD"),
335
- domain: ErrorDomain.STORAGE,
336
- category: ErrorCategory.USER,
337
- text: "No updates provided",
338
- details: { indexName }
339
- });
340
- }
341
- const namespace = params.namespace;
342
- try {
343
- const index = this.client.Index(indexName).namespace(namespace || "");
344
- if ("id" in params && params.id) {
345
- const updateObj = { id: params.id };
346
- if (update.vector) {
347
- updateObj.values = update.vector;
348
- }
349
- if (update.metadata) {
350
- updateObj.metadata = update.metadata;
351
- }
352
- await index.update(updateObj);
353
- } else if ("filter" in params && params.filter) {
354
- if (Object.keys(params.filter).length === 0) {
355
- throw new MastraError({
356
- id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "EMPTY_FILTER"),
357
- text: "Filter cannot be an empty filter object",
358
- domain: ErrorDomain.STORAGE,
359
- category: ErrorCategory.USER,
360
- details: { indexName }
361
- });
362
- }
363
- const translatedFilter = this.transformFilter(params.filter);
364
- if (translatedFilter) {
365
- const stats = await this.describeIndex({ indexName });
366
- const dummyVector = new Array(stats.dimension).fill(1 / Math.sqrt(stats.dimension));
367
- const results = await index.query({
368
- vector: dummyVector,
369
- topK: 1e4,
370
- filter: translatedFilter,
371
- includeMetadata: false,
372
- includeValues: false
373
- });
374
- const idsToUpdate = results.matches.map((m) => m.id);
375
- for (const id of idsToUpdate) {
376
- const updateObj = { id };
377
- if (update.vector) {
378
- updateObj.values = update.vector;
379
- }
380
- if (update.metadata) {
381
- updateObj.metadata = update.metadata;
382
- }
383
- await index.update(updateObj);
384
- }
385
- }
386
- }
387
- } catch (error) {
388
- if (error instanceof MastraError) throw error;
389
- throw new MastraError(
390
- {
391
- id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "FAILED"),
392
- domain: ErrorDomain.STORAGE,
393
- category: ErrorCategory.THIRD_PARTY,
394
- details: {
395
- indexName,
396
- ..."id" in params && params.id && { id: params.id },
397
- ..."filter" in params && params.filter && { filter: JSON.stringify(params.filter) }
398
- }
399
- },
400
- error
401
- );
402
- }
403
- }
404
- /**
405
- * Deletes a vector by its ID.
406
- * @param indexName - The name of the index containing the vector.
407
- * @param id - The ID of the vector to delete.
408
- * @param namespace - The namespace of the index (optional).
409
- * @returns A promise that resolves when the deletion is complete.
410
- * @throws Will throw an error if the deletion operation fails.
411
- */
412
- async deleteVector({ indexName, id, namespace }) {
413
- try {
414
- const index = this.client.Index(indexName).namespace(namespace || "");
415
- await index.deleteOne(id);
416
- } catch (error) {
417
- throw new MastraError(
418
- {
419
- id: createVectorErrorId("PINECONE", "DELETE_VECTOR", "FAILED"),
420
- domain: ErrorDomain.STORAGE,
421
- category: ErrorCategory.THIRD_PARTY,
422
- details: {
423
- indexName,
424
- ...id && { id }
425
- }
426
- },
427
- error
428
- );
429
- }
430
- }
431
- /**
432
- * Deletes multiple vectors by IDs or filter.
433
- * @param indexName - The name of the index containing the vectors.
434
- * @param ids - Array of vector IDs to delete (mutually exclusive with filter).
435
- * @param filter - Filter to match vectors to delete (mutually exclusive with ids).
436
- * @param namespace - The namespace of the index (optional, Pinecone-specific).
437
- * @returns A promise that resolves when the deletion is complete.
438
- * @throws Will throw an error if both ids and filter are provided, or if neither is provided.
439
- */
440
- async deleteVectors(params) {
441
- const { indexName, filter, ids } = params;
442
- const namespace = params.namespace;
443
- if (ids && filter) {
444
- throw new MastraError({
445
- id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "MUTUALLY_EXCLUSIVE"),
446
- text: "Cannot specify both ids and filter - they are mutually exclusive",
447
- domain: ErrorDomain.STORAGE,
448
- category: ErrorCategory.USER,
449
- details: { indexName }
450
- });
451
- }
452
- if (!ids && !filter) {
453
- throw new MastraError({
454
- id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "NO_TARGET"),
455
- text: "Either filter or ids must be provided",
456
- domain: ErrorDomain.STORAGE,
457
- category: ErrorCategory.USER,
458
- details: { indexName }
459
- });
460
- }
461
- if (ids && ids.length === 0) {
462
- throw new MastraError({
463
- id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "EMPTY_IDS"),
464
- text: "Cannot delete with empty ids array",
465
- domain: ErrorDomain.STORAGE,
466
- category: ErrorCategory.USER,
467
- details: { indexName }
468
- });
469
- }
470
- if (filter && Object.keys(filter).length === 0) {
471
- throw new MastraError({
472
- id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "EMPTY_FILTER"),
473
- text: "Cannot delete with empty filter object",
474
- domain: ErrorDomain.STORAGE,
475
- category: ErrorCategory.USER,
476
- details: { indexName }
477
- });
478
- }
479
- try {
480
- const index = this.client.Index(indexName).namespace(namespace || "");
481
- if (ids) {
482
- await index.deleteMany(ids);
483
- } else if (filter) {
484
- const translatedFilter = this.transformFilter(filter);
485
- if (translatedFilter) {
486
- const stats = await this.describeIndex({ indexName });
487
- const dummyVector = new Array(stats.dimension).fill(1 / Math.sqrt(stats.dimension));
488
- const results = await index.query({
489
- vector: dummyVector,
490
- topK: 1e4,
491
- filter: translatedFilter,
492
- includeMetadata: false,
493
- includeValues: false
494
- });
495
- const idsToDelete = results.matches.map((m) => m.id);
496
- if (idsToDelete.length > 0) {
497
- await index.deleteMany(idsToDelete);
498
- }
499
- }
500
- }
501
- } catch (error) {
502
- if (error instanceof MastraError) throw error;
503
- throw new MastraError(
504
- {
505
- id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "FAILED"),
506
- domain: ErrorDomain.STORAGE,
507
- category: ErrorCategory.THIRD_PARTY,
508
- details: {
509
- indexName,
510
- ...filter && { filter: JSON.stringify(filter) },
511
- ...ids && { idsCount: ids.length }
512
- }
513
- },
514
- error
515
- );
516
- }
517
- }
72
+ client;
73
+ cloud;
74
+ region;
75
+ /**
76
+ * Creates a new PineconeVector client.
77
+ *
78
+ * @param config - Configuration options for the Pinecone client.
79
+ * @see {@link PineconeVectorConfig} for all available options.
80
+ */
81
+ constructor({ id, cloud, region, ...pineconeConfig }) {
82
+ super({ id });
83
+ this.client = new Pinecone(pineconeConfig);
84
+ this.cloud = cloud || "aws";
85
+ this.region = region || "us-east-1";
86
+ }
87
+ get indexSeparator() {
88
+ return "-";
89
+ }
90
+ async createIndex({ indexName, dimension, metric = "cosine" }) {
91
+ try {
92
+ if (!Number.isInteger(dimension) || dimension <= 0) throw new Error("Dimension must be a positive integer");
93
+ if (metric && ![
94
+ "cosine",
95
+ "euclidean",
96
+ "dotproduct"
97
+ ].includes(metric)) throw new Error("Metric must be one of: cosine, euclidean, dotproduct");
98
+ } catch (validationError) {
99
+ throw new MastraError({
100
+ id: createVectorErrorId("PINECONE", "CREATE_INDEX", "INVALID_ARGS"),
101
+ domain: ErrorDomain.STORAGE,
102
+ category: ErrorCategory.USER,
103
+ details: {
104
+ indexName,
105
+ dimension,
106
+ metric
107
+ }
108
+ }, validationError);
109
+ }
110
+ try {
111
+ await this.client.createIndex({
112
+ name: indexName,
113
+ dimension,
114
+ metric,
115
+ spec: { serverless: {
116
+ cloud: this.cloud,
117
+ region: this.region
118
+ } }
119
+ });
120
+ } catch (error) {
121
+ const message = error?.errors?.[0]?.message || error?.message;
122
+ if (error.status === 409 || typeof message === "string" && (message.toLowerCase().includes("already exists") || message.toLowerCase().includes("duplicate"))) {
123
+ await this.validateExistingIndex(indexName, dimension, metric);
124
+ return;
125
+ }
126
+ throw new MastraError({
127
+ id: createVectorErrorId("PINECONE", "CREATE_INDEX", "FAILED"),
128
+ domain: ErrorDomain.STORAGE,
129
+ category: ErrorCategory.THIRD_PARTY,
130
+ details: {
131
+ indexName,
132
+ dimension,
133
+ metric
134
+ }
135
+ }, error);
136
+ }
137
+ }
138
+ async upsert({ indexName, vectors, metadata, ids, namespace, sparseVectors }) {
139
+ const index = this.client.Index(indexName).namespace(namespace || "");
140
+ const vectorIds = ids || vectors.map(() => crypto.randomUUID());
141
+ const records = vectors.map((vector, i) => ({
142
+ id: vectorIds[i],
143
+ values: vector,
144
+ ...sparseVectors?.[i] && { sparseValues: sparseVectors?.[i] },
145
+ metadata: metadata?.[i] || {}
146
+ }));
147
+ const batchSize = 100;
148
+ try {
149
+ for (let i = 0; i < records.length; i += batchSize) {
150
+ const batch = records.slice(i, i + batchSize);
151
+ await index.upsert(batch);
152
+ }
153
+ return vectorIds;
154
+ } catch (error) {
155
+ throw new MastraError({
156
+ id: createVectorErrorId("PINECONE", "UPSERT", "FAILED"),
157
+ domain: ErrorDomain.STORAGE,
158
+ category: ErrorCategory.THIRD_PARTY,
159
+ details: {
160
+ indexName,
161
+ vectorCount: vectors.length
162
+ }
163
+ }, error);
164
+ }
165
+ }
166
+ transformFilter(filter) {
167
+ return new PineconeFilterTranslator().translate(filter);
168
+ }
169
+ async query({ indexName, queryVector, topK = 10, filter, includeVector = false, namespace, sparseVector }) {
170
+ if (!queryVector) throw new MastraError({
171
+ id: createVectorErrorId("PINECONE", "QUERY", "MISSING_VECTOR"),
172
+ text: "queryVector is required for Pinecone queries. Metadata-only queries are not supported by this vector store.",
173
+ domain: ErrorDomain.STORAGE,
174
+ category: ErrorCategory.USER,
175
+ details: { indexName }
176
+ });
177
+ const index = this.client.Index(indexName).namespace(namespace || "");
178
+ const queryParams = {
179
+ vector: queryVector,
180
+ topK,
181
+ includeMetadata: true,
182
+ includeValues: includeVector,
183
+ filter: this.transformFilter(filter) ?? void 0
184
+ };
185
+ if (sparseVector) queryParams.sparseVector = sparseVector;
186
+ try {
187
+ return (await index.query(queryParams)).matches.map((match) => ({
188
+ id: match.id,
189
+ score: match.score || 0,
190
+ metadata: match.metadata,
191
+ ...includeVector && { vector: match.values || [] }
192
+ }));
193
+ } catch (error) {
194
+ throw new MastraError({
195
+ id: createVectorErrorId("PINECONE", "QUERY", "FAILED"),
196
+ domain: ErrorDomain.STORAGE,
197
+ category: ErrorCategory.THIRD_PARTY,
198
+ details: {
199
+ indexName,
200
+ topK
201
+ }
202
+ }, error);
203
+ }
204
+ }
205
+ async listIndexes() {
206
+ try {
207
+ return (await this.client.listIndexes())?.indexes?.map((index) => index.name) || [];
208
+ } catch (error) {
209
+ throw new MastraError({
210
+ id: createVectorErrorId("PINECONE", "LIST_INDEXES", "FAILED"),
211
+ domain: ErrorDomain.STORAGE,
212
+ category: ErrorCategory.THIRD_PARTY
213
+ }, error);
214
+ }
215
+ }
216
+ /**
217
+ * Retrieves statistics about a vector index.
218
+ *
219
+ * @param {string} indexName - The name of the index to describe
220
+ * @returns A promise that resolves to the index statistics including dimension, count and metric
221
+ */
222
+ async describeIndex({ indexName }) {
223
+ try {
224
+ const stats = await this.client.Index(indexName).describeIndexStats();
225
+ const description = await this.client.describeIndex(indexName);
226
+ return {
227
+ dimension: description.dimension,
228
+ count: stats.totalRecordCount || 0,
229
+ metric: description.metric,
230
+ namespaces: stats.namespaces
231
+ };
232
+ } catch (error) {
233
+ throw new MastraError({
234
+ id: createVectorErrorId("PINECONE", "DESCRIBE_INDEX", "FAILED"),
235
+ domain: ErrorDomain.STORAGE,
236
+ category: ErrorCategory.THIRD_PARTY,
237
+ details: { indexName }
238
+ }, error);
239
+ }
240
+ }
241
+ async deleteIndex({ indexName }) {
242
+ try {
243
+ await this.client.deleteIndex(indexName);
244
+ } catch (error) {
245
+ throw new MastraError({
246
+ id: createVectorErrorId("PINECONE", "DELETE_INDEX", "FAILED"),
247
+ domain: ErrorDomain.STORAGE,
248
+ category: ErrorCategory.THIRD_PARTY,
249
+ details: { indexName }
250
+ }, error);
251
+ }
252
+ }
253
+ /**
254
+ * Updates a vector by its ID with the provided vector and/or metadata.
255
+ * Note: Pinecone only supports update by ID, not by filter.
256
+ * @param params - Parameters containing the id for targeting the vector to update
257
+ * @param params.indexName - The name of the index containing the vector.
258
+ * @param params.id - The ID of the vector to update.
259
+ * @param params.update - An object containing the vector and/or metadata to update.
260
+ * @param namespace - The namespace of the index (optional, Pinecone-specific).
261
+ * @returns A promise that resolves when the update is complete.
262
+ * @throws Will throw an error if no updates are provided or if the update operation fails.
263
+ */
264
+ async updateVector(params) {
265
+ const { indexName, update } = params;
266
+ if ("id" in params && params.id && "filter" in params && params.filter) throw new MastraError({
267
+ id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "MUTUALLY_EXCLUSIVE"),
268
+ text: "Cannot specify both id and filter - they are mutually exclusive",
269
+ domain: ErrorDomain.STORAGE,
270
+ category: ErrorCategory.USER,
271
+ details: { indexName }
272
+ });
273
+ if (!("id" in params && params.id) && !("filter" in params && params.filter)) throw new MastraError({
274
+ id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "NO_TARGET"),
275
+ text: "Either id or filter must be provided",
276
+ domain: ErrorDomain.STORAGE,
277
+ category: ErrorCategory.USER,
278
+ details: { indexName }
279
+ });
280
+ if (!update.vector && !update.metadata) throw new MastraError({
281
+ id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "NO_PAYLOAD"),
282
+ domain: ErrorDomain.STORAGE,
283
+ category: ErrorCategory.USER,
284
+ text: "No updates provided",
285
+ details: { indexName }
286
+ });
287
+ const namespace = params.namespace;
288
+ try {
289
+ const index = this.client.Index(indexName).namespace(namespace || "");
290
+ if ("id" in params && params.id) {
291
+ const updateObj = { id: params.id };
292
+ if (update.vector) updateObj.values = update.vector;
293
+ if (update.metadata) updateObj.metadata = update.metadata;
294
+ await index.update(updateObj);
295
+ } else if ("filter" in params && params.filter) {
296
+ if (Object.keys(params.filter).length === 0) throw new MastraError({
297
+ id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "EMPTY_FILTER"),
298
+ text: "Filter cannot be an empty filter object",
299
+ domain: ErrorDomain.STORAGE,
300
+ category: ErrorCategory.USER,
301
+ details: { indexName }
302
+ });
303
+ const translatedFilter = this.transformFilter(params.filter);
304
+ if (translatedFilter) {
305
+ const stats = await this.describeIndex({ indexName });
306
+ const dummyVector = new Array(stats.dimension).fill(1 / Math.sqrt(stats.dimension));
307
+ const idsToUpdate = (await index.query({
308
+ vector: dummyVector,
309
+ topK: 1e4,
310
+ filter: translatedFilter,
311
+ includeMetadata: false,
312
+ includeValues: false
313
+ })).matches.map((m) => m.id);
314
+ for (const id of idsToUpdate) {
315
+ const updateObj = { id };
316
+ if (update.vector) updateObj.values = update.vector;
317
+ if (update.metadata) updateObj.metadata = update.metadata;
318
+ await index.update(updateObj);
319
+ }
320
+ }
321
+ }
322
+ } catch (error) {
323
+ if (error instanceof MastraError) throw error;
324
+ throw new MastraError({
325
+ id: createVectorErrorId("PINECONE", "UPDATE_VECTOR", "FAILED"),
326
+ domain: ErrorDomain.STORAGE,
327
+ category: ErrorCategory.THIRD_PARTY,
328
+ details: {
329
+ indexName,
330
+ ..."id" in params && params.id && { id: params.id },
331
+ ..."filter" in params && params.filter && { filter: JSON.stringify(params.filter) }
332
+ }
333
+ }, error);
334
+ }
335
+ }
336
+ /**
337
+ * Deletes a vector by its ID.
338
+ * @param indexName - The name of the index containing the vector.
339
+ * @param id - The ID of the vector to delete.
340
+ * @param namespace - The namespace of the index (optional).
341
+ * @returns A promise that resolves when the deletion is complete.
342
+ * @throws Will throw an error if the deletion operation fails.
343
+ */
344
+ async deleteVector({ indexName, id, namespace }) {
345
+ try {
346
+ await this.client.Index(indexName).namespace(namespace || "").deleteOne(id);
347
+ } catch (error) {
348
+ throw new MastraError({
349
+ id: createVectorErrorId("PINECONE", "DELETE_VECTOR", "FAILED"),
350
+ domain: ErrorDomain.STORAGE,
351
+ category: ErrorCategory.THIRD_PARTY,
352
+ details: {
353
+ indexName,
354
+ ...id && { id }
355
+ }
356
+ }, error);
357
+ }
358
+ }
359
+ /**
360
+ * Deletes multiple vectors by IDs or filter.
361
+ * @param indexName - The name of the index containing the vectors.
362
+ * @param ids - Array of vector IDs to delete (mutually exclusive with filter).
363
+ * @param filter - Filter to match vectors to delete (mutually exclusive with ids).
364
+ * @param namespace - The namespace of the index (optional, Pinecone-specific).
365
+ * @returns A promise that resolves when the deletion is complete.
366
+ * @throws Will throw an error if both ids and filter are provided, or if neither is provided.
367
+ */
368
+ async deleteVectors(params) {
369
+ const { indexName, filter, ids } = params;
370
+ const namespace = params.namespace;
371
+ if (ids && filter) throw new MastraError({
372
+ id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "MUTUALLY_EXCLUSIVE"),
373
+ text: "Cannot specify both ids and filter - they are mutually exclusive",
374
+ domain: ErrorDomain.STORAGE,
375
+ category: ErrorCategory.USER,
376
+ details: { indexName }
377
+ });
378
+ if (!ids && !filter) throw new MastraError({
379
+ id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "NO_TARGET"),
380
+ text: "Either filter or ids must be provided",
381
+ domain: ErrorDomain.STORAGE,
382
+ category: ErrorCategory.USER,
383
+ details: { indexName }
384
+ });
385
+ if (ids && ids.length === 0) throw new MastraError({
386
+ id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "EMPTY_IDS"),
387
+ text: "Cannot delete with empty ids array",
388
+ domain: ErrorDomain.STORAGE,
389
+ category: ErrorCategory.USER,
390
+ details: { indexName }
391
+ });
392
+ if (filter && Object.keys(filter).length === 0) throw new MastraError({
393
+ id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "EMPTY_FILTER"),
394
+ text: "Cannot delete with empty filter object",
395
+ domain: ErrorDomain.STORAGE,
396
+ category: ErrorCategory.USER,
397
+ details: { indexName }
398
+ });
399
+ try {
400
+ const index = this.client.Index(indexName).namespace(namespace || "");
401
+ if (ids) await index.deleteMany(ids);
402
+ else if (filter) {
403
+ const translatedFilter = this.transformFilter(filter);
404
+ if (translatedFilter) {
405
+ const stats = await this.describeIndex({ indexName });
406
+ const dummyVector = new Array(stats.dimension).fill(1 / Math.sqrt(stats.dimension));
407
+ const idsToDelete = (await index.query({
408
+ vector: dummyVector,
409
+ topK: 1e4,
410
+ filter: translatedFilter,
411
+ includeMetadata: false,
412
+ includeValues: false
413
+ })).matches.map((m) => m.id);
414
+ if (idsToDelete.length > 0) await index.deleteMany(idsToDelete);
415
+ }
416
+ }
417
+ } catch (error) {
418
+ if (error instanceof MastraError) throw error;
419
+ throw new MastraError({
420
+ id: createVectorErrorId("PINECONE", "DELETE_VECTORS", "FAILED"),
421
+ domain: ErrorDomain.STORAGE,
422
+ category: ErrorCategory.THIRD_PARTY,
423
+ details: {
424
+ indexName,
425
+ ...filter && { filter: JSON.stringify(filter) },
426
+ ...ids && { idsCount: ids.length }
427
+ }
428
+ }, error);
429
+ }
430
+ }
518
431
  };
519
-
520
- // src/vector/prompt.ts
521
- var PINECONE_PROMPT = `When querying Pinecone, you can ONLY use the operators listed below. Any other operators will be rejected.
432
+ //#endregion
433
+ //#region src/vector/prompt.ts
434
+ /**
435
+ * Vector store specific prompt that details supported operators and examples.
436
+ * This prompt helps users construct valid filters for Pinecone Vector.
437
+ */
438
+ const PINECONE_PROMPT = `When querying Pinecone, you can ONLY use the operators listed below. Any other operators will be rejected.
522
439
  Important: Don't explain how to construct the filter - use the specified operators and fields to search the content and return relevant results.
523
440
  If a user tries to give an explicit operator that is not supported, reject the filter entirely and let them know that the operator is not supported.
524
441
 
@@ -595,7 +512,7 @@ Example Complex Query:
595
512
  ]}
596
513
  ]
597
514
  }`;
598
-
515
+ //#endregion
599
516
  export { PINECONE_PROMPT, PineconeVector };
600
- //# sourceMappingURL=index.js.map
517
+
601
518
  //# sourceMappingURL=index.js.map