@librechat/agents 2.2.2 → 2.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/graphs/Graph.cjs +50 -14
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/main.cjs +3 -4
- package/dist/cjs/main.cjs.map +1 -1
- package/dist/cjs/messages/format.cjs +21 -0
- package/dist/cjs/messages/format.cjs.map +1 -1
- package/dist/cjs/messages/prune.cjs +124 -0
- package/dist/cjs/messages/prune.cjs.map +1 -0
- package/dist/cjs/run.cjs +24 -0
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/utils/tokens.cjs +64 -0
- package/dist/cjs/utils/tokens.cjs.map +1 -0
- package/dist/esm/graphs/Graph.mjs +50 -14
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -3
- package/dist/esm/main.mjs.map +1 -1
- package/dist/esm/messages/format.mjs +21 -1
- package/dist/esm/messages/format.mjs.map +1 -1
- package/dist/esm/messages/prune.mjs +122 -0
- package/dist/esm/messages/prune.mjs.map +1 -0
- package/dist/esm/run.mjs +24 -0
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/utils/tokens.mjs +62 -0
- package/dist/esm/utils/tokens.mjs.map +1 -0
- package/dist/types/graphs/Graph.d.ts +8 -1
- package/dist/types/messages/format.d.ts +9 -0
- package/dist/types/messages/index.d.ts +1 -2
- package/dist/types/messages/prune.d.ts +16 -0
- package/dist/types/types/run.d.ts +4 -0
- package/dist/types/utils/tokens.d.ts +2 -0
- package/package.json +1 -1
- package/src/graphs/Graph.ts +54 -16
- package/src/messages/format.ts +27 -0
- package/src/messages/index.ts +1 -2
- package/src/messages/prune.ts +167 -0
- package/src/messages/shiftIndexTokenCountMap.test.ts +81 -0
- package/src/run.ts +26 -0
- package/src/scripts/code_exec_simple.ts +21 -8
- package/src/specs/prune.test.ts +444 -0
- package/src/types/run.ts +5 -0
- package/src/utils/tokens.ts +70 -0
- package/dist/cjs/messages/transformers.cjs +0 -318
- package/dist/cjs/messages/transformers.cjs.map +0 -1
- package/dist/cjs/messages/trimMessagesFactory.cjs +0 -129
- package/dist/cjs/messages/trimMessagesFactory.cjs.map +0 -1
- package/dist/esm/messages/transformers.mjs +0 -316
- package/dist/esm/messages/transformers.mjs.map +0 -1
- package/dist/esm/messages/trimMessagesFactory.mjs +0 -127
- package/dist/esm/messages/trimMessagesFactory.mjs.map +0 -1
- package/dist/types/messages/transformers.d.ts +0 -320
- package/dist/types/messages/trimMessagesFactory.d.ts +0 -37
- package/src/messages/transformers.ts +0 -786
- package/src/messages/trimMessagesFactory.test.ts +0 -331
- package/src/messages/trimMessagesFactory.ts +0 -140
|
@@ -1,318 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var runnables = require('@langchain/core/runnables');
|
|
4
|
-
var messages = require('@langchain/core/messages');
|
|
5
|
-
|
|
6
|
-
const _isMessageType = (msg, types) => {
|
|
7
|
-
const typesAsStrings = [
|
|
8
|
-
...new Set(types?.map((t) => {
|
|
9
|
-
if (typeof t === "string") {
|
|
10
|
-
return t;
|
|
11
|
-
}
|
|
12
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
13
|
-
const instantiatedMsgClass = new t({});
|
|
14
|
-
if (!("getType" in instantiatedMsgClass) ||
|
|
15
|
-
typeof instantiatedMsgClass.getType !== "function") {
|
|
16
|
-
throw new Error("Invalid type provided.");
|
|
17
|
-
}
|
|
18
|
-
return instantiatedMsgClass.getType();
|
|
19
|
-
})),
|
|
20
|
-
];
|
|
21
|
-
const msgType = msg.getType();
|
|
22
|
-
return typesAsStrings.some((t) => t === msgType);
|
|
23
|
-
};
|
|
24
|
-
function trimMessages(messagesOrOptions, options) {
|
|
25
|
-
if (Array.isArray(messagesOrOptions)) {
|
|
26
|
-
const messages = messagesOrOptions;
|
|
27
|
-
if (!options) {
|
|
28
|
-
throw new Error("Options parameter is required when providing messages.");
|
|
29
|
-
}
|
|
30
|
-
return _trimMessagesHelper(messages, options);
|
|
31
|
-
}
|
|
32
|
-
else {
|
|
33
|
-
const trimmerOptions = messagesOrOptions;
|
|
34
|
-
return runnables.RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({
|
|
35
|
-
runName: "trim_messages",
|
|
36
|
-
});
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
async function _trimMessagesHelper(messages$1, options) {
|
|
40
|
-
const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter, } = options;
|
|
41
|
-
if (startOn && strategy === "first") {
|
|
42
|
-
throw new Error("`startOn` should only be specified if `strategy` is 'last'.");
|
|
43
|
-
}
|
|
44
|
-
if (includeSystem && strategy === "first") {
|
|
45
|
-
throw new Error("`includeSystem` should only be specified if `strategy` is 'last'.");
|
|
46
|
-
}
|
|
47
|
-
let listTokenCounter;
|
|
48
|
-
if ("getNumTokens" in tokenCounter) {
|
|
49
|
-
listTokenCounter = async (msgs) => {
|
|
50
|
-
const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content)));
|
|
51
|
-
return tokenCounts.reduce((sum, count) => sum + count, 0);
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
else {
|
|
55
|
-
listTokenCounter = async (msgs) => tokenCounter(msgs);
|
|
56
|
-
}
|
|
57
|
-
let textSplitterFunc = messages.defaultTextSplitter;
|
|
58
|
-
if (textSplitter) {
|
|
59
|
-
if ("splitText" in textSplitter) {
|
|
60
|
-
textSplitterFunc = textSplitter.splitText;
|
|
61
|
-
}
|
|
62
|
-
else {
|
|
63
|
-
textSplitterFunc = async (text) => textSplitter(text);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
if (strategy === "first") {
|
|
67
|
-
return _firstMaxTokens(messages$1, {
|
|
68
|
-
maxTokens,
|
|
69
|
-
tokenCounter: listTokenCounter,
|
|
70
|
-
textSplitter: textSplitterFunc,
|
|
71
|
-
partialStrategy: allowPartial ? "first" : undefined,
|
|
72
|
-
endOn,
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
else if (strategy === "last") {
|
|
76
|
-
return _lastMaxTokens(messages$1, {
|
|
77
|
-
maxTokens,
|
|
78
|
-
tokenCounter: listTokenCounter,
|
|
79
|
-
textSplitter: textSplitterFunc,
|
|
80
|
-
allowPartial,
|
|
81
|
-
includeSystem,
|
|
82
|
-
startOn,
|
|
83
|
-
endOn,
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
else {
|
|
87
|
-
throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`);
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
async function _firstMaxTokens(messages, options) {
|
|
91
|
-
const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options;
|
|
92
|
-
let messagesCopy = [...messages];
|
|
93
|
-
let idx = 0;
|
|
94
|
-
for (let i = 0; i < messagesCopy.length; i += 1) {
|
|
95
|
-
const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy;
|
|
96
|
-
if ((await tokenCounter(remainingMessages)) <= maxTokens) {
|
|
97
|
-
idx = messagesCopy.length - i;
|
|
98
|
-
break;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
if (idx < messagesCopy.length - 1 && partialStrategy) {
|
|
102
|
-
let includedPartial = false;
|
|
103
|
-
if (Array.isArray(messagesCopy[idx].content)) {
|
|
104
|
-
const excluded = messagesCopy[idx];
|
|
105
|
-
if (typeof excluded.content === "string") {
|
|
106
|
-
throw new Error("Expected content to be an array.");
|
|
107
|
-
}
|
|
108
|
-
const numBlock = excluded.content.length;
|
|
109
|
-
const reversedContent = partialStrategy === "last"
|
|
110
|
-
? [...excluded.content].reverse()
|
|
111
|
-
: excluded.content;
|
|
112
|
-
for (let i = 1; i <= numBlock; i += 1) {
|
|
113
|
-
const partialContent = partialStrategy === "first"
|
|
114
|
-
? reversedContent.slice(0, i)
|
|
115
|
-
: reversedContent.slice(-i);
|
|
116
|
-
const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_")));
|
|
117
|
-
const updatedMessage = _switchTypeToMessage(excluded.getType(), {
|
|
118
|
-
...fields,
|
|
119
|
-
content: partialContent,
|
|
120
|
-
});
|
|
121
|
-
const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage];
|
|
122
|
-
if ((await tokenCounter(slicedMessages)) <= maxTokens) {
|
|
123
|
-
messagesCopy = slicedMessages;
|
|
124
|
-
idx += 1;
|
|
125
|
-
includedPartial = true;
|
|
126
|
-
}
|
|
127
|
-
else {
|
|
128
|
-
break;
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
if (includedPartial && partialStrategy === "last") {
|
|
132
|
-
excluded.content = [...reversedContent].reverse();
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
if (!includedPartial) {
|
|
136
|
-
const excluded = messagesCopy[idx];
|
|
137
|
-
let text;
|
|
138
|
-
if (Array.isArray(excluded.content) &&
|
|
139
|
-
excluded.content.some((block) => typeof block === "string" || block.type === "text")) {
|
|
140
|
-
const textBlock = excluded.content.find((block) => block.type === "text" && block.text);
|
|
141
|
-
text = textBlock?.text;
|
|
142
|
-
}
|
|
143
|
-
else if (typeof excluded.content === "string") {
|
|
144
|
-
text = excluded.content;
|
|
145
|
-
}
|
|
146
|
-
if (text) {
|
|
147
|
-
const splitTexts = await textSplitter(text);
|
|
148
|
-
const numSplits = splitTexts.length;
|
|
149
|
-
if (partialStrategy === "last") {
|
|
150
|
-
splitTexts.reverse();
|
|
151
|
-
}
|
|
152
|
-
for (let _ = 0; _ < numSplits - 1; _ += 1) {
|
|
153
|
-
splitTexts.pop();
|
|
154
|
-
excluded.content = splitTexts.join("");
|
|
155
|
-
if ((await tokenCounter([...messagesCopy.slice(0, idx), excluded])) <=
|
|
156
|
-
maxTokens) {
|
|
157
|
-
if (partialStrategy === "last") {
|
|
158
|
-
excluded.content = [...splitTexts].reverse().join("");
|
|
159
|
-
}
|
|
160
|
-
messagesCopy = [...messagesCopy.slice(0, idx), excluded];
|
|
161
|
-
idx += 1;
|
|
162
|
-
break;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
if (endOn) {
|
|
169
|
-
const endOnArr = Array.isArray(endOn) ? endOn : [endOn];
|
|
170
|
-
while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) {
|
|
171
|
-
idx -= 1;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
return messagesCopy.slice(0, idx);
|
|
175
|
-
}
|
|
176
|
-
async function _lastMaxTokens(messages$1, options) {
|
|
177
|
-
const { allowPartial = false, includeSystem = false, endOn, startOn, ...rest } = options;
|
|
178
|
-
// Create a copy of messages to avoid mutation
|
|
179
|
-
let messagesCopy = messages$1.map((message) => {
|
|
180
|
-
const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_")));
|
|
181
|
-
return _switchTypeToMessage(message.getType(), fields, messages.isBaseMessageChunk(message));
|
|
182
|
-
});
|
|
183
|
-
if (endOn) {
|
|
184
|
-
const endOnArr = Array.isArray(endOn) ? endOn : [endOn];
|
|
185
|
-
while (messagesCopy.length > 0 &&
|
|
186
|
-
!_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) {
|
|
187
|
-
messagesCopy = messagesCopy.slice(0, -1);
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system";
|
|
191
|
-
let reversed_ = swappedSystem
|
|
192
|
-
? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse())
|
|
193
|
-
: messagesCopy.reverse();
|
|
194
|
-
reversed_ = await _firstMaxTokens(reversed_, {
|
|
195
|
-
...rest,
|
|
196
|
-
partialStrategy: allowPartial ? "last" : undefined,
|
|
197
|
-
endOn: startOn,
|
|
198
|
-
});
|
|
199
|
-
if (swappedSystem) {
|
|
200
|
-
return [reversed_[0], ...reversed_.slice(1).reverse()];
|
|
201
|
-
}
|
|
202
|
-
else {
|
|
203
|
-
return reversed_.reverse();
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
function _switchTypeToMessage(messageType, fields, returnChunk) {
|
|
207
|
-
let chunk;
|
|
208
|
-
let msg;
|
|
209
|
-
switch (messageType) {
|
|
210
|
-
case "human":
|
|
211
|
-
if (returnChunk) {
|
|
212
|
-
chunk = new messages.HumanMessageChunk(fields);
|
|
213
|
-
}
|
|
214
|
-
else {
|
|
215
|
-
msg = new messages.HumanMessage(fields);
|
|
216
|
-
}
|
|
217
|
-
break;
|
|
218
|
-
case "ai":
|
|
219
|
-
if (returnChunk) {
|
|
220
|
-
let aiChunkFields = {
|
|
221
|
-
...fields,
|
|
222
|
-
};
|
|
223
|
-
if ("tool_calls" in aiChunkFields) {
|
|
224
|
-
aiChunkFields = {
|
|
225
|
-
...aiChunkFields,
|
|
226
|
-
tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({
|
|
227
|
-
...tc,
|
|
228
|
-
type: "tool_call_chunk",
|
|
229
|
-
index: undefined,
|
|
230
|
-
args: JSON.stringify(tc.args),
|
|
231
|
-
})),
|
|
232
|
-
};
|
|
233
|
-
}
|
|
234
|
-
chunk = new messages.AIMessageChunk(aiChunkFields);
|
|
235
|
-
}
|
|
236
|
-
else {
|
|
237
|
-
msg = new messages.AIMessage(fields);
|
|
238
|
-
}
|
|
239
|
-
break;
|
|
240
|
-
case "system":
|
|
241
|
-
if (returnChunk) {
|
|
242
|
-
chunk = new messages.SystemMessageChunk(fields);
|
|
243
|
-
}
|
|
244
|
-
else {
|
|
245
|
-
msg = new messages.SystemMessage(fields);
|
|
246
|
-
}
|
|
247
|
-
break;
|
|
248
|
-
case "developer":
|
|
249
|
-
if (returnChunk) {
|
|
250
|
-
chunk = new messages.SystemMessageChunk({
|
|
251
|
-
...fields,
|
|
252
|
-
additional_kwargs: {
|
|
253
|
-
...fields.additional_kwargs,
|
|
254
|
-
__openai_role__: "developer",
|
|
255
|
-
},
|
|
256
|
-
});
|
|
257
|
-
}
|
|
258
|
-
else {
|
|
259
|
-
msg = new messages.SystemMessage({
|
|
260
|
-
...fields,
|
|
261
|
-
additional_kwargs: {
|
|
262
|
-
...fields.additional_kwargs,
|
|
263
|
-
__openai_role__: "developer",
|
|
264
|
-
},
|
|
265
|
-
});
|
|
266
|
-
}
|
|
267
|
-
break;
|
|
268
|
-
case "tool":
|
|
269
|
-
if ("tool_call_id" in fields) {
|
|
270
|
-
if (returnChunk) {
|
|
271
|
-
chunk = new messages.ToolMessageChunk(fields);
|
|
272
|
-
}
|
|
273
|
-
else {
|
|
274
|
-
msg = new messages.ToolMessage(fields);
|
|
275
|
-
}
|
|
276
|
-
}
|
|
277
|
-
else {
|
|
278
|
-
throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.");
|
|
279
|
-
}
|
|
280
|
-
break;
|
|
281
|
-
case "function":
|
|
282
|
-
if (returnChunk) {
|
|
283
|
-
chunk = new messages.FunctionMessageChunk(fields);
|
|
284
|
-
}
|
|
285
|
-
else {
|
|
286
|
-
if (!fields.name) {
|
|
287
|
-
throw new Error("FunctionMessage must have a 'name' field");
|
|
288
|
-
}
|
|
289
|
-
msg = new messages.FunctionMessage(fields);
|
|
290
|
-
}
|
|
291
|
-
break;
|
|
292
|
-
case "generic":
|
|
293
|
-
if ("role" in fields) {
|
|
294
|
-
if (returnChunk) {
|
|
295
|
-
chunk = new messages.ChatMessageChunk(fields);
|
|
296
|
-
}
|
|
297
|
-
else {
|
|
298
|
-
msg = new messages.ChatMessage(fields);
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
else {
|
|
302
|
-
throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.");
|
|
303
|
-
}
|
|
304
|
-
break;
|
|
305
|
-
default:
|
|
306
|
-
throw new Error(`Unrecognized message type ${messageType}`);
|
|
307
|
-
}
|
|
308
|
-
if (returnChunk && chunk) {
|
|
309
|
-
return chunk;
|
|
310
|
-
}
|
|
311
|
-
if (msg) {
|
|
312
|
-
return msg;
|
|
313
|
-
}
|
|
314
|
-
throw new Error(`Unrecognized message type ${messageType}`);
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
exports.trimMessages = trimMessages;
|
|
318
|
-
//# sourceMappingURL=transformers.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"transformers.cjs","sources":["../../../src/messages/transformers.ts"],"sourcesContent":["import { Runnable, RunnableLambda } from \"@langchain/core/runnables\";\nimport type { BaseDocumentTransformer } from \"@langchain/core/documents\";\nimport type { BaseLanguageModel } from \"@langchain/core/language_models/base\";\nimport {\n AIMessage,\n ToolMessage,\n ChatMessage,\n HumanMessage,\n SystemMessage,\n AIMessageChunk,\n FunctionMessage,\n ChatMessageChunk,\n ToolMessageChunk,\n HumanMessageChunk,\n SystemMessageChunk,\n isBaseMessageChunk,\n defaultTextSplitter,\n FunctionMessageChunk,\n} from \"@langchain/core/messages\";\nimport type {\n BaseMessage,\n MessageType,\n BaseMessageChunk,\n BaseMessageFields,\n MessageTypeOrClass,\n AIMessageChunkFields,\n ChatMessageFieldsWithRole,\n FunctionMessageFieldsWithName,\n ToolMessageFieldsWithToolCallId,\n} from \"@langchain/core/messages\";\n\nconst _isMessageType = (msg: BaseMessage, types: MessageTypeOrClass[]) => {\n const typesAsStrings = [\n ...new Set<string>(\n types?.map((t) => {\n if (typeof t === \"string\") {\n return t;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const instantiatedMsgClass = new (t as any)({});\n if (\n !(\"getType\" in instantiatedMsgClass) ||\n typeof instantiatedMsgClass.getType !== \"function\"\n ) {\n throw new Error(\"Invalid type provided.\");\n }\n return instantiatedMsgClass.getType();\n })\n ),\n ];\n const msgType = msg.getType();\n return typesAsStrings.some((t) => t === msgType);\n};\n\n// Since we can not import from `@langchain/textsplitters` we need\n// to reconstruct the interface here.\ninterface _TextSplitterInterface extends BaseDocumentTransformer {\n splitText(text: string): Promise<string[]>;\n}\n\nexport interface TrimMessagesFields {\n /**\n * @param {number} maxTokens Max token count of trimmed messages.\n */\n maxTokens: number;\n /**\n * @param {((messages: BaseMessage[]) => number) | ((messages: BaseMessage[]) => Promise<number>) | BaseLanguageModel} tokenCounter\n * Function or LLM for counting tokens in an array of `BaseMessage`s.\n * If a `BaseLanguageModel` is passed in then `BaseLanguageModel.getNumTokens()` will be used.\n */\n tokenCounter:\n | ((messages: BaseMessage[]) => number)\n | ((messages: BaseMessage[]) => Promise<number>)\n | BaseLanguageModel;\n /**\n * @param {\"first\" | \"last\"} [strategy=\"last\"] Strategy for trimming.\n * - \"first\": Keep the first <= n_count tokens of the messages.\n * - \"last\": Keep the last <= n_count tokens of the messages.\n * @default \"last\"\n */\n strategy?: \"first\" | \"last\";\n /**\n * @param {boolean} [allowPartial=false] Whether to split a message if only part of the message can be included.\n * If `strategy: \"last\"` then the last partial contents of a message are included.\n * If `strategy: \"first\"` then the first partial contents of a message are included.\n * @default false\n */\n allowPartial?: boolean;\n /**\n * @param {MessageTypeOrClass | MessageTypeOrClass[]} [endOn] The message type to end on.\n * If specified then every message after the last occurrence of this type is ignored.\n * If `strategy === \"last\"` then this is done before we attempt to get the last `maxTokens`.\n * If `strategy === \"first\"` then this is done after we get the first `maxTokens`.\n * Can be specified as string names (e.g. \"system\", \"human\", \"ai\", ...) or as `BaseMessage` classes\n * (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...). Can be a single type or an array of types.\n */\n endOn?: MessageTypeOrClass | MessageTypeOrClass[];\n /**\n * @param {MessageTypeOrClass | MessageTypeOrClass[]} [startOn] The message type to start on.\n * Should only be specified if `strategy: \"last\"`. If specified then every message before the first occurrence\n * of this type is ignored. This is done after we trim the initial messages to the last `maxTokens`.\n * Does not apply to a `SystemMessage` at index 0 if `includeSystem: true`.\n * Can be specified as string names (e.g. \"system\", \"human\", \"ai\", ...) or as `BaseMessage` classes\n * (e.g. `SystemMessage`, `HumanMessage`, `AIMessage`, ...). Can be a single type or an array of types.\n */\n startOn?: MessageTypeOrClass | MessageTypeOrClass[];\n /**\n * @param {boolean} [includeSystem=false] Whether to keep the `SystemMessage` if there is one at index 0.\n * Should only be specified if `strategy: \"last\"`.\n * @default false\n */\n includeSystem?: boolean;\n /**\n * @param {((text: string) => string[]) | BaseDocumentTransformer} [textSplitter] Function or `BaseDocumentTransformer` for\n * splitting the string contents of a message. Only used if `allowPartial: true`.\n * If `strategy: \"last\"` then the last split tokens from a partial message will be included.\n * If `strategy: \"first\"` then the first split tokens from a partial message will be included.\n * Token splitter assumes that separators are kept, so that split contents can be directly concatenated\n * to recreate the original text. Defaults to splitting on newlines.\n */\n textSplitter?:\n | ((text: string) => string[])\n | ((text: string) => Promise<string[]>)\n | _TextSplitterInterface;\n}\n\n/**\n * Trim messages to be below a token count.\n *\n * @param {BaseMessage[]} messages Array of `BaseMessage` instances to trim.\n * @param {TrimMessagesFields} options Trimming options.\n * @returns An array of trimmed `BaseMessage`s or a `Runnable` that takes a sequence of `BaseMessage`-like objects and returns\n * an array of trimmed `BaseMessage`s.\n * @throws {Error} If two incompatible arguments are specified or an unrecognized `strategy` is specified.\n *\n * @example\n * ```typescript\n * import { trimMessages, AIMessage, BaseMessage, HumanMessage, SystemMessage } from \"@langchain/core/messages\";\n *\n * const messages = [\n * new SystemMessage(\"This is a 4 token text. The full message is 10 tokens.\"),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"first\",\n * }),\n * new AIMessage({\n * content: [\n * { type: \"text\", text: \"This is the FIRST 4 token block.\" },\n * { type: \"text\", text: \"This is the SECOND 4 token block.\" },\n * ],\n * id: \"second\",\n * }),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"third\",\n * }),\n * new AIMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"fourth\",\n * }),\n * ];\n *\n * function dummyTokenCounter(messages: BaseMessage[]): number {\n * // treat each message like it adds 3 default tokens at the beginning\n * // of the message and at the end of the message. 3 + 4 + 3 = 10 tokens\n * // per message.\n *\n * const defaultContentLen = 4;\n * const defaultMsgPrefixLen = 3;\n * const defaultMsgSuffixLen = 3;\n *\n * let count = 0;\n * for (const msg of messages) {\n * if (typeof msg.content === \"string\") {\n * count += defaultMsgPrefixLen + defaultContentLen + defaultMsgSuffixLen;\n * }\n * if (Array.isArray(msg.content)) {\n * count +=\n * defaultMsgPrefixLen +\n * msg.content.length * defaultContentLen +\n * defaultMsgSuffixLen;\n * }\n * }\n * return count;\n * }\n * ```\n *\n * First 30 tokens, not allowing partial messages:\n * ```typescript\n * await trimMessages(messages, {\n * maxTokens: 30,\n * tokenCounter: dummyTokenCounter,\n * strategy: \"first\",\n * });\n * ```\n *\n * Output:\n * ```typescript\n * [\n * new SystemMessage(\n * \"This is a 4 token text. The full message is 10 tokens.\"\n * ),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"first\",\n * }),\n * ]\n * ```\n *\n * First 30 tokens, allowing partial messages:\n * ```typescript\n * await trimMessages(messages, {\n * maxTokens: 30,\n * tokenCounter: dummyTokenCounter,\n * strategy: \"first\",\n * allowPartial: true,\n * });\n * ```\n *\n * Output:\n * ```typescript\n * [\n * new SystemMessage(\n * \"This is a 4 token text. The full message is 10 tokens.\"\n * ),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"first\",\n * }),\n * new AIMessage({\n * content: [{ type: \"text\", text: \"This is the FIRST 4 token block.\" }],\n * id: \"second\",\n * }),\n * ]\n * ```\n *\n * First 30 tokens, allowing partial messages, have to end on HumanMessage:\n * ```typescript\n * await trimMessages(messages, {\n * maxTokens: 30,\n * tokenCounter: dummyTokenCounter,\n * strategy: \"first\",\n * allowPartial: true,\n * endOn: \"human\",\n * });\n * ```\n *\n * Output:\n * ```typescript\n * [\n * new SystemMessage(\n * \"This is a 4 token text. The full message is 10 tokens.\"\n * ),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"first\",\n * }),\n * ]\n * ```\n *\n * Last 30 tokens, including system message, not allowing partial messages:\n * ```typescript\n * await trimMessages(messages, {\n * maxTokens: 30,\n * includeSystem: true,\n * tokenCounter: dummyTokenCounter,\n * strategy: \"last\",\n * });\n * ```\n *\n * Output:\n * ```typescript\n * [\n * new SystemMessage(\n * \"This is a 4 token text. The full message is 10 tokens.\"\n * ),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"third\",\n * }),\n * new AIMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"fourth\",\n * }),\n * ]\n * ```\n *\n * Last 40 tokens, including system message, allowing partial messages:\n * ```typescript\n * await trimMessages(messages, {\n * maxTokens: 40,\n * tokenCounter: dummyTokenCounter,\n * strategy: \"last\",\n * allowPartial: true,\n * includeSystem: true,\n * });\n * ```\n *\n * Output:\n * ```typescript\n * [\n * new SystemMessage(\n * \"This is a 4 token text. The full message is 10 tokens.\"\n * ),\n * new AIMessage({\n * content: [{ type: \"text\", text: \"This is the FIRST 4 token block.\" }],\n * id: \"second\",\n * }),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"third\",\n * }),\n * new AIMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"fourth\",\n * }),\n * ]\n * ```\n *\n * Last 30 tokens, including system message, allowing partial messages, end on HumanMessage:\n * ```typescript\n * await trimMessages(messages, {\n * maxTokens: 30,\n * tokenCounter: dummyTokenCounter,\n * strategy: \"last\",\n * endOn: \"human\",\n * includeSystem: true,\n * allowPartial: true,\n * });\n * ```\n *\n * Output:\n * ```typescript\n * [\n * new SystemMessage(\n * \"This is a 4 token text. The full message is 10 tokens.\"\n * ),\n * new AIMessage({\n * content: [{ type: \"text\", text: \"This is the FIRST 4 token block.\" }],\n * id: \"second\",\n * }),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"third\",\n * }),\n * ]\n * ```\n *\n * Last 40 tokens, including system message, allowing partial messages, start on HumanMessage:\n * ```typescript\n * await trimMessages(messages, {\n * maxTokens: 40,\n * tokenCounter: dummyTokenCounter,\n * strategy: \"last\",\n * includeSystem: true,\n * allowPartial: true,\n * startOn: \"human\",\n * });\n * ```\n *\n * Output:\n * ```typescript\n * [\n * new SystemMessage(\n * \"This is a 4 token text. The full message is 10 tokens.\"\n * ),\n * new HumanMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"third\",\n * }),\n * new AIMessage({\n * content: \"This is a 4 token text. The full message is 10 tokens.\",\n * id: \"fourth\",\n * }),\n * ]\n * ```\n */\nexport function trimMessages(\n options: TrimMessagesFields\n): Runnable<BaseMessage[], BaseMessage[]>;\nexport function trimMessages(\n messages: BaseMessage[],\n options: TrimMessagesFields\n): Promise<BaseMessage[]>;\nexport function trimMessages(\n messagesOrOptions: BaseMessage[] | TrimMessagesFields,\n options?: TrimMessagesFields\n): Promise<BaseMessage[]> | Runnable<BaseMessage[], BaseMessage[]> {\n if (Array.isArray(messagesOrOptions)) {\n const messages = messagesOrOptions;\n if (!options) {\n throw new Error(\"Options parameter is required when providing messages.\");\n }\n return _trimMessagesHelper(messages, options);\n } else {\n const trimmerOptions = messagesOrOptions;\n return RunnableLambda.from((input: BaseMessage[]) =>\n _trimMessagesHelper(input, trimmerOptions)\n ).withConfig({\n runName: \"trim_messages\",\n });\n }\n}\n\nasync function _trimMessagesHelper(\n messages: BaseMessage[],\n options: TrimMessagesFields\n): Promise<Array<BaseMessage>> {\n const {\n maxTokens,\n tokenCounter,\n strategy = \"last\",\n allowPartial = false,\n endOn,\n startOn,\n includeSystem = false,\n textSplitter,\n } = options;\n if (startOn && strategy === \"first\") {\n throw new Error(\n \"`startOn` should only be specified if `strategy` is 'last'.\"\n );\n }\n if (includeSystem && strategy === \"first\") {\n throw new Error(\n \"`includeSystem` should only be specified if `strategy` is 'last'.\"\n );\n }\n\n let listTokenCounter: (msgs: BaseMessage[]) => Promise<number>;\n if (\"getNumTokens\" in tokenCounter) {\n listTokenCounter = async (msgs: BaseMessage[]): Promise<number> => {\n const tokenCounts = await Promise.all(\n msgs.map((msg) => tokenCounter.getNumTokens(msg.content))\n );\n return tokenCounts.reduce((sum, count) => sum + count, 0);\n };\n } else {\n listTokenCounter = async (msgs: BaseMessage[]): Promise<number> =>\n tokenCounter(msgs);\n }\n\n let textSplitterFunc: (text: string) => Promise<string[]> =\n defaultTextSplitter;\n if (textSplitter) {\n if (\"splitText\" in textSplitter) {\n textSplitterFunc = textSplitter.splitText;\n } else {\n textSplitterFunc = async (text: string): Promise<string[]> =>\n textSplitter(text);\n }\n }\n\n if (strategy === \"first\") {\n return _firstMaxTokens(messages, {\n maxTokens,\n tokenCounter: listTokenCounter,\n textSplitter: textSplitterFunc,\n partialStrategy: allowPartial ? \"first\" : undefined,\n endOn,\n });\n } else if (strategy === \"last\") {\n return _lastMaxTokens(messages, {\n maxTokens,\n tokenCounter: listTokenCounter,\n textSplitter: textSplitterFunc,\n allowPartial,\n includeSystem,\n startOn,\n endOn,\n });\n } else {\n throw new Error(\n `Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`\n );\n }\n}\n\nasync function _firstMaxTokens(\n messages: BaseMessage[],\n options: {\n maxTokens: number;\n tokenCounter: (messages: BaseMessage[]) => Promise<number>;\n textSplitter: (text: string) => Promise<string[]>;\n partialStrategy?: \"first\" | \"last\";\n endOn?: MessageTypeOrClass | MessageTypeOrClass[];\n }\n): Promise<BaseMessage[]> {\n const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } =\n options;\n let messagesCopy = [...messages];\n let idx = 0;\n for (let i = 0; i < messagesCopy.length; i += 1) {\n const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy;\n if ((await tokenCounter(remainingMessages)) <= maxTokens) {\n idx = messagesCopy.length - i;\n break;\n }\n }\n if (idx < messagesCopy.length - 1 && partialStrategy) {\n let includedPartial = false;\n if (Array.isArray(messagesCopy[idx].content)) {\n const excluded = messagesCopy[idx];\n if (typeof excluded.content === \"string\") {\n throw new Error(\"Expected content to be an array.\");\n }\n\n const numBlock = excluded.content.length;\n const reversedContent =\n partialStrategy === \"last\"\n ? [...excluded.content].reverse()\n : excluded.content;\n for (let i = 1; i <= numBlock; i += 1) {\n const partialContent =\n partialStrategy === \"first\"\n ? reversedContent.slice(0, i)\n : reversedContent.slice(-i);\n const fields = Object.fromEntries(\n Object.entries(excluded).filter(\n ([k]) => k !== \"type\" && !k.startsWith(\"lc_\")\n )\n ) as BaseMessageFields;\n const updatedMessage = _switchTypeToMessage(excluded.getType(), {\n ...fields,\n content: partialContent,\n });\n const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage];\n if ((await tokenCounter(slicedMessages)) <= maxTokens) {\n messagesCopy = slicedMessages;\n idx += 1;\n includedPartial = true;\n } else {\n break;\n }\n }\n if (includedPartial && partialStrategy === \"last\") {\n excluded.content = [...reversedContent].reverse();\n }\n }\n if (!includedPartial) {\n const excluded = messagesCopy[idx];\n let text: string | undefined;\n if (\n Array.isArray(excluded.content) &&\n excluded.content.some(\n (block) => typeof block === \"string\" || block.type === \"text\"\n )\n ) {\n const textBlock = excluded.content.find(\n (block) => block.type === \"text\" && block.text\n ) as { type: \"text\"; text: string } | undefined;\n text = textBlock?.text;\n } else if (typeof excluded.content === \"string\") {\n text = excluded.content;\n }\n if (text) {\n const splitTexts = await textSplitter(text);\n const numSplits = splitTexts.length;\n if (partialStrategy === \"last\") {\n splitTexts.reverse();\n }\n for (let _ = 0; _ < numSplits - 1; _ += 1) {\n splitTexts.pop();\n excluded.content = splitTexts.join(\"\");\n if (\n (await tokenCounter([...messagesCopy.slice(0, idx), excluded])) <=\n maxTokens\n ) {\n if (partialStrategy === \"last\") {\n excluded.content = [...splitTexts].reverse().join(\"\");\n }\n messagesCopy = [...messagesCopy.slice(0, idx), excluded];\n idx += 1;\n break;\n }\n }\n }\n }\n }\n\n if (endOn) {\n const endOnArr = Array.isArray(endOn) ? endOn : [endOn];\n while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) {\n idx -= 1;\n }\n }\n\n return messagesCopy.slice(0, idx);\n}\n\nasync function _lastMaxTokens(\n messages: BaseMessage[],\n options: {\n maxTokens: number;\n tokenCounter: (messages: BaseMessage[]) => Promise<number>;\n textSplitter: (text: string) => Promise<string[]>;\n /**\n * @default {false}\n */\n allowPartial?: boolean;\n /**\n * @default {false}\n */\n includeSystem?: boolean;\n startOn?: MessageTypeOrClass | MessageTypeOrClass[];\n endOn?: MessageTypeOrClass | MessageTypeOrClass[];\n }\n): Promise<BaseMessage[]> {\n const {\n allowPartial = false,\n includeSystem = false,\n endOn,\n startOn,\n ...rest\n } = options;\n\n // Create a copy of messages to avoid mutation\n let messagesCopy = messages.map((message) => {\n const fields = Object.fromEntries(\n Object.entries(message).filter(\n ([k]) => k !== \"type\" && !k.startsWith(\"lc_\")\n )\n ) as BaseMessageFields;\n return _switchTypeToMessage(\n message.getType(),\n fields,\n isBaseMessageChunk(message)\n );\n });\n\n if (endOn) {\n const endOnArr = Array.isArray(endOn) ? endOn : [endOn];\n while (\n messagesCopy.length > 0 &&\n !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)\n ) {\n messagesCopy = messagesCopy.slice(0, -1);\n }\n }\n\n const swappedSystem =\n includeSystem && messagesCopy[0]?.getType() === \"system\";\n let reversed_ = swappedSystem\n ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse())\n : messagesCopy.reverse();\n\n reversed_ = await _firstMaxTokens(reversed_, {\n ...rest,\n partialStrategy: allowPartial ? \"last\" : undefined,\n endOn: startOn,\n });\n\n if (swappedSystem) {\n return [reversed_[0], ...reversed_.slice(1).reverse()];\n } else {\n return reversed_.reverse();\n }\n}\n\nfunction _switchTypeToMessage(\n messageType: MessageType,\n fields: BaseMessageFields\n): BaseMessage;\nfunction _switchTypeToMessage(\n messageType: MessageType,\n fields: BaseMessageFields,\n returnChunk: true\n): BaseMessageChunk;\nfunction _switchTypeToMessage(\n messageType: MessageType,\n fields: BaseMessageFields,\n returnChunk?: boolean\n): BaseMessageChunk | BaseMessage;\nfunction _switchTypeToMessage(\n messageType: MessageType,\n fields: BaseMessageFields,\n returnChunk?: boolean\n): BaseMessageChunk | BaseMessage {\n let chunk: BaseMessageChunk | undefined;\n let msg: BaseMessage | undefined;\n\n switch (messageType) {\n case \"human\":\n if (returnChunk) {\n chunk = new HumanMessageChunk(fields);\n } else {\n msg = new HumanMessage(fields);\n }\n break;\n case \"ai\":\n if (returnChunk) {\n let aiChunkFields: AIMessageChunkFields = {\n ...fields,\n };\n if (\"tool_calls\" in aiChunkFields) {\n aiChunkFields = {\n ...aiChunkFields,\n tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({\n ...tc,\n type: \"tool_call_chunk\",\n index: undefined,\n args: JSON.stringify(tc.args),\n })),\n };\n }\n chunk = new AIMessageChunk(aiChunkFields);\n } else {\n msg = new AIMessage(fields);\n }\n break;\n case \"system\":\n if (returnChunk) {\n chunk = new SystemMessageChunk(fields);\n } else {\n msg = new SystemMessage(fields);\n }\n break;\n case \"developer\":\n if (returnChunk) {\n chunk = new SystemMessageChunk({\n ...fields,\n additional_kwargs: {\n ...fields.additional_kwargs,\n __openai_role__: \"developer\",\n },\n });\n } else {\n msg = new SystemMessage({\n ...fields,\n additional_kwargs: {\n ...fields.additional_kwargs,\n __openai_role__: \"developer\",\n },\n });\n }\n break;\n case \"tool\":\n if (\"tool_call_id\" in fields) {\n if (returnChunk) {\n chunk = new ToolMessageChunk(\n fields as ToolMessageFieldsWithToolCallId\n );\n } else {\n msg = new ToolMessage(fields as ToolMessageFieldsWithToolCallId);\n }\n } else {\n throw new Error(\n \"Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined.\"\n );\n }\n break;\n case \"function\":\n if (returnChunk) {\n chunk = new FunctionMessageChunk(fields);\n } else {\n if (!fields.name) {\n throw new Error(\"FunctionMessage must have a 'name' field\");\n }\n msg = new FunctionMessage(fields as FunctionMessageFieldsWithName);\n }\n break;\n case \"generic\":\n if (\"role\" in fields) {\n if (returnChunk) {\n chunk = new ChatMessageChunk(fields as ChatMessageFieldsWithRole);\n } else {\n msg = new ChatMessage(fields as ChatMessageFieldsWithRole);\n }\n } else {\n throw new Error(\n \"Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined.\"\n );\n }\n break;\n default:\n throw new Error(`Unrecognized message type ${messageType}`);\n }\n\n if (returnChunk && chunk) {\n return chunk;\n }\n if (msg) {\n return msg;\n }\n throw new Error(`Unrecognized message type ${messageType}`);\n}"],"names":["RunnableLambda","messages","defaultTextSplitter","isBaseMessageChunk","HumanMessageChunk","HumanMessage","AIMessageChunk","AIMessage","SystemMessageChunk","SystemMessage","ToolMessageChunk","ToolMessage","FunctionMessageChunk","FunctionMessage","ChatMessageChunk","ChatMessage"],"mappings":";;;;;AA+BA,MAAM,cAAc,GAAG,CAAC,GAAgB,EAAE,KAA2B,KAAI;AACvE,IAAA,MAAM,cAAc,GAAG;QACrB,GAAG,IAAI,GAAG,CACR,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,KAAI;AACf,YAAA,IAAI,OAAO,CAAC,KAAK,QAAQ,EAAE;AACzB,gBAAA,OAAO,CAAC;;;AAGV,YAAA,MAAM,oBAAoB,GAAG,IAAK,CAAS,CAAC,EAAE,CAAC;AAC/C,YAAA,IACE,EAAE,SAAS,IAAI,oBAAoB,CAAC;AACpC,gBAAA,OAAO,oBAAoB,CAAC,OAAO,KAAK,UAAU,EAClD;AACA,gBAAA,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC;;AAE3C,YAAA,OAAO,oBAAoB,CAAC,OAAO,EAAE;A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C,MAAM,CAAC;;iBACnC;AACL,gBAAA,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE;AAChB,oBAAA,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC;;AAE7D,gBAAA,GAAG,GAAG,IAAIC,wBAAe,CAAC,MAAuC,CAAC;;YAEpE;AACF,QAAA,KAAK,SAAS;AACZ,YAAA,IAAI,MAAM,IAAI,MAAM,EAAE;gBACpB,IAAI,WAAW,EAAE;AACf,oBAAA,KAAK,GAAG,IAAIC,yBAAgB,CAAC,MAAmC,CAAC;;qBAC5D;AACL,oBAAA,GAAG,GAAG,IAAIC,oBAAW,CAAC,MAAmC,CAAC;;;iBAEvD;AACL,gBAAA,MAAM,IAAI,KAAK,CACb,iFAAiF,CAClF;;YAEH;AACF,QAAA;AACE,YAAA,MAAM,IAAI,KAAK,CAAC,6BAA6B,WAAW,CAAA,CAAE,CAAC;;AAG/D,IAAA,IAAI,WAAW,IAAI,KAAK,EAAE;AACxB,QAAA,OAAO,KAAK;;IAEd,IAAI,GAAG,EAAE;AACP,QAAA,OAAO,GAAG;;AAEZ,IAAA,MAAM,IAAI,KAAK,CAAC,6BAA6B,WAAW,CAAA,CAAE,CAAC;AAC7D;;;;"}
|
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var transformers = require('./transformers.cjs');
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* Factory function that creates a trimMessages function that maintains an indexTokenCountMap
|
|
7
|
-
* during a run. This allows for efficient token counting by avoiding recounting tokens
|
|
8
|
-
* for messages that have already been processed.
|
|
9
|
-
*
|
|
10
|
-
* @param {Object} options - Configuration options for the trimMessages function
|
|
11
|
-
* @param {TrimMessagesFields} options.trimOptions - Options for the trimMessages function
|
|
12
|
-
* @returns {Function} A function that trims messages while maintaining a token count map
|
|
13
|
-
*
|
|
14
|
-
* @example
|
|
15
|
-
* ```typescript
|
|
16
|
-
* // Create a trimmer function with specific options
|
|
17
|
-
* const trimmer = createTrimMessagesFunction({
|
|
18
|
-
* trimOptions: {
|
|
19
|
-
* maxTokens: 4000,
|
|
20
|
-
* tokenCounter: myTokenCounter,
|
|
21
|
-
* strategy: "last",
|
|
22
|
-
* includeSystem: true
|
|
23
|
-
* }
|
|
24
|
-
* });
|
|
25
|
-
*
|
|
26
|
-
* // Use the trimmer with an array of messages
|
|
27
|
-
* // First call with initial messages
|
|
28
|
-
* const { messages: trimmedMessages1 } = await trimmer(initialMessages);
|
|
29
|
-
*
|
|
30
|
-
* // Later call with additional messages
|
|
31
|
-
* const { messages: trimmedMessages2 } = await trimmer([...initialMessages, ...newMessages]);
|
|
32
|
-
* ```
|
|
33
|
-
*/
|
|
34
|
-
function createTrimMessagesFunction({ trimOptions }) {
|
|
35
|
-
// Initialize the token count map and keep track of the last processed message array
|
|
36
|
-
const indexTokenCountMap = {};
|
|
37
|
-
let lastProcessedMessages = [];
|
|
38
|
-
/**
|
|
39
|
-
* Trims messages while maintaining a token count map for efficiency
|
|
40
|
-
*
|
|
41
|
-
* @param {BaseMessage[]} messages - Array of messages to trim
|
|
42
|
-
* @returns {Promise<Object>} Object containing trimmed messages and the current token count map
|
|
43
|
-
*/
|
|
44
|
-
return async function trimMessagesWithMap(messages) {
|
|
45
|
-
// Determine which messages are new by comparing with the last processed messages
|
|
46
|
-
const newMessages = [];
|
|
47
|
-
const newIndices = [];
|
|
48
|
-
// If this is the first call or we have more messages than before
|
|
49
|
-
if (lastProcessedMessages.length === 0) {
|
|
50
|
-
// First call, all messages are new
|
|
51
|
-
for (let i = 0; i < messages.length; i++) {
|
|
52
|
-
newMessages.push(messages[i]);
|
|
53
|
-
newIndices.push(i);
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
else if (messages.length > lastProcessedMessages.length) {
|
|
57
|
-
// We have new messages, only count those
|
|
58
|
-
for (let i = lastProcessedMessages.length; i < messages.length; i++) {
|
|
59
|
-
newMessages.push(messages[i]);
|
|
60
|
-
newIndices.push(i);
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
// Update the last processed messages
|
|
64
|
-
lastProcessedMessages = [...messages];
|
|
65
|
-
// Create a copy of the token counter to use for new messages
|
|
66
|
-
const originalTokenCounter = trimOptions.tokenCounter;
|
|
67
|
-
// Count tokens for new messages
|
|
68
|
-
for (let i = 0; i < newMessages.length; i++) {
|
|
69
|
-
const messageIndex = newIndices[i];
|
|
70
|
-
let messageTokenCount;
|
|
71
|
-
if (typeof originalTokenCounter === 'function') {
|
|
72
|
-
// Count this single message by passing it as a one-element array
|
|
73
|
-
messageTokenCount = await originalTokenCounter([newMessages[i]]);
|
|
74
|
-
}
|
|
75
|
-
else if ('getNumTokens' in originalTokenCounter) {
|
|
76
|
-
// Use the language model's getNumTokens method
|
|
77
|
-
messageTokenCount = await originalTokenCounter.getNumTokens(newMessages[i].content);
|
|
78
|
-
}
|
|
79
|
-
else {
|
|
80
|
-
throw new Error("Unsupported token counter type");
|
|
81
|
-
}
|
|
82
|
-
// Store the token count for this message
|
|
83
|
-
indexTokenCountMap[messageIndex] = messageTokenCount;
|
|
84
|
-
}
|
|
85
|
-
// Create a token counter that uses the map
|
|
86
|
-
const enhancedTokenCounter = async (msgsToCount) => {
|
|
87
|
-
let totalTokens = 0;
|
|
88
|
-
// Use the cached token counts
|
|
89
|
-
for (let i = 0; i < msgsToCount.length; i++) {
|
|
90
|
-
if (indexTokenCountMap[i] !== undefined) {
|
|
91
|
-
totalTokens += indexTokenCountMap[i];
|
|
92
|
-
}
|
|
93
|
-
else {
|
|
94
|
-
// This shouldn't happen if we've counted all messages
|
|
95
|
-
console.warn(`Missing token count for message at index ${i}`);
|
|
96
|
-
// Count it now as a fallback
|
|
97
|
-
let messageTokenCount;
|
|
98
|
-
if (typeof originalTokenCounter === 'function') {
|
|
99
|
-
messageTokenCount = await originalTokenCounter([msgsToCount[i]]);
|
|
100
|
-
}
|
|
101
|
-
else if ('getNumTokens' in originalTokenCounter) {
|
|
102
|
-
messageTokenCount = await originalTokenCounter.getNumTokens(msgsToCount[i].content);
|
|
103
|
-
}
|
|
104
|
-
else {
|
|
105
|
-
throw new Error("Unsupported token counter type");
|
|
106
|
-
}
|
|
107
|
-
indexTokenCountMap[i] = messageTokenCount;
|
|
108
|
-
totalTokens += messageTokenCount;
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
return totalTokens;
|
|
112
|
-
};
|
|
113
|
-
// Create modified trim options with our enhanced token counter
|
|
114
|
-
const modifiedTrimOptions = {
|
|
115
|
-
...trimOptions,
|
|
116
|
-
tokenCounter: enhancedTokenCounter
|
|
117
|
-
};
|
|
118
|
-
// Trim the messages using the original function
|
|
119
|
-
const trimmedMessages = await transformers.trimMessages(messages, modifiedTrimOptions);
|
|
120
|
-
// Return both the trimmed messages and the updated token count map
|
|
121
|
-
return {
|
|
122
|
-
messages: trimmedMessages,
|
|
123
|
-
indexTokenCountMap
|
|
124
|
-
};
|
|
125
|
-
};
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
exports.createTrimMessagesFunction = createTrimMessagesFunction;
|
|
129
|
-
//# sourceMappingURL=trimMessagesFactory.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"trimMessagesFactory.cjs","sources":["../../../src/messages/trimMessagesFactory.ts"],"sourcesContent":["import { BaseMessage } from \"@langchain/core/messages\";\nimport { trimMessages, TrimMessagesFields } from \"./transformers\";\n\n/**\n * Factory function that creates a trimMessages function that maintains an indexTokenCountMap\n * during a run. This allows for efficient token counting by avoiding recounting tokens\n * for messages that have already been processed.\n * \n * @param {Object} options - Configuration options for the trimMessages function\n * @param {TrimMessagesFields} options.trimOptions - Options for the trimMessages function\n * @returns {Function} A function that trims messages while maintaining a token count map\n * \n * @example\n * ```typescript\n * // Create a trimmer function with specific options\n * const trimmer = createTrimMessagesFunction({\n * trimOptions: {\n * maxTokens: 4000,\n * tokenCounter: myTokenCounter,\n * strategy: \"last\",\n * includeSystem: true\n * }\n * });\n * \n * // Use the trimmer with an array of messages\n * // First call with initial messages\n * const { messages: trimmedMessages1 } = await trimmer(initialMessages);\n * \n * // Later call with additional messages\n * const { messages: trimmedMessages2 } = await trimmer([...initialMessages, ...newMessages]);\n * ```\n */\nexport function createTrimMessagesFunction({ trimOptions }: { \n trimOptions: TrimMessagesFields \n}) {\n // Initialize the token count map and keep track of the last processed message array\n const indexTokenCountMap: Record<number, number> = {};\n let lastProcessedMessages: BaseMessage[] = [];\n \n /**\n * Trims messages while maintaining a token count map for efficiency\n * \n * @param {BaseMessage[]} messages - Array of messages to trim\n * @returns {Promise<Object>} Object containing trimmed messages and the current token count map\n */\n return async function trimMessagesWithMap(messages: BaseMessage[]): Promise<{\n messages: BaseMessage[];\n indexTokenCountMap: Record<number, number>;\n }> {\n // Determine which messages are new by comparing with the last processed messages\n const newMessages: BaseMessage[] = [];\n const newIndices: number[] = [];\n \n // If this is the first call or we have more messages than before\n if (lastProcessedMessages.length === 0) {\n // First call, all messages are new\n for (let i = 0; i < messages.length; i++) {\n newMessages.push(messages[i]);\n newIndices.push(i);\n }\n } else if (messages.length > lastProcessedMessages.length) {\n // We have new messages, only count those\n for (let i = lastProcessedMessages.length; i < messages.length; i++) {\n newMessages.push(messages[i]);\n newIndices.push(i);\n }\n }\n \n // Update the last processed messages\n lastProcessedMessages = [...messages];\n \n // Create a copy of the token counter to use for new messages\n const originalTokenCounter = trimOptions.tokenCounter;\n \n // Count tokens for new messages\n for (let i = 0; i < newMessages.length; i++) {\n const messageIndex = newIndices[i];\n let messageTokenCount: number;\n \n if (typeof originalTokenCounter === 'function') {\n // Count this single message by passing it as a one-element array\n messageTokenCount = await originalTokenCounter([newMessages[i]]);\n } else if ('getNumTokens' in originalTokenCounter) {\n // Use the language model's getNumTokens method\n messageTokenCount = await originalTokenCounter.getNumTokens(newMessages[i].content);\n } else {\n throw new Error(\"Unsupported token counter type\");\n }\n \n // Store the token count for this message\n indexTokenCountMap[messageIndex] = messageTokenCount;\n }\n \n // Create a token counter that uses the map\n const enhancedTokenCounter = async (msgsToCount: BaseMessage[]): Promise<number> => {\n let totalTokens = 0;\n \n // Use the cached token counts\n for (let i = 0; i < msgsToCount.length; i++) {\n if (indexTokenCountMap[i] !== undefined) {\n totalTokens += indexTokenCountMap[i];\n } else {\n // This shouldn't happen if we've counted all messages\n console.warn(`Missing token count for message at index ${i}`);\n \n // Count it now as a fallback\n let messageTokenCount: number;\n \n if (typeof originalTokenCounter === 'function') {\n messageTokenCount = await originalTokenCounter([msgsToCount[i]]);\n } else if ('getNumTokens' in originalTokenCounter) {\n messageTokenCount = await originalTokenCounter.getNumTokens(msgsToCount[i].content);\n } else {\n throw new Error(\"Unsupported token counter type\");\n }\n \n indexTokenCountMap[i] = messageTokenCount;\n totalTokens += messageTokenCount;\n }\n }\n \n return totalTokens;\n };\n \n // Create modified trim options with our enhanced token counter\n const modifiedTrimOptions: TrimMessagesFields = {\n ...trimOptions,\n tokenCounter: enhancedTokenCounter\n };\n \n // Trim the messages using the original function\n const trimmedMessages = await trimMessages(messages, modifiedTrimOptions);\n \n // Return both the trimmed messages and the updated token count map\n return {\n messages: trimmedMessages,\n indexTokenCountMap\n };\n };\n}\n"],"names":["trimMessages"],"mappings":";;;;AAGA;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BG;AACa,SAAA,0BAA0B,CAAC,EAAE,WAAW,EAEvD,EAAA;;IAEC,MAAM,kBAAkB,GAA2B,EAAE;IACrD,IAAI,qBAAqB,GAAkB,EAAE;AAE7C;;;;;AAKG;AACH,IAAA,OAAO,eAAe,mBAAmB,CAAC,QAAuB,EAAA;;QAK/D,MAAM,WAAW,GAAkB,EAAE;QACrC,MAAM,UAAU,GAAa,EAAE;;AAG/B,QAAA,IAAI,qBAAqB,CAAC,MAAM,KAAK,CAAC,EAAE;;AAEtC,YAAA,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;gBACxC,WAAW,CAA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