@memorylayerai/sdk 0.1.1 β†’ 0.2.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/README.md CHANGED
@@ -1,6 +1,18 @@
1
- # @memorylayerai/sdk
1
+ # MemoryLayer Node.js SDK
2
2
 
3
- Official Node.js/TypeScript SDK for MemoryLayer - Add memory capabilities to your AI applications.
3
+ Official Node.js/TypeScript SDK for [MemoryLayer](https://memorylayer.com) - The intelligent memory layer for AI applications.
4
+
5
+ [![npm version](https://badge.fury.io/js/@memorylayerai%2Fsdk.svg)](https://www.npmjs.com/package/@memorylayerai/sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Features
9
+
10
+ - 🧠 **Memory Management**: Store, retrieve, and manage AI memories
11
+ - πŸ” **Hybrid Search**: Vector + keyword + graph-based retrieval
12
+ - πŸ•ΈοΈ **Memory Graph**: Visualize and traverse memory relationships
13
+ - 🎯 **Smart Retrieval**: LLM reranking and query rewriting
14
+ - πŸ“Š **Observability**: Track performance and quality metrics
15
+ - πŸ” **Type-Safe**: Full TypeScript support with auto-completion
4
16
 
5
17
  ## Installation
6
18
 
@@ -8,35 +20,492 @@ Official Node.js/TypeScript SDK for MemoryLayer - Add memory capabilities to you
8
20
  npm install @memorylayerai/sdk
9
21
  ```
10
22
 
23
+ or with yarn:
24
+
25
+ ```bash
26
+ yarn add @memorylayerai/sdk
27
+ ```
28
+
11
29
  ## Quick Start
12
30
 
31
+ ### 1. Get Your API Key
32
+
33
+ Sign up at [memorylayer.com](https://memorylayer.com) and create an API key from your project settings.
34
+
35
+ ### 2. Initialize the Client
36
+
37
+ ```typescript
38
+ import { MemoryLayer } from '@memorylayerai/sdk';
39
+
40
+ const client = new MemoryLayer({
41
+ apiKey: 'ml_key_...',
42
+ // Optional: specify custom base URL
43
+ // baseUrl: 'https://api.memorylayer.com'
44
+ });
45
+ ```
46
+
47
+ ### 3. Create Memories
48
+
49
+ ```typescript
50
+ // Create a single memory
51
+ const memory = await client.memories.create({
52
+ projectId: 'your-project-id',
53
+ content: 'The user prefers dark mode in their applications',
54
+ type: 'preference',
55
+ tags: {
56
+ category: 'ui',
57
+ importance: 'high'
58
+ }
59
+ });
60
+
61
+ console.log('Memory created:', memory.id);
62
+ ```
63
+
64
+ ### 4. Search Memories
65
+
66
+ ```typescript
67
+ // Hybrid search (vector + keyword + graph)
68
+ const results = await client.search.hybrid({
69
+ projectId: 'your-project-id',
70
+ query: 'What are the user UI preferences?',
71
+ limit: 10,
72
+ // Optional: enable advanced features
73
+ useReranking: true, // LLM-based reranking
74
+ useQueryRewriting: true, // Query expansion
75
+ useGraphTraversal: true // Follow memory relationships
76
+ });
77
+
78
+ results.forEach(result => {
79
+ console.log(`Score: ${result.score}`);
80
+ console.log(`Content: ${result.content}`);
81
+ console.log(`Type: ${result.type}`);
82
+ });
83
+ ```
84
+
85
+ ## Core Features
86
+
87
+ ### Memory Management
88
+
89
+ #### Create Memory
90
+
91
+ ```typescript
92
+ const memory = await client.memories.create({
93
+ projectId: 'project-id',
94
+ content: 'User completed onboarding on 2024-01-15',
95
+ type: 'fact',
96
+ tags: {
97
+ event: 'onboarding',
98
+ date: '2024-01-15'
99
+ },
100
+ metadata: {
101
+ source: 'mobile-app',
102
+ version: '2.1.0'
103
+ }
104
+ });
105
+ ```
106
+
107
+ #### List Memories
108
+
109
+ ```typescript
110
+ const memories = await client.memories.list({
111
+ projectId: 'project-id',
112
+ types: ['fact', 'preference'],
113
+ status: ['active'],
114
+ page: 1,
115
+ pageSize: 50
116
+ });
117
+
118
+ console.log(`Total: ${memories.total}`);
119
+ memories.items.forEach(memory => {
120
+ console.log(memory.content);
121
+ });
122
+ ```
123
+
124
+ #### Get Memory
125
+
13
126
  ```typescript
14
- import { MemoryLayerClient } from '@memorylayerai/sdk';
127
+ const memory = await client.memories.get('memory-id');
128
+ console.log(memory.content);
129
+ ```
15
130
 
16
- const client = new MemoryLayerClient({
17
- apiKey: process.env.MEMORYLAYER_API_KEY!,
131
+ #### Update Memory
132
+
133
+ ```typescript
134
+ const updated = await client.memories.update('memory-id', {
135
+ content: 'Updated content',
136
+ tags: {
137
+ updated: 'true'
138
+ }
18
139
  });
140
+ ```
141
+
142
+ #### Delete Memory
143
+
144
+ ```typescript
145
+ await client.memories.delete('memory-id');
146
+ ```
147
+
148
+ ### Search & Retrieval
19
149
 
20
- // Add a memory
21
- const memory = await client.memories.add({
22
- content: 'User prefers dark mode',
23
- metadata: { category: 'preferences' },
24
- projectId: 'proj_abc123',
150
+ #### Hybrid Search
151
+
152
+ Combines vector search, keyword search, and graph traversal:
153
+
154
+ ```typescript
155
+ const results = await client.search.hybrid({
156
+ projectId: 'project-id',
157
+ query: 'What does the user like?',
158
+ limit: 10,
159
+
160
+ // Scoring weights (optional)
161
+ vectorWeight: 0.5,
162
+ keywordWeight: 0.3,
163
+ recencyWeight: 0.2,
164
+
165
+ // Advanced features
166
+ useReranking: true, // Use LLM to rerank results
167
+ useQueryRewriting: true, // Expand and clarify query
168
+ useGraphTraversal: true, // Follow memory relationships
169
+ graphDepth: 2 // How many hops to traverse
25
170
  });
171
+ ```
172
+
173
+ #### Vector Search Only
26
174
 
27
- // Search memories
28
- const results = await client.search.search({
175
+ ```typescript
176
+ const results = await client.search.vector({
177
+ projectId: 'project-id',
29
178
  query: 'user preferences',
30
- projectId: 'proj_abc123',
179
+ limit: 5,
180
+ threshold: 0.7 // Minimum similarity score
31
181
  });
182
+ ```
183
+
184
+ #### Keyword Search Only
32
185
 
33
- console.log(results);
186
+ ```typescript
187
+ const results = await client.search.keyword({
188
+ projectId: 'project-id',
189
+ query: 'dark mode',
190
+ limit: 5
191
+ });
34
192
  ```
35
193
 
36
- ## Documentation
194
+ ### Memory Graph
37
195
 
38
- For full documentation, visit [https://docs.memorylayer.com](https://docs.memorylayer.com)
196
+ #### Get Graph Data
197
+
198
+ ```typescript
199
+ const graph = await client.graph.get({
200
+ projectId: 'project-id',
201
+ // Optional filters
202
+ memoryTypes: ['fact', 'preference'],
203
+ searchQuery: 'user preferences',
204
+ dateRange: {
205
+ start: '2024-01-01',
206
+ end: '2024-12-31'
207
+ }
208
+ });
209
+
210
+ console.log(`Nodes: ${graph.nodes.length}`);
211
+ console.log(`Edges: ${graph.edges.length}`);
212
+
213
+ // Nodes
214
+ graph.nodes.forEach(node => {
215
+ console.log(`${node.id}: ${node.content}`);
216
+ });
217
+
218
+ // Edges (relationships)
219
+ graph.edges.forEach(edge => {
220
+ console.log(`${edge.source} -> ${edge.target} (${edge.type})`);
221
+ });
222
+ ```
223
+
224
+ #### Create Edge
225
+
226
+ ```typescript
227
+ const edge = await client.graph.createEdge({
228
+ projectId: 'project-id',
229
+ sourceMemoryId: 'memory-1',
230
+ targetMemoryId: 'memory-2',
231
+ relationshipType: 'derives', // or 'similarity', 'temporal', etc.
232
+ metadata: {
233
+ confidence: 0.95,
234
+ reason: 'User explicitly linked these'
235
+ }
236
+ });
237
+ ```
238
+
239
+ #### Traverse Graph
240
+
241
+ ```typescript
242
+ const related = await client.graph.traverse({
243
+ projectId: 'project-id',
244
+ startMemoryIds: ['memory-1'],
245
+ depth: 2, // How many hops
246
+ relationshipTypes: ['similarity', 'derives']
247
+ });
248
+
249
+ console.log(`Found ${related.length} related memories`);
250
+ ```
251
+
252
+ ### Ingestion
253
+
254
+ #### Ingest Document
255
+
256
+ ```typescript
257
+ const job = await client.ingestion.ingest({
258
+ projectId: 'project-id',
259
+ content: 'Long document content...',
260
+ metadata: {
261
+ title: 'Product Documentation',
262
+ source: 'docs.example.com'
263
+ },
264
+ // Chunking strategy
265
+ chunkingStrategy: 'semantic', // or 'fixed-size', 'sentence', 'paragraph'
266
+ chunkSize: 512,
267
+ chunkOverlap: 50
268
+ });
269
+
270
+ console.log(`Job ID: ${job.id}`);
271
+ console.log(`Status: ${job.status}`);
272
+ ```
273
+
274
+ #### Check Job Status
275
+
276
+ ```typescript
277
+ const job = await client.ingestion.getJob('job-id');
278
+ console.log(`Status: ${job.status}`);
279
+ console.log(`Progress: ${job.progress}%`);
280
+ console.log(`Memories created: ${job.memoriesCreated}`);
281
+ ```
282
+
283
+ ## Advanced Features
284
+
285
+ ### LLM Reranking
286
+
287
+ Improve search relevance using LLM-based reranking:
288
+
289
+ ```typescript
290
+ const results = await client.search.hybrid({
291
+ projectId: 'project-id',
292
+ query: 'complex user question',
293
+ limit: 20,
294
+ useReranking: true,
295
+ rerankingModel: 'gpt-4', // or 'claude-3'
296
+ rerankingTopK: 10 // Return top 10 after reranking
297
+ });
298
+ ```
299
+
300
+ ### Query Rewriting
301
+
302
+ Expand and clarify queries for better results:
303
+
304
+ ```typescript
305
+ const results = await client.search.hybrid({
306
+ projectId: 'project-id',
307
+ query: 'ML preferences', // Will expand to "machine learning preferences"
308
+ useQueryRewriting: true,
309
+ queryRewritingStrategy: 'expansion' // or 'clarification', 'multi-query'
310
+ });
311
+ ```
312
+
313
+ ### Graph Traversal
314
+
315
+ Follow memory relationships for contextual retrieval:
316
+
317
+ ```typescript
318
+ const results = await client.search.hybrid({
319
+ projectId: 'project-id',
320
+ query: 'user settings',
321
+ useGraphTraversal: true,
322
+ graphDepth: 2, // Follow relationships 2 hops deep
323
+ graphRelationshipTypes: ['similarity', 'derives']
324
+ });
325
+ ```
326
+
327
+ ## TypeScript Support
328
+
329
+ The SDK is written in TypeScript and provides full type definitions:
330
+
331
+ ```typescript
332
+ import {
333
+ MemoryLayer,
334
+ Memory,
335
+ SearchResult,
336
+ GraphData,
337
+ IngestionJob
338
+ } from '@memorylayerai/sdk';
339
+
340
+ // All methods are fully typed
341
+ const client = new MemoryLayer({ apiKey: 'ml_key_...' });
342
+
343
+ // TypeScript will auto-complete and type-check
344
+ const memory: Memory = await client.memories.create({
345
+ projectId: 'project-id',
346
+ content: 'typed content',
347
+ type: 'fact' // TypeScript knows valid types
348
+ });
349
+ ```
350
+
351
+ ## Error Handling
352
+
353
+ ```typescript
354
+ import { MemoryLayerError } from '@memorylayerai/sdk';
355
+
356
+ try {
357
+ const memory = await client.memories.create({
358
+ projectId: 'project-id',
359
+ content: 'test'
360
+ });
361
+ } catch (error) {
362
+ if (error instanceof MemoryLayerError) {
363
+ console.error('API Error:', error.message);
364
+ console.error('Status:', error.statusCode);
365
+ console.error('Request ID:', error.requestId);
366
+ } else {
367
+ console.error('Unexpected error:', error);
368
+ }
369
+ }
370
+ ```
371
+
372
+ ## Configuration
373
+
374
+ ### Custom Base URL
375
+
376
+ ```typescript
377
+ const client = new MemoryLayer({
378
+ apiKey: 'ml_key_...',
379
+ baseUrl: 'https://your-custom-domain.com'
380
+ });
381
+ ```
382
+
383
+ ### Timeout
384
+
385
+ ```typescript
386
+ const client = new MemoryLayer({
387
+ apiKey: 'ml_key_...',
388
+ timeout: 30000 // 30 seconds
389
+ });
390
+ ```
391
+
392
+ ### Retry Configuration
393
+
394
+ ```typescript
395
+ const client = new MemoryLayer({
396
+ apiKey: 'ml_key_...',
397
+ maxRetries: 3,
398
+ retryDelay: 1000 // 1 second
399
+ });
400
+ ```
401
+
402
+ ## Examples
403
+
404
+ ### Chatbot with Memory
405
+
406
+ ```typescript
407
+ import { MemoryLayer } from '@memorylayerai/sdk';
408
+
409
+ const client = new MemoryLayer({ apiKey: process.env.MEMORYLAYER_API_KEY });
410
+ const projectId = 'your-project-id';
411
+
412
+ async function chatWithMemory(userMessage: string, userId: string) {
413
+ // 1. Search for relevant memories
414
+ const memories = await client.search.hybrid({
415
+ projectId,
416
+ query: userMessage,
417
+ limit: 5,
418
+ useReranking: true,
419
+ useGraphTraversal: true
420
+ });
421
+
422
+ // 2. Build context from memories
423
+ const context = memories
424
+ .map(m => m.content)
425
+ .join('\n\n');
426
+
427
+ // 3. Send to LLM with context
428
+ const response = await callYourLLM({
429
+ system: `You are a helpful assistant. Use this context about the user:\n\n${context}`,
430
+ user: userMessage
431
+ });
432
+
433
+ // 4. Store new memory from conversation
434
+ await client.memories.create({
435
+ projectId,
436
+ content: `User said: "${userMessage}". Assistant responded: "${response}"`,
437
+ type: 'fact',
438
+ tags: { userId, timestamp: new Date().toISOString() }
439
+ });
440
+
441
+ return response;
442
+ }
443
+ ```
444
+
445
+ ### Document Q&A
446
+
447
+ ```typescript
448
+ async function ingestAndQuery(documentContent: string, question: string) {
449
+ // 1. Ingest document
450
+ const job = await client.ingestion.ingest({
451
+ projectId: 'your-project-id',
452
+ content: documentContent,
453
+ chunkingStrategy: 'semantic',
454
+ chunkSize: 512
455
+ });
456
+
457
+ // 2. Wait for ingestion to complete
458
+ let status = await client.ingestion.getJob(job.id);
459
+ while (status.status === 'processing') {
460
+ await new Promise(resolve => setTimeout(resolve, 1000));
461
+ status = await client.ingestion.getJob(job.id);
462
+ }
463
+
464
+ // 3. Query the document
465
+ const results = await client.search.hybrid({
466
+ projectId: 'your-project-id',
467
+ query: question,
468
+ limit: 3,
469
+ useReranking: true
470
+ });
471
+
472
+ return results.map(r => r.content).join('\n\n');
473
+ }
474
+ ```
475
+
476
+ ## API Reference
477
+
478
+ Full API documentation available at [docs.memorylayer.com](https://docs.memorylayer.com)
479
+
480
+ ## Support
481
+
482
+ - πŸ“§ Email: support@memorylayer.com
483
+ - πŸ’¬ Discord: [discord.gg/memorylayer](https://discord.gg/memorylayer)
484
+ - πŸ“– Docs: [docs.memorylayer.com](https://docs.memorylayer.com)
485
+ - πŸ› Issues: [github.com/memorylayer/sdk/issues](https://github.com/memorylayer/sdk/issues)
39
486
 
40
487
  ## License
41
488
 
42
- MIT
489
+ MIT License - see [LICENSE](LICENSE) file for details.
490
+
491
+ ## Changelog
492
+
493
+ ### v0.2.0 (2024-01-20)
494
+
495
+ - ✨ Added Memory Graph API support
496
+ - ✨ Added Hybrid Search with LLM reranking
497
+ - ✨ Added Query Rewriting capabilities
498
+ - ✨ Added Graph Traversal for contextual retrieval
499
+ - πŸ› Fixed type definitions for better TypeScript support
500
+ - πŸ“š Comprehensive documentation and examples
501
+
502
+ ### v0.1.1 (2024-01-10)
503
+
504
+ - πŸ› Bug fixes and stability improvements
505
+
506
+ ### v0.1.0 (2024-01-01)
507
+
508
+ - πŸŽ‰ Initial release
509
+ - ✨ Basic memory CRUD operations
510
+ - ✨ Vector search
511
+ - ✨ Ingestion API
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memorylayerai/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "description": "Official Node.js/TypeScript SDK for MemoryLayer",
6
6
  "main": "dist/index.js",
package/src/client.ts CHANGED
@@ -35,6 +35,7 @@ export class MemoryLayerClient {
35
35
  private _search?: any;
36
36
  private _ingest?: any;
37
37
  private _router?: any;
38
+ private _graph?: any;
38
39
 
39
40
  constructor(config: ClientConfig = {}) {
40
41
  // Get API key from config or environment variable
@@ -113,4 +114,15 @@ export class MemoryLayerClient {
113
114
  }
114
115
  return this._router;
115
116
  }
117
+
118
+ /**
119
+ * Access graph visualization operations
120
+ */
121
+ get graph() {
122
+ if (!this._graph) {
123
+ const { GraphResource } = require('./resources/graph.js');
124
+ this._graph = new GraphResource(this.httpClient);
125
+ }
126
+ return this._graph;
127
+ }
116
128
  }
package/src/index.ts CHANGED
@@ -41,6 +41,20 @@ export type {
41
41
  StreamChunk,
42
42
  StreamChoice,
43
43
  StreamDelta,
44
+ // Graph types
45
+ GraphData,
46
+ GraphNode,
47
+ GraphEdge,
48
+ GraphMetadata,
49
+ PaginationInfo,
50
+ NodeDetails,
51
+ GetGraphRequest,
52
+ GetNodeDetailsRequest,
53
+ GetNodeEdgesRequest,
54
+ GetNodeEdgesResponse,
55
+ MemoryStatus,
56
+ NodeType,
57
+ EdgeType,
44
58
  } from './types.js';
45
59
 
46
60
  // Resources (exported for advanced use cases)
@@ -48,3 +62,4 @@ export { MemoriesResource } from './resources/memories.js';
48
62
  export { SearchResource } from './resources/search.js';
49
63
  export { IngestResource } from './resources/ingest.js';
50
64
  export { RouterResource } from './resources/router.js';
65
+ export { GraphResource } from './resources/graph.js';