@librechat/agents 4.2.1 → 4.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/langfuse.cjs +11 -2
- package/dist/cjs/langfuse.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +40 -14
- package/dist/cjs/llm/openai/index.cjs.map +1 -1
- package/dist/cjs/stream.cjs +1 -0
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/node.cjs +72 -47
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/esm/langfuse.mjs +11 -2
- package/dist/esm/langfuse.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +40 -14
- package/dist/esm/llm/openai/index.mjs.map +1 -1
- package/dist/esm/stream.mjs +1 -0
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/node.mjs +73 -49
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/types/summarization/node.d.ts +21 -3
- package/dist/types/types/stream.d.ts +2 -0
- package/dist/types/types/summarize.d.ts +8 -0
- package/package.json +6 -5
- package/src/langfuse.ts +25 -4
- package/src/llm/openai/index.ts +99 -33
- package/src/stream.ts +22 -8
- package/src/summarization/node.ts +508 -238
- package/src/types/stream.ts +2 -0
- package/src/types/summarize.ts +8 -0
|
@@ -35,19 +35,30 @@ import {
|
|
|
35
35
|
DEFAULT_SUMMARY_OUTPUT_TOKENS,
|
|
36
36
|
DEFAULT_RETAIN_RECENT_TOKENS,
|
|
37
37
|
} from './input';
|
|
38
|
-
import {
|
|
38
|
+
import {
|
|
39
|
+
classifySummarizationError,
|
|
40
|
+
withSummarizationRetry,
|
|
41
|
+
withSummarizationRetryOwner,
|
|
42
|
+
ReasoningOnlySummaryError,
|
|
43
|
+
} from './retry';
|
|
39
44
|
import {
|
|
40
45
|
DEFAULT_RETAIN_RECENT_TURNS,
|
|
41
46
|
resolveIntraTurnRetainTokens,
|
|
42
47
|
splitAtRecencyBoundary,
|
|
43
48
|
} from '@/messages/recency';
|
|
44
|
-
import {
|
|
49
|
+
import {
|
|
50
|
+
isReasoningContentBlock,
|
|
51
|
+
hasMeaningfulReasoningContentBlock,
|
|
52
|
+
} from '@/messages/reasoningTypes';
|
|
45
53
|
import {
|
|
46
54
|
createTokenCounter,
|
|
47
55
|
encodingForModel,
|
|
48
56
|
encodingOfTokenCounter,
|
|
49
57
|
} from '@/utils/tokens';
|
|
50
|
-
import {
|
|
58
|
+
import {
|
|
59
|
+
prepareProviderRequest,
|
|
60
|
+
resolveServingModelId,
|
|
61
|
+
} from '@/llm/prepareProviderRequest';
|
|
51
62
|
import {
|
|
52
63
|
Constants,
|
|
53
64
|
ContentTypes,
|
|
@@ -75,7 +86,6 @@ import { getProviderStopReasons } from '@/llm/truncation';
|
|
|
75
86
|
import { isProviderCancellation } from '@/utils/errors';
|
|
76
87
|
import { isReasoningModel } from '@/llm/openai/utils';
|
|
77
88
|
import { initializeModel } from '@/llm/init';
|
|
78
|
-
import { getChunkContent } from '@/stream';
|
|
79
89
|
import { executeHooks } from '@/hooks';
|
|
80
90
|
|
|
81
91
|
/** Maximum number of tool failures to include in the enrichment section. */
|
|
@@ -182,10 +192,13 @@ function buildSummarizationClientConfig(
|
|
|
182
192
|
? { ...agentContext.clientOptions }
|
|
183
193
|
: {};
|
|
184
194
|
|
|
185
|
-
const clientOptions: Record<string, unknown> = withSummarizationRetryOwner(
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
195
|
+
const clientOptions: Record<string, unknown> = withSummarizationRetryOwner(
|
|
196
|
+
provider,
|
|
197
|
+
{
|
|
198
|
+
...baseOptions,
|
|
199
|
+
...llmParams,
|
|
200
|
+
}
|
|
201
|
+
);
|
|
189
202
|
|
|
190
203
|
if (modelName != null && modelName !== '') {
|
|
191
204
|
clientOptions.model = modelName;
|
|
@@ -197,14 +210,21 @@ function buildSummarizationClientConfig(
|
|
|
197
210
|
const explicitOutputTokens = readSummaryOutputLimit(provider, llmParams);
|
|
198
211
|
clearSummaryOutputLimits(provider, clientOptions);
|
|
199
212
|
let effectiveMaxSummaryTokens =
|
|
200
|
-
paramMaxSummaryTokens ??
|
|
213
|
+
paramMaxSummaryTokens ??
|
|
214
|
+
summarizationConfig?.maxSummaryTokens ??
|
|
215
|
+
explicitOutputTokens;
|
|
201
216
|
if (effectiveMaxSummaryTokens == null) {
|
|
202
217
|
effectiveMaxSummaryTokens = resolveSummaryOutputTokens(
|
|
203
|
-
provider,
|
|
218
|
+
provider,
|
|
219
|
+
clientOptions,
|
|
220
|
+
agentContext.maxContextTokens,
|
|
221
|
+
inheritedOutputTokens
|
|
204
222
|
);
|
|
205
223
|
}
|
|
206
|
-
if (effectiveMaxSummaryTokens === -1 && usesCompletionTokenAlias(provider))
|
|
207
|
-
|
|
224
|
+
if (effectiveMaxSummaryTokens === -1 && usesCompletionTokenAlias(provider))
|
|
225
|
+
effectiveMaxSummaryTokens = undefined;
|
|
226
|
+
if (effectiveMaxSummaryTokens != null)
|
|
227
|
+
clientOptions[outputKey] = effectiveMaxSummaryTokens;
|
|
208
228
|
|
|
209
229
|
return {
|
|
210
230
|
provider,
|
|
@@ -217,7 +237,9 @@ function buildSummarizationClientConfig(
|
|
|
217
237
|
}
|
|
218
238
|
|
|
219
239
|
function usesCompletionTokenAlias(provider: t.ProviderName): boolean {
|
|
220
|
-
return
|
|
240
|
+
return (
|
|
241
|
+
getProviderFamily(provider) === 'openai' || provider === Providers.MOONSHOT
|
|
242
|
+
);
|
|
221
243
|
}
|
|
222
244
|
|
|
223
245
|
function readSummaryOutputLimit(
|
|
@@ -250,26 +272,39 @@ function readSummaryOutputLimit(
|
|
|
250
272
|
aliasedCompletionLimit) as number | undefined;
|
|
251
273
|
}
|
|
252
274
|
|
|
253
|
-
function clearSummaryOutputLimits(
|
|
275
|
+
function clearSummaryOutputLimits(
|
|
276
|
+
provider: t.ProviderName,
|
|
277
|
+
options: Record<string, unknown>
|
|
278
|
+
): void {
|
|
254
279
|
delete options[getMaxOutputTokensKey(provider)];
|
|
255
280
|
const openai = usesCompletionTokenAlias(provider);
|
|
256
281
|
if (openai) delete options.maxCompletionTokens;
|
|
257
282
|
const key = openai ? 'modelKwargs' : 'invocationKwargs';
|
|
258
|
-
if (
|
|
283
|
+
if (
|
|
284
|
+
!openai &&
|
|
285
|
+
provider !== Providers.ANTHROPIC &&
|
|
286
|
+
getProviderFamily(provider) !== 'anthropic'
|
|
287
|
+
)
|
|
288
|
+
return;
|
|
259
289
|
const native = options[key] as object | undefined;
|
|
260
290
|
if (native == null) return;
|
|
261
|
-
const normalized = {...native};
|
|
262
|
-
for (const field of openai
|
|
291
|
+
const normalized = { ...native };
|
|
292
|
+
for (const field of openai
|
|
293
|
+
? ['max_output_tokens', 'max_completion_tokens', 'max_tokens']
|
|
294
|
+
: ['max_tokens']) {
|
|
263
295
|
Reflect.deleteProperty(normalized, field);
|
|
264
296
|
}
|
|
265
297
|
options[key] = normalized;
|
|
266
298
|
}
|
|
267
299
|
|
|
268
|
-
function resolveSummaryReasoning(
|
|
300
|
+
function resolveSummaryReasoning(
|
|
301
|
+
provider: t.ProviderName,
|
|
302
|
+
clientOptions: Record<string, unknown>
|
|
303
|
+
): { enabled: boolean; fixedBudget: number } {
|
|
269
304
|
type ReasoningOptions = {
|
|
270
305
|
reasoningEffort?: string;
|
|
271
306
|
reasoning_effort?: string;
|
|
272
|
-
reasoning?: {effort?: string; enabled?: boolean; max_tokens?: number};
|
|
307
|
+
reasoning?: { effort?: string; enabled?: boolean; max_tokens?: number };
|
|
273
308
|
thinking?: t.AnthropicReasoning['thinking'];
|
|
274
309
|
thinkingBudget?: number;
|
|
275
310
|
thinkingConfig?: t.GoogleThinkingConfig;
|
|
@@ -282,34 +317,72 @@ function resolveSummaryReasoning(provider: t.ProviderName, clientOptions: Record
|
|
|
282
317
|
};
|
|
283
318
|
const family = getProviderFamily(provider);
|
|
284
319
|
const google = options.thinkingConfig;
|
|
285
|
-
if (
|
|
320
|
+
if (
|
|
321
|
+
provider === Providers.GOOGLE ||
|
|
322
|
+
provider === Providers.VERTEXAI ||
|
|
323
|
+
family === 'google'
|
|
324
|
+
) {
|
|
286
325
|
const budget = google?.thinkingBudget ?? options.thinkingBudget;
|
|
287
|
-
const hasLevel =
|
|
288
|
-
|
|
326
|
+
const hasLevel =
|
|
327
|
+
google?.thinkingLevel != null &&
|
|
328
|
+
google.thinkingLevel !== 'THINKING_LEVEL_UNSPECIFIED';
|
|
329
|
+
const fixedBudget =
|
|
330
|
+
budget != null && Number.isFinite(budget) && budget > 0 ? budget : 0;
|
|
289
331
|
return {
|
|
290
332
|
enabled: hasLevel || (budget != null && (budget > 0 || budget === -1)),
|
|
291
|
-
fixedBudget:
|
|
333
|
+
fixedBudget:
|
|
334
|
+
provider === Providers.VERTEXAI && hasLevel ? 0 : fixedBudget,
|
|
292
335
|
};
|
|
293
336
|
}
|
|
294
|
-
const thinking =
|
|
295
|
-
|
|
296
|
-
|
|
337
|
+
const thinking =
|
|
338
|
+
(provider === Providers.ANTHROPIC || family === 'anthropic'
|
|
339
|
+
? options.invocationKwargs?.thinking
|
|
340
|
+
: undefined) ??
|
|
341
|
+
options.thinking ??
|
|
342
|
+
options.additionalModelRequestFields?.thinking ??
|
|
343
|
+
options.modelKwargs?.thinking;
|
|
297
344
|
if (thinking != null) {
|
|
298
|
-
const enabled =
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
345
|
+
const enabled =
|
|
346
|
+
thinking === true ||
|
|
347
|
+
(typeof thinking === 'object' &&
|
|
348
|
+
(thinking.type === 'enabled' || thinking.type === 'adaptive'));
|
|
349
|
+
let budget =
|
|
350
|
+
thinking === true
|
|
351
|
+
? (options.thinkingBudget ??
|
|
352
|
+
options.additionalModelRequestFields?.thinkingBudget)
|
|
353
|
+
: 0;
|
|
354
|
+
if (typeof thinking === 'object' && thinking.type === 'enabled')
|
|
355
|
+
budget = thinking.budget_tokens;
|
|
356
|
+
return {
|
|
357
|
+
enabled,
|
|
358
|
+
fixedBudget:
|
|
359
|
+
enabled && budget != null && Number.isFinite(budget) && budget > 0
|
|
360
|
+
? budget
|
|
361
|
+
: 0,
|
|
362
|
+
};
|
|
303
363
|
}
|
|
304
|
-
const reasoning = {...options.modelKwargs?.reasoning, ...options.reasoning};
|
|
305
|
-
const effort =
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
364
|
+
const reasoning = { ...options.modelKwargs?.reasoning, ...options.reasoning };
|
|
365
|
+
const effort =
|
|
366
|
+
reasoning.effort ??
|
|
367
|
+
options.reasoningEffort ??
|
|
368
|
+
options.reasoning_effort ??
|
|
369
|
+
options.modelKwargs?.reasoning_effort ??
|
|
370
|
+
options.modelKwargs?.reasoningEffort;
|
|
371
|
+
return {
|
|
372
|
+
enabled:
|
|
373
|
+
reasoning.enabled !== false &&
|
|
374
|
+
((effort != null &&
|
|
375
|
+
effort !== '' &&
|
|
376
|
+
effort !== 'none' &&
|
|
377
|
+
effort !== 'disabled') ||
|
|
378
|
+
reasoning.enabled === true ||
|
|
379
|
+
(reasoning.max_tokens != null && reasoning.max_tokens > 0) ||
|
|
380
|
+
(provider === Providers.OPENROUTER &&
|
|
381
|
+
options.reasoning == null &&
|
|
382
|
+
options.modelKwargs?.reasoning == null &&
|
|
383
|
+
options.include_reasoning === true)),
|
|
384
|
+
fixedBudget: 0,
|
|
385
|
+
};
|
|
313
386
|
}
|
|
314
387
|
|
|
315
388
|
function resolveSummaryOutputTokens(
|
|
@@ -319,30 +392,49 @@ function resolveSummaryOutputTokens(
|
|
|
319
392
|
inheritedOutputTokens?: number
|
|
320
393
|
): number | undefined {
|
|
321
394
|
const explicit = readSummaryOutputLimit(provider, clientOptions);
|
|
322
|
-
if (explicit != null)
|
|
395
|
+
if (explicit != null)
|
|
396
|
+
return explicit === -1 && usesCompletionTokenAlias(provider)
|
|
397
|
+
? undefined
|
|
398
|
+
: explicit;
|
|
323
399
|
const reasoning = resolveSummaryReasoning(provider, clientOptions);
|
|
324
|
-
if (
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
const
|
|
330
|
-
|
|
400
|
+
if (
|
|
401
|
+
reasoning.enabled &&
|
|
402
|
+
(inheritedOutputTokens == null || inheritedOutputTokens === -1)
|
|
403
|
+
)
|
|
404
|
+
return undefined;
|
|
405
|
+
const defaultOutputTokens =
|
|
406
|
+
reasoning.fixedBudget +
|
|
407
|
+
Math.min(
|
|
408
|
+
DEFAULT_SUMMARY_OUTPUT_TOKENS,
|
|
409
|
+
Math.max(1, Math.floor((maxContextTokens ?? 40_960) * 0.1))
|
|
410
|
+
);
|
|
411
|
+
const inherited =
|
|
412
|
+
reasoning.enabled &&
|
|
413
|
+
inheritedOutputTokens != null &&
|
|
414
|
+
Number.isFinite(inheritedOutputTokens) &&
|
|
415
|
+
inheritedOutputTokens > 0
|
|
416
|
+
? inheritedOutputTokens
|
|
417
|
+
: 0;
|
|
331
418
|
return Math.max(defaultOutputTokens, inherited);
|
|
332
419
|
}
|
|
333
420
|
|
|
334
421
|
function resolveSummaryOutputReserve(model: t.ChatModel): number {
|
|
335
422
|
let candidate: object | undefined = model;
|
|
336
423
|
const seen = new Set<object>();
|
|
337
|
-
for (
|
|
424
|
+
for (
|
|
425
|
+
let depth = 0;
|
|
426
|
+
candidate != null && depth < 20 && !seen.has(candidate);
|
|
427
|
+
depth++
|
|
428
|
+
) {
|
|
338
429
|
seen.add(candidate);
|
|
339
430
|
const runnable = candidate as {
|
|
340
|
-
profile?: {maxOutputTokens?: number};
|
|
431
|
+
profile?: { maxOutputTokens?: number };
|
|
341
432
|
bound?: object;
|
|
342
433
|
last?: object;
|
|
343
434
|
};
|
|
344
435
|
const maximum = runnable.profile?.maxOutputTokens;
|
|
345
|
-
if (maximum != null && Number.isSafeInteger(maximum) && maximum > 0)
|
|
436
|
+
if (maximum != null && Number.isSafeInteger(maximum) && maximum > 0)
|
|
437
|
+
return maximum;
|
|
346
438
|
candidate = runnable.bound ?? runnable.last;
|
|
347
439
|
}
|
|
348
440
|
throw new SummarizationInputTooLargeError();
|
|
@@ -501,8 +593,9 @@ async function prepareSummarizationBudget({
|
|
|
501
593
|
provider === agentContext.provider
|
|
502
594
|
? agentContext.systemRunnable
|
|
503
595
|
: undefined;
|
|
504
|
-
const toolTokens = usesAgentCounter
|
|
505
|
-
|
|
596
|
+
const toolTokens = usesAgentCounter
|
|
597
|
+
? agentContext.toolSchemaTokens
|
|
598
|
+
: countSummarizationToolTokens({ tools, provider, clientOptions, count });
|
|
506
599
|
let overhead = toolTokens;
|
|
507
600
|
if (system != null) {
|
|
508
601
|
overhead = usesAgentCounter
|
|
@@ -515,8 +608,10 @@ async function prepareSummarizationBudget({
|
|
|
515
608
|
const ratio = usesAgentCounter
|
|
516
609
|
? Math.max(1, agentContext.calibrationRatio)
|
|
517
610
|
: 1;
|
|
518
|
-
const outputReserve =
|
|
519
|
-
|
|
611
|
+
const outputReserve =
|
|
612
|
+
contextBudgetMode === 'window' && maxContextTokens != null
|
|
613
|
+
? (outputTokens ?? resolveSummaryOutputReserve(model))
|
|
614
|
+
: 0;
|
|
520
615
|
const budget =
|
|
521
616
|
maxContextTokens == null
|
|
522
617
|
? Number.MAX_SAFE_INTEGER
|
|
@@ -530,23 +625,49 @@ async function prepareSummarizationBudget({
|
|
|
530
625
|
return { count, system, budget };
|
|
531
626
|
}
|
|
532
627
|
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
628
|
+
/**
|
|
629
|
+
* What one summarization round has streamed. Deltas go out as the provider
|
|
630
|
+
* produces them, so an attempt that is then abandoned has already published
|
|
631
|
+
* text that is not the summary. `abandon` marks that text stale: the next delta
|
|
632
|
+
* to go out says to replace it, and `retract` withdraws it when none follows.
|
|
633
|
+
*/
|
|
634
|
+
export type SummaryDeltaStream = {
|
|
635
|
+
/** Call once per outgoing delta; true when it must replace what was streamed. */
|
|
636
|
+
next(): boolean;
|
|
637
|
+
abandon(): void;
|
|
638
|
+
retract(config?: RunnableConfig): Promise<void>;
|
|
639
|
+
};
|
|
640
|
+
|
|
641
|
+
export function createSummaryDeltaStream(stepId?: string): SummaryDeltaStream {
|
|
642
|
+
let streamed = false;
|
|
643
|
+
let stale = false;
|
|
644
|
+
return {
|
|
645
|
+
next(): boolean {
|
|
646
|
+
const reset = stale;
|
|
647
|
+
stale = false;
|
|
648
|
+
streamed = true;
|
|
649
|
+
return reset;
|
|
650
|
+
},
|
|
651
|
+
abandon(): void {
|
|
652
|
+
stale = streamed;
|
|
653
|
+
},
|
|
654
|
+
async retract(config?: RunnableConfig): Promise<void> {
|
|
655
|
+
if (!stale || stepId == null || stepId === '' || config == null) {
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
stale = false;
|
|
659
|
+
streamed = false;
|
|
543
660
|
await safeDispatchCustomEvent(
|
|
544
661
|
GraphEvents.ON_SUMMARIZE_DELTA,
|
|
545
|
-
|
|
662
|
+
{
|
|
663
|
+
id: stepId,
|
|
664
|
+
reset: true,
|
|
665
|
+
delta: { summary: { type: ContentTypes.SUMMARY, content: [] } },
|
|
666
|
+
} satisfies t.SummarizeDeltaEvent,
|
|
546
667
|
config
|
|
547
668
|
);
|
|
548
|
-
|
|
549
|
-
|
|
669
|
+
},
|
|
670
|
+
};
|
|
550
671
|
}
|
|
551
672
|
|
|
552
673
|
/**
|
|
@@ -797,27 +918,53 @@ function describeFallbackError(
|
|
|
797
918
|
* Runs the summarization LLM call with primary + fallback providers,
|
|
798
919
|
* preserving history when every provider fails.
|
|
799
920
|
*/
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
}
|
|
921
|
+
/**
|
|
922
|
+
* Runs the round and settles what it streamed: when the round ends without a
|
|
923
|
+
* summary, or with one that came from an attempt that did not stream, the text
|
|
924
|
+
* an earlier attempt published is withdrawn before the result is reported.
|
|
925
|
+
*/
|
|
926
|
+
async function executeSummarizationWithFallback(
|
|
927
|
+
params: Parameters<typeof runSummarizationAttempts>[0]
|
|
928
|
+
): ReturnType<typeof runSummarizationAttempts> {
|
|
929
|
+
const deltas = createSummaryDeltaStream(params.stepId);
|
|
930
|
+
try {
|
|
931
|
+
const result = await runSummarizationAttempts(params, deltas);
|
|
932
|
+
if (result.text === '') {
|
|
933
|
+
deltas.abandon();
|
|
934
|
+
}
|
|
935
|
+
return result;
|
|
936
|
+
} catch (error) {
|
|
937
|
+
deltas.abandon();
|
|
938
|
+
throw error;
|
|
939
|
+
} finally {
|
|
940
|
+
await deltas.retract(params.summarizeConfig);
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
async function runSummarizationAttempts(
|
|
945
|
+
params: {
|
|
946
|
+
agentContext: AgentContext;
|
|
947
|
+
messages: BaseMessage[];
|
|
948
|
+
requiredHeadLength: number;
|
|
949
|
+
clientConfig: SummarizationClientConfig;
|
|
950
|
+
summarizeConfig?: RunnableConfig;
|
|
951
|
+
stepId: string;
|
|
952
|
+
usePromptCache: boolean;
|
|
953
|
+
shrinkInput?: boolean;
|
|
954
|
+
semanticIndex: RenderedCompactionSemanticIndex;
|
|
955
|
+
log: LogFn;
|
|
956
|
+
onUsage: (attempt: t.SummarizationAttemptUsage) => void;
|
|
957
|
+
/** Carries the run's stream limits so the event cap covers summary streams. */
|
|
958
|
+
graph?: StreamLimitState & {
|
|
959
|
+
getBreakerSignal?: () => AbortSignal;
|
|
960
|
+
getToolsForBinding?: (
|
|
961
|
+
provider: t.ProviderName,
|
|
962
|
+
clientOptions: t.ClientOptions | undefined
|
|
963
|
+
) => t.GraphTools | undefined;
|
|
964
|
+
};
|
|
965
|
+
},
|
|
966
|
+
deltas: SummaryDeltaStream
|
|
967
|
+
): Promise<{
|
|
821
968
|
text: string;
|
|
822
969
|
usage?: Partial<UsageMetadata>;
|
|
823
970
|
provider: string;
|
|
@@ -880,11 +1027,17 @@ async function executeSummarizationWithFallback(params: {
|
|
|
880
1027
|
() =>
|
|
881
1028
|
summarizeWithCacheHit({
|
|
882
1029
|
agentContext,
|
|
883
|
-
onUsage: usage =>
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
1030
|
+
onUsage: (usage) =>
|
|
1031
|
+
onUsage({
|
|
1032
|
+
provider: clientConfig.provider as t.ProviderName,
|
|
1033
|
+
model:
|
|
1034
|
+
clientConfig.modelName ??
|
|
1035
|
+
resolveServingModelId(summarizationModel) ??
|
|
1036
|
+
resolveClientOptionsModel(
|
|
1037
|
+
clientConfig.clientOptions as t.ClientOptions
|
|
1038
|
+
),
|
|
1039
|
+
usage,
|
|
1040
|
+
}),
|
|
888
1041
|
shrinkInput,
|
|
889
1042
|
outputTokens: clientConfig.effectiveMaxSummaryTokens,
|
|
890
1043
|
clientOptions: clientConfig.clientOptions as t.ClientOptions,
|
|
@@ -899,30 +1052,30 @@ async function executeSummarizationWithFallback(params: {
|
|
|
899
1052
|
config: summarizeConfig,
|
|
900
1053
|
stepId,
|
|
901
1054
|
provider: clientConfig.provider,
|
|
902
|
-
reasoningKey: agentContext.reasoningKey,
|
|
903
1055
|
graph,
|
|
1056
|
+
deltas,
|
|
904
1057
|
usePromptCache,
|
|
905
1058
|
promptCacheTtl:
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
}
|
|
913
|
-
).promptCacheTtl
|
|
914
|
-
: undefined,
|
|
915
|
-
bedrockModelId:
|
|
916
|
-
clientConfig.provider === Providers.BEDROCK
|
|
917
|
-
? resolveBedrockCompactionCacheModel(
|
|
918
|
-
clientConfig.clientOptions as
|
|
919
|
-
| {
|
|
920
|
-
applicationInferenceProfile?: string;
|
|
921
|
-
model?: string;
|
|
1059
|
+
clientConfig.provider === Providers.ANTHROPIC ||
|
|
1060
|
+
clientConfig.provider === Providers.OPENROUTER ||
|
|
1061
|
+
clientConfig.provider === Providers.BEDROCK
|
|
1062
|
+
? (
|
|
1063
|
+
clientConfig.clientOptions as {
|
|
1064
|
+
promptCacheTtl?: PromptCacheTtl;
|
|
922
1065
|
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
:
|
|
1066
|
+
).promptCacheTtl
|
|
1067
|
+
: undefined,
|
|
1068
|
+
bedrockModelId:
|
|
1069
|
+
clientConfig.provider === Providers.BEDROCK
|
|
1070
|
+
? resolveBedrockCompactionCacheModel(
|
|
1071
|
+
clientConfig.clientOptions as
|
|
1072
|
+
| {
|
|
1073
|
+
applicationInferenceProfile?: string;
|
|
1074
|
+
model?: string;
|
|
1075
|
+
}
|
|
1076
|
+
| undefined
|
|
1077
|
+
)
|
|
1078
|
+
: undefined,
|
|
926
1079
|
log,
|
|
927
1080
|
}),
|
|
928
1081
|
{
|
|
@@ -963,6 +1116,7 @@ async function executeSummarizationWithFallback(params: {
|
|
|
963
1116
|
}
|
|
964
1117
|
|
|
965
1118
|
withBreakerSignal(summarizeConfig, graph)?.signal?.throwIfAborted();
|
|
1119
|
+
deltas.abandon();
|
|
966
1120
|
errorCode = classifySummarizationError(primaryError);
|
|
967
1121
|
|
|
968
1122
|
const primaryDescribed = describeProviderError(
|
|
@@ -985,27 +1139,34 @@ async function executeSummarizationWithFallback(params: {
|
|
|
985
1139
|
const maxContextTokens =
|
|
986
1140
|
fallback.maxContextTokens ?? agentContext.maxContextTokens;
|
|
987
1141
|
const outputTokens = resolveSummaryOutputTokens(
|
|
988
|
-
fallback.provider,
|
|
1142
|
+
fallback.provider,
|
|
1143
|
+
{ ...fallback.clientOptions },
|
|
1144
|
+
maxContextTokens
|
|
989
1145
|
);
|
|
990
|
-
const clientOptions: Record<string, unknown> =
|
|
1146
|
+
const clientOptions: Record<string, unknown> =
|
|
1147
|
+
withSummarizationRetryOwner(fallback.provider, {
|
|
1148
|
+
...fallback.clientOptions,
|
|
1149
|
+
});
|
|
991
1150
|
clearSummaryOutputLimits(fallback.provider, clientOptions);
|
|
992
|
-
if (outputTokens != null)
|
|
1151
|
+
if (outputTokens != null)
|
|
1152
|
+
clientOptions[getMaxOutputTokensKey(fallback.provider)] =
|
|
1153
|
+
outputTokens;
|
|
993
1154
|
return {
|
|
994
1155
|
...fallback,
|
|
995
1156
|
clientOptions,
|
|
996
1157
|
maxContextTokens,
|
|
997
|
-
contextBudgetMode:
|
|
998
|
-
|
|
1158
|
+
contextBudgetMode:
|
|
1159
|
+
fallback.maxContextTokens == null
|
|
1160
|
+
? agentContext.summarizationBudgetMode
|
|
1161
|
+
: (fallback.contextBudgetMode ?? 'window'),
|
|
999
1162
|
} as t.FallbackConfig;
|
|
1000
1163
|
});
|
|
1001
|
-
let fallbackIdentity: {provider: string; model?: string} | undefined;
|
|
1002
|
-
const pendingDeltas: t.SummarizeDeltaEvent[] = [];
|
|
1164
|
+
let fallbackIdentity: { provider: string; model?: string } | undefined;
|
|
1003
1165
|
const onChunk = createSummarizationChunkHandler({
|
|
1004
|
-
|
|
1166
|
+
deltas,
|
|
1005
1167
|
stepId,
|
|
1006
1168
|
config: traceConfig(summarizeConfig, 'cache_hit_compaction'),
|
|
1007
1169
|
provider: clientConfig.provider,
|
|
1008
|
-
reasoningKey: agentContext.reasoningKey,
|
|
1009
1170
|
graph,
|
|
1010
1171
|
});
|
|
1011
1172
|
const fallbackTools = agentContext.getToolsForBinding();
|
|
@@ -1023,11 +1184,14 @@ async function executeSummarizationWithFallback(params: {
|
|
|
1023
1184
|
config,
|
|
1024
1185
|
}) => {
|
|
1025
1186
|
config?.signal?.throwIfAborted();
|
|
1026
|
-
|
|
1187
|
+
deltas.abandon();
|
|
1027
1188
|
const instruction = buildSummarizationInstruction(
|
|
1028
|
-
clientConfig.promptText,
|
|
1189
|
+
clientConfig.promptText,
|
|
1190
|
+
clientConfig.updatePromptText,
|
|
1191
|
+
priorSummaryText,
|
|
1029
1192
|
semanticIndex.appendix,
|
|
1030
|
-
provider === agentContext.provider &&
|
|
1193
|
+
provider === agentContext.provider &&
|
|
1194
|
+
agentContext.systemRunnable != null
|
|
1031
1195
|
);
|
|
1032
1196
|
const { count, system, budget } = await prepareSummarizationBudget({
|
|
1033
1197
|
agentContext,
|
|
@@ -1036,7 +1200,9 @@ async function executeSummarizationWithFallback(params: {
|
|
|
1036
1200
|
clientOptions,
|
|
1037
1201
|
maxContextTokens,
|
|
1038
1202
|
contextBudgetMode,
|
|
1039
|
-
outputTokens: readSummaryOutputLimit(provider, {
|
|
1203
|
+
outputTokens: readSummaryOutputLimit(provider, {
|
|
1204
|
+
...clientOptions,
|
|
1205
|
+
}),
|
|
1040
1206
|
instruction,
|
|
1041
1207
|
tools: fallbackTools,
|
|
1042
1208
|
config,
|
|
@@ -1048,20 +1214,34 @@ async function executeSummarizationWithFallback(params: {
|
|
|
1048
1214
|
budget,
|
|
1049
1215
|
provider,
|
|
1050
1216
|
});
|
|
1051
|
-
const bedrock = clientOptions as
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1217
|
+
const bedrock = clientOptions as
|
|
1218
|
+
| t.BedrockAnthropicInput
|
|
1219
|
+
| undefined;
|
|
1220
|
+
const windowWithCache =
|
|
1221
|
+
provider === Providers.BEDROCK
|
|
1222
|
+
? applySummarizationHistoryCache({
|
|
1223
|
+
messages: bounded,
|
|
1224
|
+
provider,
|
|
1225
|
+
enabled: bedrock?.promptCache === true,
|
|
1226
|
+
promptCacheTtl: bedrock?.promptCacheTtl,
|
|
1227
|
+
bedrockModelId: resolveClientOptionsModel(clientOptions),
|
|
1228
|
+
})
|
|
1229
|
+
: bounded;
|
|
1230
|
+
const history =
|
|
1231
|
+
system == null
|
|
1232
|
+
? windowWithCache
|
|
1233
|
+
: await system.invoke(windowWithCache, config);
|
|
1058
1234
|
const request = prepareProviderRequest({
|
|
1059
1235
|
model,
|
|
1060
1236
|
messages: [...history, new HumanMessage(instruction)],
|
|
1061
1237
|
provider,
|
|
1062
1238
|
config,
|
|
1063
1239
|
});
|
|
1064
|
-
fallbackIdentity = {
|
|
1240
|
+
fallbackIdentity = {
|
|
1241
|
+
provider,
|
|
1242
|
+
model:
|
|
1243
|
+
request.modelId ?? resolveClientOptionsModel(clientOptions),
|
|
1244
|
+
};
|
|
1065
1245
|
return request;
|
|
1066
1246
|
},
|
|
1067
1247
|
config: withBreakerSignal(
|
|
@@ -1071,20 +1251,37 @@ async function executeSummarizationWithFallback(params: {
|
|
|
1071
1251
|
primaryError,
|
|
1072
1252
|
onChunk,
|
|
1073
1253
|
streamLimitState: graph,
|
|
1074
|
-
invokeModel: (params, config) =>
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1254
|
+
invokeModel: (params, config) =>
|
|
1255
|
+
withSummarizationRetry(
|
|
1256
|
+
async () => {
|
|
1257
|
+
deltas.abandon();
|
|
1258
|
+
const result = await attemptInvoke(
|
|
1259
|
+
{
|
|
1260
|
+
...params,
|
|
1261
|
+
onModelComplete: (response) => {
|
|
1262
|
+
params.onModelComplete?.(response);
|
|
1263
|
+
const usage = readSummarizationUsage(response);
|
|
1264
|
+
if (usage != null && fallbackIdentity != null)
|
|
1265
|
+
onUsage({
|
|
1266
|
+
provider: fallbackIdentity.provider as t.ProviderName,
|
|
1267
|
+
model: fallbackIdentity.model,
|
|
1268
|
+
usage,
|
|
1269
|
+
});
|
|
1270
|
+
},
|
|
1271
|
+
},
|
|
1272
|
+
config
|
|
1273
|
+
);
|
|
1274
|
+
config?.signal?.throwIfAborted();
|
|
1275
|
+
const response = result.messages?.[0];
|
|
1276
|
+
validateSummaryResponse(response);
|
|
1277
|
+
return result;
|
|
1278
|
+
},
|
|
1279
|
+
{
|
|
1280
|
+
signal: config?.signal,
|
|
1281
|
+
onRetry: (retry) =>
|
|
1282
|
+
log('debug', 'Retrying fallback summarization', retry),
|
|
1283
|
+
}
|
|
1284
|
+
),
|
|
1088
1285
|
});
|
|
1089
1286
|
const fbMsg = fbResult?.messages?.[0];
|
|
1090
1287
|
if (fbMsg) {
|
|
@@ -1093,14 +1290,12 @@ async function executeSummarizationWithFallback(params: {
|
|
|
1093
1290
|
fbMsg as { content: string | object }
|
|
1094
1291
|
);
|
|
1095
1292
|
if (summaryText !== '') {
|
|
1096
|
-
if (fallbackIdentity == null)
|
|
1293
|
+
if (fallbackIdentity == null)
|
|
1294
|
+
throw new Error('Missing successful fallback identity', {
|
|
1295
|
+
cause: primaryError,
|
|
1296
|
+
});
|
|
1097
1297
|
summaryProvider = fallbackIdentity.provider;
|
|
1098
1298
|
summaryModel = fallbackIdentity.model;
|
|
1099
|
-
await flushSummarizationDeltas(
|
|
1100
|
-
pendingDeltas,
|
|
1101
|
-
summarizeConfig,
|
|
1102
|
-
graph
|
|
1103
|
-
);
|
|
1104
1299
|
}
|
|
1105
1300
|
}
|
|
1106
1301
|
} catch (fbErr) {
|
|
@@ -1117,6 +1312,7 @@ async function executeSummarizationWithFallback(params: {
|
|
|
1117
1312
|
throw fbErr;
|
|
1118
1313
|
}
|
|
1119
1314
|
withBreakerSignal(summarizeConfig, graph)?.signal?.throwIfAborted();
|
|
1315
|
+
deltas.abandon();
|
|
1120
1316
|
errorCode = classifySummarizationError(fbErr);
|
|
1121
1317
|
const fbDescribed = describeFallbackError(fbErr, fallbacks);
|
|
1122
1318
|
log('warn', `Fallback providers also failed ${fbDescribed.suffix}`, {
|
|
@@ -1216,7 +1412,7 @@ async function dispatchCompletionEvents(params: {
|
|
|
1216
1412
|
id: stepId,
|
|
1217
1413
|
agentId,
|
|
1218
1414
|
summary: summaryBlock,
|
|
1219
|
-
...(attemptUsage.length > 0 ? {attemptUsage: [...attemptUsage]} : {}),
|
|
1415
|
+
...(attemptUsage.length > 0 ? { attemptUsage: [...attemptUsage] } : {}),
|
|
1220
1416
|
} satisfies t.SummarizeCompleteEvent,
|
|
1221
1417
|
runnableConfig
|
|
1222
1418
|
);
|
|
@@ -1522,22 +1718,20 @@ export function createSummarizeNode({
|
|
|
1522
1718
|
)
|
|
1523
1719
|
)
|
|
1524
1720
|
: undefined);
|
|
1525
|
-
const {
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
? retainTurns
|
|
1533
|
-
: (retainRecent.turns ?? DEFAULT_RETAIN_RECENT_TURNS),
|
|
1534
|
-
tokens: retainTokens,
|
|
1535
|
-
tokenCounter: recencyTokenCounter,
|
|
1536
|
-
intraTurnTokens: resolveIntraTurnRetainTokens({
|
|
1721
|
+
const { head: compactableHead, tail: projectedTail } =
|
|
1722
|
+
splitAtRecencyBoundary(windowMessages, {
|
|
1723
|
+
provider: agentContext.provider,
|
|
1724
|
+
turns:
|
|
1725
|
+
retainRecent == null
|
|
1726
|
+
? retainTurns
|
|
1727
|
+
: (retainRecent.turns ?? DEFAULT_RETAIN_RECENT_TURNS),
|
|
1537
1728
|
tokens: retainTokens,
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1729
|
+
tokenCounter: recencyTokenCounter,
|
|
1730
|
+
intraTurnTokens: resolveIntraTurnRetainTokens({
|
|
1731
|
+
tokens: retainTokens,
|
|
1732
|
+
maxContextTokens: agentContext.maxContextTokens,
|
|
1733
|
+
}),
|
|
1734
|
+
});
|
|
1541
1735
|
|
|
1542
1736
|
const messagesToRefine = compactableHead;
|
|
1543
1737
|
|
|
@@ -1571,8 +1765,10 @@ export function createSummarizeNode({
|
|
|
1571
1765
|
return { summarizationRequest: undefined };
|
|
1572
1766
|
}
|
|
1573
1767
|
|
|
1574
|
-
const messagesToRetain =
|
|
1575
|
-
|
|
1768
|
+
const messagesToRetain =
|
|
1769
|
+
windowMessages === state.messages
|
|
1770
|
+
? projectedTail
|
|
1771
|
+
: restoreRetainedMessages(projectedTail, state.messages);
|
|
1576
1772
|
|
|
1577
1773
|
const semanticIndex = renderCompactionSemanticIndex(
|
|
1578
1774
|
agentContext.compactionSemanticIndex,
|
|
@@ -1743,7 +1939,7 @@ export function createSummarizeNode({
|
|
|
1743
1939
|
agentContext,
|
|
1744
1940
|
messages: windowMessages,
|
|
1745
1941
|
requiredHeadLength: messagesToRefine.length,
|
|
1746
|
-
onUsage: attempt => {
|
|
1942
|
+
onUsage: (attempt) => {
|
|
1747
1943
|
attemptUsage.push(attempt);
|
|
1748
1944
|
runStep.usage = buildSummarizationStepUsage(attemptUsage);
|
|
1749
1945
|
},
|
|
@@ -1777,11 +1973,11 @@ export function createSummarizeNode({
|
|
|
1777
1973
|
} else {
|
|
1778
1974
|
await graph.dispatchRunStepCompleted(
|
|
1779
1975
|
stepId,
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1976
|
+
{
|
|
1977
|
+
type: 'summary',
|
|
1978
|
+
summary: placeholderSummary,
|
|
1979
|
+
} satisfies t.SummaryCompleted,
|
|
1980
|
+
runnableConfig
|
|
1785
1981
|
);
|
|
1786
1982
|
}
|
|
1787
1983
|
if (runnableConfig) {
|
|
@@ -1792,7 +1988,9 @@ export function createSummarizeNode({
|
|
|
1792
1988
|
agentId: request.agentId,
|
|
1793
1989
|
error: `Summarization failed during ${preservationReason}; conversation history was preserved`,
|
|
1794
1990
|
errorCode,
|
|
1795
|
-
...(attemptUsage.length > 0
|
|
1991
|
+
...(attemptUsage.length > 0
|
|
1992
|
+
? { attemptUsage: [...attemptUsage] }
|
|
1993
|
+
: {}),
|
|
1796
1994
|
} satisfies t.SummarizeCompleteEvent,
|
|
1797
1995
|
runnableConfig
|
|
1798
1996
|
);
|
|
@@ -1825,7 +2023,9 @@ export function createSummarizeNode({
|
|
|
1825
2023
|
agentId: request.agentId,
|
|
1826
2024
|
error: 'Summarization produced empty output',
|
|
1827
2025
|
errorCode: 'unknown',
|
|
1828
|
-
...(attemptUsage.length > 0
|
|
2026
|
+
...(attemptUsage.length > 0
|
|
2027
|
+
? { attemptUsage: [...attemptUsage] }
|
|
2028
|
+
: {}),
|
|
1829
2029
|
} satisfies t.SummarizeCompleteEvent,
|
|
1830
2030
|
runnableConfig
|
|
1831
2031
|
);
|
|
@@ -1927,10 +2127,16 @@ export function createSummarizeNode({
|
|
|
1927
2127
|
}
|
|
1928
2128
|
|
|
1929
2129
|
/** Extracts text from an LLM response, skipping reasoning/thinking blocks. */
|
|
1930
|
-
|
|
1931
|
-
|
|
2130
|
+
/** A streamed chunk's text block is `text_delta` from Anthropic, `text` elsewhere. */
|
|
2131
|
+
const CHUNK_TEXT_TYPES: readonly string[] = ['text', 'text_delta'];
|
|
2132
|
+
|
|
2133
|
+
/** The text a response or one streamed chunk carries, reasoning left out. */
|
|
2134
|
+
function collectText(
|
|
2135
|
+
content: unknown,
|
|
2136
|
+
textTypes: readonly string[] = ['text']
|
|
2137
|
+
): string {
|
|
1932
2138
|
if (typeof content === 'string') {
|
|
1933
|
-
return content
|
|
2139
|
+
return content;
|
|
1934
2140
|
}
|
|
1935
2141
|
if (!Array.isArray(content)) {
|
|
1936
2142
|
return '';
|
|
@@ -1952,11 +2158,19 @@ function extractResponseText(response: { content: string | object }): string {
|
|
|
1952
2158
|
) {
|
|
1953
2159
|
continue;
|
|
1954
2160
|
}
|
|
1955
|
-
if (
|
|
2161
|
+
if (
|
|
2162
|
+
typeof rec.type === 'string' &&
|
|
2163
|
+
textTypes.includes(rec.type) &&
|
|
2164
|
+
typeof rec.text === 'string'
|
|
2165
|
+
) {
|
|
1956
2166
|
parts.push(rec.text);
|
|
1957
2167
|
}
|
|
1958
2168
|
}
|
|
1959
|
-
return parts.join('')
|
|
2169
|
+
return parts.join('');
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
function extractResponseText(response: { content: string | object }): string {
|
|
2173
|
+
return collectText(response.content).trim();
|
|
1960
2174
|
}
|
|
1961
2175
|
|
|
1962
2176
|
class ToolOnlySummaryError extends ReasoningOnlySummaryError {
|
|
@@ -1970,63 +2184,104 @@ class ToolOnlySummaryError extends ReasoningOnlySummaryError {
|
|
|
1970
2184
|
function validateSummaryResponse(response: BaseMessage | undefined): void {
|
|
1971
2185
|
if (response == null) return;
|
|
1972
2186
|
if (isReasoningOnlySummary(response)) throw new ReasoningOnlySummaryError();
|
|
1973
|
-
if (
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
2187
|
+
if (
|
|
2188
|
+
extractResponseText(response) === '' &&
|
|
2189
|
+
'tool_calls' in response &&
|
|
2190
|
+
Array.isArray(response.tool_calls) &&
|
|
2191
|
+
response.tool_calls.length > 0
|
|
2192
|
+
) {
|
|
2193
|
+
const kwargs = response.additional_kwargs as
|
|
2194
|
+
| { refusal?: string }
|
|
2195
|
+
| undefined;
|
|
2196
|
+
if (
|
|
2197
|
+
kwargs?.refusal != null ||
|
|
2198
|
+
getProviderStopReasons(response).some(
|
|
2199
|
+
(reason) =>
|
|
2200
|
+
reason !== 'end_turn' &&
|
|
2201
|
+
reason !== 'stop' &&
|
|
2202
|
+
reason !== 'tool_use' &&
|
|
2203
|
+
reason !== 'tool_calls'
|
|
2204
|
+
)
|
|
2205
|
+
)
|
|
2206
|
+
return;
|
|
1978
2207
|
throw new ToolOnlySummaryError();
|
|
1979
2208
|
}
|
|
1980
2209
|
}
|
|
1981
2210
|
|
|
1982
2211
|
function isReasoningOnlySummary(response: BaseMessage): boolean {
|
|
1983
|
-
const kwargs = response.additional_kwargs as
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
2212
|
+
const kwargs = response.additional_kwargs as
|
|
2213
|
+
| (BaseMessage['additional_kwargs'] & { refusal?: string })
|
|
2214
|
+
| undefined;
|
|
2215
|
+
if (
|
|
2216
|
+
kwargs?.refusal != null ||
|
|
2217
|
+
getProviderStopReasons(response).some(
|
|
2218
|
+
(reason) => reason !== 'end_turn' && reason !== 'stop'
|
|
2219
|
+
)
|
|
2220
|
+
)
|
|
2221
|
+
return false;
|
|
2222
|
+
if (
|
|
2223
|
+
'tool_calls' in response &&
|
|
2224
|
+
Array.isArray(response.tool_calls) &&
|
|
2225
|
+
response.tool_calls.length > 0
|
|
2226
|
+
)
|
|
2227
|
+
return false;
|
|
2228
|
+
if (
|
|
2229
|
+
'invalid_tool_calls' in response &&
|
|
2230
|
+
Array.isArray(response.invalid_tool_calls) &&
|
|
2231
|
+
response.invalid_tool_calls.length > 0
|
|
2232
|
+
)
|
|
2233
|
+
return false;
|
|
1989
2234
|
let hasReasoning = kwargs != null && hasReasoningKwargs(response);
|
|
1990
|
-
if (typeof response.content === 'string')
|
|
2235
|
+
if (typeof response.content === 'string')
|
|
2236
|
+
return hasReasoning && response.content.trim() === '';
|
|
1991
2237
|
if (!Array.isArray(response.content)) return false;
|
|
1992
2238
|
for (const block of response.content) {
|
|
1993
2239
|
if (isReasoningContentBlock(block)) {
|
|
1994
2240
|
hasReasoning ||= hasMeaningfulReasoningContentBlock(block);
|
|
1995
2241
|
continue;
|
|
1996
2242
|
}
|
|
1997
|
-
if (
|
|
2243
|
+
if (
|
|
2244
|
+
block.type !== 'text' ||
|
|
2245
|
+
typeof block.text !== 'string' ||
|
|
2246
|
+
block.text.trim() !== ''
|
|
2247
|
+
)
|
|
2248
|
+
return false;
|
|
1998
2249
|
}
|
|
1999
2250
|
return hasReasoning;
|
|
2000
2251
|
}
|
|
2001
2252
|
|
|
2002
|
-
/**
|
|
2253
|
+
/**
|
|
2254
|
+
* Creates an `onChunk` callback that dispatches each chunk as an
|
|
2255
|
+
* `ON_SUMMARIZE_DELTA` while the provider is still responding. With `deltas`,
|
|
2256
|
+
* a chunk from a new attempt replaces what an earlier attempt streamed.
|
|
2257
|
+
*/
|
|
2003
2258
|
export function createSummarizationChunkHandler({
|
|
2004
2259
|
stepId,
|
|
2005
2260
|
config,
|
|
2006
2261
|
provider,
|
|
2007
|
-
reasoningKey = 'reasoning_content',
|
|
2008
2262
|
graph,
|
|
2009
|
-
|
|
2263
|
+
deltas,
|
|
2010
2264
|
}: {
|
|
2011
2265
|
stepId?: string;
|
|
2012
2266
|
config?: RunnableConfig;
|
|
2013
2267
|
provider?: t.ProviderName;
|
|
2268
|
+
/** @deprecated Not read: a delta carries summary text, never reasoning. */
|
|
2014
2269
|
reasoningKey?: 'reasoning_content' | 'reasoning';
|
|
2015
2270
|
graph?: StreamLimitState & { getBreakerController?: () => AbortController };
|
|
2016
|
-
|
|
2271
|
+
deltas?: SummaryDeltaStream;
|
|
2017
2272
|
}): OnChunk | undefined {
|
|
2018
2273
|
if (stepId == null || stepId === '' || !config) {
|
|
2019
2274
|
return undefined;
|
|
2020
2275
|
}
|
|
2021
2276
|
const limitMetadata = config.metadata as Record<string, unknown> | undefined;
|
|
2022
|
-
let
|
|
2277
|
+
let streamingAttempt: unknown;
|
|
2023
2278
|
return (chunk, attemptMetadata) => {
|
|
2024
2279
|
if (
|
|
2025
|
-
|
|
2026
|
-
|
|
2280
|
+
deltas != null &&
|
|
2281
|
+
streamingAttempt !== attemptMetadata?.[STREAM_LIMIT_ATTEMPT_KEY]
|
|
2027
2282
|
) {
|
|
2028
|
-
|
|
2029
|
-
|
|
2283
|
+
deltas.abandon();
|
|
2284
|
+
streamingAttempt = attemptMetadata?.[STREAM_LIMIT_ATTEMPT_KEY];
|
|
2030
2285
|
}
|
|
2031
2286
|
/**
|
|
2032
2287
|
* Charged as `producer` so it PAIRS with the run's registered stream
|
|
@@ -2067,26 +2322,26 @@ export function createSummarizationChunkHandler({
|
|
|
2067
2322
|
config.signal
|
|
2068
2323
|
);
|
|
2069
2324
|
if (protectionTrip != null) throw protectionTrip;
|
|
2070
|
-
const chunkAny = chunk as Parameters<typeof getChunkContent>[0]['chunk'];
|
|
2071
2325
|
const servingProvider =
|
|
2072
2326
|
(attemptMetadata?.[Constants.INVOKED_PROVIDER] as
|
|
2073
2327
|
| t.ProviderName
|
|
2074
2328
|
| undefined) ?? provider;
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2329
|
+
/**
|
|
2330
|
+
* Summary text only. A chunk of reasoning is not part of the summary, and
|
|
2331
|
+
* a response that turns out to be nothing but reasoning is retried, so
|
|
2332
|
+
* publishing it here would show the model's thinking as the summary.
|
|
2333
|
+
*/
|
|
2334
|
+
const text = collectText(chunk.content, CHUNK_TEXT_TYPES);
|
|
2335
|
+
if (text === '') {
|
|
2081
2336
|
return;
|
|
2082
2337
|
}
|
|
2083
|
-
const contentBlocks: t.MessageContentComplex[] =
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
: raw;
|
|
2338
|
+
const contentBlocks: t.MessageContentComplex[] = [
|
|
2339
|
+
{ type: ContentTypes.TEXT, text } as t.MessageContentComplex,
|
|
2340
|
+
];
|
|
2087
2341
|
|
|
2088
2342
|
const event: t.SummarizeDeltaEvent = {
|
|
2089
2343
|
id: stepId,
|
|
2344
|
+
...(deltas?.next() === true ? { reset: true } : {}),
|
|
2090
2345
|
delta: {
|
|
2091
2346
|
summary: {
|
|
2092
2347
|
type: ContentTypes.SUMMARY,
|
|
@@ -2102,11 +2357,12 @@ export function createSummarizationChunkHandler({
|
|
|
2102
2357
|
},
|
|
2103
2358
|
},
|
|
2104
2359
|
};
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2360
|
+
/** Awaited so deltas, and the reset that separates two attempts, arrive in order. */
|
|
2361
|
+
return safeDispatchCustomEvent(
|
|
2362
|
+
GraphEvents.ON_SUMMARIZE_DELTA,
|
|
2363
|
+
event,
|
|
2364
|
+
config
|
|
2365
|
+
).then(() => undefined);
|
|
2110
2366
|
};
|
|
2111
2367
|
}
|
|
2112
2368
|
|
|
@@ -2181,8 +2437,8 @@ async function summarizeWithCacheHit({
|
|
|
2181
2437
|
config,
|
|
2182
2438
|
stepId,
|
|
2183
2439
|
provider,
|
|
2184
|
-
reasoningKey,
|
|
2185
2440
|
graph,
|
|
2441
|
+
deltas,
|
|
2186
2442
|
usePromptCache,
|
|
2187
2443
|
promptCacheTtl,
|
|
2188
2444
|
bedrockModelId,
|
|
@@ -2204,8 +2460,8 @@ async function summarizeWithCacheHit({
|
|
|
2204
2460
|
config?: RunnableConfig;
|
|
2205
2461
|
stepId?: string;
|
|
2206
2462
|
provider: t.ProviderName;
|
|
2207
|
-
reasoningKey?: 'reasoning_content' | 'reasoning';
|
|
2208
2463
|
graph?: StreamLimitState & { getBreakerSignal?: () => AbortSignal };
|
|
2464
|
+
deltas?: SummaryDeltaStream;
|
|
2209
2465
|
usePromptCache?: boolean;
|
|
2210
2466
|
promptCacheTtl?: PromptCacheTtl;
|
|
2211
2467
|
bedrockModelId?: string;
|
|
@@ -2257,10 +2513,20 @@ async function summarizeWithCacheHit({
|
|
|
2257
2513
|
provider,
|
|
2258
2514
|
shrink: attempt > 0 || shrinkInput === true,
|
|
2259
2515
|
});
|
|
2260
|
-
const windowWithCache =
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2516
|
+
const windowWithCache =
|
|
2517
|
+
provider === Providers.BEDROCK
|
|
2518
|
+
? applySummarizationHistoryCache({
|
|
2519
|
+
messages: boundedHistory,
|
|
2520
|
+
provider,
|
|
2521
|
+
enabled: usePromptCache === true,
|
|
2522
|
+
promptCacheTtl,
|
|
2523
|
+
bedrockModelId,
|
|
2524
|
+
})
|
|
2525
|
+
: boundedHistory;
|
|
2526
|
+
const history =
|
|
2527
|
+
system == null
|
|
2528
|
+
? windowWithCache
|
|
2529
|
+
: await system.invoke(windowWithCache, config);
|
|
2264
2530
|
const cachedHistory =
|
|
2265
2531
|
system != null || provider === Providers.BEDROCK
|
|
2266
2532
|
? history
|
|
@@ -2271,14 +2537,15 @@ async function summarizeWithCacheHit({
|
|
|
2271
2537
|
promptCacheTtl,
|
|
2272
2538
|
bedrockModelId,
|
|
2273
2539
|
});
|
|
2274
|
-
|
|
2540
|
+
/** Each pass is a new attempt: what an earlier one streamed is not its output. */
|
|
2541
|
+
deltas?.abandon();
|
|
2275
2542
|
try {
|
|
2276
2543
|
result = await attemptInvoke(
|
|
2277
2544
|
{
|
|
2278
2545
|
model,
|
|
2279
2546
|
messages: [...cachedHistory, new HumanMessage(instruction)],
|
|
2280
2547
|
provider,
|
|
2281
|
-
onModelComplete: response => {
|
|
2548
|
+
onModelComplete: (response) => {
|
|
2282
2549
|
const usage = readSummarizationUsage(response);
|
|
2283
2550
|
if (usage != null) onUsage(usage);
|
|
2284
2551
|
},
|
|
@@ -2286,9 +2553,8 @@ async function summarizeWithCacheHit({
|
|
|
2286
2553
|
stepId,
|
|
2287
2554
|
config: traceConfig(config, 'cache_hit_compaction'),
|
|
2288
2555
|
provider,
|
|
2289
|
-
reasoningKey,
|
|
2290
2556
|
graph,
|
|
2291
|
-
|
|
2557
|
+
deltas,
|
|
2292
2558
|
}),
|
|
2293
2559
|
streamLimitState: graph,
|
|
2294
2560
|
},
|
|
@@ -2297,8 +2563,8 @@ async function summarizeWithCacheHit({
|
|
|
2297
2563
|
const response = result.messages?.[0];
|
|
2298
2564
|
signalConfig?.signal?.throwIfAborted();
|
|
2299
2565
|
validateSummaryResponse(response);
|
|
2300
|
-
if (response
|
|
2301
|
-
|
|
2566
|
+
if (response == null || extractResponseText(response) === '') {
|
|
2567
|
+
deltas?.abandon();
|
|
2302
2568
|
}
|
|
2303
2569
|
break;
|
|
2304
2570
|
} catch (error) {
|
|
@@ -2317,8 +2583,12 @@ async function summarizeWithCacheHit({
|
|
|
2317
2583
|
? extractResponseText(responseMsg as { content: string | object })
|
|
2318
2584
|
: '';
|
|
2319
2585
|
const usage = readSummarizationUsage(responseMsg);
|
|
2320
|
-
const usageSource =
|
|
2321
|
-
|
|
2586
|
+
const usageSource =
|
|
2587
|
+
responseMsg != null &&
|
|
2588
|
+
'usage_metadata' in responseMsg &&
|
|
2589
|
+
responseMsg.usage_metadata != null
|
|
2590
|
+
? 'usage_metadata'
|
|
2591
|
+
: 'response_metadata';
|
|
2322
2592
|
const cacheDetails = (
|
|
2323
2593
|
usage as
|
|
2324
2594
|
| {
|