Elffuss BraidHub

kikocis/continue public

35c0ed0a3308 · 2.5 KiBRawPermalink
1import request from "request";
2import { Chunk } from "../..";
3
4export interface SiteIndexingResults {
5 chunks: (Chunk & { embedding: number[] })[];
6 url: string;
7 title: string;
8}
9
10export class DocsCache {
11 static readonly AWS_REGION: string = "us-west-1";
12 static readonly BUCKET_NAME: string = "continue-preindexed-docs";
13
14 /**
15 * Normalizes an embedding ID by stripping the constructor name part.
16 * This is done because we don't care about the provider, just the
17 * model and the max embedding chunk size.
18 */
19 static normalizeEmbeddingId(embeddingId: string): string {
20 // Split by "::" and remove the first part (constructor name)
21 const parts = embeddingId.split("::");
22 if (parts.length <= 1) return embeddingId; // Return original if no "::" found
23
24 // Return everything except the first part, joining with "::"
25 return parts.slice(1).join("::");
26 }
27
28 /**
29 * Gets the filepath for a given embedding ID and URL
30 */
31 static getFilepathForEmbeddingIdAndUrl(
32 embeddingId: string,
33 url: string,
34 ): string {
35 const normalizedEmbeddingId = DocsCache.normalizeEmbeddingId(embeddingId);
36 const normalizedUrl = encodeURIComponent(url.replace(/\//g, "_"));
37 return normalizedEmbeddingId + "/" + normalizedUrl;
38 }
39
40 /**
41 * Gets the fully qualified S3 URL for a given filepath
42 */
43 private static getS3Url(filepath: string): string {
44 const pathname = filepath.split("/").map(encodeURIComponent).join("/");
45 return `https://${this.BUCKET_NAME}.s3.${this.AWS_REGION}.amazonaws.com/${pathname}`;
46 }
47
48 /**
49 * Downloads cached site indexing results from S3 for a given embedding ID and URL
50 * @param embeddingId The embedding ID
51 * @param url The URL of the document
52 * @returns The downloaded data as a string
53 */
54 static async getDocsCacheForUrl(
55 embeddingId: string,
56 url: string,
57 ): Promise<string> {
58 const filepath = DocsCache.getFilepathForEmbeddingIdAndUrl(
59 embeddingId,
60 url,
61 );
62
63 return new Promise<string>((resolve, reject) => {
64 let data = "";
65 const url = this.getS3Url(filepath);
66 const download = request({
67 url,
68 });
69
70 download.on("response", (response: any) => {
71 if (response.statusCode !== 200) {
72 reject(
73 new Error("There was an error retrieving the pre-indexed doc"),
74 );
75 }
76 });
77
78 download.on("error", (err: any) => reject(err));
79 download.on("data", (chunk: any) => (data += chunk));
80 download.on("end", () => resolve(data));
81 });
82 }
83}