| 1 | import socketIOClient, { Socket } from "socket.io-client"; |
| 2 | |
| 3 | import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js"; |
| 4 | import { renderChatMessage } from "../../util/messageContent.js"; |
| 5 | import { BaseLLM } from "../index.js"; |
| 6 | |
| 7 | interface IFlowiseApiOptions { |
| 8 | /** Sampling temperature to use */ |
| 9 | temperature?: number; |
| 10 | |
| 11 | /** |
| 12 | * Maximum number of tokens to generate in the completion. |
| 13 | */ |
| 14 | maxTokens?: number; |
| 15 | |
| 16 | /** Total probability mass of tokens to consider at each step */ |
| 17 | topP?: number; |
| 18 | |
| 19 | /** Integer to define the top tokens considered within the sample operation to create new text. */ |
| 20 | topK?: number; |
| 21 | |
| 22 | presencePenalty?: number; |
| 23 | |
| 24 | /** Penalizes repeated tokens according to frequency */ |
| 25 | frequencyPenalty?: number; |
| 26 | |
| 27 | // Flowise allows you to pass custom properties |
| 28 | [key: string]: any; |
| 29 | } |
| 30 | |
| 31 | interface IFlowiseSocketManager { |
| 32 | isConnected: boolean; |
| 33 | hasNextToken: () => Promise<boolean>; |
| 34 | internal: { |
| 35 | timeout?: NodeJS.Timeout; |
| 36 | hasNextTokenPromiseResolve: (value: boolean | PromiseLike<boolean>) => void; |
| 37 | hasNextTokenPromiseReject: (reason?: any) => void; |
| 38 | messageHistory: string[]; |
| 39 | }; |
| 40 | error?: Error; |
| 41 | getCurrentMessage: () => string; |
| 42 | } |
| 43 | |
| 44 | interface IFlowiseKeyValueProperty { |
| 45 | key: string; |
| 46 | value: any; |
| 47 | } |
| 48 | |
| 49 | interface IFlowiseProviderLLMOptions extends LLMOptions { |
| 50 | timeout?: number; |
| 51 | additionalHeaders?: IFlowiseKeyValueProperty[]; |
| 52 | additionalFlowiseConfiguration?: IFlowiseKeyValueProperty[]; |
| 53 | } |
| 54 | |
| 55 | class Flowise extends BaseLLM { |
| 56 | static providerName = "flowise"; |
| 57 | static defaultOptions: Partial<IFlowiseProviderLLMOptions> = { |
| 58 | apiBase: "http://localhost:3000", |
| 59 | }; |
| 60 | static FlowiseMessageType = { |
| 61 | User: "userMessage", |
| 62 | Assistant: "apiMessage", |
| 63 | }; |
| 64 | |
| 65 | protected additionalFlowiseConfiguration: IFlowiseKeyValueProperty[] = []; |
| 66 | protected timeout = 5000; |
| 67 | protected additionalHeaders: IFlowiseKeyValueProperty[] = []; |
| 68 | |
| 69 | constructor(options: IFlowiseProviderLLMOptions) { |
| 70 | super(options); |
| 71 | this.timeout = options.timeout ?? 5000; |
| 72 | this.additionalHeaders = options.additionalHeaders ?? []; |
| 73 | this.additionalFlowiseConfiguration = |
| 74 | options.additionalFlowiseConfiguration ?? []; |
| 75 | } |
| 76 | |
| 77 | private _getChatUrl(): string { |
| 78 | return String(this.apiBase); |
| 79 | } |
| 80 | |
| 81 | private _getSocketUrl(): string { |
| 82 | return new URL(this._getChatUrl()).origin; |
| 83 | } |
| 84 | |
| 85 | private _getHeaders(): HeadersInit | undefined { |
| 86 | const headers: HeadersInit = { |
| 87 | "Content-Type": "application/json", |
| 88 | }; |
| 89 | |
| 90 | if (this.apiKey) { |
| 91 | headers.Authorization = `Bearer ${this.apiKey}`; |
| 92 | } |
| 93 | |
| 94 | for (const additionalHeader of this.additionalHeaders) { |
| 95 | headers[additionalHeader.key] = additionalHeader.value; |
| 96 | } |
| 97 | |
| 98 | return headers; |
| 99 | } |
| 100 | |
| 101 | protected _convertArgs(options: CompletionOptions): IFlowiseApiOptions { |
| 102 | const finalOptions: IFlowiseApiOptions = { |
| 103 | temperature: options.temperature, |
| 104 | maxTokens: options.maxTokens, |
| 105 | topP: options.topP, |
| 106 | topK: options.topK, |
| 107 | presencePenalty: options.presencePenalty, |
| 108 | frequencyPenalty: options.frequencyPenalty, |
| 109 | }; |
| 110 | |
| 111 | for (const additionalConfig of this.additionalFlowiseConfiguration) { |
| 112 | finalOptions[additionalConfig.key] = additionalConfig.value; |
| 113 | } |
| 114 | return finalOptions; |
| 115 | } |
| 116 | |
| 117 | protected async *_streamComplete( |
| 118 | prompt: string, |
| 119 | signal: AbortSignal, |
| 120 | options: CompletionOptions, |
| 121 | ): AsyncGenerator<string> { |
| 122 | const message: ChatMessage = { role: "user", content: prompt }; |
| 123 | for await (const chunk of this._streamChat([message], signal, options)) { |
| 124 | yield renderChatMessage(chunk); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | protected async *_streamChat( |
| 129 | messages: ChatMessage[], |
| 130 | signal: AbortSignal, |
| 131 | options: CompletionOptions, |
| 132 | ): AsyncGenerator<ChatMessage> { |
| 133 | const requestBody = this._getRequestBody(messages, options); |
| 134 | const { socket, socketInfo } = await this._initializeSocket(); |
| 135 | const response = await this.fetch(this._getChatUrl(), { |
| 136 | method: "POST", |
| 137 | headers: this._getHeaders(), |
| 138 | body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }), |
| 139 | signal, |
| 140 | }); |
| 141 | |
| 142 | if (response.status === 499) { |
| 143 | return; // Aborted by user |
| 144 | } |
| 145 | |
| 146 | while (await socketInfo.hasNextToken()) { |
| 147 | yield { role: "assistant", content: socketInfo.getCurrentMessage() }; |
| 148 | } |
| 149 | if (socketInfo.error) { |
| 150 | socket.disconnect(); |
| 151 | try { |
| 152 | yield { role: "assistant", content: await response.text() }; |
| 153 | } catch (error: any) { |
| 154 | yield { role: "assistant", content: (error as Error).message ?? error }; |
| 155 | } |
| 156 | } |
| 157 | socket.disconnect(); |
| 158 | } |
| 159 | |
| 160 | protected _getRequestBody( |
| 161 | messages: ChatMessage[], |
| 162 | options: CompletionOptions, |
| 163 | ): any { |
| 164 | const lastMessage = messages[messages.length - 1]; |
| 165 | const history = messages |
| 166 | .filter((m) => m !== lastMessage) |
| 167 | .map((m) => ({ |
| 168 | type: |
| 169 | m.role === "user" |
| 170 | ? Flowise.FlowiseMessageType.User |
| 171 | : Flowise.FlowiseMessageType.Assistant, |
| 172 | message: m.content, |
| 173 | })); |
| 174 | const requestBody = { |
| 175 | question: lastMessage.content, |
| 176 | history: history, |
| 177 | overrideConfig: this._convertArgs(options), |
| 178 | }; |
| 179 | return requestBody; |
| 180 | } |
| 181 | |
| 182 | protected _initializeSocket(): Promise<{ |
| 183 | socket: Socket; |
| 184 | socketInfo: IFlowiseSocketManager; |
| 185 | }> { |
| 186 | return new Promise((res, rej) => { |
| 187 | const socket = socketIOClient(this._getSocketUrl()); |
| 188 | const socketInfo: IFlowiseSocketManager = { |
| 189 | isConnected: false, |
| 190 | hasNextToken: () => Promise.resolve(false), |
| 191 | internal: { |
| 192 | hasNextTokenPromiseResolve: () => {}, |
| 193 | hasNextTokenPromiseReject: () => {}, |
| 194 | messageHistory: [], |
| 195 | }, |
| 196 | getCurrentMessage: () => "", |
| 197 | }; |
| 198 | socketInfo.getCurrentMessage = () => |
| 199 | socketInfo.internal.messageHistory.shift() ?? ""; |
| 200 | socketInfo.hasNextToken = () => { |
| 201 | return new Promise<boolean>( |
| 202 | (hasNextTokenResolve, hasNextTokenReject) => { |
| 203 | socketInfo.internal.hasNextTokenPromiseResolve = |
| 204 | hasNextTokenResolve; |
| 205 | socketInfo.internal.hasNextTokenPromiseReject = hasNextTokenReject; |
| 206 | }, |
| 207 | ); |
| 208 | }; |
| 209 | const resetTimeout = () => { |
| 210 | clearTimeout(socketInfo.internal.timeout); |
| 211 | socketInfo.internal.timeout = setTimeout(() => { |
| 212 | socketInfo.error = new Error("Timeout occurred"); |
| 213 | socketInfo.internal.hasNextTokenPromiseResolve(false); |
| 214 | rej(`Timeout trying to connect to socket: ${this._getSocketUrl()}`); |
| 215 | }, this.timeout); |
| 216 | }; |
| 217 | resetTimeout(); |
| 218 | socket.on("connect", () => { |
| 219 | socketInfo.isConnected = true; |
| 220 | resetTimeout(); |
| 221 | res({ socket, socketInfo }); |
| 222 | }); |
| 223 | socket.on("token", (token) => { |
| 224 | if (socketInfo.isConnected) { |
| 225 | socketInfo.internal.messageHistory.push(token); |
| 226 | resetTimeout(); |
| 227 | socketInfo.internal.hasNextTokenPromiseResolve(true); |
| 228 | } |
| 229 | }); |
| 230 | socket.on("error", (error) => { |
| 231 | clearTimeout(socketInfo.internal.timeout); |
| 232 | socketInfo.error = error; |
| 233 | socketInfo.internal.hasNextTokenPromiseResolve(false); |
| 234 | rej(`Error trying to connect to socket: ${this._getSocketUrl()}`); |
| 235 | }); |
| 236 | socket.on("end", () => { |
| 237 | clearTimeout(socketInfo.internal.timeout); |
| 238 | socketInfo.hasNextToken = () => |
| 239 | Promise.resolve(Boolean(socketInfo.internal.messageHistory.length)); |
| 240 | }); |
| 241 | socket.on("disconnect", () => { |
| 242 | socketInfo.isConnected = false; |
| 243 | clearTimeout(socketInfo.internal.timeout); |
| 244 | socketInfo.internal.hasNextTokenPromiseResolve(false); |
| 245 | }); |
| 246 | }); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | export default Flowise; |