@cilow/sdk 0.2.1 → 0.3.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.
Files changed (84) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +109 -492
  3. package/dist/abstain.d.ts +43 -0
  4. package/dist/abstain.d.ts.map +1 -0
  5. package/dist/abstain.js +42 -0
  6. package/dist/abstain.js.map +1 -0
  7. package/dist/adapters/anthropic.d.ts +57 -0
  8. package/dist/adapters/anthropic.d.ts.map +1 -0
  9. package/dist/adapters/anthropic.js +57 -0
  10. package/dist/adapters/anthropic.js.map +1 -0
  11. package/dist/adapters/index.d.ts +16 -0
  12. package/dist/adapters/index.d.ts.map +1 -0
  13. package/dist/adapters/index.js +16 -0
  14. package/dist/adapters/index.js.map +1 -0
  15. package/dist/adapters/langchain.d.ts +62 -0
  16. package/dist/adapters/langchain.d.ts.map +1 -0
  17. package/dist/adapters/langchain.js +68 -0
  18. package/dist/adapters/langchain.js.map +1 -0
  19. package/dist/adapters/memory.d.ts +105 -0
  20. package/dist/adapters/memory.d.ts.map +1 -0
  21. package/dist/adapters/memory.js +105 -0
  22. package/dist/adapters/memory.js.map +1 -0
  23. package/dist/adapters/openai.d.ts +56 -0
  24. package/dist/adapters/openai.d.ts.map +1 -0
  25. package/dist/adapters/openai.js +64 -0
  26. package/dist/adapters/openai.js.map +1 -0
  27. package/dist/adapters/remaining.d.ts +52 -0
  28. package/dist/adapters/remaining.d.ts.map +1 -0
  29. package/dist/adapters/remaining.js +67 -0
  30. package/dist/adapters/remaining.js.map +1 -0
  31. package/dist/client.d.ts +512 -173
  32. package/dist/client.d.ts.map +1 -0
  33. package/dist/client.js +648 -504
  34. package/dist/client.js.map +1 -1
  35. package/dist/errors.d.ts +25 -0
  36. package/dist/errors.d.ts.map +1 -0
  37. package/dist/errors.js +28 -0
  38. package/dist/errors.js.map +1 -0
  39. package/dist/hash.d.ts +13 -0
  40. package/dist/hash.d.ts.map +1 -0
  41. package/dist/hash.js +92 -0
  42. package/dist/hash.js.map +1 -0
  43. package/dist/index.d.ts +18 -109
  44. package/dist/index.d.ts.map +1 -0
  45. package/dist/index.js +16 -876
  46. package/dist/index.js.map +1 -1
  47. package/dist/types.d.ts +809 -486
  48. package/dist/types.d.ts.map +1 -0
  49. package/dist/types.js +18 -17
  50. package/dist/types.js.map +1 -1
  51. package/package.json +30 -103
  52. package/dist/client.d.mts +0 -224
  53. package/dist/client.mjs +0 -505
  54. package/dist/client.mjs.map +0 -1
  55. package/dist/index.d.mts +0 -111
  56. package/dist/index.mjs +0 -863
  57. package/dist/index.mjs.map +0 -1
  58. package/dist/providers/langchain.js +0 -821
  59. package/dist/providers/langchain.js.map +0 -1
  60. package/dist/providers/langchain.mjs +0 -816
  61. package/dist/providers/langchain.mjs.map +0 -1
  62. package/dist/providers/openai.js +0 -737
  63. package/dist/providers/openai.js.map +0 -1
  64. package/dist/providers/openai.mjs +0 -732
  65. package/dist/providers/openai.mjs.map +0 -1
  66. package/dist/providers/vercel.js +0 -866
  67. package/dist/providers/vercel.js.map +0 -1
  68. package/dist/providers/vercel.mjs +0 -860
  69. package/dist/providers/vercel.mjs.map +0 -1
  70. package/dist/react/hooks.d.mts +0 -327
  71. package/dist/react/hooks.d.ts +0 -327
  72. package/dist/react/hooks.js +0 -1183
  73. package/dist/react/hooks.js.map +0 -1
  74. package/dist/react/hooks.mjs +0 -1172
  75. package/dist/react/hooks.mjs.map +0 -1
  76. package/dist/types.d.mts +0 -494
  77. package/dist/types.mjs +0 -14
  78. package/dist/types.mjs.map +0 -1
  79. package/dist/websocket.d.mts +0 -160
  80. package/dist/websocket.d.ts +0 -160
  81. package/dist/websocket.js +0 -342
  82. package/dist/websocket.js.map +0 -1
  83. package/dist/websocket.mjs +0 -339
  84. package/dist/websocket.mjs.map +0 -1
@@ -1,821 +0,0 @@
1
- 'use strict';
2
-
3
- // src/client.ts
4
- async function fetchWithRetry(url, options, config) {
5
- const controller = new AbortController();
6
- const timeoutId = setTimeout(() => controller.abort(), config.timeout);
7
- let lastError = null;
8
- for (let attempt = 0; attempt <= config.retries; attempt++) {
9
- try {
10
- const response = await fetch(url, {
11
- ...options,
12
- signal: controller.signal
13
- });
14
- clearTimeout(timeoutId);
15
- if (!response.ok) {
16
- const errorBody = await response.text();
17
- let apiError;
18
- try {
19
- apiError = JSON.parse(errorBody);
20
- } catch {
21
- apiError = {
22
- code: `HTTP_${response.status}`,
23
- message: errorBody || response.statusText
24
- };
25
- }
26
- throw new CilowApiError(apiError.message, apiError.code, response.status, apiError.details);
27
- }
28
- return response;
29
- } catch (error) {
30
- lastError = error;
31
- if (error instanceof CilowApiError) {
32
- throw error;
33
- }
34
- if (config.debug) {
35
- console.warn(`Cilow API request failed (attempt ${attempt + 1}/${config.retries + 1}):`, error);
36
- }
37
- if (attempt < config.retries) {
38
- await new Promise((resolve) => setTimeout(resolve, Math.pow(2, attempt) * 100));
39
- }
40
- }
41
- }
42
- clearTimeout(timeoutId);
43
- throw lastError || new Error("Request failed");
44
- }
45
- var CilowApiError = class extends Error {
46
- constructor(message, code, statusCode, details) {
47
- super(message);
48
- this.code = code;
49
- this.statusCode = statusCode;
50
- this.details = details;
51
- this.name = "CilowApiError";
52
- }
53
- };
54
- var CilowClient = class {
55
- constructor(config) {
56
- this.baseUrl = config.apiUrl.replace(/\/$/, "");
57
- this.apiKey = config.apiKey;
58
- this.timeout = config.timeout ?? 3e4;
59
- this.retries = config.retries ?? 3;
60
- this.debug = config.debug ?? false;
61
- const authHeaders = this.apiKey.startsWith("cilow_") ? { "X-API-Key": this.apiKey } : { Authorization: `Bearer ${this.apiKey}` };
62
- this.headers = {
63
- "Content-Type": "application/json",
64
- ...authHeaders,
65
- ...config.headers
66
- };
67
- }
68
- /**
69
- * Make an API request
70
- */
71
- async request(method, path, body, queryParams) {
72
- let url = `${this.baseUrl}${path}`;
73
- if (queryParams) {
74
- const params = new URLSearchParams();
75
- for (const [key, value] of Object.entries(queryParams)) {
76
- if (value !== void 0) {
77
- params.append(key, String(value));
78
- }
79
- }
80
- const queryString = params.toString();
81
- if (queryString) {
82
- url += `?${queryString}`;
83
- }
84
- }
85
- if (this.debug) {
86
- console.log(`Cilow API: ${method} ${url}`);
87
- }
88
- const response = await fetchWithRetry(
89
- url,
90
- {
91
- method,
92
- headers: this.headers,
93
- body: body ? JSON.stringify(body) : void 0
94
- },
95
- { timeout: this.timeout, retries: this.retries, debug: this.debug }
96
- );
97
- const text = await response.text();
98
- if (!text) {
99
- return void 0;
100
- }
101
- return JSON.parse(text);
102
- }
103
- // ===========================================================================
104
- // Simple API (remember, recall, forget)
105
- // ===========================================================================
106
- /**
107
- * Store a memory (simple API)
108
- *
109
- * @param content - The content to remember
110
- * @param options - Optional configuration
111
- * @returns The created memory ID
112
- *
113
- * @example
114
- * ```typescript
115
- * await cilow.remember("User prefers dark mode", {
116
- * tags: ["preference"],
117
- * userId: "user-123"
118
- * });
119
- * ```
120
- */
121
- async remember(content, options) {
122
- const response = await this.request("POST", "/api/v1/memory/add", {
123
- content,
124
- tags: options?.tags ?? [],
125
- user_id: options?.userId,
126
- session_id: options?.sessionId,
127
- metadata: options?.metadata,
128
- type: options?.tier
129
- });
130
- return response.memory_id || response.id || "";
131
- }
132
- /**
133
- * Search memories (simple API)
134
- *
135
- * @param query - Search query text
136
- * @param options - Search options
137
- * @returns Array of search results
138
- *
139
- * @example
140
- * ```typescript
141
- * const memories = await cilow.recall("user preferences", {
142
- * limit: 10,
143
- * tags: ["preference"]
144
- * });
145
- * ```
146
- */
147
- async recall(query, options) {
148
- const response = await this.request("POST", "/api/v1/memory/search", {
149
- query,
150
- limit: options?.limit ?? 10,
151
- min_score: options?.minRelevance ?? 0.3,
152
- tags: options?.tags,
153
- user_id: options?.userId
154
- });
155
- return (response.results ?? []).map((r) => ({
156
- memory: {
157
- id: r.memory_id,
158
- content: r.content,
159
- tags: r.tags ?? [],
160
- tier: "hot",
161
- status: "active",
162
- accessCount: 0,
163
- tokenCount: Math.ceil(r.content.length / 4),
164
- metadata: {},
165
- createdAt: r.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
166
- updatedAt: r.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
167
- lastAccessedAt: (/* @__PURE__ */ new Date()).toISOString()
168
- },
169
- score: r.similarity,
170
- highlights: []
171
- }));
172
- }
173
- /**
174
- * Delete memories (simple API)
175
- *
176
- * @param filter - Filter criteria for deletion
177
- * @returns Number of memories deleted
178
- *
179
- * @example
180
- * ```typescript
181
- * // Delete by tags
182
- * await cilow.forget({ tags: ["temporary"] });
183
- *
184
- * // Delete by user
185
- * await cilow.forget({ userId: "user-123" });
186
- *
187
- * // Delete specific memory
188
- * await cilow.forget({ memoryId: "mem-abc" });
189
- * ```
190
- */
191
- async forget(filter) {
192
- if (filter.memoryId) {
193
- await this.deleteMemory(filter.memoryId);
194
- return 1;
195
- }
196
- const response = await this.request("DELETE", "/api/v1/memories/bulk", {
197
- filter_tags: filter.tags,
198
- user_id: filter.userId,
199
- session_id: filter.sessionId,
200
- older_than: filter.olderThan
201
- });
202
- return response.deleted ?? 0;
203
- }
204
- // ===========================================================================
205
- // Memory CRUD Operations
206
- // ===========================================================================
207
- /**
208
- * Create a new memory
209
- */
210
- async createMemory(content, options) {
211
- return this.request("POST", "/api/v1/memories", {
212
- content,
213
- tags: options?.tags ?? [],
214
- user_id: options?.userId,
215
- session_id: options?.sessionId,
216
- metadata: options?.metadata,
217
- tier: options?.tier
218
- });
219
- }
220
- /**
221
- * Get a memory by ID
222
- */
223
- async getMemory(memoryId) {
224
- return this.request("GET", `/api/v1/memories/${memoryId}`);
225
- }
226
- /**
227
- * Update a memory
228
- */
229
- async updateMemory(memoryId, updates) {
230
- return this.request("PATCH", `/api/v1/memories/${memoryId}`, {
231
- content: updates.content,
232
- tags: updates.tags,
233
- metadata: updates.metadata,
234
- tier: updates.tier
235
- });
236
- }
237
- /**
238
- * Delete a memory
239
- */
240
- async deleteMemory(memoryId) {
241
- await this.request("DELETE", `/api/v1/memories/${memoryId}`);
242
- }
243
- /**
244
- * List memories with pagination
245
- */
246
- async listMemories(options) {
247
- const response = await this.request(
248
- "GET",
249
- "/api/v1/memory/list",
250
- void 0,
251
- {
252
- limit: options?.limit ?? 20,
253
- offset: options?.offset ?? 0,
254
- user_id: options?.userId,
255
- session_id: options?.sessionId,
256
- tags: options?.tags?.join(","),
257
- type: options?.tier
258
- }
259
- );
260
- const items = (response.memories ?? []).map((m) => ({
261
- id: m.memory_id || m.id || "",
262
- content: m.content,
263
- tags: m.tags ?? [],
264
- createdAt: m.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
265
- tier: m.type || "hot"
266
- }));
267
- const limit = options?.limit ?? 20;
268
- const offset = options?.offset ?? 0;
269
- const total = response.total ?? items.length;
270
- return {
271
- items,
272
- total,
273
- limit,
274
- offset,
275
- hasMore: offset + items.length < total
276
- };
277
- }
278
- // ===========================================================================
279
- // Search Operations
280
- // ===========================================================================
281
- /**
282
- * Search memories with full options
283
- */
284
- async searchMemories(query) {
285
- const response = await this.request("POST", "/api/v1/memories/search", {
286
- text: query.text,
287
- limit: query.limit ?? 10,
288
- min_relevance: query.minRelevance ?? 0.3,
289
- filter_tags: query.tags,
290
- user_id: query.userId,
291
- session_id: query.sessionId,
292
- tier: query.tier,
293
- created_after: query.createdAfter,
294
- created_before: query.createdBefore,
295
- include_archived: query.includeArchived,
296
- mode: query.mode ?? "hybrid"
297
- });
298
- return response.results ?? [];
299
- }
300
- /**
301
- * Advanced search with reranking and boosts
302
- */
303
- async advancedSearch(query) {
304
- const response = await this.request("POST", "/api/v1/memories/search/advanced", {
305
- text: query.text,
306
- limit: query.limit ?? 10,
307
- min_relevance: query.minRelevance ?? 0.3,
308
- filter_tags: query.tags,
309
- required_tags: query.requiredTags,
310
- excluded_tags: query.excludedTags,
311
- user_id: query.userId,
312
- session_id: query.sessionId,
313
- recency_boost: query.recencyBoost,
314
- frequency_boost: query.frequencyBoost,
315
- metadata_filters: query.metadataFilters,
316
- reranker: query.reranker
317
- });
318
- return response.results ?? [];
319
- }
320
- /**
321
- * Get context for AI applications
322
- */
323
- async getContext(query, options) {
324
- const maxTokens = options?.maxTokens ?? 4e3;
325
- const tokensPerChar = 0.25;
326
- const results = await this.searchMemories({
327
- text: query,
328
- limit: 30,
329
- minRelevance: 0.3,
330
- userId: options?.userId,
331
- tags: options?.tags
332
- });
333
- let context = "";
334
- let estimatedTokens = 0;
335
- const memoryIds = [];
336
- const scores = [];
337
- for (const result of results) {
338
- const memoryText = `[Relevance: ${(result.score * 100).toFixed(0)}%]
339
- ${result.memory.content}
340
-
341
- `;
342
- const memoryTokens = Math.ceil(memoryText.length * tokensPerChar);
343
- if (estimatedTokens + memoryTokens > maxTokens) break;
344
- context += memoryText;
345
- estimatedTokens += memoryTokens;
346
- memoryIds.push(result.memory.id);
347
- scores.push(result.score);
348
- }
349
- return {
350
- context: context.trim(),
351
- memoriesUsed: memoryIds.length,
352
- estimatedTokens,
353
- memoryIds,
354
- scores
355
- };
356
- }
357
- // ===========================================================================
358
- // Conversation Operations
359
- // ===========================================================================
360
- /**
361
- * Store a conversation turn
362
- */
363
- async storeConversation(turn) {
364
- const content = `User: ${turn.userMessage}
365
-
366
- Assistant: ${turn.assistantResponse}`;
367
- const tags = ["conversation"];
368
- if (turn.sessionId) {
369
- tags.push(`session:${turn.sessionId}`);
370
- }
371
- return this.remember(content, {
372
- tags,
373
- userId: turn.userId,
374
- sessionId: turn.sessionId,
375
- metadata: {
376
- type: "conversation",
377
- ...turn.metadata
378
- }
379
- });
380
- }
381
- /**
382
- * Get conversation history for a session
383
- */
384
- async getConversationHistory(sessionId, options) {
385
- const response = await this.listMemories({
386
- sessionId,
387
- tags: ["conversation"],
388
- limit: options?.limit ?? 50,
389
- offset: options?.offset ?? 0
390
- });
391
- return response.items;
392
- }
393
- // ===========================================================================
394
- // Graph Operations
395
- // ===========================================================================
396
- /**
397
- * Get a graph node
398
- */
399
- async getGraphNode(nodeId) {
400
- return this.request("GET", `/api/v1/graph/nodes/${nodeId}`);
401
- }
402
- /**
403
- * Create a graph node
404
- */
405
- async createGraphNode(type, name, properties) {
406
- return this.request("POST", "/api/v1/graph/nodes", {
407
- type,
408
- name,
409
- properties: properties ?? {}
410
- });
411
- }
412
- /**
413
- * Create a graph edge
414
- */
415
- async createGraphEdge(sourceId, targetId, type, properties) {
416
- return this.request("POST", "/api/v1/graph/edges", {
417
- source_id: sourceId,
418
- target_id: targetId,
419
- type,
420
- properties: properties ?? {}
421
- });
422
- }
423
- /**
424
- * Traverse the graph from a starting node
425
- */
426
- async traverseGraph(options) {
427
- return this.request("POST", "/api/v1/graph/traverse", {
428
- start_node_id: options.startNodeId,
429
- max_depth: options.maxDepth ?? 3,
430
- relationship_types: options.relationshipTypes,
431
- limit: options.limit ?? 100,
432
- direction: options.direction ?? "both"
433
- });
434
- }
435
- /**
436
- * Get related nodes for a memory
437
- */
438
- async getRelatedNodes(memoryId) {
439
- const response = await this.request(
440
- "GET",
441
- `/api/v1/memories/${memoryId}/related-nodes`
442
- );
443
- return response.nodes ?? [];
444
- }
445
- // ===========================================================================
446
- // Statistics & Admin
447
- // ===========================================================================
448
- /**
449
- * Get memory statistics
450
- */
451
- async getStats() {
452
- return this.request("GET", "/api/v1/stats");
453
- }
454
- /**
455
- * Get all tags with counts
456
- */
457
- async getTags() {
458
- const response = await this.request("GET", "/api/v1/tags");
459
- return response.tags ?? [];
460
- }
461
- /**
462
- * Get user statistics
463
- */
464
- async getUserStats(userId) {
465
- return this.request("GET", `/api/v1/users/${userId}/stats`);
466
- }
467
- /**
468
- * Health check
469
- */
470
- async healthCheck() {
471
- return this.request("GET", "/health");
472
- }
473
- // ===========================================================================
474
- // Batch Operations
475
- // ===========================================================================
476
- /**
477
- * Batch create memories
478
- */
479
- async batchCreate(items) {
480
- const response = await this.request("POST", "/api/v1/memories/batch", {
481
- memories: items.map((item) => ({
482
- content: item.content,
483
- tags: item.options?.tags ?? [],
484
- user_id: item.options?.userId,
485
- session_id: item.options?.sessionId,
486
- metadata: item.options?.metadata
487
- }))
488
- });
489
- return response.ids ?? [];
490
- }
491
- /**
492
- * Batch delete memories
493
- */
494
- async batchDelete(memoryIds) {
495
- const response = await this.request("DELETE", "/api/v1/memories/batch", {
496
- ids: memoryIds
497
- });
498
- return response.deleted ?? 0;
499
- }
500
- };
501
-
502
- // src/providers/langchain.ts
503
- var CilowMemory = class {
504
- constructor(config) {
505
- this.client = new CilowClient(config);
506
- this.userId = config.userId;
507
- this.sessionId = config.sessionId;
508
- this.memoryKey = config.memoryKey ?? "history";
509
- this.inputKey = config.inputKey ?? "input";
510
- this.outputKey = config.outputKey ?? "output";
511
- this.returnMessages = config.returnMessages ?? true;
512
- this.maxMemories = config.maxMemories ?? 10;
513
- this.minRelevance = config.minRelevance ?? 0.3;
514
- this.memoryKeys = [this.memoryKey];
515
- }
516
- /**
517
- * Load memory variables based on input
518
- */
519
- async loadMemoryVariables(values) {
520
- const input = values[this.inputKey];
521
- const query = typeof input === "string" ? input : JSON.stringify(input);
522
- const results = await this.client.recall(query, {
523
- limit: this.maxMemories,
524
- minRelevance: this.minRelevance,
525
- userId: this.userId
526
- });
527
- if (this.returnMessages) {
528
- const messages = this.resultsToMessages(results);
529
- return { [this.memoryKey]: messages };
530
- } else {
531
- const history = this.resultsToString(results);
532
- return { [this.memoryKey]: history };
533
- }
534
- }
535
- /**
536
- * Save context from a conversation turn
537
- */
538
- async saveContext(inputValues, outputValues) {
539
- const input = inputValues[this.inputKey];
540
- const output = outputValues[this.outputKey];
541
- const userMessage = typeof input === "string" ? input : JSON.stringify(input);
542
- const assistantMessage = typeof output === "string" ? output : JSON.stringify(output);
543
- await this.client.storeConversation({
544
- userMessage,
545
- assistantResponse: assistantMessage,
546
- userId: this.userId ?? "anonymous",
547
- sessionId: this.sessionId
548
- });
549
- }
550
- /**
551
- * Clear memory for the current session
552
- */
553
- async clear() {
554
- if (this.sessionId) {
555
- await this.client.forget({
556
- sessionId: this.sessionId
557
- });
558
- } else if (this.userId) {
559
- await this.client.forget({
560
- userId: this.userId,
561
- tags: ["conversation"]
562
- });
563
- }
564
- }
565
- /**
566
- * Convert search results to LangChain messages
567
- */
568
- resultsToMessages(results) {
569
- const messages = [];
570
- for (const result of results) {
571
- const content = result.memory.content;
572
- if (content.includes("User:") && content.includes("Assistant:")) {
573
- const [userPart, assistantPart] = content.split("\n\nAssistant:");
574
- const userMessage = userPart.replace("User:", "").trim();
575
- const assistantMessage = assistantPart?.trim() ?? "";
576
- messages.push({
577
- _getType: () => "human",
578
- content: userMessage
579
- });
580
- if (assistantMessage) {
581
- messages.push({
582
- _getType: () => "ai",
583
- content: assistantMessage
584
- });
585
- }
586
- } else {
587
- messages.push({
588
- _getType: () => "system",
589
- content
590
- });
591
- }
592
- }
593
- return messages;
594
- }
595
- /**
596
- * Convert search results to string history
597
- */
598
- resultsToString(results) {
599
- return results.map((r, i) => `[Memory ${i + 1} - Relevance: ${(r.score * 100).toFixed(0)}%]
600
- ${r.memory.content}`).join("\n\n");
601
- }
602
- /**
603
- * Set user ID
604
- */
605
- setUserId(userId) {
606
- this.userId = userId;
607
- }
608
- /**
609
- * Set session ID
610
- */
611
- setSessionId(sessionId) {
612
- this.sessionId = sessionId;
613
- }
614
- };
615
- var CilowRetriever = class {
616
- constructor(config) {
617
- this.client = new CilowClient(config);
618
- this.userId = config.userId;
619
- this.tags = config.tags;
620
- this.topK = config.topK ?? 5;
621
- this.minRelevance = config.minRelevance ?? 0.3;
622
- }
623
- /**
624
- * Retrieve relevant documents for a query
625
- */
626
- async getRelevantDocuments(query) {
627
- const results = await this.client.recall(query, {
628
- limit: this.topK,
629
- minRelevance: this.minRelevance,
630
- tags: this.tags,
631
- userId: this.userId
632
- });
633
- return results.map((result) => this.resultToDocument(result));
634
- }
635
- /**
636
- * Alias for getRelevantDocuments (LangChain compatibility)
637
- */
638
- async invoke(query) {
639
- return this.getRelevantDocuments(query);
640
- }
641
- /**
642
- * Convert search result to LangChain document
643
- */
644
- resultToDocument(result) {
645
- return {
646
- pageContent: result.memory.content,
647
- metadata: {
648
- id: result.memory.id,
649
- score: result.score,
650
- tags: result.memory.tags,
651
- tier: result.memory.tier,
652
- createdAt: result.memory.createdAt,
653
- ...result.memory.metadata
654
- }
655
- };
656
- }
657
- /**
658
- * Add documents to the memory store
659
- */
660
- async addDocuments(documents) {
661
- const ids = [];
662
- for (const doc of documents) {
663
- const id = await this.client.remember(doc.pageContent, {
664
- tags: doc.metadata?.tags ?? [],
665
- userId: this.userId,
666
- metadata: doc.metadata
667
- });
668
- ids.push(id);
669
- }
670
- return ids;
671
- }
672
- /**
673
- * Delete documents by IDs
674
- */
675
- async deleteDocuments(ids) {
676
- await this.client.batchDelete(ids);
677
- }
678
- /**
679
- * Set user ID for filtering
680
- */
681
- setUserId(userId) {
682
- this.userId = userId;
683
- }
684
- /**
685
- * Set tags for filtering
686
- */
687
- setTags(tags) {
688
- this.tags = tags;
689
- }
690
- };
691
- var CilowVectorStore = class {
692
- constructor(config) {
693
- this.client = new CilowClient(config);
694
- this.userId = config.userId;
695
- this.defaultTags = config.defaultTags ?? [];
696
- }
697
- /**
698
- * Add documents to the vector store
699
- */
700
- async addDocuments(documents) {
701
- const items = documents.map((doc) => ({
702
- content: doc.pageContent,
703
- options: {
704
- tags: [...this.defaultTags, ...doc.metadata?.tags ?? []],
705
- userId: this.userId,
706
- metadata: doc.metadata
707
- }
708
- }));
709
- return this.client.batchCreate(items);
710
- }
711
- /**
712
- * Add texts to the vector store
713
- */
714
- async addTexts(texts, metadatas) {
715
- const documents = texts.map((text, i) => ({
716
- pageContent: text,
717
- metadata: metadatas?.[i] ?? {}
718
- }));
719
- return this.addDocuments(documents);
720
- }
721
- /**
722
- * Similarity search by query text
723
- */
724
- async similaritySearch(query, k = 5) {
725
- const results = await this.client.recall(query, {
726
- limit: k,
727
- userId: this.userId
728
- });
729
- return results.map((r) => ({
730
- pageContent: r.memory.content,
731
- metadata: {
732
- id: r.memory.id,
733
- score: r.score,
734
- tags: r.memory.tags,
735
- ...r.memory.metadata
736
- }
737
- }));
738
- }
739
- /**
740
- * Similarity search with scores
741
- */
742
- async similaritySearchWithScore(query, k = 5) {
743
- const results = await this.client.recall(query, {
744
- limit: k,
745
- userId: this.userId
746
- });
747
- return results.map((r) => [
748
- {
749
- pageContent: r.memory.content,
750
- metadata: {
751
- id: r.memory.id,
752
- tags: r.memory.tags,
753
- ...r.memory.metadata
754
- }
755
- },
756
- r.score
757
- ]);
758
- }
759
- /**
760
- * Maximum marginal relevance search
761
- */
762
- async maxMarginalRelevanceSearch(query, options) {
763
- return this.similaritySearch(query, options?.k ?? 5);
764
- }
765
- /**
766
- * Delete documents by IDs
767
- */
768
- async delete(ids) {
769
- await this.client.batchDelete(ids);
770
- }
771
- /**
772
- * Get retriever from this vector store
773
- */
774
- asRetriever(options) {
775
- return new CilowRetriever({
776
- apiUrl: "",
777
- // Will be overridden
778
- apiKey: "",
779
- // Will be overridden
780
- userId: this.userId,
781
- topK: options?.k ?? 5
782
- });
783
- }
784
- /**
785
- * Set user ID
786
- */
787
- setUserId(userId) {
788
- this.userId = userId;
789
- }
790
- };
791
- function createMemoryCallbackHandler(config) {
792
- const client = new CilowClient(config);
793
- const userId = config.userId ?? "anonymous";
794
- let currentInput = "";
795
- return {
796
- handleChainStart(chain, inputs) {
797
- currentInput = typeof inputs.input === "string" ? inputs.input : JSON.stringify(inputs.input);
798
- },
799
- async handleChainEnd(outputs) {
800
- const output = typeof outputs.output === "string" ? outputs.output : typeof outputs.text === "string" ? outputs.text : JSON.stringify(outputs);
801
- if (currentInput && output) {
802
- await client.storeConversation({
803
- userMessage: currentInput,
804
- assistantResponse: output,
805
- userId
806
- });
807
- }
808
- currentInput = "";
809
- },
810
- handleChainError(_error) {
811
- currentInput = "";
812
- }
813
- };
814
- }
815
-
816
- exports.CilowMemory = CilowMemory;
817
- exports.CilowRetriever = CilowRetriever;
818
- exports.CilowVectorStore = CilowVectorStore;
819
- exports.createMemoryCallbackHandler = createMemoryCallbackHandler;
820
- //# sourceMappingURL=langchain.js.map
821
- //# sourceMappingURL=langchain.js.map