@mastra/turbopuffer 0.0.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/LICENSE ADDED
@@ -0,0 +1,44 @@
1
+ Elastic License 2.0 (ELv2)
2
+
3
+ **Acceptance**
4
+ By using the software, you agree to all of the terms and conditions below.
5
+
6
+ **Copyright License**
7
+ The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable, non-transferable license to use, copy, distribute, make available, and prepare derivative works of the software, in each case subject to the limitations and conditions below
8
+
9
+ **Limitations**
10
+ You may not provide the software to third parties as a hosted or managed service, where the service provides users with access to any substantial set of the features or functionality of the software.
11
+
12
+ You may not move, change, disable, or circumvent the license key functionality in the software, and you may not remove or obscure any functionality in the software that is protected by the license key.
13
+
14
+ You may not alter, remove, or obscure any licensing, copyright, or other notices of the licensor in the software. Any use of the licensor’s trademarks is subject to applicable law.
15
+
16
+ **Patents**
17
+ The licensor grants you a license, under any patent claims the licensor can license, or becomes able to license, to make, have made, use, sell, offer for sale, import and have imported the software, in each case subject to the limitations and conditions in this license. This license does not cover any patent claims that you cause to be infringed by modifications or additions to the software. If you or your company make any written claim that the software infringes or contributes to infringement of any patent, your patent license for the software granted under these terms ends immediately. If your company makes such a claim, your patent license ends immediately for work on behalf of your company.
18
+
19
+ **Notices**
20
+ You must ensure that anyone who gets a copy of any part of the software from you also gets a copy of these terms.
21
+
22
+ If you modify the software, you must include in any modified copies of the software prominent notices stating that you have modified the software.
23
+
24
+ **No Other Rights**
25
+ These terms do not imply any licenses other than those expressly granted in these terms.
26
+
27
+ **Termination**
28
+ If you use the software in violation of these terms, such use is not licensed, and your licenses will automatically terminate. If the licensor provides you with a notice of your violation, and you cease all violation of this license no later than 30 days after you receive that notice, your licenses will be reinstated retroactively. However, if you violate these terms after such reinstatement, any additional violation of these terms will cause your licenses to terminate automatically and permanently.
29
+
30
+ **No Liability**
31
+ As far as the law allows, the software comes as is, without any warranty or condition, and the licensor will not be liable to you for any damages arising out of these terms or the use or nature of the software, under any kind of legal claim.
32
+
33
+ **Definitions**
34
+ The _licensor_ is the entity offering these terms, and the _software_ is the software the licensor makes available under these terms, including any portion of it.
35
+
36
+ _you_ refers to the individual or entity agreeing to these terms.
37
+
38
+ _your company_ is any legal entity, sole proprietorship, or other kind of organization that you work for, plus all organizations that have control over, are under the control of, or are under common control with that organization. _control_ means ownership of substantially all the assets of an entity, or the power to direct its management and policies by vote, contract, or otherwise. Control can be direct or indirect.
39
+
40
+ _your licenses_ are all the licenses granted to you for the software under these terms.
41
+
42
+ _use_ means anything you do with the software requiring one of your licenses.
43
+
44
+ _trademark_ means trademarks, service marks, and similar rights.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # @mastra/turbopuffer
2
+
3
+ Vector store implementation for Turbopuffer, using the official @turbopuffer/turbopuffer SDK with added telemetry support.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pnpm add @mastra/turbopuffer
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```typescript
14
+ import { TurbopufferVector } from '@mastra/turbopuffer';
15
+
16
+ const vectorStore = new TurbopufferVector({
17
+ apiKey: 'your-api-key',
18
+ baseUrl: 'https://gcp-us-central1.turbopuffer.com',
19
+ });
20
+
21
+ // Create a new index
22
+ await vectorStore.createIndex({ indexName: 'my-index', dimension: 1536, metric: 'cosine' });
23
+
24
+ // Add vectors
25
+ const vectors = [[0.1, 0.2, ...], [0.3, 0.4, ...]];
26
+ const metadata = [{ text: 'doc1' }, { text: 'doc2' }];
27
+ const ids = await vectorStore.upsert({ indexName: 'my-index', vectors, metadata });
28
+
29
+ // Query vectors
30
+ const results = await vectorStore.query({
31
+ indexName: 'my-index',
32
+ queryVector: [0.1, 0.2, ...],
33
+ topK: 10,
34
+ filter: { text: { $eq: 'doc1' } },
35
+ includeVector: false,
36
+ );
37
+ ```
38
+
39
+ ## Configuration
40
+
41
+ Required:
42
+
43
+ - `apiKey`: Your Turbopuffer API key
44
+
45
+ Optional:
46
+
47
+ - `baseUrl`: Your Turbopuffer base URL (default: https://api.turbopuffer.com)
48
+ - `connectTimeout`: Timeout to establish a connection, in ms (default: 10_000)
49
+ - `connectionIdleTimeout`: Socket idle timeout, in ms (default: 60_000)
50
+ - `warmConnections`: Number of connections to open initially (default: 0)
51
+ - `compression`: Whether to compress requests and accept compressed responses (default: true)
52
+ - `schemaConfigForIndex`: A function that returns a Turbopuffer schema config for an index (default: undefined).
53
+
54
+ ## Related Links
55
+
56
+ - [Turbopuffer Documentation](https://turbopuffer.com/docs)
57
+ - [Turbopuffer Typescript Client Library](https://github.com/turbopuffer/turbopuffer-typescript)
@@ -0,0 +1,116 @@
1
+ import { BaseFilterTranslator } from '@mastra/core/vector/filter';
2
+ import type { CreateIndexParams } from '@mastra/core/vector';
3
+ import type { Filters } from '@turbopuffer/turbopuffer';
4
+ import type { IndexStats } from '@mastra/core/vector';
5
+ import { MastraVector } from '@mastra/core/vector';
6
+ import type { OperatorSupport } from '@mastra/core/vector/filter';
7
+ import type { QueryResult } from '@mastra/core/vector';
8
+ import type { QueryVectorParams } from '@mastra/core/vector';
9
+ import { Schema } from '@turbopuffer/turbopuffer';
10
+ import type { UpsertVectorParams } from '@mastra/core/vector';
11
+ import type { VectorFilter } from '@mastra/core/vector/filter';
12
+
13
+ /**
14
+ * Translator for converting Mastra filters to Turbopuffer format
15
+ *
16
+ * Mastra filters: { field: { $gt: 10 } }
17
+ * Turbopuffer filters: ["And", [["field", "Gt", 10]]]
18
+ */
19
+ export declare class TurbopufferFilterTranslator extends BaseFilterTranslator {
20
+ protected getSupportedOperators(): OperatorSupport;
21
+ /**
22
+ * Map Mastra operators to Turbopuffer operators
23
+ */
24
+ private operatorMap;
25
+ /**
26
+ * Convert the Mastra filter to Turbopuffer format
27
+ */
28
+ translate(filter?: VectorFilter): Filters | undefined;
29
+ /**
30
+ * Recursively translate a filter node
31
+ */
32
+ private translateNode;
33
+ /**
34
+ * Translate a field condition
35
+ */
36
+ private translateFieldCondition;
37
+ /**
38
+ * Translate a logical operator
39
+ */
40
+ private translateLogical;
41
+ /**
42
+ * Translate a specific operator
43
+ */
44
+ private translateOperator;
45
+ /**
46
+ * Normalize a value for comparison operations
47
+ */
48
+ protected normalizeValue(value: any): any;
49
+ /**
50
+ * Normalize array values
51
+ */
52
+ protected normalizeArrayValues(values: any[]): any[];
53
+ }
54
+
55
+ declare class TurbopufferVector extends MastraVector {
56
+ private client;
57
+ private filterTranslator;
58
+ private createIndexCache;
59
+ private opts;
60
+ constructor(opts: TurbopufferVectorOptions);
61
+ createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void>;
62
+ upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]>;
63
+ query({ indexName, queryVector, topK, filter, includeVector }: QueryVectorParams): Promise<QueryResult[]>;
64
+ listIndexes(): Promise<string[]>;
65
+ describeIndex(indexName: string): Promise<IndexStats>;
66
+ deleteIndex(indexName: string): Promise<void>;
67
+ }
68
+ export { TurbopufferVector }
69
+ export { TurbopufferVector as TurbopufferVector_alias_1 }
70
+
71
+ declare interface TurbopufferVectorOptions {
72
+ /** The API key to authenticate with. */
73
+ apiKey: string;
74
+ /** The base URL. Default is https://api.turbopuffer.com. */
75
+ baseUrl?: string;
76
+ /** The timeout to establish a connection, in ms. Default is 10_000. Only applicable in Node and Deno.*/
77
+ connectTimeout?: number;
78
+ /** The socket idle timeout, in ms. Default is 60_000. Only applicable in Node and Deno.*/
79
+ connectionIdleTimeout?: number;
80
+ /** The number of connections to open initially when creating a new client. Default is 0. */
81
+ warmConnections?: number;
82
+ /** Whether to compress requests and accept compressed responses. Default is true. */
83
+ compression?: boolean;
84
+ /**
85
+ * A callback function that takes an index name and returns a config object for that index.
86
+ * This allows you to define explicit schemas per index.
87
+ *
88
+ * Example:
89
+ * ```typescript
90
+ * schemaConfigForIndex: (indexName: string) => {
91
+ * // Mastra's default embedding model and index for memory messages:
92
+ * if (indexName === "memory_messages_384") {
93
+ * return {
94
+ * dimensions: 384,
95
+ * schema: {
96
+ * thread_id: {
97
+ * type: "string",
98
+ * filterable: true,
99
+ * },
100
+ * },
101
+ * };
102
+ * } else {
103
+ * throw new Error(`TODO: add schema for index: ${indexName}`);
104
+ * }
105
+ * },
106
+ * ```
107
+ */
108
+ schemaConfigForIndex?: (indexName: string) => {
109
+ dimensions: number;
110
+ schema: Schema;
111
+ };
112
+ }
113
+ export { TurbopufferVectorOptions }
114
+ export { TurbopufferVectorOptions as TurbopufferVectorOptions_alias_1 }
115
+
116
+ export { }
@@ -0,0 +1,116 @@
1
+ import { BaseFilterTranslator } from '@mastra/core/vector/filter';
2
+ import type { CreateIndexParams } from '@mastra/core/vector';
3
+ import type { Filters } from '@turbopuffer/turbopuffer';
4
+ import type { IndexStats } from '@mastra/core/vector';
5
+ import { MastraVector } from '@mastra/core/vector';
6
+ import type { OperatorSupport } from '@mastra/core/vector/filter';
7
+ import type { QueryResult } from '@mastra/core/vector';
8
+ import type { QueryVectorParams } from '@mastra/core/vector';
9
+ import { Schema } from '@turbopuffer/turbopuffer';
10
+ import type { UpsertVectorParams } from '@mastra/core/vector';
11
+ import type { VectorFilter } from '@mastra/core/vector/filter';
12
+
13
+ /**
14
+ * Translator for converting Mastra filters to Turbopuffer format
15
+ *
16
+ * Mastra filters: { field: { $gt: 10 } }
17
+ * Turbopuffer filters: ["And", [["field", "Gt", 10]]]
18
+ */
19
+ export declare class TurbopufferFilterTranslator extends BaseFilterTranslator {
20
+ protected getSupportedOperators(): OperatorSupport;
21
+ /**
22
+ * Map Mastra operators to Turbopuffer operators
23
+ */
24
+ private operatorMap;
25
+ /**
26
+ * Convert the Mastra filter to Turbopuffer format
27
+ */
28
+ translate(filter?: VectorFilter): Filters | undefined;
29
+ /**
30
+ * Recursively translate a filter node
31
+ */
32
+ private translateNode;
33
+ /**
34
+ * Translate a field condition
35
+ */
36
+ private translateFieldCondition;
37
+ /**
38
+ * Translate a logical operator
39
+ */
40
+ private translateLogical;
41
+ /**
42
+ * Translate a specific operator
43
+ */
44
+ private translateOperator;
45
+ /**
46
+ * Normalize a value for comparison operations
47
+ */
48
+ protected normalizeValue(value: any): any;
49
+ /**
50
+ * Normalize array values
51
+ */
52
+ protected normalizeArrayValues(values: any[]): any[];
53
+ }
54
+
55
+ declare class TurbopufferVector extends MastraVector {
56
+ private client;
57
+ private filterTranslator;
58
+ private createIndexCache;
59
+ private opts;
60
+ constructor(opts: TurbopufferVectorOptions);
61
+ createIndex({ indexName, dimension, metric }: CreateIndexParams): Promise<void>;
62
+ upsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]>;
63
+ query({ indexName, queryVector, topK, filter, includeVector }: QueryVectorParams): Promise<QueryResult[]>;
64
+ listIndexes(): Promise<string[]>;
65
+ describeIndex(indexName: string): Promise<IndexStats>;
66
+ deleteIndex(indexName: string): Promise<void>;
67
+ }
68
+ export { TurbopufferVector }
69
+ export { TurbopufferVector as TurbopufferVector_alias_1 }
70
+
71
+ declare interface TurbopufferVectorOptions {
72
+ /** The API key to authenticate with. */
73
+ apiKey: string;
74
+ /** The base URL. Default is https://api.turbopuffer.com. */
75
+ baseUrl?: string;
76
+ /** The timeout to establish a connection, in ms. Default is 10_000. Only applicable in Node and Deno.*/
77
+ connectTimeout?: number;
78
+ /** The socket idle timeout, in ms. Default is 60_000. Only applicable in Node and Deno.*/
79
+ connectionIdleTimeout?: number;
80
+ /** The number of connections to open initially when creating a new client. Default is 0. */
81
+ warmConnections?: number;
82
+ /** Whether to compress requests and accept compressed responses. Default is true. */
83
+ compression?: boolean;
84
+ /**
85
+ * A callback function that takes an index name and returns a config object for that index.
86
+ * This allows you to define explicit schemas per index.
87
+ *
88
+ * Example:
89
+ * ```typescript
90
+ * schemaConfigForIndex: (indexName: string) => {
91
+ * // Mastra's default embedding model and index for memory messages:
92
+ * if (indexName === "memory_messages_384") {
93
+ * return {
94
+ * dimensions: 384,
95
+ * schema: {
96
+ * thread_id: {
97
+ * type: "string",
98
+ * filterable: true,
99
+ * },
100
+ * },
101
+ * };
102
+ * } else {
103
+ * throw new Error(`TODO: add schema for index: ${indexName}`);
104
+ * }
105
+ * },
106
+ * ```
107
+ */
108
+ schemaConfigForIndex?: (indexName: string) => {
109
+ dimensions: number;
110
+ schema: Schema;
111
+ };
112
+ }
113
+ export { TurbopufferVectorOptions }
114
+ export { TurbopufferVectorOptions as TurbopufferVectorOptions_alias_1 }
115
+
116
+ export { }
package/dist/index.cjs ADDED
@@ -0,0 +1,336 @@
1
+ 'use strict';
2
+
3
+ var vector = require('@mastra/core/vector');
4
+ var turbopuffer = require('@turbopuffer/turbopuffer');
5
+ var filter = require('@mastra/core/vector/filter');
6
+
7
+ // src/vector/index.ts
8
+ var TurbopufferFilterTranslator = class extends filter.BaseFilterTranslator {
9
+ getSupportedOperators() {
10
+ return {
11
+ ...filter.BaseFilterTranslator.DEFAULT_OPERATORS,
12
+ logical: ["$and", "$or"],
13
+ array: ["$in", "$nin", "$all"],
14
+ element: ["$exists"],
15
+ regex: [],
16
+ // No regex support in Turbopuffer
17
+ custom: []
18
+ // No custom operators
19
+ };
20
+ }
21
+ /**
22
+ * Map Mastra operators to Turbopuffer operators
23
+ */
24
+ operatorMap = {
25
+ $eq: "Eq",
26
+ $ne: "NotEq",
27
+ $gt: "Gt",
28
+ $gte: "Gte",
29
+ $lt: "Lt",
30
+ $lte: "Lte",
31
+ $in: "In",
32
+ $nin: "NotIn"
33
+ };
34
+ /**
35
+ * Convert the Mastra filter to Turbopuffer format
36
+ */
37
+ translate(filter) {
38
+ if (this.isEmpty(filter)) {
39
+ return void 0;
40
+ }
41
+ this.validateFilter(filter);
42
+ const result = this.translateNode(filter);
43
+ if (!Array.isArray(result) || result.length !== 2 || result[0] !== "And" && result[0] !== "Or") {
44
+ return ["And", [result]];
45
+ }
46
+ return result;
47
+ }
48
+ /**
49
+ * Recursively translate a filter node
50
+ */
51
+ translateNode(node) {
52
+ if (node === null || node === void 0 || Object.keys(node).length === 0) {
53
+ return ["And", []];
54
+ }
55
+ if (this.isPrimitive(node)) {
56
+ throw new Error("Direct primitive values not valid in this context for Turbopuffer");
57
+ }
58
+ if (Array.isArray(node)) {
59
+ throw new Error("Direct array values not valid in this context for Turbopuffer");
60
+ }
61
+ const entries = Object.entries(node);
62
+ if (entries.length === 0) {
63
+ return ["And", []];
64
+ }
65
+ const [key, value] = entries[0];
66
+ if (key && this.isLogicalOperator(key)) {
67
+ return this.translateLogical(key, value);
68
+ }
69
+ if (entries.length > 1) {
70
+ const conditions = entries.map(([field, fieldValue]) => this.translateFieldCondition(field, fieldValue));
71
+ return ["And", conditions];
72
+ }
73
+ return this.translateFieldCondition(key, value);
74
+ }
75
+ /**
76
+ * Translate a field condition
77
+ */
78
+ translateFieldCondition(field, value) {
79
+ if (value instanceof Date) {
80
+ return [field, "Eq", this.normalizeValue(value)];
81
+ }
82
+ if (this.isPrimitive(value)) {
83
+ return [field, "Eq", this.normalizeValue(value)];
84
+ }
85
+ if (Array.isArray(value)) {
86
+ return [field, "In", this.normalizeArrayValues(value)];
87
+ }
88
+ if (typeof value === "object" && value !== null) {
89
+ const operators = Object.keys(value);
90
+ if (operators.length > 1) {
91
+ const allOperators = operators.every((op2) => this.isOperator(op2));
92
+ if (allOperators) {
93
+ const conditions = operators.map((op2) => this.translateOperator(field, op2, value[op2]));
94
+ return ["And", conditions];
95
+ } else {
96
+ const conditions = operators.map((op2) => {
97
+ const nestedField = `${field}.${op2}`;
98
+ return this.translateFieldCondition(nestedField, value[op2]);
99
+ });
100
+ return ["And", conditions];
101
+ }
102
+ }
103
+ const op = operators[0];
104
+ if (op && this.isOperator(op)) {
105
+ return this.translateOperator(field, op, value[op]);
106
+ }
107
+ if (op && !this.isOperator(op)) {
108
+ const nestedField = `${field}.${op}`;
109
+ return this.translateFieldCondition(nestedField, value[op]);
110
+ }
111
+ }
112
+ throw new Error(`Unsupported filter format for field: ${field}`);
113
+ }
114
+ /**
115
+ * Translate a logical operator
116
+ */
117
+ translateLogical(operator, conditions) {
118
+ const logicalOp = operator === "$and" ? "And" : "Or";
119
+ if (!Array.isArray(conditions)) {
120
+ throw new Error(`Logical operator ${operator} requires an array of conditions`);
121
+ }
122
+ const translatedConditions = conditions.map((condition) => {
123
+ if (typeof condition !== "object" || condition === null) {
124
+ throw new Error(`Invalid condition for logical operator ${operator}`);
125
+ }
126
+ return this.translateNode(condition);
127
+ });
128
+ return [logicalOp, translatedConditions];
129
+ }
130
+ /**
131
+ * Translate a specific operator
132
+ */
133
+ translateOperator(field, operator, value) {
134
+ if (operator && this.operatorMap[operator]) {
135
+ return [field, this.operatorMap[operator], this.normalizeValue(value)];
136
+ }
137
+ switch (operator) {
138
+ case "$exists":
139
+ return value ? [field, "NotEq", null] : [field, "Eq", null];
140
+ case "$all":
141
+ if (!Array.isArray(value) || value.length === 0) {
142
+ throw new Error("$all operator requires a non-empty array");
143
+ }
144
+ const allConditions = value.map((item) => [field, "In", [this.normalizeValue(item)]]);
145
+ return ["And", allConditions];
146
+ default:
147
+ throw new Error(`Unsupported operator: ${operator || "undefined"}`);
148
+ }
149
+ }
150
+ /**
151
+ * Normalize a value for comparison operations
152
+ */
153
+ normalizeValue(value) {
154
+ if (value instanceof Date) {
155
+ return value.toISOString();
156
+ }
157
+ return value;
158
+ }
159
+ /**
160
+ * Normalize array values
161
+ */
162
+ normalizeArrayValues(values) {
163
+ return values.map((value) => this.normalizeValue(value));
164
+ }
165
+ };
166
+
167
+ // src/vector/index.ts
168
+ var TurbopufferVector = class extends vector.MastraVector {
169
+ client;
170
+ filterTranslator;
171
+ // There is no explicit create index operation in Turbopuffer, so just register that
172
+ // someone has called createIndex() and verify that subsequent upsert calls are consistent
173
+ // with how the index was "created"
174
+ createIndexCache = /* @__PURE__ */ new Map();
175
+ opts;
176
+ constructor(opts) {
177
+ super();
178
+ this.filterTranslator = new TurbopufferFilterTranslator();
179
+ this.opts = opts;
180
+ const baseClient = new turbopuffer.Turbopuffer(opts);
181
+ const telemetry = this.__getTelemetry();
182
+ this.client = telemetry?.traceClass(baseClient, {
183
+ spanNamePrefix: "turbopuffer-vector",
184
+ attributes: {
185
+ "vector.type": "turbopuffer"
186
+ }
187
+ }) ?? baseClient;
188
+ }
189
+ async createIndex({ indexName, dimension, metric }) {
190
+ metric = metric ?? "cosine";
191
+ if (this.createIndexCache.has(indexName)) {
192
+ const expected = this.createIndexCache.get(indexName);
193
+ if (dimension !== expected.dimension || metric !== expected.metric) {
194
+ throw new Error(
195
+ `createIndex() called more than once with inconsistent inputs. Index ${indexName} expected dimensions=${expected.dimension} and metric=${expected.metric} but got dimensions=${dimension} and metric=${metric}`
196
+ );
197
+ }
198
+ return;
199
+ }
200
+ if (dimension <= 0) {
201
+ throw new Error("Dimension must be a positive integer");
202
+ }
203
+ let distanceMetric = "cosine_distance";
204
+ switch (metric) {
205
+ case "cosine":
206
+ distanceMetric = "cosine_distance";
207
+ break;
208
+ case "euclidean":
209
+ distanceMetric = "euclidean_squared";
210
+ break;
211
+ case "dotproduct":
212
+ throw new Error("dotproduct is not supported in Turbopuffer");
213
+ }
214
+ this.createIndexCache.set(indexName, {
215
+ indexName,
216
+ dimension,
217
+ metric,
218
+ tpufDistanceMetric: distanceMetric
219
+ });
220
+ }
221
+ async upsert({ indexName, vectors, metadata, ids }) {
222
+ try {
223
+ if (vectors.length === 0) {
224
+ throw new Error("upsert() called with empty vectors");
225
+ }
226
+ const index = this.client.namespace(indexName);
227
+ const createIndex = this.createIndexCache.get(indexName);
228
+ if (!createIndex) {
229
+ throw new Error(`createIndex() not called for this index`);
230
+ }
231
+ const distanceMetric = createIndex.tpufDistanceMetric;
232
+ const vectorIds = ids || vectors.map(() => crypto.randomUUID());
233
+ const records = vectors.map((vector, i) => ({
234
+ id: vectorIds[i],
235
+ vector,
236
+ attributes: metadata?.[i] || {}
237
+ }));
238
+ const batchSize = 100;
239
+ for (let i = 0; i < records.length; i += batchSize) {
240
+ const batch = records.slice(i, i + batchSize);
241
+ const upsertOptions = {
242
+ vectors: batch,
243
+ distance_metric: distanceMetric
244
+ };
245
+ const schemaConfig = this.opts.schemaConfigForIndex?.(indexName);
246
+ if (schemaConfig) {
247
+ upsertOptions.schema = schemaConfig.schema;
248
+ if (vectors[0]?.length !== schemaConfig.dimensions) {
249
+ throw new Error(
250
+ `Turbopuffer index ${indexName} was configured with dimensions=${schemaConfig.dimensions} but attempting to upsert vectors[0].length=${vectors[0]?.length}`
251
+ );
252
+ }
253
+ }
254
+ await index.upsert(upsertOptions);
255
+ }
256
+ return vectorIds;
257
+ } catch (error) {
258
+ throw new Error(`Failed to upsert vectors into Turbopuffer namespace ${indexName}: ${error}`);
259
+ }
260
+ }
261
+ async query({ indexName, queryVector, topK, filter, includeVector }) {
262
+ const schemaConfig = this.opts.schemaConfigForIndex?.(indexName);
263
+ if (schemaConfig) {
264
+ if (queryVector.length !== schemaConfig.dimensions) {
265
+ throw new Error(
266
+ `Turbopuffer index ${indexName} was configured with dimensions=${schemaConfig.dimensions} but attempting to query with queryVector.length=${queryVector.length}`
267
+ );
268
+ }
269
+ }
270
+ const createIndex = this.createIndexCache.get(indexName);
271
+ if (!createIndex) {
272
+ throw new Error(`createIndex() not called for this index`);
273
+ }
274
+ const distanceMetric = createIndex.tpufDistanceMetric;
275
+ try {
276
+ const index = this.client.namespace(indexName);
277
+ const translatedFilter = this.filterTranslator.translate(filter);
278
+ const results = await index.query({
279
+ distance_metric: distanceMetric,
280
+ vector: queryVector,
281
+ top_k: topK,
282
+ filters: translatedFilter,
283
+ include_vectors: includeVector,
284
+ include_attributes: true,
285
+ consistency: { level: "strong" }
286
+ // todo: make this configurable somehow?
287
+ });
288
+ return results.map((item) => ({
289
+ id: String(item.id),
290
+ score: typeof item.dist === "number" ? item.dist : 0,
291
+ metadata: item.attributes || {},
292
+ ...includeVector && item.vector ? { vector: item.vector } : {}
293
+ }));
294
+ } catch (error) {
295
+ throw new Error(`Failed to query Turbopuffer namespace ${indexName}: ${error}`);
296
+ }
297
+ }
298
+ async listIndexes() {
299
+ try {
300
+ const namespacesResult = await this.client.namespaces({});
301
+ return namespacesResult.namespaces.map((namespace) => namespace.id);
302
+ } catch (error) {
303
+ throw new Error(`Failed to list Turbopuffer namespaces: ${error}`);
304
+ }
305
+ }
306
+ async describeIndex(indexName) {
307
+ try {
308
+ const namespace = this.client.namespace(indexName);
309
+ const metadata = await namespace.metadata();
310
+ const createIndex = this.createIndexCache.get(indexName);
311
+ if (!createIndex) {
312
+ throw new Error(`createIndex() not called for this index`);
313
+ }
314
+ const dimension = metadata.dimensions;
315
+ const count = metadata.approx_count;
316
+ return {
317
+ dimension,
318
+ count,
319
+ metric: createIndex.metric
320
+ };
321
+ } catch (error) {
322
+ throw new Error(`Failed to describe Turbopuffer namespace ${indexName}: ${error}`);
323
+ }
324
+ }
325
+ async deleteIndex(indexName) {
326
+ try {
327
+ const namespace = this.client.namespace(indexName);
328
+ await namespace.deleteAll();
329
+ this.createIndexCache.delete(indexName);
330
+ } catch (error) {
331
+ throw new Error(`Failed to delete Turbopuffer namespace ${indexName}: ${error.message}`);
332
+ }
333
+ }
334
+ };
335
+
336
+ exports.TurbopufferVector = TurbopufferVector;
@@ -0,0 +1,2 @@
1
+ export { TurbopufferVectorOptions } from './_tsup-dts-rollup.cjs';
2
+ export { TurbopufferVector } from './_tsup-dts-rollup.cjs';
@@ -0,0 +1,2 @@
1
+ export { TurbopufferVectorOptions } from './_tsup-dts-rollup.js';
2
+ export { TurbopufferVector } from './_tsup-dts-rollup.js';
package/dist/index.js ADDED
@@ -0,0 +1,334 @@
1
+ import { MastraVector } from '@mastra/core/vector';
2
+ import { Turbopuffer } from '@turbopuffer/turbopuffer';
3
+ import { BaseFilterTranslator } from '@mastra/core/vector/filter';
4
+
5
+ // src/vector/index.ts
6
+ var TurbopufferFilterTranslator = class extends BaseFilterTranslator {
7
+ getSupportedOperators() {
8
+ return {
9
+ ...BaseFilterTranslator.DEFAULT_OPERATORS,
10
+ logical: ["$and", "$or"],
11
+ array: ["$in", "$nin", "$all"],
12
+ element: ["$exists"],
13
+ regex: [],
14
+ // No regex support in Turbopuffer
15
+ custom: []
16
+ // No custom operators
17
+ };
18
+ }
19
+ /**
20
+ * Map Mastra operators to Turbopuffer operators
21
+ */
22
+ operatorMap = {
23
+ $eq: "Eq",
24
+ $ne: "NotEq",
25
+ $gt: "Gt",
26
+ $gte: "Gte",
27
+ $lt: "Lt",
28
+ $lte: "Lte",
29
+ $in: "In",
30
+ $nin: "NotIn"
31
+ };
32
+ /**
33
+ * Convert the Mastra filter to Turbopuffer format
34
+ */
35
+ translate(filter) {
36
+ if (this.isEmpty(filter)) {
37
+ return void 0;
38
+ }
39
+ this.validateFilter(filter);
40
+ const result = this.translateNode(filter);
41
+ if (!Array.isArray(result) || result.length !== 2 || result[0] !== "And" && result[0] !== "Or") {
42
+ return ["And", [result]];
43
+ }
44
+ return result;
45
+ }
46
+ /**
47
+ * Recursively translate a filter node
48
+ */
49
+ translateNode(node) {
50
+ if (node === null || node === void 0 || Object.keys(node).length === 0) {
51
+ return ["And", []];
52
+ }
53
+ if (this.isPrimitive(node)) {
54
+ throw new Error("Direct primitive values not valid in this context for Turbopuffer");
55
+ }
56
+ if (Array.isArray(node)) {
57
+ throw new Error("Direct array values not valid in this context for Turbopuffer");
58
+ }
59
+ const entries = Object.entries(node);
60
+ if (entries.length === 0) {
61
+ return ["And", []];
62
+ }
63
+ const [key, value] = entries[0];
64
+ if (key && this.isLogicalOperator(key)) {
65
+ return this.translateLogical(key, value);
66
+ }
67
+ if (entries.length > 1) {
68
+ const conditions = entries.map(([field, fieldValue]) => this.translateFieldCondition(field, fieldValue));
69
+ return ["And", conditions];
70
+ }
71
+ return this.translateFieldCondition(key, value);
72
+ }
73
+ /**
74
+ * Translate a field condition
75
+ */
76
+ translateFieldCondition(field, value) {
77
+ if (value instanceof Date) {
78
+ return [field, "Eq", this.normalizeValue(value)];
79
+ }
80
+ if (this.isPrimitive(value)) {
81
+ return [field, "Eq", this.normalizeValue(value)];
82
+ }
83
+ if (Array.isArray(value)) {
84
+ return [field, "In", this.normalizeArrayValues(value)];
85
+ }
86
+ if (typeof value === "object" && value !== null) {
87
+ const operators = Object.keys(value);
88
+ if (operators.length > 1) {
89
+ const allOperators = operators.every((op2) => this.isOperator(op2));
90
+ if (allOperators) {
91
+ const conditions = operators.map((op2) => this.translateOperator(field, op2, value[op2]));
92
+ return ["And", conditions];
93
+ } else {
94
+ const conditions = operators.map((op2) => {
95
+ const nestedField = `${field}.${op2}`;
96
+ return this.translateFieldCondition(nestedField, value[op2]);
97
+ });
98
+ return ["And", conditions];
99
+ }
100
+ }
101
+ const op = operators[0];
102
+ if (op && this.isOperator(op)) {
103
+ return this.translateOperator(field, op, value[op]);
104
+ }
105
+ if (op && !this.isOperator(op)) {
106
+ const nestedField = `${field}.${op}`;
107
+ return this.translateFieldCondition(nestedField, value[op]);
108
+ }
109
+ }
110
+ throw new Error(`Unsupported filter format for field: ${field}`);
111
+ }
112
+ /**
113
+ * Translate a logical operator
114
+ */
115
+ translateLogical(operator, conditions) {
116
+ const logicalOp = operator === "$and" ? "And" : "Or";
117
+ if (!Array.isArray(conditions)) {
118
+ throw new Error(`Logical operator ${operator} requires an array of conditions`);
119
+ }
120
+ const translatedConditions = conditions.map((condition) => {
121
+ if (typeof condition !== "object" || condition === null) {
122
+ throw new Error(`Invalid condition for logical operator ${operator}`);
123
+ }
124
+ return this.translateNode(condition);
125
+ });
126
+ return [logicalOp, translatedConditions];
127
+ }
128
+ /**
129
+ * Translate a specific operator
130
+ */
131
+ translateOperator(field, operator, value) {
132
+ if (operator && this.operatorMap[operator]) {
133
+ return [field, this.operatorMap[operator], this.normalizeValue(value)];
134
+ }
135
+ switch (operator) {
136
+ case "$exists":
137
+ return value ? [field, "NotEq", null] : [field, "Eq", null];
138
+ case "$all":
139
+ if (!Array.isArray(value) || value.length === 0) {
140
+ throw new Error("$all operator requires a non-empty array");
141
+ }
142
+ const allConditions = value.map((item) => [field, "In", [this.normalizeValue(item)]]);
143
+ return ["And", allConditions];
144
+ default:
145
+ throw new Error(`Unsupported operator: ${operator || "undefined"}`);
146
+ }
147
+ }
148
+ /**
149
+ * Normalize a value for comparison operations
150
+ */
151
+ normalizeValue(value) {
152
+ if (value instanceof Date) {
153
+ return value.toISOString();
154
+ }
155
+ return value;
156
+ }
157
+ /**
158
+ * Normalize array values
159
+ */
160
+ normalizeArrayValues(values) {
161
+ return values.map((value) => this.normalizeValue(value));
162
+ }
163
+ };
164
+
165
+ // src/vector/index.ts
166
+ var TurbopufferVector = class extends MastraVector {
167
+ client;
168
+ filterTranslator;
169
+ // There is no explicit create index operation in Turbopuffer, so just register that
170
+ // someone has called createIndex() and verify that subsequent upsert calls are consistent
171
+ // with how the index was "created"
172
+ createIndexCache = /* @__PURE__ */ new Map();
173
+ opts;
174
+ constructor(opts) {
175
+ super();
176
+ this.filterTranslator = new TurbopufferFilterTranslator();
177
+ this.opts = opts;
178
+ const baseClient = new Turbopuffer(opts);
179
+ const telemetry = this.__getTelemetry();
180
+ this.client = telemetry?.traceClass(baseClient, {
181
+ spanNamePrefix: "turbopuffer-vector",
182
+ attributes: {
183
+ "vector.type": "turbopuffer"
184
+ }
185
+ }) ?? baseClient;
186
+ }
187
+ async createIndex({ indexName, dimension, metric }) {
188
+ metric = metric ?? "cosine";
189
+ if (this.createIndexCache.has(indexName)) {
190
+ const expected = this.createIndexCache.get(indexName);
191
+ if (dimension !== expected.dimension || metric !== expected.metric) {
192
+ throw new Error(
193
+ `createIndex() called more than once with inconsistent inputs. Index ${indexName} expected dimensions=${expected.dimension} and metric=${expected.metric} but got dimensions=${dimension} and metric=${metric}`
194
+ );
195
+ }
196
+ return;
197
+ }
198
+ if (dimension <= 0) {
199
+ throw new Error("Dimension must be a positive integer");
200
+ }
201
+ let distanceMetric = "cosine_distance";
202
+ switch (metric) {
203
+ case "cosine":
204
+ distanceMetric = "cosine_distance";
205
+ break;
206
+ case "euclidean":
207
+ distanceMetric = "euclidean_squared";
208
+ break;
209
+ case "dotproduct":
210
+ throw new Error("dotproduct is not supported in Turbopuffer");
211
+ }
212
+ this.createIndexCache.set(indexName, {
213
+ indexName,
214
+ dimension,
215
+ metric,
216
+ tpufDistanceMetric: distanceMetric
217
+ });
218
+ }
219
+ async upsert({ indexName, vectors, metadata, ids }) {
220
+ try {
221
+ if (vectors.length === 0) {
222
+ throw new Error("upsert() called with empty vectors");
223
+ }
224
+ const index = this.client.namespace(indexName);
225
+ const createIndex = this.createIndexCache.get(indexName);
226
+ if (!createIndex) {
227
+ throw new Error(`createIndex() not called for this index`);
228
+ }
229
+ const distanceMetric = createIndex.tpufDistanceMetric;
230
+ const vectorIds = ids || vectors.map(() => crypto.randomUUID());
231
+ const records = vectors.map((vector, i) => ({
232
+ id: vectorIds[i],
233
+ vector,
234
+ attributes: metadata?.[i] || {}
235
+ }));
236
+ const batchSize = 100;
237
+ for (let i = 0; i < records.length; i += batchSize) {
238
+ const batch = records.slice(i, i + batchSize);
239
+ const upsertOptions = {
240
+ vectors: batch,
241
+ distance_metric: distanceMetric
242
+ };
243
+ const schemaConfig = this.opts.schemaConfigForIndex?.(indexName);
244
+ if (schemaConfig) {
245
+ upsertOptions.schema = schemaConfig.schema;
246
+ if (vectors[0]?.length !== schemaConfig.dimensions) {
247
+ throw new Error(
248
+ `Turbopuffer index ${indexName} was configured with dimensions=${schemaConfig.dimensions} but attempting to upsert vectors[0].length=${vectors[0]?.length}`
249
+ );
250
+ }
251
+ }
252
+ await index.upsert(upsertOptions);
253
+ }
254
+ return vectorIds;
255
+ } catch (error) {
256
+ throw new Error(`Failed to upsert vectors into Turbopuffer namespace ${indexName}: ${error}`);
257
+ }
258
+ }
259
+ async query({ indexName, queryVector, topK, filter, includeVector }) {
260
+ const schemaConfig = this.opts.schemaConfigForIndex?.(indexName);
261
+ if (schemaConfig) {
262
+ if (queryVector.length !== schemaConfig.dimensions) {
263
+ throw new Error(
264
+ `Turbopuffer index ${indexName} was configured with dimensions=${schemaConfig.dimensions} but attempting to query with queryVector.length=${queryVector.length}`
265
+ );
266
+ }
267
+ }
268
+ const createIndex = this.createIndexCache.get(indexName);
269
+ if (!createIndex) {
270
+ throw new Error(`createIndex() not called for this index`);
271
+ }
272
+ const distanceMetric = createIndex.tpufDistanceMetric;
273
+ try {
274
+ const index = this.client.namespace(indexName);
275
+ const translatedFilter = this.filterTranslator.translate(filter);
276
+ const results = await index.query({
277
+ distance_metric: distanceMetric,
278
+ vector: queryVector,
279
+ top_k: topK,
280
+ filters: translatedFilter,
281
+ include_vectors: includeVector,
282
+ include_attributes: true,
283
+ consistency: { level: "strong" }
284
+ // todo: make this configurable somehow?
285
+ });
286
+ return results.map((item) => ({
287
+ id: String(item.id),
288
+ score: typeof item.dist === "number" ? item.dist : 0,
289
+ metadata: item.attributes || {},
290
+ ...includeVector && item.vector ? { vector: item.vector } : {}
291
+ }));
292
+ } catch (error) {
293
+ throw new Error(`Failed to query Turbopuffer namespace ${indexName}: ${error}`);
294
+ }
295
+ }
296
+ async listIndexes() {
297
+ try {
298
+ const namespacesResult = await this.client.namespaces({});
299
+ return namespacesResult.namespaces.map((namespace) => namespace.id);
300
+ } catch (error) {
301
+ throw new Error(`Failed to list Turbopuffer namespaces: ${error}`);
302
+ }
303
+ }
304
+ async describeIndex(indexName) {
305
+ try {
306
+ const namespace = this.client.namespace(indexName);
307
+ const metadata = await namespace.metadata();
308
+ const createIndex = this.createIndexCache.get(indexName);
309
+ if (!createIndex) {
310
+ throw new Error(`createIndex() not called for this index`);
311
+ }
312
+ const dimension = metadata.dimensions;
313
+ const count = metadata.approx_count;
314
+ return {
315
+ dimension,
316
+ count,
317
+ metric: createIndex.metric
318
+ };
319
+ } catch (error) {
320
+ throw new Error(`Failed to describe Turbopuffer namespace ${indexName}: ${error}`);
321
+ }
322
+ }
323
+ async deleteIndex(indexName) {
324
+ try {
325
+ const namespace = this.client.namespace(indexName);
326
+ await namespace.deleteAll();
327
+ this.createIndexCache.delete(indexName);
328
+ } catch (error) {
329
+ throw new Error(`Failed to delete Turbopuffer namespace ${indexName}: ${error.message}`);
330
+ }
331
+ }
332
+ };
333
+
334
+ export { TurbopufferVector };
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@mastra/turbopuffer",
3
+ "version": "0.0.1-alpha.0",
4
+ "description": "Turbopuffer vector store provider for Mastra",
5
+ "type": "module",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "main": "dist/index.js",
10
+ "types": "dist/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "import": {
14
+ "types": "./dist/index.d.ts",
15
+ "default": "./dist/index.js"
16
+ },
17
+ "require": {
18
+ "types": "./dist/index.d.cts",
19
+ "default": "./dist/index.cjs"
20
+ }
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "dependencies": {
25
+ "@turbopuffer/turbopuffer": "^0.6.4",
26
+ "@mastra/core": "^0.5.0"
27
+ },
28
+ "devDependencies": {
29
+ "@microsoft/api-extractor": "^7.52.1",
30
+ "@types/node": "^22.13.10",
31
+ "dotenv": "^16.4.7",
32
+ "eslint": "^9.22.0",
33
+ "tsup": "^8.4.0",
34
+ "typescript": "^5.8.2",
35
+ "vitest": "^3.0.8",
36
+ "@internal/lint": "0.0.1"
37
+ },
38
+ "scripts": {
39
+ "build": "tsup src/index.ts --format esm,cjs --experimental-dts --clean --treeshake=smallest --splitting",
40
+ "build:watch": "pnpm build --watch",
41
+ "test": "vitest run",
42
+ "lint": "eslint ."
43
+ }
44
+ }