@librechat/agents 4.1.1 → 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 +4 -6
- 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 +2 -4
- 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 +12 -6
- 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 +7 -11
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import type { SummarizationErrorCode } from '@/types/summarize';
|
|
2
|
+
import type * as t from '@/types';
|
|
3
|
+
import {
|
|
4
|
+
extractErrorMessage,
|
|
5
|
+
isContextOverflowError,
|
|
6
|
+
isProviderCancellation,
|
|
7
|
+
} from '@/utils/errors';
|
|
8
|
+
import { ProviderTextProtectionError } from '@/protection/providerText';
|
|
9
|
+
import { StreamLimitExceededError } from '@/llm/streamLimits';
|
|
10
|
+
import { getProviderFamily } from '@/llm/providerRegistry';
|
|
11
|
+
import { Providers } from '@/common';
|
|
12
|
+
|
|
13
|
+
const MAX_ATTEMPTS = 3;
|
|
14
|
+
const BACKOFF_MS = 250;
|
|
15
|
+
const BACKPRESSURE_BACKOFF_MS = 2000;
|
|
16
|
+
const MAX_RETRY_DELAY_MS = 60_000;
|
|
17
|
+
const MAX_ERROR_DEPTH = 4;
|
|
18
|
+
|
|
19
|
+
/** Compaction owns retries; model/transport defaults must not multiply attempts. */
|
|
20
|
+
export function withSummarizationRetryOwner<T extends object>(
|
|
21
|
+
provider: t.ProviderName,
|
|
22
|
+
clientOptions: T
|
|
23
|
+
): T & { maxRetries: number } {
|
|
24
|
+
const options = { ...clientOptions, maxRetries: 0 };
|
|
25
|
+
const family = getProviderFamily(provider);
|
|
26
|
+
// Moonshot keeps generic request shaping but uses the OpenAI transport.
|
|
27
|
+
if (
|
|
28
|
+
provider === Providers.OPENAI ||
|
|
29
|
+
provider === Providers.AZURE ||
|
|
30
|
+
provider === Providers.OPENROUTER ||
|
|
31
|
+
provider === Providers.MOONSHOT ||
|
|
32
|
+
family === 'openai'
|
|
33
|
+
) {
|
|
34
|
+
const openai = clientOptions as Partial<t.OpenAIClientOptions>;
|
|
35
|
+
return {
|
|
36
|
+
...options,
|
|
37
|
+
configuration: { ...openai.configuration, maxRetries: 0 },
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
if (provider === Providers.ANTHROPIC || family === 'anthropic') {
|
|
41
|
+
const anthropic = clientOptions as Partial<t.AnthropicClientOptions>;
|
|
42
|
+
return {
|
|
43
|
+
...options,
|
|
44
|
+
clientOptions: { ...anthropic.clientOptions, maxRetries: 0 },
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
if (provider === Providers.BEDROCK || family === 'bedrock') {
|
|
48
|
+
const bedrock = clientOptions as Partial<t.BedrockAnthropicInput>;
|
|
49
|
+
return {
|
|
50
|
+
...options,
|
|
51
|
+
clientOptions: { ...bedrock.clientOptions, maxAttempts: 1 },
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
return options;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class ReasoningOnlySummaryError extends Error {
|
|
58
|
+
constructor() {
|
|
59
|
+
super('The summarizer returned reasoning without summary text');
|
|
60
|
+
this.name = 'ReasoningOnlySummaryError';
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
interface ProviderError {
|
|
65
|
+
name?: string;
|
|
66
|
+
code?: string | number;
|
|
67
|
+
type?: string;
|
|
68
|
+
status?: number;
|
|
69
|
+
statusCode?: number;
|
|
70
|
+
httpStatusCode?: number;
|
|
71
|
+
headers?: Headers | Record<string, string | number | undefined>;
|
|
72
|
+
cause?: unknown;
|
|
73
|
+
error?: unknown;
|
|
74
|
+
body?: unknown;
|
|
75
|
+
data?: unknown;
|
|
76
|
+
response?: unknown;
|
|
77
|
+
$metadata?: unknown;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface SummarizationRetryOptions {
|
|
81
|
+
signal?: AbortSignal;
|
|
82
|
+
/** Reports the upcoming attempt (2 or 3), without provider error text. */
|
|
83
|
+
onRetry?: (retry: {
|
|
84
|
+
attempt: number;
|
|
85
|
+
errorCode: SummarizationErrorCode;
|
|
86
|
+
delayMs?: number;
|
|
87
|
+
}) => void;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function* errorChain(error: unknown, depth = 0): Generator<unknown> {
|
|
91
|
+
if (error == null || depth > MAX_ERROR_DEPTH) {
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
yield error;
|
|
95
|
+
if (typeof error !== 'object') {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const record = error as ProviderError;
|
|
99
|
+
for (const nested of [
|
|
100
|
+
record.cause,
|
|
101
|
+
record.error,
|
|
102
|
+
record.body,
|
|
103
|
+
record.data,
|
|
104
|
+
record.response,
|
|
105
|
+
record.$metadata,
|
|
106
|
+
]) {
|
|
107
|
+
yield* errorChain(nested, depth + 1);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function describeFailure(error: unknown): {
|
|
112
|
+
errorCode: SummarizationErrorCode;
|
|
113
|
+
retryable: boolean;
|
|
114
|
+
} {
|
|
115
|
+
if (isProviderCancellation(error)) {
|
|
116
|
+
return { errorCode: 'unknown', retryable: false };
|
|
117
|
+
}
|
|
118
|
+
let errorCode: SummarizationErrorCode = isContextOverflowError(error)
|
|
119
|
+
? 'context_exceeded'
|
|
120
|
+
: 'unknown';
|
|
121
|
+
let retryable = error instanceof ReasoningOnlySummaryError;
|
|
122
|
+
|
|
123
|
+
for (const cause of errorChain(error)) {
|
|
124
|
+
const record: ProviderError =
|
|
125
|
+
typeof cause === 'object' && cause !== null ? cause : {};
|
|
126
|
+
const text = `${record.name ?? ''} ${record.code ?? ''} ${record.type ?? ''} ${extractErrorMessage(cause)}`;
|
|
127
|
+
if (
|
|
128
|
+
cause instanceof StreamLimitExceededError ||
|
|
129
|
+
cause instanceof ProviderTextProtectionError ||
|
|
130
|
+
/^(?:StreamLimitExceededError|ProviderTextProtectionError)$/.test(
|
|
131
|
+
record.name ?? ''
|
|
132
|
+
)
|
|
133
|
+
) {
|
|
134
|
+
return { errorCode: 'unknown', retryable: false };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (record.name === 'SummarizationInputTooLargeError') {
|
|
138
|
+
errorCode = 'context_exceeded';
|
|
139
|
+
}
|
|
140
|
+
const status =
|
|
141
|
+
record.status ??
|
|
142
|
+
record.statusCode ??
|
|
143
|
+
record.httpStatusCode ??
|
|
144
|
+
record.code;
|
|
145
|
+
const overloaded =
|
|
146
|
+
Number(status) === 529 || /\boverloaded(?:_error)?\b/i.test(text);
|
|
147
|
+
const rateLimited =
|
|
148
|
+
Number(status) === 429 ||
|
|
149
|
+
/rate[_ -]?limit|too many requests|ThrottlingException/i.test(text);
|
|
150
|
+
const timeout =
|
|
151
|
+
Number(status) === 408 ||
|
|
152
|
+
/timed?[_ -]?out|timeout|ETIMEDOUT|ESOCKETTIMEDOUT|UND_ERR_(?:CONNECT|HEADERS|BODY)_TIMEOUT/i.test(
|
|
153
|
+
text
|
|
154
|
+
);
|
|
155
|
+
retryable ||=
|
|
156
|
+
overloaded ||
|
|
157
|
+
rateLimited ||
|
|
158
|
+
timeout ||
|
|
159
|
+
(Number(status) >= 500 && Number(status) < 600) ||
|
|
160
|
+
/internal[_ ]server[_ ]error|service[_ ]unavailable|\b(?:HTTP|status(?: code)?)\s*[:=]?\s*5\d\d\b|ECONNRESET|ECONNABORTED|EPIPE|UND_ERR_SOCKET|ERR_STREAM_PREMATURE_CLOSE|socket hang up|socket closed|connection (?:reset|closed|terminated)|terminated|premature (?:close|end)|stream (?:disconnected|interrupted|closed)|fetch failed/i.test(
|
|
161
|
+
text
|
|
162
|
+
);
|
|
163
|
+
if (errorCode === 'context_exceeded') {
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (overloaded) {
|
|
167
|
+
errorCode = 'provider_overloaded';
|
|
168
|
+
} else if (rateLimited && errorCode !== 'provider_overloaded') {
|
|
169
|
+
errorCode = 'rate_limited';
|
|
170
|
+
} else if (timeout && errorCode === 'unknown') {
|
|
171
|
+
errorCode = 'timeout';
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
errorCode,
|
|
177
|
+
retryable: retryable && errorCode !== 'context_exceeded',
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Maps provider failures to safe event metadata, never provider text. */
|
|
182
|
+
export function classifySummarizationError(
|
|
183
|
+
error: unknown
|
|
184
|
+
): SummarizationErrorCode {
|
|
185
|
+
return describeFailure(error).errorCode;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function parseRetryAfter(
|
|
189
|
+
value: string | number | null | undefined,
|
|
190
|
+
unitMs: number
|
|
191
|
+
): number {
|
|
192
|
+
if (typeof value !== 'string' && typeof value !== 'number') {
|
|
193
|
+
return 0;
|
|
194
|
+
}
|
|
195
|
+
const text = String(value).trim();
|
|
196
|
+
if (/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) {
|
|
197
|
+
return Math.min(MAX_RETRY_DELAY_MS, Math.ceil(Number(text) * unitMs));
|
|
198
|
+
}
|
|
199
|
+
if (unitMs !== 1000 || !/^[a-z]{3}[a-z,]*\s/i.test(text)) {
|
|
200
|
+
return 0;
|
|
201
|
+
}
|
|
202
|
+
const date = Date.parse(text);
|
|
203
|
+
return Number.isFinite(date)
|
|
204
|
+
? Math.min(MAX_RETRY_DELAY_MS, Math.max(0, date - Date.now()))
|
|
205
|
+
: 0;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function retryHeaderDelay(headers: ProviderError['headers']): number {
|
|
209
|
+
if (headers == null || typeof headers !== 'object') {
|
|
210
|
+
return 0;
|
|
211
|
+
}
|
|
212
|
+
if (typeof headers.get === 'function') {
|
|
213
|
+
return Math.max(
|
|
214
|
+
parseRetryAfter(headers.get('retry-after'), 1000),
|
|
215
|
+
parseRetryAfter(headers.get('retry-after-ms'), 1)
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
let delay = 0;
|
|
219
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
220
|
+
const header = name.toLowerCase();
|
|
221
|
+
if (header === 'retry-after' || header === 'retry-after-ms') {
|
|
222
|
+
delay = Math.max(
|
|
223
|
+
delay,
|
|
224
|
+
parseRetryAfter(value, header === 'retry-after' ? 1000 : 1)
|
|
225
|
+
);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return delay;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function retryDelay(
|
|
232
|
+
error: unknown,
|
|
233
|
+
errorCode: SummarizationErrorCode,
|
|
234
|
+
attempt: number
|
|
235
|
+
): number {
|
|
236
|
+
const backpressure =
|
|
237
|
+
errorCode === 'provider_overloaded' || errorCode === 'rate_limited';
|
|
238
|
+
const base = backpressure ? BACKPRESSURE_BACKOFF_MS : BACKOFF_MS;
|
|
239
|
+
const jitter = 1 + Math.random() * (backpressure ? 0.5 : 1);
|
|
240
|
+
let delay = Math.floor(base * 2 ** (attempt - 1) * jitter);
|
|
241
|
+
for (const cause of errorChain(error)) {
|
|
242
|
+
if (typeof cause === 'object' && cause !== null) {
|
|
243
|
+
delay = Math.max(
|
|
244
|
+
delay,
|
|
245
|
+
retryHeaderDelay((cause as ProviderError).headers)
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return Math.min(MAX_RETRY_DELAY_MS, delay);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function waitForRetry(ms: number, signal?: AbortSignal): Promise<void> {
|
|
253
|
+
signal?.throwIfAborted();
|
|
254
|
+
return new Promise((resolve, reject) => {
|
|
255
|
+
const onAbort = (): void => {
|
|
256
|
+
clearTimeout(timer);
|
|
257
|
+
signal?.removeEventListener('abort', onAbort);
|
|
258
|
+
reject(signal?.reason);
|
|
259
|
+
};
|
|
260
|
+
const timer = setTimeout(() => {
|
|
261
|
+
signal?.removeEventListener('abort', onAbort);
|
|
262
|
+
resolve();
|
|
263
|
+
}, ms);
|
|
264
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Runs at most three attempts. Pass the same signal to the provider callback. */
|
|
269
|
+
export async function withSummarizationRetry<T>(
|
|
270
|
+
operation: () => Promise<T>,
|
|
271
|
+
{ signal, onRetry }: SummarizationRetryOptions = {}
|
|
272
|
+
): Promise<T> {
|
|
273
|
+
for (let attempt = 1; ; attempt++) {
|
|
274
|
+
signal?.throwIfAborted();
|
|
275
|
+
try {
|
|
276
|
+
const result = await operation();
|
|
277
|
+
signal?.throwIfAborted();
|
|
278
|
+
return result;
|
|
279
|
+
} catch (error) {
|
|
280
|
+
signal?.throwIfAborted();
|
|
281
|
+
const failure = describeFailure(error);
|
|
282
|
+
if (!failure.retryable || attempt === MAX_ATTEMPTS) {
|
|
283
|
+
throw error;
|
|
284
|
+
}
|
|
285
|
+
const delayMs = retryDelay(error, failure.errorCode, attempt);
|
|
286
|
+
onRetry?.({
|
|
287
|
+
attempt: attempt + 1,
|
|
288
|
+
errorCode: failure.errorCode,
|
|
289
|
+
delayMs,
|
|
290
|
+
});
|
|
291
|
+
await waitForRetry(delayMs, signal);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
@@ -35,6 +35,8 @@ export function buildSummaryCarrierText(summaryText: string): string {
|
|
|
35
35
|
/** Structured checkpoint prompt for fresh summarization (no prior summary). */
|
|
36
36
|
export const DEFAULT_SUMMARIZATION_PROMPT = `Hold on, before you continue I need you to write me a checkpoint of everything so far. Your context window is filling up and this checkpoint replaces the messages above, so capture everything you need to pick right back up.
|
|
37
37
|
|
|
38
|
+
Do not call tools, perform calculations, or continue the task. Summarize only the existing transcript.
|
|
39
|
+
|
|
38
40
|
Don't second-guess or fact-check anything you did, your tool results reflect exactly what happened. If a tool result appears truncated, that's just a display artifact from context management: the tool executed fully. Just record what you did and what you observed. Only the checkpoint, don't respond to me or continue the conversation.
|
|
39
41
|
|
|
40
42
|
## Checkpoint
|
|
@@ -71,6 +73,8 @@ Rules:
|
|
|
71
73
|
/** Prompt for re-compaction when a prior summary exists. */
|
|
72
74
|
export const DEFAULT_UPDATE_SUMMARIZATION_PROMPT = `Hold on again, update your checkpoint. Merge the new messages into your existing checkpoint and give me a single consolidated replacement.
|
|
73
75
|
|
|
76
|
+
Do not call tools, perform calculations, or continue the task. Summarize only the existing transcript.
|
|
77
|
+
|
|
74
78
|
Keep it roughly the same length as your last checkpoint. Compress older details to make room for what's new, don't just append. Give recent actions more detail, compress older items to one-liners.
|
|
75
79
|
|
|
76
80
|
Don't fact-check or second-guess anything, your tool results are ground truth. If a tool result appears truncated, that's just a display artifact: the tool executed fully. Only the checkpoint, don't respond to me or continue the conversation.
|
|
@@ -116,7 +120,8 @@ export function buildSummarizationInstruction(
|
|
|
116
120
|
promptText: string,
|
|
117
121
|
updatePromptText: string | undefined,
|
|
118
122
|
priorSummaryText?: string,
|
|
119
|
-
semanticIndexAppendix = ''
|
|
123
|
+
semanticIndexAppendix = '',
|
|
124
|
+
priorSummaryInPrefix = false
|
|
120
125
|
): string {
|
|
121
126
|
const prior = priorSummaryText?.trim() ?? '';
|
|
122
127
|
const effectivePrompt = prior ? (updatePromptText ?? promptText) : promptText;
|
|
@@ -124,7 +129,9 @@ export function buildSummarizationInstruction(
|
|
|
124
129
|
? [semanticIndexAppendix, '\n\n', effectivePrompt]
|
|
125
130
|
: [effectivePrompt];
|
|
126
131
|
if (prior) {
|
|
127
|
-
parts.push(
|
|
132
|
+
parts.push(priorSummaryInPrefix
|
|
133
|
+
? '\n\n<previous-summary>The prior checkpoint is already present in the request prefix above; update that checkpoint using the conversation above.</previous-summary>'
|
|
134
|
+
: `\n\n<previous-summary>\n${prior}\n</previous-summary>`);
|
|
128
135
|
}
|
|
129
136
|
return parts.join('');
|
|
130
137
|
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { SystemMessage } from '@langchain/core/messages';
|
|
2
|
+
import { convertToOpenAIFunction } from '@langchain/core/utils/function_calling';
|
|
3
|
+
import type { StructuredToolInterface } from '@langchain/core/tools';
|
|
4
|
+
import type {
|
|
5
|
+
GraphTools,
|
|
6
|
+
ProviderName,
|
|
7
|
+
ClientOptions,
|
|
8
|
+
TokenCounter,
|
|
9
|
+
} from '@/types';
|
|
10
|
+
import {
|
|
11
|
+
ANTHROPIC_TOOL_TOKEN_MULTIPLIER,
|
|
12
|
+
DEFAULT_TOOL_TOKEN_MULTIPLIER,
|
|
13
|
+
} from '@/common/constants';
|
|
14
|
+
import { getProviderFamily } from '@/llm/providerRegistry';
|
|
15
|
+
import { resolveClientOptionsModel } from '@/llm/request';
|
|
16
|
+
import { toJsonSchema } from '@/utils/schema';
|
|
17
|
+
import { Providers } from '@/common/enum';
|
|
18
|
+
|
|
19
|
+
function toolPayload(tool: GraphTools[number], anthropic: boolean): object {
|
|
20
|
+
if (!('schema' in tool)) {
|
|
21
|
+
return tool;
|
|
22
|
+
}
|
|
23
|
+
const candidate = tool as Partial<
|
|
24
|
+
Pick<StructuredToolInterface, 'name' | 'description' | 'schema' | 'extras'>
|
|
25
|
+
>;
|
|
26
|
+
const extras = candidate.extras;
|
|
27
|
+
const providerToolDefinition = extras?.providerToolDefinition;
|
|
28
|
+
if (
|
|
29
|
+
anthropic &&
|
|
30
|
+
providerToolDefinition != null &&
|
|
31
|
+
typeof providerToolDefinition === 'object'
|
|
32
|
+
) {
|
|
33
|
+
return providerToolDefinition;
|
|
34
|
+
}
|
|
35
|
+
const schema = candidate.schema;
|
|
36
|
+
if (schema == null || typeof schema !== 'object') {
|
|
37
|
+
return tool;
|
|
38
|
+
}
|
|
39
|
+
const normalized = {
|
|
40
|
+
name: candidate.name ?? '',
|
|
41
|
+
description: candidate.description ?? '',
|
|
42
|
+
schema: toJsonSchema(schema),
|
|
43
|
+
};
|
|
44
|
+
if (anthropic) {
|
|
45
|
+
return {
|
|
46
|
+
name: normalized.name,
|
|
47
|
+
description: normalized.description,
|
|
48
|
+
input_schema: normalized.schema,
|
|
49
|
+
...extras,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return { type: 'function', function: convertToOpenAIFunction(normalized) };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Counts only the resolved bound inventory, using the serving model's counter. */
|
|
56
|
+
export function countSummarizationToolTokens({
|
|
57
|
+
tools,
|
|
58
|
+
provider,
|
|
59
|
+
clientOptions,
|
|
60
|
+
count,
|
|
61
|
+
}: {
|
|
62
|
+
tools?: GraphTools;
|
|
63
|
+
provider: ProviderName;
|
|
64
|
+
clientOptions?: ClientOptions;
|
|
65
|
+
count: TokenCounter;
|
|
66
|
+
}): number {
|
|
67
|
+
if (tools == null || tools.length === 0) {
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
const family = getProviderFamily(provider);
|
|
71
|
+
const anthropic = provider === Providers.ANTHROPIC || family === 'anthropic';
|
|
72
|
+
const anthropicMultiplier =
|
|
73
|
+
provider !== Providers.BEDROCK &&
|
|
74
|
+
family !== 'bedrock' &&
|
|
75
|
+
(anthropic ||
|
|
76
|
+
/anthropic|claude/i.test(resolveClientOptionsModel(clientOptions) ?? ''));
|
|
77
|
+
const multiplier = anthropicMultiplier
|
|
78
|
+
? ANTHROPIC_TOOL_TOKEN_MULTIPLIER
|
|
79
|
+
: DEFAULT_TOOL_TOKEN_MULTIPLIER;
|
|
80
|
+
let tokens = 0;
|
|
81
|
+
for (const tool of tools) {
|
|
82
|
+
tokens += count(
|
|
83
|
+
new SystemMessage(JSON.stringify(toolPayload(tool, anthropic)))
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
return Math.ceil(tokens * multiplier);
|
|
87
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type { UsageMetadata, BaseMessage } from '@langchain/core/messages';
|
|
2
|
+
import type { SummarizationAttemptUsage } from '@/types/summarize';
|
|
3
|
+
|
|
4
|
+
interface BedrockSummarizationUsage {
|
|
5
|
+
inputTokens?: number;
|
|
6
|
+
outputTokens?: number;
|
|
7
|
+
totalTokens?: number;
|
|
8
|
+
cacheReadInputTokens?: number;
|
|
9
|
+
cacheWriteInputTokens?: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function tokenCount(value: number | undefined): number | undefined {
|
|
13
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0
|
|
14
|
+
? value
|
|
15
|
+
: undefined;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function normalizeBedrockInputUsage(
|
|
19
|
+
usage: Partial<UsageMetadata>,
|
|
20
|
+
raw: BedrockSummarizationUsage | undefined
|
|
21
|
+
): Partial<UsageMetadata> {
|
|
22
|
+
const input = tokenCount(usage.input_tokens);
|
|
23
|
+
if (input == null || input !== tokenCount(raw?.inputTokens)) return usage;
|
|
24
|
+
|
|
25
|
+
const cached = (tokenCount(raw?.cacheReadInputTokens) ?? 0) +
|
|
26
|
+
(tokenCount(raw?.cacheWriteInputTokens) ?? 0);
|
|
27
|
+
return cached === 0 ? usage : { ...usage, input_tokens: input + cached };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function readSummarizationUsage(
|
|
31
|
+
response: BaseMessage | undefined
|
|
32
|
+
): Partial<UsageMetadata> | undefined {
|
|
33
|
+
if (response == null) return undefined;
|
|
34
|
+
const metadata = response.response_metadata as {
|
|
35
|
+
usage?: BedrockSummarizationUsage;
|
|
36
|
+
metadata?: { usage?: BedrockSummarizationUsage };
|
|
37
|
+
} | undefined;
|
|
38
|
+
const raw = metadata?.metadata?.usage ?? metadata?.usage;
|
|
39
|
+
if ('usage_metadata' in response && response.usage_metadata != null) {
|
|
40
|
+
return normalizeBedrockInputUsage(
|
|
41
|
+
response.usage_metadata as Partial<UsageMetadata>, raw
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
if (raw == null) return undefined;
|
|
45
|
+
|
|
46
|
+
const input_tokens = tokenCount(raw.inputTokens);
|
|
47
|
+
const output_tokens = tokenCount(raw.outputTokens);
|
|
48
|
+
const total_tokens = tokenCount(raw.totalTokens);
|
|
49
|
+
const cache_read = tokenCount(raw.cacheReadInputTokens);
|
|
50
|
+
const cache_creation = tokenCount(raw.cacheWriteInputTokens);
|
|
51
|
+
if (
|
|
52
|
+
input_tokens == null &&
|
|
53
|
+
output_tokens == null &&
|
|
54
|
+
total_tokens == null &&
|
|
55
|
+
cache_read == null &&
|
|
56
|
+
cache_creation == null
|
|
57
|
+
) return undefined;
|
|
58
|
+
|
|
59
|
+
return normalizeBedrockInputUsage({
|
|
60
|
+
...(input_tokens == null ? {} : { input_tokens }),
|
|
61
|
+
...(output_tokens == null ? {} : { output_tokens }),
|
|
62
|
+
...(total_tokens == null ? {} : { total_tokens }),
|
|
63
|
+
...(cache_read == null && cache_creation == null
|
|
64
|
+
? {}
|
|
65
|
+
: {
|
|
66
|
+
input_token_details: {
|
|
67
|
+
...(cache_read == null ? {} : { cache_read }),
|
|
68
|
+
...(cache_creation == null ? {} : { cache_creation }),
|
|
69
|
+
},
|
|
70
|
+
}),
|
|
71
|
+
}, raw);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function buildSummarizationStepUsage(
|
|
75
|
+
attempts: readonly SummarizationAttemptUsage[]
|
|
76
|
+
): {
|
|
77
|
+
prompt_tokens: number;
|
|
78
|
+
completion_tokens: number;
|
|
79
|
+
total_tokens: number;
|
|
80
|
+
attemptUsage?: readonly SummarizationAttemptUsage[];
|
|
81
|
+
} | undefined {
|
|
82
|
+
if (attempts.length === 0) return undefined;
|
|
83
|
+
|
|
84
|
+
let prompt_tokens = 0;
|
|
85
|
+
let completion_tokens = 0;
|
|
86
|
+
let total_tokens = 0;
|
|
87
|
+
const attemptUsage: SummarizationAttemptUsage[] | undefined =
|
|
88
|
+
attempts.length > 1 ? [] : undefined;
|
|
89
|
+
for (const attempt of attempts) {
|
|
90
|
+
const { usage } = attempt;
|
|
91
|
+
const input = tokenCount(usage.input_tokens) ?? 0;
|
|
92
|
+
const output = tokenCount(usage.output_tokens) ?? 0;
|
|
93
|
+
prompt_tokens += input;
|
|
94
|
+
completion_tokens += output;
|
|
95
|
+
total_tokens += tokenCount(usage.total_tokens) ?? input + output;
|
|
96
|
+
attemptUsage?.push({
|
|
97
|
+
provider: attempt.provider,
|
|
98
|
+
...(attempt.model == null ? {} : { model: attempt.model }),
|
|
99
|
+
usage: {
|
|
100
|
+
...usage,
|
|
101
|
+
...(usage.input_token_details == null
|
|
102
|
+
? {}
|
|
103
|
+
: { input_token_details: { ...usage.input_token_details } }),
|
|
104
|
+
...(usage.output_token_details == null
|
|
105
|
+
? {}
|
|
106
|
+
: { output_token_details: { ...usage.output_token_details } }),
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return {
|
|
112
|
+
prompt_tokens,
|
|
113
|
+
completion_tokens,
|
|
114
|
+
total_tokens,
|
|
115
|
+
...(attemptUsage == null ? {} : { attemptUsage }),
|
|
116
|
+
};
|
|
117
|
+
}
|