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