| 1 | import { ChatMessage, CompletionOptions, CustomLLM } from "../../index.js"; |
| 2 | import { renderChatMessage } from "../../util/messageContent.js"; |
| 3 | import { BaseLLM } from "../index.js"; |
| 4 | |
| 5 | class CustomLLMClass extends BaseLLM { |
| 6 | get providerName() { |
| 7 | return "custom"; |
| 8 | } |
| 9 | |
| 10 | private customStreamCompletion?: ( |
| 11 | prompt: string, |
| 12 | signal: AbortSignal, |
| 13 | options: CompletionOptions, |
| 14 | fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>, |
| 15 | ) => AsyncGenerator<string>; |
| 16 | |
| 17 | private customStreamChat?: ( |
| 18 | messages: ChatMessage[], |
| 19 | signal: AbortSignal, |
| 20 | options: CompletionOptions, |
| 21 | fetch: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>, |
| 22 | ) => AsyncGenerator<ChatMessage | string>; |
| 23 | |
| 24 | constructor(custom: CustomLLM) { |
| 25 | super(custom.options || { model: "custom" }); |
| 26 | this.customStreamCompletion = custom.streamCompletion; |
| 27 | this.customStreamChat = custom.streamChat; |
| 28 | } |
| 29 | |
| 30 | protected async *_streamChat( |
| 31 | messages: ChatMessage[], |
| 32 | signal: AbortSignal, |
| 33 | options: CompletionOptions, |
| 34 | ): AsyncGenerator<ChatMessage> { |
| 35 | if (this.customStreamChat) { |
| 36 | for await (const content of this.customStreamChat( |
| 37 | messages, |
| 38 | signal, |
| 39 | options, |
| 40 | (...args) => this.fetch(...args), |
| 41 | )) { |
| 42 | if (typeof content === "string") { |
| 43 | yield { role: "assistant", content }; |
| 44 | } else { |
| 45 | yield content; |
| 46 | } |
| 47 | } |
| 48 | } else { |
| 49 | for await (const update of super._streamChat(messages, signal, options)) { |
| 50 | yield update; |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | protected async *_streamComplete( |
| 56 | prompt: string, |
| 57 | signal: AbortSignal, |
| 58 | options: CompletionOptions, |
| 59 | ): AsyncGenerator<string> { |
| 60 | if (this.customStreamCompletion) { |
| 61 | for await (const content of this.customStreamCompletion( |
| 62 | prompt, |
| 63 | signal, |
| 64 | options, |
| 65 | (...args) => this.fetch(...args), |
| 66 | )) { |
| 67 | yield content; |
| 68 | } |
| 69 | } else if (this.customStreamChat) { |
| 70 | for await (const content of this.customStreamChat( |
| 71 | [{ role: "user", content: prompt }], |
| 72 | signal, |
| 73 | options, |
| 74 | (...args) => this.fetch(...args), |
| 75 | )) { |
| 76 | if (typeof content === "string") { |
| 77 | yield content; |
| 78 | } else { |
| 79 | yield renderChatMessage(content); |
| 80 | } |
| 81 | } |
| 82 | } else { |
| 83 | throw new Error( |
| 84 | "Either streamCompletion or streamChat must be defined in a custom LLM in config.ts", |
| 85 | ); |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | export default CustomLLMClass; |