aboutsummaryrefslogtreecommitdiff
path: root/apps/cf-ai-backend/src/utils/OpenAIEmbedder.ts
blob: a151afc0c6bd1d2562db9c0dbe16a45dfb5099cb (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
import { z } from "zod";

interface OpenAIEmbeddingsParams {
	apiKey: string;
	modelName: string;
}

export class OpenAIEmbeddings {
	private apiKey: string;
	private modelName: string;

	constructor({ apiKey, modelName }: OpenAIEmbeddingsParams) {
		this.apiKey = apiKey;
		this.modelName = modelName;
	}

	async embedDocuments(texts: string[]): Promise<number[][]> {
		const responses = await Promise.all(
			texts.map((text) => this.embedQuery(text)),
		);
		return responses;
	}

	async embedQuery(text: string): Promise<number[]> {
		const response = await fetch(
			"https://gateway.ai.cloudflare.com/v1/47c2b4d598af9d423c06fc9f936226d5/supermemory/openai/embeddings",
			{
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Authorization: `Bearer ${this.apiKey}`,
				},
				body: JSON.stringify({
					input: text,
					model: this.modelName,
				}),
			},
		);

		const data = await response.json();

		const zodTypeExpected = z.object({
			data: z.array(
				z.object({
					embedding: z.array(z.number()),
				}),
			),
		});

		const json = zodTypeExpected.safeParse(data);

		if (!json.success) {
			console.log(JSON.stringify(data));
			throw new Error("Invalid response from OpenAI: " + json.error.message);
		}

		return json.data.data[0].embedding;
	}
}