Elffuss BraidHub

kikocis/continue public

71fd2e7d4456 · 7.4 KiBRawPermalink
1import socketIOClient, { Socket } from "socket.io-client";
2
3import { ChatMessage, CompletionOptions, LLMOptions } from "../../index.js";
4import { renderChatMessage } from "../../util/messageContent.js";
5import { BaseLLM } from "../index.js";
6
7interface 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
31interface 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
44interface IFlowiseKeyValueProperty {
45 key: string;
46 value: any;
47}
48
49interface IFlowiseProviderLLMOptions extends LLMOptions {
50 timeout?: number;
51 additionalHeaders?: IFlowiseKeyValueProperty[];
52 additionalFlowiseConfiguration?: IFlowiseKeyValueProperty[];
53}
54
55class 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 request = this.fetch(this._getChatUrl(), {
136 method: "POST",
137 headers: this._getHeaders(),
138 body: JSON.stringify({ ...requestBody, socketIOClientId: socket.id }),
139 signal,
140 }).then((res) => res.json());
141
142 while (await socketInfo.hasNextToken()) {
143 yield { role: "assistant", content: socketInfo.getCurrentMessage() };
144 }
145 if (socketInfo.error) {
146 socket.disconnect();
147 try {
148 yield { role: "assistant", content: (await request).text };
149 } catch (error: any) {
150 yield { role: "assistant", content: (error as Error).message ?? error };
151 }
152 }
153 socket.disconnect();
154 }
155
156 protected _getRequestBody(
157 messages: ChatMessage[],
158 options: CompletionOptions,
159 ): any {
160 const lastMessage = messages[messages.length - 1];
161 const history = messages
162 .filter((m) => m !== lastMessage)
163 .map((m) => ({
164 type:
165 m.role === "user"
166 ? Flowise.FlowiseMessageType.User
167 : Flowise.FlowiseMessageType.Assistant,
168 message: m.content,
169 }));
170 const requestBody = {
171 question: lastMessage.content,
172 history: history,
173 overrideConfig: this._convertArgs(options),
174 };
175 return requestBody;
176 }
177
178 protected _initializeSocket(): Promise<{
179 socket: Socket;
180 socketInfo: IFlowiseSocketManager;
181 }> {
182 return new Promise((res, rej) => {
183 const socket = socketIOClient(this._getSocketUrl());
184 const socketInfo: IFlowiseSocketManager = {
185 isConnected: false,
186 hasNextToken: () => Promise.resolve(false),
187 internal: {
188 hasNextTokenPromiseResolve: () => {},
189 hasNextTokenPromiseReject: () => {},
190 messageHistory: [],
191 },
192 getCurrentMessage: () => "",
193 };
194 socketInfo.getCurrentMessage = () =>
195 socketInfo.internal.messageHistory.shift() ?? "";
196 socketInfo.hasNextToken = () => {
197 return new Promise<boolean>(
198 (hasNextTokenResolve, hasNextTokenReject) => {
199 socketInfo.internal.hasNextTokenPromiseResolve =
200 hasNextTokenResolve;
201 socketInfo.internal.hasNextTokenPromiseReject = hasNextTokenReject;
202 },
203 );
204 };
205 const resetTimeout = () => {
206 clearTimeout(socketInfo.internal.timeout);
207 socketInfo.internal.timeout = setTimeout(() => {
208 socketInfo.error = new Error("Timeout occurred");
209 socketInfo.internal.hasNextTokenPromiseResolve(false);
210 rej(`Timeout trying to connect to socket: ${this._getSocketUrl()}`);
211 }, this.timeout);
212 };
213 resetTimeout();
214 socket.on("connect", () => {
215 socketInfo.isConnected = true;
216 resetTimeout();
217 res({ socket, socketInfo });
218 });
219 socket.on("token", (token) => {
220 if (socketInfo.isConnected) {
221 socketInfo.internal.messageHistory.push(token);
222 resetTimeout();
223 socketInfo.internal.hasNextTokenPromiseResolve(true);
224 }
225 });
226 socket.on("error", (error) => {
227 clearTimeout(socketInfo.internal.timeout);
228 socketInfo.error = error;
229 socketInfo.internal.hasNextTokenPromiseResolve(false);
230 rej(`Error trying to connect to socket: ${this._getSocketUrl()}`);
231 });
232 socket.on("end", () => {
233 clearTimeout(socketInfo.internal.timeout);
234 socketInfo.hasNextToken = () =>
235 Promise.resolve(Boolean(socketInfo.internal.messageHistory.length));
236 });
237 socket.on("disconnect", () => {
238 socketInfo.isConnected = false;
239 clearTimeout(socketInfo.internal.timeout);
240 socketInfo.internal.hasNextTokenPromiseResolve(false);
241 });
242 });
243 }
244}
245
246export default Flowise;