@neural-tools/vector-db 0.1.4 → 0.1.6

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.md CHANGED
@@ -1,80 +1,21 @@
1
- # Neural Tools License
2
-
3
- Copyright (c) 2025 Luke Amy. All rights reserved.
4
-
5
- ## License Agreement
6
-
7
- This software is provided under a dual-license model:
8
-
9
- ### 1. Free Tier License (MIT)
10
-
11
- The following components are licensed under the MIT License:
12
-
13
- - Basic MCP generation functionality
14
- - Claude command generation
15
- - Core utilities and types
16
- - Basic templates
17
- - Documentation and examples
18
-
19
- Permission is hereby granted, free of charge, to any person obtaining a copy of the free tier components to use, copy, modify, merge, publish, and distribute, subject to the following conditions:
20
-
21
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
22
-
23
- ### 2. Pro/Enterprise License (Proprietary)
24
-
25
- The following features require a valid Pro or Enterprise license:
26
-
27
- **Pro Features:**
28
- - Vector database integration
29
- - Semantic caching
30
- - Fine-tuning workflows
31
- - Cloud deployment templates (AWS/GCP)
32
- - Premium templates and examples
33
- - GitHub automation features
34
-
35
- **Enterprise Features:**
36
- - White-label support
37
- - Custom integrations
38
- - Priority support
39
- - SLA guarantees
40
- - Team collaboration features
41
-
42
- These features are proprietary and may not be used without a valid license key purchased from neural-tools.dev.
43
-
44
- ### License Terms
45
-
46
- 1. **Free Tier**: You may use the free tier features for any purpose, including commercial use, under the MIT License terms.
47
-
48
- 2. **Pro/Enterprise**: You must purchase a license to access Pro or Enterprise features. Each license is:
49
- - Per-user for individual licenses
50
- - Per-organization for team/enterprise licenses
51
- - Non-transferable without written consent
52
- - Subject to the terms at neural-tools.dev/terms
53
-
54
- 3. **Source Code**: This repository is private. You may not:
55
- - Redistribute the source code
56
- - Create derivative works for redistribution
57
- - Reverse engineer Pro/Enterprise features
58
- - Remove or circumvent license checks
59
-
60
- 4. **Support**: Support is provided based on your license tier:
61
- - Free: Community support only
62
- - Pro: Email support (48-hour response)
63
- - Enterprise: Priority support with SLA
64
-
65
- ### Warranty Disclaimer
66
-
67
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
68
-
69
- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70
-
71
- ### Contact
72
-
73
- For licensing inquiries:
74
- - Email: licensing@neural-tools.dev
75
- - Website: https://neural-tools.dev/pricing
76
- - Support: support@neural-tools.dev
77
-
78
- ---
79
-
80
- **Last Updated:** January 2025
1
+ # MIT License
2
+
3
+ Copyright (c) 2025 Luke Amy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,421 @@
1
+ # @neural-tools/vector-db
2
+
3
+ > Vector database abstraction layer for Neural Tools
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@neural-tools/vector-db)](https://www.npmjs.com/package/@neural-tools/vector-db)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](../../LICENSE.md)
7
+
8
+ Unified interface for working with vector databases. Supports Pinecone, Chroma, Qdrant, and a local in-memory store.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+ npm install @neural-tools/vector-db
14
+ ```
15
+
16
+ ### With Pinecone
17
+
18
+ ```bash
19
+ npm install @neural-tools/vector-db @pinecone-database/pinecone
20
+ ```
21
+
22
+ ### With Chroma
23
+
24
+ ```bash
25
+ npm install @neural-tools/vector-db chromadb
26
+ ```
27
+
28
+ ### With Qdrant
29
+
30
+ ```bash
31
+ npm install @neural-tools/vector-db @qdrant/js-client-rest
32
+ ```
33
+
34
+ ## Features
35
+
36
+ - **Unified API** - Same interface for all vector databases
37
+ - **Multiple Providers** - Pinecone, Chroma, Qdrant, local storage
38
+ - **Type-Safe** - Full TypeScript support
39
+ - **Easy Switching** - Change providers without code changes
40
+ - **Local Development** - In-memory store for testing
41
+
42
+ ## Quick Start
43
+
44
+ ### Using Pinecone
45
+
46
+ ```typescript
47
+ import { VectorDB } from '@neural-tools/vector-db';
48
+
49
+ const db = new VectorDB({
50
+ provider: 'pinecone',
51
+ config: {
52
+ apiKey: process.env.PINECONE_API_KEY,
53
+ environment: 'us-west1-gcp',
54
+ indexName: 'my-index'
55
+ }
56
+ });
57
+
58
+ await db.connect();
59
+
60
+ // Insert vectors
61
+ await db.upsert([
62
+ {
63
+ id: '1',
64
+ values: [0.1, 0.2, 0.3, ...],
65
+ metadata: { text: 'Hello world', category: 'greeting' }
66
+ }
67
+ ]);
68
+
69
+ // Query
70
+ const results = await db.query({
71
+ vector: [0.1, 0.2, 0.3, ...],
72
+ topK: 5,
73
+ filter: { category: 'greeting' }
74
+ });
75
+ ```
76
+
77
+ ### Using Local Store (Development)
78
+
79
+ ```typescript
80
+ import { VectorDB } from '@neural-tools/vector-db';
81
+
82
+ const db = new VectorDB({
83
+ provider: 'local',
84
+ config: {
85
+ dimension: 1536 // Embedding dimension
86
+ }
87
+ });
88
+
89
+ await db.connect();
90
+
91
+ // Same API as other providers
92
+ await db.upsert([...]);
93
+ const results = await db.query({...});
94
+ ```
95
+
96
+ ### Using Chroma
97
+
98
+ ```typescript
99
+ import { VectorDB } from '@neural-tools/vector-db';
100
+
101
+ const db = new VectorDB({
102
+ provider: 'chroma',
103
+ config: {
104
+ url: 'http://localhost:8000',
105
+ collectionName: 'my-collection'
106
+ }
107
+ });
108
+
109
+ await db.connect();
110
+ ```
111
+
112
+ ### Using Qdrant
113
+
114
+ ```typescript
115
+ import { VectorDB } from '@neural-tools/vector-db';
116
+
117
+ const db = new VectorDB({
118
+ provider: 'qdrant',
119
+ config: {
120
+ url: 'http://localhost:6333',
121
+ collectionName: 'my-collection',
122
+ apiKey: process.env.QDRANT_API_KEY // Optional
123
+ }
124
+ });
125
+
126
+ await db.connect();
127
+ ```
128
+
129
+ ## API Reference
130
+
131
+ ### Constructor
132
+
133
+ ```typescript
134
+ new VectorDB(options: VectorDBOptions)
135
+
136
+ interface VectorDBOptions {
137
+ provider: 'pinecone' | 'chroma' | 'qdrant' | 'local';
138
+ config: ProviderConfig;
139
+ }
140
+ ```
141
+
142
+ ### Methods
143
+
144
+ #### `connect()`
145
+
146
+ Connect to the vector database.
147
+
148
+ ```typescript
149
+ await db.connect();
150
+ ```
151
+
152
+ #### `disconnect()`
153
+
154
+ Disconnect from the database.
155
+
156
+ ```typescript
157
+ await db.disconnect();
158
+ ```
159
+
160
+ #### `upsert(vectors)`
161
+
162
+ Insert or update vectors.
163
+
164
+ ```typescript
165
+ await db.upsert([
166
+ {
167
+ id: string;
168
+ values: number[];
169
+ metadata?: Record<string, any>;
170
+ }
171
+ ]);
172
+ ```
173
+
174
+ #### `query(options)`
175
+
176
+ Search for similar vectors.
177
+
178
+ ```typescript
179
+ const results = await db.query({
180
+ vector: number[]; // Query vector
181
+ topK: number; // Number of results
182
+ filter?: object; // Metadata filter
183
+ includeMetadata?: boolean;
184
+ includeValues?: boolean;
185
+ });
186
+
187
+ // Returns
188
+ interface QueryResult {
189
+ id: string;
190
+ score: number;
191
+ values?: number[];
192
+ metadata?: Record<string, any>;
193
+ }
194
+ ```
195
+
196
+ #### `delete(ids)`
197
+
198
+ Delete vectors by ID.
199
+
200
+ ```typescript
201
+ await db.delete(['id1', 'id2']);
202
+ ```
203
+
204
+ #### `fetch(ids)`
205
+
206
+ Retrieve vectors by ID.
207
+
208
+ ```typescript
209
+ const vectors = await db.fetch(['id1', 'id2']);
210
+ ```
211
+
212
+ ## Configuration
213
+
214
+ ### Pinecone
215
+
216
+ ```typescript
217
+ {
218
+ provider: 'pinecone',
219
+ config: {
220
+ apiKey: string;
221
+ environment: string;
222
+ indexName: string;
223
+ namespace?: string;
224
+ }
225
+ }
226
+ ```
227
+
228
+ ### Chroma
229
+
230
+ ```typescript
231
+ {
232
+ provider: 'chroma',
233
+ config: {
234
+ url: string;
235
+ collectionName: string;
236
+ auth?: {
237
+ provider: string;
238
+ credentials: string;
239
+ };
240
+ }
241
+ }
242
+ ```
243
+
244
+ ### Qdrant
245
+
246
+ ```typescript
247
+ {
248
+ provider: 'qdrant',
249
+ config: {
250
+ url: string;
251
+ collectionName: string;
252
+ apiKey?: string;
253
+ }
254
+ }
255
+ ```
256
+
257
+ ### Local (In-Memory)
258
+
259
+ ```typescript
260
+ {
261
+ provider: 'local',
262
+ config: {
263
+ dimension: number; // Vector dimension
264
+ }
265
+ }
266
+ ```
267
+
268
+ ## Examples
269
+
270
+ ### Semantic Search
271
+
272
+ ```typescript
273
+ import { VectorDB } from '@neural-tools/vector-db';
274
+ import { embed } from './embeddings'; // Your embedding function
275
+
276
+ const db = new VectorDB({
277
+ provider: 'pinecone',
278
+ config: { /* ... */ }
279
+ });
280
+
281
+ await db.connect();
282
+
283
+ // Index documents
284
+ const documents = [
285
+ 'Neural Tools is amazing',
286
+ 'I love building with AI',
287
+ 'Vector databases are powerful'
288
+ ];
289
+
290
+ for (const [i, doc] of documents.entries()) {
291
+ const embedding = await embed(doc);
292
+ await db.upsert([{
293
+ id: `doc-${i}`,
294
+ values: embedding,
295
+ metadata: { text: doc }
296
+ }]);
297
+ }
298
+
299
+ // Search
300
+ const queryEmbedding = await embed('AI development tools');
301
+ const results = await db.query({
302
+ vector: queryEmbedding,
303
+ topK: 2,
304
+ includeMetadata: true
305
+ });
306
+
307
+ console.log(results);
308
+ // [
309
+ // { id: 'doc-0', score: 0.95, metadata: { text: 'Neural Tools is amazing' } },
310
+ // { id: 'doc-1', score: 0.87, metadata: { text: 'I love building with AI' } }
311
+ // ]
312
+ ```
313
+
314
+ ### Filtered Search
315
+
316
+ ```typescript
317
+ await db.query({
318
+ vector: queryVector,
319
+ topK: 10,
320
+ filter: {
321
+ category: 'documentation',
322
+ published: true,
323
+ date: { $gte: '2024-01-01' }
324
+ }
325
+ });
326
+ ```
327
+
328
+ ### Batch Operations
329
+
330
+ ```typescript
331
+ // Batch insert
332
+ await db.upsert(
333
+ Array.from({ length: 1000 }, (_, i) => ({
334
+ id: `vector-${i}`,
335
+ values: generateVector(),
336
+ metadata: { index: i }
337
+ }))
338
+ );
339
+
340
+ // Batch delete
341
+ await db.delete(
342
+ Array.from({ length: 100 }, (_, i) => `vector-${i}`)
343
+ );
344
+ ```
345
+
346
+ ## Environment Variables
347
+
348
+ ```bash
349
+ # Pinecone
350
+ PINECONE_API_KEY=your-api-key
351
+ PINECONE_ENVIRONMENT=us-west1-gcp
352
+ PINECONE_INDEX=my-index
353
+
354
+ # Chroma
355
+ CHROMA_URL=http://localhost:8000
356
+ CHROMA_COLLECTION=my-collection
357
+
358
+ # Qdrant
359
+ QDRANT_URL=http://localhost:6333
360
+ QDRANT_API_KEY=your-api-key
361
+ QDRANT_COLLECTION=my-collection
362
+ ```
363
+
364
+ ## Testing
365
+
366
+ The local provider is perfect for testing:
367
+
368
+ ```typescript
369
+ import { VectorDB } from '@neural-tools/vector-db';
370
+
371
+ describe('Vector operations', () => {
372
+ let db: VectorDB;
373
+
374
+ beforeEach(async () => {
375
+ db = new VectorDB({
376
+ provider: 'local',
377
+ config: { dimension: 1536 }
378
+ });
379
+ await db.connect();
380
+ });
381
+
382
+ it('should insert and query', async () => {
383
+ await db.upsert([{
384
+ id: '1',
385
+ values: new Array(1536).fill(0.1),
386
+ metadata: { test: true }
387
+ }]);
388
+
389
+ const results = await db.query({
390
+ vector: new Array(1536).fill(0.1),
391
+ topK: 1
392
+ });
393
+
394
+ expect(results[0].id).toBe('1');
395
+ });
396
+ });
397
+ ```
398
+
399
+ ## Dependencies
400
+
401
+ - [@neural-tools/core](../core) - Core utilities
402
+
403
+ ### Peer Dependencies (Optional)
404
+
405
+ - `@pinecone-database/pinecone` - For Pinecone support
406
+ - `chromadb` - For Chroma support
407
+ - `@qdrant/js-client-rest` - For Qdrant support
408
+
409
+ ## Contributing
410
+
411
+ Contributions are welcome! See the [main repository](https://github.com/MacLeanLuke/neural-tools) for guidelines.
412
+
413
+ ## License
414
+
415
+ MIT - See [LICENSE.md](../../LICENSE.md) for details.
416
+
417
+ ## Links
418
+
419
+ - [Documentation](https://neural-tools.com/docs/vector-db.html)
420
+ - [GitHub](https://github.com/MacLeanLuke/neural-tools)
421
+ - [npm](https://www.npmjs.com/package/@neural-tools/vector-db)
@@ -0,0 +1,110 @@
1
+ interface VectorDBConfig {
2
+ provider: 'pinecone' | 'qdrant' | 'chromadb' | 'local';
3
+ apiKey?: string;
4
+ endpoint?: string;
5
+ dimension?: number;
6
+ metric?: 'cosine' | 'euclidean' | 'dotproduct';
7
+ namespace?: string;
8
+ }
9
+ interface Vector {
10
+ id: string;
11
+ values: number[];
12
+ metadata?: Record<string, any>;
13
+ }
14
+ interface QueryResult {
15
+ id: string;
16
+ score: number;
17
+ metadata?: Record<string, any>;
18
+ values?: number[];
19
+ }
20
+ interface QueryOptions {
21
+ topK?: number;
22
+ filter?: Record<string, any>;
23
+ includeValues?: boolean;
24
+ includeMetadata?: boolean;
25
+ }
26
+ interface UpsertOptions {
27
+ namespace?: string;
28
+ batch?: boolean;
29
+ }
30
+ declare abstract class VectorStore {
31
+ protected config: VectorDBConfig;
32
+ constructor(config: VectorDBConfig);
33
+ /**
34
+ * Initialize the vector store connection
35
+ */
36
+ abstract connect(): Promise<void>;
37
+ /**
38
+ * Insert or update vectors
39
+ */
40
+ abstract upsert(vectors: Vector[], options?: UpsertOptions): Promise<void>;
41
+ /**
42
+ * Query for similar vectors
43
+ */
44
+ abstract query(vector: number[], options?: QueryOptions): Promise<QueryResult[]>;
45
+ /**
46
+ * Delete vectors by ID
47
+ */
48
+ abstract delete(ids: string[], namespace?: string): Promise<void>;
49
+ /**
50
+ * Get vector by ID
51
+ */
52
+ abstract fetch(ids: string[], namespace?: string): Promise<Vector[]>;
53
+ /**
54
+ * Delete all vectors in a namespace
55
+ */
56
+ abstract deleteNamespace(namespace: string): Promise<void>;
57
+ /**
58
+ * Close the connection
59
+ */
60
+ abstract disconnect(): Promise<void>;
61
+ }
62
+
63
+ /**
64
+ * Simple in-memory vector store for local development and testing
65
+ */
66
+ declare class LocalVectorStore extends VectorStore {
67
+ private vectors;
68
+ connect(): Promise<void>;
69
+ upsert(vectors: Vector[], options?: UpsertOptions): Promise<void>;
70
+ query(vector: number[], options?: QueryOptions): Promise<QueryResult[]>;
71
+ delete(ids: string[]): Promise<void>;
72
+ fetch(ids: string[]): Promise<Vector[]>;
73
+ deleteNamespace(): Promise<void>;
74
+ disconnect(): Promise<void>;
75
+ /**
76
+ * Calculate cosine similarity between two vectors
77
+ */
78
+ private cosineSimilarity;
79
+ /**
80
+ * Check if metadata matches filter
81
+ */
82
+ private matchesFilter;
83
+ /**
84
+ * Get all vectors (for testing/debugging)
85
+ */
86
+ getAll(): Vector[];
87
+ /**
88
+ * Get count of vectors
89
+ */
90
+ count(): number;
91
+ }
92
+
93
+ /**
94
+ * Create a vector store instance based on the configuration
95
+ */
96
+ declare function createVectorStore(config: VectorDBConfig): Promise<VectorStore>;
97
+ /**
98
+ * Helper function to create embeddings from text
99
+ * In production, this would call OpenAI, Anthropic, or other embedding APIs
100
+ */
101
+ declare function createEmbedding(text: string): Promise<number[]>;
102
+ /**
103
+ * Batch text into chunks for embedding
104
+ */
105
+ declare function chunkText(text: string, options?: {
106
+ chunkSize?: number;
107
+ overlap?: number;
108
+ }): string[];
109
+
110
+ export { LocalVectorStore, type QueryOptions, type QueryResult, type UpsertOptions, type Vector, type VectorDBConfig, VectorStore, chunkText, createEmbedding, createVectorStore };
package/dist/index.d.ts CHANGED
@@ -1,19 +1,110 @@
1
- import { VectorDBConfig, VectorStore } from './types';
2
- export * from './types';
3
- export { LocalVectorStore } from './local-store';
1
+ interface VectorDBConfig {
2
+ provider: 'pinecone' | 'qdrant' | 'chromadb' | 'local';
3
+ apiKey?: string;
4
+ endpoint?: string;
5
+ dimension?: number;
6
+ metric?: 'cosine' | 'euclidean' | 'dotproduct';
7
+ namespace?: string;
8
+ }
9
+ interface Vector {
10
+ id: string;
11
+ values: number[];
12
+ metadata?: Record<string, any>;
13
+ }
14
+ interface QueryResult {
15
+ id: string;
16
+ score: number;
17
+ metadata?: Record<string, any>;
18
+ values?: number[];
19
+ }
20
+ interface QueryOptions {
21
+ topK?: number;
22
+ filter?: Record<string, any>;
23
+ includeValues?: boolean;
24
+ includeMetadata?: boolean;
25
+ }
26
+ interface UpsertOptions {
27
+ namespace?: string;
28
+ batch?: boolean;
29
+ }
30
+ declare abstract class VectorStore {
31
+ protected config: VectorDBConfig;
32
+ constructor(config: VectorDBConfig);
33
+ /**
34
+ * Initialize the vector store connection
35
+ */
36
+ abstract connect(): Promise<void>;
37
+ /**
38
+ * Insert or update vectors
39
+ */
40
+ abstract upsert(vectors: Vector[], options?: UpsertOptions): Promise<void>;
41
+ /**
42
+ * Query for similar vectors
43
+ */
44
+ abstract query(vector: number[], options?: QueryOptions): Promise<QueryResult[]>;
45
+ /**
46
+ * Delete vectors by ID
47
+ */
48
+ abstract delete(ids: string[], namespace?: string): Promise<void>;
49
+ /**
50
+ * Get vector by ID
51
+ */
52
+ abstract fetch(ids: string[], namespace?: string): Promise<Vector[]>;
53
+ /**
54
+ * Delete all vectors in a namespace
55
+ */
56
+ abstract deleteNamespace(namespace: string): Promise<void>;
57
+ /**
58
+ * Close the connection
59
+ */
60
+ abstract disconnect(): Promise<void>;
61
+ }
62
+
63
+ /**
64
+ * Simple in-memory vector store for local development and testing
65
+ */
66
+ declare class LocalVectorStore extends VectorStore {
67
+ private vectors;
68
+ connect(): Promise<void>;
69
+ upsert(vectors: Vector[], options?: UpsertOptions): Promise<void>;
70
+ query(vector: number[], options?: QueryOptions): Promise<QueryResult[]>;
71
+ delete(ids: string[]): Promise<void>;
72
+ fetch(ids: string[]): Promise<Vector[]>;
73
+ deleteNamespace(): Promise<void>;
74
+ disconnect(): Promise<void>;
75
+ /**
76
+ * Calculate cosine similarity between two vectors
77
+ */
78
+ private cosineSimilarity;
79
+ /**
80
+ * Check if metadata matches filter
81
+ */
82
+ private matchesFilter;
83
+ /**
84
+ * Get all vectors (for testing/debugging)
85
+ */
86
+ getAll(): Vector[];
87
+ /**
88
+ * Get count of vectors
89
+ */
90
+ count(): number;
91
+ }
92
+
4
93
  /**
5
94
  * Create a vector store instance based on the configuration
6
95
  */
7
- export declare function createVectorStore(config: VectorDBConfig): Promise<VectorStore>;
96
+ declare function createVectorStore(config: VectorDBConfig): Promise<VectorStore>;
8
97
  /**
9
98
  * Helper function to create embeddings from text
10
99
  * In production, this would call OpenAI, Anthropic, or other embedding APIs
11
100
  */
12
- export declare function createEmbedding(text: string): Promise<number[]>;
101
+ declare function createEmbedding(text: string): Promise<number[]>;
13
102
  /**
14
103
  * Batch text into chunks for embedding
15
104
  */
16
- export declare function chunkText(text: string, options?: {
105
+ declare function chunkText(text: string, options?: {
17
106
  chunkSize?: number;
18
107
  overlap?: number;
19
108
  }): string[];
109
+
110
+ export { LocalVectorStore, type QueryOptions, type QueryResult, type UpsertOptions, type Vector, type VectorDBConfig, VectorStore, chunkText, createEmbedding, createVectorStore };
package/dist/index.js CHANGED
@@ -1,87 +1 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.LocalVectorStore = void 0;
18
- exports.createVectorStore = createVectorStore;
19
- exports.createEmbedding = createEmbedding;
20
- exports.chunkText = chunkText;
21
- const local_store_1 = require("./local-store");
22
- const core_1 = require("@neural-tools/core");
23
- __exportStar(require("./types"), exports);
24
- var local_store_2 = require("./local-store");
25
- Object.defineProperty(exports, "LocalVectorStore", { enumerable: true, get: function () { return local_store_2.LocalVectorStore; } });
26
- /**
27
- * Create a vector store instance based on the configuration
28
- */
29
- async function createVectorStore(config) {
30
- switch (config.provider) {
31
- case 'local':
32
- return new local_store_1.LocalVectorStore(config);
33
- case 'pinecone':
34
- await (0, core_1.requireFeature)('vector-db', 'Vector Database Integration');
35
- throw new Error('Pinecone integration coming soon. Use local provider for now.');
36
- case 'qdrant':
37
- await (0, core_1.requireFeature)('vector-db', 'Vector Database Integration');
38
- throw new Error('Qdrant integration coming soon. Use local provider for now.');
39
- case 'chromadb':
40
- await (0, core_1.requireFeature)('vector-db', 'Vector Database Integration');
41
- throw new Error('ChromaDB integration coming soon. Use local provider for now.');
42
- default:
43
- throw new Error(`Unknown vector store provider: ${config.provider}`);
44
- }
45
- }
46
- /**
47
- * Helper function to create embeddings from text
48
- * In production, this would call OpenAI, Anthropic, or other embedding APIs
49
- */
50
- async function createEmbedding(text) {
51
- // Placeholder: Simple hash-based embedding for testing
52
- // In production, use proper embedding models
53
- const hash = simpleHash(text);
54
- const dimension = 384; // Common embedding dimension
55
- const embedding = new Array(dimension).fill(0);
56
- // Create a deterministic but distributed embedding from hash
57
- for (let i = 0; i < dimension; i++) {
58
- embedding[i] = Math.sin(hash + i) * Math.cos(hash / (i + 1));
59
- }
60
- // Normalize
61
- const norm = Math.sqrt(embedding.reduce((sum, val) => sum + val * val, 0));
62
- return embedding.map(val => val / norm);
63
- }
64
- function simpleHash(str) {
65
- let hash = 0;
66
- for (let i = 0; i < str.length; i++) {
67
- const char = str.charCodeAt(i);
68
- hash = ((hash << 5) - hash) + char;
69
- hash = hash & hash; // Convert to 32-bit integer
70
- }
71
- return Math.abs(hash);
72
- }
73
- /**
74
- * Batch text into chunks for embedding
75
- */
76
- function chunkText(text, options = {}) {
77
- const chunkSize = options.chunkSize || 500;
78
- const overlap = options.overlap || 50;
79
- const chunks = [];
80
- let start = 0;
81
- while (start < text.length) {
82
- const end = Math.min(start + chunkSize, text.length);
83
- chunks.push(text.slice(start, end));
84
- start += chunkSize - overlap;
85
- }
86
- return chunks;
87
- }
1
+ "use strict";var d=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var p=Object.getOwnPropertyNames;var f=Object.prototype.hasOwnProperty;var h=(t,e)=>{for(var r in e)d(t,r,{get:e[r],enumerable:!0})},g=(t,e,r,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of p(e))!f.call(t,n)&&n!==r&&d(t,n,{get:()=>e[n],enumerable:!(o=m(e,n))||o.enumerable});return t};var v=t=>g(d({},"__esModule",{value:!0}),t);var P={};h(P,{LocalVectorStore:()=>c,VectorStore:()=>a,chunkText:()=>w,createEmbedding:()=>y,createVectorStore:()=>b});module.exports=v(P);var a=class{config;constructor(e){this.config=e}};var c=class extends a{vectors=new Map;async connect(){}async upsert(e,r){for(let o of e)this.vectors.set(o.id,o)}async query(e,r){let o=r?.topK||10,n=[];for(let[s,i]of this.vectors){if(r?.filter&&!this.matchesFilter(i.metadata,r.filter))continue;let l=this.cosineSimilarity(e,i.values);n.push({id:s,score:l,metadata:r?.includeMetadata!==!1?i.metadata:void 0,values:r?.includeValues?i.values:void 0})}return n.sort((s,i)=>i.score-s.score),n.slice(0,o)}async delete(e){for(let r of e)this.vectors.delete(r)}async fetch(e){let r=[];for(let o of e){let n=this.vectors.get(o);n&&r.push(n)}return r}async deleteNamespace(){this.vectors.clear()}async disconnect(){}cosineSimilarity(e,r){if(e.length!==r.length)throw new Error("Vectors must have same length");let o=0,n=0,s=0;for(let i=0;i<e.length;i++)o+=e[i]*r[i],n+=e[i]*e[i],s+=r[i]*r[i];return o/(Math.sqrt(n)*Math.sqrt(s))}matchesFilter(e,r){if(!e)return!1;for(let[o,n]of Object.entries(r))if(e[o]!==n)return!1;return!0}getAll(){return Array.from(this.vectors.values())}count(){return this.vectors.size}};var u=require("@neural-tools/core");async function b(t){switch(t.provider){case"local":return new c(t);case"pinecone":throw await(0,u.requireFeature)("vector-db","Vector Database Integration"),new Error("Pinecone integration coming soon. Use local provider for now.");case"qdrant":throw await(0,u.requireFeature)("vector-db","Vector Database Integration"),new Error("Qdrant integration coming soon. Use local provider for now.");case"chromadb":throw await(0,u.requireFeature)("vector-db","Vector Database Integration"),new Error("ChromaDB integration coming soon. Use local provider for now.");default:throw new Error(`Unknown vector store provider: ${t.provider}`)}}async function y(t){let e=V(t),r=384,o=new Array(r).fill(0);for(let s=0;s<r;s++)o[s]=Math.sin(e+s)*Math.cos(e/(s+1));let n=Math.sqrt(o.reduce((s,i)=>s+i*i,0));return o.map(s=>s/n)}function V(t){let e=0;for(let r=0;r<t.length;r++){let o=t.charCodeAt(r);e=(e<<5)-e+o,e=e&e}return Math.abs(e)}function w(t,e={}){let r=e.chunkSize||500,o=e.overlap||50,n=[],s=0;for(;s<t.length;){let i=Math.min(s+r,t.length);n.push(t.slice(s,i)),s+=r-o}return n}0&&(module.exports={LocalVectorStore,VectorStore,chunkText,createEmbedding,createVectorStore});
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ var a=class{config;constructor(e){this.config=e}};var c=class extends a{vectors=new Map;async connect(){}async upsert(e,r){for(let n of e)this.vectors.set(n.id,n)}async query(e,r){let n=r?.topK||10,s=[];for(let[t,o]of this.vectors){if(r?.filter&&!this.matchesFilter(o.metadata,r.filter))continue;let d=this.cosineSimilarity(e,o.values);s.push({id:t,score:d,metadata:r?.includeMetadata!==!1?o.metadata:void 0,values:r?.includeValues?o.values:void 0})}return s.sort((t,o)=>o.score-t.score),s.slice(0,n)}async delete(e){for(let r of e)this.vectors.delete(r)}async fetch(e){let r=[];for(let n of e){let s=this.vectors.get(n);s&&r.push(s)}return r}async deleteNamespace(){this.vectors.clear()}async disconnect(){}cosineSimilarity(e,r){if(e.length!==r.length)throw new Error("Vectors must have same length");let n=0,s=0,t=0;for(let o=0;o<e.length;o++)n+=e[o]*r[o],s+=e[o]*e[o],t+=r[o]*r[o];return n/(Math.sqrt(s)*Math.sqrt(t))}matchesFilter(e,r){if(!e)return!1;for(let[n,s]of Object.entries(r))if(e[n]!==s)return!1;return!0}getAll(){return Array.from(this.vectors.values())}count(){return this.vectors.size}};import{requireFeature as u}from"@neural-tools/core";async function w(i){switch(i.provider){case"local":return new c(i);case"pinecone":throw await u("vector-db","Vector Database Integration"),new Error("Pinecone integration coming soon. Use local provider for now.");case"qdrant":throw await u("vector-db","Vector Database Integration"),new Error("Qdrant integration coming soon. Use local provider for now.");case"chromadb":throw await u("vector-db","Vector Database Integration"),new Error("ChromaDB integration coming soon. Use local provider for now.");default:throw new Error(`Unknown vector store provider: ${i.provider}`)}}async function P(i){let e=l(i),r=384,n=new Array(r).fill(0);for(let t=0;t<r;t++)n[t]=Math.sin(e+t)*Math.cos(e/(t+1));let s=Math.sqrt(n.reduce((t,o)=>t+o*o,0));return n.map(t=>t/s)}function l(i){let e=0;for(let r=0;r<i.length;r++){let n=i.charCodeAt(r);e=(e<<5)-e+n,e=e&e}return Math.abs(e)}function x(i,e={}){let r=e.chunkSize||500,n=e.overlap||50,s=[],t=0;for(;t<i.length;){let o=Math.min(t+r,i.length);s.push(i.slice(t,o)),t+=r-n}return s}export{c as LocalVectorStore,a as VectorStore,x as chunkText,P as createEmbedding,w as createVectorStore};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neural-tools/vector-db",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Vector database abstraction layer for Neural Tools",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -13,7 +13,7 @@
13
13
  "url": "https://github.com/MacLeanLuke/neural-tools.git",
14
14
  "directory": "packages/vector-db"
15
15
  },
16
- "homepage": "https://neural-tools.com",
16
+ "homepage": "https://neural-tools.com/docs/vector-db.html",
17
17
  "bugs": {
18
18
  "url": "https://github.com/MacLeanLuke/neural-tools/issues"
19
19
  },
@@ -27,7 +27,7 @@
27
27
  "ai"
28
28
  ],
29
29
  "dependencies": {
30
- "@neural-tools/core": "0.1.4"
30
+ "@neural-tools/core": "0.1.6"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/node": "^20.11.5",
@@ -53,8 +53,8 @@
53
53
  "dist"
54
54
  ],
55
55
  "scripts": {
56
- "build": "tsc",
57
- "dev": "tsc --watch",
56
+ "build": "tsup",
57
+ "dev": "tsup --watch",
58
58
  "clean": "rm -rf dist",
59
59
  "test": "echo 'Tests coming soon'"
60
60
  }
@@ -1,30 +0,0 @@
1
- import { VectorStore, Vector, QueryResult, QueryOptions, UpsertOptions } from './types';
2
- /**
3
- * Simple in-memory vector store for local development and testing
4
- */
5
- export declare class LocalVectorStore extends VectorStore {
6
- private vectors;
7
- connect(): Promise<void>;
8
- upsert(vectors: Vector[], options?: UpsertOptions): Promise<void>;
9
- query(vector: number[], options?: QueryOptions): Promise<QueryResult[]>;
10
- delete(ids: string[]): Promise<void>;
11
- fetch(ids: string[]): Promise<Vector[]>;
12
- deleteNamespace(): Promise<void>;
13
- disconnect(): Promise<void>;
14
- /**
15
- * Calculate cosine similarity between two vectors
16
- */
17
- private cosineSimilarity;
18
- /**
19
- * Check if metadata matches filter
20
- */
21
- private matchesFilter;
22
- /**
23
- * Get all vectors (for testing/debugging)
24
- */
25
- getAll(): Vector[];
26
- /**
27
- * Get count of vectors
28
- */
29
- count(): number;
30
- }
@@ -1,103 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.LocalVectorStore = void 0;
4
- const types_1 = require("./types");
5
- /**
6
- * Simple in-memory vector store for local development and testing
7
- */
8
- class LocalVectorStore extends types_1.VectorStore {
9
- vectors = new Map();
10
- async connect() {
11
- // No connection needed for local store
12
- }
13
- async upsert(vectors, options) {
14
- for (const vector of vectors) {
15
- this.vectors.set(vector.id, vector);
16
- }
17
- }
18
- async query(vector, options) {
19
- const topK = options?.topK || 10;
20
- const results = [];
21
- // Calculate similarity for all vectors
22
- for (const [id, storedVector] of this.vectors) {
23
- // Skip if filter doesn't match
24
- if (options?.filter && !this.matchesFilter(storedVector.metadata, options.filter)) {
25
- continue;
26
- }
27
- const score = this.cosineSimilarity(vector, storedVector.values);
28
- results.push({
29
- id,
30
- score,
31
- metadata: options?.includeMetadata !== false ? storedVector.metadata : undefined,
32
- values: options?.includeValues ? storedVector.values : undefined
33
- });
34
- }
35
- // Sort by score descending and take topK
36
- results.sort((a, b) => b.score - a.score);
37
- return results.slice(0, topK);
38
- }
39
- async delete(ids) {
40
- for (const id of ids) {
41
- this.vectors.delete(id);
42
- }
43
- }
44
- async fetch(ids) {
45
- const results = [];
46
- for (const id of ids) {
47
- const vector = this.vectors.get(id);
48
- if (vector) {
49
- results.push(vector);
50
- }
51
- }
52
- return results;
53
- }
54
- async deleteNamespace() {
55
- this.vectors.clear();
56
- }
57
- async disconnect() {
58
- // No cleanup needed for local store
59
- }
60
- /**
61
- * Calculate cosine similarity between two vectors
62
- */
63
- cosineSimilarity(a, b) {
64
- if (a.length !== b.length) {
65
- throw new Error('Vectors must have same length');
66
- }
67
- let dotProduct = 0;
68
- let normA = 0;
69
- let normB = 0;
70
- for (let i = 0; i < a.length; i++) {
71
- dotProduct += a[i] * b[i];
72
- normA += a[i] * a[i];
73
- normB += b[i] * b[i];
74
- }
75
- return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
76
- }
77
- /**
78
- * Check if metadata matches filter
79
- */
80
- matchesFilter(metadata, filter) {
81
- if (!metadata)
82
- return false;
83
- for (const [key, value] of Object.entries(filter)) {
84
- if (metadata[key] !== value) {
85
- return false;
86
- }
87
- }
88
- return true;
89
- }
90
- /**
91
- * Get all vectors (for testing/debugging)
92
- */
93
- getAll() {
94
- return Array.from(this.vectors.values());
95
- }
96
- /**
97
- * Get count of vectors
98
- */
99
- count() {
100
- return this.vectors.size;
101
- }
102
- }
103
- exports.LocalVectorStore = LocalVectorStore;
package/dist/types.d.ts DELETED
@@ -1,61 +0,0 @@
1
- export interface VectorDBConfig {
2
- provider: 'pinecone' | 'qdrant' | 'chromadb' | 'local';
3
- apiKey?: string;
4
- endpoint?: string;
5
- dimension?: number;
6
- metric?: 'cosine' | 'euclidean' | 'dotproduct';
7
- namespace?: string;
8
- }
9
- export interface Vector {
10
- id: string;
11
- values: number[];
12
- metadata?: Record<string, any>;
13
- }
14
- export interface QueryResult {
15
- id: string;
16
- score: number;
17
- metadata?: Record<string, any>;
18
- values?: number[];
19
- }
20
- export interface QueryOptions {
21
- topK?: number;
22
- filter?: Record<string, any>;
23
- includeValues?: boolean;
24
- includeMetadata?: boolean;
25
- }
26
- export interface UpsertOptions {
27
- namespace?: string;
28
- batch?: boolean;
29
- }
30
- export declare abstract class VectorStore {
31
- protected config: VectorDBConfig;
32
- constructor(config: VectorDBConfig);
33
- /**
34
- * Initialize the vector store connection
35
- */
36
- abstract connect(): Promise<void>;
37
- /**
38
- * Insert or update vectors
39
- */
40
- abstract upsert(vectors: Vector[], options?: UpsertOptions): Promise<void>;
41
- /**
42
- * Query for similar vectors
43
- */
44
- abstract query(vector: number[], options?: QueryOptions): Promise<QueryResult[]>;
45
- /**
46
- * Delete vectors by ID
47
- */
48
- abstract delete(ids: string[], namespace?: string): Promise<void>;
49
- /**
50
- * Get vector by ID
51
- */
52
- abstract fetch(ids: string[], namespace?: string): Promise<Vector[]>;
53
- /**
54
- * Delete all vectors in a namespace
55
- */
56
- abstract deleteNamespace(namespace: string): Promise<void>;
57
- /**
58
- * Close the connection
59
- */
60
- abstract disconnect(): Promise<void>;
61
- }
package/dist/types.js DELETED
@@ -1,10 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VectorStore = void 0;
4
- class VectorStore {
5
- config;
6
- constructor(config) {
7
- this.config = config;
8
- }
9
- }
10
- exports.VectorStore = VectorStore;