forked from continuedev/continue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
444 lines (382 loc) · 11.3 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
import {
ChatMessage,
ChatMessageRole,
CompletionOptions,
ILLM,
LLMFullCompletionOptions,
LLMOptions,
LLMReturnValue,
ModelName,
ModelProvider,
RequestOptions,
TemplateType,
} from "..";
import mergeJson from "../util/merge";
import { Telemetry } from "../util/posthog";
import {
autodetectPromptTemplates,
autodetectTemplateFunction,
autodetectTemplateType,
modelSupportsImages,
} from "./autodetect";
import {
CONTEXT_LENGTH_FOR_MODEL,
DEFAULT_ARGS,
DEFAULT_CONTEXT_LENGTH,
DEFAULT_MAX_TOKENS,
} from "./constants";
import {
compileChatMessages,
countTokens,
pruneRawPromptFromTop,
} from "./countTokens";
import CompletionOptionsForModels from "./templates/options";
export abstract class BaseLLM implements ILLM {
static providerName: ModelProvider;
static defaultOptions: Partial<LLMOptions> | undefined = undefined;
get providerName(): ModelProvider {
return (this.constructor as typeof BaseLLM).providerName;
}
supportsImages(): boolean {
return modelSupportsImages(this.providerName, this.model);
}
uniqueId: string;
model: string;
title?: string;
systemMessage?: string;
contextLength: number;
completionOptions: CompletionOptions;
requestOptions?: RequestOptions;
template?: TemplateType;
promptTemplates?: Record<string, string>;
templateMessages?: (messages: ChatMessage[]) => string;
writeLog?: (str: string) => Promise<void>;
llmRequestHook?: (model: string, prompt: string) => any;
apiKey?: string;
apiBase?: string;
engine?: string;
apiVersion?: string;
apiType?: string;
region?: string;
projectId?: string;
private _llmOptions: LLMOptions;
constructor(options: LLMOptions) {
this._llmOptions = options;
// Set default options
options = {
title: (this.constructor as typeof BaseLLM).providerName,
...(this.constructor as typeof BaseLLM).defaultOptions,
...options,
};
const templateType =
options.template || autodetectTemplateType(options.model);
this.title = options.title;
this.uniqueId = options.uniqueId || "None";
this.model = options.model;
this.systemMessage = options.systemMessage;
this.contextLength = options.contextLength || DEFAULT_CONTEXT_LENGTH;
this.completionOptions = {
...options.completionOptions,
model: options.model || "gpt-4",
maxTokens: options.completionOptions?.maxTokens || DEFAULT_MAX_TOKENS,
};
if (CompletionOptionsForModels[options.model as ModelName]) {
this.completionOptions = mergeJson(
this.completionOptions,
CompletionOptionsForModels[options.model as ModelName] || {}
);
}
this.requestOptions = options.requestOptions;
this.promptTemplates = {
...autodetectPromptTemplates(options.model, templateType),
...options.promptTemplates,
};
this.templateMessages =
options.templateMessages ||
autodetectTemplateFunction(
options.model,
this.providerName,
options.template
);
this.writeLog = options.writeLog;
this.llmRequestHook = options.llmRequestHook;
this.apiKey = options.apiKey;
this.apiBase = options.apiBase;
if (this.apiBase?.endsWith("/")) {
this.apiBase = this.apiBase.slice(0, -1);
}
this.engine = options.engine;
this.apiVersion = options.apiVersion;
this.apiType = options.apiType;
this.region = options.region;
this.projectId = options.projectId;
}
listModels(): Promise<string[]> {
return Promise.resolve([]);
}
private _compileChatMessages(
options: CompletionOptions,
messages: ChatMessage[],
functions?: any[]
) {
let contextLength = this.contextLength;
if (
options.model !== this.model &&
options.model in CONTEXT_LENGTH_FOR_MODEL
) {
contextLength =
CONTEXT_LENGTH_FOR_MODEL[options.model] || DEFAULT_CONTEXT_LENGTH;
}
return compileChatMessages(
options.model,
messages,
contextLength,
options.maxTokens || DEFAULT_MAX_TOKENS,
this.supportsImages(),
undefined,
functions,
this.systemMessage
);
}
private _getSystemMessage(): string | undefined {
// TODO: Merge with config system message
return this.systemMessage;
}
private _templatePromptLikeMessages(prompt: string): string {
if (!this.templateMessages) {
return prompt;
}
const msgs: ChatMessage[] = [{ role: "user", content: prompt }];
const systemMessage = this._getSystemMessage();
if (systemMessage) {
msgs.unshift({ role: "system", content: systemMessage });
}
return this.templateMessages(msgs);
}
private _compileLogMessage(
prompt: string,
completionOptions: CompletionOptions
): string {
const dict = { contextLength: this.contextLength, ...completionOptions };
const settings = Object.entries(dict)
.map(([key, value]) => `${key}: ${value}`)
.join("\n");
return `Settings:
${settings}
############################################
${prompt}`;
}
private _logTokensGenerated(model: string, completion: string) {
let tokens = this.countTokens(completion);
Telemetry.capture("tokens_generated", {
model: model,
provider: this.providerName,
tokens: tokens,
});
Telemetry.capture("tokensGenerated", {
model: model,
provider: this.providerName,
tokens: tokens,
});
}
_fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> =
undefined;
protected fetch(
url: RequestInfo | URL,
init?: RequestInit
): Promise<Response> {
if (this._fetch) {
// Custom Node.js fetch
return this._fetch(url, init);
}
// Most of the requestOptions aren't available in the browser
const headers = new Headers(init?.headers);
for (const [key, value] of Object.entries(
this.requestOptions?.headers || {}
)) {
headers.append(key, value as string);
}
return fetch(url, {
...init,
headers,
});
}
private _parseCompletionOptions(options: LLMFullCompletionOptions) {
const log = options.log ?? true;
const raw = options.raw ?? false;
delete options.log;
delete options.raw;
const completionOptions: CompletionOptions = mergeJson(
this.completionOptions,
options
);
return { completionOptions, log, raw };
}
private _formatChatMessages(messages: ChatMessage[]): string {
let formatted = "";
for (let msg of messages) {
formatted += `<${msg.role}>\n${msg.content || ""}\n\n`;
}
return formatted;
}
async *streamComplete(
prompt: string,
options: LLMFullCompletionOptions = {}
) {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
prompt = pruneRawPromptFromTop(
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens || DEFAULT_MAX_TOKENS
);
if (!raw) {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
let completion = "";
for await (const chunk of this._streamComplete(prompt, completionOptions)) {
completion += chunk;
yield chunk;
}
this._logTokensGenerated(completionOptions.model, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
return { prompt, completion };
}
async complete(prompt: string, options: LLMFullCompletionOptions = {}) {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
prompt = pruneRawPromptFromTop(
completionOptions.model,
this.contextLength,
prompt,
completionOptions.maxTokens || DEFAULT_MAX_TOKENS
);
if (!raw) {
prompt = this._templatePromptLikeMessages(prompt);
}
if (log) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
const completion = await this._complete(prompt, completionOptions);
this._logTokensGenerated(completionOptions.model, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
return completion;
}
async chat(messages: ChatMessage[], options: LLMFullCompletionOptions = {}) {
let completion = "";
for await (const chunk of this.streamChat(messages, options)) {
completion += chunk.content;
}
return { role: "assistant" as ChatMessageRole, content: completion };
}
async *streamChat(
messages: ChatMessage[],
options: LLMFullCompletionOptions = {}
): AsyncGenerator<ChatMessage, LLMReturnValue> {
const { completionOptions, log, raw } =
this._parseCompletionOptions(options);
messages = this._compileChatMessages(completionOptions, messages);
const prompt = this.templateMessages
? this.templateMessages(messages)
: this._formatChatMessages(messages);
if (log) {
if (this.writeLog) {
await this.writeLog(this._compileLogMessage(prompt, completionOptions));
}
if (this.llmRequestHook) {
this.llmRequestHook(completionOptions.model, prompt);
}
}
let completion = "";
try {
if (this.templateMessages) {
for await (const chunk of this._streamComplete(
prompt,
completionOptions
)) {
completion += chunk;
yield { role: "assistant", content: chunk };
}
} else {
for await (const chunk of this._streamChat(
messages,
completionOptions
)) {
completion += chunk.content;
yield chunk;
}
}
} catch (error) {
console.log(error);
throw error;
}
this._logTokensGenerated(completionOptions.model, completion);
if (log && this.writeLog) {
await this.writeLog(`Completion:\n\n${completion}\n\n`);
}
return { prompt, completion };
}
protected async *_streamComplete(
prompt: string,
options: CompletionOptions
): AsyncGenerator<string> {
throw new Error("Not implemented");
}
protected async *_streamChat(
messages: ChatMessage[],
options: CompletionOptions
): AsyncGenerator<ChatMessage> {
if (!this.templateMessages) {
throw new Error(
"You must either implement templateMessages or _streamChat"
);
}
for await (const chunk of this._streamComplete(
this.templateMessages(messages),
options
)) {
yield { role: "assistant", content: chunk };
}
}
protected async _complete(prompt: string, options: CompletionOptions) {
let completion = "";
for await (const chunk of this._streamComplete(prompt, options)) {
completion += chunk;
}
return completion;
}
countTokens(text: string): number {
return countTokens(text, this.model);
}
protected collectArgs(options: CompletionOptions): any {
return {
...DEFAULT_ARGS,
// model: this.model,
...options,
};
}
private _shouldRequestDirectly() {
if (typeof window === "undefined") {
return true;
}
return window?.ide !== "vscode";
}
}