Elffuss BraidHub

kikocis/continue public

main · 1.5 KiBRawPermalink
1import { streamSse } from "@continuedev/fetch";
2import { CompletionOptions } from "../../index.js";
3import { BaseLLM } from "../index.js";
4
5class HuggingFaceInferenceAPI extends BaseLLM {
6 static providerName = "huggingface-inference-api";
7
8 private _convertArgs(options: CompletionOptions) {
9 return {
10 max_new_tokens: options.maxTokens ?? 1024,
11 temperature: options.temperature,
12 top_k: options.topK,
13 top_p: options.topP,
14 };
15 }
16
17 protected async *_streamComplete(
18 prompt: string,
19 signal: AbortSignal,
20 options: CompletionOptions,
21 ): AsyncGenerator<string> {
22 if (!this.apiBase) {
23 throw new Error(
24 "No API base URL provided. Please add the `apiBase` field in your config.json.",
25 );
26 }
27
28 const response = await this.fetch(this.apiBase, {
29 headers: {
30 Authorization: `Bearer ${this.apiKey}`,
31 "Content-Type": "application/json",
32 Accept: "application/json",
33 },
34 method: "POST",
35 body: JSON.stringify({
36 inputs: prompt,
37 stream: true,
38 parameters: this._convertArgs(options),
39 }),
40 signal,
41 });
42
43 async function* stream() {
44 for await (const chunk of streamSse(response)) {
45 const text = chunk?.token?.text ?? "";
46 if (text.endsWith("</s>")) {
47 yield text.slice(0, -5);
48 } else {
49 yield text;
50 }
51 }
52 }
53
54 for await (const text of stream()) {
55 yield text;
56 }
57 }
58}
59
60export default HuggingFaceInferenceAPI;