Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 3.5 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 const embedError = JSON.parse(text) as TEIEmbedErrorResponse;
56 if (!embedError.error_type || !embedError.error) {
57 throw new Error(text);
58 }
59 throw new TEIEmbedError(embedError);
60 }
61 return (await resp.json()) as number[][];
62 }
63
64 async doInfoRequest(): Promise<TEIInfoResponse> {
65 // TODO - need to use custom fetch for this request?
66 const resp = await this.fetch(new URL("info", this.apiBase), {
67 method: "GET",
68 });
69 if (!resp.ok) {
70 throw new Error(await resp.text());
71 }
72 return (await resp.json()) as TEIInfoResponse;
73 }
74
75 async rerank(query: string, chunks: Chunk[]): Promise<number[]> {
76 const headers: Record<string, string> = {
77 "Content-Type": "application/json",
78 };
79
80 if (this.apiKey) {
81 headers["Authorization"] = `Bearer ${this.apiKey}`;
82 }
83
84 const resp = await this.fetch(new URL("rerank", this.apiBase), {
85 method: "POST",
86 headers,
87 body: JSON.stringify({
88 query: query,
89 return_text: false,
90 raw_scores: false,
91 texts: chunks.map((chunk) => chunk.content),
92 truncation_direction: "Right",
93 truncate: true,
94 }),
95 });
96
97 if (!resp.ok) {
98 throw new Error(await resp.text());
99 }
100
101 const data = (await resp.json()) as any;
102 // Resort into original order and extract scores
103 const results = data.sort((a: any, b: any) => a.index - b.index);
104 return results.map((result: any) => result.score);
105 }
106}
107
108class TEIEmbedError extends Error {
109 constructor(teiResponse: TEIEmbedErrorResponse) {
110 super(JSON.stringify(teiResponse));
111 }
112}
113
114type TEIEmbedErrorResponse = {
115 error: string;
116 error_type: string;
117};
118
119type TEIInfoResponse = {
120 model_id: string;
121 model_sha: string;
122 model_dtype: string;
123 model_type: {
124 embedding: {
125 pooling: string;
126 };
127 };
128 max_concurrent_requests: number;
129 max_input_length: number;
130 max_batch_tokens: number;
131 max_batch_requests: number;
132 max_client_batch_size: number;
133 auto_truncate: boolean;
134 tokenization_workers: number;
135 version: string;
136 sha: string;
137 docker_label: string;
138};
139
140export default HuggingFaceTEIEmbeddingsProvider;