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