-
-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathresolveChatWrapper.ts
More file actions
536 lines (473 loc) · 24.2 KB
/
resolveChatWrapper.ts
File metadata and controls
536 lines (473 loc) · 24.2 KB
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
import {parseModelFileName} from "../../utils/parseModelFileName.js";
import {Llama3ChatWrapper} from "../Llama3ChatWrapper.js";
import {Llama2ChatWrapper} from "../Llama2ChatWrapper.js";
import {ChatMLChatWrapper} from "../ChatMLChatWrapper.js";
import {GeneralChatWrapper} from "../GeneralChatWrapper.js";
import {FalconChatWrapper} from "../FalconChatWrapper.js";
import {FunctionaryChatWrapper} from "../FunctionaryChatWrapper.js";
import {AlpacaChatWrapper} from "../AlpacaChatWrapper.js";
import {GemmaChatWrapper} from "../GemmaChatWrapper.js";
import {Gemma4ChatWrapper} from "../Gemma4ChatWrapper.js";
import {JinjaTemplateChatWrapper, JinjaTemplateChatWrapperOptions} from "../generic/JinjaTemplateChatWrapper.js";
import {TemplateChatWrapper} from "../generic/TemplateChatWrapper.js";
import {getConsoleLogPrefix} from "../../utils/getConsoleLogPrefix.js";
import {Llama3_1ChatWrapper} from "../Llama3_1ChatWrapper.js";
import {Llama3_2LightweightChatWrapper} from "../Llama3_2LightweightChatWrapper.js";
import {DeepSeekChatWrapper} from "../DeepSeekChatWrapper.js";
import {MistralChatWrapper} from "../MistralChatWrapper.js";
import {Tokenizer} from "../../types.js";
import {includesText} from "../../utils/includesText.js";
import {LlamaModel} from "../../evaluator/LlamaModel/LlamaModel.js";
import {QwenChatWrapper} from "../QwenChatWrapper.js";
import {HarmonyChatWrapper} from "../HarmonyChatWrapper.js";
import {SeedChatWrapper} from "../SeedChatWrapper.js";
import {isJinjaTemplateEquivalentToSpecializedChatWrapper} from "./isJinjaTemplateEquivalentToSpecializedChatWrapper.js";
import {getModelLinageNames} from "./getModelLinageNames.js";
import type {GgufFileInfo} from "../../gguf/types/GgufFileInfoTypes.js";
export const specializedChatWrapperTypeNames = Object.freeze([
"general", "deepSeek", "qwen", "llama3.2-lightweight", "llama3.1", "llama3", "llama2Chat", "mistral", "alpacaChat", "functionary",
"chatML", "falconChat", "gemma4", "gemma", "harmony", "seed"
] as const);
export type SpecializedChatWrapperTypeName = (typeof specializedChatWrapperTypeNames)[number];
export const templateChatWrapperTypeNames = Object.freeze([
"template", "jinjaTemplate"
] as const);
export type TemplateChatWrapperTypeName = (typeof templateChatWrapperTypeNames)[number];
export const resolvableChatWrapperTypeNames = Object.freeze([
"auto",
...specializedChatWrapperTypeNames,
...templateChatWrapperTypeNames
] as const);
export type ResolvableChatWrapperTypeName = (typeof resolvableChatWrapperTypeNames)[number];
export const chatWrappers = Object.freeze({
"general": GeneralChatWrapper,
"deepSeek": DeepSeekChatWrapper,
"qwen": QwenChatWrapper,
"llama3.1": Llama3_1ChatWrapper,
"llama3.2-lightweight": Llama3_2LightweightChatWrapper,
"llama3": Llama3ChatWrapper,
"llama2Chat": Llama2ChatWrapper,
"mistral": MistralChatWrapper,
"alpacaChat": AlpacaChatWrapper,
"functionary": FunctionaryChatWrapper,
"chatML": ChatMLChatWrapper,
"falconChat": FalconChatWrapper,
"gemma4": Gemma4ChatWrapper,
"gemma": GemmaChatWrapper,
"harmony": HarmonyChatWrapper,
"seed": SeedChatWrapper,
"template": TemplateChatWrapper,
"jinjaTemplate": JinjaTemplateChatWrapper
} as const satisfies Record<SpecializedChatWrapperTypeName | TemplateChatWrapperTypeName, any>);
const chatWrapperToConfigType = new Map(
Object.entries(chatWrappers)
.map(([configType, Wrapper]) => (
[Wrapper, configType as keyof typeof chatWrappers]
))
);
const specializedChatWrapperRelatedTexts = {
"harmony": ["gpt", "gpt-oss"],
"gemma4": ["gemma 4", "gemma-4"]
} satisfies Partial<Record<ResolvableChatWrapperTypeName, string[]>>;
export type BuiltInChatWrapperType = InstanceType<typeof chatWrappers[keyof typeof chatWrappers]>;
export type ResolveChatWrapperOptions = {
/**
* Resolve to a specific chat wrapper type.
* You better not set this option unless you need to force a specific chat wrapper type.
*
* Defaults to `"auto"`.
*/
type?: "auto" | SpecializedChatWrapperTypeName | TemplateChatWrapperTypeName,
bosString?: string | null,
filename?: string,
fileInfo?: GgufFileInfo,
tokenizer?: Tokenizer,
customWrapperSettings?: {
[wrapper in keyof typeof chatWrappers]?: ConstructorParameters<(typeof chatWrappers)[wrapper]>[0]
},
/**
* Defaults to `true`.
*/
warningLogs?: boolean,
/**
* Defaults to `true`.
*/
fallbackToOtherWrappersOnJinjaError?: boolean,
/**
* Don't resolve to a Jinja chat wrapper unless `type` is set to a Jinja chat wrapper type.
*
* Defaults to `false`.
*/
noJinja?: boolean
};
export type ResolveChatWrapperWithModelOptions = {
/**
* Resolve to a specific chat wrapper type.
* You better not set this option unless you need to force a specific chat wrapper type.
*
* Defaults to `"auto"`.
*/
type?: "auto" | SpecializedChatWrapperTypeName | TemplateChatWrapperTypeName,
customWrapperSettings?: {
[wrapper in keyof typeof chatWrappers]?: typeof JinjaTemplateChatWrapper extends (typeof chatWrappers)[wrapper]
? Partial<ConstructorParameters<(typeof chatWrappers)[wrapper]>[0]>
: ConstructorParameters<(typeof chatWrappers)[wrapper]>[0]
},
/**
* Defaults to `true`.
*/
warningLogs?: boolean,
/**
* Defaults to `true`.
*/
fallbackToOtherWrappersOnJinjaError?: boolean,
/**
* Don't resolve to a Jinja chat wrapper unless `type` is set to a Jinja chat wrapper type.
*
* Defaults to `false`.
*/
noJinja?: boolean
};
/**
* Resolve to a chat wrapper instance based on the provided information.
* The more information provided, the better the resolution will be (except for `type`).
*
* It's recommended to not set `type` to a specific chat wrapper in order for the resolution to be more flexible, but it is useful for when
* you need to provide the ability to force a specific chat wrapper type.
* Note that when setting `type` to a generic chat wrapper type (such as `"template"` or `"jinjaTemplate"`), the `customWrapperSettings`
* must contain the necessary settings for that chat wrapper to be created.
*
* When loading a Jinja chat template from either `fileInfo` or `customWrapperSettings.jinjaTemplate.template`,
* if the chat template format is invalid, it fallbacks to resolve other chat wrappers,
* unless `fallbackToOtherWrappersOnJinjaError` is set to `false` (in which case, it will throw an error).
* @example
* ```typescript
* import {getLlama, resolveChatWrapper, GeneralChatWrapper} from "node-llama-cpp";
*
* const llama = await getLlama();
* const model = await llama.loadModel({modelPath: "path/to/model.gguf"});
*
* const chatWrapper = resolveChatWrapper(model, {
* customWrapperSettings: {
* "llama3.1": {
* cuttingKnowledgeDate: new Date("2025-01-01T00:00:00Z")
* }
* }
* }) ?? new GeneralChatWrapper()
* ```
* @example
*```typescript
* import {getLlama, resolveChatWrapper, GeneralChatWrapper} from "node-llama-cpp";
*
* const llama = await getLlama();
* const model = await llama.loadModel({modelPath: "path/to/model.gguf"});
*
* const chatWrapper = resolveChatWrapper({
* bosString: model.tokens.bosString,
* filename: model.filename,
* fileInfo: model.fileInfo,
* tokenizer: model.tokenizer
* }) ?? new GeneralChatWrapper()
* ```
*/
export function resolveChatWrapper(model: LlamaModel, options?: ResolveChatWrapperWithModelOptions): BuiltInChatWrapperType;
export function resolveChatWrapper(options: ResolveChatWrapperOptions): BuiltInChatWrapperType | null;
export function resolveChatWrapper(
options: ResolveChatWrapperOptions | LlamaModel,
modelOptions?: ResolveChatWrapperWithModelOptions
): BuiltInChatWrapperType | null {
if (options instanceof LlamaModel)
return resolveChatWrapper({
...(modelOptions ?? {}),
customWrapperSettings: modelOptions?.customWrapperSettings as ResolveChatWrapperOptions["customWrapperSettings"],
bosString: options.tokens.bosString,
filename: options.filename,
fileInfo: options.fileInfo,
tokenizer: options.tokenizer
}) ?? new GeneralChatWrapper();
const {
type = "auto",
bosString,
filename,
fileInfo,
tokenizer,
customWrapperSettings,
warningLogs = true,
fallbackToOtherWrappersOnJinjaError = true,
noJinja = false
} = options;
function createSpecializedChatWrapper<const T extends typeof chatWrappers[SpecializedChatWrapperTypeName]>(
specializedChatWrapper: T,
defaultSettings: ConstructorParameters<T>[0] = {}
): InstanceType<T> {
const chatWrapperConfigType = chatWrapperToConfigType.get(specializedChatWrapper) as SpecializedChatWrapperTypeName;
const chatWrapperSettings = customWrapperSettings?.[chatWrapperConfigType];
return new (specializedChatWrapper as any)({
...(defaultSettings ?? {}),
...(chatWrapperSettings ?? {})
});
}
if (type !== "auto" && type != null) {
if (isTemplateChatWrapperType(type)) {
const Wrapper = chatWrappers[type];
if (isClassReference(Wrapper, TemplateChatWrapper)) {
const wrapperSettings = customWrapperSettings?.template;
if (wrapperSettings == null || wrapperSettings?.template == null || wrapperSettings?.historyTemplate == null ||
wrapperSettings.historyTemplate.system == null || wrapperSettings.historyTemplate.user == null ||
wrapperSettings.historyTemplate.model == null
) {
if (warningLogs)
console.warn(getConsoleLogPrefix() + "Template chat wrapper settings must have a template, historyTemplate, historyTemplate.system, historyTemplate.user, and historyTemplate.model. Falling back to resolve other chat wrapper types.");
} else
return new TemplateChatWrapper(wrapperSettings);
} else if (isClassReference(Wrapper, JinjaTemplateChatWrapper)) {
const jinjaTemplate = customWrapperSettings?.jinjaTemplate?.template ?? fileInfo?.metadata?.tokenizer?.chat_template;
if (jinjaTemplate == null) {
if (warningLogs)
console.warn(getConsoleLogPrefix() + "Jinja template chat wrapper received no template. Falling back to resolve other chat wrapper types.");
} else {
try {
return new JinjaTemplateChatWrapper({
tokenizer,
...(customWrapperSettings?.jinjaTemplate ?? {}),
template: jinjaTemplate
});
} catch (err) {
if (!fallbackToOtherWrappersOnJinjaError)
throw err;
else if (warningLogs)
console.error(getConsoleLogPrefix() + "Error creating Jinja template chat wrapper. Falling back to resolve other chat wrappers. Error:", err);
}
}
} else
void (Wrapper satisfies never);
} else if (Object.hasOwn(chatWrappers, type)) {
const Wrapper = chatWrappers[type];
const wrapperSettings: ConstructorParameters<typeof Wrapper>[0] | undefined =
customWrapperSettings?.[type];
return new (Wrapper as any)(wrapperSettings);
}
}
const modelJinjaTemplate = customWrapperSettings?.jinjaTemplate?.template ?? fileInfo?.metadata?.tokenizer?.chat_template;
if (modelJinjaTemplate != null && modelJinjaTemplate.trim() !== "") {
const jinjaTemplateChatWrapperOptions: JinjaTemplateChatWrapperOptions = {
tokenizer,
...(customWrapperSettings?.jinjaTemplate ?? {}),
template: modelJinjaTemplate
};
const chatWrapperNamesToCheck = orderChatWrapperNamesByAssumedCompatibilityWithModel(
specializedChatWrapperTypeNames,
{filename, fileInfo}
);
for (const specializedChatWrapperTypeName of chatWrapperNamesToCheck) {
const Wrapper = chatWrappers[specializedChatWrapperTypeName];
const wrapperSettings = customWrapperSettings?.[specializedChatWrapperTypeName];
const isCompatible = Wrapper._checkModelCompatibility({
tokenizer,
fileInfo
});
if (!isCompatible)
continue;
const testOptionConfigurations = Wrapper._getOptionConfigurationsToTestIfCanSupersedeJinjaTemplate?.() ?? [];
if (testOptionConfigurations.length === 0)
testOptionConfigurations.push({} as any);
for (const testConfigurationOrPair of testOptionConfigurations) {
const testConfig = testConfigurationOrPair instanceof Array
? (testConfigurationOrPair[0]! ?? {})
: testConfigurationOrPair;
const applyConfig = testConfigurationOrPair instanceof Array
? (testConfigurationOrPair[1]! ?? {})
: testConfigurationOrPair;
const additionalJinjaOptions = testConfigurationOrPair instanceof Array
? testConfigurationOrPair[2]!
: undefined;
const testChatWrapperSettings = {
...(wrapperSettings ?? {}),
...(testConfig ?? {})
};
const applyChatWrapperSettings = {
...(wrapperSettings ?? {}),
...(applyConfig ?? {})
};
const chatWrapper = new (Wrapper as any)(testChatWrapperSettings);
const jinjaTemplateChatWrapperOptionsWithAdditionalParameters: JinjaTemplateChatWrapperOptions = {
...(additionalJinjaOptions ?? {}),
...jinjaTemplateChatWrapperOptions,
additionalRenderParameters: additionalJinjaOptions?.additionalRenderParameters == null
? jinjaTemplateChatWrapperOptions.additionalRenderParameters
: {
...(jinjaTemplateChatWrapperOptions.additionalRenderParameters ?? {}),
...additionalJinjaOptions.additionalRenderParameters
}
};
if (
isJinjaTemplateEquivalentToSpecializedChatWrapper(
jinjaTemplateChatWrapperOptionsWithAdditionalParameters,
chatWrapper,
tokenizer
)
)
return new (Wrapper as any)(applyChatWrapperSettings);
}
}
if (!noJinja) {
if (!fallbackToOtherWrappersOnJinjaError)
return new JinjaTemplateChatWrapper(jinjaTemplateChatWrapperOptions);
try {
return new JinjaTemplateChatWrapper(jinjaTemplateChatWrapperOptions);
} catch (err) {
console.error(getConsoleLogPrefix() + "Error creating Jinja template chat wrapper. Falling back to resolve other chat wrappers. Error:", err);
}
}
}
for (const modelNames of getModelLinageNames(fileInfo?.metadata)) {
if (includesText(modelNames, ["llama 3.2", "llama-3.2", "llama3.2"]) && Llama3_2LightweightChatWrapper._checkModelCompatibility({tokenizer, fileInfo}))
return createSpecializedChatWrapper(Llama3_2LightweightChatWrapper);
else if (includesText(modelNames, ["llama 3.1", "llama-3.1", "llama3.1"]) && Llama3_1ChatWrapper._checkModelCompatibility({tokenizer, fileInfo}))
return createSpecializedChatWrapper(Llama3_1ChatWrapper);
else if (includesText(modelNames, ["llama 3", "llama-3", "llama3"]))
return createSpecializedChatWrapper(Llama3ChatWrapper);
else if (includesText(modelNames, ["Mistral", "Mistral Large", "Mistral Large Instruct", "Mistral-Large", "Codestral"]))
return createSpecializedChatWrapper(MistralChatWrapper);
else if (includesText(modelNames, ["Gemma 4", "Gemma-4", "gemma-4"]))
return createSpecializedChatWrapper(Gemma4ChatWrapper);
else if (includesText(modelNames, ["Gemma", "Gemma 2"]))
return createSpecializedChatWrapper(GemmaChatWrapper);
else if (includesText(modelNames, ["gpt-oss", "Gpt Oss", "Gpt-Oss", "openai_gpt-oss", "Openai_Gpt Oss", "openai.gpt-oss", "Openai.Gpt Oss"]))
return createSpecializedChatWrapper(HarmonyChatWrapper);
else if (includesText(modelNames, ["seed-oss", "Seed Oss", "Seed OSS", "Seed-Oss", "Seed-OSS", "ByteDance-Seed_Seed-OSS", "ByteDance-Seed.Seed-OSS"]))
return createSpecializedChatWrapper(SeedChatWrapper);
}
// try to find a pattern in the Jinja template to resolve to a specialized chat wrapper,
// with a logic similar to `llama.cpp`'s `llama_chat_apply_template_internal` function
if (modelJinjaTemplate != null && modelJinjaTemplate.trim() !== "") {
if (modelJinjaTemplate.includes("<seed:think>") || (
modelJinjaTemplate.includes("<seed:bos>") && modelJinjaTemplate.includes("<seed:eos>")
))
return createSpecializedChatWrapper(SeedChatWrapper);
else if (modelJinjaTemplate.includes("<|start|>") && modelJinjaTemplate.includes("<|channel|>"))
return createSpecializedChatWrapper(HarmonyChatWrapper);
else if (modelJinjaTemplate.includes("<|turn>") && modelJinjaTemplate.includes("<|tool_call>call:"))
return createSpecializedChatWrapper(Gemma4ChatWrapper);
else if (modelJinjaTemplate.includes("<|im_start|>"))
return createSpecializedChatWrapper(ChatMLChatWrapper);
else if (modelJinjaTemplate.includes("[INST]"))
return createSpecializedChatWrapper(Llama2ChatWrapper, {
addSpaceBeforeEos: modelJinjaTemplate.includes("' ' + eos_token")
});
else if (modelJinjaTemplate.includes("<|start_header_id|>") && modelJinjaTemplate.includes("<|end_header_id|>")) {
if (Llama3_1ChatWrapper._checkModelCompatibility({tokenizer, fileInfo}))
return createSpecializedChatWrapper(Llama3_1ChatWrapper);
else
return createSpecializedChatWrapper(Llama3ChatWrapper);
} else if (modelJinjaTemplate.includes("<start_of_turn>"))
return createSpecializedChatWrapper(GemmaChatWrapper);
}
if (filename != null) {
const {name, subType, fileType, otherInfo} = parseModelFileName(filename);
if (fileType?.toLowerCase() === "gguf") {
const lowercaseName = name?.toLowerCase();
const lowercaseSubType = subType?.toLowerCase();
const splitLowercaseSubType = (lowercaseSubType?.split("-") ?? []).concat(
otherInfo.map((info) => info.toLowerCase())
);
const firstSplitLowercaseSubType = splitLowercaseSubType[0];
if (lowercaseName === "llama") {
if (splitLowercaseSubType.includes("chat"))
return createSpecializedChatWrapper(Llama2ChatWrapper);
return createSpecializedChatWrapper(GeneralChatWrapper);
} else if (lowercaseName === "codellama")
return createSpecializedChatWrapper(GeneralChatWrapper);
else if (lowercaseName === "yarn" && firstSplitLowercaseSubType === "llama")
return createSpecializedChatWrapper(Llama2ChatWrapper);
else if (lowercaseName === "orca")
return createSpecializedChatWrapper(ChatMLChatWrapper);
else if (lowercaseName === "phind" && lowercaseSubType === "codellama")
return createSpecializedChatWrapper(Llama2ChatWrapper);
else if (lowercaseName === "mistral")
return createSpecializedChatWrapper(GeneralChatWrapper);
else if (firstSplitLowercaseSubType === "llama")
return createSpecializedChatWrapper(Llama2ChatWrapper);
else if (lowercaseSubType === "alpaca")
return createSpecializedChatWrapper(AlpacaChatWrapper);
else if (lowercaseName === "functionary")
return createSpecializedChatWrapper(FunctionaryChatWrapper);
else if (lowercaseName === "dolphin" && splitLowercaseSubType.includes("mistral"))
return createSpecializedChatWrapper(ChatMLChatWrapper);
else if (lowercaseName === "gemma") {
if (firstSplitLowercaseSubType === "4")
return createSpecializedChatWrapper(Gemma4ChatWrapper);
return createSpecializedChatWrapper(GemmaChatWrapper);
} else if (splitLowercaseSubType.includes("chatml"))
return createSpecializedChatWrapper(ChatMLChatWrapper);
}
}
if (bosString !== "" && bosString != null) {
if ("<s>[INST] <<SYS>>\n".startsWith(bosString)) {
return createSpecializedChatWrapper(Llama2ChatWrapper);
} else if ("<|im_start|>system\n".startsWith(bosString)) {
return createSpecializedChatWrapper(ChatMLChatWrapper);
}
}
if (fileInfo != null) {
const arch = fileInfo.metadata.general?.architecture;
if (arch === "llama")
return createSpecializedChatWrapper(GeneralChatWrapper);
else if (arch === "falcon")
return createSpecializedChatWrapper(FalconChatWrapper);
else if (arch === "gemma" || arch === "gemma2")
return createSpecializedChatWrapper(GemmaChatWrapper);
else if (arch === "gemma4")
return createSpecializedChatWrapper(Gemma4ChatWrapper);
}
return null;
}
export function isSpecializedChatWrapperType(type: string): type is SpecializedChatWrapperTypeName {
return specializedChatWrapperTypeNames.includes(type as any);
}
export function isTemplateChatWrapperType(type: string): type is TemplateChatWrapperTypeName {
return templateChatWrapperTypeNames.includes(type as any);
}
// this is needed because TypeScript guards don't work automatically with class references
function isClassReference<T>(value: any, classReference: T): value is T {
return value === classReference;
}
function orderChatWrapperNamesByAssumedCompatibilityWithModel<T extends ResolvableChatWrapperTypeName>(chatWrapperNames: readonly T[], {
filename, fileInfo
}: {
filename?: string,
fileInfo?: GgufFileInfo
}): readonly T[] {
const rankPoints = {
modelName: 3,
modelNamePosition: 4,
fileName: 2,
fileNamePosition: 3
} as const;
function getPointsForTextMatch(pattern: string, fullText: string | undefined, existsPoints: number, positionPoints: number) {
if (fullText == null)
return 0;
const index = fullText.toLowerCase().indexOf(pattern.toLowerCase());
if (index >= 0)
return existsPoints + (((index + 1) / fullText.length) * positionPoints);
return 0;
}
function getPointsForWrapperName(wrapperName: T, fullText: string | undefined, existsPoints: number, positionPoints: number) {
const additionalNames = specializedChatWrapperRelatedTexts[wrapperName as keyof typeof specializedChatWrapperRelatedTexts] ?? [];
return [wrapperName, ...additionalNames]
.map((pattern) => getPointsForTextMatch(pattern, fullText, existsPoints, positionPoints))
.reduce((res, item) => Math.max(res, item), 0);
}
const modelName = fileInfo?.metadata?.general?.name;
return chatWrapperNames
.slice()
.sort((a, b) => {
let aPoints = 0;
let bPoints = 0;
aPoints += getPointsForWrapperName(a, modelName, rankPoints.modelName, rankPoints.modelNamePosition);
bPoints += getPointsForWrapperName(b, modelName, rankPoints.modelName, rankPoints.modelNamePosition);
aPoints += getPointsForWrapperName(a, filename, rankPoints.fileName, rankPoints.fileNamePosition);
bPoints += getPointsForWrapperName(b, filename, rankPoints.fileName, rankPoints.fileNamePosition);
return bPoints - aPoints;
});
}