@nebula-ai/sdk 0.0.31 → 0.0.34

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/README.md CHANGED
@@ -1,295 +1,168 @@
1
1
  # @nebula-ai/sdk
2
2
 
3
- Official JavaScript/TypeScript SDK for Nebula - Memory, Search, and AI-powered conversations.
4
-
5
- [![npm version](https://badge.fury.io/js/%40nebula-ai%2Fsdk.svg)](https://badge.fury.io/js/%40nebula-ai%2Fsdk)
6
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
- [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue.svg)](https://www.typescriptlang.org/)
3
+ Persistent memory layer for AI applications. Store, search, and retrieve information with semantic understanding.
8
4
 
9
5
  ## Installation
10
6
 
11
7
  ```bash
12
8
  npm install @nebula-ai/sdk
13
- # or
14
- yarn add @nebula-ai/sdk
15
- # or
16
- pnpm add @nebula-ai/sdk
17
9
  ```
18
10
 
19
11
  ## Quick Start
20
12
 
21
13
  ```typescript
22
- import { NebulaClient, RetrievalType } from '@nebula-ai/sdk';
14
+ import { NebulaClient } from '@nebula-ai/sdk';
23
15
 
24
- // Initialize the SDK
16
+ // Initialize client
25
17
  const client = new NebulaClient({
26
- apiKey: 'your-nebula-api-key',
27
- baseUrl: 'https://api.nebulacloud.app', // optional, defaults to this
28
- timeout: 30000 // optional, defaults to 30 seconds
18
+ apiKey: 'your-api-key'
29
19
  });
30
20
 
31
- // Create a cluster
32
- const cluster = await client.createCluster({
33
- name: 'My Project',
34
- description: 'A collection of project memories'
21
+ // Create a collection
22
+ const collection = await client.createCluster({
23
+ name: 'my_notes'
35
24
  });
36
25
 
37
- // Store a memory using the unified Memory model
26
+ // Store a memory
38
27
  const memoryId = await client.storeMemory({
39
- collection_id: cluster.id,
40
- content: 'This is an important piece of information about my project.',
41
- metadata: { category: 'project', priority: 'high' }
28
+ collection_id: collection.id,
29
+ content: 'Machine learning is transforming healthcare',
30
+ metadata: { topic: 'AI', importance: 'high' }
42
31
  });
43
32
 
44
- // Search for memories with advanced options
33
+ // Search memories
45
34
  const results = await client.search({
46
- query: 'project information',
47
- collection_ids: [cluster.id],
48
- limit: 5,
49
- retrieval_type: RetrievalType.ADVANCED,
50
- filters: { 'metadata.category': 'project' }
35
+ query: 'machine learning healthcare',
36
+ collection_ids: [collection.id],
37
+ limit: 5
51
38
  });
52
39
 
53
- console.log('Found memories:', results);
54
- ```
55
-
56
- ## API Reference
57
-
58
- ### Constructor
59
-
60
- ```typescript
61
- new NebulaClient(config: NebulaClientConfig)
40
+ results.forEach(result => {
41
+ console.log(`Score: ${result.score?.toFixed(2)}`);
42
+ console.log(`Content: ${result.content}`);
43
+ });
62
44
  ```
63
45
 
64
- **Config Options:**
65
- - `apiKey` (required): Your Nebula API key
66
- - `baseUrl` (optional): Custom API base URL, defaults to `https://api.nebulacloud.app`
67
- - `timeout` (optional): Request timeout in milliseconds, defaults to 30000
68
-
69
- ### Core Methods
46
+ ## Core Operations
70
47
 
71
- #### Clusters
48
+ ### Collections
72
49
 
73
50
  ```typescript
74
- // Create a new cluster
75
- await client.createCluster(options: { name: string, description?: string, metadata?: Record<string, any> })
76
-
77
- // Get a cluster by ID
78
- await client.getCluster(collectionId: string)
51
+ // Create
52
+ const collection = await client.createCluster({
53
+ name: 'my_collection',
54
+ description: 'Optional description'
55
+ });
79
56
 
80
- // Get a cluster by name
81
- await client.getClusterByName(name: string)
57
+ // List
58
+ const collections = await client.listClusters();
82
59
 
83
- // List all clusters
84
- await client.listClusters(options?: { limit?: number, offset?: number })
60
+ // Get by ID or name
61
+ const collection = await client.getCluster(collectionId);
62
+ const collection = await client.getClusterByName('my_collection');
85
63
 
86
- // Update a cluster
87
- await client.updateCluster(options: { collectionId: string, name?: string, description?: string, metadata?: Record<string, any> })
64
+ // Update
65
+ await client.updateCluster({
66
+ collectionId,
67
+ name: 'new_name'
68
+ });
88
69
 
89
- // Delete a cluster
90
- await client.deleteCluster(collectionId: string)
70
+ // Delete
71
+ await client.deleteCluster(collectionId);
91
72
  ```
92
73
 
93
- #### Conversations
74
+ ### Store Memories
94
75
 
95
76
  ```typescript
96
- // List conversations for the authenticated user
97
- await client.listConversations(options?: {
98
- limit?: number,
99
- offset?: number,
100
- collection_ids?: string[],
101
- metadata_filters?: Record<string, any> // MongoDB-like operators: $eq, $ne, $in, $nin, $exists, $and, $or
102
- })
103
-
104
- // Example: Filter playground conversations
105
- const playgroundConversations = await client.listConversations({
106
- collection_ids: ['cluster-id'],
107
- metadata_filters: {
108
- 'metadata.playground': { $eq: true }
109
- }
77
+ // Single memory
78
+ const memoryId = await client.storeMemory({
79
+ collection_id: collection.id,
80
+ content: 'Your content here',
81
+ metadata: { category: 'example' }
110
82
  });
111
83
 
112
- // Get conversation messages
113
- await client.getConversationMessages(conversationId: string): Promise<MemoryResponse[]>
114
- await client.getConversationMessages(conversationIds: string[]): Promise<Record<string, MemoryResponse[]>>
115
-
116
- // Delete a conversation and all its messages
117
- await client.deleteConversation(conversationId: string)
84
+ // Batch storage
85
+ const memoryIds = await client.storeMemories([
86
+ { collection_id: collection.id, content: 'First memory' },
87
+ { collection_id: collection.id, content: 'Second memory' }
88
+ ]);
118
89
  ```
119
90
 
120
- #### Memories
91
+ ### Retrieve Memories
121
92
 
122
93
  ```typescript
123
- // Store a single memory
124
- await client.storeMemory(memory: Memory | Record<string, any>)
125
-
126
- // Store multiple memories
127
- await client.storeMemories(memories: Memory[])
128
-
129
- // Get a specific memory
130
- await client.getMemory(memoryId: string)
131
-
132
- // List memories from clusters
133
- await client.listMemories(options: {
134
- collection_ids: string | string[],
135
- limit?: number,
136
- offset?: number,
137
- metadata_filters?: Record<string, any> // MongoDB-like operators: $eq, $ne, $in, $nin, $exists, $and, $or
138
- })
139
-
140
- // Example: List memories excluding conversations
94
+ // List memories
141
95
  const memories = await client.listMemories({
142
- collection_ids: ['cluster-id'],
143
- metadata_filters: {
144
- 'metadata.content_type': { $ne: 'conversation' }
145
- }
96
+ collection_ids: [collection.id],
97
+ limit: 10
146
98
  });
147
99
 
148
- // Example: Complex filter with multiple conditions
149
- const playgroundMemories = await client.listMemories({
150
- collection_ids: ['cluster-id'],
100
+ // Filter with metadata
101
+ const memories = await client.listMemories({
102
+ collection_ids: [collection.id],
151
103
  metadata_filters: {
152
- $and: [
153
- { 'metadata.playground': { $eq: true } },
154
- { 'metadata.session_id': { $exists: true } }
155
- ]
104
+ 'metadata.category': { $eq: 'example' }
156
105
  }
157
106
  });
158
107
 
159
- // Delete one or more memories
160
- // Single deletion:
161
- await client.delete('memory-id') // Returns: boolean
162
-
163
- // Batch deletion:
164
- await client.delete(['id1', 'id2', 'id3']) // Returns: detailed results object
165
- ```
166
-
167
- #### Search
168
-
169
- ```typescript
170
- // Search within clusters
171
- await client.search(options: {
172
- query: string,
173
- collection_ids: string | string[],
174
- limit?: number,
175
- retrieval_type?: RetrievalType | string,
176
- filters?: Record<string, any>,
177
- searchSettings?: Record<string, any>
178
- })
179
- ```
180
-
181
- #### Health Check
182
-
183
- ```typescript
184
- // Check API health
185
- await client.healthCheck()
186
- ```
187
-
188
- ### Data Models
189
-
190
- #### Memory (for writing)
191
-
192
- ```typescript
193
- interface Memory {
194
- collection_id: string; // Required: cluster to store in
195
- content: string; // Required: text content
196
- role?: string; // Optional: 'user', 'assistant', or custom (for conversations)
197
- parent_id?: string; // Optional: conversation ID (for conversations)
198
- metadata?: Record<string, any>; // Optional: additional metadata
199
- }
108
+ // Get specific memory
109
+ const memory = await client.getMemory('memory-id');
200
110
  ```
201
111
 
202
- #### MemoryResponse (for reading)
112
+ ### Search
203
113
 
204
114
  ```typescript
205
- interface MemoryResponse {
206
- id: string;
207
- content?: string;
208
- chunks?: string[];
209
- metadata: Record<string, any>;
210
- collection_ids: string[];
211
- created_at?: string;
212
- updated_at?: string;
213
- }
115
+ // Semantic search
116
+ const results = await client.search({
117
+ query: 'your search query',
118
+ collection_ids: [collection.id],
119
+ limit: 10
120
+ });
214
121
  ```
215
122
 
216
- #### SearchResult
123
+ ### Delete
217
124
 
218
125
  ```typescript
219
- interface SearchResult {
220
- id: string;
221
- score: number;
222
- metadata: Record<string, any>;
223
- source?: string;
224
-
225
- // Chunk fields
226
- content?: string;
227
-
228
- // Graph fields
229
- graph_result_type?: GraphSearchResultType;
230
- graph_entity?: GraphEntityResult;
231
- graph_relationship?: GraphRelationshipResult;
232
- graph_community?: GraphCommunityResult;
233
- chunk_ids?: string[];
234
- }
235
- ```
236
-
237
- #### AgentResponse
126
+ // Single deletion
127
+ const deleted = await client.delete('memory-id'); // Returns boolean
238
128
 
239
- ```typescript
240
- interface AgentResponse {
241
- content: string;
242
- agent_id: string;
243
- conversation_id?: string;
244
- metadata: Record<string, any>;
245
- citations: Record<string, any>[];
246
- }
129
+ // Batch deletion
130
+ const result = await client.delete(['id1', 'id2', 'id3']); // Returns detailed results
247
131
  ```
248
132
 
249
- #### RetrievalType
133
+ ## Conversations
250
134
 
251
135
  ```typescript
252
- enum RetrievalType {
253
- BASIC = "basic",
254
- ADVANCED = "advanced",
255
- CUSTOM = "custom"
256
- }
257
- ```
258
-
259
- ### Search Options
136
+ // Store conversation messages
137
+ const conversationId = await client.storeMemory({
138
+ collection_id: collection.id,
139
+ content: 'What is machine learning?',
140
+ role: 'user'
141
+ });
260
142
 
261
- The search method supports advanced configuration:
143
+ await client.storeMemory({
144
+ collection_id: collection.id,
145
+ content: 'Machine learning is a subset of AI...',
146
+ role: 'assistant',
147
+ parent_id: conversationId
148
+ });
262
149
 
263
- ```typescript
264
- const results = await client.search({
265
- query: 'query',
266
- collection_ids: [collectionId],
267
- limit: 10,
268
- retrieval_type: RetrievalType.ADVANCED,
269
- filters: { 'metadata.category': 'science' },
270
- searchSettings: {
271
- graph_settings: {
272
- enabled: true,
273
- bfs_enabled: true,
274
- bfs_max_depth: 2
275
- },
276
- num_sub_queries: 3
277
- }
150
+ // List conversations
151
+ const conversations = await client.listConversations({
152
+ collection_ids: [collection.id]
278
153
  });
279
- ```
280
154
 
281
- ### Error Handling
155
+ // Get messages
156
+ const messages = await client.getConversationMessages(conversationId);
157
+ ```
282
158
 
283
- The SDK provides custom error classes matching the Python SDK:
159
+ ## Error Handling
284
160
 
285
161
  ```typescript
286
- import {
287
- NebulaException,
288
- NebulaClientException,
162
+ import {
289
163
  NebulaAuthenticationException,
290
164
  NebulaRateLimitException,
291
- NebulaValidationException,
292
- NebulaClusterNotFoundException
165
+ NebulaValidationException
293
166
  } from '@nebula-ai/sdk';
294
167
 
295
168
  try {
@@ -299,254 +172,15 @@ try {
299
172
  console.log('Invalid API key');
300
173
  } else if (error instanceof NebulaRateLimitException) {
301
174
  console.log('Rate limit exceeded');
302
- } else if (error instanceof NebulaValidationException) {
303
- console.log('Validation error:', error.details);
304
- } else if (error instanceof NebulaException) {
305
- console.log('API error:', error.statusCode, error.details);
306
175
  }
307
176
  }
308
177
  ```
309
178
 
310
- ## Examples
179
+ ## Documentation
311
180
 
312
- ### Basic Memory Management
313
-
314
- ```typescript
315
- import { NebulaClient } from '@nebula-ai/sdk';
316
-
317
- const client = new NebulaClient({ apiKey: 'your-key' });
318
-
319
- async function manageMemories() {
320
- // Create a cluster
321
- const cluster = await client.createCluster({
322
- name: 'Knowledge Base',
323
- description: 'My personal knowledge repository'
324
- });
325
-
326
- // Store memories using the unified model
327
- const memories = [
328
- {
329
- collection_id: cluster.id,
330
- content: 'JavaScript is a programming language',
331
- metadata: { category: 'programming', difficulty: 'beginner' }
332
- },
333
- {
334
- collection_id: cluster.id,
335
- content: 'TypeScript adds static typing to JavaScript',
336
- metadata: { category: 'programming', difficulty: 'beginner' }
337
- }
338
- ];
339
-
340
- // Store all memories at once
341
- const memoryIds = await client.storeMemories(memories);
342
- console.log('Stored memories:', memoryIds);
343
-
344
- // Search for memories
345
- const results = await client.search({ query: 'JavaScript', collection_ids: [cluster.id] });
346
- console.log('Search results:', results);
347
-
348
- // Delete a single memory
349
- const deleted = await client.delete(memoryIds[0]);
350
- console.log('Deleted single memory:', deleted); // true
351
-
352
- // Delete multiple memories at once
353
- const batchResult = await client.delete([memoryIds[1], memoryIds[2]]);
354
- console.log('Batch deletion results:', batchResult);
355
- // {
356
- // message: "Deleted 2 of 2 documents",
357
- // results: {
358
- // successful: ["id1", "id2"],
359
- // failed: [],
360
- // summary: { total: 2, succeeded: 2, failed: 0 }
361
- // }
362
- // }
363
- }
364
- ```
365
-
366
- ### Conversation Tracking
367
-
368
- ```typescript
369
- import { NebulaClient } from '@nebula-ai/sdk';
370
-
371
- const client = new NebulaClient({ apiKey: 'your-key' });
372
-
373
- async function trackConversation() {
374
- const cluster = await client.createCluster({
375
- name: 'Conversations',
376
- description: 'AI chat history'
377
- });
378
-
379
- // Store conversation turns
380
- const conversationMemories = [
381
- {
382
- collection_id: cluster.id,
383
- content: 'What is machine learning?',
384
- role: 'user',
385
- metadata: { topic: 'AI' }
386
- },
387
- {
388
- collection_id: cluster.id,
389
- content: 'Machine learning is a subset of AI...',
390
- role: 'assistant',
391
- metadata: { topic: 'AI' }
392
- }
393
- ];
394
-
395
- // Store conversation (returns conversation IDs)
396
- const conversationIds = await client.storeMemories(conversationMemories);
397
- console.log('Conversation IDs:', conversationIds);
398
-
399
- // Retrieve conversation messages directly from conversations API
400
- const messages = await client.getConversationMessages(conversationIds[0]);
401
- console.log('Conversation messages:', messages);
402
- }
403
-
404
- ### Managing Conversations
405
-
406
- ```typescript
407
- import { NebulaClient } from '@nebula-ai/sdk';
408
-
409
- const client = new NebulaClient({ apiKey: 'your-key' });
410
-
411
- async function manageConversations() {
412
- // List all conversations
413
- const conversations = await client.listConversations({ limit: 10, offset: 0 });
414
- console.log('All conversations:', conversations);
415
-
416
- // Get messages from a specific conversation
417
- const messages = await client.getConversationMessages('conversation-id');
418
- console.log('Conversation messages:', messages);
419
-
420
- // Get messages from multiple conversations at once
421
- const multipleMessages = await client.getConversationMessages(['conv1', 'conv2']);
422
- console.log('Multiple conversations:', multipleMessages);
423
-
424
- // Delete a conversation
425
- await client.deleteConversation('conversation-id');
426
- console.log('Conversation deleted');
427
- }
428
- ```
429
-
430
- ### Advanced Search with Graph Results
431
-
432
- ```typescript
433
- import { NebulaClient, RetrievalType } from '@nebula-ai/sdk';
434
-
435
- const client = new NebulaClient({ apiKey: 'your-key' });
436
-
437
- async function advancedSearch() {
438
- const cluster = await client.createCluster({
439
- name: 'Knowledge Graph',
440
- description: 'Entity relationships'
441
- });
442
-
443
- // Store knowledge graph data
444
- await client.storeMemory({
445
- collection_id: cluster.id,
446
- content: 'Einstein developed the theory of relativity',
447
- metadata: { entity: 'Einstein', concept: 'relativity', field: 'physics' }
448
- });
449
-
450
- // Search with graph settings
451
- const results = await client.search({
452
- query: 'Einstein relativity',
453
- collection_ids: [cluster.id],
454
- limit: 10,
455
- retrieval_type: RetrievalType.ADVANCED,
456
- searchSettings: {
457
- graph_settings: {
458
- enabled: true,
459
- bfs_enabled: true,
460
- bfs_max_depth: 2
461
- }
462
- }
463
- });
464
-
465
- // Handle both chunk and graph results
466
- results.forEach(result => {
467
- if (result.content) {
468
- console.log('Chunk result:', result.content);
469
- }
470
- if (result.graph_entity) {
471
- console.log('Entity:', result.graph_entity.name);
472
- }
473
- if (result.graph_relationship) {
474
- console.log('Relationship:', result.graph_relationship.subject,
475
- result.graph_relationship.predicate,
476
- result.graph_relationship.object);
477
- }
478
- });
479
- }
480
- ```
481
-
482
- ## Browser vs Node.js
483
-
484
- ### Browser Usage
485
-
486
- ```typescript
487
- import { NebulaClient } from '@nebula-ai/sdk';
488
-
489
- const client = new NebulaClient({
490
- apiKey: 'your-api-key'
491
- // Note: CORS handling is now built into the SDK
492
- });
493
- ```
494
-
495
- ### Node.js Usage
496
-
497
- ```typescript
498
- import { NebulaClient } from '@nebula-ai/sdk';
499
-
500
- const client = new NebulaClient({
501
- apiKey: 'your-api-key'
502
- // No additional configuration needed
503
- });
504
- ```
505
-
506
- ## Development
507
-
508
- ### Building
509
-
510
- ```bash
511
- npm run build
512
- ```
513
-
514
- ### Testing
515
-
516
- ```bash
517
- npm test
518
- ```
519
-
520
- ### Type Checking
521
-
522
- ```bash
523
- npm run type-check
524
- ```
525
-
526
- ## Contributing
527
-
528
- 1. Fork the repository
529
- 2. Create a feature branch
530
- 3. Make your changes
531
- 4. Add tests
532
- 5. Submit a pull request
533
-
534
- ## License
535
-
536
- MIT License - see [LICENSE](LICENSE) file for details.
181
+ - [Full Documentation](https://docs.trynebula.ai)
182
+ - [API Reference](https://docs.trynebula.ai/clients/nodejs)
537
183
 
538
184
  ## Support
539
185
 
540
- - 📧 Email: support@trynebula.ai
541
- - 🐛 Issues: [GitHub Issues](https://github.com/nebula-cloud/nebula-sdk-js/issues)
542
- - 📚 Documentation: [Nebula Docs](https://docs.trynebula.ai)
543
-
544
- ## Changelog
545
-
546
- ### v0.0.19
547
- - Complete rewrite to match Python SDK client.py exactly
548
- - Unified Memory model for text and conversations
549
- - Advanced search with graph results support
550
- - Proper error handling matching Python SDK
551
- - Full TypeScript support with comprehensive interfaces
552
- - Browser and Node.js compatibility
186
+ Email [support@trynebula.ai](mailto:support@trynebula.ai)
package/dist/index.d.mts CHANGED
@@ -9,6 +9,14 @@ interface Chunk {
9
9
  metadata: Record<string, any>;
10
10
  role?: string;
11
11
  }
12
+ /**
13
+ * Structured chunk format returned by backend for conversation messages.
14
+ * Contains message text and role metadata inline.
15
+ */
16
+ interface StructuredChunk {
17
+ text: string;
18
+ role: 'user' | 'assistant' | 'system';
19
+ }
12
20
  interface MemoryResponse {
13
21
  id: string;
14
22
  content?: string;
@@ -193,11 +201,20 @@ declare class NebulaClient {
193
201
  collection_ids?: string[];
194
202
  metadata_filters?: Record<string, any>;
195
203
  }): Promise<any[]>;
196
- /** Get conversation messages directly from the conversations API */
204
+ /**
205
+ * Get conversation messages from the engrams API.
206
+ *
207
+ * This method retrieves conversation engrams and parses their chunks into structured messages.
208
+ * Expects conversation engrams to contain structured chunks with role metadata:
209
+ * `{text: string, role: 'user'|'assistant'|'system'}`.
210
+ * Converts chunks to `MemoryResponse` objects with proper role metadata.
211
+ *
212
+ * @param conversationId - Single conversation ID (returns array of messages)
213
+ * @param conversationIds - Multiple conversation IDs (returns map of conversation_id -> messages)
214
+ * @returns Messages for the requested conversation(s)
215
+ */
197
216
  getConversationMessages(conversationId: string): Promise<MemoryResponse[]>;
198
217
  getConversationMessages(conversationIds: string[]): Promise<Record<string, MemoryResponse[]>>;
199
- /** Helper method to transform conversation messages to MemoryResponse format */
200
- private _transformConversationMessages;
201
218
  /** Update a collection */
202
219
  updateCollection(options: {
203
220
  collectionId: string;
@@ -440,4 +457,4 @@ declare class NebulaClient {
440
457
  private _formDataFromObject;
441
458
  }
442
459
 
443
- export { type AgentResponse, type Chunk, type Collection, type GraphCommunityResult, type GraphEntityResult, type GraphRelationshipResult, GraphSearchResultType, type Memory, type MemoryResponse, NebulaAuthenticationException, NebulaClient, type NebulaClientConfig, NebulaClientException, NebulaCollectionNotFoundException, NebulaException, NebulaNotFoundException, NebulaRateLimitException, NebulaValidationException, type SearchOptions, type SearchResult };
460
+ export { type AgentResponse, type Chunk, type Collection, type GraphCommunityResult, type GraphEntityResult, type GraphRelationshipResult, GraphSearchResultType, type Memory, type MemoryResponse, NebulaAuthenticationException, NebulaClient, type NebulaClientConfig, NebulaClientException, NebulaCollectionNotFoundException, NebulaException, NebulaNotFoundException, NebulaRateLimitException, NebulaValidationException, type SearchOptions, type SearchResult, type StructuredChunk };