@mastra/pinecone 0.11.4 → 0.11.7-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.
@@ -1,364 +0,0 @@
1
- import { MastraError, ErrorDomain, ErrorCategory } from '@mastra/core/error';
2
- import { MastraVector } from '@mastra/core/vector';
3
- import type {
4
- QueryResult,
5
- IndexStats,
6
- CreateIndexParams,
7
- UpsertVectorParams,
8
- QueryVectorParams,
9
- DescribeIndexParams,
10
- DeleteIndexParams,
11
- DeleteVectorParams,
12
- UpdateVectorParams,
13
- } from '@mastra/core/vector';
14
- import { Pinecone } from '@pinecone-database/pinecone';
15
- import type {
16
- IndexStatsDescription,
17
- QueryOptions,
18
- RecordSparseValues,
19
- UpdateOptions,
20
- } from '@pinecone-database/pinecone';
21
-
22
- import { PineconeFilterTranslator } from './filter';
23
- import type { PineconeVectorFilter } from './filter';
24
-
25
- interface PineconeIndexStats extends IndexStats {
26
- namespaces?: IndexStatsDescription['namespaces'];
27
- }
28
-
29
- interface PineconeQueryVectorParams extends QueryVectorParams<PineconeVectorFilter> {
30
- namespace?: string;
31
- sparseVector?: RecordSparseValues;
32
- }
33
-
34
- interface PineconeUpsertVectorParams extends UpsertVectorParams {
35
- namespace?: string;
36
- sparseVectors?: RecordSparseValues[];
37
- }
38
-
39
- interface PineconeUpdateVectorParams extends UpdateVectorParams {
40
- namespace?: string;
41
- }
42
-
43
- interface PineconeDeleteVectorParams extends DeleteVectorParams {
44
- namespace?: string;
45
- }
46
-
47
- export class PineconeVector extends MastraVector<PineconeVectorFilter> {
48
- private client: Pinecone;
49
-
50
- /**
51
- * Creates a new PineconeVector client.
52
- * @param apiKey - The API key for Pinecone.
53
- * @param environment - The environment for Pinecone.
54
- */
55
- constructor({ apiKey, environment }: { apiKey: string; environment?: string }) {
56
- super();
57
- const opts: { apiKey: string; controllerHostUrl?: string } = { apiKey };
58
- if (environment) {
59
- opts['controllerHostUrl'] = environment;
60
- }
61
- const baseClient = new Pinecone(opts);
62
- const telemetry = this.__getTelemetry();
63
- this.client =
64
- telemetry?.traceClass(baseClient, {
65
- spanNamePrefix: 'pinecone-vector',
66
- attributes: {
67
- 'vector.type': 'pinecone',
68
- },
69
- }) ?? baseClient;
70
- }
71
-
72
- get indexSeparator(): string {
73
- return '-';
74
- }
75
-
76
- async createIndex({ indexName, dimension, metric = 'cosine' }: CreateIndexParams): Promise<void> {
77
- try {
78
- if (!Number.isInteger(dimension) || dimension <= 0) {
79
- throw new Error('Dimension must be a positive integer');
80
- }
81
- if (metric && !['cosine', 'euclidean', 'dotproduct'].includes(metric)) {
82
- throw new Error('Metric must be one of: cosine, euclidean, dotproduct');
83
- }
84
- } catch (validationError) {
85
- throw new MastraError(
86
- {
87
- id: 'STORAGE_PINECONE_VECTOR_CREATE_INDEX_INVALID_ARGS',
88
- domain: ErrorDomain.STORAGE,
89
- category: ErrorCategory.USER,
90
- details: { indexName, dimension, metric },
91
- },
92
- validationError,
93
- );
94
- }
95
-
96
- try {
97
- await this.client.createIndex({
98
- name: indexName,
99
- dimension: dimension,
100
- metric: metric,
101
- spec: {
102
- serverless: {
103
- cloud: 'aws',
104
- region: 'us-east-1',
105
- },
106
- },
107
- });
108
- } catch (error: any) {
109
- // Check for 'already exists' error
110
- const message = error?.errors?.[0]?.message || error?.message;
111
- if (
112
- error.status === 409 ||
113
- (typeof message === 'string' &&
114
- (message.toLowerCase().includes('already exists') || message.toLowerCase().includes('duplicate')))
115
- ) {
116
- // Fetch index info and check dimensions
117
- await this.validateExistingIndex(indexName, dimension, metric);
118
- return;
119
- }
120
- // For any other errors, wrap in MastraError
121
- throw new MastraError(
122
- {
123
- id: 'STORAGE_PINECONE_VECTOR_CREATE_INDEX_FAILED',
124
- domain: ErrorDomain.STORAGE,
125
- category: ErrorCategory.THIRD_PARTY,
126
- details: { indexName, dimension, metric },
127
- },
128
- error,
129
- );
130
- }
131
- }
132
-
133
- async upsert({
134
- indexName,
135
- vectors,
136
- metadata,
137
- ids,
138
- namespace,
139
- sparseVectors,
140
- }: PineconeUpsertVectorParams): Promise<string[]> {
141
- const index = this.client.Index(indexName).namespace(namespace || '');
142
-
143
- // Generate IDs if not provided
144
- const vectorIds = ids || vectors.map(() => crypto.randomUUID());
145
-
146
- const records = vectors.map((vector, i) => ({
147
- id: vectorIds[i]!,
148
- values: vector,
149
- ...(sparseVectors?.[i] && { sparseValues: sparseVectors?.[i] }),
150
- metadata: metadata?.[i] || {},
151
- }));
152
-
153
- // Pinecone has a limit of 100 vectors per upsert request
154
- const batchSize = 100;
155
- try {
156
- for (let i = 0; i < records.length; i += batchSize) {
157
- const batch = records.slice(i, i + batchSize);
158
- await index.upsert(batch);
159
- }
160
-
161
- return vectorIds;
162
- } catch (error) {
163
- throw new MastraError(
164
- {
165
- id: 'STORAGE_PINECONE_VECTOR_UPSERT_FAILED',
166
- domain: ErrorDomain.STORAGE,
167
- category: ErrorCategory.THIRD_PARTY,
168
- details: { indexName, vectorCount: vectors.length },
169
- },
170
- error,
171
- );
172
- }
173
- }
174
-
175
- transformFilter(filter?: PineconeVectorFilter) {
176
- const translator = new PineconeFilterTranslator();
177
- return translator.translate(filter);
178
- }
179
-
180
- async query({
181
- indexName,
182
- queryVector,
183
- topK = 10,
184
- filter,
185
- includeVector = false,
186
- namespace,
187
- sparseVector,
188
- }: PineconeQueryVectorParams): Promise<QueryResult[]> {
189
- const index = this.client.Index(indexName).namespace(namespace || '');
190
-
191
- const translatedFilter = this.transformFilter(filter) ?? undefined;
192
-
193
- const queryParams: QueryOptions = {
194
- vector: queryVector,
195
- topK,
196
- includeMetadata: true,
197
- includeValues: includeVector,
198
- filter: translatedFilter,
199
- };
200
-
201
- // If sparse vector is provided, use hybrid search
202
- if (sparseVector) {
203
- queryParams.sparseVector = sparseVector;
204
- }
205
-
206
- try {
207
- const results = await index.query(queryParams);
208
-
209
- return results.matches.map(match => ({
210
- id: match.id,
211
- score: match.score || 0,
212
- metadata: match.metadata as Record<string, any>,
213
- ...(includeVector && { vector: match.values || [] }),
214
- }));
215
- } catch (error) {
216
- throw new MastraError(
217
- {
218
- id: 'STORAGE_PINECONE_VECTOR_QUERY_FAILED',
219
- domain: ErrorDomain.STORAGE,
220
- category: ErrorCategory.THIRD_PARTY,
221
- details: { indexName, topK },
222
- },
223
- error,
224
- );
225
- }
226
- }
227
-
228
- async listIndexes(): Promise<string[]> {
229
- try {
230
- const indexesResult = await this.client.listIndexes();
231
- return indexesResult?.indexes?.map(index => index.name) || [];
232
- } catch (error) {
233
- throw new MastraError(
234
- {
235
- id: 'STORAGE_PINECONE_VECTOR_LIST_INDEXES_FAILED',
236
- domain: ErrorDomain.STORAGE,
237
- category: ErrorCategory.THIRD_PARTY,
238
- },
239
- error,
240
- );
241
- }
242
- }
243
-
244
- /**
245
- * Retrieves statistics about a vector index.
246
- *
247
- * @param {string} indexName - The name of the index to describe
248
- * @returns A promise that resolves to the index statistics including dimension, count and metric
249
- */
250
- async describeIndex({ indexName }: DescribeIndexParams): Promise<PineconeIndexStats> {
251
- try {
252
- const index = this.client.Index(indexName);
253
- const stats = await index.describeIndexStats();
254
- const description = await this.client.describeIndex(indexName);
255
-
256
- return {
257
- dimension: description.dimension,
258
- count: stats.totalRecordCount || 0,
259
- metric: description.metric as 'cosine' | 'euclidean' | 'dotproduct',
260
- namespaces: stats.namespaces,
261
- };
262
- } catch (error) {
263
- throw new MastraError(
264
- {
265
- id: 'STORAGE_PINECONE_VECTOR_DESCRIBE_INDEX_FAILED',
266
- domain: ErrorDomain.STORAGE,
267
- category: ErrorCategory.THIRD_PARTY,
268
- details: { indexName },
269
- },
270
- error,
271
- );
272
- }
273
- }
274
-
275
- async deleteIndex({ indexName }: DeleteIndexParams): Promise<void> {
276
- try {
277
- await this.client.deleteIndex(indexName);
278
- } catch (error) {
279
- throw new MastraError(
280
- {
281
- id: 'STORAGE_PINECONE_VECTOR_DELETE_INDEX_FAILED',
282
- domain: ErrorDomain.STORAGE,
283
- category: ErrorCategory.THIRD_PARTY,
284
- details: { indexName },
285
- },
286
- error,
287
- );
288
- }
289
- }
290
-
291
- /**
292
- * Updates a vector by its ID with the provided vector and/or metadata.
293
- * @param indexName - The name of the index containing the vector.
294
- * @param id - The ID of the vector to update.
295
- * @param update - An object containing the vector and/or metadata to update.
296
- * @param update.vector - An optional array of numbers representing the new vector.
297
- * @param update.metadata - An optional record containing the new metadata.
298
- * @param namespace - The namespace of the index (optional).
299
- * @returns A promise that resolves when the update is complete.
300
- * @throws Will throw an error if no updates are provided or if the update operation fails.
301
- */
302
- async updateVector({ indexName, id, update, namespace }: PineconeUpdateVectorParams): Promise<void> {
303
- if (!update.vector && !update.metadata) {
304
- throw new MastraError({
305
- id: 'STORAGE_PINECONE_VECTOR_UPDATE_VECTOR_INVALID_ARGS',
306
- domain: ErrorDomain.STORAGE,
307
- category: ErrorCategory.USER,
308
- text: 'No updates provided',
309
- details: { indexName, id },
310
- });
311
- }
312
-
313
- try {
314
- const index = this.client.Index(indexName).namespace(namespace || '');
315
-
316
- const updateObj: UpdateOptions = { id };
317
-
318
- if (update.vector) {
319
- updateObj.values = update.vector;
320
- }
321
-
322
- if (update.metadata) {
323
- updateObj.metadata = update.metadata;
324
- }
325
-
326
- await index.update(updateObj);
327
- } catch (error) {
328
- throw new MastraError(
329
- {
330
- id: 'STORAGE_PINECONE_VECTOR_UPDATE_VECTOR_FAILED',
331
- domain: ErrorDomain.STORAGE,
332
- category: ErrorCategory.THIRD_PARTY,
333
- details: { indexName, id },
334
- },
335
- error,
336
- );
337
- }
338
- }
339
-
340
- /**
341
- * Deletes a vector by its ID.
342
- * @param indexName - The name of the index containing the vector.
343
- * @param id - The ID of the vector to delete.
344
- * @param namespace - The namespace of the index (optional).
345
- * @returns A promise that resolves when the deletion is complete.
346
- * @throws Will throw an error if the deletion operation fails.
347
- */
348
- async deleteVector({ indexName, id, namespace }: PineconeDeleteVectorParams): Promise<void> {
349
- try {
350
- const index = this.client.Index(indexName).namespace(namespace || '');
351
- await index.deleteOne(id);
352
- } catch (error) {
353
- throw new MastraError(
354
- {
355
- id: 'STORAGE_PINECONE_VECTOR_DELETE_VECTOR_FAILED',
356
- domain: ErrorDomain.STORAGE,
357
- category: ErrorCategory.THIRD_PARTY,
358
- details: { indexName, id },
359
- },
360
- error,
361
- );
362
- }
363
- }
364
- }
@@ -1,81 +0,0 @@
1
- /**
2
- * Vector store specific prompt that details supported operators and examples.
3
- * This prompt helps users construct valid filters for Pinecone Vector.
4
- */
5
- export const PINECONE_PROMPT = `When querying Pinecone, you can ONLY use the operators listed below. Any other operators will be rejected.
6
- Important: Don't explain how to construct the filter - use the specified operators and fields to search the content and return relevant results.
7
- 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.
8
-
9
- Basic Comparison Operators:
10
- - $eq: Exact match (default when using field: value)
11
- Example: { "category": "electronics" }
12
- - $ne: Not equal
13
- Example: { "category": { "$ne": "electronics" } }
14
- - $gt: Greater than
15
- Example: { "price": { "$gt": 100 } }
16
- - $gte: Greater than or equal
17
- Example: { "price": { "$gte": 100 } }
18
- - $lt: Less than
19
- Example: { "price": { "$lt": 100 } }
20
- - $lte: Less than or equal
21
- Example: { "price": { "$lte": 100 } }
22
-
23
- Array Operators:
24
- - $in: Match any value in array
25
- Example: { "category": { "$in": ["electronics", "books"] } }
26
- - $nin: Does not match any value in array
27
- Example: { "category": { "$nin": ["electronics", "books"] } }
28
- - $all: Match all values in array
29
- Example: { "tags": { "$all": ["premium", "sale"] } }
30
-
31
- Logical Operators:
32
- - $and: Logical AND (can be implicit or explicit)
33
- Implicit Example: { "price": { "$gt": 100 }, "category": "electronics" }
34
- Explicit Example: { "$and": [{ "price": { "$gt": 100 } }, { "category": "electronics" }] }
35
- - $or: Logical OR
36
- Example: { "$or": [{ "price": { "$lt": 50 } }, { "category": "books" }] }
37
-
38
- Element Operators:
39
- - $exists: Check if field exists
40
- Example: { "rating": { "$exists": true } }
41
-
42
- Restrictions:
43
- - Regex patterns are not supported
44
- - Only $and and $or logical operators are supported at the top level
45
- - Empty arrays in $in/$nin will return no results
46
- - A non-empty array is required for $all operator
47
- - Nested fields are supported using dot notation
48
- - Multiple conditions on the same field are supported with both implicit and explicit $and
49
- - At least one key-value pair is required in filter object
50
- - Empty objects and undefined values are treated as no filter
51
- - Invalid types in comparison operators will throw errors
52
- - All non-logical operators must be used within a field condition
53
- Valid: { "field": { "$gt": 100 } }
54
- Valid: { "$and": [...] }
55
- Invalid: { "$gt": 100 }
56
- - Logical operators must contain field conditions, not direct operators
57
- Valid: { "$and": [{ "field": { "$gt": 100 } }] }
58
- Invalid: { "$and": [{ "$gt": 100 }] }
59
- - Logical operators ($and, $or):
60
- - Can only be used at top level or nested within other logical operators
61
- - Can not be used on a field level, or be nested inside a field
62
- - Can not be used inside an operator
63
- - Valid: { "$and": [{ "field": { "$gt": 100 } }] }
64
- - Valid: { "$or": [{ "$and": [{ "field": { "$gt": 100 } }] }] }
65
- - Invalid: { "field": { "$and": [{ "$gt": 100 }] } }
66
- - Invalid: { "field": { "$or": [{ "$gt": 100 }] } }
67
- - Invalid: { "field": { "$gt": { "$and": [{...}] } } }
68
-
69
- Example Complex Query:
70
- {
71
- "$and": [
72
- { "category": { "$in": ["electronics", "computers"] } },
73
- { "price": { "$gte": 100, "$lte": 1000 } },
74
- { "tags": { "$all": ["premium", "sale"] } },
75
- { "rating": { "$exists": true, "$gt": 4 } },
76
- { "$or": [
77
- { "stock": { "$gt": 0 } },
78
- { "preorder": true }
79
- ]}
80
- ]
81
- }`;
@@ -1,9 +0,0 @@
1
- {
2
- "extends": ["./tsconfig.json", "../../tsconfig.build.json"],
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src"
6
- },
7
- "include": ["src/**/*"],
8
- "exclude": ["node_modules", "**/*.test.ts", "src/**/*.mock.ts"]
9
- }
package/tsconfig.json DELETED
@@ -1,5 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.node.json",
3
- "include": ["src/**/*", "tsup.config.ts"],
4
- "exclude": ["node_modules", "**/*.test.ts"]
5
- }
package/tsup.config.ts DELETED
@@ -1,17 +0,0 @@
1
- import { generateTypes } from '@internal/types-builder';
2
- import { defineConfig } from 'tsup';
3
-
4
- export default defineConfig({
5
- entry: ['src/index.ts'],
6
- format: ['esm', 'cjs'],
7
- clean: true,
8
- dts: false,
9
- splitting: true,
10
- treeshake: {
11
- preset: 'smallest',
12
- },
13
- sourcemap: true,
14
- onSuccess: async () => {
15
- await generateTypes(process.cwd());
16
- },
17
- });
package/vitest.config.ts DELETED
@@ -1,11 +0,0 @@
1
- import { defineConfig } from 'vitest/config';
2
-
3
- export default defineConfig({
4
- test: {
5
- environment: 'node',
6
- include: ['src/**/*.test.ts'],
7
- coverage: {
8
- reporter: ['text', 'json', 'html'],
9
- },
10
- },
11
- });