llm-large-files 0.4.1 → 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 +1400 -338
- package/README.md +217 -49
- 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 +117 -0
- package/dist/anthropic/adapter.d.ts.map +1 -0
- package/dist/anthropic/adapter.js +542 -0
- package/dist/anthropic/adapter.js.map +1 -0
- package/dist/anthropic/index.d.ts +3 -0
- package/dist/anthropic/index.d.ts.map +1 -0
- package/dist/anthropic/index.js +2 -0
- package/dist/anthropic/index.js.map +1 -0
- package/dist/ask.d.ts +200 -0
- package/dist/ask.d.ts.map +1 -0
- package/dist/ask.js +1402 -0
- package/dist/ask.js.map +1 -0
- package/dist/budget.d.ts +23 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +64 -0
- package/dist/budget.js.map +1 -0
- 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 +42 -0
- package/dist/evidence.d.ts.map +1 -0
- package/dist/evidence.js +138 -0
- package/dist/evidence.js.map +1 -0
- 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 +59 -0
- package/dist/gemini/adapter.d.ts.map +1 -0
- package/dist/gemini/adapter.js +226 -0
- package/dist/gemini/adapter.js.map +1 -0
- package/dist/gemini/chat.d.ts +53 -77
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +42 -300
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +16 -0
- package/dist/gemini/errors.d.ts.map +1 -0
- package/dist/gemini/errors.js +46 -0
- package/dist/gemini/errors.js.map +1 -0
- package/dist/gemini/generate.d.ts +18 -21
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +49 -92
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +6 -4
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +4 -3
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -2
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -38
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +136 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +401 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +96 -8
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +414 -96
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +37 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +255 -61
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +278 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +222 -0
- package/dist/model.js.map +1 -0
- 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 +109 -0
- package/dist/openai/adapter.d.ts.map +1 -0
- package/dist/openai/adapter.js +567 -0
- package/dist/openai/adapter.js.map +1 -0
- package/dist/openai/index.d.ts +3 -0
- package/dist/openai/index.d.ts.map +1 -0
- package/dist/openai/index.js +2 -0
- package/dist/openai/index.js.map +1 -0
- package/dist/output-limit.d.ts +42 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +121 -0
- package/dist/output-limit.js.map +1 -0
- 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 +76 -0
- package/dist/retry.d.ts.map +1 -0
- package/dist/retry.js +141 -0
- package/dist/retry.js.map +1 -0
- 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 +36 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +153 -0
- package/dist/sse.js.map +1 -0
- 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 +72 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +341 -60
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +128 -4
- 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 +58 -184
- package/docs/configuration.md +34 -490
- package/docs/getting-started.md +412 -177
- 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 +1022 -138
- 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 +902 -90
- package/docs/troubleshooting.md +1390 -0
- package/package.json +22 -4
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +611 -0
- package/src/anthropic/index.ts +2 -0
- package/src/ask.ts +1560 -0
- package/src/budget.ts +71 -0
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +165 -0
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +271 -0
- package/src/gemini/chat.ts +87 -355
- package/src/gemini/errors.ts +48 -0
- package/src/gemini/generate.ts +67 -94
- package/src/gemini/index.ts +6 -4
- package/src/gemini/sse.ts +1 -34
- package/src/http.ts +434 -0
- package/src/index.ts +55 -4
- package/src/library.ts +497 -97
- package/src/map-reduce.ts +266 -59
- package/src/model.ts +433 -0
- 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 +613 -0
- package/src/openai/index.ts +2 -0
- package/src/output-limit.ts +135 -0
- 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 +176 -0
- package/src/search.ts +63 -10
- package/src/sse.ts +159 -0
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +338 -62
- package/src/types.ts +129 -5
- package/src/zip-directory.ts +136 -0
|
@@ -0,0 +1,758 @@
|
|
|
1
|
+
# Errors, retries and streams
|
|
2
|
+
|
|
3
|
+
This is the reference for the errors of model requests, the rule that sends a failed request again,
|
|
4
|
+
the waits on a silent model, and the parser of event streams, all from the main entry,
|
|
5
|
+
`llm-large-files`. Use it when you handle a failed question, write an adapter or a loop of your
|
|
6
|
+
own, or tune retries. What to show a user for each failure, and how the pieces work together, is
|
|
7
|
+
in [Errors and reliability](../guides/errors-and-reliability.md).
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import {
|
|
11
|
+
classifyModelError,
|
|
12
|
+
DEFAULT_FIRST_BYTE_TIMEOUT_MS,
|
|
13
|
+
DEFAULT_IDLE_TIMEOUT_MS,
|
|
14
|
+
errorKindOf,
|
|
15
|
+
isRetryableStatus,
|
|
16
|
+
ModelRequestError,
|
|
17
|
+
parseSseJson,
|
|
18
|
+
retryAfterMs,
|
|
19
|
+
withRetry,
|
|
20
|
+
} from "llm-large-files";
|
|
21
|
+
import type { EventError, IdleWaits, ModelErrorClass, ModelErrorKind, RetryNotice, RetryOptions, SseHooks } from "llm-large-files";
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Contents:
|
|
25
|
+
|
|
26
|
+
- Errors: [`ModelRequestError`](#modelrequesterror), [`ModelErrorKind`](#modelerrorkind),
|
|
27
|
+
[`ModelErrorClass`](#modelerrorclass),
|
|
28
|
+
[`classifyModelError`](#classifymodelerrorstatus-message-signals),
|
|
29
|
+
[`errorKindOf`](#errorkindoferror), [other error classes](#other-error-classes),
|
|
30
|
+
[errors in events: `EventError`](#errors-in-events-eventerror)
|
|
31
|
+
- Retries: [`withRetry`](#withretryrun-options), [`RetryOptions`](#retryoptions),
|
|
32
|
+
[`RetryNotice`](#retrynotice), [retries in events](#retries-in-events),
|
|
33
|
+
[`isRetryableStatus`](#isretryablestatusstatus), [`retryAfterMs`](#retryaftermsheaders-body-now)
|
|
34
|
+
- Waits on a reply: [`DEFAULT_FIRST_BYTE_TIMEOUT_MS`](#default_first_byte_timeout_ms),
|
|
35
|
+
[`DEFAULT_IDLE_TIMEOUT_MS`](#default_idle_timeout_ms), [`IdleWaits`](#idlewaits)
|
|
36
|
+
- Streams: [`parseSseJson`](#parsessejsonstream-hooks), [`SseHooks`](#ssehooks)
|
|
37
|
+
|
|
38
|
+
## Errors
|
|
39
|
+
|
|
40
|
+
### `ModelRequestError`
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
declare class ModelRequestError extends Error {
|
|
44
|
+
constructor(message: string, status: number, options?: {
|
|
45
|
+
retryAfterMs?: number;
|
|
46
|
+
cause?: unknown;
|
|
47
|
+
kind?: ModelErrorKind;
|
|
48
|
+
code?: string | undefined;
|
|
49
|
+
details?: unknown;
|
|
50
|
+
});
|
|
51
|
+
readonly status: number;
|
|
52
|
+
readonly kind: ModelErrorKind;
|
|
53
|
+
readonly retryAfterMs?: number;
|
|
54
|
+
readonly limitTokens?: number;
|
|
55
|
+
readonly requestedTokens?: number;
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
A model request that failed: the provider answered with an HTTP error, or no answer came
|
|
60
|
+
(`status` 0). Every adapter of the package throws a subclass of it (see
|
|
61
|
+
[other error classes](#other-error-classes)), and `askWithFiles` and `askGemini` throw it as it
|
|
62
|
+
came when another try did not help or was not worth making. `name` is `"ModelRequestError"`; each
|
|
63
|
+
subclass sets its own.
|
|
64
|
+
|
|
65
|
+
| Field | Type | What it holds |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `status` | `number` | The HTTP status of the provider's answer. 0 when no answer came: the connection failed, the adapter's wait on a silent model ran out (kind `"timeout"`), a stream ended before it was complete, or a reply of HTTP 200 came with an empty body. For an error event inside a stream whose response was HTTP 200, it is the status the event names or implies (Claude's `overloaded_error` is 529 and `invalid_request_error` 400; a Claude error with no `type`, or one the adapter does not map, is 500, as an OpenAI-compatible error the server does not name is). A Gemini error without a numeric `code` keeps the response's 200. A reply of HTTP 200 that the adapter could not read (a body that is not JSON, or a streamed event too long) keeps its 200, with kind `"invalid"`. See the adapter's page. |
|
|
68
|
+
| `kind` | `ModelErrorKind` | What went wrong. The `kind` option when it was given; otherwise `classifyModelError(status, message, { code, details }).kind`. New in 0.6.0. |
|
|
69
|
+
| `retryAfterMs` | `number`, optional | The wait the provider asked for, in milliseconds, when it named one. The adapters read it with [`retryAfterMs()`](#retryaftermsheaders-body-now). Unset otherwise. |
|
|
70
|
+
| `limitTokens` | `number`, optional | Only for kind `"context_overflow"`: the most input tokens the model takes, as the provider counts them, when its message names the number. New in 0.6.0. |
|
|
71
|
+
| `requestedTokens` | `number`, optional | Only for kind `"context_overflow"`: the tokens of the refused request that the provider counted against the window, when its message names them. Some providers (OpenRouter, vLLM) count the output it would have taken too. New in 0.6.0. |
|
|
72
|
+
| `message` | `string` | The provider's own message when its error body has one, otherwise the adapter's ("Claude returned HTTP 502."). It can name projects, quotas and models: log it, and show your users your own text. |
|
|
73
|
+
| `cause` | `unknown` | The `cause` option: for a request that got no answer, the error of `fetch`. |
|
|
74
|
+
|
|
75
|
+
The constructor options (`kind`, `code` and `details` are new in 0.6.0):
|
|
76
|
+
|
|
77
|
+
| Option | Type | Default | What it does |
|
|
78
|
+
|---|---|---|---|
|
|
79
|
+
| `retryAfterMs` | `number` | none | Sets `retryAfterMs`. |
|
|
80
|
+
| `cause` | `unknown` | none | Passed to `Error` as its `cause`. |
|
|
81
|
+
| `kind` | `ModelErrorKind` | told by `classifyModelError` | The kind, when you know it better than the status and message tell. Give `"timeout"` with status 0 when your own wait on the model ran out: without it, status 0 is `"unreachable"`. |
|
|
82
|
+
| `code` | `string \| undefined` | none | The provider's own word for the error, used to tell the kind: OpenAI's `error.code`, Claude's `error.type`, Gemini's `error.status`. `ModelRequestError` does not keep it. |
|
|
83
|
+
| `details` | `unknown` | none | The `details` array of a Gemini error body, used to tell a quota per day and an API key that is not valid. Not kept. |
|
|
84
|
+
|
|
85
|
+
`limitTokens` and `requestedTokens` are set only when the kind is `"context_overflow"` and
|
|
86
|
+
`classifyModelError` also reads the failure (its status, message and code) as an overflow, by the
|
|
87
|
+
checks of the [`ModelErrorKind`](#modelerrorkind) table. A `kind: "context_overflow"` you give gets
|
|
88
|
+
no numbers when the classifier reads the failure as another kind: status 0, a quota, a status of
|
|
89
|
+
500 and more, throttling wording, or none of the signs of an overflow. The constructor throws
|
|
90
|
+
nothing.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { ModelRequestError } from "llm-large-files";
|
|
94
|
+
|
|
95
|
+
const error = new ModelRequestError("prompt is too long: 210417 tokens > 200000 maximum", 400);
|
|
96
|
+
console.log(error.kind, error.limitTokens, error.requestedTokens); // "context_overflow" 200000 210417
|
|
97
|
+
|
|
98
|
+
console.log(new ModelRequestError("fetch failed", 0).kind); // "unreachable"
|
|
99
|
+
console.log(new ModelRequestError("Nothing for 600 s.", 0, { kind: "timeout" }).kind); // "timeout"
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
In a call of your own, throw it with the status, the provider's wait and its code, so that
|
|
103
|
+
[`withRetry`](#withretryrun-options) and your error handling can read them:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { ModelRequestError, retryAfterMs } from "llm-large-files";
|
|
107
|
+
|
|
108
|
+
/** One request to a model service of your own. Its failures are ModelRequestErrors. */
|
|
109
|
+
export async function post(url: string, body: unknown, signal?: AbortSignal): Promise<unknown> {
|
|
110
|
+
let response: Response;
|
|
111
|
+
try {
|
|
112
|
+
response = await fetch(url, {
|
|
113
|
+
method: "POST",
|
|
114
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.MODEL_API_KEY}` },
|
|
115
|
+
body: JSON.stringify(body),
|
|
116
|
+
...(signal ? { signal } : {}),
|
|
117
|
+
});
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (signal?.aborted) throw error;
|
|
120
|
+
// No answer at all: status 0, kind "unreachable".
|
|
121
|
+
throw new ModelRequestError("The model could not be reached.", 0, { cause: error });
|
|
122
|
+
}
|
|
123
|
+
if (response.ok) return response.json();
|
|
124
|
+
const data: unknown = await response.json().catch(() => null);
|
|
125
|
+
const failure = (data as { error?: { message?: unknown; code?: unknown } } | null)?.error;
|
|
126
|
+
const wait = retryAfterMs(response.headers, data);
|
|
127
|
+
throw new ModelRequestError(
|
|
128
|
+
typeof failure?.message === "string" ? failure.message : `The model returned HTTP ${response.status}.`,
|
|
129
|
+
response.status,
|
|
130
|
+
{
|
|
131
|
+
...(wait === undefined ? {} : { retryAfterMs: wait }),
|
|
132
|
+
...(typeof failure?.code === "string" ? { code: failure.code } : {}),
|
|
133
|
+
},
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Writing a whole adapter: [Your own adapter and loop](../guides/own-adapter-and-loop.md). What to
|
|
139
|
+
do with each kind: [Errors and reliability](../guides/errors-and-reliability.md).
|
|
140
|
+
|
|
141
|
+
### `ModelErrorKind`
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
type ModelErrorKind = "context_overflow" | "quota" | "rate_limit" | "timeout" | "unreachable" | "server" | "auth" | "invalid";
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
What went wrong with a model request. `classifyModelError` runs its checks in the order of this
|
|
148
|
+
table, and the first that matches gives the kind:
|
|
149
|
+
|
|
150
|
+
| Kind | What went wrong | How `classifyModelError` tells it | `withRetry` |
|
|
151
|
+
|---|---|---|---|
|
|
152
|
+
| `"unreachable"` | No answer at all: the connection failed, a stream ended before it was complete, or a reply of HTTP 200 came with an empty body. | Status 0. | Sends it again, up to `retries` times. |
|
|
153
|
+
| `"quota"` | A quota that does not come back soon: a daily cap, no credit left, a spending limit reached. | The code `insufficient_quota` (OpenAI), at any status but 0. Status 402. Status 429 with a Gemini `details` entry whose `violations` name a quota per day (a `quotaId` or `quotaMetric` that matches "per day": "PerDay", "per_day"), or with [quota-per-day wording](#classifymodelerrorstatus-message-signals) in the message. A status below 500 with [no-credit wording](#classifymodelerrorstatus-message-signals). | Never. |
|
|
154
|
+
| `"context_overflow"` | The request was larger than the model takes: its context window, the size of the body, or the tokens a minute (or a day) that the provider allows. | Status 429 or 413 with [allowance wording](#classifymodelerrorstatus-message-signals) (OpenAI's and Groq's "Request too large … on tokens per min (TPM)"). Otherwise a status below 500 and not 429, a message without [throttling wording](#classifymodelerrorstatus-message-signals), and one of: status 413; the code `context_length_exceeded` or `request_too_large`; [overflow wording](#classifymodelerrorstatus-message-signals) in the message. | Never, whatever its status: only a smaller request can pass. `askWithFiles` makes room instead: see [`askWithFiles`](./ask.md#askwithfilesoptions). |
|
|
155
|
+
| `"rate_limit"` | Too many requests or tokens for now, a Gemini quota per minute among them. | Any other status 429. | Sends it again, up to `retries` times, after the wait the provider asked for or a wait that doubles. Not when the provider asks for more than `maxDelayMs`. |
|
|
156
|
+
| `"timeout"` | Nothing came from the model for the adapter's wait, or the provider or a gateway said the request timed out. | Status 408. The classifier never gives it for status 0: the adapters pass `kind: "timeout"` when their own wait runs out. | Status 0: once. Status 408: up to `retries` times. |
|
|
157
|
+
| `"server"` | The provider failed on its side. | Status 500 or more. | Sends it again, up to `retries` times. |
|
|
158
|
+
| `"auth"` | The key or token was refused. | Status 401 or 403, or a Gemini `details` entry with `reason: "API_KEY_INVALID"` (Gemini sends it as HTTP 400). | Never. |
|
|
159
|
+
| `"invalid"` | The provider refused the request as it was. The adapters also give it to a reply of HTTP 200 they could not read: a body that is not JSON (a gateway's page), or a streamed event too long. | Any other status: 400, 404, 409, 422… | Never, except status 409, which [`isRetryableStatus`](#isretryablestatusstatus) accepts. |
|
|
160
|
+
|
|
161
|
+
Nothing is sent again after the caller's signal aborted, once `canRetry` says no, or when the
|
|
162
|
+
provider said not to (Claude's `x-should-retry: false`): see [`withRetry`](#withretryrun-options).
|
|
163
|
+
|
|
164
|
+
Kinds are new in 0.6.0. 0.5.0 sent an error again by its status alone: every status 0, 408, 409,
|
|
165
|
+
429 and 500 or more, so a quota or a request too large that came as HTTP 429 was sent again as it
|
|
166
|
+
was, up to three times.
|
|
167
|
+
|
|
168
|
+
### `ModelErrorClass`
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
type ModelErrorClass = {
|
|
172
|
+
kind: ModelErrorKind;
|
|
173
|
+
limitTokens?: number;
|
|
174
|
+
requestedTokens?: number;
|
|
175
|
+
};
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
What [`classifyModelError`](#classifymodelerrorstatus-message-signals) returns. New in 0.6.0.
|
|
179
|
+
|
|
180
|
+
| Field | Type | What it holds |
|
|
181
|
+
|---|---|---|
|
|
182
|
+
| `kind` | `ModelErrorKind` | The kind of the failure. |
|
|
183
|
+
| `limitTokens` | `number`, optional | For `"context_overflow"` only, when the message names it: the most input tokens the model takes. |
|
|
184
|
+
| `requestedTokens` | `number`, optional | For `"context_overflow"` only, when the message names it: the tokens the provider counted for the refused request. |
|
|
185
|
+
|
|
186
|
+
### classifyModelError(status, message, signals)
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
declare function classifyModelError(
|
|
190
|
+
status: number,
|
|
191
|
+
message: string,
|
|
192
|
+
signals?: { code?: string | undefined; details?: unknown },
|
|
193
|
+
): ModelErrorClass;
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
Tells the kind of a failure from its HTTP status, the provider's message and the provider's own
|
|
197
|
+
signals, by the order of the [`ModelErrorKind`](#modelerrorkind) table. For an overflow it also
|
|
198
|
+
reads the provider's numbers from the message. `ModelRequestError` calls it in its constructor;
|
|
199
|
+
call it yourself to see how a message of your provider is read. New in 0.6.0.
|
|
200
|
+
|
|
201
|
+
| Parameter | Type | Default | What it is |
|
|
202
|
+
|---|---|---|---|
|
|
203
|
+
| `status` | `number` | required | The HTTP status. 0 for a request that got no answer. |
|
|
204
|
+
| `message` | `string` | required | The provider's message. |
|
|
205
|
+
| `signals.code` | `string \| undefined` | none | The provider's own word for the error: OpenAI's `error.code`, Claude's `error.type`, Gemini's `error.status`. Three values change the kind: `insufficient_quota`, `context_length_exceeded` and `request_too_large`. |
|
|
206
|
+
| `signals.details` | `unknown` | none | A Gemini error's `details` array: a `QuotaFailure` with a quota per day, or a `reason` of `API_KEY_INVALID`. |
|
|
207
|
+
|
|
208
|
+
Returns a [`ModelErrorClass`](#modelerrorclass). Throws nothing.
|
|
209
|
+
|
|
210
|
+
The wording is matched without regard to case.
|
|
211
|
+
|
|
212
|
+
- **Quota-per-day wording**, at status 429: "quota" followed, within 200 characters, by "per day",
|
|
213
|
+
"per_day", "per-day" or "perday", as in Vertex AI's "Quota exceeded for
|
|
214
|
+
aiplatform.googleapis.com/generate_content_requests_per_day_per_project_per_base_model".
|
|
215
|
+
- **No-credit wording**, at any status below 500: "credit balance is too low" (Claude),
|
|
216
|
+
"insufficient balance" (DeepSeek), "insufficient credit(s)" (OpenRouter), "insufficient funds",
|
|
217
|
+
"reached your (specified) API usage limits" (Claude's spending limits).
|
|
218
|
+
- **Allowance wording**, at status 429 or 413: "request too large for", then, within 200
|
|
219
|
+
characters, "on tokens per min", "on tokens per minute" or "on tokens per day", as OpenAI's "Request too large for
|
|
220
|
+
gpt-4o in organization org-… on tokens per min (TPM): Limit 30000, Requested 45237." and Groq's
|
|
221
|
+
"… on tokens per minute (TPM): Limit 6000, Requested 6438". It is an overflow whatever else the
|
|
222
|
+
message says.
|
|
223
|
+
- **Throttling wording**, which keeps any other message from being an overflow even when it talks
|
|
224
|
+
of tokens: "rate limit" (or "rate-limit", "ratelimit"), "too many requests", "please wait",
|
|
225
|
+
"please try again later", "per minute", "per second", "per day", "TPM", "RPM", "throttl…".
|
|
226
|
+
- **Overflow wording**:
|
|
227
|
+
- "context_length_exceeded" (or "context length exceeded"), "request_too_large";
|
|
228
|
+
- "maximum context length", "maximum context size", "maximum context window";
|
|
229
|
+
- "prompt is too long";
|
|
230
|
+
- "input token count … exceeds" (within 40 characters), "input token count is N but",
|
|
231
|
+
"input token(s) exceed(s)";
|
|
232
|
+
- "model only supports up to";
|
|
233
|
+
- "exceed(s) the maximum number of tokens";
|
|
234
|
+
- "too large for (the) model with N maximum context";
|
|
235
|
+
- "exceed(s) (the) context size", "… context window", "… context length", also with "available"
|
|
236
|
+
or "model's" before "context";
|
|
237
|
+
- "request payload size exceeds", "reduce the length of the messages", "exceed context limit";
|
|
238
|
+
- "`inputs` tokens + `max_new_tokens` must be <=" and "`inputs` must have less than
|
|
239
|
+
N tokens" (Text Generation Inference, Together), "loaded with context length of only" and
|
|
240
|
+
"tokens to keep from the initial prompt is greater than the context length" (LM Studio),
|
|
241
|
+
"input is too long for (the) (requested) model" (Amazon Bedrock).
|
|
242
|
+
- **The window** (`limitTokens`), the first that matches: "maximum context length is N", "maximum
|
|
243
|
+
number of tokens allowed (N)" or "allowed N", "> N maximum", "with N maximum context", "configured
|
|
244
|
+
limit of N tokens", "supports up to N", "context limit: A + B > N", "must be <= N", "must have
|
|
245
|
+
less than N tokens", "context length of only N tokens", "Limit N, Requested" (or "Limit: N").
|
|
246
|
+
- **The request** (`requestedTokens`), the first that matches: "input token count (N)", "input
|
|
247
|
+
token count is N", "context limit: N +", "(N in the messages", "resulted in N tokens", "too long:
|
|
248
|
+
N tokens", "prompt contains N tokens", "requested (about) N tokens", "your request has N input
|
|
249
|
+
tokens" (vLLM), "Given: N", "Requested N" (or "Requested: N").
|
|
250
|
+
|
|
251
|
+
Numbers may have commas ("1,048,576"). A number that is not above 0 is left out.
|
|
252
|
+
|
|
253
|
+
```ts
|
|
254
|
+
import { classifyModelError } from "llm-large-files";
|
|
255
|
+
|
|
256
|
+
// A request larger than the tokens a minute allows, at status 429:
|
|
257
|
+
// { kind: "context_overflow", limitTokens: 30000, requestedTokens: 50000 }
|
|
258
|
+
classifyModelError(429, "Request too large for gpt-4o in organization org-1 on tokens per min (TPM): Limit 30000, Requested 50000.");
|
|
259
|
+
|
|
260
|
+
// Any other 429 is a rate limit, even one that speaks of tokens: { kind: "rate_limit" }
|
|
261
|
+
classifyModelError(429, "Rate limit reached for gpt-4o on tokens per min (TPM): Limit 30000, Used 29000, Requested 2000.");
|
|
262
|
+
|
|
263
|
+
// Throttling wording keeps a message from being an overflow at any status: { kind: "invalid" }
|
|
264
|
+
classifyModelError(400, "Input tokens exceed the limit. Please try again later.");
|
|
265
|
+
|
|
266
|
+
// No credit left: { kind: "quota" }
|
|
267
|
+
classifyModelError(402, "Insufficient Balance");
|
|
268
|
+
|
|
269
|
+
// A Gemini quota per day: { kind: "quota" }. With a quota per minute it is "rate_limit".
|
|
270
|
+
classifyModelError(429, "You exceeded your current quota.", {
|
|
271
|
+
code: "RESOURCE_EXHAUSTED",
|
|
272
|
+
details: [{ "@type": "type.googleapis.com/google.rpc.QuotaFailure", violations: [{ quotaId: "GenerateRequestsPerDayPerProjectPerModel" }] }],
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
// Vertex AI's wording: { kind: "context_overflow", limitTokens: 1048576 }
|
|
276
|
+
classifyModelError(400, "The input token count exceeds the maximum number of tokens allowed 1048576.");
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
A message your provider words another way is `"invalid"`, and `askWithFiles` does not make room
|
|
280
|
+
for it. An adapter or a wrapper of your own can set the kind itself with the `kind` option of
|
|
281
|
+
[`ModelRequestError`](#modelrequesterror).
|
|
282
|
+
|
|
283
|
+
### errorKindOf(error)
|
|
284
|
+
|
|
285
|
+
```ts
|
|
286
|
+
declare function errorKindOf(error: unknown): ModelErrorKind | undefined;
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
The kind of a model error: the `kind` field of the value when it is a string, whatever the
|
|
290
|
+
string. That covers `ModelRequestError` and its subclasses, and any error of your own with the
|
|
291
|
+
same field. Returns `undefined` for a value without one, such as `DocumentsNotFoundError`,
|
|
292
|
+
`DocumentStoreError`, the default reason of an aborted signal, or a plain `Error`. Throws nothing.
|
|
293
|
+
New in 0.6.0.
|
|
294
|
+
|
|
295
|
+
Since 0.6.0 the adapters throw no `SyntaxError` for a reply that is not JSON: it is the `cause` of
|
|
296
|
+
a `ModelRequestError` of kind `"invalid"` and status 200. Test `error.cause instanceof SyntaxError`
|
|
297
|
+
where you tested `error instanceof SyntaxError`: kind `"invalid"` alone also covers every other
|
|
298
|
+
request that the provider refused.
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
import { errorKindOf, ModelRequestError } from "llm-large-files";
|
|
302
|
+
|
|
303
|
+
errorKindOf(new ModelRequestError("Too many requests.", 429)); // "rate_limit"
|
|
304
|
+
errorKindOf(new Error("socket hang up")); // undefined
|
|
305
|
+
errorKindOf({ kind: "quota" }); // "quota": any value with a string kind
|
|
306
|
+
```
|
|
307
|
+
|
|
308
|
+
### Other error classes
|
|
309
|
+
|
|
310
|
+
The adapters' errors are `ModelRequestError`s, so `instanceof ModelRequestError` and
|
|
311
|
+
`errorKindOf` work for all three. The two errors of the documents are not, and have no `kind`.
|
|
312
|
+
|
|
313
|
+
| Class | Exported from | Extends | Fields of its own | Reference |
|
|
314
|
+
|---|---|---|---|---|
|
|
315
|
+
| `GeminiRequestError` | `llm-large-files/gemini` | `ModelRequestError` | none | [gemini.md](./gemini.md) |
|
|
316
|
+
| `OpenAiRequestError` | `llm-large-files/openai` | `ModelRequestError` | `param`, `code` | [openai.md](./openai.md) |
|
|
317
|
+
| `AnthropicRequestError` | `llm-large-files/anthropic` | `ModelRequestError` | `type` | [anthropic.md](./anthropic.md) |
|
|
318
|
+
| `DocumentsNotFoundError` | `llm-large-files`, `llm-large-files/gemini` | `Error` | `ids` | [ask.md](./ask.md#documentsnotfounderror) |
|
|
319
|
+
| `DocumentStoreError` | `llm-large-files` | `Error` | `code`, `syscall`, and the caught error as `cause` | [library.md](./library.md#documentstoreerror) |
|
|
320
|
+
|
|
321
|
+
### Errors in events: `EventError`
|
|
322
|
+
|
|
323
|
+
```ts
|
|
324
|
+
type EventError = { message: string; kind?: ModelErrorKind; status?: number; name?: string };
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
New in 0.7.0. An error as the events of a question or an ingest carry it ([events](./events.md)):
|
|
328
|
+
in `retry`, in `request.end` with outcome `"error"`, in `run.error` and in `ingest.error`. It is
|
|
329
|
+
plain data, safe to send to a browser. The error that is thrown is unchanged, the provider's words
|
|
330
|
+
included: log that one.
|
|
331
|
+
|
|
332
|
+
| Field | Type | What it holds |
|
|
333
|
+
|---|---|---|
|
|
334
|
+
| `message` | `string` | Words your users may see. A model error is told by its kind and status, never in the provider's words, which can name projects, hosts or keys: "The model was busy (HTTP 429).", "The model's quota has run out (HTTP 429).", "The model could not be reached.", "The model refused the key or token it was sent (HTTP 401)." A Node system error is told by its code ("The file could not be read from storage (ENOENT)."), a `DocumentStoreError` by its own message, which names only its code, and a store that failed to write in `ingest.error` as "The document could not be stored. Try again later.". The library's own errors (a refused file, `DocumentsNotFoundError`, an abort, the error a listener threw) keep their message, and so does any other `Error` without a `kind` or a numeric `status`, such as one an adapter or a token function of your own throws: give such errors a status, or words of your own. A value that is not an `Error` is "Something went wrong.". |
|
|
335
|
+
| `kind` | [`ModelErrorKind`](#modelerrorkind), optional | For a model error: its kind, as [`errorKindOf`](#errorkindoferror) reads it. |
|
|
336
|
+
| `status` | `number`, optional | For an HTTP error: its status. 0 when no answer came. |
|
|
337
|
+
| `name` | `string`, optional | The error's class name: `"ModelRequestError"`, `"GeminiRequestError"`, `"AbortError"`, `"DocumentsNotFoundError"`… |
|
|
338
|
+
|
|
339
|
+
To show your own words, map the error by `kind`, `status` or `name`, as you would the thrown one
|
|
340
|
+
(see [Errors and reliability](../guides/errors-and-reliability.md)).
|
|
341
|
+
|
|
342
|
+
## Retries
|
|
343
|
+
|
|
344
|
+
### withRetry(run, options)
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
declare function withRetry<T>(run: () => Promise<T>, options?: {
|
|
348
|
+
retry?: RetryOptions | undefined;
|
|
349
|
+
signal?: AbortSignal | undefined;
|
|
350
|
+
canRetry?: () => boolean;
|
|
351
|
+
onRetry?: (notice: RetryNotice) => void;
|
|
352
|
+
unknownErrors?: "once" | "never";
|
|
353
|
+
}): Promise<T>;
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
Runs `run`, and runs it again when it failed in a way that another try can mend. It is the rule
|
|
357
|
+
`askWithFiles` and `askGemini` use for each chat request, and the whole-file part reads use for
|
|
358
|
+
each part. It reads three fields of what `run` throws, so any error with them works, not only a
|
|
359
|
+
`ModelRequestError`: `status` (a finite number), `kind` and `retryAfterMs`. `run` is called again
|
|
360
|
+
as it is: build the request inside it.
|
|
361
|
+
|
|
362
|
+
| Option | Type | Default | What it does |
|
|
363
|
+
|---|---|---|---|
|
|
364
|
+
| `retry` | [`RetryOptions`](#retryoptions) | the `RetryOptions` defaults: 3 retries, a base wait of 500 ms before the jitter, at most 60,000 ms | How many times, and how long the waits are. |
|
|
365
|
+
| `signal` | `AbortSignal` | none | Once it has aborted, a failure is thrown as it is. A wait that is under way ends with the signal's reason. |
|
|
366
|
+
| `canRetry` | `() => boolean` | always true | Asked after each failure. `false` throws the error as it is: return `false` once the attempt did something that must not happen twice. `askWithFiles` returns `false` once text of the reply was shown: passed to `onText` and the `text` events as it streamed (see [retries in events](#retries-in-events)). |
|
|
367
|
+
| `onRetry` | `(notice: RetryNotice) => void` | none | Called before each wait with a [`RetryNotice`](#retrynotice): the error, `attempt` (the number of the retry to come, counting every retry made so far, the one of `unknownErrors` included: 1 for the first) and `delayMs` (the wait). Not called for the retry of an error without a status, which has no wait. `askWithFiles` turns it into an `onActivity` line such as "The model did not answer (HTTP 503). Trying again in 2 s…", "The model could not be reached. Trying again…", or, for a reply that began and was cut off on its way, "The model's reply was cut off on its way. Trying again…", and into a `retry` event. |
|
|
368
|
+
| `unknownErrors` | `"once" \| "never"` | `"never"` | An error without a numeric `status` (a bug in `run`, the abort error of a time limit of your own): `"once"` runs it once more at once, without a wait; any other value throws it. The part reads of a whole-file read use `"once"`; the chat requests of the loop do not. |
|
|
369
|
+
|
|
370
|
+
What happens to an error, checked in this order:
|
|
371
|
+
|
|
372
|
+
1. The signal has aborted, or `canRetry()` returned `false`: it is thrown.
|
|
373
|
+
2. Its `kind` is `"quota"` or `"context_overflow"`: it is thrown. A wait does not mend a daily cap
|
|
374
|
+
or an empty balance, and only a smaller request passes a limit of size, whatever its status
|
|
375
|
+
(OpenAI's request larger than the tokens a minute allows comes as 429). 0.5.0, which had no
|
|
376
|
+
kinds, sent both again when their status was 0, 408, 409, 429 or 500 and more.
|
|
377
|
+
3. The provider said not to send it again: the adapter took note of Claude's
|
|
378
|
+
`x-should-retry: false`. It is thrown, whatever its status. The note is internal: an error of
|
|
379
|
+
your own cannot carry it.
|
|
380
|
+
4. Its `kind` is `"timeout"` and its `status` 0 (the adapter's wait on a silent model ran out): the
|
|
381
|
+
first in the whole run goes on to the checks below, like any status-0 failure; a second one is
|
|
382
|
+
thrown. A 408 follows the rules below.
|
|
383
|
+
5. It has no numeric `status`: see `unknownErrors`.
|
|
384
|
+
6. Its status is one that [`isRetryableStatus`](#isretryablestatusstatus) refuses (400, 401, 403,
|
|
385
|
+
404, 413, 422…): it is thrown.
|
|
386
|
+
7. `retries` retries were made already: it is thrown.
|
|
387
|
+
8. Otherwise `run` is called again after a wait. When the error has a `retryAfterMs` (a finite
|
|
388
|
+
number, 0 or more), the wait is that; when that is longer than `maxDelayMs`, the error is
|
|
389
|
+
thrown at once instead. Without one, the wait is `baseDelayMs × 2^n × (0.5 + random() / 2)`,
|
|
390
|
+
where n is the number of retries made so far, and never more than `maxDelayMs`. With the
|
|
391
|
+
defaults: 250 to 500 ms, then 500 to 1,000 ms, then 1,000 to 2,000 ms.
|
|
392
|
+
|
|
393
|
+
Every retry counts towards `retries`, the one after a silent model and the one of `unknownErrors`
|
|
394
|
+
included, so `retries: 0` turns them all off. The one of `unknownErrors` is still made when the
|
|
395
|
+
other retries have used up `retries`. Each call of `withRetry` has its own count.
|
|
396
|
+
|
|
397
|
+
Returns what `run` resolves to. Throws the last error of `run` as it came, not wrapped; or, when
|
|
398
|
+
the signal aborts during a wait, the signal's reason (with the default `sleep`).
|
|
399
|
+
|
|
400
|
+
```ts
|
|
401
|
+
import { withRetry } from "llm-large-files";
|
|
402
|
+
|
|
403
|
+
// post() is the function of the ModelRequestError sample above.
|
|
404
|
+
const controller = new AbortController();
|
|
405
|
+
const reply = await withRetry(
|
|
406
|
+
() => post(`${process.env.MODEL_URL}/generate`, { prompt: "A title for this chat." }, controller.signal),
|
|
407
|
+
{
|
|
408
|
+
retry: { retries: 2, maxDelayMs: 20_000 },
|
|
409
|
+
signal: controller.signal,
|
|
410
|
+
onRetry: ({ attempt, delayMs }) => console.warn(`Retry ${attempt} in ${Math.round(delayMs)} ms`),
|
|
411
|
+
},
|
|
412
|
+
);
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
How the loop retries and what your users see meanwhile:
|
|
416
|
+
[Errors and reliability](../guides/errors-and-reliability.md).
|
|
417
|
+
|
|
418
|
+
### `RetryOptions`
|
|
419
|
+
|
|
420
|
+
```ts
|
|
421
|
+
type RetryOptions = {
|
|
422
|
+
retries?: number;
|
|
423
|
+
baseDelayMs?: number;
|
|
424
|
+
maxDelayMs?: number;
|
|
425
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
426
|
+
random?: () => number;
|
|
427
|
+
};
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
How a model request that failed is sent again. It is the `retry` option of `askWithFiles`
|
|
431
|
+
([`AskOptions`](./ask.md#askoptions)), of `askGemini` ([gemini.md](./gemini.md)), of
|
|
432
|
+
`files.tools()` ([`ToolOptions`](./library.md#tooloptions)) and of `withRetry`. In `askWithFiles`
|
|
433
|
+
and `askGemini` it applies to the chat requests and to the part reads of a whole-file read; in
|
|
434
|
+
`files.tools()`, to the part reads.
|
|
435
|
+
|
|
436
|
+
| Field | Type | Default | What it does |
|
|
437
|
+
|---|---|---|---|
|
|
438
|
+
| `retries` | `number` | 3 | How many times a failed request is sent again: at most 4 tries with the default, 5 when `unknownErrors: "once"` also retries an error without a status. A value that is not a finite number (`NaN`, `Infinity`, `-Infinity`, a string) counts as not set: 3. Any other number is cut to a whole number; 0 or less turns retries off. |
|
|
439
|
+
| `baseDelayMs` | `number` | 500 | The first wait, in milliseconds, before the jitter. Each later wait is twice as long. A value that is not a finite number (`NaN`, `Infinity`, `-Infinity`, a string) counts as not set: 500; any other negative number counts as 0. |
|
|
440
|
+
| `maxDelayMs` | `number` | 60,000 | The longest wait, in milliseconds. A computed wait is cut to it. When the provider asks for a longer one (`retryAfterMs`), the request is not sent again and the error is thrown at once. A value that is not a finite number (`NaN`, `Infinity`, `-Infinity`, a string) counts as not set: 60,000; any other negative number counts as 0. To allow longer waits, give a larger finite number, not `Infinity`. |
|
|
441
|
+
| `sleep` | `(ms, signal?) => Promise<void>` | a timer that ends early, with the signal's reason, when the signal aborts | For tests: the wait itself. It gets the `signal` of `withRetry`. |
|
|
442
|
+
| `random` | `() => number` | `Math.random` | For tests: the source of the jitter, a number from 0 up to 1. The wait is multiplied by `0.5 + random() / 2`: `() => 0` gives the shortest waits, `() => 1` the longest. |
|
|
443
|
+
|
|
444
|
+
```ts
|
|
445
|
+
import { ModelRequestError, withRetry, type RetryOptions } from "llm-large-files";
|
|
446
|
+
|
|
447
|
+
// In a test: record the waits instead of waiting, and take the shortest ones.
|
|
448
|
+
const waits: number[] = [];
|
|
449
|
+
const retry: RetryOptions = { random: () => 0, sleep: async (ms) => { waits.push(ms); } };
|
|
450
|
+
|
|
451
|
+
let tries = 0;
|
|
452
|
+
const value = await withRetry(async () => {
|
|
453
|
+
if (++tries < 3) throw new ModelRequestError("The model is overloaded.", 503);
|
|
454
|
+
return "done";
|
|
455
|
+
}, { retry });
|
|
456
|
+
console.log(value, tries, waits); // "done" 3 [250, 500]
|
|
457
|
+
```
|
|
458
|
+
|
|
459
|
+
Testing an integration without a real model: [Testing](../guides/testing.md).
|
|
460
|
+
|
|
461
|
+
### `RetryNotice`
|
|
462
|
+
|
|
463
|
+
```ts
|
|
464
|
+
type RetryNotice = {
|
|
465
|
+
error: unknown;
|
|
466
|
+
attempt: number;
|
|
467
|
+
delayMs: number;
|
|
468
|
+
};
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
What [`withRetry`](#withretryrun-options) passes to its `onRetry` option before each wait. The retry
|
|
472
|
+
of an error without a status has no wait, and no notice. The type is exported so that you can write
|
|
473
|
+
the handler apart from the call.
|
|
474
|
+
|
|
475
|
+
| Field | Type | What it holds |
|
|
476
|
+
|---|---|---|
|
|
477
|
+
| `error` | `unknown` | The error of the attempt that failed, as `run` threw it. |
|
|
478
|
+
| `attempt` | `number` | The number of the retry to come, 1 for the first. It counts every retry made so far, the one of `unknownErrors: "once"` included, which has no notice. |
|
|
479
|
+
| `delayMs` | `number` | How long it waits, in milliseconds, before it sends the request again: the error's `retryAfterMs`, or the computed wait (see [`withRetry`](#withretryrun-options)). |
|
|
480
|
+
|
|
481
|
+
```ts
|
|
482
|
+
import { withRetry, type RetryNotice } from "llm-large-files";
|
|
483
|
+
|
|
484
|
+
// One handler for the retries of every request of your own.
|
|
485
|
+
const logRetry = ({ attempt, delayMs, error }: RetryNotice): void => {
|
|
486
|
+
console.warn(`Retry ${attempt} in ${Math.round(delayMs)} ms:`, error);
|
|
487
|
+
};
|
|
488
|
+
|
|
489
|
+
// post() is the function of the ModelRequestError sample above.
|
|
490
|
+
const title = await withRetry(
|
|
491
|
+
() => post(`${process.env.MODEL_URL}/generate`, { prompt: "A title for this chat." }),
|
|
492
|
+
{ onRetry: logRetry },
|
|
493
|
+
);
|
|
494
|
+
```
|
|
495
|
+
|
|
496
|
+
### Retries in events
|
|
497
|
+
|
|
498
|
+
New in 0.7.0. With `onEvent` (or [`askStream`](./ask.md#askstreamoptions)), each retry of a question
|
|
499
|
+
is a `retry` event, between the `request.start` and the `request.end` of its request:
|
|
500
|
+
|
|
501
|
+
```ts
|
|
502
|
+
{ type: "retry", requestId: "req_3", attempt: 1, delayMs: 2000,
|
|
503
|
+
error: { message: "The model failed on its side (HTTP 503).", kind: "server", status: 503, name: "GeminiRequestError" },
|
|
504
|
+
message: "The model did not answer (HTTP 503). Trying again in 2 s…", seq: 9, runId: "run_…", time: 1795000000000 }
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
- **Structured, and safe to show.** `attempt` and `delayMs` are those of the
|
|
508
|
+
[`RetryNotice`](#retrynotice). `error` is an [`EventError`](#errors-in-events-eventerror): told by
|
|
509
|
+
its kind and status, never in the provider's words. `message` is the line `onActivity` gets.
|
|
510
|
+
- **The retries of whole-file reads are visible.** The requests of `analyze_whole_document` are
|
|
511
|
+
`request.start` events with `role: "reader"` and the `callId` of their call, and their retries
|
|
512
|
+
are `retry` events. Earlier versions, and `onActivity` still, did not tell them.
|
|
513
|
+
- **A reply that fails after its first text is not sent again.** With `streamText` (on by default
|
|
514
|
+
with `onText`, and in `askStream`), the text comes as it is written, and once some of it was
|
|
515
|
+
shown the request is not retried: its `request.end` has outcome `"error"`, and the question
|
|
516
|
+
throws. With `streamText: false`, a reply's text comes once the reply is in, so a reply that
|
|
517
|
+
fails on its way is sent again by the rule above, at the cost of a longer wait for the first
|
|
518
|
+
word; the whole reply must then arrive within the adapter's `firstByteTimeoutMs`. A listener of
|
|
519
|
+
the events alone does not ask for streaming.
|
|
520
|
+
- **The end tells the outcome.** `request.end` comes once for each request, after its retries,
|
|
521
|
+
with `ms` from its start, waits included. An overflow made smaller is a new request: the first
|
|
522
|
+
ends with an `EventError` of kind `"context_overflow"`.
|
|
523
|
+
|
|
524
|
+
### isRetryableStatus(status)
|
|
525
|
+
|
|
526
|
+
```ts
|
|
527
|
+
declare function isRetryableStatus(status: number): boolean;
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
Whether a request that failed with this status is worth sending again: `true` for 0 (no answer),
|
|
531
|
+
408, 409, 429 and every status from 500 up; `false` for every other, such as 400, 401, 403, 404,
|
|
532
|
+
413 and 422, which the provider would refuse again. Throws nothing. `withRetry` uses it after the
|
|
533
|
+
checks of `kind` (a `"quota"` or `"context_overflow"` error with status 429 is not sent again).
|
|
534
|
+
|
|
535
|
+
```ts
|
|
536
|
+
import { isRetryableStatus } from "llm-large-files";
|
|
537
|
+
|
|
538
|
+
isRetryableStatus(529); // true: Claude's "overloaded"
|
|
539
|
+
isRetryableStatus(400); // false
|
|
540
|
+
```
|
|
541
|
+
|
|
542
|
+
### retryAfterMs(headers, body, now)
|
|
543
|
+
|
|
544
|
+
```ts
|
|
545
|
+
declare function retryAfterMs(headers: Headers | undefined, body?: unknown, now?: () => number): number | undefined;
|
|
546
|
+
```
|
|
547
|
+
|
|
548
|
+
The wait a provider asked for, in milliseconds. It looks in three places and takes the first that
|
|
549
|
+
gives one:
|
|
550
|
+
|
|
551
|
+
1. The `retry-after-ms` header: a number, 0 or more, taken as it is.
|
|
552
|
+
2. The `Retry-After` header: a number of seconds, 0 or more (decimals are rounded to the
|
|
553
|
+
millisecond), or an HTTP date: the time from `now()` until then, 0 when it has passed.
|
|
554
|
+
3. In the body, `error.details`: the first entry with a `retryDelay` written in seconds, such as
|
|
555
|
+
`"17s"` or `"34.5s"`. That is Gemini's `google.rpc.RetryInfo`.
|
|
556
|
+
|
|
557
|
+
A header that is neither is passed over, and the next place is tried. In Node, a negative
|
|
558
|
+
`Retry-After` number reads as a past date and gives 0. Header names do not depend on case.
|
|
559
|
+
|
|
560
|
+
| Parameter | Type | Default | What it is |
|
|
561
|
+
|---|---|---|---|
|
|
562
|
+
| `headers` | `Headers \| undefined` | required | The headers of the response. `undefined` reads the body only. |
|
|
563
|
+
| `body` | `unknown` | none | The error body, parsed from JSON. |
|
|
564
|
+
| `now` | `() => number` | `Date.now` | The time now, in milliseconds, for a `Retry-After` date. For tests. |
|
|
565
|
+
|
|
566
|
+
Returns the wait, or `undefined` when none was asked for. Throws nothing.
|
|
567
|
+
|
|
568
|
+
```ts
|
|
569
|
+
import { retryAfterMs } from "llm-large-files";
|
|
570
|
+
|
|
571
|
+
retryAfterMs(new Headers({ "retry-after": "17" })); // 17000
|
|
572
|
+
retryAfterMs(new Headers({ "retry-after-ms": "250", "retry-after": "17" })); // 250
|
|
573
|
+
retryAfterMs(undefined, {
|
|
574
|
+
error: { details: [{ "@type": "type.googleapis.com/google.rpc.RetryInfo", retryDelay: "34.5s" }] },
|
|
575
|
+
}); // 34500
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
## Waits on a reply
|
|
579
|
+
|
|
580
|
+
### `DEFAULT_FIRST_BYTE_TIMEOUT_MS`
|
|
581
|
+
|
|
582
|
+
```ts
|
|
583
|
+
const DEFAULT_FIRST_BYTE_TIMEOUT_MS = 600_000; // 10 minutes
|
|
584
|
+
```
|
|
585
|
+
|
|
586
|
+
The default `firstByteTimeoutMs` of the adapters: the longest wait for the first piece of a reply.
|
|
587
|
+
Headers do not count, since some servers send them at once. It is long because a model that thinks
|
|
588
|
+
sends nothing while it does (Gemini without its thoughts, OpenAI's reasoning models), and a reply
|
|
589
|
+
that is not streamed comes whole at the end. New in 0.6.0.
|
|
590
|
+
|
|
591
|
+
### `DEFAULT_IDLE_TIMEOUT_MS`
|
|
592
|
+
|
|
593
|
+
```ts
|
|
594
|
+
const DEFAULT_IDLE_TIMEOUT_MS = 300_000; // 5 minutes
|
|
595
|
+
```
|
|
596
|
+
|
|
597
|
+
The default `idleTimeoutMs` of the adapters: the longest wait between two pieces of a reply once
|
|
598
|
+
it has started to arrive. An event of a stream, a keep-alive and a piece of a body all count. A
|
|
599
|
+
model that is writing sends something well within it. New in 0.6.0.
|
|
600
|
+
|
|
601
|
+
### `IdleWaits`
|
|
602
|
+
|
|
603
|
+
```ts
|
|
604
|
+
type IdleWaits = {
|
|
605
|
+
firstByteTimeoutMs?: number | undefined;
|
|
606
|
+
idleTimeoutMs?: number | undefined;
|
|
607
|
+
};
|
|
608
|
+
```
|
|
609
|
+
|
|
610
|
+
How long an adapter waits on a chat request that sends nothing. `gemini()`, `askGemini`,
|
|
611
|
+
`openAiCompatible()` and `anthropic()` take these two options under the same names (see
|
|
612
|
+
[gemini.md](./gemini.md), [openai.md](./openai.md), [anthropic.md](./anthropic.md)). The type is
|
|
613
|
+
exported so that you can keep the pair in one setting; the watch itself is internal. New in 0.6.0.
|
|
614
|
+
|
|
615
|
+
| Field | Type | Default | What it does |
|
|
616
|
+
|---|---|---|---|
|
|
617
|
+
| `firstByteTimeoutMs` | `number` | 600,000 ([`DEFAULT_FIRST_BYTE_TIMEOUT_MS`](#default_first_byte_timeout_ms)) | The longest wait, in milliseconds, from the start of a chat request to the first piece of its reply. Headers do not count. |
|
|
618
|
+
| `idleTimeoutMs` | `number` | 300,000 ([`DEFAULT_IDLE_TIMEOUT_MS`](#default_idle_timeout_ms)) | The longest wait, in milliseconds, between two pieces of the reply once it has started. Keep-alives count. |
|
|
619
|
+
|
|
620
|
+
- `undefined` takes the default. 0, or any value that is not a positive finite number, waits
|
|
621
|
+
without end; each of the two can be turned off alone.
|
|
622
|
+
- When a wait runs out, the adapter aborts the request and throws its error with `status` 0 and
|
|
623
|
+
`kind` `"timeout"`: "Gemini sent nothing for 600 s.", "The model sent nothing for 600 s."
|
|
624
|
+
(OpenAI-compatible) or "Claude sent nothing for 600 s.". The loop sends it again once, by the
|
|
625
|
+
rule of [`withRetry`](#withretryrun-options), unless text of it was already shown. The error
|
|
626
|
+
comes when the wait runs out, also with a `fetch` whose body never settles its `cancel()`.
|
|
627
|
+
- The waits are new in 0.6.0: 0.5.0 waited on a silent model without end.
|
|
628
|
+
- A reply that keeps arriving has no time limit.
|
|
629
|
+
- The waits watch the chat requests (`send`). The part reads of a whole-file read have a time
|
|
630
|
+
limit of their own: see the adapter's page.
|
|
631
|
+
|
|
632
|
+
```ts
|
|
633
|
+
import { GoogleAuth } from "google-auth-library";
|
|
634
|
+
import type { IdleWaits } from "llm-large-files";
|
|
635
|
+
import { anthropic } from "llm-large-files/anthropic";
|
|
636
|
+
import { gemini, vertexAi } from "llm-large-files/gemini";
|
|
637
|
+
|
|
638
|
+
// One setting for every adapter of the app: give up sooner than the defaults.
|
|
639
|
+
const waits: IdleWaits = { firstByteTimeoutMs: 120_000, idleTimeoutMs: 60_000 };
|
|
640
|
+
|
|
641
|
+
const auth = new GoogleAuth({ scopes: "https://www.googleapis.com/auth/cloud-platform" });
|
|
642
|
+
const model = gemini(vertexAi({
|
|
643
|
+
project: process.env.GOOGLE_CLOUD_PROJECT!,
|
|
644
|
+
model: "gemini-3.8-flash",
|
|
645
|
+
accessToken: async () => (await auth.getAccessToken())!,
|
|
646
|
+
}), waits);
|
|
647
|
+
const claude = anthropic({ apiKey: process.env.ANTHROPIC_API_KEY!, model: "claude-opus-5-5", ...waits });
|
|
648
|
+
```
|
|
649
|
+
|
|
650
|
+
Choosing the waits, and proxies that cut a quiet stream sooner:
|
|
651
|
+
[Errors and reliability](../guides/errors-and-reliability.md) and
|
|
652
|
+
[Deployment](../guides/deployment.md).
|
|
653
|
+
|
|
654
|
+
## Streams
|
|
655
|
+
|
|
656
|
+
### parseSseJson(stream, hooks)
|
|
657
|
+
|
|
658
|
+
```ts
|
|
659
|
+
declare function parseSseJson<T>(
|
|
660
|
+
stream: ReadableStream<Uint8Array> | AsyncIterable<Uint8Array | string>,
|
|
661
|
+
hooks?: SseHooks,
|
|
662
|
+
): AsyncGenerator<T>;
|
|
663
|
+
```
|
|
664
|
+
|
|
665
|
+
Parses a `text/event-stream` body into one JSON value for each event. The body is a web stream
|
|
666
|
+
(`response.body` of the global `fetch`) or any async iterable of bytes or strings (a Node stream,
|
|
667
|
+
from node-fetch and the like). The adapters read their streams with it, and
|
|
668
|
+
`llm-large-files/gemini` exports the same function.
|
|
669
|
+
|
|
670
|
+
- An event ends at a blank line. Lines may end with LF, CRLF or a CR alone (a CR alone since
|
|
671
|
+
0.6.0). The bytes are decoded as UTF-8 across pieces, so an event, a line ending or a character
|
|
672
|
+
cut between two reads is put together. Each piece is read once, however long the event it belongs
|
|
673
|
+
to: one event of 8 MB in pieces of 16 KB, in memory, took 0.97 to 1.19 s in 0.5.0, and takes 10
|
|
674
|
+
to 20 ms in 0.6.0, on Node 24 on Windows ([Measurements](../measurements.md#the-server)). On a
|
|
675
|
+
machine busy with other Node processes, the same function at 5157e7f (main before the last changes
|
|
676
|
+
of 0.6.0), which reads a stream as 0.5.0 does, took 1.1 to 3.6 s, and 0.6.0 takes 11 to 46 ms.
|
|
677
|
+
- Only `data:` lines count: the text after `data:`, without its leading white space. The `data:` lines
|
|
678
|
+
of one event are joined with a newline. Comments (`: …`), `event:`, `id:` and `retry:` lines are
|
|
679
|
+
passed over.
|
|
680
|
+
- An event without data gives nothing. `data: [DONE]` gives nothing and calls `onDone`.
|
|
681
|
+
- A last event that no blank line follows is read when the stream ends.
|
|
682
|
+
- The data of each event goes through `JSON.parse` and is yielded as `T`, unchecked.
|
|
683
|
+
- One event may hold at most `hooks.maxEventLength` characters, 64,000,000 by default (new in
|
|
684
|
+
0.6.0). A longer one ends the stream with an error, whether it comes whole or in pieces: a server
|
|
685
|
+
that never ends an event holds at most that many characters of your server's memory for each
|
|
686
|
+
stream it sends. The limit is not on all streams together.
|
|
687
|
+
|
|
688
|
+
Throws a `SyntaxError` for an event whose data is not JSON (it is not passed over), the signal's
|
|
689
|
+
reason when `hooks.signal` aborts, and any error of the stream itself. For an event past
|
|
690
|
+
`maxEventLength` it throws an `SseEventTooLongError` (exported from `llm-large-files` and
|
|
691
|
+
`llm-large-files/gemini`, new in 0.6.0; its `limit` holds the limit), whose message is
|
|
692
|
+
`An event of the stream held more than 64,000,000 characters.`, the number being the limit in the
|
|
693
|
+
en-US way. The adapters turn it into their own
|
|
694
|
+
error, of kind `"invalid"`, that is not sent again (see their pages). Leaving the loop early
|
|
695
|
+
(`break`, `return`, a throw), or the end of the stream, ends the reading: a web stream's reader is
|
|
696
|
+
cancelled, and an async iterable's `return()` is called. Neither is waited for: a `cancel()` or
|
|
697
|
+
`return()` that never settles, that gives no promise, or that throws neither holds nor fails the
|
|
698
|
+
caller.
|
|
699
|
+
|
|
700
|
+
```ts
|
|
701
|
+
import { parseSseJson } from "llm-large-files";
|
|
702
|
+
|
|
703
|
+
type Chunk = { choices?: Array<{ delta?: { content?: string | null }; finish_reason?: string | null }> };
|
|
704
|
+
|
|
705
|
+
// Give up when nothing arrives for 60 s: each piece of the stream starts the wait again.
|
|
706
|
+
const controller = new AbortController();
|
|
707
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
708
|
+
const arm = () => {
|
|
709
|
+
clearTimeout(timer);
|
|
710
|
+
timer = setTimeout(() => controller.abort(new Error("Nothing arrived for 60 s.")), 60_000);
|
|
711
|
+
};
|
|
712
|
+
arm();
|
|
713
|
+
|
|
714
|
+
let done = false;
|
|
715
|
+
let finished = false;
|
|
716
|
+
try {
|
|
717
|
+
const response = await fetch(`${process.env.LLM_BASE_URL}/chat/completions`, {
|
|
718
|
+
method: "POST",
|
|
719
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.LLM_API_KEY}` },
|
|
720
|
+
body: JSON.stringify({ model: "gpt-5.5", stream: true, messages: [{ role: "user", content: "Say hello." }] }),
|
|
721
|
+
signal: controller.signal,
|
|
722
|
+
});
|
|
723
|
+
if (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);
|
|
724
|
+
|
|
725
|
+
for await (const chunk of parseSseJson<Chunk>(response.body, { onData: arm, onDone: () => { done = true; }, signal: controller.signal })) {
|
|
726
|
+
process.stdout.write(chunk.choices?.[0]?.delta?.content ?? "");
|
|
727
|
+
if (chunk.choices?.[0]?.finish_reason) finished = true;
|
|
728
|
+
}
|
|
729
|
+
} finally {
|
|
730
|
+
clearTimeout(timer);
|
|
731
|
+
}
|
|
732
|
+
// A stream that closes with neither a finish_reason nor [DONE] was cut off on its way.
|
|
733
|
+
if (!done && !finished) throw new Error("The reply ended before it was complete.");
|
|
734
|
+
```
|
|
735
|
+
|
|
736
|
+
A Gemini stream (`streamGenerateContent?alt=sse`) reads the same way; it sends no `[DONE]`.
|
|
737
|
+
Streaming an adapter of your own: [Your own adapter and loop](../guides/own-adapter-and-loop.md).
|
|
738
|
+
|
|
739
|
+
### `SseHooks`
|
|
740
|
+
|
|
741
|
+
```ts
|
|
742
|
+
type SseHooks = {
|
|
743
|
+
onData?: () => void;
|
|
744
|
+
onDone?: () => void;
|
|
745
|
+
signal?: AbortSignal | undefined;
|
|
746
|
+
maxEventLength?: number;
|
|
747
|
+
};
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
What [`parseSseJson`](#parsessejsonstream-hooks) tells you as the stream goes, and the most one
|
|
751
|
+
event may hold. New in 0.6.0: 0.5.0's `parseSseJson` took the stream alone.
|
|
752
|
+
|
|
753
|
+
| Field | Type | Default | What it does |
|
|
754
|
+
|---|---|---|---|
|
|
755
|
+
| `onData` | `() => void` | none | Called for each piece of bytes that arrives, before it is parsed: an event, part of one, or a keep-alive comment. Use it to start a wait on silence again. |
|
|
756
|
+
| `onDone` | `() => void` | none | Called when an event's data is `[DONE]`, which OpenAI-compatible servers send at the end. The OpenAI-compatible adapter takes a stream that closes with neither `[DONE]` nor a `finish_reason` as cut off on its way. |
|
|
757
|
+
| `signal` | `AbortSignal \| undefined` | none | When it aborts, the next piece is not waited for: the generator throws the signal's reason, and the body is ended. |
|
|
758
|
+
| `maxEventLength` | `number` | 64,000,000 | The most characters one event may hold: what its data lines hold after `data:` and the spaces after it, and the line feeds that join them. A line of another field (a comment, `event:`, `id:`) counts in full with the event while it is read, as it is held until its end. A longer event ends the stream with an error named `SseEventTooLongError`, however the stream is cut into pieces. `Infinity` sets no limit; a value that is not a positive number counts as not set. New in 0.6.0. |
|