@librechat/agents 4.1.0 → 4.2.0
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 +9 -1
- package/dist/cjs/agents/AgentContext.cjs.map +1 -1
- package/dist/cjs/common/constants.cjs +2 -0
- package/dist/cjs/common/constants.cjs.map +1 -1
- package/dist/cjs/graphs/Graph.cjs +15 -12
- package/dist/cjs/graphs/Graph.cjs.map +1 -1
- package/dist/cjs/graphs/MultiAgentGraph.cjs +1 -1
- package/dist/cjs/hitl/approvalReview.cjs +10 -2
- package/dist/cjs/hitl/approvalReview.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/defaults.cjs +12 -0
- package/dist/cjs/llm/anthropic/defaults.cjs.map +1 -0
- package/dist/cjs/llm/anthropic/index.cjs +6 -0
- package/dist/cjs/llm/anthropic/index.cjs.map +1 -1
- package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +1 -1
- package/dist/cjs/llm/google/utils/common.cjs +1 -1
- package/dist/cjs/llm/init.cjs +5 -2
- package/dist/cjs/llm/init.cjs.map +1 -1
- package/dist/cjs/llm/invoke.cjs +17 -15
- package/dist/cjs/llm/invoke.cjs.map +1 -1
- package/dist/cjs/llm/openai/index.cjs +1 -1
- package/dist/cjs/llm/openai/utils/index.cjs.map +1 -1
- package/dist/cjs/llm/request.cjs +13 -0
- package/dist/cjs/llm/request.cjs.map +1 -1
- package/dist/cjs/llm/stream/chunkAdapters.cjs +2 -3
- package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
- package/dist/cjs/llm/truncation.cjs +12 -2
- package/dist/cjs/llm/truncation.cjs.map +1 -1
- package/dist/cjs/main.cjs +7 -4
- package/dist/cjs/messages/core.cjs +1 -1
- package/dist/cjs/messages/format.cjs +1 -1
- package/dist/cjs/messages/index.cjs +1 -1
- package/dist/cjs/messages/prune.cjs +2 -2
- package/dist/cjs/messages/reasoningTypes.cjs +20 -0
- package/dist/cjs/messages/reasoningTypes.cjs.map +1 -1
- package/dist/cjs/messages/recency.cjs +68 -7
- package/dist/cjs/messages/recency.cjs.map +1 -1
- package/dist/cjs/run.cjs +135 -54
- package/dist/cjs/run.cjs.map +1 -1
- package/dist/cjs/session/AgentSession.cjs +7 -10
- package/dist/cjs/session/AgentSession.cjs.map +1 -1
- package/dist/cjs/stream.cjs +3 -2
- package/dist/cjs/stream.cjs.map +1 -1
- package/dist/cjs/summarization/input.cjs +87 -0
- package/dist/cjs/summarization/input.cjs.map +1 -0
- package/dist/cjs/summarization/node.cjs +470 -135
- package/dist/cjs/summarization/node.cjs.map +1 -1
- package/dist/cjs/summarization/retry.cjs +172 -0
- package/dist/cjs/summarization/retry.cjs.map +1 -0
- package/dist/cjs/summarization/shared.cjs +6 -2
- package/dist/cjs/summarization/shared.cjs.map +1 -1
- package/dist/cjs/summarization/toolBudget.cjs +45 -0
- package/dist/cjs/summarization/toolBudget.cjs.map +1 -0
- package/dist/cjs/summarization/usage.cjs +70 -0
- package/dist/cjs/summarization/usage.cjs.map +1 -0
- package/dist/cjs/tools/ToolNode.cjs +46 -16
- package/dist/cjs/tools/ToolNode.cjs.map +1 -1
- package/dist/cjs/tools/cloudflare/CloudflareBridgeRuntime.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs +155 -18
- package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
- package/dist/cjs/tools/subagent/SubagentReplay.cjs +6 -1
- package/dist/cjs/tools/subagent/SubagentReplay.cjs.map +1 -1
- package/dist/cjs/tools/subagent/childGraphConfig.cjs +2 -1
- package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -1
- package/dist/cjs/tools/toolBatchReplay.cjs +182 -6
- package/dist/cjs/tools/toolBatchReplay.cjs.map +1 -1
- package/dist/cjs/utils/errors.cjs +21 -0
- package/dist/cjs/utils/errors.cjs.map +1 -1
- package/dist/cjs/utils/index.cjs +1 -1
- package/dist/cjs/utils/schema.cjs +17 -0
- package/dist/cjs/utils/schema.cjs.map +1 -1
- package/dist/esm/agents/AgentContext.mjs +9 -1
- package/dist/esm/agents/AgentContext.mjs.map +1 -1
- package/dist/esm/common/constants.mjs +2 -1
- package/dist/esm/common/constants.mjs.map +1 -1
- package/dist/esm/graphs/Graph.mjs +16 -13
- package/dist/esm/graphs/Graph.mjs.map +1 -1
- package/dist/esm/graphs/MultiAgentGraph.mjs +1 -1
- package/dist/esm/hitl/approvalReview.mjs +10 -2
- package/dist/esm/hitl/approvalReview.mjs.map +1 -1
- package/dist/esm/llm/anthropic/defaults.mjs +12 -0
- package/dist/esm/llm/anthropic/defaults.mjs.map +1 -0
- package/dist/esm/llm/anthropic/index.mjs +6 -0
- package/dist/esm/llm/anthropic/index.mjs.map +1 -1
- package/dist/esm/llm/anthropic/utils/message_inputs.mjs +1 -1
- package/dist/esm/llm/google/utils/common.mjs +1 -1
- package/dist/esm/llm/init.mjs +5 -2
- package/dist/esm/llm/init.mjs.map +1 -1
- package/dist/esm/llm/invoke.mjs +18 -16
- package/dist/esm/llm/invoke.mjs.map +1 -1
- package/dist/esm/llm/openai/index.mjs +1 -1
- package/dist/esm/llm/openai/utils/index.mjs.map +1 -1
- package/dist/esm/llm/request.mjs +13 -1
- package/dist/esm/llm/request.mjs.map +1 -1
- package/dist/esm/llm/stream/chunkAdapters.mjs +2 -3
- package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
- package/dist/esm/llm/truncation.mjs +12 -3
- package/dist/esm/llm/truncation.mjs.map +1 -1
- package/dist/esm/main.mjs +8 -8
- package/dist/esm/messages/core.mjs +1 -1
- package/dist/esm/messages/format.mjs +1 -1
- package/dist/esm/messages/index.mjs +1 -1
- package/dist/esm/messages/prune.mjs +2 -2
- package/dist/esm/messages/reasoningTypes.mjs +19 -1
- package/dist/esm/messages/reasoningTypes.mjs.map +1 -1
- package/dist/esm/messages/recency.mjs +68 -8
- package/dist/esm/messages/recency.mjs.map +1 -1
- package/dist/esm/run.mjs +135 -54
- package/dist/esm/run.mjs.map +1 -1
- package/dist/esm/session/AgentSession.mjs +7 -10
- package/dist/esm/session/AgentSession.mjs.map +1 -1
- package/dist/esm/stream.mjs +3 -2
- package/dist/esm/stream.mjs.map +1 -1
- package/dist/esm/summarization/input.mjs +84 -0
- package/dist/esm/summarization/input.mjs.map +1 -0
- package/dist/esm/summarization/node.mjs +469 -133
- package/dist/esm/summarization/node.mjs.map +1 -1
- package/dist/esm/summarization/retry.mjs +169 -0
- package/dist/esm/summarization/retry.mjs.map +1 -0
- package/dist/esm/summarization/shared.mjs +6 -2
- package/dist/esm/summarization/shared.mjs.map +1 -1
- package/dist/esm/summarization/toolBudget.mjs +45 -0
- package/dist/esm/summarization/toolBudget.mjs.map +1 -0
- package/dist/esm/summarization/usage.mjs +69 -0
- package/dist/esm/summarization/usage.mjs.map +1 -0
- package/dist/esm/tools/ToolNode.mjs +46 -16
- package/dist/esm/tools/ToolNode.mjs.map +1 -1
- package/dist/esm/tools/cloudflare/CloudflareBridgeRuntime.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentExecutor.mjs +156 -19
- package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
- package/dist/esm/tools/subagent/SubagentReplay.mjs +6 -1
- package/dist/esm/tools/subagent/SubagentReplay.mjs.map +1 -1
- package/dist/esm/tools/subagent/childGraphConfig.mjs +2 -1
- package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -1
- package/dist/esm/tools/toolBatchReplay.mjs +178 -7
- package/dist/esm/tools/toolBatchReplay.mjs.map +1 -1
- package/dist/esm/utils/errors.mjs +21 -1
- package/dist/esm/utils/errors.mjs.map +1 -1
- package/dist/esm/utils/index.mjs +1 -1
- package/dist/esm/utils/schema.mjs +17 -0
- package/dist/esm/utils/schema.mjs.map +1 -1
- package/dist/types/agents/AgentContext.d.ts +2 -0
- package/dist/types/common/constants.d.ts +2 -0
- package/dist/types/hitl/approvalReview.d.ts +1 -1
- package/dist/types/llm/anthropic/defaults.d.ts +11 -0
- package/dist/types/llm/init.d.ts +2 -1
- package/dist/types/llm/invoke.d.ts +8 -1
- package/dist/types/llm/request.d.ts +12 -0
- package/dist/types/llm/stream/chunkAdapters.d.ts +1 -1
- package/dist/types/llm/truncation.d.ts +2 -0
- package/dist/types/messages/reasoningTypes.d.ts +6 -0
- package/dist/types/messages/recency.d.ts +2 -0
- package/dist/types/run.d.ts +3 -0
- package/dist/types/summarization/input.d.ts +16 -0
- package/dist/types/summarization/node.d.ts +2 -1
- package/dist/types/summarization/retry.d.ts +22 -0
- package/dist/types/summarization/shared.d.ts +3 -3
- package/dist/types/summarization/toolBudget.d.ts +8 -0
- package/dist/types/summarization/usage.d.ts +9 -0
- package/dist/types/tools/subagent/SubagentReplay.d.ts +3 -1
- package/dist/types/tools/toolBatchReplay.d.ts +14 -1
- package/dist/types/types/graph.d.ts +2 -1
- package/dist/types/types/hitl.d.ts +2 -0
- package/dist/types/types/llm.d.ts +3 -0
- package/dist/types/types/run.d.ts +1 -1
- package/dist/types/types/summarize.d.ts +15 -3
- package/dist/types/utils/errors.d.ts +2 -0
- package/dist/types/utils/schema.d.ts +1 -1
- package/package.json +13 -4
- package/src/agents/AgentContext.ts +7 -0
- package/src/common/constants.ts +3 -0
- package/src/graphs/Graph.ts +16 -21
- package/src/hitl/approvalReview.ts +10 -2
- package/src/llm/anthropic/defaults.ts +22 -0
- package/src/llm/anthropic/index.ts +15 -2
- package/src/llm/init.ts +16 -2
- package/src/llm/invoke.ts +33 -14
- package/src/llm/openai/utils/index.ts +2 -4
- package/src/llm/request.ts +44 -0
- package/src/llm/stream/chunkAdapters.ts +14 -18
- package/src/llm/truncation.ts +33 -17
- package/src/messages/reasoningTypes.ts +71 -0
- package/src/messages/recency.ts +78 -0
- package/src/run.ts +190 -81
- package/src/session/AgentSession.ts +8 -11
- package/src/stream.ts +1 -0
- package/src/summarization/input.ts +98 -0
- package/src/summarization/node.ts +749 -356
- package/src/summarization/retry.ts +294 -0
- package/src/summarization/shared.ts +9 -2
- package/src/summarization/toolBudget.ts +87 -0
- package/src/summarization/usage.ts +117 -0
- package/src/tools/ToolNode.ts +84 -23
- package/src/tools/cloudflare/CloudflareBridgeRuntime.ts +2 -2
- package/src/tools/subagent/SubagentExecutor.ts +227 -32
- package/src/tools/subagent/SubagentReplay.ts +30 -1
- package/src/tools/subagent/childGraphConfig.ts +9 -2
- package/src/tools/toolBatchReplay.ts +237 -7
- package/src/types/graph.ts +2 -1
- package/src/types/hitl.ts +4 -0
- package/src/types/llm.ts +4 -0
- package/src/types/run.ts +6 -3
- package/src/types/summarize.ts +22 -3
- package/src/utils/errors.ts +45 -0
- package/src/utils/schema.ts +26 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
require("../common/enum.cjs");
|
|
2
2
|
require("../common/index.cjs");
|
|
3
|
-
const require_truncation = require("../utils/truncation.cjs");
|
|
4
3
|
const require_toolContent = require("../utils/toolContent.cjs");
|
|
4
|
+
const require_reasoningTypes = require("../messages/reasoningTypes.cjs");
|
|
5
5
|
const require_cache = require("../messages/cache.cjs");
|
|
6
6
|
const require_providerRegistry = require("../llm/providerRegistry.cjs");
|
|
7
7
|
const require_streamLimits = require("../llm/streamLimits.cjs");
|
|
@@ -16,26 +16,20 @@ const require_anthropicToolCache = require("../messages/anthropicToolCache.cjs")
|
|
|
16
16
|
const require_reducer = require("../messages/reducer.cjs");
|
|
17
17
|
const require_recency = require("../messages/recency.cjs");
|
|
18
18
|
const require_stream = require("../stream.cjs");
|
|
19
|
+
const require_errors = require("../utils/errors.cjs");
|
|
20
|
+
const require_prepareProviderRequest = require("../llm/prepareProviderRequest.cjs");
|
|
21
|
+
const require_truncation = require("../llm/truncation.cjs");
|
|
19
22
|
const require_init = require("../llm/init.cjs");
|
|
20
23
|
const require_invoke = require("../llm/invoke.cjs");
|
|
21
24
|
const require_shared = require("./shared.cjs");
|
|
22
25
|
const require_promptCacheTools = require("../llm/promptCacheTools.cjs");
|
|
26
|
+
const require_input = require("./input.cjs");
|
|
27
|
+
const require_retry = require("./retry.cjs");
|
|
28
|
+
const require_usage = require("./usage.cjs");
|
|
29
|
+
const require_chunkAdapters = require("../llm/stream/chunkAdapters.cjs");
|
|
30
|
+
const require_toolBudget = require("./toolBudget.cjs");
|
|
23
31
|
let _langchain_core_messages = require("@langchain/core/messages");
|
|
24
32
|
//#region src/summarization/node.ts
|
|
25
|
-
function generateMetadataStub(messages) {
|
|
26
|
-
const counts = {};
|
|
27
|
-
const toolNames = /* @__PURE__ */ new Set();
|
|
28
|
-
for (const msg of messages) {
|
|
29
|
-
const role = msg.getType();
|
|
30
|
-
counts[role] = (counts[role] ?? 0) + 1;
|
|
31
|
-
if (role === "tool" && msg.name != null && msg.name !== "") toolNames.add(msg.name);
|
|
32
|
-
if (role === "ai" && msg instanceof _langchain_core_messages.AIMessage && msg.tool_calls && msg.tool_calls.length > 0) for (const tc of msg.tool_calls) toolNames.add(tc.name);
|
|
33
|
-
}
|
|
34
|
-
const countParts = Object.entries(counts).map(([role, count]) => `${count} ${role}`).join(", ");
|
|
35
|
-
const lines = [`[Metadata summary: ${messages.length} messages (${countParts})]`];
|
|
36
|
-
if (toolNames.size > 0) lines.push(`[Tools used: ${Array.from(toolNames).join(", ")}]`);
|
|
37
|
-
return lines.join("\n");
|
|
38
|
-
}
|
|
39
33
|
const MAX_TOOL_FAILURES = 8;
|
|
40
34
|
const MAX_TOOL_FAILURE_CHARS = 240;
|
|
41
35
|
function extractToolFailuresSection(messages) {
|
|
@@ -64,29 +58,6 @@ function extractToolFailuresSection(messages) {
|
|
|
64
58
|
function enrichSummary(summaryText, messages) {
|
|
65
59
|
return summaryText + extractToolFailuresSection(messages);
|
|
66
60
|
}
|
|
67
|
-
function restoreOriginalToolContent(messages, originalToolContent, maxContextTokens) {
|
|
68
|
-
if (originalToolContent == null || originalToolContent.size === 0) return messages;
|
|
69
|
-
const restorable = [];
|
|
70
|
-
for (const [index, content] of originalToolContent) {
|
|
71
|
-
const message = messages[index];
|
|
72
|
-
if (message instanceof _langchain_core_messages.ToolMessage && !require_toolContent.isComputerCallOutputMessage(message)) restorable.push({
|
|
73
|
-
index,
|
|
74
|
-
message,
|
|
75
|
-
content
|
|
76
|
-
});
|
|
77
|
-
}
|
|
78
|
-
if (restorable.length === 0) return messages;
|
|
79
|
-
let remainingChars = require_truncation.calculateMaxToolResultChars(maxContextTokens);
|
|
80
|
-
const restored = [...messages];
|
|
81
|
-
for (let i = 0; i < restorable.length; i++) {
|
|
82
|
-
const { index, message, content } = restorable[i];
|
|
83
|
-
const maxChars = Math.floor(remainingChars / (restorable.length - i));
|
|
84
|
-
const compacted = require_toolContent.compactToolContent(content, maxChars).content;
|
|
85
|
-
restored[index] = require_toolContent.cloneToolMessageWithContent(message, compacted);
|
|
86
|
-
remainingChars -= require_toolContent.serializeToolContentBounded(compacted, maxChars).length;
|
|
87
|
-
}
|
|
88
|
-
return restored;
|
|
89
|
-
}
|
|
90
61
|
function buildSummarizationClientConfig(agentContext, summarizationConfig) {
|
|
91
62
|
const provider = summarizationConfig?.provider ?? agentContext.provider;
|
|
92
63
|
const modelName = summarizationConfig?.model;
|
|
@@ -94,16 +65,23 @@ function buildSummarizationClientConfig(agentContext, summarizationConfig) {
|
|
|
94
65
|
const promptText = summarizationConfig?.prompt ?? require_shared.DEFAULT_SUMMARIZATION_PROMPT;
|
|
95
66
|
const updatePromptText = summarizationConfig?.updatePrompt ?? require_shared.DEFAULT_UPDATE_SUMMARIZATION_PROMPT;
|
|
96
67
|
const { llmParams, maxSummaryTokens: paramMaxSummaryTokens } = require_shared.separateSummarizationParameters(parameters);
|
|
97
|
-
const
|
|
98
|
-
|
|
68
|
+
const baseOptions = provider === agentContext.provider && agentContext.clientOptions ? { ...agentContext.clientOptions } : {};
|
|
69
|
+
const clientOptions = require_retry.withSummarizationRetryOwner(provider, {
|
|
70
|
+
...baseOptions,
|
|
99
71
|
...llmParams
|
|
100
|
-
};
|
|
72
|
+
});
|
|
101
73
|
if (modelName != null && modelName !== "") {
|
|
102
74
|
clientOptions.model = modelName;
|
|
103
75
|
clientOptions.modelName = modelName;
|
|
104
76
|
}
|
|
105
|
-
const
|
|
106
|
-
|
|
77
|
+
const outputKey = require_request.getMaxOutputTokensKey(provider);
|
|
78
|
+
const inheritedOutputTokens = readSummaryOutputLimit(provider, baseOptions);
|
|
79
|
+
const explicitOutputTokens = readSummaryOutputLimit(provider, llmParams);
|
|
80
|
+
clearSummaryOutputLimits(provider, clientOptions);
|
|
81
|
+
let effectiveMaxSummaryTokens = paramMaxSummaryTokens ?? summarizationConfig?.maxSummaryTokens ?? explicitOutputTokens;
|
|
82
|
+
if (effectiveMaxSummaryTokens == null) effectiveMaxSummaryTokens = resolveSummaryOutputTokens(provider, clientOptions, agentContext.maxContextTokens, inheritedOutputTokens);
|
|
83
|
+
if (effectiveMaxSummaryTokens === -1 && usesCompletionTokenAlias(provider)) effectiveMaxSummaryTokens = void 0;
|
|
84
|
+
if (effectiveMaxSummaryTokens != null) clientOptions[outputKey] = effectiveMaxSummaryTokens;
|
|
107
85
|
return {
|
|
108
86
|
provider,
|
|
109
87
|
modelName,
|
|
@@ -113,6 +91,87 @@ function buildSummarizationClientConfig(agentContext, summarizationConfig) {
|
|
|
113
91
|
updatePromptText
|
|
114
92
|
};
|
|
115
93
|
}
|
|
94
|
+
function usesCompletionTokenAlias(provider) {
|
|
95
|
+
return require_providerRegistry.getProviderFamily(provider) === "openai" || provider === "moonshot";
|
|
96
|
+
}
|
|
97
|
+
function readSummaryOutputLimit(provider, options) {
|
|
98
|
+
const openai = usesCompletionTokenAlias(provider);
|
|
99
|
+
const native = openai ? options.modelKwargs : options.invocationKwargs;
|
|
100
|
+
const anthropic = provider === "anthropic" || require_providerRegistry.getProviderFamily(provider) === "anthropic";
|
|
101
|
+
let nativeLimit;
|
|
102
|
+
if (openai) nativeLimit = native?.max_output_tokens;
|
|
103
|
+
else if (anthropic) nativeLimit = native?.max_tokens;
|
|
104
|
+
return nativeLimit ?? (openai ? options.maxCompletionTokens : void 0) ?? options[require_request.getMaxOutputTokensKey(provider)];
|
|
105
|
+
}
|
|
106
|
+
function clearSummaryOutputLimits(provider, options) {
|
|
107
|
+
delete options[require_request.getMaxOutputTokensKey(provider)];
|
|
108
|
+
const openai = usesCompletionTokenAlias(provider);
|
|
109
|
+
if (openai) delete options.maxCompletionTokens;
|
|
110
|
+
const key = openai ? "modelKwargs" : "invocationKwargs";
|
|
111
|
+
if (!openai && provider !== "anthropic" && require_providerRegistry.getProviderFamily(provider) !== "anthropic") return;
|
|
112
|
+
const native = options[key];
|
|
113
|
+
if (native == null) return;
|
|
114
|
+
const normalized = { ...native };
|
|
115
|
+
for (const field of openai ? [
|
|
116
|
+
"max_output_tokens",
|
|
117
|
+
"max_completion_tokens",
|
|
118
|
+
"max_tokens"
|
|
119
|
+
] : ["max_tokens"]) Reflect.deleteProperty(normalized, field);
|
|
120
|
+
options[key] = normalized;
|
|
121
|
+
}
|
|
122
|
+
function resolveSummaryReasoning(provider, clientOptions) {
|
|
123
|
+
const options = clientOptions;
|
|
124
|
+
const family = require_providerRegistry.getProviderFamily(provider);
|
|
125
|
+
const google = options.thinkingConfig;
|
|
126
|
+
if (provider === "google" || provider === "vertexai" || family === "google") {
|
|
127
|
+
const budget = google?.thinkingBudget ?? options.thinkingBudget;
|
|
128
|
+
const hasLevel = google?.thinkingLevel != null && google.thinkingLevel !== "THINKING_LEVEL_UNSPECIFIED";
|
|
129
|
+
return {
|
|
130
|
+
enabled: hasLevel || budget != null && (budget > 0 || budget === -1),
|
|
131
|
+
fixedBudget: provider === "vertexai" && hasLevel ? 0 : budget != null && Number.isFinite(budget) && budget > 0 ? budget : 0
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
const thinking = (provider === "anthropic" || family === "anthropic" ? options.invocationKwargs?.thinking : void 0) ?? options.thinking ?? options.additionalModelRequestFields?.thinking ?? options.modelKwargs?.thinking;
|
|
135
|
+
if (thinking != null) {
|
|
136
|
+
const enabled = thinking === true || typeof thinking === "object" && (thinking.type === "enabled" || thinking.type === "adaptive");
|
|
137
|
+
let budget = thinking === true ? options.thinkingBudget ?? options.additionalModelRequestFields?.thinkingBudget : 0;
|
|
138
|
+
if (typeof thinking === "object" && thinking.type === "enabled") budget = thinking.budget_tokens;
|
|
139
|
+
return {
|
|
140
|
+
enabled,
|
|
141
|
+
fixedBudget: enabled && budget != null && Number.isFinite(budget) && budget > 0 ? budget : 0
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const reasoning = {
|
|
145
|
+
...options.modelKwargs?.reasoning,
|
|
146
|
+
...options.reasoning
|
|
147
|
+
};
|
|
148
|
+
const effort = reasoning.effort ?? options.reasoningEffort ?? options.reasoning_effort ?? options.modelKwargs?.reasoning_effort ?? options.modelKwargs?.reasoningEffort;
|
|
149
|
+
return {
|
|
150
|
+
enabled: reasoning.enabled !== false && (effort != null && effort !== "" && effort !== "none" && effort !== "disabled" || reasoning.enabled === true || reasoning.max_tokens != null && reasoning.max_tokens > 0 || provider === "openrouter" && options.reasoning == null && options.modelKwargs?.reasoning == null && options.include_reasoning === true),
|
|
151
|
+
fixedBudget: 0
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
function resolveSummaryOutputTokens(provider, clientOptions, maxContextTokens, inheritedOutputTokens) {
|
|
155
|
+
const explicit = readSummaryOutputLimit(provider, clientOptions);
|
|
156
|
+
if (explicit != null) return explicit === -1 && usesCompletionTokenAlias(provider) ? void 0 : explicit;
|
|
157
|
+
const reasoning = resolveSummaryReasoning(provider, clientOptions);
|
|
158
|
+
if (reasoning.enabled && (inheritedOutputTokens == null || inheritedOutputTokens === -1)) return void 0;
|
|
159
|
+
const defaultOutputTokens = reasoning.fixedBudget + Math.min(require_input.DEFAULT_SUMMARY_OUTPUT_TOKENS, Math.max(1, Math.floor((maxContextTokens ?? 40960) * .1)));
|
|
160
|
+
const inherited = reasoning.enabled && inheritedOutputTokens != null && Number.isFinite(inheritedOutputTokens) && inheritedOutputTokens > 0 ? inheritedOutputTokens : 0;
|
|
161
|
+
return Math.max(defaultOutputTokens, inherited);
|
|
162
|
+
}
|
|
163
|
+
function resolveSummaryOutputReserve(model) {
|
|
164
|
+
let candidate = model;
|
|
165
|
+
const seen = /* @__PURE__ */ new Set();
|
|
166
|
+
for (let depth = 0; candidate != null && depth < 20 && !seen.has(candidate); depth++) {
|
|
167
|
+
seen.add(candidate);
|
|
168
|
+
const runnable = candidate;
|
|
169
|
+
const maximum = runnable.profile?.maxOutputTokens;
|
|
170
|
+
if (maximum != null && Number.isSafeInteger(maximum) && maximum > 0) return maximum;
|
|
171
|
+
candidate = runnable.bound ?? runnable.last;
|
|
172
|
+
}
|
|
173
|
+
throw new require_input.SummarizationInputTooLargeError();
|
|
174
|
+
}
|
|
116
175
|
async function computeSummaryTokenCount(summaryText, agentContext) {
|
|
117
176
|
const carrier = new _langchain_core_messages.HumanMessage(require_shared.buildSummaryCarrierText(summaryText));
|
|
118
177
|
const encoding = encodingForReceivingAgent(agentContext);
|
|
@@ -122,15 +181,67 @@ async function computeSummaryTokenCount(summaryText, agentContext) {
|
|
|
122
181
|
return (await require_tokens.createTokenCounter(encoding))(carrier);
|
|
123
182
|
}
|
|
124
183
|
function encodingForReceivingAgent(agentContext) {
|
|
125
|
-
|
|
184
|
+
return encodingForSummarizationModel(agentContext.provider, agentContext.clientOptions);
|
|
185
|
+
}
|
|
186
|
+
function encodingForSummarizationModel(provider, clientOptions) {
|
|
187
|
+
const model = require_request.resolveClientOptionsModel(clientOptions);
|
|
126
188
|
if (model != null && require_tokens.encodingForModel(model) === "claude") return "claude";
|
|
127
|
-
return
|
|
189
|
+
return provider === "anthropic" || require_providerRegistry.getProviderFamily(provider) === "anthropic" ? "claude" : "o200k_base";
|
|
190
|
+
}
|
|
191
|
+
async function prepareSummarizationBudget({ agentContext, model, provider, clientOptions, maxContextTokens, outputTokens, contextBudgetMode = "input", instruction, tools, config }) {
|
|
192
|
+
const encoding = encodingForSummarizationModel(provider, clientOptions);
|
|
193
|
+
const hostCounter = agentContext.tokenCounter;
|
|
194
|
+
const hostEncoding = hostCounter == null ? void 0 : require_tokens.encodingOfTokenCounter(hostCounter);
|
|
195
|
+
const usesAgentCounter = provider === agentContext.provider && encoding === encodingForReceivingAgent(agentContext) && hostCounter != null && (hostEncoding == null || hostEncoding === encoding);
|
|
196
|
+
const count = usesAgentCounter ? agentContext.contextPressureTokenCounts?.count ?? hostCounter : await require_tokens.createTokenCounter(encoding);
|
|
197
|
+
const system = provider === agentContext.provider ? agentContext.systemRunnable : void 0;
|
|
198
|
+
let overhead = usesAgentCounter ? agentContext.toolSchemaTokens : require_toolBudget.countSummarizationToolTokens({
|
|
199
|
+
tools,
|
|
200
|
+
provider,
|
|
201
|
+
clientOptions,
|
|
202
|
+
count
|
|
203
|
+
});
|
|
204
|
+
if (system != null) overhead = usesAgentCounter ? agentContext.instructionTokens : (await system.invoke([], config)).reduce((total, message) => total + count(message), overhead);
|
|
205
|
+
const ratio = usesAgentCounter ? Math.max(1, agentContext.calibrationRatio) : 1;
|
|
206
|
+
const outputReserve = contextBudgetMode === "window" && maxContextTokens != null ? outputTokens ?? resolveSummaryOutputReserve(model) : 0;
|
|
207
|
+
return {
|
|
208
|
+
count,
|
|
209
|
+
system,
|
|
210
|
+
budget: maxContextTokens == null ? Number.MAX_SAFE_INTEGER : Math.floor((maxContextTokens - overhead - outputReserve - count(new _langchain_core_messages.HumanMessage(instruction))) / ratio)
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
async function flushSummarizationDeltas(deltas, config, graph) {
|
|
214
|
+
const signal = withBreakerSignal(config, graph)?.signal;
|
|
215
|
+
signal?.throwIfAborted();
|
|
216
|
+
for (const delta of deltas) {
|
|
217
|
+
signal?.throwIfAborted();
|
|
218
|
+
if (config != null) await require_events.safeDispatchCustomEvent("on_summarize_delta", delta, config);
|
|
219
|
+
}
|
|
220
|
+
signal?.throwIfAborted();
|
|
128
221
|
}
|
|
129
222
|
function isSyntheticContext(message) {
|
|
130
223
|
const { additional_kwargs: kwargs } = message;
|
|
131
224
|
if (kwargs.injected === true || kwargs.isMeta === true) return true;
|
|
132
225
|
return kwargs.source != null && kwargs.source !== "steer";
|
|
133
226
|
}
|
|
227
|
+
function restoreRetainedMessages(retained, canonical) {
|
|
228
|
+
if (retained.length === 0) return retained;
|
|
229
|
+
const pending = /* @__PURE__ */ new Map();
|
|
230
|
+
for (let i = 0; i < retained.length; i++) {
|
|
231
|
+
const id = retained[i].id;
|
|
232
|
+
if (id != null) pending.set(id, i);
|
|
233
|
+
}
|
|
234
|
+
const restored = [...retained];
|
|
235
|
+
for (let i = canonical.length - 1; i >= 0 && pending.size > 0; i--) {
|
|
236
|
+
const message = canonical[i];
|
|
237
|
+
if (message.id == null) continue;
|
|
238
|
+
const index = pending.get(message.id);
|
|
239
|
+
if (index == null) continue;
|
|
240
|
+
restored[index] = message;
|
|
241
|
+
pending.delete(message.id);
|
|
242
|
+
}
|
|
243
|
+
return restored;
|
|
244
|
+
}
|
|
134
245
|
function resolveSummaryCoverage(messagesToRetain) {
|
|
135
246
|
for (let i = 0; i < messagesToRetain.length; i++) {
|
|
136
247
|
const message = messagesToRetain[i];
|
|
@@ -218,25 +329,41 @@ function describeFallbackError(err, fallbacks) {
|
|
|
218
329
|
};
|
|
219
330
|
}
|
|
220
331
|
async function executeSummarizationWithFallback(params) {
|
|
221
|
-
const { agentContext, messages, clientConfig, summarizeConfig, stepId, usePromptCache, semanticIndex, log, graph } = params;
|
|
332
|
+
const { agentContext, messages, requiredHeadLength, clientConfig, summarizeConfig, stepId, usePromptCache, shrinkInput, semanticIndex, log, graph, onUsage } = params;
|
|
222
333
|
const priorSummaryText = agentContext.getSummaryText()?.trim() ?? "";
|
|
223
334
|
let summaryText = "";
|
|
335
|
+
let summaryProvider = clientConfig.provider;
|
|
336
|
+
let summaryModel = clientConfig.modelName;
|
|
224
337
|
let summaryUsage;
|
|
225
|
-
let
|
|
338
|
+
let errorCode;
|
|
226
339
|
try {
|
|
227
|
-
const summarizationTools =
|
|
340
|
+
const summarizationTools = clientConfig.provider === agentContext.provider ? graph?.getToolsForBinding?.(clientConfig.provider, clientConfig.clientOptions) ?? require_promptCacheTools.prepareToolsForPromptCache({
|
|
228
341
|
provider: clientConfig.provider,
|
|
229
342
|
clientOptions: clientConfig.clientOptions,
|
|
230
343
|
tools: agentContext.getToolsForBinding(),
|
|
231
344
|
isDeferred: require_anthropicToolCache.makeIsDeferred(agentContext.getEffectiveToolDefinitions())
|
|
232
345
|
}) : agentContext.getToolsForBinding();
|
|
233
|
-
const
|
|
234
|
-
|
|
346
|
+
const summarizationModel = require_init.initializeModel({
|
|
347
|
+
provider: clientConfig.provider,
|
|
348
|
+
clientOptions: clientConfig.clientOptions,
|
|
349
|
+
tools: summarizationTools,
|
|
350
|
+
disableToolCalling: true
|
|
351
|
+
});
|
|
352
|
+
const signal = withBreakerSignal(summarizeConfig, graph)?.signal;
|
|
353
|
+
const result = await require_retry.withSummarizationRetry(() => summarizeWithCacheHit({
|
|
354
|
+
agentContext,
|
|
355
|
+
onUsage: (usage) => onUsage({
|
|
235
356
|
provider: clientConfig.provider,
|
|
236
|
-
|
|
237
|
-
|
|
357
|
+
model: clientConfig.modelName ?? require_prepareProviderRequest.resolveServingModelId(summarizationModel) ?? require_request.resolveClientOptionsModel(clientConfig.clientOptions),
|
|
358
|
+
usage
|
|
238
359
|
}),
|
|
360
|
+
shrinkInput,
|
|
361
|
+
outputTokens: clientConfig.effectiveMaxSummaryTokens,
|
|
362
|
+
clientOptions: clientConfig.clientOptions,
|
|
363
|
+
model: summarizationModel,
|
|
364
|
+
tools: summarizationTools,
|
|
239
365
|
messages,
|
|
366
|
+
requiredHeadLength,
|
|
240
367
|
promptText: clientConfig.promptText,
|
|
241
368
|
updatePromptText: clientConfig.updatePromptText,
|
|
242
369
|
priorSummaryText,
|
|
@@ -250,15 +377,20 @@ async function executeSummarizationWithFallback(params) {
|
|
|
250
377
|
promptCacheTtl: clientConfig.provider === "anthropic" || clientConfig.provider === "openrouter" || clientConfig.provider === "bedrock" ? clientConfig.clientOptions.promptCacheTtl : void 0,
|
|
251
378
|
bedrockModelId: clientConfig.provider === "bedrock" ? resolveBedrockCompactionCacheModel(clientConfig.clientOptions) : void 0,
|
|
252
379
|
log
|
|
380
|
+
}), {
|
|
381
|
+
signal,
|
|
382
|
+
onRetry: (retry) => log("debug", "Retrying summarization", retry)
|
|
253
383
|
});
|
|
254
384
|
summaryText = result.text;
|
|
255
385
|
summaryUsage = result.usage;
|
|
256
386
|
} catch (primaryError) {
|
|
257
|
-
if (primaryError instanceof require_streamLimits.StreamLimitExceededError || primaryError instanceof require_providerText.ProviderTextProtectionError) throw primaryError;
|
|
387
|
+
if (primaryError instanceof require_streamLimits.StreamLimitExceededError || primaryError instanceof require_providerText.ProviderTextProtectionError || require_errors.isProviderCancellation(primaryError)) throw primaryError;
|
|
258
388
|
{
|
|
259
389
|
const trippedReason = findStreamLimitAbortReason(graph?.getBreakerSignal?.(), summarizeConfig?.signal);
|
|
260
390
|
if (trippedReason != null) throw trippedReason;
|
|
261
391
|
}
|
|
392
|
+
withBreakerSignal(summarizeConfig, graph)?.signal?.throwIfAborted();
|
|
393
|
+
errorCode = require_retry.classifySummarizationError(primaryError);
|
|
262
394
|
const primaryDescribed = describeProviderError(primaryError, clientConfig.provider, clientConfig.modelName);
|
|
263
395
|
log("error", `Summarization LLM call failed ${primaryDescribed.suffix}`, {
|
|
264
396
|
...primaryDescribed.data,
|
|
@@ -267,37 +399,130 @@ async function executeSummarizationWithFallback(params) {
|
|
|
267
399
|
const rawFallbacks = clientConfig.clientOptions?.fallbacks;
|
|
268
400
|
const fallbacks = Array.isArray(rawFallbacks) ? rawFallbacks : [];
|
|
269
401
|
if (fallbacks.length > 0) try {
|
|
402
|
+
const boundedFallbacks = fallbacks.map((fallback) => {
|
|
403
|
+
const maxContextTokens = fallback.maxContextTokens ?? agentContext.maxContextTokens;
|
|
404
|
+
const outputTokens = resolveSummaryOutputTokens(fallback.provider, { ...fallback.clientOptions }, maxContextTokens);
|
|
405
|
+
const clientOptions = require_retry.withSummarizationRetryOwner(fallback.provider, { ...fallback.clientOptions });
|
|
406
|
+
clearSummaryOutputLimits(fallback.provider, clientOptions);
|
|
407
|
+
if (outputTokens != null) clientOptions[require_request.getMaxOutputTokensKey(fallback.provider)] = outputTokens;
|
|
408
|
+
return {
|
|
409
|
+
...fallback,
|
|
410
|
+
clientOptions,
|
|
411
|
+
maxContextTokens,
|
|
412
|
+
contextBudgetMode: fallback.maxContextTokens == null ? agentContext.summarizationBudgetMode : fallback.contextBudgetMode ?? "window"
|
|
413
|
+
};
|
|
414
|
+
});
|
|
415
|
+
let fallbackIdentity;
|
|
416
|
+
const pendingDeltas = [];
|
|
270
417
|
const onChunk = createSummarizationChunkHandler({
|
|
418
|
+
pendingDeltas,
|
|
271
419
|
stepId,
|
|
272
420
|
config: traceConfig(summarizeConfig, "cache_hit_compaction"),
|
|
273
421
|
provider: clientConfig.provider,
|
|
274
422
|
reasoningKey: agentContext.reasoningKey,
|
|
275
423
|
graph
|
|
276
424
|
});
|
|
425
|
+
const fallbackTools = agentContext.getToolsForBinding();
|
|
277
426
|
const fbMsg = (await require_invoke.tryFallbackProviders({
|
|
278
|
-
fallbacks,
|
|
279
|
-
|
|
280
|
-
|
|
427
|
+
fallbacks: boundedFallbacks,
|
|
428
|
+
disableToolCalling: true,
|
|
429
|
+
tools: fallbackTools,
|
|
430
|
+
messages,
|
|
431
|
+
prepareProviderRequest: async ({ model, provider, clientOptions, maxContextTokens, contextBudgetMode, config }) => {
|
|
432
|
+
config?.signal?.throwIfAborted();
|
|
433
|
+
pendingDeltas.length = 0;
|
|
434
|
+
const instruction = require_shared.buildSummarizationInstruction(clientConfig.promptText, clientConfig.updatePromptText, priorSummaryText, semanticIndex.appendix, provider === agentContext.provider && agentContext.systemRunnable != null);
|
|
435
|
+
const { count, system, budget } = await prepareSummarizationBudget({
|
|
436
|
+
agentContext,
|
|
437
|
+
model,
|
|
438
|
+
provider,
|
|
439
|
+
clientOptions,
|
|
440
|
+
maxContextTokens,
|
|
441
|
+
contextBudgetMode,
|
|
442
|
+
outputTokens: readSummaryOutputLimit(provider, { ...clientOptions }),
|
|
443
|
+
instruction,
|
|
444
|
+
tools: fallbackTools,
|
|
445
|
+
config
|
|
446
|
+
});
|
|
447
|
+
const bounded = require_input.boundSummarizationInput({
|
|
448
|
+
messages,
|
|
449
|
+
requiredHeadLength,
|
|
450
|
+
tokenCounter: count,
|
|
451
|
+
budget,
|
|
452
|
+
provider
|
|
453
|
+
});
|
|
454
|
+
const bedrock = clientOptions;
|
|
455
|
+
const windowWithCache = provider === "bedrock" ? applySummarizationHistoryCache({
|
|
456
|
+
messages: bounded,
|
|
457
|
+
provider,
|
|
458
|
+
enabled: bedrock?.promptCache === true,
|
|
459
|
+
promptCacheTtl: bedrock?.promptCacheTtl,
|
|
460
|
+
bedrockModelId: require_request.resolveClientOptionsModel(clientOptions)
|
|
461
|
+
}) : bounded;
|
|
462
|
+
const request = require_prepareProviderRequest.prepareProviderRequest({
|
|
463
|
+
model,
|
|
464
|
+
messages: [...system == null ? windowWithCache : await system.invoke(windowWithCache, config), new _langchain_core_messages.HumanMessage(instruction)],
|
|
465
|
+
provider,
|
|
466
|
+
config
|
|
467
|
+
});
|
|
468
|
+
fallbackIdentity = {
|
|
469
|
+
provider,
|
|
470
|
+
model: request.modelId ?? require_request.resolveClientOptionsModel(clientOptions)
|
|
471
|
+
};
|
|
472
|
+
return request;
|
|
473
|
+
},
|
|
281
474
|
config: withBreakerSignal(traceConfig(summarizeConfig, "cache_hit_compaction"), graph),
|
|
282
475
|
primaryError,
|
|
283
476
|
onChunk,
|
|
284
|
-
streamLimitState: graph
|
|
477
|
+
streamLimitState: graph,
|
|
478
|
+
invokeModel: (params, config) => require_retry.withSummarizationRetry(async () => {
|
|
479
|
+
pendingDeltas.length = 0;
|
|
480
|
+
const result = await require_invoke.attemptInvoke({
|
|
481
|
+
...params,
|
|
482
|
+
onModelComplete: (response) => {
|
|
483
|
+
params.onModelComplete?.(response);
|
|
484
|
+
const usage = require_usage.readSummarizationUsage(response);
|
|
485
|
+
if (usage != null && fallbackIdentity != null) onUsage({
|
|
486
|
+
provider: fallbackIdentity.provider,
|
|
487
|
+
model: fallbackIdentity.model,
|
|
488
|
+
usage
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
}, config);
|
|
492
|
+
config?.signal?.throwIfAborted();
|
|
493
|
+
const response = result.messages?.[0];
|
|
494
|
+
validateSummaryResponse(response);
|
|
495
|
+
return result;
|
|
496
|
+
}, {
|
|
497
|
+
signal: config?.signal,
|
|
498
|
+
onRetry: (retry) => log("debug", "Retrying fallback summarization", retry)
|
|
499
|
+
})
|
|
285
500
|
}))?.messages?.[0];
|
|
286
|
-
if (fbMsg)
|
|
501
|
+
if (fbMsg) {
|
|
502
|
+
summaryUsage = require_usage.readSummarizationUsage(fbMsg);
|
|
503
|
+
summaryText = extractResponseText(fbMsg);
|
|
504
|
+
if (summaryText !== "") {
|
|
505
|
+
if (fallbackIdentity == null) throw new Error("Missing successful fallback identity", { cause: primaryError });
|
|
506
|
+
summaryProvider = fallbackIdentity.provider;
|
|
507
|
+
summaryModel = fallbackIdentity.model;
|
|
508
|
+
await flushSummarizationDeltas(pendingDeltas, summarizeConfig, graph);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
287
511
|
} catch (fbErr) {
|
|
288
512
|
const trip = findStreamLimitAbortReason(graph?.getBreakerSignal?.(), summarizeConfig?.signal);
|
|
289
513
|
if (trip != null) throw trip;
|
|
290
|
-
if (fbErr instanceof require_streamLimits.StreamLimitExceededError || fbErr instanceof require_providerText.ProviderTextProtectionError) throw fbErr;
|
|
514
|
+
if (fbErr instanceof require_streamLimits.StreamLimitExceededError || fbErr instanceof require_providerText.ProviderTextProtectionError || require_errors.isProviderCancellation(fbErr)) throw fbErr;
|
|
515
|
+
withBreakerSignal(summarizeConfig, graph)?.signal?.throwIfAborted();
|
|
516
|
+
errorCode = require_retry.classifySummarizationError(fbErr);
|
|
291
517
|
const fbDescribed = describeFallbackError(fbErr, fallbacks);
|
|
292
518
|
log("warn", `Fallback providers also failed ${fbDescribed.suffix}`, { ...fbDescribed.data });
|
|
293
519
|
}
|
|
294
520
|
if (!summaryText) {
|
|
295
|
-
log("warn", `Summarization failed
|
|
521
|
+
log("warn", `Summarization failed; preserving conversation history ${primaryDescribed.suffix}`, {
|
|
296
522
|
...primaryDescribed.data,
|
|
297
523
|
messagesToRefineCount: messages.length
|
|
298
524
|
});
|
|
299
|
-
summaryText =
|
|
300
|
-
usedMetadataStub = true;
|
|
525
|
+
summaryText = "";
|
|
301
526
|
}
|
|
302
527
|
}
|
|
303
528
|
const trip = findStreamLimitAbortReason(graph?.getBreakerSignal?.(), summarizeConfig?.signal);
|
|
@@ -305,18 +530,20 @@ async function executeSummarizationWithFallback(params) {
|
|
|
305
530
|
return {
|
|
306
531
|
text: summaryText,
|
|
307
532
|
usage: summaryUsage,
|
|
308
|
-
|
|
533
|
+
provider: summaryProvider,
|
|
534
|
+
model: summaryModel,
|
|
535
|
+
...summaryText === "" ? { errorCode } : {}
|
|
309
536
|
};
|
|
310
537
|
}
|
|
311
538
|
async function dispatchCompletionEvents(params) {
|
|
312
|
-
const { graph, runnableConfig, stepId, summaryBlock, agentContext, runStep, summaryUsage, agentId, messagesAfterCount } = params;
|
|
539
|
+
const { graph, runnableConfig, stepId, summaryBlock, agentContext, runStep, summaryUsage, attemptUsage, agentId, messagesAfterCount } = params;
|
|
313
540
|
const assertNotTripped = () => {
|
|
314
541
|
const trip = findStreamLimitAbortReason(graph.getBreakerSignal?.(), runnableConfig?.signal);
|
|
315
542
|
if (trip != null) throw trip;
|
|
316
543
|
};
|
|
317
544
|
assertNotTripped();
|
|
318
545
|
runStep.summary = summaryBlock;
|
|
319
|
-
if (summaryUsage) runStep.usage = {
|
|
546
|
+
if (summaryUsage && runStep.usage == null) runStep.usage = {
|
|
320
547
|
prompt_tokens: Number(summaryUsage.input_tokens) || 0,
|
|
321
548
|
completion_tokens: Number(summaryUsage.output_tokens) || 0,
|
|
322
549
|
total_tokens: (Number(summaryUsage.input_tokens) || 0) + (Number(summaryUsage.output_tokens) || 0)
|
|
@@ -329,7 +556,8 @@ async function dispatchCompletionEvents(params) {
|
|
|
329
556
|
if (runnableConfig) await require_events.safeDispatchCustomEvent("on_summarize_complete", {
|
|
330
557
|
id: stepId,
|
|
331
558
|
agentId,
|
|
332
|
-
summary: summaryBlock
|
|
559
|
+
summary: summaryBlock,
|
|
560
|
+
...attemptUsage.length > 0 ? { attemptUsage: [...attemptUsage] } : {}
|
|
333
561
|
}, runnableConfig);
|
|
334
562
|
assertNotTripped();
|
|
335
563
|
const sessionId = graph.runId ?? "";
|
|
@@ -411,7 +639,9 @@ function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId
|
|
|
411
639
|
return { summarizationRequest: void 0 };
|
|
412
640
|
}
|
|
413
641
|
const maxCtx = agentContext.maxContextTokens ?? 0;
|
|
414
|
-
|
|
642
|
+
const usesAgentInstructions = (agentContext.summarizationConfig?.provider ?? agentContext.provider) === agentContext.provider;
|
|
643
|
+
const instructionOverhead = usesAgentInstructions ? agentContext.instructionTokens : agentContext.toolSchemaTokens;
|
|
644
|
+
if (usesAgentInstructions && maxCtx > 0 && instructionOverhead >= maxCtx) {
|
|
415
645
|
if (request.reason === "manual") throw new require_shared.ManualSummarizationSkippedError("instructions_exceed_budget", "Compaction skipped: instructions and tool definitions exceed the context budget");
|
|
416
646
|
require_events.emitAgentLog(config, "warn", "summarize", "Summarization skipped, instructions exceed context budget. Reduce the number of tools or increase maxContextTokens.", {
|
|
417
647
|
instructionTokens: agentContext.instructionTokens,
|
|
@@ -423,27 +653,28 @@ function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId
|
|
|
423
653
|
});
|
|
424
654
|
return { summarizationRequest: void 0 };
|
|
425
655
|
}
|
|
426
|
-
const originalPending = agentContext.pendingOriginalToolContent;
|
|
427
|
-
const restoredMessages = restoreOriginalToolContent(state.messages, originalPending, agentContext.maxContextTokens);
|
|
428
656
|
const runnableConfig = config ?? graph.config;
|
|
657
|
+
const clientConfig = buildSummarizationClientConfig(agentContext, agentContext.summarizationConfig);
|
|
658
|
+
const windowMessages = request.windowMessages ?? state.messages;
|
|
429
659
|
const retainRecent = agentContext.summarizationConfig?.retainRecent;
|
|
430
|
-
const retainTurns =
|
|
431
|
-
const recencyTokenCounter = agentContext.contextPressureTokenCounts?.count ?? agentContext.tokenCounter;
|
|
432
|
-
const
|
|
660
|
+
const retainTurns = retainRecent?.turns ?? 2;
|
|
661
|
+
const recencyTokenCounter = agentContext.contextPressureTokenCounts?.count ?? agentContext.tokenCounter ?? await require_tokens.createTokenCounter(encodingForReceivingAgent(agentContext));
|
|
662
|
+
const retainTokens = retainRecent?.tokens ?? (retainRecent == null ? Math.min(16e3, Math.max(1, Math.floor((agentContext.maxContextTokens ?? 1e5) * .16))) : void 0);
|
|
663
|
+
const { head: compactableHead, tail: projectedTail } = require_recency.splitAtRecencyBoundary(windowMessages, {
|
|
433
664
|
provider: agentContext.provider,
|
|
434
|
-
turns: retainTurns,
|
|
435
|
-
tokens:
|
|
665
|
+
turns: retainRecent == null ? retainTurns : retainRecent.turns ?? 2,
|
|
666
|
+
tokens: retainTokens,
|
|
436
667
|
tokenCounter: recencyTokenCounter,
|
|
437
668
|
intraTurnTokens: require_recency.resolveIntraTurnRetainTokens({
|
|
438
|
-
tokens:
|
|
669
|
+
tokens: retainTokens,
|
|
439
670
|
maxContextTokens: agentContext.maxContextTokens
|
|
440
671
|
})
|
|
441
672
|
});
|
|
442
|
-
const
|
|
673
|
+
const messagesToRefine = compactableHead;
|
|
443
674
|
if (messagesToRefine.length === 0) {
|
|
444
675
|
if (request.reason === "manual") throw new require_shared.ManualSummarizationSkippedError("nothing_to_summarize", "Nothing to compact: the retained recent turns cover the whole conversation");
|
|
445
676
|
require_events.emitAgentLog(config, "debug", "summarize", "Summarization skipped — recency window retains all messages", {
|
|
446
|
-
messagesRetained:
|
|
677
|
+
messagesRetained: projectedTail.length,
|
|
447
678
|
retainTurns
|
|
448
679
|
}, {
|
|
449
680
|
runId: graph.runId,
|
|
@@ -452,7 +683,7 @@ function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId
|
|
|
452
683
|
agentContext.markSummarizationTriggered(state.messages.length);
|
|
453
684
|
return { summarizationRequest: void 0 };
|
|
454
685
|
}
|
|
455
|
-
const
|
|
686
|
+
const messagesToRetain = windowMessages === state.messages ? projectedTail : restoreRetainedMessages(projectedTail, state.messages);
|
|
456
687
|
const semanticIndex = require_semanticIndex.renderCompactionSemanticIndex(agentContext.compactionSemanticIndex, messagesToRefine);
|
|
457
688
|
const [stepId, stepIndex] = generateStepId(`summarize-${request.agentId}`);
|
|
458
689
|
const placeholderSummary = {
|
|
@@ -460,6 +691,7 @@ function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId
|
|
|
460
691
|
model: clientConfig.modelName,
|
|
461
692
|
provider: clientConfig.provider
|
|
462
693
|
};
|
|
694
|
+
const attemptUsage = [];
|
|
463
695
|
const runStep = {
|
|
464
696
|
stepIndex,
|
|
465
697
|
id: stepId,
|
|
@@ -539,30 +771,39 @@ function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId
|
|
|
539
771
|
const preCallTrip = findStreamLimitAbortReason(entryBreakerSignal, config?.signal);
|
|
540
772
|
if (preCallTrip != null) throw preCallTrip;
|
|
541
773
|
}
|
|
542
|
-
const { text: rawText, usage: summaryUsage,
|
|
774
|
+
const { text: rawText, usage: summaryUsage, provider: summaryProvider, model: summaryModel, errorCode } = await executeSummarizationWithFallback({
|
|
543
775
|
agentContext,
|
|
544
|
-
messages:
|
|
776
|
+
messages: windowMessages,
|
|
777
|
+
requiredHeadLength: messagesToRefine.length,
|
|
778
|
+
onUsage: (attempt) => {
|
|
779
|
+
attemptUsage.push(attempt);
|
|
780
|
+
runStep.usage = require_usage.buildSummarizationStepUsage(attemptUsage);
|
|
781
|
+
},
|
|
545
782
|
clientConfig,
|
|
546
783
|
summarizeConfig,
|
|
547
784
|
stepId,
|
|
548
785
|
usePromptCache: isSelfSummarizeModel && hasPromptCache,
|
|
786
|
+
shrinkInput: request.reason === "overflow",
|
|
549
787
|
semanticIndex,
|
|
550
788
|
log,
|
|
551
789
|
graph
|
|
552
790
|
});
|
|
553
|
-
if (
|
|
554
|
-
const preservationReason = PRESERVATION_REASONS[request.reason ?? "trigger"] ?? "
|
|
555
|
-
log("warn", `Summarization failed during ${preservationReason}; keeping history
|
|
791
|
+
if (errorCode != null) {
|
|
792
|
+
const preservationReason = PRESERVATION_REASONS[request.reason ?? "trigger"] ?? "automatic compaction";
|
|
793
|
+
log("warn", `Summarization failed during ${preservationReason}; keeping history unchanged`);
|
|
556
794
|
agentContext.markSummarizationTriggered(state.messages.length);
|
|
557
795
|
agentContext.recordSummarizationFailure();
|
|
558
|
-
await graph.
|
|
796
|
+
if (graph.closeRunStep != null) await graph.closeRunStep(stepId, "failed", runnableConfig);
|
|
797
|
+
else await graph.dispatchRunStepCompleted(stepId, {
|
|
559
798
|
type: "summary",
|
|
560
799
|
summary: placeholderSummary
|
|
561
800
|
}, runnableConfig);
|
|
562
801
|
if (runnableConfig) await require_events.safeDispatchCustomEvent("on_summarize_complete", {
|
|
563
802
|
id: stepId,
|
|
564
803
|
agentId: request.agentId,
|
|
565
|
-
error: `Summarization failed during ${preservationReason}; conversation history was preserved
|
|
804
|
+
error: `Summarization failed during ${preservationReason}; conversation history was preserved`,
|
|
805
|
+
errorCode,
|
|
806
|
+
...attemptUsage.length > 0 ? { attemptUsage: [...attemptUsage] } : {}
|
|
566
807
|
}, runnableConfig);
|
|
567
808
|
return { summarizationRequest: void 0 };
|
|
568
809
|
}
|
|
@@ -576,7 +817,9 @@ function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId
|
|
|
576
817
|
if (runnableConfig) await require_events.safeDispatchCustomEvent("on_summarize_complete", {
|
|
577
818
|
id: stepId,
|
|
578
819
|
agentId: request.agentId,
|
|
579
|
-
error: "Summarization produced empty output"
|
|
820
|
+
error: "Summarization produced empty output",
|
|
821
|
+
errorCode: "unknown",
|
|
822
|
+
...attemptUsage.length > 0 ? { attemptUsage: [...attemptUsage] } : {}
|
|
580
823
|
}, runnableConfig);
|
|
581
824
|
await graph.closeRunStep?.(stepId, "failed", runnableConfig);
|
|
582
825
|
return { summarizationRequest: void 0 };
|
|
@@ -587,7 +830,9 @@ function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId
|
|
|
587
830
|
const tokenCount = await computeSummaryTokenCount(summaryText, agentContext);
|
|
588
831
|
const commitTrip = findStreamLimitAbortReason(entryBreakerSignal, config?.signal);
|
|
589
832
|
if (commitTrip != null) throw commitTrip;
|
|
590
|
-
|
|
833
|
+
runnableConfig?.signal?.throwIfAborted();
|
|
834
|
+
entryBreakerSignal?.throwIfAborted();
|
|
835
|
+
if (messagesToRetain.length > 0) agentContext.setSummary(summaryText, tokenCount, { precedesMessages: true });
|
|
591
836
|
else agentContext.setSummary(summaryText, tokenCount);
|
|
592
837
|
log("info", "Summary persisted");
|
|
593
838
|
log("debug", "Summary details", {
|
|
@@ -612,22 +857,19 @@ function createSummarizeNode({ agentContext, graph: adapterGraph, generateStepId
|
|
|
612
857
|
coverage: resolveSummaryCoverage(messagesToRetain),
|
|
613
858
|
stepId,
|
|
614
859
|
stepIndex: runStep.index,
|
|
615
|
-
modelName:
|
|
616
|
-
provider:
|
|
860
|
+
modelName: summaryModel,
|
|
861
|
+
provider: summaryProvider,
|
|
617
862
|
summaryVersion: agentContext.summaryVersion
|
|
618
863
|
}),
|
|
619
864
|
agentContext,
|
|
620
865
|
runStep,
|
|
621
866
|
summaryUsage,
|
|
867
|
+
attemptUsage,
|
|
622
868
|
agentId: request.agentId,
|
|
623
869
|
messagesAfterCount: messagesToRetain.length
|
|
624
870
|
});
|
|
625
871
|
agentContext.markSummarizationTriggered(messagesToRetain.length);
|
|
626
|
-
|
|
627
|
-
const tailPending = /* @__PURE__ */ new Map();
|
|
628
|
-
for (const [idx, content] of originalPending) if (idx >= tailStartIndex) tailPending.set(idx - tailStartIndex, content);
|
|
629
|
-
agentContext.pendingOriginalToolContent = tailPending.size > 0 ? tailPending : void 0;
|
|
630
|
-
} else agentContext.pendingOriginalToolContent = void 0;
|
|
872
|
+
agentContext.pendingOriginalToolContent = void 0;
|
|
631
873
|
return {
|
|
632
874
|
summarizationRequest: void 0,
|
|
633
875
|
messages: messagesToRetain.length > 0 ? [require_reducer.createRemoveAllMessage(), ...messagesToRetain] : [require_reducer.createRemoveAllMessage()],
|
|
@@ -652,10 +894,47 @@ function extractResponseText(response) {
|
|
|
652
894
|
}
|
|
653
895
|
return parts.join("").trim();
|
|
654
896
|
}
|
|
655
|
-
|
|
897
|
+
var ToolOnlySummaryError = class extends require_retry.ReasoningOnlySummaryError {
|
|
898
|
+
constructor() {
|
|
899
|
+
super();
|
|
900
|
+
this.name = "ToolOnlySummaryError";
|
|
901
|
+
this.message = "The summarizer requested tools instead of summary text";
|
|
902
|
+
}
|
|
903
|
+
};
|
|
904
|
+
function validateSummaryResponse(response) {
|
|
905
|
+
if (response == null) return;
|
|
906
|
+
if (isReasoningOnlySummary(response)) throw new require_retry.ReasoningOnlySummaryError();
|
|
907
|
+
if (extractResponseText(response) === "" && "tool_calls" in response && Array.isArray(response.tool_calls) && response.tool_calls.length > 0) {
|
|
908
|
+
if (response.additional_kwargs?.refusal != null || require_truncation.getProviderStopReasons(response).some((reason) => reason !== "end_turn" && reason !== "stop" && reason !== "tool_use" && reason !== "tool_calls")) return;
|
|
909
|
+
throw new ToolOnlySummaryError();
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
function isReasoningOnlySummary(response) {
|
|
913
|
+
const kwargs = response.additional_kwargs;
|
|
914
|
+
if (kwargs?.refusal != null || require_truncation.getProviderStopReasons(response).some((reason) => reason !== "end_turn" && reason !== "stop")) return false;
|
|
915
|
+
if ("tool_calls" in response && Array.isArray(response.tool_calls) && response.tool_calls.length > 0) return false;
|
|
916
|
+
if ("invalid_tool_calls" in response && Array.isArray(response.invalid_tool_calls) && response.invalid_tool_calls.length > 0) return false;
|
|
917
|
+
let hasReasoning = kwargs != null && require_chunkAdapters.hasReasoningKwargs(response);
|
|
918
|
+
if (typeof response.content === "string") return hasReasoning && response.content.trim() === "";
|
|
919
|
+
if (!Array.isArray(response.content)) return false;
|
|
920
|
+
for (const block of response.content) {
|
|
921
|
+
if (require_reasoningTypes.isReasoningContentBlock(block)) {
|
|
922
|
+
hasReasoning ||= require_reasoningTypes.hasMeaningfulReasoningContentBlock(block);
|
|
923
|
+
continue;
|
|
924
|
+
}
|
|
925
|
+
if (block.type !== "text" || typeof block.text !== "string" || block.text.trim() !== "") return false;
|
|
926
|
+
}
|
|
927
|
+
return hasReasoning;
|
|
928
|
+
}
|
|
929
|
+
function createSummarizationChunkHandler({ stepId, config, provider, reasoningKey = "reasoning_content", graph, pendingDeltas }) {
|
|
656
930
|
if (stepId == null || stepId === "" || !config) return;
|
|
657
931
|
const limitMetadata = config.metadata;
|
|
932
|
+
let bufferedAttempt;
|
|
658
933
|
return (chunk, attemptMetadata) => {
|
|
934
|
+
if (pendingDeltas != null && bufferedAttempt !== attemptMetadata?.["lc_stream_limit_attempt"]) {
|
|
935
|
+
pendingDeltas.length = 0;
|
|
936
|
+
bufferedAttempt = attemptMetadata?.[require_streamLimits.STREAM_LIMIT_ATTEMPT_KEY];
|
|
937
|
+
}
|
|
659
938
|
if (graph != null) try {
|
|
660
939
|
require_streamLimits.enforceStreamLimitsForWireChunk({
|
|
661
940
|
graph,
|
|
@@ -668,25 +947,31 @@ function createSummarizationChunkHandler({ stepId, config, provider, reasoningKe
|
|
|
668
947
|
}
|
|
669
948
|
const protectionTrip = findStreamLimitAbortReason(graph?.getBreakerController?.().signal, config.signal);
|
|
670
949
|
if (protectionTrip != null) throw protectionTrip;
|
|
950
|
+
const chunkAny = chunk;
|
|
951
|
+
const servingProvider = attemptMetadata?.["__invoked_provider"] ?? provider;
|
|
671
952
|
const raw = require_stream.getChunkContent({
|
|
672
|
-
chunk,
|
|
673
|
-
provider,
|
|
953
|
+
chunk: chunkAny,
|
|
954
|
+
provider: servingProvider,
|
|
674
955
|
reasoningKey
|
|
675
956
|
});
|
|
676
957
|
if (raw == null || typeof raw === "string" && !raw) return;
|
|
677
|
-
const
|
|
678
|
-
type: "text",
|
|
679
|
-
text: raw
|
|
680
|
-
}] : raw;
|
|
681
|
-
require_events.safeDispatchCustomEvent("on_summarize_delta", {
|
|
958
|
+
const event = {
|
|
682
959
|
id: stepId,
|
|
683
960
|
delta: { summary: {
|
|
684
961
|
type: "summary",
|
|
685
|
-
content:
|
|
686
|
-
|
|
687
|
-
|
|
962
|
+
content: typeof raw === "string" ? [{
|
|
963
|
+
type: "text",
|
|
964
|
+
text: raw
|
|
965
|
+
}] : raw,
|
|
966
|
+
provider: String(servingProvider ?? config.metadata?.summarization_provider ?? ""),
|
|
967
|
+
model: String(attemptMetadata?.["__invoked_model"] ?? config.metadata?.summarization_model ?? "")
|
|
688
968
|
} }
|
|
689
|
-
}
|
|
969
|
+
};
|
|
970
|
+
if (pendingDeltas != null) {
|
|
971
|
+
pendingDeltas.push(event);
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
require_events.safeDispatchCustomEvent("on_summarize_delta", event, config);
|
|
690
975
|
};
|
|
691
976
|
}
|
|
692
977
|
function traceConfig(config, stage) {
|
|
@@ -710,46 +995,96 @@ function applySummarizationHistoryCache(params) {
|
|
|
710
995
|
function resolveBedrockCompactionCacheModel(options) {
|
|
711
996
|
return options?.model;
|
|
712
997
|
}
|
|
713
|
-
async function summarizeWithCacheHit({ model, messages, promptText, updatePromptText, priorSummaryText, semanticIndexAppendix, config, stepId, provider, reasoningKey, graph, usePromptCache, promptCacheTtl, bedrockModelId, log }) {
|
|
714
|
-
const instruction = require_shared.buildSummarizationInstruction(promptText, updatePromptText, priorSummaryText, semanticIndexAppendix);
|
|
715
|
-
const
|
|
998
|
+
async function summarizeWithCacheHit({ agentContext, onUsage, shrinkInput, outputTokens, clientOptions, model, tools, messages, requiredHeadLength, promptText, updatePromptText, priorSummaryText, semanticIndexAppendix, config, stepId, provider, reasoningKey, graph, usePromptCache, promptCacheTtl, bedrockModelId, log }) {
|
|
999
|
+
const instruction = require_shared.buildSummarizationInstruction(promptText, updatePromptText, priorSummaryText, semanticIndexAppendix, provider === agentContext.provider && agentContext.systemRunnable != null);
|
|
1000
|
+
const { count, system, budget } = await prepareSummarizationBudget({
|
|
1001
|
+
agentContext,
|
|
716
1002
|
model,
|
|
717
|
-
|
|
1003
|
+
provider,
|
|
1004
|
+
clientOptions,
|
|
1005
|
+
maxContextTokens: agentContext.maxContextTokens,
|
|
1006
|
+
outputTokens,
|
|
1007
|
+
contextBudgetMode: agentContext.summarizationBudgetMode,
|
|
1008
|
+
instruction,
|
|
1009
|
+
tools,
|
|
1010
|
+
config
|
|
1011
|
+
});
|
|
1012
|
+
const scales = [
|
|
1013
|
+
1,
|
|
1014
|
+
.85,
|
|
1015
|
+
.65,
|
|
1016
|
+
.45,
|
|
1017
|
+
.3
|
|
1018
|
+
];
|
|
1019
|
+
let result;
|
|
1020
|
+
const initialTokens = messages.reduce((total, message) => total + count(message), 0);
|
|
1021
|
+
let lastError;
|
|
1022
|
+
for (let attempt = 0; attempt < scales.length; attempt++) {
|
|
1023
|
+
const signalConfig = withBreakerSignal(traceConfig(config, "cache_hit_compaction"), graph);
|
|
1024
|
+
signalConfig?.signal?.throwIfAborted();
|
|
1025
|
+
const boundedHistory = require_input.boundSummarizationInput({
|
|
718
1026
|
messages,
|
|
1027
|
+
requiredHeadLength,
|
|
1028
|
+
tokenCounter: count,
|
|
1029
|
+
budget: Math.floor(Math.min(budget, attempt === 0 && shrinkInput !== true ? budget : initialTokens) * scales[attempt]),
|
|
1030
|
+
provider,
|
|
1031
|
+
shrink: attempt > 0 || shrinkInput === true
|
|
1032
|
+
});
|
|
1033
|
+
const windowWithCache = provider === "bedrock" ? applySummarizationHistoryCache({
|
|
1034
|
+
messages: boundedHistory,
|
|
719
1035
|
provider,
|
|
720
1036
|
enabled: usePromptCache === true,
|
|
721
1037
|
promptCacheTtl,
|
|
722
1038
|
bedrockModelId
|
|
723
|
-
})
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
config: traceConfig(config, "cache_hit_compaction"),
|
|
1039
|
+
}) : boundedHistory;
|
|
1040
|
+
const history = system == null ? windowWithCache : await system.invoke(windowWithCache, config);
|
|
1041
|
+
const cachedHistory = system != null || provider === "bedrock" ? history : applySummarizationHistoryCache({
|
|
1042
|
+
messages: history,
|
|
728
1043
|
provider,
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
1044
|
+
enabled: usePromptCache === true,
|
|
1045
|
+
promptCacheTtl,
|
|
1046
|
+
bedrockModelId
|
|
1047
|
+
});
|
|
1048
|
+
const pendingDeltas = [];
|
|
1049
|
+
try {
|
|
1050
|
+
result = await require_invoke.attemptInvoke({
|
|
1051
|
+
model,
|
|
1052
|
+
messages: [...cachedHistory, new _langchain_core_messages.HumanMessage(instruction)],
|
|
1053
|
+
provider,
|
|
1054
|
+
onModelComplete: (response) => {
|
|
1055
|
+
const usage = require_usage.readSummarizationUsage(response);
|
|
1056
|
+
if (usage != null) onUsage(usage);
|
|
1057
|
+
},
|
|
1058
|
+
onChunk: createSummarizationChunkHandler({
|
|
1059
|
+
stepId,
|
|
1060
|
+
config: traceConfig(config, "cache_hit_compaction"),
|
|
1061
|
+
provider,
|
|
1062
|
+
reasoningKey,
|
|
1063
|
+
graph,
|
|
1064
|
+
pendingDeltas
|
|
1065
|
+
}),
|
|
1066
|
+
streamLimitState: graph
|
|
1067
|
+
}, signalConfig);
|
|
1068
|
+
const response = result.messages?.[0];
|
|
1069
|
+
signalConfig?.signal?.throwIfAborted();
|
|
1070
|
+
validateSummaryResponse(response);
|
|
1071
|
+
if (response != null && extractResponseText(response) !== "") await flushSummarizationDeltas(pendingDeltas, config, graph);
|
|
1072
|
+
break;
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
signalConfig?.signal?.throwIfAborted();
|
|
1075
|
+
if (require_retry.classifySummarizationError(error) !== "context_exceeded") throw error;
|
|
1076
|
+
lastError = error;
|
|
1077
|
+
log?.("debug", "Shrinking summarization context", { attempt: attempt + 1 });
|
|
748
1078
|
}
|
|
749
1079
|
}
|
|
1080
|
+
if (result == null) throw lastError;
|
|
1081
|
+
const responseMsg = result.messages?.[0];
|
|
1082
|
+
const text = responseMsg ? extractResponseText(responseMsg) : "";
|
|
1083
|
+
const usage = require_usage.readSummarizationUsage(responseMsg);
|
|
1084
|
+
const usageSource = responseMsg != null && "usage_metadata" in responseMsg && responseMsg.usage_metadata != null ? "usage_metadata" : "response_metadata";
|
|
750
1085
|
const cacheDetails = usage?.input_token_details;
|
|
751
1086
|
log?.("debug", "Summarization LLM usage", {
|
|
752
|
-
source: usageSource,
|
|
1087
|
+
source: usage == null ? "none" : usageSource,
|
|
753
1088
|
input_tokens: usage?.input_tokens,
|
|
754
1089
|
output_tokens: usage?.output_tokens,
|
|
755
1090
|
...cacheDetails?.cache_read != null || cacheDetails?.cache_creation != null ? {
|