llm-large-files 0.5.0 → 0.7.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/CHANGELOG.md +1402 -467
- package/README.md +188 -60
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1012 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +306 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/src/model.ts
CHANGED
|
@@ -43,6 +43,17 @@ export type ChatTurn = { role: "user" | "assistant" | "model"; text: string };
|
|
|
43
43
|
*/
|
|
44
44
|
export type ToolTurn = { role: "tools"; calls: Array<ToolCall & { result: ToolResult }> };
|
|
45
45
|
|
|
46
|
+
/**
|
|
47
|
+
* A result of a stored tool round, as it is sent again in a later question: without
|
|
48
|
+
* `tool_turns_left`, which counted the tool turns its own question had left, not those of the
|
|
49
|
+
* later one. The same result when it has none.
|
|
50
|
+
*/
|
|
51
|
+
export function laterResult(result: ToolResult): ToolResult {
|
|
52
|
+
if (result === null || typeof result !== "object" || !("tool_turns_left" in result)) return result;
|
|
53
|
+
const { tool_turns_left: _left, ...rest } = result;
|
|
54
|
+
return rest;
|
|
55
|
+
}
|
|
56
|
+
|
|
46
57
|
/** What `askWithFiles` takes as conversation: plain turns, stored tool rounds, and turns with native parts. */
|
|
47
58
|
export type ChatMessage = ChatTurn | ToolTurn | ModelTextMessage;
|
|
48
59
|
|
|
@@ -78,7 +89,15 @@ export type ModelReply = {
|
|
|
78
89
|
calls: ToolCall[];
|
|
79
90
|
/** This turn in the provider's own form, to send back unchanged with the tool results. */
|
|
80
91
|
raw?: unknown;
|
|
92
|
+
/** Why the reply ended, in the provider's own word ("STOP", "length", "end_turn"). */
|
|
81
93
|
finishReason?: string;
|
|
94
|
+
/**
|
|
95
|
+
* How the reply ended, in terms every adapter maps its own to: "complete"; "cut" at the output
|
|
96
|
+
* limit; "filtered" by the provider's safety filters; "malformed_call", a tool call the model
|
|
97
|
+
* tried to make that could not be read (Gemini's MALFORMED_FUNCTION_CALL). Unset when the
|
|
98
|
+
* adapter does not know the reason.
|
|
99
|
+
*/
|
|
100
|
+
finish?: "complete" | "cut" | "filtered" | "malformed_call";
|
|
82
101
|
/** Why the provider refused the prompt, when it did. Nothing more is asked after it. */
|
|
83
102
|
blockReason?: string;
|
|
84
103
|
usage?: Partial<ModelUsage>;
|
|
@@ -128,6 +147,13 @@ export type ModelCapabilities = {
|
|
|
128
147
|
* question is answered with what it has.
|
|
129
148
|
*/
|
|
130
149
|
appendOnly?: boolean;
|
|
150
|
+
/**
|
|
151
|
+
* True for a model whose provider may clear old tool results from the conversation on its side,
|
|
152
|
+
* before the model reads it (Claude's context editing with `clear_tool_uses`, or compaction). A
|
|
153
|
+
* call made again is then run again, instead of being answered with a pointer to an earlier
|
|
154
|
+
* result that the model may no longer have.
|
|
155
|
+
*/
|
|
156
|
+
clearsToolResults?: boolean;
|
|
131
157
|
};
|
|
132
158
|
|
|
133
159
|
/** A model provider, as the tool loop sees it. */
|
|
@@ -135,7 +161,12 @@ export interface ModelAdapter {
|
|
|
135
161
|
/** Names the model in usage totals and messages: "gemini-3.8-flash". */
|
|
136
162
|
readonly id: string;
|
|
137
163
|
readonly capabilities: ModelCapabilities;
|
|
138
|
-
/**
|
|
164
|
+
/**
|
|
165
|
+
* @deprecated Never called. The loop counts every request in the library's estimate
|
|
166
|
+
* (`estimateTokens`), as the documents were counted when they were uploaded, and turns that into
|
|
167
|
+
* this model's tokens with `capabilities.tokenScale`: set `tokenScale` instead. Kept so that
|
|
168
|
+
* adapters that declare it still compile; it may be removed in a later version.
|
|
169
|
+
*/
|
|
139
170
|
estimateTokens?(text: string): number;
|
|
140
171
|
/**
|
|
141
172
|
* One chat request. Throw a `ModelRequestError` for an HTTP error or a connection that failed:
|
|
@@ -151,21 +182,223 @@ export interface ModelAdapter {
|
|
|
151
182
|
generateText?: GenerateText;
|
|
152
183
|
}
|
|
153
184
|
|
|
185
|
+
/**
|
|
186
|
+
* What went wrong with a model request, as far as the error says:
|
|
187
|
+
* - "context_overflow": the request was larger than the model takes (its context window, or the
|
|
188
|
+
* size of the body). A smaller request can work.
|
|
189
|
+
* - "quota": a quota that does not come back soon (a daily cap, no credit left). Sending again
|
|
190
|
+
* does not help.
|
|
191
|
+
* - "rate_limit": too many requests or tokens for now (HTTP 429). Sending again later helps.
|
|
192
|
+
* - "timeout": nothing came from the model for longer than the adapter waits (`firstByteTimeoutMs`,
|
|
193
|
+
* `idleTimeoutMs`; status 0), or the provider or a gateway said the request timed out (HTTP 408).
|
|
194
|
+
* - "unreachable": no answer at all: the connection failed.
|
|
195
|
+
* - "server": the provider failed on its side (HTTP 5xx).
|
|
196
|
+
* - "auth": the key or token was refused (HTTP 401, 403).
|
|
197
|
+
* - "invalid": the provider refused the request as it was (another HTTP 4xx).
|
|
198
|
+
*/
|
|
199
|
+
export type ModelErrorKind = "context_overflow" | "quota" | "rate_limit" | "timeout" | "unreachable" | "server" | "auth" | "invalid";
|
|
200
|
+
|
|
201
|
+
/** How an error was told apart, with the numbers of an overflow when the message gives them. */
|
|
202
|
+
export type ModelErrorClass = {
|
|
203
|
+
kind: ModelErrorKind;
|
|
204
|
+
/** The most input tokens the model takes, as the provider counts them. */
|
|
205
|
+
limitTokens?: number;
|
|
206
|
+
/**
|
|
207
|
+
* The tokens of the refused request that the provider counted against the window: its input,
|
|
208
|
+
* and for some providers (OpenRouter, vLLM) the output it would have taken too.
|
|
209
|
+
*/
|
|
210
|
+
requestedTokens?: number;
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
/** Wording of a request larger than the model takes, across providers. */
|
|
214
|
+
const OVERFLOW_WORDING = [
|
|
215
|
+
/context[_ ]length[_ ]exceeded/i,
|
|
216
|
+
/maximum context length/i,
|
|
217
|
+
/prompt is too long/i,
|
|
218
|
+
/input token count\b.{0,40}\bexceeds/i,
|
|
219
|
+
// Vertex AI: "Unable to submit request because the input token count is N but model only supports up to M."
|
|
220
|
+
/input token count is [\d,]+ but/i,
|
|
221
|
+
/model only supports up to/i,
|
|
222
|
+
/exceeds? the maximum number of tokens/i,
|
|
223
|
+
/maximum context (?:size|window)/i,
|
|
224
|
+
/too large for (?:the )?model with [\d,]+ maximum context/i,
|
|
225
|
+
/exceeds? (?:the )?(?:available |model'?s? )?context (?:size|window|length)/i,
|
|
226
|
+
/request payload size exceeds/i,
|
|
227
|
+
/reduce the length of the messages/i,
|
|
228
|
+
/input tokens? exceeds?/i,
|
|
229
|
+
/request_too_large/i,
|
|
230
|
+
// Claude 3.7 to 4.1: "input length and `max_tokens` exceed context limit: 188240 + 21333 > 200000".
|
|
231
|
+
/exceed context limit/i,
|
|
232
|
+
// Text Generation Inference (Hugging Face, Together): "Input validation error: `inputs` tokens +
|
|
233
|
+
// `max_new_tokens` must be <= 32769. Given: 40000 `inputs` tokens and 1024 `max_new_tokens`".
|
|
234
|
+
/`?inputs`? tokens \+ `?max_new_tokens`? must be <=/i,
|
|
235
|
+
/`?inputs`? must have less than [\d,]+ tokens/i,
|
|
236
|
+
// LM Studio: "Trying to keep the first 9000 tokens when context the overflows. However, the model
|
|
237
|
+
// is loaded with context length of only 4096 tokens, which is not enough."
|
|
238
|
+
/loaded with context length of only/i,
|
|
239
|
+
/tokens to keep from the initial prompt is greater than the context length/i,
|
|
240
|
+
// Amazon Bedrock: "Input is too long for requested model."
|
|
241
|
+
/input is too long for (?:the )?(?:requested )?model/i,
|
|
242
|
+
];
|
|
243
|
+
/**
|
|
244
|
+
* A request larger than the tokens a whole minute (or day) allows. OpenAI: "Request too large for
|
|
245
|
+
* gpt-4o in organization org-… on tokens per min (TPM): Limit 30000, Requested 45237.", as HTTP 429.
|
|
246
|
+
* Groq says "tokens per minute", as HTTP 413. No wait lets it pass: only a smaller request can.
|
|
247
|
+
*/
|
|
248
|
+
const RATE_TOO_SMALL = /request too large for .{0,200}\bon tokens per (min(?:ute)?|day)\b/i;
|
|
249
|
+
/** Wording of throttling, which can share words with an overflow ("too many tokens, please wait"). */
|
|
250
|
+
const THROTTLE_WORDING = /rate.?limit|too many requests|please (?:wait|try again later)|per (?:minute|second|day)\b|\b[TR]PM\b|throttl/i;
|
|
251
|
+
|
|
252
|
+
const LIMIT_WORDING = [
|
|
253
|
+
/maximum context length is ([\d,]+)/i,
|
|
254
|
+
// The Gemini API puts the number in parentheses; Vertex AI (November 2026) does not:
|
|
255
|
+
// "The input token count exceeds the maximum number of tokens allowed 1048576."
|
|
256
|
+
/maximum number of tokens allowed \(?([\d,]+)/i,
|
|
257
|
+
/> ?([\d,]+) maximum/i,
|
|
258
|
+
/with ([\d,]+) maximum context/i,
|
|
259
|
+
/configured limit of ([\d,]+) tokens/i,
|
|
260
|
+
/supports up to ([\d,]+)/i,
|
|
261
|
+
/context limit: [\d,]+ \+ [\d,]+ > ([\d,]+)/i,
|
|
262
|
+
/must be <= ?([\d,]+)/i,
|
|
263
|
+
/must have less than ([\d,]+) tokens/i,
|
|
264
|
+
/context length of only ([\d,]+) tokens/i,
|
|
265
|
+
/\bLimit:? ([\d,]+), Requested\b/i,
|
|
266
|
+
];
|
|
267
|
+
const REQUESTED_WORDING = [
|
|
268
|
+
/input token count \(([\d,]+)\)/i,
|
|
269
|
+
/input token count is ([\d,]+)/i,
|
|
270
|
+
/context limit: ([\d,]+) \+/i,
|
|
271
|
+
/\(([\d,]+) in the messages/i,
|
|
272
|
+
/resulted in ([\d,]+) tokens/i,
|
|
273
|
+
/too long: ([\d,]+) tokens/i,
|
|
274
|
+
/prompt contains ([\d,]+) tokens/i,
|
|
275
|
+
/requested (?:about )?([\d,]+) tokens/i,
|
|
276
|
+
// vLLM since its errors changed: "However, your request has 40000 input tokens."
|
|
277
|
+
/your request has ([\d,]+) input tokens/i,
|
|
278
|
+
/\bGiven: ([\d,]+)/i,
|
|
279
|
+
/\bRequested:? ([\d,]+)/i,
|
|
280
|
+
];
|
|
281
|
+
/**
|
|
282
|
+
* Wording of a quota that does not come back soon: no credit left (DeepSeek's "Insufficient
|
|
283
|
+
* Balance", OpenRouter's "Insufficient credits", Claude's "Your credit balance is too low"), or a
|
|
284
|
+
* spending cap that was reached (Claude's "You have reached your API usage limits").
|
|
285
|
+
*/
|
|
286
|
+
const QUOTA_WORDING = /credit balance is too low|insufficient (?:balance|credits?|funds)|reached your (?:specified )?API usage limits/i;
|
|
287
|
+
/** A quota per day named in the message alone: Vertex AI's "Quota exceeded for …requests_per_day_per_project…". */
|
|
288
|
+
const DAILY_QUOTA_WORDING = /quota.{0,200}(?:per[_ -]?day|PerDay)/i;
|
|
289
|
+
|
|
290
|
+
function firstNumber(message: string, patterns: RegExp[]): number | undefined {
|
|
291
|
+
for (const pattern of patterns) {
|
|
292
|
+
const found = pattern.exec(message)?.[1];
|
|
293
|
+
if (!found) continue;
|
|
294
|
+
const value = Number(found.replace(/,/g, ""));
|
|
295
|
+
if (Number.isFinite(value) && value > 0) return value;
|
|
296
|
+
}
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** True when a Gemini error says a quota per day ran out: `google.rpc.QuotaFailure` with a "PerDay" quota. */
|
|
301
|
+
function dailyQuota(details: unknown): boolean {
|
|
302
|
+
if (!Array.isArray(details)) return false;
|
|
303
|
+
return details.some((detail) => {
|
|
304
|
+
const violations = (detail as { violations?: unknown } | null)?.violations;
|
|
305
|
+
return Array.isArray(violations) && violations.some((violation) => {
|
|
306
|
+
const id = (violation as { quotaId?: unknown; quotaMetric?: unknown } | null);
|
|
307
|
+
return /per.?day/i.test(`${String(id?.quotaId ?? "")} ${String(id?.quotaMetric ?? "")}`);
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** A request larger than the model takes, with the numbers its message gives. */
|
|
313
|
+
function overflowOf(message: string): ModelErrorClass {
|
|
314
|
+
const limitTokens = firstNumber(message, LIMIT_WORDING);
|
|
315
|
+
const requestedTokens = firstNumber(message, REQUESTED_WORDING);
|
|
316
|
+
return { kind: "context_overflow", ...(limitTokens ? { limitTokens } : {}), ...(requestedTokens ? { requestedTokens } : {}) };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** True when a Gemini error names an API key that is not valid (it comes as HTTP 400). */
|
|
320
|
+
const keyRefused = (details: unknown): boolean => Array.isArray(details) && details.some((detail) => (detail as { reason?: unknown } | null)?.reason === "API_KEY_INVALID");
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Tells what kind of failure an HTTP status and an error message are (see `ModelErrorKind`).
|
|
324
|
+
* `code` is the provider's own word, when it gives one (OpenAI's `error.code`, Claude's
|
|
325
|
+
* `error.type`, Gemini's `error.status`); `details` is a Gemini error's `details`. A quota is told
|
|
326
|
+
* from those, from HTTP 402 (payment required), and from words that only a quota uses (no credit
|
|
327
|
+
* left, a spending cap, a quota per day): Gemini says "You exceeded your current quota" of a limit
|
|
328
|
+
* per minute too, which a wait mends.
|
|
329
|
+
*/
|
|
330
|
+
export function classifyModelError(status: number, message: string, signals: { code?: string | undefined; details?: unknown } = {}): ModelErrorClass {
|
|
331
|
+
const { code, details } = signals;
|
|
332
|
+
if (status === 0) return { kind: "unreachable" };
|
|
333
|
+
if (code === "insufficient_quota" || status === 402 || (status === 429 && (dailyQuota(details) || DAILY_QUOTA_WORDING.test(message)))) return { kind: "quota" };
|
|
334
|
+
if (status < 500 && QUOTA_WORDING.test(message)) return { kind: "quota" };
|
|
335
|
+
// Larger than the provider lets through in a minute: a context overflow, though it comes as 429,
|
|
336
|
+
// and though its words are those of a rate limit.
|
|
337
|
+
if ((status === 429 || status === 413) && RATE_TOO_SMALL.test(message)) return overflowOf(message);
|
|
338
|
+
const throttled = THROTTLE_WORDING.test(message);
|
|
339
|
+
const overflow = !throttled && status !== 429 && status < 500 && (
|
|
340
|
+
status === 413 || code === "context_length_exceeded" || code === "request_too_large" || OVERFLOW_WORDING.some((pattern) => pattern.test(message))
|
|
341
|
+
);
|
|
342
|
+
if (overflow) return overflowOf(message);
|
|
343
|
+
if (status === 429) return { kind: "rate_limit" };
|
|
344
|
+
if (status === 408) return { kind: "timeout" };
|
|
345
|
+
if (status >= 500) return { kind: "server" };
|
|
346
|
+
if (status === 401 || status === 403 || keyRefused(details)) return { kind: "auth" };
|
|
347
|
+
return { kind: "invalid" };
|
|
348
|
+
}
|
|
349
|
+
|
|
154
350
|
/**
|
|
155
351
|
* A model request that failed: the provider answered with an HTTP error, or could not be reached
|
|
156
|
-
* (`status` 0). `retryAfterMs` is the wait the provider asked for, when it named one.
|
|
352
|
+
* (`status` 0). `retryAfterMs` is the wait the provider asked for, when it named one. `kind` says
|
|
353
|
+
* what went wrong (see `ModelErrorKind`); for a request larger than the model takes,
|
|
354
|
+
* `limitTokens` and `requestedTokens` are the provider's numbers, when its message gives them.
|
|
157
355
|
*/
|
|
158
356
|
export class ModelRequestError extends Error {
|
|
159
357
|
readonly status: number;
|
|
160
358
|
readonly retryAfterMs?: number;
|
|
161
|
-
|
|
359
|
+
readonly kind: ModelErrorKind;
|
|
360
|
+
readonly limitTokens?: number;
|
|
361
|
+
readonly requestedTokens?: number;
|
|
362
|
+
constructor(message: string, status: number, options: {
|
|
363
|
+
retryAfterMs?: number;
|
|
364
|
+
cause?: unknown;
|
|
365
|
+
/** The kind, when the adapter knows it (a timeout). Otherwise it is told from the status and the message. */
|
|
366
|
+
kind?: ModelErrorKind;
|
|
367
|
+
/** The provider's own word for the error, used to tell its kind. */
|
|
368
|
+
code?: string | undefined;
|
|
369
|
+
/** The `details` of a Gemini error, used to tell its kind. */
|
|
370
|
+
details?: unknown;
|
|
371
|
+
} = {}) {
|
|
162
372
|
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
163
373
|
this.name = "ModelRequestError";
|
|
164
374
|
this.status = status;
|
|
165
375
|
if (options.retryAfterMs !== undefined) this.retryAfterMs = options.retryAfterMs;
|
|
376
|
+
const found = classifyModelError(status, message, { code: options.code, details: options.details });
|
|
377
|
+
this.kind = options.kind ?? found.kind;
|
|
378
|
+
if (this.kind === "context_overflow") {
|
|
379
|
+
if (found.limitTokens) this.limitTokens = found.limitTokens;
|
|
380
|
+
if (found.requestedTokens) this.requestedTokens = found.requestedTokens;
|
|
381
|
+
}
|
|
166
382
|
}
|
|
167
383
|
}
|
|
168
384
|
|
|
385
|
+
/** The kind of a model error, when it has one: a `ModelRequestError`'s, or that of an error with the same field. */
|
|
386
|
+
export function errorKindOf(error: unknown): ModelErrorKind | undefined {
|
|
387
|
+
const kind = (error as { kind?: unknown } | null)?.kind;
|
|
388
|
+
return typeof kind === "string" ? kind as ModelErrorKind : undefined;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* For a request refused as larger than the tokens a minute (or a day) of the provider allows, not
|
|
393
|
+
* than the model's window: that period. Undefined for any other error.
|
|
394
|
+
*/
|
|
395
|
+
export function rateAllowanceOf(error: unknown): "minute" | "day" | undefined {
|
|
396
|
+
if (errorKindOf(error) !== "context_overflow" || !(error instanceof Error)) return undefined;
|
|
397
|
+
const period = RATE_TOO_SMALL.exec(error.message)?.[1];
|
|
398
|
+
if (period === undefined) return undefined;
|
|
399
|
+
return period.toLowerCase() === "day" ? "day" : "minute";
|
|
400
|
+
}
|
|
401
|
+
|
|
169
402
|
/** Some document IDs were never uploaded, have expired, or belong to another owner. */
|
|
170
403
|
export class DocumentsNotFoundError extends Error {
|
|
171
404
|
constructor(readonly ids: string[]) {
|
package/src/node/handlers.ts
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
-
import {
|
|
2
|
+
import { isStoreWriteFailure } from "../errors.js";
|
|
3
|
+
import { eventStream, newRunId, type EventError, type IngestEvent } from "../events.js";
|
|
4
|
+
import { checkOwner, toDocumentSummary, type IngestInput, type LargeFiles } from "../library.js";
|
|
3
5
|
import { formatBytes } from "../plan.js";
|
|
6
|
+
import type { DocumentMeta } from "../types.js";
|
|
7
|
+
import { writeSseEvents } from "./sse.js";
|
|
4
8
|
|
|
5
9
|
export type DocumentHandlerOptions = {
|
|
6
10
|
/**
|
|
7
11
|
* The signed-in user for this request. When set, uploads are owned by that user and other
|
|
8
|
-
* users cannot read or delete them. Return undefined to allow anonymous access.
|
|
12
|
+
* users cannot read or delete them. Return undefined to allow anonymous access. An empty owner
|
|
13
|
+
* ("", spaces only, or null from JavaScript) is the server's mistake: the upload is answered with a 500
|
|
14
|
+
* `{"error":"Upload failed (empty owner)."}`, before its body is read. So is an owner from
|
|
15
|
+
* JavaScript that is neither a string nor a finite number (`req.user` in place of `req.user.id`,
|
|
16
|
+
* say): `{"error":"Upload failed (owner is not a string)."}`.
|
|
9
17
|
*
|
|
10
18
|
* To refuse a request, throw an error with a `status` (or `statusCode`) between 400 and 599, as
|
|
11
19
|
* the `http-errors` package makes: the handler answers with that status and the error's message.
|
|
@@ -17,10 +25,21 @@ export type DocumentHandlerOptions = {
|
|
|
17
25
|
|
|
18
26
|
/**
|
|
19
27
|
* The handlers answer every request themselves, errors included, and never reject: they can be
|
|
20
|
-
* called without a `catch`, from `node:http
|
|
28
|
+
* called without a `catch`, from `node:http`, from Express 4 (which does not catch a rejected
|
|
29
|
+
* promise) or from Express 5.
|
|
21
30
|
*/
|
|
22
31
|
export type DocumentHandlers = {
|
|
23
|
-
/**
|
|
32
|
+
/**
|
|
33
|
+
* POST: the body is the raw file. Name it with an `X-File-Name` header (URI-encoded) or `?name=`.
|
|
34
|
+
* A file that cannot be read is answered with a 422 and the reason. A store that fails while it
|
|
35
|
+
* writes is answered with a 500 that does not repeat its message, unless its error has a status.
|
|
36
|
+
*
|
|
37
|
+
* When the request's `Accept` header names `text/event-stream` (not with `q=0`, nor only through a
|
|
38
|
+
* wildcard), a file that passes the checks of the name, the owner and the size (which still
|
|
39
|
+
* answer with an HTTP error) is answered with a 200 and Server-Sent Events: the ingest's events (`ingest.start`, `ingest.progress`…), ending
|
|
40
|
+
* with `ingest.finish`, whose data is the summary a 201 would hold, or `ingest.error`, whose data
|
|
41
|
+
* is `{ error: { message, status } }` with the message and status a JSON answer would have.
|
|
42
|
+
*/
|
|
24
43
|
upload(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
25
44
|
/** GET: the document's summary, or 404. */
|
|
26
45
|
get(request: IncomingMessage, response: ServerResponse, id: string): Promise<void>;
|
|
@@ -53,18 +72,92 @@ function systemErrorCode(error: unknown): string | undefined {
|
|
|
53
72
|
}
|
|
54
73
|
|
|
55
74
|
/**
|
|
56
|
-
*
|
|
57
|
-
* the server's trouble: a 500 that says what failed and, for a system error, its code.
|
|
75
|
+
* The answer to a failed request. An error with a status keeps its status and message. Anything
|
|
76
|
+
* else is the server's trouble: a 500 that says what failed and, for a system error, its code.
|
|
58
77
|
*/
|
|
59
|
-
function
|
|
78
|
+
function answerOf(error: unknown, failed: string, tooLarge: string): { status: number; message: string } {
|
|
60
79
|
const status = statusOf(error);
|
|
61
80
|
if (status !== undefined) {
|
|
62
|
-
|
|
63
|
-
send(response, status, { error: message });
|
|
64
|
-
return;
|
|
81
|
+
return { status, message: status === 413 ? tooLarge : error instanceof Error && error.message ? error.message : `${failed}.` };
|
|
65
82
|
}
|
|
66
83
|
const code = systemErrorCode(error);
|
|
67
|
-
|
|
84
|
+
return { status: 500, message: code ? `${failed} (${code}).` : `${failed}.` };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Answers a failed request with JSON (see `answerOf`). */
|
|
88
|
+
function fail(response: ServerResponse, error: unknown, failed: string, tooLarge: string): void {
|
|
89
|
+
const { status, message } = answerOf(error, failed, tooLarge);
|
|
90
|
+
send(response, status, { error: message });
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* An error of `ingest` as the upload answers it. A file that cannot be read is the client's 422,
|
|
95
|
+
* with the reason. An error with a status keeps it, and a system error is the server's 500 with its
|
|
96
|
+
* code. A store that failed in another way is the server's 500 too, without its message: that is
|
|
97
|
+
* the store's own, and may name a database host. So is a value that is not an Error, whoever threw it.
|
|
98
|
+
*/
|
|
99
|
+
function ingestFailure(error: unknown): unknown {
|
|
100
|
+
if (statusOf(error) !== undefined || systemErrorCode(error) !== undefined) return error;
|
|
101
|
+
if (isStoreWriteFailure(error) || !(error instanceof Error)) return error;
|
|
102
|
+
return new HttpError(422, error.message);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Whether the client asked for the upload's progress as Server-Sent Events: its `Accept` header
|
|
107
|
+
* names `text/event-stream` itself, without `q=0`. A wildcard (`text/*`, or any type at all) keeps
|
|
108
|
+
* the JSON answer.
|
|
109
|
+
*/
|
|
110
|
+
function wantsEvents(request: IncomingMessage): boolean {
|
|
111
|
+
const accept = request.headers.accept;
|
|
112
|
+
return (Array.isArray(accept) ? accept.join(",") : accept ?? "").split(",").some((range) => {
|
|
113
|
+
const [type, ...parameters] = range.split(";").map((part) => part.trim().toLowerCase());
|
|
114
|
+
if (type !== "text/event-stream") return false;
|
|
115
|
+
const q = parameters.map((parameter) => parameter.split("=").map((part) => part.trim())).find(([name]) => name === "q");
|
|
116
|
+
return q === undefined || Number(q[1]) > 0;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Ingests the upload and answers with its events as Server-Sent Events. The last one is always
|
|
122
|
+
* `ingest.finish` or `ingest.error`, even with a `LargeFiles` of your own whose `ingest` sends no events.
|
|
123
|
+
*/
|
|
124
|
+
async function streamIngest(files: LargeFiles, input: IngestInput, response: ServerResponse, tooLarge: string): Promise<void> {
|
|
125
|
+
const runId = newRunId("ing");
|
|
126
|
+
const stream = eventStream<IngestEvent, DocumentMeta>(
|
|
127
|
+
(onEvent, signal) => files.ingest({ ...input, runId, onEvent, signal }),
|
|
128
|
+
{ signal: input.signal },
|
|
129
|
+
);
|
|
130
|
+
// The error as a JSON answer would give it: the event's own may hold a store's message.
|
|
131
|
+
const answer = async (fallback: EventError): Promise<EventError> => {
|
|
132
|
+
try {
|
|
133
|
+
await stream.result;
|
|
134
|
+
return { message: fallback.message, ...(fallback.status !== undefined ? { status: fallback.status } : {}) };
|
|
135
|
+
} catch (error) {
|
|
136
|
+
return answerOf(ingestFailure(error), "Upload failed", tooLarge);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
async function* events(): AsyncGenerator<IngestEvent> {
|
|
140
|
+
let seq = 0;
|
|
141
|
+
for await (const event of stream) {
|
|
142
|
+
seq = event.seq;
|
|
143
|
+
if (event.type === "ingest.error") {
|
|
144
|
+
yield { ...event, error: await answer(event.error) };
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
yield event;
|
|
148
|
+
if (event.type === "ingest.finish") return;
|
|
149
|
+
}
|
|
150
|
+
// The ingest ended without a last event: a `LargeFiles` of your own whose ingest sends none.
|
|
151
|
+
const base = { seq: seq + 1, runId, time: Date.now() };
|
|
152
|
+
try {
|
|
153
|
+
yield { ...base, type: "ingest.finish", document: toDocumentSummary(await stream.result) };
|
|
154
|
+
} catch {
|
|
155
|
+
yield { ...base, type: "ingest.error", error: await answer({ message: "Upload failed." }) };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
// Each message is the event itself, as for a question: `ingest.finish` holds the summary a 201
|
|
159
|
+
// answer would (`document`), `ingest.error` the message and status a JSON answer would (`error`).
|
|
160
|
+
await writeSseEvents(response, events());
|
|
68
161
|
}
|
|
69
162
|
|
|
70
163
|
function send(response: ServerResponse, status: number, value: unknown): void {
|
|
@@ -115,7 +208,8 @@ async function readBody(request: IncomingMessage, limit: number): Promise<Uint8A
|
|
|
115
208
|
|
|
116
209
|
/**
|
|
117
210
|
* Upload, get, and delete handlers for any Node HTTP server (node:http, Express, Fastify via
|
|
118
|
-
* `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON
|
|
211
|
+
* `request.raw`/`reply.raw`, Next.js API routes on the Node runtime). Responses are JSON, except an upload that asks for
|
|
212
|
+
* `text/event-stream`: it is answered with its ingest events.
|
|
119
213
|
*/
|
|
120
214
|
export function createDocumentHandlers(files: LargeFiles, options: DocumentHandlerOptions = {}): DocumentHandlers {
|
|
121
215
|
const tooLarge = `The file is larger than the ${formatBytes(files.maxUploadBytes)} upload limit.`;
|
|
@@ -127,27 +221,48 @@ export function createDocumentHandlers(files: LargeFiles, options: DocumentHandl
|
|
|
127
221
|
const url = new URL(request.url ?? "/", "http://localhost");
|
|
128
222
|
const name = header(request, "x-file-name").trim() || url.searchParams.get("name")?.trim() || "";
|
|
129
223
|
if (!name) throw new HttpError(400, "Name the file with an X-File-Name header or a ?name= query parameter.");
|
|
130
|
-
// Who is asking comes first: a refused upload is not read into memory.
|
|
224
|
+
// Who is asking comes first: a refused upload is not read into memory. An owner that
|
|
225
|
+
// `ingest` would refuse ("", or an object such as `req.user` from JavaScript) is the server's
|
|
226
|
+
// mistake, answered with a 500 before the body is read. Its message says which, so that the
|
|
227
|
+
// operator knows where to look; it says nothing else.
|
|
131
228
|
const currentOwner = await owner(request);
|
|
229
|
+
try {
|
|
230
|
+
checkOwner(currentOwner);
|
|
231
|
+
} catch {
|
|
232
|
+
const empty = typeof currentOwner === "string" || currentOwner === null;
|
|
233
|
+
throw new HttpError(500, empty ? "Upload failed (empty owner)." : "Upload failed (owner is not a string).");
|
|
234
|
+
}
|
|
132
235
|
const bytes = await readBody(request, files.maxUploadBytes);
|
|
133
236
|
const contentType = header(request, "content-type");
|
|
134
237
|
const mimeType = header(request, "x-file-type") || (contentType && !contentType.startsWith("application/octet-stream") ? contentType : "");
|
|
238
|
+
// A client that goes away before the answer stops the reading of its file: nobody would
|
|
239
|
+
// get the document, and the server has other work.
|
|
240
|
+
const gone = new AbortController();
|
|
241
|
+
const onClose = () => {
|
|
242
|
+
if (!response.writableFinished) gone.abort(new Error("The upload was cancelled: the client closed the connection."));
|
|
243
|
+
};
|
|
244
|
+
response.once("close", onClose);
|
|
245
|
+
const input: IngestInput = {
|
|
246
|
+
name,
|
|
247
|
+
bytes,
|
|
248
|
+
...(mimeType ? { mimeType } : {}),
|
|
249
|
+
...(currentOwner !== undefined ? { owner: currentOwner } : {}),
|
|
250
|
+
signal: gone.signal,
|
|
251
|
+
};
|
|
135
252
|
let meta;
|
|
136
253
|
try {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
bytes,
|
|
140
|
-
...(mimeType ? { mimeType } : {}),
|
|
141
|
-
...(currentOwner !== undefined ? { owner: currentOwner } : {}),
|
|
142
|
-
});
|
|
254
|
+
if (wantsEvents(request)) return await streamIngest(files, input, response, tooLarge);
|
|
255
|
+
meta = await files.ingest(input);
|
|
143
256
|
} catch (error) {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
257
|
+
throw ingestFailure(error);
|
|
258
|
+
} finally {
|
|
259
|
+
response.off("close", onClose);
|
|
147
260
|
}
|
|
148
261
|
send(response, 201, toDocumentSummary(meta));
|
|
149
262
|
} catch (error) {
|
|
150
263
|
fail(response, error, "Upload failed", tooLarge);
|
|
264
|
+
// An event stream that failed after its headers were sent cannot answer with a status.
|
|
265
|
+
if (response.headersSent && !response.writableEnded) response.end();
|
|
151
266
|
}
|
|
152
267
|
},
|
|
153
268
|
|
package/src/node/index.ts
CHANGED