@librechat/agents 4.2.13 → 4.2.15
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/agents/AgentContext.cjs +75 -19
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +52 -6
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/harness/providerText.cjs +1 -0
- package/dist/cjs/harness/providerText.cjs.map +1 -1
- package/dist/cjs/llm/google/utils/signatures.cjs +22 -14
- package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +122 -13
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +8 -2
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/llm/openai/typedContent.cjs +94 -0
- package/dist/cjs/llm/openai/typedContent.cjs.map +1 -0
- package/dist/cjs/llm/prepareProviderRequest.cjs +102 -7
- package/dist/cjs/llm/prepareProviderRequest.cjs.map +1 -1
- package/dist/cjs/llm/providerTextBatch.cjs +128 -0
- package/dist/cjs/llm/providerTextBatch.cjs.map +1 -0
- package/dist/cjs/llm/providerTextBoundary.cjs +81 -12
- package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
- package/dist/cjs/main.cjs +3 -0
- package/dist/cjs/messages/content.cjs +3 -3
- package/dist/cjs/messages/content.cjs.map +1 -1
- package/dist/cjs/messages/vision.cjs +77 -0
- package/dist/cjs/messages/vision.cjs.map +1 -0
- package/dist/cjs/protection/providerText.cjs +56 -6
- package/dist/cjs/protection/providerText.cjs.map +1 -1
- package/dist/cjs/protection/providerTextAdmission.cjs +5 -0
- package/dist/cjs/protection/providerTextAdmission.cjs.map +1 -1
- package/dist/cjs/run.cjs +7 -2
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/runtime/client.cjs +2 -0
- package/dist/cjs/runtime/client.cjs.map +1 -1
- package/dist/cjs/stream.cjs +9 -2
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +6 -2
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/tools/handlers.cjs +47 -1
- package/dist/cjs/tools/handlers.cjs.map +1 -1
- package/dist/cjs/tools/search/citations.cjs +194 -0
- package/dist/cjs/tools/search/citations.cjs.map +1 -0
- package/dist/cjs/tools/search/firecrawl.cjs +4 -9
- package/dist/cjs/tools/search/firecrawl.cjs.map +1 -1
- package/dist/cjs/tools/search/google.cjs +68 -0
- package/dist/cjs/tools/search/google.cjs.map +1 -0
- package/dist/cjs/tools/search/openai.cjs +80 -0
- package/dist/cjs/tools/search/openai.cjs.map +1 -0
- package/dist/cjs/utils/tokens.cjs +6 -0
- package/dist/cjs/utils/tokens.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +76 -20
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +53 -7
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/harness/providerText.mjs +1 -0
- package/dist/esm/harness/providerText.mjs.map +1 -1
- package/dist/esm/llm/google/utils/signatures.mjs +22 -14
- package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +124 -15
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +8 -2
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/llm/openai/typedContent.mjs +93 -0
- package/dist/esm/llm/openai/typedContent.mjs.map +1 -0
- package/dist/esm/llm/prepareProviderRequest.mjs +102 -7
- package/dist/esm/llm/prepareProviderRequest.mjs.map +1 -1
- package/dist/esm/llm/providerTextBatch.mjs +128 -0
- package/dist/esm/llm/providerTextBatch.mjs.map +1 -0
- package/dist/esm/llm/providerTextBoundary.mjs +81 -12
- package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
- package/dist/esm/main.mjs +4 -4
- package/dist/esm/messages/content.mjs +3 -3
- package/dist/esm/messages/content.mjs.map +1 -1
- package/dist/esm/messages/vision.mjs +73 -0
- package/dist/esm/messages/vision.mjs.map +1 -0
- package/dist/esm/protection/providerText.mjs +55 -7
- package/dist/esm/protection/providerText.mjs.map +1 -1
- package/dist/esm/protection/providerTextAdmission.mjs +5 -0
- package/dist/esm/protection/providerTextAdmission.mjs.map +1 -1
- package/dist/esm/run.mjs +7 -2
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/runtime/client.mjs +2 -0
- package/dist/esm/runtime/client.mjs.map +1 -1
- package/dist/esm/stream.mjs +9 -2
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +6 -2
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/tools/handlers.mjs +47 -2
- package/dist/esm/tools/handlers.mjs.map +1 -1
- package/dist/esm/tools/search/citations.mjs +190 -0
- package/dist/esm/tools/search/citations.mjs.map +1 -0
- package/dist/esm/tools/search/firecrawl.mjs +4 -9
- package/dist/esm/tools/search/firecrawl.mjs.map +1 -1
- package/dist/esm/tools/search/google.mjs +67 -0
- package/dist/esm/tools/search/google.mjs.map +1 -0
- package/dist/esm/tools/search/openai.mjs +80 -0
- package/dist/esm/tools/search/openai.mjs.map +1 -0
- package/dist/esm/utils/tokens.mjs +6 -1
- package/dist/esm/utils/tokens.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +20 -1
- package/dist/types/graphs/Graph.d.ts +14 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/llm/openai/typedContent.d.ts +14 -0
- package/dist/types/llm/prepareProviderRequest.d.ts +7 -1
- package/dist/types/llm/providerTextBatch.d.ts +26 -0
- package/dist/types/llm/providerTextBoundary.d.ts +7 -1
- package/dist/types/messages/content.d.ts +2 -1
- package/dist/types/messages/vision.d.ts +20 -0
- package/dist/types/protection/providerText.d.ts +29 -1
- package/dist/types/protection/providerTextAdmission.d.ts +1 -0
- package/dist/types/tools/handlers.d.ts +13 -0
- package/dist/types/tools/search/citations.d.ts +88 -0
- package/dist/types/tools/search/firecrawl.d.ts +3 -1
- package/dist/types/tools/search/google.d.ts +11 -0
- package/dist/types/tools/search/openai.d.ts +3 -0
- package/dist/types/tools/search/types.d.ts +24 -0
- package/dist/types/types/graph.d.ts +8 -0
- package/dist/types/types/stream.d.ts +12 -0
- package/dist/types/utils/tokens.d.ts +3 -0
- package/package.json +1 -1
- package/src/agents/AgentContext.ts +188 -78
- package/src/graphs/Graph.ts +117 -8
- package/src/harness/providerText.ts +1 -0
- package/src/index.ts +2 -0
- package/src/llm/google/utils/signatures.ts +52 -36
- package/src/llm/invoke.ts +160 -16
- package/src/llm/openai/index.ts +18 -5
- package/src/llm/openai/typedContent.ts +110 -0
- package/src/llm/prepareProviderRequest.ts +206 -7
- package/src/llm/providerTextBatch.ts +158 -0
- package/src/llm/providerTextBoundary.ts +119 -13
- package/src/messages/content.ts +10 -4
- package/src/messages/vision.ts +109 -0
- package/src/protection/providerText.ts +95 -6
- package/src/protection/providerTextAdmission.ts +6 -0
- package/src/run.ts +22 -1
- package/src/runtime/client.ts +3 -0
- package/src/stream.ts +18 -2
- package/src/summarization/node.ts +4 -0
- package/src/tools/handlers.ts +110 -5
- package/src/tools/search/citations.ts +375 -0
- package/src/tools/search/firecrawl.ts +13 -16
- package/src/tools/search/google.ts +122 -0
- package/src/tools/search/openai.ts +118 -0
- package/src/tools/search/types.ts +21 -0
- package/src/types/graph.ts +8 -0
- package/src/types/stream.ts +9 -0
- package/src/utils/tokens.ts +13 -1
|
@@ -21,6 +21,7 @@ import {
|
|
|
21
21
|
import { isProviderTextInput } from '@/protection/providerTextInput';
|
|
22
22
|
import { createProviderTextChunk } from '@/llm/providerTextChunk';
|
|
23
23
|
import { preserveModelInvocationContext } from '@/llm/invocation';
|
|
24
|
+
import { ProviderTextBatch } from '@/llm/providerTextBatch';
|
|
24
25
|
import { getChatModelClass } from '@/llm/providers';
|
|
25
26
|
import { Providers } from '@/common';
|
|
26
27
|
|
|
@@ -136,6 +137,52 @@ function validateMetadata(metadata: AIMessageChunk['response_metadata'], google
|
|
|
136
137
|
}
|
|
137
138
|
}
|
|
138
139
|
|
|
140
|
+
/** The staged frame may contain provider controls as well as raw prose. */
|
|
141
|
+
function batchControls(generation: ChatGenerationChunk): number {
|
|
142
|
+
const message = generation.message as AIMessageChunk;
|
|
143
|
+
if (
|
|
144
|
+
(message.tool_calls?.length ?? 0) > 0 ||
|
|
145
|
+
(message.tool_call_chunks?.length ?? 0) > 0 ||
|
|
146
|
+
(message.invalid_tool_calls?.length ?? 0) > 0 ||
|
|
147
|
+
Object.hasOwn(message.response_metadata, 'output') ||
|
|
148
|
+
generation.text !== message.content
|
|
149
|
+
) throw new ProviderTextProtectionError('unsupported');
|
|
150
|
+
|
|
151
|
+
for (const key of Object.keys(message.additional_kwargs)) {
|
|
152
|
+
if (!Object.hasOwn(additionalControls, key) || additionalControls[key]?.(message.additional_kwargs[key]) !== true) {
|
|
153
|
+
throw new ProviderTextProtectionError('unsupported');
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
validateMetadata(message.response_metadata);
|
|
157
|
+
validateMetadata(generation.generationInfo ?? {});
|
|
158
|
+
if (!numericMetadata(message.usage_metadata)) throw new ProviderTextProtectionError('unsupported');
|
|
159
|
+
|
|
160
|
+
let bytes = 256 + ((message.id?.length ?? 0) + (message.name?.length ?? 0)) * 2;
|
|
161
|
+
for (const record of [message.additional_kwargs, message.response_metadata, generation.generationInfo]) {
|
|
162
|
+
if (record == null) continue;
|
|
163
|
+
for (const [key, value] of Object.entries(record)) {
|
|
164
|
+
bytes += key.length * 2 + metadataBytes(value);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return bytes + metadataBytes(message.usage_metadata);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Called only for already validated scalar or bounded numeric metadata. */
|
|
171
|
+
function metadataBytes(value: unknown): number {
|
|
172
|
+
if (typeof value === 'string') return value.length * 2 + 16;
|
|
173
|
+
if (typeof value !== 'object' || value == null) return 16;
|
|
174
|
+
let bytes = 64;
|
|
175
|
+
for (const [key, entry] of Object.entries(value)) bytes += key.length * 2 + metadataBytes(entry);
|
|
176
|
+
return bytes;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function batchChunk(text: string): ChatGenerationChunk | undefined {
|
|
180
|
+
return text === '' ? undefined : new ChatGenerationChunk({
|
|
181
|
+
text,
|
|
182
|
+
message: new AIMessageChunk({ content: text }),
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
139
186
|
class Candidate {
|
|
140
187
|
private block?: TextBlock;
|
|
141
188
|
private stringContent = false;
|
|
@@ -144,10 +191,23 @@ class Candidate {
|
|
|
144
191
|
|
|
145
192
|
constructor(private readonly attempt: ProviderTextAttempt, private readonly provider?: ProviderName) { this.responses = new ResponsesTextProjection(attempt); }
|
|
146
193
|
|
|
147
|
-
strip(generation: ChatGenerationChunk): ChatGenerationChunk
|
|
194
|
+
strip(generation: ChatGenerationChunk): ChatGenerationChunk;
|
|
195
|
+
strip(generation: ChatGenerationChunk, batch: ProviderTextBatch | undefined): ChatGenerationChunk | undefined;
|
|
196
|
+
strip(generation: ChatGenerationChunk, batch?: ProviderTextBatch): ChatGenerationChunk | undefined {
|
|
148
197
|
const message = generation.message;
|
|
149
198
|
if (!(message instanceof AIMessageChunk))
|
|
150
199
|
throw new ProviderTextProtectionError('unsupported');
|
|
200
|
+
if (batch != null) {
|
|
201
|
+
if (typeof message.content !== 'string') throw new ProviderTextProtectionError('unsupported');
|
|
202
|
+
batch.append(message.content);
|
|
203
|
+
if (message.id == null && message.name == null && message.usage_metadata == null &&
|
|
204
|
+
Object.keys(message.additional_kwargs).length === 0 &&
|
|
205
|
+
Object.keys(message.response_metadata).length === 0 &&
|
|
206
|
+
Object.keys(generation.generationInfo ?? {}).length === 0) return undefined;
|
|
207
|
+
return new ChatGenerationChunk({
|
|
208
|
+
text: '', message: copyMessage(message, ''), generationInfo: generation.generationInfo,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
151
211
|
this.attempt.observeChunk();
|
|
152
212
|
for (const key of Object.keys(message.additional_kwargs)) {
|
|
153
213
|
if (additionalKeys.has(key)) continue;
|
|
@@ -303,17 +363,25 @@ function usesInternalStreaming(
|
|
|
303
363
|
return false;
|
|
304
364
|
}
|
|
305
365
|
|
|
366
|
+
interface BatchInvocation {
|
|
367
|
+
getAttempt: (signal?: AbortSignal) => ProviderTextAttempt;
|
|
368
|
+
dispatchStart?: (attempt: ProviderTextAttempt) => void | Promise<void>;
|
|
369
|
+
}
|
|
370
|
+
|
|
306
371
|
/** Clone only known runnable shells. Never mutate a shared provider or its callback configuration. */
|
|
307
372
|
export function withProviderTextBoundary(
|
|
308
373
|
model: ChatModel,
|
|
309
374
|
policy: ProviderTextProtection,
|
|
310
|
-
provider?: ProviderName
|
|
375
|
+
provider?: ProviderName,
|
|
376
|
+
batchInvocation?: BatchInvocation
|
|
311
377
|
): ChatModel {
|
|
312
378
|
const protectedModel = clone(model);
|
|
313
379
|
if (model instanceof RunnableBinding) {
|
|
314
380
|
assertBindingShell(model);
|
|
315
381
|
Object.defineProperty(protectedModel, 'bound', {
|
|
316
|
-
value: withProviderTextBoundary(
|
|
382
|
+
value: withProviderTextBoundary(
|
|
383
|
+
model.bound as ChatModel, policy, provider, batchInvocation
|
|
384
|
+
),
|
|
317
385
|
});
|
|
318
386
|
return protectedModel;
|
|
319
387
|
}
|
|
@@ -330,7 +398,8 @@ export function withProviderTextBoundary(
|
|
|
330
398
|
value: withProviderTextBoundary(
|
|
331
399
|
steps[steps.length - 1] as ChatModel,
|
|
332
400
|
policy,
|
|
333
|
-
provider
|
|
401
|
+
provider,
|
|
402
|
+
batchInvocation
|
|
334
403
|
),
|
|
335
404
|
});
|
|
336
405
|
return protectedModel;
|
|
@@ -354,16 +423,27 @@ export function withProviderTextBoundary(
|
|
|
354
423
|
if (model.disableStreaming && usesInternalStreaming(model)) {
|
|
355
424
|
throw new ProviderTextProtectionError('unsupported');
|
|
356
425
|
}
|
|
426
|
+
if (policy.batching != null && provider !== Providers.OPENAI) {
|
|
427
|
+
throw new ProviderTextProtectionError('unsupported');
|
|
428
|
+
}
|
|
357
429
|
const protectedChat = clone(model);
|
|
358
430
|
protectedChat._streamResponseChunks = async function* (
|
|
359
431
|
messages,
|
|
360
432
|
options,
|
|
361
433
|
runManager
|
|
362
434
|
): AsyncGenerator<ChatGenerationChunk> {
|
|
363
|
-
const attempt =
|
|
435
|
+
const attempt =
|
|
436
|
+
batchInvocation?.getAttempt(options.signal) ??
|
|
437
|
+
new ProviderTextAttempt(policy, options.signal);
|
|
364
438
|
const candidate = new Candidate(attempt, provider);
|
|
439
|
+
const batch = policy.batching == null ? undefined : new ProviderTextBatch(attempt, policy.batching, batchControls);
|
|
440
|
+
let completed = false;
|
|
365
441
|
let source: AsyncGenerator<ChatGenerationChunk> | undefined;
|
|
366
442
|
try {
|
|
443
|
+
if (batch != null) {
|
|
444
|
+
const ready = batchInvocation?.dispatchStart?.(attempt);
|
|
445
|
+
if (ready != null) await ready;
|
|
446
|
+
}
|
|
367
447
|
source = model._streamResponseChunks(
|
|
368
448
|
messages,
|
|
369
449
|
preserveModelInvocationContext(
|
|
@@ -374,26 +454,35 @@ export function withProviderTextBoundary(
|
|
|
374
454
|
undefined
|
|
375
455
|
);
|
|
376
456
|
for (;;) {
|
|
377
|
-
const next = await attempt.wait(source.next());
|
|
457
|
+
const next = batch == null ? await attempt.wait(source.next()) : await batch.read(source);
|
|
458
|
+
attempt.check();
|
|
459
|
+
if (next !== 'flush' && next.done === true) break;
|
|
460
|
+
const chunk = next === 'flush'
|
|
461
|
+
? batchChunk(await batch!.flush(false))
|
|
462
|
+
: candidate.strip(next.value, batch);
|
|
463
|
+
if (chunk == null) continue;
|
|
378
464
|
attempt.check();
|
|
379
|
-
if (
|
|
380
|
-
const chunk = candidate.strip(next.value);
|
|
465
|
+
if (batch != null && chunk.text !== '') attempt.markTextPublished();
|
|
381
466
|
yield chunk;
|
|
382
|
-
|
|
383
|
-
|
|
467
|
+
if (batch != null) attempt.check();
|
|
468
|
+
const notification = runManager?.handleLLMNewToken(
|
|
469
|
+
chunk.text,
|
|
384
470
|
undefined,
|
|
385
471
|
undefined,
|
|
386
472
|
undefined,
|
|
387
473
|
undefined,
|
|
388
474
|
{ chunk }
|
|
389
475
|
);
|
|
476
|
+
if (batch != null && notification != null) await attempt.wait(notification, false);
|
|
477
|
+
else await notification;
|
|
390
478
|
}
|
|
391
|
-
const canonical = await candidate.canonical();
|
|
479
|
+
const canonical = batch == null ? await candidate.canonical() : batchChunk(await batch.flush(true));
|
|
392
480
|
attempt.check();
|
|
393
481
|
if (canonical != null) {
|
|
482
|
+
if (batch != null) attempt.markTextPublished();
|
|
394
483
|
yield canonical;
|
|
395
484
|
attempt.check();
|
|
396
|
-
|
|
485
|
+
const notification = runManager?.handleLLMNewToken(
|
|
397
486
|
canonical.text,
|
|
398
487
|
undefined,
|
|
399
488
|
undefined,
|
|
@@ -401,8 +490,23 @@ export function withProviderTextBoundary(
|
|
|
401
490
|
undefined,
|
|
402
491
|
{ chunk: canonical }
|
|
403
492
|
);
|
|
493
|
+
if (batch != null && notification != null) await attempt.wait(notification, false);
|
|
494
|
+
else await notification;
|
|
404
495
|
}
|
|
496
|
+
completed = true;
|
|
497
|
+
} catch (error) {
|
|
498
|
+
if (batch == null) throw error;
|
|
499
|
+
attempt.check();
|
|
500
|
+
const safe = error instanceof ProviderTextProtectionError
|
|
501
|
+
? error
|
|
502
|
+
: new ProviderTextProtectionError('unavailable');
|
|
503
|
+
attempt.stop(safe);
|
|
504
|
+
throw safe;
|
|
405
505
|
} finally {
|
|
506
|
+
if (batch != null) {
|
|
507
|
+
batch.close();
|
|
508
|
+
if (!completed) attempt.stop(new ProviderTextProtectionError('cancelled'));
|
|
509
|
+
}
|
|
406
510
|
try {
|
|
407
511
|
if (source != null) void attempt.wait(source.return(undefined)).catch(() => {});
|
|
408
512
|
} finally {
|
|
@@ -413,7 +517,9 @@ export function withProviderTextBoundary(
|
|
|
413
517
|
protectedChat._streamChatModelEvents =
|
|
414
518
|
BaseChatModel.prototype._streamChatModelEvents;
|
|
415
519
|
protectedChat._generate = async function (messages, options, runManager): Promise<ChatResult> {
|
|
416
|
-
if (usesInternalStreaming(model, options))
|
|
520
|
+
if (policy.batching != null || usesInternalStreaming(model, options)) {
|
|
521
|
+
throw new ProviderTextProtectionError('unsupported');
|
|
522
|
+
}
|
|
417
523
|
const attempt = new ProviderTextAttempt(policy, options.signal);
|
|
418
524
|
try {
|
|
419
525
|
const result = await attempt.wait(
|
package/src/messages/content.ts
CHANGED
|
@@ -12,18 +12,22 @@ import { cloneMessage } from './cache';
|
|
|
12
12
|
/**
|
|
13
13
|
* Whether {@link formatContentStrings} will flatten this message's content:
|
|
14
14
|
* a human/ai/system message whose content is an array of text-only blocks.
|
|
15
|
+
* Pass `content` to judge replacement content before cloning the message.
|
|
15
16
|
*/
|
|
16
|
-
export const isLegacyConvertible = (
|
|
17
|
+
export const isLegacyConvertible = (
|
|
18
|
+
message: BaseMessage,
|
|
19
|
+
content: BaseMessage['content'] | MessageContentComplex[] = message.content
|
|
20
|
+
): boolean => {
|
|
17
21
|
const messageType = message.getType();
|
|
18
22
|
const isValidMessage =
|
|
19
23
|
messageType === 'human' || messageType === 'ai' || messageType === 'system';
|
|
20
24
|
if (!isValidMessage) {
|
|
21
25
|
return false;
|
|
22
26
|
}
|
|
23
|
-
if (!Array.isArray(
|
|
27
|
+
if (!Array.isArray(content)) {
|
|
24
28
|
return false;
|
|
25
29
|
}
|
|
26
|
-
return
|
|
30
|
+
return content.every((block) => block.type === ContentTypes.TEXT);
|
|
27
31
|
};
|
|
28
32
|
|
|
29
33
|
/** Joins the text of {@link isLegacyConvertible} content blocks into the exact
|
|
@@ -63,7 +67,9 @@ export const formatContentStrings = (
|
|
|
63
67
|
isGeminiReplayParts(message.additional_kwargs[GEMINI_PARTS]);
|
|
64
68
|
const content = preserveNativeText
|
|
65
69
|
? blocks
|
|
66
|
-
.map((block) =>
|
|
70
|
+
.map((block) =>
|
|
71
|
+
'text' in block && typeof block.text === 'string' ? block.text : ''
|
|
72
|
+
)
|
|
67
73
|
.join('')
|
|
68
74
|
: flattenLegacyContent(blocks);
|
|
69
75
|
result.push(cloneMessage(message, content));
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import type { MessageContentComplex } from '@langchain/core/messages';
|
|
2
|
+
import { getCacheControl, withCacheControl } from './cache';
|
|
3
|
+
import { getMediaMimeType } from '@/utils/tokens';
|
|
4
|
+
|
|
5
|
+
/** Stands in for each image a model without image input cannot read. */
|
|
6
|
+
export const OMITTED_IMAGE_TEXT =
|
|
7
|
+
'[Image omitted because this model does not accept image input.]';
|
|
8
|
+
|
|
9
|
+
const IMAGE_BLOCK_TYPES = new Set(['image', 'image_url', 'input_image']);
|
|
10
|
+
const MIME_TYPED_BLOCK_TYPES = new Set(['file', 'media']);
|
|
11
|
+
|
|
12
|
+
/** Whether a content block carries an image, in any provider's shape. */
|
|
13
|
+
export function isImageContentBlock(block: MessageContentComplex): boolean {
|
|
14
|
+
const type = block.type;
|
|
15
|
+
if (typeof type !== 'string') {
|
|
16
|
+
return false;
|
|
17
|
+
}
|
|
18
|
+
if (IMAGE_BLOCK_TYPES.has(type) || type.startsWith('image/')) {
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
if (!MIME_TYPED_BLOCK_TYPES.has(type)) {
|
|
22
|
+
return false;
|
|
23
|
+
}
|
|
24
|
+
return (
|
|
25
|
+
getMediaMimeType(block as Record<string, unknown>)?.startsWith('image/') ===
|
|
26
|
+
true
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The text marker standing in for `image`, carrying its prompt-cache breakpoint. */
|
|
31
|
+
export function toOmittedImageBlock(
|
|
32
|
+
image: MessageContentComplex
|
|
33
|
+
): MessageContentComplex {
|
|
34
|
+
const text: MessageContentComplex = {
|
|
35
|
+
type: 'text',
|
|
36
|
+
text: OMITTED_IMAGE_TEXT,
|
|
37
|
+
};
|
|
38
|
+
const marker = getCacheControl(image);
|
|
39
|
+
return marker == null ? text : withCacheControl(text, marker);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* `block` with its image replaced by the marker, or a native `tool_result` or
|
|
44
|
+
* custom-content `document` with the images inside it replaced; `block` itself
|
|
45
|
+
* when it holds no image.
|
|
46
|
+
*/
|
|
47
|
+
export function omitImageBlock(
|
|
48
|
+
block: MessageContentComplex
|
|
49
|
+
): MessageContentComplex {
|
|
50
|
+
if (isImageContentBlock(block)) {
|
|
51
|
+
return toOmittedImageBlock(block);
|
|
52
|
+
}
|
|
53
|
+
if (block.type === 'tool_result' && Array.isArray(block.content)) {
|
|
54
|
+
const nested = omitImageBlocks(block.content as MessageContentComplex[]);
|
|
55
|
+
return nested == null ? block : { ...block, content: nested };
|
|
56
|
+
}
|
|
57
|
+
const source =
|
|
58
|
+
block.type === 'document'
|
|
59
|
+
? (block as { source?: { type?: unknown; content?: unknown } }).source
|
|
60
|
+
: undefined;
|
|
61
|
+
if (
|
|
62
|
+
source == null ||
|
|
63
|
+
typeof source !== 'object' ||
|
|
64
|
+
source.type !== 'content' ||
|
|
65
|
+
!Array.isArray(source.content)
|
|
66
|
+
) {
|
|
67
|
+
return block;
|
|
68
|
+
}
|
|
69
|
+
const nested = omitImageBlocks(source.content as MessageContentComplex[]);
|
|
70
|
+
return nested == null
|
|
71
|
+
? block
|
|
72
|
+
: { ...block, source: { ...source, content: nested } };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* A tool artifact with the images in its `content` replaced by markers, for
|
|
77
|
+
* the request it is expanded into; `undefined` when it holds none.
|
|
78
|
+
*/
|
|
79
|
+
export function omitArtifactImages(
|
|
80
|
+
artifact: unknown
|
|
81
|
+
): Record<string, unknown> | undefined {
|
|
82
|
+
if (artifact == null || typeof artifact !== 'object') {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
const { content } = artifact as { content?: unknown };
|
|
86
|
+
if (!Array.isArray(content)) {
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
const omitted = omitImageBlocks(content as MessageContentComplex[]);
|
|
90
|
+
return omitted == null ? undefined : { ...artifact, content: omitted };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** `content` with every image replaced by its marker; `undefined` when it holds none. */
|
|
94
|
+
export function omitImageBlocks(
|
|
95
|
+
content: MessageContentComplex[]
|
|
96
|
+
): MessageContentComplex[] | undefined {
|
|
97
|
+
let omitted: MessageContentComplex[] | undefined;
|
|
98
|
+
for (let index = 0; index < content.length; index++) {
|
|
99
|
+
const block = content[index];
|
|
100
|
+
const replacement = omitImageBlock(block);
|
|
101
|
+
if (replacement === block) {
|
|
102
|
+
omitted?.push(block);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
omitted ??= content.slice(0, index);
|
|
106
|
+
omitted.push(replacement);
|
|
107
|
+
}
|
|
108
|
+
return omitted;
|
|
109
|
+
}
|
|
@@ -7,6 +7,21 @@ import { PreparedSubagentError } from '@/tools/preparedSubagents';
|
|
|
7
7
|
import { StreamLimitExceededError } from '@/llm/streamLimits';
|
|
8
8
|
|
|
9
9
|
export const PROVIDER_TEXT_PROTECTION_VERSION = 1;
|
|
10
|
+
export const PROVIDER_TEXT_BATCHING_VERSION = 1;
|
|
11
|
+
export const BATCHED_PROVIDER_EVENT_OWNER = 'librechat:batched-provider-event-owner';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Opt in only when every rule is substring-local with a certified maximum match width.
|
|
15
|
+
* No anchors, surrounding-context assertions, or partial rewrites. Classification and
|
|
16
|
+
* inspection must be valid over overlapping UTF-16 windows. Omit this option to inspect
|
|
17
|
+
* the whole reply without releasing any prose early.
|
|
18
|
+
*/
|
|
19
|
+
export interface ProviderTextBatching {
|
|
20
|
+
readonly version: 1;
|
|
21
|
+
readonly batchBytes: number;
|
|
22
|
+
readonly flushMs: number;
|
|
23
|
+
readonly maxMatchChars: number;
|
|
24
|
+
}
|
|
10
25
|
|
|
11
26
|
export type ProviderTextProtectionErrorCode =
|
|
12
27
|
| 'blocked'
|
|
@@ -43,6 +58,7 @@ export interface ProviderTextProtection {
|
|
|
43
58
|
readonly maxAttemptBytes: number;
|
|
44
59
|
/** Shared across all attempts using this policy, including child graphs. */
|
|
45
60
|
readonly maxBufferedBytes: number;
|
|
61
|
+
readonly batching?: ProviderTextBatching;
|
|
46
62
|
readonly classify: (content: string) => 'prose' | 'unsupported';
|
|
47
63
|
readonly inspect: (input: {
|
|
48
64
|
readonly version: 1;
|
|
@@ -214,6 +230,25 @@ export function validateProviderTextProtection(
|
|
|
214
230
|
) {
|
|
215
231
|
throw new ProviderTextProtectionError('incompatible');
|
|
216
232
|
}
|
|
233
|
+
const batch = policy.batching as
|
|
234
|
+
| (Omit<ProviderTextBatching, 'version'> & { version: number })
|
|
235
|
+
| null
|
|
236
|
+
| undefined;
|
|
237
|
+
if (
|
|
238
|
+
batch !== undefined &&
|
|
239
|
+
(batch == null ||
|
|
240
|
+
batch.version !== 1 ||
|
|
241
|
+
!Number.isSafeInteger(batch.batchBytes) ||
|
|
242
|
+
batch.batchBytes < 2 ||
|
|
243
|
+
!Number.isSafeInteger(batch.maxMatchChars) ||
|
|
244
|
+
batch.maxMatchChars < 1 ||
|
|
245
|
+
(batch.maxMatchChars - 1) * 2 > batch.batchBytes ||
|
|
246
|
+
batch.batchBytes > policy.maxAttemptBytes ||
|
|
247
|
+
!Number.isSafeInteger(batch.flushMs) ||
|
|
248
|
+
batch.flushMs < 1 ||
|
|
249
|
+
batch.flushMs > policy.timeoutMs)
|
|
250
|
+
)
|
|
251
|
+
throw new ProviderTextProtectionError('incompatible');
|
|
217
252
|
}
|
|
218
253
|
|
|
219
254
|
export interface ProviderTextAttemptOptions {
|
|
@@ -233,6 +268,9 @@ export class ProviderTextAttempt {
|
|
|
233
268
|
private readonly timer: ReturnType<typeof setTimeout>;
|
|
234
269
|
private readonly abort: () => void;
|
|
235
270
|
private finished = false;
|
|
271
|
+
private publishedText = false;
|
|
272
|
+
private finishHeld = false;
|
|
273
|
+
private finishPending = false;
|
|
236
274
|
private readonly admission?: ProviderTextAdmissionLease;
|
|
237
275
|
|
|
238
276
|
constructor(
|
|
@@ -285,6 +323,25 @@ export class ProviderTextAttempt {
|
|
|
285
323
|
return this.controller.signal;
|
|
286
324
|
}
|
|
287
325
|
|
|
326
|
+
followSignal(signal?: AbortSignal): (() => void) | undefined {
|
|
327
|
+
if (signal == null || signal === this.signal || signal === this.parent) return;
|
|
328
|
+
const abort = (): void => this.controller.abort(protectionAbortError(signal));
|
|
329
|
+
if (signal.aborted) {
|
|
330
|
+
abort();
|
|
331
|
+
this.check();
|
|
332
|
+
}
|
|
333
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
334
|
+
return (): void => signal.removeEventListener('abort', abort);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
get hasPublishedText(): boolean {
|
|
338
|
+
return this.publishedText;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
markTextPublished(): void {
|
|
342
|
+
this.publishedText = true;
|
|
343
|
+
}
|
|
344
|
+
|
|
288
345
|
check(): void {
|
|
289
346
|
if (this.finished) throw new ProviderTextProtectionError('incompatible');
|
|
290
347
|
if (this.signal.aborted) throw this.signal.reason;
|
|
@@ -347,13 +404,25 @@ export class ProviderTextAttempt {
|
|
|
347
404
|
this.charge(bytes);
|
|
348
405
|
}
|
|
349
406
|
|
|
407
|
+
/** Release staged window charges after its raw references and inspector have settled. */
|
|
408
|
+
releaseWindow(bytes: number): void {
|
|
409
|
+
this.admission?.uncharge(bytes);
|
|
410
|
+
this.bytes -= bytes;
|
|
411
|
+
this.budget.bytes -= bytes;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
stop(error: ProviderTextProtectionError): void {
|
|
415
|
+
this.controller.abort(error);
|
|
416
|
+
}
|
|
417
|
+
|
|
350
418
|
observeChunk(): void {
|
|
351
419
|
this.check();
|
|
352
420
|
this.charge(128);
|
|
353
421
|
}
|
|
354
422
|
|
|
355
|
-
|
|
356
|
-
|
|
423
|
+
/** Approved-text callbacks can stop blocking cleanup without retaining raw capacity. */
|
|
424
|
+
async wait<T>(work: Promise<T>, retain = true): Promise<T> {
|
|
425
|
+
if (retain) this.pending.add(work);
|
|
357
426
|
return new Promise<T>((resolve, reject) => {
|
|
358
427
|
const abort = (): void => {
|
|
359
428
|
this.signal.removeEventListener('abort', abort);
|
|
@@ -363,7 +432,7 @@ export class ProviderTextAttempt {
|
|
|
363
432
|
if (this.signal.aborted) abort();
|
|
364
433
|
const settle = (): void => {
|
|
365
434
|
this.signal.removeEventListener('abort', abort);
|
|
366
|
-
this.pending.delete(work);
|
|
435
|
+
if (retain) this.pending.delete(work);
|
|
367
436
|
};
|
|
368
437
|
void work.then(
|
|
369
438
|
(value) => {
|
|
@@ -378,9 +447,8 @@ export class ProviderTextAttempt {
|
|
|
378
447
|
});
|
|
379
448
|
}
|
|
380
449
|
|
|
381
|
-
async
|
|
450
|
+
async inspect(content: string): Promise<string> {
|
|
382
451
|
this.check();
|
|
383
|
-
const content = this.fragments.join('');
|
|
384
452
|
if (!content) return '';
|
|
385
453
|
let result: ProviderTextProtectionResult;
|
|
386
454
|
try {
|
|
@@ -409,12 +477,33 @@ export class ProviderTextAttempt {
|
|
|
409
477
|
this.check();
|
|
410
478
|
const canonical = validateResult(result);
|
|
411
479
|
this.check();
|
|
412
|
-
this.charge(canonical.length * 2);
|
|
413
480
|
return canonical;
|
|
414
481
|
}
|
|
415
482
|
|
|
483
|
+
async release(): Promise<string> {
|
|
484
|
+
this.check();
|
|
485
|
+
const content = this.fragments.join('');
|
|
486
|
+
if (!content) return '';
|
|
487
|
+
const canonical = await this.inspect(content);
|
|
488
|
+
this.retain(canonical.length * 2);
|
|
489
|
+
return canonical;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** Native prefetch can end the iterator while the invocation still dispatches its final chunk. */
|
|
493
|
+
holdFinish(): () => void {
|
|
494
|
+
this.finishHeld = true;
|
|
495
|
+
return (): void => {
|
|
496
|
+
this.finishHeld = false;
|
|
497
|
+
if (this.finishPending) this.finish();
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
416
501
|
finish(): void {
|
|
417
502
|
if (this.finished) return;
|
|
503
|
+
if (this.finishHeld) {
|
|
504
|
+
this.finishPending = true;
|
|
505
|
+
return;
|
|
506
|
+
}
|
|
418
507
|
this.finished = true;
|
|
419
508
|
clearTimeout(this.timer);
|
|
420
509
|
try {
|
|
@@ -16,6 +16,7 @@ export interface ProviderTextAdmissionSnapshot {
|
|
|
16
16
|
/** Internal ownership lease; only the attempt that acquires it may release it. */
|
|
17
17
|
export interface ProviderTextAdmissionLease {
|
|
18
18
|
charge(bytes: number): void;
|
|
19
|
+
uncharge(bytes: number): void;
|
|
19
20
|
retain(): void;
|
|
20
21
|
release(): void;
|
|
21
22
|
}
|
|
@@ -66,6 +67,11 @@ export class ProviderTextAdmission {
|
|
|
66
67
|
bytes += amount;
|
|
67
68
|
if (retained) this.retainedBytes += amount;
|
|
68
69
|
},
|
|
70
|
+
uncharge: (amount): void => {
|
|
71
|
+
this.bufferedBytes -= amount;
|
|
72
|
+
bytes -= amount;
|
|
73
|
+
if (retained) this.retainedBytes -= amount;
|
|
74
|
+
},
|
|
69
75
|
retain: (): void => {
|
|
70
76
|
if (retained || released) return;
|
|
71
77
|
retained = true;
|
package/src/run.ts
CHANGED
|
@@ -95,6 +95,10 @@ import {
|
|
|
95
95
|
findCallback,
|
|
96
96
|
type CallbackEntry,
|
|
97
97
|
} from '@/utils/callbacks';
|
|
98
|
+
import {
|
|
99
|
+
BATCHED_PROVIDER_EVENT_OWNER,
|
|
100
|
+
ProviderTextProtectionError,
|
|
101
|
+
} from '@/protection/providerText';
|
|
98
102
|
import {
|
|
99
103
|
resolveLangfuseRuntimeScope,
|
|
100
104
|
withLangfuseRuntimeScope,
|
|
@@ -108,7 +112,6 @@ import {
|
|
|
108
112
|
createTitleRunnable,
|
|
109
113
|
} from '@/utils/title';
|
|
110
114
|
import { applyGraphRuntimeConfig } from '@/graphs/applyGraphRuntimeConfig';
|
|
111
|
-
import { ProviderTextProtectionError } from '@/protection/providerText';
|
|
112
115
|
import { LANGFUSE_OPERATION_METADATA_KEY } from '@/langfuseOperation';
|
|
113
116
|
import { createTokenCounter, encodingForModel } from '@/utils/tokens';
|
|
114
117
|
import { stampSyntheticProviderMessage } from '@/messages/provenance';
|
|
@@ -635,6 +638,15 @@ export class Run<_T extends t.BaseGraphState> {
|
|
|
635
638
|
throw new ToolResultProtectionError('incompatible');
|
|
636
639
|
}
|
|
637
640
|
|
|
641
|
+
if (
|
|
642
|
+
this.providerTextProtection?.batching != null &&
|
|
643
|
+
(config.humanInTheLoop?.enabled === true ||
|
|
644
|
+
('agents' in config.graphConfig &&
|
|
645
|
+
config.graphConfig.agents.length !== 1))
|
|
646
|
+
) {
|
|
647
|
+
throw new ProviderTextProtectionError('unsupported');
|
|
648
|
+
}
|
|
649
|
+
|
|
638
650
|
/** Handle different graph types */
|
|
639
651
|
if (config.graphConfig.type === 'multi-agent') {
|
|
640
652
|
if (
|
|
@@ -1628,6 +1640,14 @@ export class Run<_T extends t.BaseGraphState> {
|
|
|
1628
1640
|
for await (const event of stream) {
|
|
1629
1641
|
const { data, metadata, ...info } = event;
|
|
1630
1642
|
const eventName: t.EventName = info.event;
|
|
1643
|
+
// The batched attempt owns start and delta delivery and their deadline.
|
|
1644
|
+
if (
|
|
1645
|
+
this.providerTextProtection?.batching != null &&
|
|
1646
|
+
(eventName === GraphEvents.CHAT_MODEL_START ||
|
|
1647
|
+
eventName === GraphEvents.CHAT_MODEL_STREAM) &&
|
|
1648
|
+
metadata[BATCHED_PROVIDER_EVENT_OWNER] === true
|
|
1649
|
+
)
|
|
1650
|
+
continue;
|
|
1631
1651
|
|
|
1632
1652
|
if (CUSTOM_GRAPH_EVENTS.has(eventName)) {
|
|
1633
1653
|
continue;
|
|
@@ -1672,6 +1692,7 @@ export class Run<_T extends t.BaseGraphState> {
|
|
|
1672
1692
|
}
|
|
1673
1693
|
|
|
1674
1694
|
if (eventName === GraphEvents.CHAT_MODEL_END && this.Graph != null) {
|
|
1695
|
+
await this.Graph.settleSearchCitations(metadata);
|
|
1675
1696
|
await this.Graph.closeOpenMessageStep(metadata, modelEndAt);
|
|
1676
1697
|
}
|
|
1677
1698
|
|
package/src/runtime/client.ts
CHANGED
|
@@ -28,6 +28,7 @@ import type { SdkAgentIdentity } from './identity';
|
|
|
28
28
|
import {
|
|
29
29
|
Run,
|
|
30
30
|
ToolResultProtectionError,
|
|
31
|
+
ProviderTextProtectionError,
|
|
31
32
|
executeHooks,
|
|
32
33
|
GraphEvents,
|
|
33
34
|
HOOK_EVENTS,
|
|
@@ -67,6 +68,8 @@ export async function createRemoteSdkRun({
|
|
|
67
68
|
);
|
|
68
69
|
if (config.toolResultProtection != null)
|
|
69
70
|
throw new ToolResultProtectionError('unsupported');
|
|
71
|
+
if (config.providerTextProtection?.batching != null)
|
|
72
|
+
throw new ProviderTextProtectionError('unsupported');
|
|
70
73
|
if (config.providerTextProtection && !hostServices?.providerText)
|
|
71
74
|
throw new Error(
|
|
72
75
|
'Remote SDK provider protection requires a supported policy adapter'
|