@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,737 +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/openai.ts
503
- function createCilowOpenAI(openai, config) {
504
- const cilowClient = new CilowClient(config);
505
- const defaultUserId = config.defaultUserId;
506
- const maxContextTokens = config.maxContextTokens ?? 4e3;
507
- config.minRelevance ?? 0.3;
508
- const autoStore = config.autoStore ?? false;
509
- const systemPromptPrefix = config.systemPromptPrefix ?? "The following is relevant context from memory. Use it when appropriate:";
510
- async function injectMemoryContext(messages, options) {
511
- if (options?.skipMemory) {
512
- return { messages, memoriesUsed: 0, memoryIds: [] };
513
- }
514
- const lastUserMessage = [...messages].reverse().find(
515
- (m) => m.role === "user" && typeof m.content === "string"
516
- );
517
- if (!lastUserMessage) {
518
- return { messages, memoriesUsed: 0, memoryIds: [] };
519
- }
520
- const context = await cilowClient.getContext(lastUserMessage.content, {
521
- maxTokens: maxContextTokens,
522
- userId: options?.userId ?? defaultUserId,
523
- tags: options?.tags
524
- });
525
- if (!context.context || context.memoriesUsed === 0) {
526
- return { messages, memoriesUsed: 0, memoryIds: [] };
527
- }
528
- const memoryContext = `${systemPromptPrefix}
529
-
530
- ${context.context}`;
531
- const messagesCopy = [...messages];
532
- const systemIndex = messagesCopy.findIndex((m) => m.role === "system");
533
- if (systemIndex >= 0) {
534
- const existingSystem = messagesCopy[systemIndex];
535
- if (typeof existingSystem.content === "string") {
536
- messagesCopy[systemIndex] = {
537
- ...existingSystem,
538
- content: `${existingSystem.content}
539
-
540
- ---
541
-
542
- ${memoryContext}`
543
- };
544
- }
545
- } else {
546
- messagesCopy.unshift({
547
- role: "system",
548
- content: memoryContext
549
- });
550
- }
551
- return {
552
- messages: messagesCopy,
553
- memoriesUsed: context.memoriesUsed,
554
- memoryIds: context.memoryIds
555
- };
556
- }
557
- async function storeConversation(userMessage, assistantResponse, options) {
558
- if (options?.skipStore || !autoStore) {
559
- return void 0;
560
- }
561
- return cilowClient.storeConversation({
562
- userMessage,
563
- assistantResponse,
564
- userId: options?.userId ?? defaultUserId ?? "anonymous",
565
- sessionId: options?.sessionId
566
- });
567
- }
568
- const chatCompletions = {
569
- async create(params, options) {
570
- const { messages, memoriesUsed, memoryIds } = await injectMemoryContext(
571
- params.messages,
572
- options
573
- );
574
- const completion = await openai.chat.completions.create({
575
- ...params,
576
- messages
577
- });
578
- let storedMemoryId;
579
- const lastUserMessage = [...params.messages].reverse().find(
580
- (m) => m.role === "user" && typeof m.content === "string"
581
- );
582
- const assistantResponse = completion.choices[0]?.message?.content;
583
- if (lastUserMessage && assistantResponse) {
584
- storedMemoryId = await storeConversation(
585
- lastUserMessage.content,
586
- assistantResponse,
587
- options
588
- );
589
- }
590
- return {
591
- completion,
592
- memoriesUsed,
593
- memoryIds,
594
- storedMemoryId
595
- };
596
- },
597
- async createStream(params, options) {
598
- const { messages, memoriesUsed, memoryIds } = await injectMemoryContext(
599
- params.messages,
600
- options
601
- );
602
- const stream = await openai.chat.completions.create({
603
- ...params,
604
- messages,
605
- stream: true
606
- });
607
- return {
608
- stream,
609
- memoriesUsed,
610
- memoryIds
611
- };
612
- }
613
- };
614
- return {
615
- chat: {
616
- completions: chatCompletions
617
- },
618
- memory: cilowClient,
619
- openai,
620
- async remember(content, options) {
621
- return cilowClient.remember(content, {
622
- tags: options?.tags,
623
- userId: options?.userId ?? defaultUserId
624
- });
625
- },
626
- async recall(query, options) {
627
- return cilowClient.recall(query, {
628
- limit: options?.limit,
629
- userId: options?.userId ?? defaultUserId
630
- });
631
- },
632
- async forget(filter) {
633
- return cilowClient.forget({
634
- ...filter,
635
- userId: filter.userId ?? defaultUserId
636
- });
637
- }
638
- };
639
- }
640
- var cilowFunctions = [
641
- {
642
- name: "search_memories",
643
- description: "Search through stored memories using semantic similarity",
644
- parameters: {
645
- type: "object",
646
- properties: {
647
- query: {
648
- type: "string",
649
- description: "The search query to find relevant memories"
650
- },
651
- limit: {
652
- type: "number",
653
- description: "Maximum number of results (default: 10)"
654
- },
655
- tags: {
656
- type: "array",
657
- items: { type: "string" },
658
- description: "Filter by specific tags"
659
- }
660
- },
661
- required: ["query"]
662
- }
663
- },
664
- {
665
- name: "store_memory",
666
- description: "Store a new memory for future retrieval",
667
- parameters: {
668
- type: "object",
669
- properties: {
670
- content: {
671
- type: "string",
672
- description: "The content to remember"
673
- },
674
- tags: {
675
- type: "array",
676
- items: { type: "string" },
677
- description: "Tags to categorize the memory"
678
- }
679
- },
680
- required: ["content"]
681
- }
682
- },
683
- {
684
- name: "delete_memory",
685
- description: "Delete memories by ID or filter criteria",
686
- parameters: {
687
- type: "object",
688
- properties: {
689
- memoryId: {
690
- type: "string",
691
- description: "Specific memory ID to delete"
692
- },
693
- tags: {
694
- type: "array",
695
- items: { type: "string" },
696
- description: "Delete memories with these tags"
697
- }
698
- }
699
- }
700
- }
701
- ];
702
- async function executeCilowFunction(client, functionName, args, userId) {
703
- switch (functionName) {
704
- case "search_memories":
705
- return client.recall(args.query, {
706
- limit: args.limit,
707
- tags: args.tags,
708
- userId
709
- });
710
- case "store_memory":
711
- return client.remember(args.content, {
712
- tags: args.tags,
713
- userId
714
- });
715
- case "delete_memory":
716
- return client.forget({
717
- memoryId: args.memoryId,
718
- tags: args.tags,
719
- userId
720
- });
721
- default:
722
- throw new Error(`Unknown function: ${functionName}`);
723
- }
724
- }
725
- function createFunctionExecutor(config) {
726
- const client = new CilowClient(config);
727
- return async function execute(functionName, args, userId) {
728
- return executeCilowFunction(client, functionName, args, userId);
729
- };
730
- }
731
-
732
- exports.cilowFunctions = cilowFunctions;
733
- exports.createCilowOpenAI = createCilowOpenAI;
734
- exports.createFunctionExecutor = createFunctionExecutor;
735
- exports.executeCilowFunction = executeCilowFunction;
736
- //# sourceMappingURL=openai.js.map
737
- //# sourceMappingURL=openai.js.map