-
-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathLlama3_1ChatWrapper.ts
More file actions
393 lines (338 loc) · 15.4 KB
/
Llama3_1ChatWrapper.ts
File metadata and controls
393 lines (338 loc) · 15.4 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
import {ChatWrapper, ChatWrapperJinjaMatchConfiguration} from "../ChatWrapper.js";
import {
ChatHistoryItem, ChatModelFunctions, ChatSystemMessage, ChatWrapperCheckModelCompatibilityParams,
ChatWrapperGenerateContextStateOptions, ChatWrapperGeneratedContextState, ChatWrapperSettings
} from "../types.js";
import {SpecialToken, LlamaText, SpecialTokensText} from "../utils/LlamaText.js";
import {ChatModelFunctionsDocumentationGenerator} from "./utils/ChatModelFunctionsDocumentationGenerator.js";
import {jsonDumps} from "./utils/jsonDumps.js";
import {isLlama3_2LightweightModel} from "./utils/isLlama3_2LightweightModel.js";
// source: https://llama.meta.com/docs/model-cards-and-prompt-formats/llama3_1
export class Llama3_1ChatWrapper extends ChatWrapper {
public readonly wrapperName: string = "Llama 3.1";
public readonly cuttingKnowledgeDate?: Date | (() => Date) | null;
public readonly todayDate: Date | (() => Date) | null;
public readonly noToolInstructions: boolean;
/** @internal */ private readonly _specialTokensTextForPreamble: boolean;
public override readonly settings: ChatWrapperSettings = {
supportsSystemMessages: true,
functions: {
call: {
optionalPrefixSpace: true,
prefix: LlamaText(new SpecialTokensText("<function=")),
paramsPrefix: LlamaText(new SpecialTokensText(">")),
suffix: LlamaText(new SpecialTokensText("</function><|eom_id|>"))
},
result: {
prefix: LlamaText(new SpecialTokensText("\n<|start_header_id|>ipython<|end_header_id|>\n\n")),
suffix: LlamaText(new SpecialToken("EOT"), new SpecialTokensText("<|start_header_id|>assistant<|end_header_id|>\n\n"))
}
}
};
public constructor(options: {
/**
* Set to `null` to disable
*
* Defaults to December 2023
*/
cuttingKnowledgeDate?: Date | (() => Date) | number | string | null,
/**
* Set to `null` to disable
*
* Defaults to current date
*/
todayDate?: Date | (() => Date) | number | string | null,
noToolInstructions?: boolean,
/** @internal */
_specialTokensTextForPreamble?: boolean
} = {}) {
super();
const {
cuttingKnowledgeDate = new Date("2023-12-01T00:00:00Z"),
todayDate = () => new Date(),
noToolInstructions = false,
_specialTokensTextForPreamble = false
} = options;
this.cuttingKnowledgeDate = cuttingKnowledgeDate == null
? null
: cuttingKnowledgeDate instanceof Function
? cuttingKnowledgeDate
: new Date(cuttingKnowledgeDate);
this.todayDate = todayDate == null
? null
: todayDate instanceof Function
? todayDate
: new Date(todayDate);
this.noToolInstructions = noToolInstructions;
this._specialTokensTextForPreamble = _specialTokensTextForPreamble;
}
public override addAvailableFunctionsSystemMessageToHistory(
history: readonly ChatHistoryItem[],
availableFunctions?: ChatModelFunctions, {
documentParams = true
}: {
documentParams?: boolean
} = {}
) {
const availableFunctionNames = Object.keys(availableFunctions ?? {});
if (availableFunctions == null || availableFunctionNames.length === 0)
return history;
const res = history.slice();
const functionsSystemMessage: ChatSystemMessage = {
type: "system",
text: this.generateAvailableFunctionsSystemText(availableFunctions, {documentParams}).toJSON()
};
if (res.length >= 2 && res[0]!.type === "system" && res[1]!.type === "system")
res.splice(1, 0, functionsSystemMessage);
else
res.unshift({
type: "system",
text: this.generateAvailableFunctionsSystemText(availableFunctions, {documentParams}).toJSON()
});
return res;
}
public override generateContextState({
chatHistory, availableFunctions, documentFunctionParams
}: ChatWrapperGenerateContextStateOptions): ChatWrapperGeneratedContextState {
const chatHistoryWithPreamble = this.prependPreambleToChatHistory(chatHistory);
const historyWithFunctions = this.addAvailableFunctionsSystemMessageToHistory(chatHistoryWithPreamble, availableFunctions, {
documentParams: documentFunctionParams
});
const resultItems: Array<{
system: LlamaText | null,
user: LlamaText | null,
model: LlamaText | null
}> = [];
let systemTexts: LlamaText[] = [];
let userTexts: LlamaText[] = [];
let modelTexts: LlamaText[] = [];
let currentAggregateFocus: "system" | "user" | "model" | null = null;
const flush = () => {
if (systemTexts.length > 0 || userTexts.length > 0 || modelTexts.length > 0)
resultItems.push({
system: systemTexts.length === 0
? null
: LlamaText.joinValues(
resultItems.length === 0 && this._specialTokensTextForPreamble
? LlamaText(new SpecialTokensText("\n\n"))
: "\n\n",
systemTexts
),
user: userTexts.length === 0
? null
: LlamaText.joinValues("\n\n", userTexts),
model: modelTexts.length === 0
? null
: LlamaText.joinValues("\n\n", modelTexts)
});
systemTexts = [];
userTexts = [];
modelTexts = [];
};
for (const item of historyWithFunctions) {
if (item.type === "system") {
if (currentAggregateFocus !== "system")
flush();
currentAggregateFocus = "system";
systemTexts.push(LlamaText.fromJSON(item.text));
} else if (item.type === "user") {
if (currentAggregateFocus !== "user")
flush();
currentAggregateFocus = "user";
userTexts.push(LlamaText(item.text));
} else if (item.type === "model") {
if (currentAggregateFocus !== "model")
flush();
currentAggregateFocus = "model";
modelTexts.push(this.generateModelResponseText(item.response));
} else
void (item satisfies never);
}
flush();
const contextText = LlamaText(
new SpecialToken("BOS"),
resultItems.map((item, index) => {
const isLastItem = index === resultItems.length - 1;
const res: LlamaText[] = [];
if (item.system != null) {
res.push(
LlamaText([
new SpecialTokensText("<|start_header_id|>system<|end_header_id|>\n\n"),
item.system,
new SpecialToken("EOT")
])
);
}
if (item.user != null) {
res.push(
LlamaText([
new SpecialTokensText("<|start_header_id|>user<|end_header_id|>\n\n"),
item.user,
new SpecialToken("EOT")
])
);
}
if (item.model != null) {
res.push(
LlamaText([
new SpecialTokensText("<|start_header_id|>assistant<|end_header_id|>\n\n"),
item.model,
isLastItem
? LlamaText([])
: new SpecialToken("EOT")
])
);
}
return LlamaText(res);
})
);
return {
contextText,
stopGenerationTriggers: [
LlamaText(new SpecialToken("EOS")),
LlamaText(new SpecialToken("EOT")),
LlamaText(new SpecialTokensText("<|eot_id|>")),
LlamaText(new SpecialTokensText("<|end_of_text|>")),
LlamaText("<|eot_id|>"),
LlamaText("<|end_of_text|>")
]
};
}
public override generateAvailableFunctionsSystemText(availableFunctions: ChatModelFunctions, {documentParams = true}: {
documentParams?: boolean
}) {
const functionsDocumentationGenerator = new ChatModelFunctionsDocumentationGenerator(availableFunctions);
if (!functionsDocumentationGenerator.hasAnyFunctions)
return LlamaText([]);
return LlamaText.joinValues("\n", [
"You have access to the following functions:",
"",
functionsDocumentationGenerator.getLlama3_1FunctionSignatures({documentParams}),
"",
"",
"If you choose to call a function ONLY reply in the following format:",
"<{start_tag}={function_name}>{parameters}{end_tag}",
"where",
"",
"start_tag => `<function`",
"parameters => a JSON dict with the function argument name as key and function argument value as value.",
"end_tag => `</function>`",
"",
"Here is an example,",
LlamaText([
new SpecialTokensText("<function="),
"example_function_name",
new SpecialTokensText(">"),
jsonDumps({"example_name": "example_value"}),
new SpecialTokensText("</function>")
]),
"",
"Reminder:",
"- Function calls MUST follow the specified format",
"- Only call one function at a time",
"- Put the entire function call reply on one line",
"- Always add your sources when using search results to answer the user query",
"- After calling a function, the result will appear afterwards and is only visible to you",
"- To make information visible to the user, you must include it in your response",
"- Do not tell the user about the functions you are using",
"- Only call functions when needed"
]);
}
public prependPreambleToChatHistory(chatHistory: readonly ChatHistoryItem[]): readonly ChatHistoryItem[] {
const res = chatHistory.slice();
const formatMonthDate = (date: Date, timezone?: "UTC") => {
const today = this.todayDate instanceof Function
? this.todayDate()
: (this.todayDate ?? new Date());
if (today.getUTCMonth() === date.getUTCMonth() && today.getUTCFullYear() === date.getUTCFullYear())
return formatDate(date, timezone);
const month = date.toLocaleDateString("en-US", {month: "long", timeZone: timezone});
const year = date.toLocaleDateString("en-US", {year: "numeric", timeZone: timezone});
return `${month} ${year}`;
};
const lines: string[] = [];
if (this.cuttingKnowledgeDate != null) {
const date = this.cuttingKnowledgeDate instanceof Function
? this.cuttingKnowledgeDate()
: this.cuttingKnowledgeDate;
lines.push(`Cutting Knowledge Date: ${formatMonthDate(date, "UTC")}`);
}
if (this.todayDate != null) {
const date = this.todayDate instanceof Function
? this.todayDate()
: this.todayDate;
lines.push(`Today Date: ${formatDate(date, undefined)}`);
}
if (!this.noToolInstructions) {
if (lines.length > 0)
lines.push("");
lines.push("# Tool Instructions");
lines.push("- When looking for real time information use relevant functions if available");
lines.push("");
lines.push("");
}
if (lines.length > 0)
res.unshift({
type: "system",
text: this._specialTokensTextForPreamble
? LlamaText(new SpecialTokensText(lines.join("\n"))).toJSON()
: LlamaText.joinValues("\n", lines).toJSON()
});
return res;
}
/** @internal */
public static override _checkModelCompatibility(options: ChatWrapperCheckModelCompatibilityParams): boolean {
if (options.tokenizer != null) {
const tokens = options.tokenizer("<|eom_id|>", true, "trimLeadingSpace");
return tokens.length === 1 && options.tokenizer.isSpecialToken(tokens[0]!) && !isLlama3_2LightweightModel(options);
}
return !isLlama3_2LightweightModel(options);
}
/** @internal */
public static override _getOptionConfigurationsToTestIfCanSupersedeJinjaTemplate(): ChatWrapperJinjaMatchConfiguration<typeof this> {
return [
[{}, undefined, {functionCallMessageTemplate: "noJinja"}],
[{todayDate: null}, {}, {functionCallMessageTemplate: "noJinja"}],
[{cuttingKnowledgeDate: null}, {}, {functionCallMessageTemplate: "noJinja"}],
[{noToolInstructions: true}, {}, {functionCallMessageTemplate: "noJinja"}],
[{todayDate: null, cuttingKnowledgeDate: null}, {}, {functionCallMessageTemplate: "noJinja"}],
[{todayDate: null, cuttingKnowledgeDate: null, noToolInstructions: true}, {}, {functionCallMessageTemplate: "noJinja"}],
[
{todayDate: new Date("2024-07-26T00:00:00"), cuttingKnowledgeDate: null, noToolInstructions: true},
{},
{functionCallMessageTemplate: "noJinja"}
],
[
{
todayDate: new Date("2024-07-26T00:00:00"),
cuttingKnowledgeDate: new Date("2023-12-01T00:00:00Z"),
noToolInstructions: true
},
{cuttingKnowledgeDate: new Date("2023-12-01T00:00:00Z")},
{
additionalRenderParameters: {"date_string": formatDate(new Date("2024-07-26T00:00:00"), undefined)},
functionCallMessageTemplate: "noJinja"
}
],
[
{
todayDate: new Date("2024-07-26T00:00:00"),
cuttingKnowledgeDate: new Date("2023-12-01T00:00:00Z"),
noToolInstructions: true,
_specialTokensTextForPreamble: true
},
{cuttingKnowledgeDate: new Date("2023-12-01T00:00:00Z")},
{
additionalRenderParameters: {"date_string": formatDate(new Date("2024-07-26T00:00:00"), undefined)},
functionCallMessageTemplate: "noJinja"
}
]
];
}
}
function formatDate(date: Date, timezone?: "UTC") {
const day = date.toLocaleDateString("en-US", {day: "numeric", timeZone: timezone});
const month = date.toLocaleDateString("en-US", {month: "short", timeZone: timezone});
const year = date.toLocaleDateString("en-US", {year: "numeric", timeZone: timezone});
return `${day} ${month} ${year}`;
}