-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcontextLengthError.ts
More file actions
228 lines (200 loc) · 6.1 KB
/
Copy pathcontextLengthError.ts
File metadata and controls
228 lines (200 loc) · 6.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
export interface ContextLengthExceededInfo {
isExceeded: boolean;
message: string;
actualTokens?: number;
limitTokens?: number;
}
const MAX_COLLECT_DEPTH = 4;
const TIMEOUT_PATTERNS = [
/\bcontext deadline exceeded\b/i,
/\bdeadline exceeded\b/i,
/\b(?:request|connection|read|context)\s+timed out\b/i,
/\b(?:request|connection|read|context)\s+timeout\b/i,
/\b(?:timeout|timed out)\s+(?:after|while|during)\b/i,
];
const CONTEXT_LENGTH_PATTERNS = [
/\bcontext[_\s-]?length[_\s-]?exceeded\b/i,
/\bmaximum context length\b/i,
/\bprompt\s+(?:is\s+)?too long\b/i,
/\binput\s+(?:token\s+)?(?:count\s+|length\s+)?(?:is\s+)?too long\b/i,
/\brange of input length should be\b/i,
/\btoo many tokens\b/i,
/\btokens?\s*>\s*[\d,]+\s*(?:maximum|max|limit)\b/i,
/\b(?:input|prompt|messages?|context)\b[^\n]{0,120}\btokens?\b[^\n]{0,120}\bexceed(?:s|ed|ing)?\b/i,
];
function parseInteger(value: string): number {
return Number.parseInt(value.replace(/,/g, ''), 10);
}
function parseTokenCounts(text: string): {
actualTokens?: number;
limitTokens?: number;
} {
const greaterThanMatch = text.match(/(\d[\d,]*)\s*tokens?\s*>\s*(\d[\d,]*)/i);
if (greaterThanMatch) {
return {
actualTokens: parseInteger(greaterThanMatch[1]!),
limitTokens: parseInteger(greaterThanMatch[2]!),
};
}
const openAiMatch = text.match(
/maximum context length is\s*(\d[\d,]*)\s*tokens?[\s\S]*?(?:resulted in|requested|used)\s*(\d[\d,]*)\s*tokens?/i,
);
if (openAiMatch) {
return {
actualTokens: parseInteger(openAiMatch[2]!),
limitTokens: parseInteger(openAiMatch[1]!),
};
}
const maxContextLimitMatch = text.match(
/maximum context length is\s*(\d[\d,]*)\s*tokens?/i,
);
if (maxContextLimitMatch) {
return {
limitTokens: parseInteger(maxContextLimitMatch[1]!),
};
}
const inputExceedsMatch = text.match(
/input\s+token\s+(?:count|length)[^\d]*(\d[\d,]*)[\s\S]*?exceed(?:s|ed)?[\s\S]*?(?:maximum|limit)[^\d]*(\d[\d,]*)/i,
);
if (inputExceedsMatch) {
return {
actualTokens: parseInteger(inputExceedsMatch[1]!),
limitTokens: parseInteger(inputExceedsMatch[2]!),
};
}
return {};
}
function tryParseEmbeddedJson(text: string): unknown | undefined {
const trimmed = text.trim();
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
try {
return JSON.parse(trimmed) as unknown;
} catch {
// Fall through to embedded-object parsing.
}
}
const start = text.indexOf('{');
const end = text.lastIndexOf('}');
if (start === -1 || end <= start) {
return undefined;
}
try {
return JSON.parse(text.slice(start, end + 1)) as unknown;
} catch {
return undefined;
}
}
function safeReadProperty(value: object, key: string): unknown {
try {
return (value as Record<string, unknown>)[key];
} catch {
return undefined;
}
}
function enumerableValues(value: object): unknown[] {
try {
return Object.values(value);
} catch {
try {
const descriptors = Object.getOwnPropertyDescriptors(value);
return Object.values(descriptors)
.filter(
(descriptor): descriptor is PropertyDescriptor & { value: unknown } =>
'value' in descriptor && descriptor.enumerable === true,
)
.map((descriptor) => descriptor.value);
} catch {
return [];
}
}
}
function collectStrings(
value: unknown,
seen: Set<object>,
depth = 0,
): string[] {
if (depth > MAX_COLLECT_DEPTH || value === null || value === undefined) {
return [];
}
if (typeof value === 'string') {
const parsed = tryParseEmbeddedJson(value);
if (parsed === undefined) {
return [value];
}
return [value, ...collectStrings(parsed, seen, depth + 1)];
}
if (typeof value === 'number' || typeof value === 'boolean') {
return [String(value)];
}
if (typeof value !== 'object') {
return [];
}
if (seen.has(value)) {
return [];
}
seen.add(value);
const strings: string[] = [];
if (value instanceof Error) {
const name = safeReadProperty(value, 'name');
const message = safeReadProperty(value, 'message');
if (typeof name === 'string') {
strings.push(name);
}
if (typeof message === 'string') {
strings.push(message);
}
strings.push(
...collectStrings(safeReadProperty(value, 'cause'), seen, depth + 1),
);
}
for (const nested of enumerableValues(value)) {
strings.push(...collectStrings(nested, seen, depth + 1));
}
return strings;
}
function uniqueNonEmpty(values: string[]): string[] {
const seen = new Set<string>();
const result: string[] = [];
for (const value of values) {
const trimmed = value.trim();
if (!trimmed || seen.has(trimmed)) {
continue;
}
seen.add(trimmed);
result.push(trimmed);
}
return result;
}
export function getContextLengthExceededInfo(
error: unknown,
): ContextLengthExceededInfo {
const fragments = uniqueNonEmpty(collectStrings(error, new Set<object>()));
const message = fragments.join('\n');
// The timeout veto is applied per fragment, alongside the context-length
// test it is vetoing. Testing it against the joined message instead let a
// timeout phrase anywhere in the error object suppress detection for the
// whole error -- and provider SDKs routinely attach retry/attempt metadata,
// so an overflow arriving with `previous attempt: request timed out` in a
// sibling field was reported as not-an-overflow and never reached the
// compaction path. A fragment counts as evidence only if it names a
// context-length failure and is not itself a timeout message.
const isExceeded = fragments.some(
(fragment) =>
CONTEXT_LENGTH_PATTERNS.some((pattern) => pattern.test(fragment)) &&
!TIMEOUT_PATTERNS.some((pattern) => pattern.test(fragment)),
);
const counts = isExceeded ? parseTokenCounts(message) : {};
return {
isExceeded,
message,
...counts,
};
}
export function isContextLengthExceededError(error: unknown): boolean {
return getContextLengthExceededInfo(error).isExceeded;
}