@mastra/libsql 0.13.8-alpha.0 → 0.13.8-alpha.1

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,515 +0,0 @@
1
- import { createClient } from '@libsql/client';
2
- import type { Client as TursoClient, InValue } from '@libsql/client';
3
-
4
- import { ErrorCategory, ErrorDomain, MastraError } from '@mastra/core/error';
5
- import { parseSqlIdentifier } from '@mastra/core/utils';
6
- import { MastraVector } from '@mastra/core/vector';
7
- import type {
8
- IndexStats,
9
- QueryResult,
10
- QueryVectorParams,
11
- CreateIndexParams,
12
- UpsertVectorParams,
13
- DescribeIndexParams,
14
- DeleteIndexParams,
15
- DeleteVectorParams,
16
- UpdateVectorParams,
17
- } from '@mastra/core/vector';
18
- import type { LibSQLVectorFilter } from './filter';
19
- import { LibSQLFilterTranslator } from './filter';
20
- import { buildFilterQuery } from './sql-builder';
21
-
22
- interface LibSQLQueryVectorParams extends QueryVectorParams<LibSQLVectorFilter> {
23
- minScore?: number;
24
- }
25
-
26
- export interface LibSQLVectorConfig {
27
- connectionUrl: string;
28
- authToken?: string;
29
- syncUrl?: string;
30
- syncInterval?: number;
31
- /**
32
- * Maximum number of retries for write operations if an SQLITE_BUSY error occurs.
33
- * @default 5
34
- */
35
- maxRetries?: number;
36
- /**
37
- * Initial backoff time in milliseconds for retrying write operations on SQLITE_BUSY.
38
- * The backoff time will double with each retry (exponential backoff).
39
- * @default 100
40
- */
41
- initialBackoffMs?: number;
42
- }
43
-
44
- export class LibSQLVector extends MastraVector<LibSQLVectorFilter> {
45
- private turso: TursoClient;
46
- private readonly maxRetries: number;
47
- private readonly initialBackoffMs: number;
48
-
49
- constructor({
50
- connectionUrl,
51
- authToken,
52
- syncUrl,
53
- syncInterval,
54
- maxRetries = 5,
55
- initialBackoffMs = 100,
56
- }: LibSQLVectorConfig) {
57
- super();
58
-
59
- this.turso = createClient({
60
- url: connectionUrl,
61
- syncUrl: syncUrl,
62
- authToken,
63
- syncInterval,
64
- });
65
- this.maxRetries = maxRetries;
66
- this.initialBackoffMs = initialBackoffMs;
67
-
68
- if (connectionUrl.includes(`file:`) || connectionUrl.includes(`:memory:`)) {
69
- this.turso
70
- .execute('PRAGMA journal_mode=WAL;')
71
- .then(() => this.logger.debug('LibSQLStore: PRAGMA journal_mode=WAL set.'))
72
- .catch(err => this.logger.warn('LibSQLStore: Failed to set PRAGMA journal_mode=WAL.', err));
73
- this.turso
74
- .execute('PRAGMA busy_timeout = 5000;')
75
- .then(() => this.logger.debug('LibSQLStore: PRAGMA busy_timeout=5000 set.'))
76
- .catch(err => this.logger.warn('LibSQLStore: Failed to set PRAGMA busy_timeout=5000.', err));
77
- }
78
- }
79
-
80
- private async executeWriteOperationWithRetry<T>(operation: () => Promise<T>, isTransaction = false): Promise<T> {
81
- let attempts = 0;
82
- let backoff = this.initialBackoffMs;
83
- while (attempts < this.maxRetries) {
84
- try {
85
- return await operation();
86
- } catch (error: any) {
87
- if (
88
- error.code === 'SQLITE_BUSY' ||
89
- (error.message && error.message.toLowerCase().includes('database is locked'))
90
- ) {
91
- attempts++;
92
- if (attempts >= this.maxRetries) {
93
- this.logger.error(
94
- `LibSQLVector: Operation failed after ${this.maxRetries} attempts due to: ${error.message}`,
95
- error,
96
- );
97
- throw error;
98
- }
99
- this.logger.warn(
100
- `LibSQLVector: Attempt ${attempts} failed due to ${isTransaction ? 'transaction ' : ''}database lock. Retrying in ${backoff}ms...`,
101
- );
102
- await new Promise(resolve => setTimeout(resolve, backoff));
103
- backoff *= 2;
104
- } else {
105
- throw error;
106
- }
107
- }
108
- }
109
- throw new Error('LibSQLVector: Max retries reached, but no error was re-thrown from the loop.');
110
- }
111
-
112
- transformFilter(filter?: LibSQLVectorFilter) {
113
- const translator = new LibSQLFilterTranslator();
114
- return translator.translate(filter);
115
- }
116
-
117
- async query({
118
- indexName,
119
- queryVector,
120
- topK = 10,
121
- filter,
122
- includeVector = false,
123
- minScore = -1, // Default to -1 to include all results (cosine similarity ranges from -1 to 1)
124
- }: LibSQLQueryVectorParams): Promise<QueryResult[]> {
125
- try {
126
- if (!Number.isInteger(topK) || topK <= 0) {
127
- throw new Error('topK must be a positive integer');
128
- }
129
- if (!Array.isArray(queryVector) || !queryVector.every(x => typeof x === 'number' && Number.isFinite(x))) {
130
- throw new Error('queryVector must be an array of finite numbers');
131
- }
132
- } catch (error) {
133
- throw new MastraError(
134
- {
135
- id: 'LIBSQL_VECTOR_QUERY_INVALID_ARGS',
136
- domain: ErrorDomain.STORAGE,
137
- category: ErrorCategory.USER,
138
- },
139
- error,
140
- );
141
- }
142
-
143
- try {
144
- const parsedIndexName = parseSqlIdentifier(indexName, 'index name');
145
-
146
- const vectorStr = `[${queryVector.join(',')}]`;
147
-
148
- const translatedFilter = this.transformFilter(filter);
149
- const { sql: filterQuery, values: filterValues } = buildFilterQuery(translatedFilter);
150
- filterValues.push(minScore);
151
- filterValues.push(topK);
152
-
153
- const query = `
154
- WITH vector_scores AS (
155
- SELECT
156
- vector_id as id,
157
- (1-vector_distance_cos(embedding, '${vectorStr}')) as score,
158
- metadata
159
- ${includeVector ? ', vector_extract(embedding) as embedding' : ''}
160
- FROM ${parsedIndexName}
161
- ${filterQuery}
162
- )
163
- SELECT *
164
- FROM vector_scores
165
- WHERE score > ?
166
- ORDER BY score DESC
167
- LIMIT ?`;
168
-
169
- const result = await this.turso.execute({
170
- sql: query,
171
- args: filterValues,
172
- });
173
-
174
- return result.rows.map(({ id, score, metadata, embedding }) => ({
175
- id: id as string,
176
- score: score as number,
177
- metadata: JSON.parse((metadata as string) ?? '{}'),
178
- ...(includeVector && embedding && { vector: JSON.parse(embedding as string) }),
179
- }));
180
- } catch (error) {
181
- throw new MastraError(
182
- {
183
- id: 'LIBSQL_VECTOR_QUERY_FAILED',
184
- domain: ErrorDomain.STORAGE,
185
- category: ErrorCategory.THIRD_PARTY,
186
- },
187
- error,
188
- );
189
- }
190
- }
191
-
192
- public upsert(args: UpsertVectorParams): Promise<string[]> {
193
- try {
194
- return this.executeWriteOperationWithRetry(() => this.doUpsert(args), true);
195
- } catch (error) {
196
- throw new MastraError(
197
- {
198
- id: 'LIBSQL_VECTOR_UPSERT_FAILED',
199
- domain: ErrorDomain.STORAGE,
200
- category: ErrorCategory.THIRD_PARTY,
201
- },
202
- error,
203
- );
204
- }
205
- }
206
-
207
- private async doUpsert({ indexName, vectors, metadata, ids }: UpsertVectorParams): Promise<string[]> {
208
- const tx = await this.turso.transaction('write');
209
- try {
210
- const parsedIndexName = parseSqlIdentifier(indexName, 'index name');
211
- const vectorIds = ids || vectors.map(() => crypto.randomUUID());
212
-
213
- for (let i = 0; i < vectors.length; i++) {
214
- const query = `
215
- INSERT INTO ${parsedIndexName} (vector_id, embedding, metadata)
216
- VALUES (?, vector32(?), ?)
217
- ON CONFLICT(vector_id) DO UPDATE SET
218
- embedding = vector32(?),
219
- metadata = ?
220
- `;
221
- await tx.execute({
222
- sql: query,
223
- args: [
224
- vectorIds[i] as InValue,
225
- JSON.stringify(vectors[i]),
226
- JSON.stringify(metadata?.[i] || {}),
227
- JSON.stringify(vectors[i]),
228
- JSON.stringify(metadata?.[i] || {}),
229
- ],
230
- });
231
- }
232
- await tx.commit();
233
- return vectorIds;
234
- } catch (error) {
235
- !tx.closed && (await tx.rollback());
236
- if (error instanceof Error && error.message?.includes('dimensions are different')) {
237
- const match = error.message.match(/dimensions are different: (\d+) != (\d+)/);
238
- if (match) {
239
- const [, actual, expected] = match;
240
- throw new Error(
241
- `Vector dimension mismatch: Index "${indexName}" expects ${expected} dimensions but got ${actual} dimensions. ` +
242
- `Either use a matching embedding model or delete and recreate the index with the new dimension.`,
243
- );
244
- }
245
- }
246
- throw error;
247
- }
248
- }
249
-
250
- public createIndex(args: CreateIndexParams): Promise<void> {
251
- try {
252
- return this.executeWriteOperationWithRetry(() => this.doCreateIndex(args));
253
- } catch (error) {
254
- throw new MastraError(
255
- {
256
- id: 'LIBSQL_VECTOR_CREATE_INDEX_FAILED',
257
- domain: ErrorDomain.STORAGE,
258
- category: ErrorCategory.THIRD_PARTY,
259
- details: { indexName: args.indexName, dimension: args.dimension },
260
- },
261
- error,
262
- );
263
- }
264
- }
265
-
266
- private async doCreateIndex({ indexName, dimension }: CreateIndexParams): Promise<void> {
267
- if (!Number.isInteger(dimension) || dimension <= 0) {
268
- throw new Error('Dimension must be a positive integer');
269
- }
270
- const parsedIndexName = parseSqlIdentifier(indexName, 'index name');
271
- await this.turso.execute({
272
- sql: `
273
- CREATE TABLE IF NOT EXISTS ${parsedIndexName} (
274
- id SERIAL PRIMARY KEY,
275
- vector_id TEXT UNIQUE NOT NULL,
276
- embedding F32_BLOB(${dimension}),
277
- metadata TEXT DEFAULT '{}'
278
- );
279
- `,
280
- args: [],
281
- });
282
- await this.turso.execute({
283
- sql: `
284
- CREATE INDEX IF NOT EXISTS ${parsedIndexName}_vector_idx
285
- ON ${parsedIndexName} (libsql_vector_idx(embedding))
286
- `,
287
- args: [],
288
- });
289
- }
290
-
291
- public deleteIndex(args: DeleteIndexParams): Promise<void> {
292
- try {
293
- return this.executeWriteOperationWithRetry(() => this.doDeleteIndex(args));
294
- } catch (error) {
295
- throw new MastraError(
296
- {
297
- id: 'LIBSQL_VECTOR_DELETE_INDEX_FAILED',
298
- domain: ErrorDomain.STORAGE,
299
- category: ErrorCategory.THIRD_PARTY,
300
- details: { indexName: args.indexName },
301
- },
302
- error,
303
- );
304
- }
305
- }
306
-
307
- private async doDeleteIndex({ indexName }: DeleteIndexParams): Promise<void> {
308
- const parsedIndexName = parseSqlIdentifier(indexName, 'index name');
309
- await this.turso.execute({
310
- sql: `DROP TABLE IF EXISTS ${parsedIndexName}`,
311
- args: [],
312
- });
313
- }
314
-
315
- async listIndexes(): Promise<string[]> {
316
- try {
317
- const vectorTablesQuery = `
318
- SELECT name FROM sqlite_master
319
- WHERE type='table'
320
- AND sql LIKE '%F32_BLOB%';
321
- `;
322
- const result = await this.turso.execute({
323
- sql: vectorTablesQuery,
324
- args: [],
325
- });
326
- return result.rows.map(row => row.name as string);
327
- } catch (error: any) {
328
- throw new MastraError(
329
- {
330
- id: 'LIBSQL_VECTOR_LIST_INDEXES_FAILED',
331
- domain: ErrorDomain.STORAGE,
332
- category: ErrorCategory.THIRD_PARTY,
333
- },
334
- error,
335
- );
336
- }
337
- }
338
-
339
- /**
340
- * Retrieves statistics about a vector index.
341
- *
342
- * @param {string} indexName - The name of the index to describe
343
- * @returns A promise that resolves to the index statistics including dimension, count and metric
344
- */
345
- async describeIndex({ indexName }: DescribeIndexParams): Promise<IndexStats> {
346
- try {
347
- const parsedIndexName = parseSqlIdentifier(indexName, 'index name');
348
- // Get table info including column info
349
- const tableInfoQuery = `
350
- SELECT sql
351
- FROM sqlite_master
352
- WHERE type='table'
353
- AND name = ?;
354
- `;
355
- const tableInfo = await this.turso.execute({
356
- sql: tableInfoQuery,
357
- args: [parsedIndexName],
358
- });
359
-
360
- if (!tableInfo.rows[0]?.sql) {
361
- throw new Error(`Table ${parsedIndexName} not found`);
362
- }
363
-
364
- // Extract dimension from F32_BLOB definition
365
- const dimension = parseInt((tableInfo.rows[0].sql as string).match(/F32_BLOB\((\d+)\)/)?.[1] || '0');
366
-
367
- // Get row count
368
- const countQuery = `
369
- SELECT COUNT(*) as count
370
- FROM ${parsedIndexName};
371
- `;
372
- const countResult = await this.turso.execute({
373
- sql: countQuery,
374
- args: [],
375
- });
376
-
377
- // LibSQL only supports cosine similarity currently
378
- const metric: 'cosine' | 'euclidean' | 'dotproduct' = 'cosine';
379
-
380
- return {
381
- dimension,
382
- count: (countResult?.rows?.[0]?.count as number) ?? 0,
383
- metric,
384
- };
385
- } catch (e: any) {
386
- throw new MastraError(
387
- {
388
- id: 'LIBSQL_VECTOR_DESCRIBE_INDEX_FAILED',
389
- domain: ErrorDomain.STORAGE,
390
- category: ErrorCategory.THIRD_PARTY,
391
- details: { indexName },
392
- },
393
- e,
394
- );
395
- }
396
- }
397
-
398
- /**
399
- * Updates a vector by its ID with the provided vector and/or metadata.
400
- *
401
- * @param indexName - The name of the index containing the vector.
402
- * @param id - The ID of the vector to update.
403
- * @param update - An object containing the vector and/or metadata to update.
404
- * @param update.vector - An optional array of numbers representing the new vector.
405
- * @param update.metadata - An optional record containing the new metadata.
406
- * @returns A promise that resolves when the update is complete.
407
- * @throws Will throw an error if no updates are provided or if the update operation fails.
408
- */
409
- public updateVector(args: UpdateVectorParams): Promise<void> {
410
- return this.executeWriteOperationWithRetry(() => this.doUpdateVector(args));
411
- }
412
-
413
- private async doUpdateVector({ indexName, id, update }: UpdateVectorParams): Promise<void> {
414
- const parsedIndexName = parseSqlIdentifier(indexName, 'index name');
415
- const updates = [];
416
- const args: InValue[] = [];
417
-
418
- if (update.vector) {
419
- updates.push('embedding = vector32(?)');
420
- args.push(JSON.stringify(update.vector));
421
- }
422
-
423
- if (update.metadata) {
424
- updates.push('metadata = ?');
425
- args.push(JSON.stringify(update.metadata));
426
- }
427
-
428
- if (updates.length === 0) {
429
- throw new MastraError({
430
- id: 'LIBSQL_VECTOR_UPDATE_VECTOR_INVALID_ARGS',
431
- domain: ErrorDomain.STORAGE,
432
- category: ErrorCategory.USER,
433
- details: { indexName, id },
434
- text: 'No updates provided',
435
- });
436
- }
437
- args.push(id);
438
- const query = `
439
- UPDATE ${parsedIndexName}
440
- SET ${updates.join(', ')}
441
- WHERE vector_id = ?;
442
- `;
443
-
444
- try {
445
- await this.turso.execute({
446
- sql: query,
447
- args,
448
- });
449
- } catch (error) {
450
- throw new MastraError(
451
- {
452
- id: 'LIBSQL_VECTOR_UPDATE_VECTOR_FAILED',
453
- domain: ErrorDomain.STORAGE,
454
- category: ErrorCategory.THIRD_PARTY,
455
- details: { indexName, id },
456
- },
457
- error,
458
- );
459
- }
460
- }
461
-
462
- /**
463
- * Deletes a vector by its ID.
464
- * @param indexName - The name of the index containing the vector.
465
- * @param id - The ID of the vector to delete.
466
- * @returns A promise that resolves when the deletion is complete.
467
- * @throws Will throw an error if the deletion operation fails.
468
- */
469
- public deleteVector(args: DeleteVectorParams): Promise<void> {
470
- try {
471
- return this.executeWriteOperationWithRetry(() => this.doDeleteVector(args));
472
- } catch (error) {
473
- throw new MastraError(
474
- {
475
- id: 'LIBSQL_VECTOR_DELETE_VECTOR_FAILED',
476
- domain: ErrorDomain.STORAGE,
477
- category: ErrorCategory.THIRD_PARTY,
478
- details: { indexName: args.indexName, id: args.id },
479
- },
480
- error,
481
- );
482
- }
483
- }
484
-
485
- private async doDeleteVector({ indexName, id }: DeleteVectorParams): Promise<void> {
486
- const parsedIndexName = parseSqlIdentifier(indexName, 'index name');
487
- await this.turso.execute({
488
- sql: `DELETE FROM ${parsedIndexName} WHERE vector_id = ?`,
489
- args: [id],
490
- });
491
- }
492
-
493
- public truncateIndex(args: DeleteIndexParams): Promise<void> {
494
- try {
495
- return this.executeWriteOperationWithRetry(() => this._doTruncateIndex(args));
496
- } catch (error) {
497
- throw new MastraError(
498
- {
499
- id: 'LIBSQL_VECTOR_TRUNCATE_INDEX_FAILED',
500
- domain: ErrorDomain.STORAGE,
501
- category: ErrorCategory.THIRD_PARTY,
502
- details: { indexName: args.indexName },
503
- },
504
- error,
505
- );
506
- }
507
- }
508
-
509
- private async _doTruncateIndex({ indexName }: DeleteIndexParams): Promise<void> {
510
- await this.turso.execute({
511
- sql: `DELETE FROM ${parseSqlIdentifier(indexName, 'index name')}`,
512
- args: [],
513
- });
514
- }
515
- }
@@ -1,101 +0,0 @@
1
- /**
2
- * Vector store specific prompt that details supported operators and examples.
3
- * This prompt helps users construct valid filters for LibSQL Vector.
4
- */
5
- export const LIBSQL_PROMPT = `When querying LibSQL Vector, 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
- - $elemMatch: Match array elements that meet all specified conditions
31
- Example: { "items": { "$elemMatch": { "price": { "$gt": 100 } } } }
32
- - $contains: Check if array contains value
33
- Example: { "tags": { "$contains": "premium" } }
34
-
35
- Logical Operators:
36
- - $and: Logical AND (implicit when using multiple conditions)
37
- Example: { "$and": [{ "price": { "$gt": 100 } }, { "category": "electronics" }] }
38
- - $or: Logical OR
39
- Example: { "$or": [{ "price": { "$lt": 50 } }, { "category": "books" }] }
40
- - $not: Logical NOT
41
- Example: { "$not": { "category": "electronics" } }
42
- - $nor: Logical NOR
43
- Example: { "$nor": [{ "price": { "$lt": 50 } }, { "category": "books" }] }
44
-
45
- Element Operators:
46
- - $exists: Check if field exists
47
- Example: { "rating": { "$exists": true } }
48
-
49
- Special Operators:
50
- - $size: Array length check
51
- Example: { "tags": { "$size": 2 } }
52
-
53
- Restrictions:
54
- - Regex patterns are not supported
55
- - Direct RegExp patterns will throw an error
56
- - Nested fields are supported using dot notation
57
- - Multiple conditions on the same field are supported with both implicit and explicit $and
58
- - Array operations work on array fields only
59
- - Basic operators handle array values as JSON strings
60
- - Empty arrays in conditions are handled gracefully
61
- - Only logical operators ($and, $or, $not, $nor) can be used at the top level
62
- - All other operators must be used within a field condition
63
- Valid: { "field": { "$gt": 100 } }
64
- Valid: { "$and": [...] }
65
- Invalid: { "$gt": 100 }
66
- Invalid: { "$contains": "value" }
67
- - Logical operators must contain field conditions, not direct operators
68
- Valid: { "$and": [{ "field": { "$gt": 100 } }] }
69
- Invalid: { "$and": [{ "$gt": 100 }] }
70
- - $not operator:
71
- - Must be an object
72
- - Cannot be empty
73
- - Can be used at field level or top level
74
- - Valid: { "$not": { "field": "value" } }
75
- - Valid: { "field": { "$not": { "$eq": "value" } } }
76
- - Other logical operators ($and, $or, $nor):
77
- - Can only be used at top level or nested within other logical operators
78
- - Can not be used on a field level, or be nested inside a field
79
- - Can not be used inside an operator
80
- - Valid: { "$and": [{ "field": { "$gt": 100 } }] }
81
- - Valid: { "$or": [{ "$and": [{ "field": { "$gt": 100 } }] }] }
82
- - Invalid: { "field": { "$and": [{ "$gt": 100 }] } }
83
- - Invalid: { "field": { "$or": [{ "$gt": 100 }] } }
84
- - Invalid: { "field": { "$gt": { "$and": [{...}] } } }
85
- - $elemMatch requires an object with conditions
86
- Valid: { "array": { "$elemMatch": { "field": "value" } } }
87
- Invalid: { "array": { "$elemMatch": "value" } }
88
-
89
- Example Complex Query:
90
- {
91
- "$and": [
92
- { "category": { "$in": ["electronics", "computers"] } },
93
- { "price": { "$gte": 100, "$lte": 1000 } },
94
- { "tags": { "$all": ["premium", "sale"] } },
95
- { "items": { "$elemMatch": { "price": { "$gt": 50 }, "inStock": true } } },
96
- { "$or": [
97
- { "stock": { "$gt": 0 } },
98
- { "preorder": true }
99
- ]}
100
- ]
101
- }`;