| 1 | import { streamSse } from "@continuedev/fetch"; |
| 2 | import { CompletionOptions, LLMOptions } from "../../index.js"; |
| 3 | import { BaseLLM } from "../index.js"; |
| 4 | |
| 5 | class HuggingFaceTGI extends BaseLLM { |
| 6 | private static MAX_STOP_TOKENS = 4; |
| 7 | static providerName = "huggingface-tgi"; |
| 8 | static defaultOptions: Partial<LLMOptions> = { |
| 9 | apiBase: "http://localhost:8080/", |
| 10 | }; |
| 11 | |
| 12 | constructor(options: LLMOptions) { |
| 13 | super(options); |
| 14 | |
| 15 | this.fetch(new URL("info", this.apiBase), { |
| 16 | method: "GET", |
| 17 | }) |
| 18 | .then(async (response) => { |
| 19 | if (response.status !== 200) { |
| 20 | console.warn( |
| 21 | "Error calling Hugging Face TGI /info endpoint: ", |
| 22 | await response.text(), |
| 23 | ); |
| 24 | return; |
| 25 | } |
| 26 | const json = await response.json(); |
| 27 | this.model = json.model_id; |
| 28 | this._contextLength = Number.parseInt(json.max_input_length); |
| 29 | }) |
| 30 | .catch((e) => { |
| 31 | console.log(`Failed to list models for HuggingFace TGI: ${e.message}`); |
| 32 | }); |
| 33 | } |
| 34 | |
| 35 | private _convertArgs(options: CompletionOptions, prompt: string) { |
| 36 | const finalOptions = { |
| 37 | max_new_tokens: options.maxTokens, |
| 38 | best_of: 1, |
| 39 | temperature: options.temperature, |
| 40 | top_p: options.topP, |
| 41 | top_k: options.topK, |
| 42 | presence_penalty: options.presencePenalty, |
| 43 | frequency_penalty: options.frequencyPenalty, |
| 44 | stop: options.stop?.slice( |
| 45 | 0, |
| 46 | this.maxStopWords ?? HuggingFaceTGI.MAX_STOP_TOKENS, |
| 47 | ), |
| 48 | }; |
| 49 | |
| 50 | return finalOptions; |
| 51 | } |
| 52 | |
| 53 | protected async *_streamComplete( |
| 54 | prompt: string, |
| 55 | signal: AbortSignal, |
| 56 | options: CompletionOptions, |
| 57 | ): AsyncGenerator<string> { |
| 58 | const args = this._convertArgs(options, prompt); |
| 59 | |
| 60 | const response = await this.fetch( |
| 61 | new URL("generate_stream", this.apiBase), |
| 62 | { |
| 63 | method: "POST", |
| 64 | headers: { |
| 65 | "Content-Type": "application/json", |
| 66 | }, |
| 67 | body: JSON.stringify({ inputs: prompt, parameters: args }), |
| 68 | signal, |
| 69 | }, |
| 70 | ); |
| 71 | |
| 72 | for await (const value of streamSse(response)) { |
| 73 | yield value.token.text; |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | export default HuggingFaceTGI; |