Elffuss BraidHub

kikocis/continue public

d691089ac9f7 · 3.7 KiBRawPermalink
1import { Chunk, LLMOptions } from "../../index.js";
2import { BaseLLM } from "../index.js";
3
4class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
5 static providerName = "huggingface-tei";
6
7 static defaultOptions: Partial<LLMOptions> | undefined = {
8 apiBase: "http://localhost:8080",
9 model: "tei",
10 };
11
12 constructor(options: LLMOptions) {
13 super(options);
14
15 this.doInfoRequest()
16 .then((response) => {
17 this.model = response.model_id;
18 this.maxEmbeddingBatchSize = response.max_client_batch_size;
19 })
20 .catch((error) => {
21 console.error(
22 "Failed to fetch info from HuggingFace TEI Embeddings Provider:",
23 error,
24 );
25 });
26 }
27
28 async embed(chunks: string[]) {
29 const batchedChunks = this.getBatchedChunks(chunks);
30
31 const results = await Promise.all(
32 batchedChunks.map((batch) => this.doEmbedRequest(batch)),
33 );
34 return results.flat();
35 }
36
37 async doEmbedRequest(batch: string[]): Promise<number[][]> {
38 const headers: Record<string, string> = {
39 "Content-Type": "application/json",
40 };
41
42 if (this.apiKey) {
43 headers["Authorization"] = `Bearer ${this.apiKey}`;
44 }
45
46 const resp = await this.fetch(new URL("embed", this.apiBase), {
47 method: "POST",
48 body: JSON.stringify({
49 inputs: batch,
50 }),
51 headers,
52 });
53 if (!resp.ok) {
54 const text = await resp.text();
55 let teiError: TEIEmbedErrorResponse | null = null;
56 try {
57 teiError = JSON.parse(text);
58 } catch (e) {
59 console.log(`Failed to parse TEI embed error response:\n${text}`, e);
60 }
61 if (teiError && (teiError.error_type || teiError.error)) {
62 throw new TEIEmbedError(teiError);
63 }
64 throw new Error(text);
65 }
66 return (await resp.json()) as number[][];
67 }
68
69 async doInfoRequest(): Promise<TEIInfoResponse> {
70 // TODO - need to use custom fetch for this request?
71 const resp = await this.fetch(new URL("info", this.apiBase), {
72 method: "GET",
73 });
74 if (!resp.ok) {
75 throw new Error(await resp.text());
76 }
77 return (await resp.json()) as TEIInfoResponse;
78 }
79
80 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
81 const headers: Record<string, string> = {
82 "Content-Type": "application/json",
83 };
84
85 if (this.apiKey) {
86 headers["Authorization"] = `Bearer ${this.apiKey}`;
87 }
88
89 const resp = await this.fetch(new URL("rerank", this.apiBase), {
90 method: "POST",
91 headers,
92 body: JSON.stringify({
93 query: query,
94 return_text: false,
95 raw_scores: false,
96 texts: chunks.map((chunk) => chunk.content),
97 truncation_direction: "Right",
98 truncate: true,
99 }),
100 });
101
102 if (!resp.ok) {
103 throw new Error(await resp.text());
104 }
105
106 const data = (await resp.json()) as any;
107 // Resort into original order and extract scores
108 const results = data.sort((a: any, b: any) => a.index - b.index);
109 return results.map((result: any) => result.score);
110 }
111}
112
113class TEIEmbedError extends Error {
114 constructor(teiResponse: TEIEmbedErrorResponse) {
115 super(JSON.stringify(teiResponse));
116 }
117}
118
119type TEIEmbedErrorResponse = {
120 error: string;
121 error_type: string;
122};
123
124type TEIInfoResponse = {
125 model_id: string;
126 model_sha: string;
127 model_dtype: string;
128 model_type: {
129 embedding: {
130 pooling: string;
131 };
132 };
133 max_concurrent_requests: number;
134 max_input_length: number;
135 max_batch_tokens: number;
136 max_batch_requests: number;
137 max_client_batch_size: number;
138 auto_truncate: boolean;
139 tokenization_workers: number;
140 version: string;
141 sha: string;
142 docker_label: string;
143};
144
145export default HuggingFaceTEIEmbeddingsProvider;