aboutsummaryrefslogtreecommitdiff
path: root/apps/cf-ai-backend/src/helper.ts
blob: 5147db740c25fd96f524c15e841d89bf6397975f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import { Context } from "hono";
import { Env, vectorObj, Chunks } from "./types";
import { CloudflareVectorizeStore } from "@langchain/cloudflare";
import { OpenAIEmbeddings } from "./utils/OpenAIEmbedder";
import { createOpenAI } from "@ai-sdk/openai";
import { createGoogleGenerativeAI } from "@ai-sdk/google";
import { createAnthropic } from "@ai-sdk/anthropic";
import { z } from "zod";
import { seededRandom } from "./utils/seededRandom";
import { bulkInsertKv } from "./utils/kvBulkInsert";

export async function initQuery(env: Env, model: string = "gemini-1.5-pro") {
	const embeddings = new OpenAIEmbeddings({
		apiKey: env.OPENAI_API_KEY,
		modelName: "text-embedding-3-small",
	});

	const store = new CloudflareVectorizeStore(embeddings, {
		index: env.VECTORIZE_INDEX,
	});

	let selectedModel:
		| ReturnType<ReturnType<typeof createOpenAI>>
		| ReturnType<ReturnType<typeof createGoogleGenerativeAI>>
		| ReturnType<ReturnType<typeof createAnthropic>>;

	switch (model) {
		case "claude-3-opus":
			const anthropic = createAnthropic({
				apiKey: env.ANTHROPIC_API_KEY,
				baseURL:
					"https://gateway.ai.cloudflare.com/v1/47c2b4d598af9d423c06fc9f936226d5/supermemory/anthropic",
			});
			selectedModel = anthropic.chat("claude-3-opus-20240229");
			console.log("Selected model: ", selectedModel);
			break;
		case "gemini-1.5-pro":
			console.log("YES GOOGLE");
			const googleai = createGoogleGenerativeAI({
				apiKey: env.GOOGLE_AI_API_KEY,
			});
			selectedModel = googleai.chat("models/gemini-1.5-flash-8b");
			console.log("Selected model: ", selectedModel);
			break;
		case "gpt-4o":
		default:
			const openai = createOpenAI({
				apiKey: env.OPENAI_API_KEY,
				baseURL:
					"https://gateway.ai.cloudflare.com/v1/47c2b4d598af9d423c06fc9f936226d5/supermemory/openai",
			});
			selectedModel = openai.chat("gpt-4o-mini");
			break;
	}

	return { store, model: selectedModel };
}

export async function deleteDocument({
	url,
	user,
	c,
	store,
}: {
	url: string;
	user: string;
	c: Context<{ Bindings: Env }>;
	store: CloudflareVectorizeStore;
}) {
	const toBeDeleted = `${url}#supermemory-web`;
	const random = seededRandom(toBeDeleted);

	const uuid =
		random().toString(36).substring(2, 15) +
		random().toString(36).substring(2, 15);

	const allIds = await c.env.KV.list({ prefix: uuid });

	if (allIds.keys.length > 0) {
		const savedVectorIds = allIds.keys.map((key) => key.name);
		const vectors = await c.env.VECTORIZE_INDEX.getByIds(savedVectorIds);
		// We don't actually delete document directly, we just remove the user from the metadata.
		// If there's no user left, we can delete the document.
		const newVectors = vectors.map((vector) => {
			delete vector.metadata[`user-${user}`];

			// Get count of how many users are left
			const userCount = Object.keys(vector.metadata).filter((key) =>
				key.startsWith("user-"),
			).length;

			// If there's no user left, we can delete the document.
			// need to make sure that every chunk is deleted otherwise it would be problematic.
			if (userCount === 0) {
				store.delete({ ids: savedVectorIds });
				void Promise.all(savedVectorIds.map((id) => c.env.KV.delete(id)));
				return null;
			}

			return vector;
		});

		// If all vectors are null (deleted), we can delete the KV too. Otherwise, we update (upsert) the vectors.
		if (newVectors.every((v) => v === null)) {
			await c.env.KV.delete(uuid);
		} else {
			await c.env.VECTORIZE_INDEX.upsert(newVectors.filter((v) => v !== null));
		}
	}
}

function sanitizeKey(key: string): string {
	if (!key) throw new Error("Key cannot be empty");

	// Remove or replace invalid characters
	let sanitizedKey = key.replace(/[.$"]/g, "_");

	// Ensure key does not start with $
	if (sanitizedKey.startsWith("$")) {
		sanitizedKey = sanitizedKey.substring(1);
	}

	return sanitizedKey;
}

export async function batchCreateChunksAndEmbeddings({
	store,
	body,
	chunks,
	env: env,
}: {
	store: CloudflareVectorizeStore;
	body: z.infer<typeof vectorObj>;
	chunks: Chunks;
	env: Env;
}) {
	//! NOTE that we use #supermemory-web to ensure that
	//! If a user saves it through the extension, we don't want other users to be able to see it.
	// Requests from the extension should ALWAYS have a unique ID with the USERiD in it.
	// I cannot stress this enough, important for security.

	const ourID = `${body.url}#supermemory-web`;
	const random = seededRandom(ourID);
	const uuid =
		random().toString(36).substring(2, 15) +
		random().toString(36).substring(2, 15);

	const allIds = await env.KV.list({ prefix: uuid });

	// If some chunks for that content already exist, we'll just update the metadata to include
	// the user.
	if (allIds.keys.length > 0) {
		const savedVectorIds = allIds.keys.map((key) => key.name);
		const vectors = [];
		//Search in a batch of 20
		for (let i = 0; i < savedVectorIds.length; i += 20) {
			const batch = savedVectorIds.slice(i, i + 20);
			const batchVectors = await env.VECTORIZE_INDEX.getByIds(batch);
			vectors.push(...batchVectors);
		}
		console.log(
			"vector Id list: ",
			vectors.map((vector) => {
				return vector.id;
			}),
		);
		// Now, we'll update all vector metadatas with one more userId and all spaceIds
		const newVectors = vectors.map((vector) => {
			console.log(JSON.stringify(vector.metadata));
			vector.metadata = {
				...vector.metadata,
				[`user-${body.user}`]: 1,

				// For each space in body, add the spaceId to the vector metadata
				...(body.spaces ?? [])?.reduce((acc, space) => {
					acc[`space-${body.user}-${space}`] = 1;
					return acc;
				}, {}),
			};
			return vector;
		});

		// upsert in batch of 20
		const results = [];
		for (let i = 0; i < newVectors.length; i += 20) {
			results.push(newVectors.slice(i, i + 20));
			console.log(newVectors);
		}

		await Promise.all(
			results.map((result) => {
				return env.VECTORIZE_INDEX.upsert(result);
			}),
		);
		return;
	}

	switch (chunks.type) {
		case "tweet":
			{
				const commonMetaData = {
					type: body.type ?? "tweet",
					title: body.title?.slice(0, 50) ?? "",
					description: body.description?.slice(0, 50) ?? "",
					url: body.url,
					[sanitizeKey(`user-${body.user}`)]: 1,
				};

				const spaceMetadata = body.spaces?.reduce((acc, space) => {
					acc[`space-${body.user}-${space}`] = 1;
					return acc;
				}, {});

				const ids = [];
				const preparedDocuments = chunks.chunks
					.map((tweet, i) => {
						return tweet.chunkedTweet.map((chunk) => {
							const id = `${uuid}-${i}`;
							ids.push(id);
							const { tweetLinks, tweetVids, tweetId, tweetImages } =
								tweet.metadata;
							return {
								pageContent: chunk,
								metadata: {
									content: chunk,
									links: tweetLinks,
									videos: tweetVids,
									tweetId: tweetId,
									tweetImages: tweetImages,
									...commonMetaData,
									...spaceMetadata,
								},
							};
						});
					})
					.flat();

				const docs = await store.addDocuments(preparedDocuments, {
					ids: ids,
				});
				console.log("these are the doucment ids", ids);
				console.log("Docs added:", docs);
				const { CF_KV_AUTH_TOKEN, CF_ACCOUNT_ID, KV_NAMESPACE_ID } = env;
				await bulkInsertKv(
					{ CF_KV_AUTH_TOKEN, CF_ACCOUNT_ID, KV_NAMESPACE_ID },
					{ chunkIds: ids, urlid: ourID },
				);
			}
			break;
		case "page":
			{
				const commonMetaData = {
					type: body.type ?? "page",
					title: body.title?.slice(0, 50) ?? "",
					description: body.description?.slice(0, 50) ?? "",
					url: body.url,
					[sanitizeKey(`user-${body.user}`)]: 1,
				};
				const spaceMetadata = body.spaces?.reduce((acc, space) => {
					acc[`space-${body.user}-${space}`] = 1;
					return acc;
				}, {});

				const ids = [];
				console.log("Page hit moving on to the for loop");
				for (let i = 0; i < chunks.chunks.length; i++) {
					const chunk = chunks.chunks[i];
					const id = `${uuid}-${i}`;
					ids.push(id);
					const document = {
						pageContent: chunk,
						metadata: {
							...commonMetaData,
							...spaceMetadata,
						},
					};
					const docs = await store.addDocuments([document], { ids: [id] });
					console.log("Docs added:", docs);
					// Wait for a second after every 20 documents for open ai rate limit
					console.log(
						"This is the 20th thing in the list?",
						(i + 1) % 20 === 0,
					);
					if ((i + 1) % 20 === 0) {
						await new Promise((resolve) => setTimeout(resolve, 1000));
					}
				}

				const { CF_KV_AUTH_TOKEN, CF_ACCOUNT_ID, KV_NAMESPACE_ID } = env;
				await bulkInsertKv(
					{ CF_KV_AUTH_TOKEN, CF_ACCOUNT_ID, KV_NAMESPACE_ID },
					{ chunkIds: ids, urlid: ourID },
				);
			}
			break;
		case "note":
			{
				const commonMetaData = {
					title: body.title?.slice(0, 50) ?? "",
					type: body.type ?? "page",
					description: body.description?.slice(0, 50) ?? "",
					url: body.url,
					[sanitizeKey(`user-${body.user}`)]: 1,
				};
				const spaceMetadata = body.spaces?.reduce((acc, space) => {
					acc[`space-${body.user}-${space}`] = 1;
					return acc;
				}, {});

				const ids = [];
				for (let i = 0; i < chunks.chunks.length; i++) {
					const chunk = chunks.chunks[i];
					const id = `${uuid}-${i}`;
					ids.push(id);
					const document = {
						pageContent: chunk,
						metadata: {
							...commonMetaData,
							...spaceMetadata,
						},
					};
					const docs = await store.addDocuments([document], { ids: [id] });
					console.log("Docs added:", docs);
					// Wait for a second after every 20 documents for open ai rate limit
					console.log(
						"This is the 20th thing in the list?",
						(i + 1) % 20 === 0,
					);
					if ((i + 1) % 20 === 0) {
						await new Promise((resolve) => setTimeout(resolve, 1000));
					}
				}

				const { CF_KV_AUTH_TOKEN, CF_ACCOUNT_ID, KV_NAMESPACE_ID } = env;
				await bulkInsertKv(
					{ CF_KV_AUTH_TOKEN, CF_ACCOUNT_ID, KV_NAMESPACE_ID },
					{ chunkIds: ids, urlid: ourID },
				);
			}
			break;
		case "image": {
			const commonMetaData = {
				type: body.type ?? "image",
				title: body.title,
				description: body.description?.slice(0, 50) ?? "",
				url: body.url,
				[sanitizeKey(`user-${body.user}`)]: 1,
			};
			const spaceMetadata = body.spaces?.reduce((acc, space) => {
				acc[`space-${body.user}-${space}`] = 1;
				return acc;
			}, {});

			const ids = [];
			for (let i = 0; i < chunks.chunks.length; i++) {
				const chunk = chunks.chunks[i];
				const id = `${uuid}-${i}`;
				ids.push(id);
				const document = {
					pageContent: chunk,
					metadata: {
						...commonMetaData,
						...spaceMetadata,
					},
				};
				const docs = await store.addDocuments([document], { ids: [id] });
				console.log("Docs added:", docs);
				// Wait for a second after every 20 documents for open ai rate limit
				console.log("This is the 20th thing in the list?", (i + 1) % 20 === 0);
				if ((i + 1) % 20 === 0) {
					console.log("-----------waiting atm");
					await new Promise((resolve) => setTimeout(resolve, 1000));
				}
			}

			const { CF_KV_AUTH_TOKEN, CF_ACCOUNT_ID, KV_NAMESPACE_ID } = env;
			await bulkInsertKv(
				{ CF_KV_AUTH_TOKEN, CF_ACCOUNT_ID, KV_NAMESPACE_ID },
				{ chunkIds: ids, urlid: ourID },
			);
		}
	}

	return;
}