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