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,735 @@
|
|
|
1
|
+
# Errors and reliability
|
|
2
|
+
|
|
3
|
+
This guide is for anyone who calls `askWithFiles` or `askGemini` from a server. It says what the
|
|
4
|
+
library does on its own when a model request fails, what reaches your code when that is not
|
|
5
|
+
enough, and how to turn each error into a message for your user and an HTTP status. The exact
|
|
6
|
+
signatures are in [the reference for errors and retries](../reference/errors-and-retries.md).
|
|
7
|
+
|
|
8
|
+
The samples assume what a question needs: `files` from `createLargeFiles`, `endpoint` from
|
|
9
|
+
`vertexAi()` (see [Getting started](../getting-started.md) and
|
|
10
|
+
[Gemini and Vertex AI](./vertex-and-gemini.md)), and the question's `documentIds`, `messages` and
|
|
11
|
+
`owner`.
|
|
12
|
+
|
|
13
|
+
## What the library does for you
|
|
14
|
+
|
|
15
|
+
A question makes many model requests. Most failures are handled inside it, and your code never
|
|
16
|
+
sees them:
|
|
17
|
+
|
|
18
|
+
- A request that failed in a way another try can mend (no answer, HTTP 408, 409, 429 or 5xx) is
|
|
19
|
+
sent again, up to 3 more times, after a wait that doubles or the wait the provider asked for. See
|
|
20
|
+
[Retries](#retries).
|
|
21
|
+
- A request that gets nothing from the model for 10 minutes before its reply, or for 5 minutes in
|
|
22
|
+
the middle of it, is aborted and sent again, once. See
|
|
23
|
+
[Waits on a silent model](#waits-on-a-silent-model).
|
|
24
|
+
- A request larger than the model takes, or than the tokens the provider allows in a minute, is
|
|
25
|
+
made smaller and sent again, or the documents are planned again for a smaller request. See
|
|
26
|
+
[A request too large for the model](#a-request-too-large-for-the-model).
|
|
27
|
+
- A first reply with nothing in it, a tool call that cannot be read, and an answer that comes back
|
|
28
|
+
without text are asked for once more. See [Empty or broken turns](#empty-or-broken-turns).
|
|
29
|
+
- A streamed reply that stops before its end is sent again, when none of it was shown. See
|
|
30
|
+
[A stream cut off](#a-stream-cut-off).
|
|
31
|
+
- A tool that fails (a pattern that does not compile, a store that did not answer, a whole-file
|
|
32
|
+
read whose parts all failed) returns its error to the model, which tries another way. Nothing is
|
|
33
|
+
thrown. See [Failures inside tools](#failures-inside-tools).
|
|
34
|
+
|
|
35
|
+
What is left for you: catch what the question throws, show your own words for it, keep what a
|
|
36
|
+
failed question found, check `answered`, and set an overall deadline.
|
|
37
|
+
|
|
38
|
+
## What a question can throw
|
|
39
|
+
|
|
40
|
+
`askWithFiles` and `askGemini` throw the same errors:
|
|
41
|
+
|
|
42
|
+
| Error | When | Fields to use | `partialResultOf` |
|
|
43
|
+
|---|---|---|---|
|
|
44
|
+
| `DocumentsNotFoundError` | A document ID was never uploaded, has expired, was deleted, or belongs to another `owner`. Thrown before any model request. | `ids`: the IDs that are missing. | No |
|
|
45
|
+
| `DocumentStoreError` | The store could not be read while the question planned its documents: a volume that did not answer, a database that is down. The documents are not gone, and the same question may work a moment later. | `code` (`EIO`, `EMFILE`) and `syscall` when a system error is behind it; `cause`, the error that was caught. | No |
|
|
46
|
+
| `ModelRequestError`: a `GeminiRequestError`, `OpenAiRequestError` or `AnthropicRequestError` | A model request failed in a way that was not worth sending again, or still failed after the retries. A reply of HTTP 200 whose body is not JSON (a gateway's page in the model's place) is one too, of kind `invalid`, with status 200 and the `SyntaxError` as `cause`; it is not sent again. A reply of HTTP 200 whose body is empty is of kind `unreachable`, status 0, and is sent again first. | `kind`, `status` (0 when no answer came, or the reply stopped on its way), `retryAfterMs`, `limitTokens`, `requestedTokens`, `cause`. `OpenAiRequestError` adds `param` and `code`; `AnthropicRequestError` adds `type`. | Yes |
|
|
47
|
+
| The reason of your `signal` | You stopped the question, or your deadline ran out. See [An overall deadline](#an-overall-deadline). | Test your signals, not the error. | Yes, for a reason that is an object |
|
|
48
|
+
| `Error` | A mistake in the call: "The last message must be the user's.", or a budget that cannot work, such as "budget.reservedTokens (…) must be smaller than budget.contextTokens (…): nothing would be left for the conversation." | `message`, for your log. | No |
|
|
49
|
+
|
|
50
|
+
Until 0.6.0, a reply of HTTP 200 that was not JSON threw a `SyntaxError`, with no `status` (a
|
|
51
|
+
streamed Gemini request got an empty reply instead). Now the `SyntaxError` is the `cause` of the
|
|
52
|
+
`ModelRequestError`: where you tested
|
|
53
|
+
`error instanceof SyntaxError`, test `error.cause instanceof SyntaxError`. Kind `invalid` alone
|
|
54
|
+
also covers every other request that the provider refused.
|
|
55
|
+
|
|
56
|
+
Whose words each message is:
|
|
57
|
+
|
|
58
|
+
- `DocumentsNotFoundError`: "A document is no longer available: doc_…. Upload it again." It names
|
|
59
|
+
document IDs. Your user knows the files by name, so map the IDs to the names you keep with the
|
|
60
|
+
chat.
|
|
61
|
+
- `DocumentStoreError`: "The document store could not be read (EIO). Try again." It is written to
|
|
62
|
+
be shown: it names no path and no host. Log its `cause` on the server.
|
|
63
|
+
- `ModelRequestError`: the provider's own message, or, when it gave none, the adapter's: "Gemini
|
|
64
|
+
returned HTTP 503.", "The model returned HTTP 503." (OpenAI-compatible, and Gemini's part reads)
|
|
65
|
+
or "Claude returned HTTP 503.". It can name your project, model, region or quota. Log it, and
|
|
66
|
+
show your own words, chosen by its [`kind`](#the-kind-of-a-model-error). The adapters' own
|
|
67
|
+
messages, with "Gemini's", "The model's" or "Claude's" first:
|
|
68
|
+
- a reply of HTTP 200 that is not JSON: "Gemini's reply could not be read: it was not JSON
|
|
69
|
+
(text/html). A proxy or gateway may have answered in its place." The part in parentheses is the
|
|
70
|
+
content type of the reply, and is left out when it has none;
|
|
71
|
+
- a reply of HTTP 200 that is empty: "Gemini could not be reached (the reply was empty).", "The
|
|
72
|
+
model could not be reached (the reply was empty)." or "Claude could not be reached (the reply
|
|
73
|
+
was empty).";
|
|
74
|
+
- a streamed event longer than 64,000,000 characters: "Gemini's reply could not be read: an event
|
|
75
|
+
of its stream held more than 64,000,000 characters."
|
|
76
|
+
|
|
77
|
+
### Telling them apart
|
|
78
|
+
|
|
79
|
+
Use `instanceof` for the classes, and `errorKindOf(error)` for the kind. `errorKindOf` reads the
|
|
80
|
+
`kind` field of any error that has one, so it also works when two copies of the package are
|
|
81
|
+
installed side by side, where `instanceof` fails. The four model error classes are all
|
|
82
|
+
`ModelRequestError`.
|
|
83
|
+
|
|
84
|
+
| Export | Entry point |
|
|
85
|
+
|---|---|
|
|
86
|
+
| `ModelRequestError`, `errorKindOf`, `classifyModelError`, `DocumentsNotFoundError`, `DocumentStoreError`, `partialResultOf` | `llm-large-files` |
|
|
87
|
+
| `GeminiRequestError`, and `DocumentsNotFoundError` and `partialResultOf` again | `llm-large-files/gemini` |
|
|
88
|
+
| `OpenAiRequestError` | `llm-large-files/openai` |
|
|
89
|
+
| `AnthropicRequestError` | `llm-large-files/anthropic` |
|
|
90
|
+
|
|
91
|
+
## The kind of a model error
|
|
92
|
+
|
|
93
|
+
`kind` is told from the HTTP status, the provider's message, and the provider's own word for the
|
|
94
|
+
error (Gemini's `error.status` and `details`, OpenAI's `error.code`, Claude's `error.type`):
|
|
95
|
+
|
|
96
|
+
| `kind` | Cause | Sent again | What to tell the user |
|
|
97
|
+
|---|---|---|---|
|
|
98
|
+
| `context_overflow` | The request was larger than the model takes: its context window, or the size of the body (HTTP 413). Or larger than the tokens the provider lets through in a minute, which only a smaller request can pass: OpenAI's "Request too large for gpt-4o … on tokens per min (TPM): Limit 30000, Requested 45237" (HTTP 429), and Groq's "… on tokens per minute (TPM): Limit 6000, Requested 6438" (HTTP 413 or 429). `limitTokens` and `requestedTokens` are the provider's numbers, when its message gives them. | Never by the retry rule, whatever its status. The loop makes the request smaller, at most twice, or plans the documents again, once. It throws when neither helps. | "This chat is too long for the model. Start a new chat, or ask about fewer files." |
|
|
99
|
+
| `quota` | A quota that does not come back soon: OpenAI's `insufficient_quota`; HTTP 402 (DeepSeek's "Insufficient Balance", OpenRouter's "Insufficient credits"); Claude's "Your credit balance is too low" and its spending limits ("You have reached your API usage limits", or HTTP 429 with `enforced_spend_limit_reached`); a Gemini quota per day (HTTP 429 with a `QuotaFailure` whose quota is per day, or a Vertex AI quota per day that only the message names). | Never. | "The assistant is not available right now." Alert whoever runs the account. |
|
|
100
|
+
| `rate_limit` | Too many requests or tokens for now: any other HTTP 429, a Gemini quota per minute among them. | 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`. | "The assistant is busy. Try again in a minute." Use `retryAfterMs` when it is set. |
|
|
101
|
+
| `timeout` | Status 0: nothing came from the model for the adapter's wait (`firstByteTimeoutMs`, `idleTimeoutMs`). Or HTTP 408 from the provider or a gateway. | The adapter's wait: once. HTTP 408: up to `retries` times. | "The model took too long to answer. Try again." |
|
|
102
|
+
| `unreachable` | Status 0: the connection failed, before or during the reply, a stream ended before its end, or a reply of HTTP 200 came empty. | Up to `retries` times. | "The model could not be reached. Try again." |
|
|
103
|
+
| `server` | HTTP 5xx: the provider failed on its side. Claude's 529 (overloaded) and DeepSeek's `insufficient_system_resource` (taken as 503) are among them. | Up to `retries` times. | "The model could not answer just now. Try again." |
|
|
104
|
+
| `auth` | HTTP 401 or 403, or a Gemini API key that is not valid (`API_KEY_INVALID`, which comes as HTTP 400). | Never. | A general error. It is your configuration: an expired token, a wrong key, a missing role. Log it. |
|
|
105
|
+
| `invalid` | Any other HTTP 4xx, or an error a Gemini reply reported after HTTP 200 without a status of its own (see [A stream cut off](#a-stream-cut-off)): the provider refused the request as it was. Also a reply of HTTP 200 that is not JSON (a gateway's page), and a streamed event longer than 64,000,000 characters, both with status 200. | Never, except HTTP 409, which is sent again like a 5xx. | A general error. Log it, with the model and its options. |
|
|
106
|
+
|
|
107
|
+
Nothing is sent again once text of the reply was shown to the user, or after your `signal`
|
|
108
|
+
aborted.
|
|
109
|
+
|
|
110
|
+
The kind depends on the provider's wording. The wording of Gemini, Vertex AI, OpenAI, Claude, vLLM,
|
|
111
|
+
Mistral and llama.cpp for a request too large is known, and so is that of Text Generation Inference
|
|
112
|
+
and Together ("`inputs` tokens + `max_new_tokens` must be <= 32769. Given: 40000 …"), LM Studio
|
|
113
|
+
("loaded with context length of only 4096 tokens"), Amazon Bedrock ("Input is too long for
|
|
114
|
+
requested model.") and vLLM's newer "your request has 40000 input tokens". An OpenAI-compatible
|
|
115
|
+
server's message is read from `error`, from a `message` at the top of the body (vLLM before its
|
|
116
|
+
OpenAI-shaped errors, SGLang, FastChat) or from FastAPI's `detail`. Throttling that shares words
|
|
117
|
+
with a request too large ("tokens per minute") is not taken for one, except the TPM refusal of a
|
|
118
|
+
single request larger than the minute's allowance. A message the classifier does not know is
|
|
119
|
+
`invalid`, and the loop does not recover from it.
|
|
120
|
+
`classifyModelError(status, message, { code, details })` shows how a message is read. An adapter
|
|
121
|
+
of your own, or a wrapper around a gateway, can set the kind itself:
|
|
122
|
+
`new ModelRequestError(message, 400, { kind: "context_overflow" })`. See
|
|
123
|
+
[Your own adapter and loop](./own-adapter-and-loop.md).
|
|
124
|
+
|
|
125
|
+
## Retries
|
|
126
|
+
|
|
127
|
+
Every model request of a question, the chat's and the part reads of a whole-file read, is sent
|
|
128
|
+
again by one rule (`withRetry`), each request on its own count:
|
|
129
|
+
|
|
130
|
+
- **What is sent again**: an error with status 0 (no answer), 408, 409, 429 or 5xx
|
|
131
|
+
(`isRetryableStatus`).
|
|
132
|
+
- **How often**: up to `retries` more times (3). A wait on a silent model that ran out (status 0,
|
|
133
|
+
kind `timeout`) is sent again only once: another such wait is long, and a model that went silent
|
|
134
|
+
twice will most likely do so again.
|
|
135
|
+
- **How long it waits**: `baseDelayMs` (500), twice as long for each earlier try, with jitter: 0.25
|
|
136
|
+
to 0.5 s, then 0.5 to 1 s, then 1 to 2 s, and never more than `maxDelayMs` (60 s). When the
|
|
137
|
+
provider asks for a wait (a `Retry-After` header in seconds or as a date, `retry-after-ms`, or the
|
|
138
|
+
`retryDelay` of Gemini's `RetryInfo`, such as "17s"), that wait is used instead. When it asks for
|
|
139
|
+
more than `maxDelayMs`, the request is not sent again: the error is thrown, with `retryAfterMs`
|
|
140
|
+
set.
|
|
141
|
+
- **What is not sent again**: a `quota` error; a `context_overflow` error, whatever its status (a
|
|
142
|
+
TPM refusal comes as HTTP 429: only a smaller request can pass); an error the provider said not
|
|
143
|
+
to send again (Claude's `x-should-retry: false` header), whatever its status; any other status
|
|
144
|
+
(400, 401, 403, 404, 413…), among them a reply of HTTP 200 that is not JSON and a streamed event
|
|
145
|
+
too long to read (kind `invalid`, status 200); a chat request whose error has no status; a
|
|
146
|
+
request once text of it was shown to the user; anything after your `signal` aborted.
|
|
147
|
+
- **Part reads** of a whole-file read also try once more, at once, an error that has no status,
|
|
148
|
+
their own time limit among them. A part that still fails is reported to the model as a part that
|
|
149
|
+
could not be read, and the question goes on.
|
|
150
|
+
|
|
151
|
+
While a chat request waits to be sent again, `onActivity` gets a line such as "The model did not
|
|
152
|
+
answer (HTTP 429). Trying again in 17 s…", "The model could not be reached. Trying again…" (no
|
|
153
|
+
reply began), "The model's reply was cut off on its way. Trying again…" (a stream that closed
|
|
154
|
+
before its end, a connection that broke once the reply had begun, or a reply of HTTP 200 that came
|
|
155
|
+
empty) or "The model sent nothing for too long. Trying again…". Show it as a passing status.
|
|
156
|
+
|
|
157
|
+
Set the rule with `retry`, an option of `askWithFiles` and `askGemini` that also applies to part
|
|
158
|
+
reads: `retries` (3; 0 turns retries off, the one after a silent model too), `baseDelayMs` (500)
|
|
159
|
+
and `maxDelayMs` (60,000). Every field:
|
|
160
|
+
[`RetryOptions`](../reference/errors-and-retries.md#retryoptions).
|
|
161
|
+
|
|
162
|
+
```ts
|
|
163
|
+
import { askGemini } from "llm-large-files/gemini";
|
|
164
|
+
|
|
165
|
+
const result = await askGemini({
|
|
166
|
+
files,
|
|
167
|
+
endpoint,
|
|
168
|
+
documentIds,
|
|
169
|
+
messages,
|
|
170
|
+
owner,
|
|
171
|
+
// A user is waiting: two more tries at most, and no wait longer than 20 s.
|
|
172
|
+
retry: { retries: 2, maxDelayMs: 20_000 },
|
|
173
|
+
});
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Your own calls with `withRetry`
|
|
177
|
+
|
|
178
|
+
Your app may make model requests of its own next to a question: a title for the chat, a summary for
|
|
179
|
+
a notification. `withRetry` sends them again by the same rule. It reads three fields of what your
|
|
180
|
+
call throws: `status`, a number (0 for no answer); `kind` (`"quota"` and `"context_overflow"` are
|
|
181
|
+
never sent again, `"timeout"` with status 0 only once); and `retryAfterMs`. Throw a
|
|
182
|
+
`ModelRequestError` and the error gets its `kind` from the status and the message. Pass the
|
|
183
|
+
service's error code as `code` (or set `kind: "quota"` yourself) so a quota is not sent again: a
|
|
184
|
+
quota is told from `code: "insufficient_quota"`, Gemini's `details`, HTTP 402, or words that only
|
|
185
|
+
a quota uses (no credit left, a spending cap, a quota per day). An HTTP 429 without them is a
|
|
186
|
+
`rate_limit`, which is sent again.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import { ModelRequestError, retryAfterMs, withRetry } from "llm-large-files";
|
|
190
|
+
|
|
191
|
+
/** A title for the chat, from a model service of your own. */
|
|
192
|
+
export async function chatTitle(question: string, signal?: AbortSignal): Promise<string> {
|
|
193
|
+
return withRetry(async () => {
|
|
194
|
+
let response: Response;
|
|
195
|
+
try {
|
|
196
|
+
response = await fetch(process.env.TITLE_SERVICE_URL ?? "", {
|
|
197
|
+
method: "POST",
|
|
198
|
+
headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.TITLE_SERVICE_KEY}` },
|
|
199
|
+
body: JSON.stringify({ text: question, maxWords: 6 }),
|
|
200
|
+
...(signal ? { signal } : {}),
|
|
201
|
+
});
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (signal?.aborted) throw error;
|
|
204
|
+
// No answer at all: status 0, which is sent again.
|
|
205
|
+
throw new ModelRequestError("The title service could not be reached.", 0, { cause: error });
|
|
206
|
+
}
|
|
207
|
+
const body: unknown = await response.json().catch(() => null);
|
|
208
|
+
if (!response.ok) {
|
|
209
|
+
const wait = retryAfterMs(response.headers, body);
|
|
210
|
+
const code = (body as { error?: { code?: unknown } } | null)?.error?.code;
|
|
211
|
+
throw new ModelRequestError(`The title service returned HTTP ${response.status}.`, response.status, {
|
|
212
|
+
...(wait === undefined ? {} : { retryAfterMs: wait }),
|
|
213
|
+
...(typeof code === "string" ? { code } : {}), // "insufficient_quota" makes it a quota: not sent again
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
return String((body as { title?: unknown } | null)?.title ?? "");
|
|
217
|
+
}, {
|
|
218
|
+
retry: { retries: 2 },
|
|
219
|
+
signal,
|
|
220
|
+
onRetry: ({ attempt, delayMs }) => console.warn(`Title request failed: retry ${attempt} in ${Math.round(delayMs)} ms`),
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Two more options: `canRetry`, a function that returns false once the attempt did something that
|
|
226
|
+
must not happen twice (the loop uses it for text that was shown), and `unknownErrors: "once"`,
|
|
227
|
+
which tries an error without a status once more, at once (the part reads use it).
|
|
228
|
+
|
|
229
|
+
## Waits on a silent model
|
|
230
|
+
|
|
231
|
+
Each adapter watches a chat request for silence. `firstByteTimeoutMs` (600 s) bounds the wait for
|
|
232
|
+
the first piece of a reply, headers not counted, and `idleTimeoutMs` (300 s) the gap between two
|
|
233
|
+
pieces, keep-alives counted; 0 waits without end
|
|
234
|
+
([`IdleWaits`](../reference/errors-and-retries.md#idlewaits)).
|
|
235
|
+
|
|
236
|
+
They are options of `gemini()`, `askGemini`, `openAiCompatible()` and `anthropic()`. The first wait
|
|
237
|
+
is long because a model that thinks sends nothing while it does (Gemini without its thoughts,
|
|
238
|
+
OpenAI's reasoning models), and a reply that is not streamed arrives whole at the end: on Gemini and
|
|
239
|
+
OpenAI-compatible endpoints any request without `onText` (an explorer's among them); on Gemini also
|
|
240
|
+
any request to an endpoint without a `streamUrl`; on OpenAI-compatible endpoints also any with
|
|
241
|
+
`stream: false` or from a gateway that answers without a stream; on Claude only with `stream: false`
|
|
242
|
+
or from a gateway that answers without a stream. A reply that keeps arriving has no time limit.
|
|
243
|
+
|
|
244
|
+
When a wait runs out, the adapter aborts the request and throws its error, with status 0 and kind
|
|
245
|
+
`timeout`: "Gemini sent nothing for 600 s.", "The model sent nothing for 600 s." (OpenAI-compatible)
|
|
246
|
+
or "Claude sent nothing for 600 s.". The loop sends it again once, unless text of it was shown or
|
|
247
|
+
`retries` is 0, and then throws it.
|
|
248
|
+
|
|
249
|
+
```ts
|
|
250
|
+
import { askGemini, gemini } from "llm-large-files/gemini";
|
|
251
|
+
import { anthropic } from "llm-large-files/anthropic";
|
|
252
|
+
|
|
253
|
+
// A model that does not think long: fail sooner than the defaults.
|
|
254
|
+
const answer = await askGemini({ files, endpoint, documentIds, messages, owner, firstByteTimeoutMs: 120_000, idleTimeoutMs: 60_000 });
|
|
255
|
+
|
|
256
|
+
// The same options on an adapter, for askWithFiles.
|
|
257
|
+
const model = gemini(endpoint, { firstByteTimeoutMs: 120_000, idleTimeoutMs: 60_000 });
|
|
258
|
+
const claude = anthropic({ model: "claude-opus-5-5", apiKey: process.env.ANTHROPIC_API_KEY, idleTimeoutMs: 120_000 });
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
These waits are for one request. A proxy between your server and your user may cut a stream that
|
|
262
|
+
is quiet for less: see [Deployment](./deployment.md).
|
|
263
|
+
|
|
264
|
+
### Part reads have a time limit of their own
|
|
265
|
+
|
|
266
|
+
The waits cover chat requests. Each request of a whole-file read (a part read) has a limit on its
|
|
267
|
+
whole time instead: `timeoutMs` of `openAiCompatible()` and `anthropic()`, 180,000 by default. For
|
|
268
|
+
Gemini it is 180 s, and neither `gemini()` nor `askGemini` has an option for it. A part read that
|
|
269
|
+
runs out of time is tried once more, at once. If it fails again, the tool's result says the part
|
|
270
|
+
could not be read (`parts_that_failed`), and the question goes on.
|
|
271
|
+
|
|
272
|
+
To give Gemini part reads more time, replace the adapter's `generateText` and call
|
|
273
|
+
`askWithFiles`:
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import { askWithFiles, type ModelAdapter } from "llm-large-files";
|
|
277
|
+
import { createGeminiGenerateText, gemini } from "llm-large-files/gemini";
|
|
278
|
+
|
|
279
|
+
const patient: ModelAdapter = {
|
|
280
|
+
...gemini(endpoint),
|
|
281
|
+
// Each part read may take 5 minutes.
|
|
282
|
+
generateText: createGeminiGenerateText({ url: endpoint.url, headers: endpoint.headers, timeoutMs: 300_000 }),
|
|
283
|
+
};
|
|
284
|
+
const result = await askWithFiles({ files, model: patient, documentIds, messages, owner });
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
`analysisConfig` of `gemini()` is `generationConfig` here, if you set one. With an
|
|
288
|
+
[explorer model](./explorer-model.md), the part reads are the explorer's: replace its
|
|
289
|
+
`generateText`.
|
|
290
|
+
|
|
291
|
+
## An overall deadline
|
|
292
|
+
|
|
293
|
+
A question has no time limit of its own. It makes up to `limits.toolTurns` (12) answered chat
|
|
294
|
+
requests, plus up to three that the provider refused as too large and the loop recovered from (see
|
|
295
|
+
[A request too large for the model](#a-request-too-large-for-the-model)). Each may wait
|
|
296
|
+
`firstByteTimeoutMs` twice and be tried up to 4 times, and a whole-file read adds its part reads. To bound the time your user waits, pass a `signal` that aborts at your deadline,
|
|
297
|
+
joined with one that aborts when the user leaves:
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
import type { ServerResponse } from "node:http";
|
|
301
|
+
import { askGemini } from "llm-large-files/gemini";
|
|
302
|
+
|
|
303
|
+
export async function ask(response: ServerResponse): Promise<string | undefined> {
|
|
304
|
+
const userLeft = new AbortController();
|
|
305
|
+
response.on("close", () => userLeft.abort());
|
|
306
|
+
const deadline = AbortSignal.timeout(15 * 60_000); // 15 minutes for the whole question: above firstByteTimeoutMs (10 minutes)
|
|
307
|
+
|
|
308
|
+
try {
|
|
309
|
+
const result = await askGemini({ files, endpoint, documentIds, messages, owner, signal: AbortSignal.any([userLeft.signal, deadline]) });
|
|
310
|
+
return result.text;
|
|
311
|
+
} catch (error) {
|
|
312
|
+
if (deadline.aborted) return "The question took too long. Ask again, or ask about less.";
|
|
313
|
+
if (userLeft.signal.aborted) return undefined; // nobody is waiting for the answer
|
|
314
|
+
throw error;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
When the signal aborts, the request under way stops, the tool calls of the turn stop, and nothing
|
|
320
|
+
more is sent or sent again, no further part of a whole-file read either. The question stops at
|
|
321
|
+
once, even with an adapter of your own, or a part reader, that does not look at the signal: the
|
|
322
|
+
loop no longer waits for it, and text that such an adapter sends later is not shown. The question
|
|
323
|
+
throws the signal's reason: a `DOMException` named "TimeoutError" for `AbortSignal.timeout`, a
|
|
324
|
+
`DOMException` named "AbortError" for `controller.abort()`, and your reason for
|
|
325
|
+
`controller.abort(reason)`. It does so also when the adapter then fails at once with its own error.
|
|
326
|
+
When the abort comes just after a request failed, that request's error may be thrown instead. So
|
|
327
|
+
test which signal aborted, as above, not the error.
|
|
328
|
+
|
|
329
|
+
`partialResultOf(error)` works for a stopped question too, when the reason is an object. Abort with
|
|
330
|
+
an `Error`, or with no reason, rather than a string. Its `usage` is what was counted when the
|
|
331
|
+
question stopped: a request still running then, in an adapter that did not stop, may be billed by
|
|
332
|
+
the provider, and is not counted.
|
|
333
|
+
|
|
334
|
+
How the client side cancels a streamed answer is in [Web app](./web-app.md).
|
|
335
|
+
|
|
336
|
+
## A request too large for the model
|
|
337
|
+
|
|
338
|
+
When the provider refuses a request as larger than the model takes (kind `context_overflow`), the
|
|
339
|
+
loop does not give up at once. The same holds for a request larger than the tokens the provider
|
|
340
|
+
lets through in a minute (OpenAI's and Groq's TPM, or a day's allowance): that allowance then
|
|
341
|
+
stands for the window.
|
|
342
|
+
|
|
343
|
+
1. It takes the provider's count and window for the rest of the question, replaces tool results
|
|
344
|
+
with stand-ins (those of all but the last three tool rounds, then all but the last two, then all
|
|
345
|
+
but the last one, then all of them, as far as needed), and sends the request again, at most
|
|
346
|
+
twice in a question. The step says "The request was larger than the model takes: older tool
|
|
347
|
+
results were shortened, and it was sent again", or for an allowance, "The request was larger
|
|
348
|
+
than the provider allows in a minute: older tool results were shortened, and it was sent again".
|
|
349
|
+
2. When shortening does not help (nothing is left to shorten, a model of the question may only grow
|
|
350
|
+
its conversation, such as Claude, or the request sent again shorter was refused again), and no
|
|
351
|
+
tool call of this question was answered and no text shown yet, it plans
|
|
352
|
+
the documents again for a smaller window and starts over, once. A document that was sent whole
|
|
353
|
+
may now be searched instead. The step says "The first request was larger than the model's
|
|
354
|
+
window of 131,072 tokens: the files were planned again to fit it", or "…for a smaller window".
|
|
355
|
+
For an allowance it says "The first request was larger than the 30,000 tokens a minute that the
|
|
356
|
+
provider allows: the files were planned again to fit it", or, when the message gives no limit,
|
|
357
|
+
"The first request was larger than the provider allows in a minute: the files were planned again
|
|
358
|
+
for a smaller request" ("a day" for an allowance per day).
|
|
359
|
+
What the first try used counts in `usage` and against `limits`.
|
|
360
|
+
3. Otherwise it throws the error, with `partialResultOf`.
|
|
361
|
+
|
|
362
|
+
How the smaller window is worked out from the provider's numbers is in
|
|
363
|
+
[How it works](../how-it-works.md#a-request-too-large-for-the-model).
|
|
364
|
+
|
|
365
|
+
A part of a whole-file read that the model refuses as too large, for its window or for the minute's
|
|
366
|
+
allowance, is read as two halves, inside the tool. It does not throw. A refusal of a part that asked
|
|
367
|
+
for the larger output limit of a thinking model (32,768 tokens) turns that limit off for the model
|
|
368
|
+
only when the window, or the allowance, is no larger than it; otherwise later parts may still get
|
|
369
|
+
it.
|
|
370
|
+
|
|
371
|
+
When the error reaches you, one of these is the cause:
|
|
372
|
+
|
|
373
|
+
- **The conversation is too long.** The library does not shorten the text turns of the history.
|
|
374
|
+
Drop old turns, or start a new chat. See [Conversations](./conversations.md).
|
|
375
|
+
- **The model's window is smaller than the budget assumes** (1,000,000 tokens by default). Give the
|
|
376
|
+
adapter its `contextTokens`, so every question is planned for it. A gateway whose body limit is
|
|
377
|
+
below 10 MB answers 413: give the adapter its `maxRequestBytes`. `askGemini` has neither option:
|
|
378
|
+
set them in the budget instead, `createLargeFiles({ store, budget: { contextTokens: 128_000,
|
|
379
|
+
maxRequestBytes: 8_000_000 } })`, or in `budget` of `askGemini` for one question. See
|
|
380
|
+
[Costs and limits](./costs-and-limits.md).
|
|
381
|
+
- **The question names too many documents.** Ask about fewer.
|
|
382
|
+
- **The provider lets through fewer tokens a minute than a request needs** (OpenAI's TPM on a low
|
|
383
|
+
tier, Groq's free tier). `limitTokens` is that allowance. Give the adapter a `contextTokens` below
|
|
384
|
+
it, or ask the provider for a higher limit.
|
|
385
|
+
- **The provider's wording is not known**, and the error came as `invalid`. See
|
|
386
|
+
[The kind of a model error](#the-kind-of-a-model-error).
|
|
387
|
+
|
|
388
|
+
## Empty or broken turns
|
|
389
|
+
|
|
390
|
+
In the tool loop (when a document is searched rather than sent whole, or a PDF's pages can be
|
|
391
|
+
looked at), two kinds of reply are asked for once more, with a short note at the end of the request
|
|
392
|
+
that says what was wrong:
|
|
393
|
+
|
|
394
|
+
- **A tool call that could not be read**: Gemini's `MALFORMED_FUNCTION_CALL` or
|
|
395
|
+
`UNEXPECTED_TOOL_CALL`. The step says "The model's tool call could not be read: it was asked to
|
|
396
|
+
send it again".
|
|
397
|
+
- **A first reply with nothing in it**: no text and no tool call, before any tool call of the
|
|
398
|
+
question was answered, and not cut off at the output limit or stopped by a filter. The step says
|
|
399
|
+
"The model's first reply was empty: it was asked again".
|
|
400
|
+
|
|
401
|
+
Without the second try, the answer would be written from the document cards alone and look like any
|
|
402
|
+
other. At most two such second tries are made in a question, and each takes one of
|
|
403
|
+
`limits.toolTurns`. When they are made, and which model keeps the note, is in
|
|
404
|
+
[How it works](../how-it-works.md#empty-or-broken-turns). When the second try is empty too, the
|
|
405
|
+
loop asks for the answer, as it does at the end of every question.
|
|
406
|
+
|
|
407
|
+
**The answer's second try.** The request for the answer (`toolChoice: "none"`) is asked for once
|
|
408
|
+
more when its reply has no text: when it is empty, or holds a tool call the model was told not to
|
|
409
|
+
make (Gemini's `UNEXPECTED_TOOL_CALL` or `MALFORMED_FUNCTION_CALL`, or calls from an adapter of
|
|
410
|
+
your own). The note at the end of that request is "Your last reply had no text. No tool can be
|
|
411
|
+
called in this reply: write the answer now, in text, from what is above.", and it is not kept. The
|
|
412
|
+
step says "The model's answer was empty: it was asked again", or "The model called a tool instead
|
|
413
|
+
of answering: it was asked again for the answer". It is one of the two second tries of the
|
|
414
|
+
question, and it can be one request past `limits.toolTurns`. It is not made after a refusal, a
|
|
415
|
+
filter, or a reply cut off at the output limit with nothing in it, nor once `limits.requests` or
|
|
416
|
+
`limits.inputTokens` is reached. When its reply has no text either, `answered` is false.
|
|
417
|
+
|
|
418
|
+
A single call that cannot be run is not a broken turn: arguments that are not a JSON object, a call
|
|
419
|
+
cut off at the output limit, a Claude call whose block never closed. It is answered with an error
|
|
420
|
+
that says why and asks the model to send it again, and the other calls of the turn run. A turn with
|
|
421
|
+
more calls than `limits.callsPerTurn` (8) runs the first 8 and answers the others "Not run: one turn
|
|
422
|
+
runs at most 8 tool calls. Send this call again if you still need it."
|
|
423
|
+
|
|
424
|
+
## A stream cut off
|
|
425
|
+
|
|
426
|
+
A streamed reply ends with the provider's word for why it ended: a `finishReason` in Gemini's last
|
|
427
|
+
chunk, a `finish_reason` or `[DONE]` in an OpenAI-compatible stream, a `stop_reason` in Claude's. A
|
|
428
|
+
stream that closes without it was cut off on its way, by a proxy or a dropped connection. The
|
|
429
|
+
adapter does not take it for a whole reply: it throws an error with status 0, of kind
|
|
430
|
+
`unreachable`: "Gemini's reply ended before it was complete.", "The model's reply ended before it
|
|
431
|
+
was complete." or "Claude's reply ended before it was complete.". A connection that fails while the
|
|
432
|
+
reply arrives is the same, and so is a reply of HTTP 200 whose body is empty.
|
|
433
|
+
|
|
434
|
+
A stream that said it is whole (`[DONE]` on an OpenAI-compatible stream, `message_stop` on
|
|
435
|
+
Claude's) has its reply, whatever the connection does next. The body is read for one more second
|
|
436
|
+
at most, then cancelled, which closes the connection: a server or gateway that leaves it open does
|
|
437
|
+
not hold the request until `idleTimeoutMs`. A connection that breaks after the end marker loses
|
|
438
|
+
nothing either. 0.5.0 waited for such a connection to close, and took one that broke for a model
|
|
439
|
+
that could not be reached, with the whole answer already shown.
|
|
440
|
+
|
|
441
|
+
A reply asked for as a stream is read as one when its content type is `text/event-stream`. Of any
|
|
442
|
+
other type (a gateway that streams under `application/octet-stream`, or under none), it is read by
|
|
443
|
+
its first characters: as events when it starts with `data:` or a comment, as JSON when it starts
|
|
444
|
+
with `{` or `[` (Gemini's chunks in a list, as it sends them without `alt=sse`). A body that starts
|
|
445
|
+
with more than 65,536 characters of white space is read as JSON, whatever follows. A body that is
|
|
446
|
+
neither, such as an HTML page, is a reply that is not JSON: kind `invalid`, status 200, not sent
|
|
447
|
+
again. One event of a stream may hold 64,000,000 characters at most; a longer one ends the reply
|
|
448
|
+
with kind `invalid` and status 200, and is not sent again: it would come again.
|
|
449
|
+
|
|
450
|
+
An error the provider sends inside a stream that began with HTTP 200 takes the status the error
|
|
451
|
+
names, and is sent again or not by that status:
|
|
452
|
+
|
|
453
|
+
- On Gemini, its `code`. An error without one keeps the stream's 200, and is not sent again.
|
|
454
|
+
- On an OpenAI-compatible stream, its `code` or `type`: `context_length_exceeded` is 400 (kind
|
|
455
|
+
`context_overflow`), `insufficient_quota` 429 (kind `quota`), and `code` and `param` stay on the
|
|
456
|
+
error. One that names no status the adapter knows counts as a 500.
|
|
457
|
+
- On Claude, its `type`: `overloaded_error` 529, `rate_limit_error` 429, `api_error` 500,
|
|
458
|
+
`timeout_error` 408, `invalid_request_error` 400, `authentication_error` 401, `billing_error`
|
|
459
|
+
402, `permission_error` 403, `not_found_error` 404, `request_too_large` 413 (kind
|
|
460
|
+
`context_overflow`). A type the adapter does not know is the server's failure, 500.
|
|
461
|
+
|
|
462
|
+
What happens next depends on what your user saw:
|
|
463
|
+
|
|
464
|
+
- **Nothing of that reply was passed to `onText`**: a turn of tool calls, an explorer's request, a
|
|
465
|
+
request without `onText`, a reply that failed before its first word. It is sent again, by the
|
|
466
|
+
retry rule.
|
|
467
|
+
- **Text of it was shown**: it is not sent again, since a second reply would repeat or contradict
|
|
468
|
+
what is on the screen. The error is thrown, and `partialResultOf(error).text` is the text that
|
|
469
|
+
was shown.
|
|
470
|
+
|
|
471
|
+
So in your UI, keep the text that arrived, mark it as cut off, and offer to ask again. This holds
|
|
472
|
+
for every error after the first word of an answer, not only for a cut stream.
|
|
473
|
+
|
|
474
|
+
## Failures inside tools
|
|
475
|
+
|
|
476
|
+
The tools answer the model, not you. When a call fails, its result is `{ error: "…" }`, and the
|
|
477
|
+
model reads it and tries another way: a regex that does not compile, a page past the end of a PDF
|
|
478
|
+
(`view_pages`), a store that did not answer ("The document store could not be read (EIO). Try again."), a whole-file read
|
|
479
|
+
whose parts all failed. The question goes on, and can still be answered. A failed call shows:
|
|
480
|
+
|
|
481
|
+
- in `steps`, as a line that ends in " — failed: " and the error;
|
|
482
|
+
- in `toolTurns`, as a call whose `result.error` is a string;
|
|
483
|
+
- not in `evidence`, which lists only what was shown.
|
|
484
|
+
|
|
485
|
+
A whole-file read tells the model why a model request failed by the error's kind, its HTTP status
|
|
486
|
+
or the code of a connection that failed, never by the error's words: the provider's message, or an
|
|
487
|
+
HTTP client's, can name a project, a host, a masked key, or a URL with a key in it. The same words
|
|
488
|
+
are in its step and in `toolTurns`: "Read all of app.log for “Summarize.” — failed: Could not read
|
|
489
|
+
any part of app.log: The model refused the key or token it was sent (HTTP 401)." The reasons:
|
|
490
|
+
|
|
491
|
+
| The error | The reason |
|
|
492
|
+
|---|---|
|
|
493
|
+
| A reply with no text, from a part reader of the package | "The model returned no text (SAFETY).", with the provider's reason when it is a plain word, or "The model returned no text." |
|
|
494
|
+
| An error with a `kind` (the package's adapters set one) | By its kind, with " (HTTP n)" when it has a status: "The request was larger than the model takes", "The model's quota has run out", "The model was busy", "The model took too long to answer", "The model could not be reached", "The model failed on its side", "The model refused the key or token it was sent", "The model refused the request". Kind `invalid` with a status of success: "The model's reply could not be read (HTTP 200)." |
|
|
495
|
+
| An error with an HTTP status and no kind (`status`, `statusCode` or `response.status`, as a provider's SDK, got and axios set them) | Its kind is told from its status and message, as `classifyModelError` does, and the reason follows from it: "The model failed on its side (HTTP 503)." |
|
|
496
|
+
| An error whose `code`, or that of its `cause`, is that of a connection that failed (`ECONNREFUSED`, `ENOTFOUND`, undici's `UND_ERR_SOCKET`…) | "The model could not be reached." |
|
|
497
|
+
| An error named `TimeoutError` (an `AbortSignal.timeout`, or a part reader's `timeoutMs`), or undici's `UND_ERR_HEADERS_TIMEOUT` and `UND_ERR_BODY_TIMEOUT` | "The model took too long to answer." |
|
|
498
|
+
| Anything else: a plain `Error` of a `generate` of your own, a thrown string | "The model request failed." ("The model request failed (HTTP 302)." for a status from 100 to 399) |
|
|
499
|
+
|
|
500
|
+
These reasons go into "Could not read any part of app.log: …", "[This part could not be read: …]",
|
|
501
|
+
the note of a read whose last step failed (`notes_only`), and "The whole-file read of app.log failed
|
|
502
|
+
earlier in this question (…)". A failure to read a part's lines from the store keeps the store's
|
|
503
|
+
own message, which names no path or host: "The document store could not be read (EIO). Try again."
|
|
504
|
+
The provider's words belong in your log: log them in your own `fetch`, adapter or `generate`. To
|
|
505
|
+
give the model a specific reason from a `generate` of your own, throw an error with a `kind` or an
|
|
506
|
+
HTTP `status`.
|
|
507
|
+
|
|
508
|
+
A whole-file read that worked in part says so in its result (`parts_that_failed`, `notes_only`,
|
|
509
|
+
`notes_cut_short`, `answer_cut_short`). Its step ends in ", notes only" when the answer is only the
|
|
510
|
+
notes of the parts, and otherwise in ", incomplete" when notes or the answer were cut short. A read
|
|
511
|
+
that only lost parts has no such mark: its step ends in " — 12 parts, 3 relevant" as a complete
|
|
512
|
+
read's does, the failed parts among the 12. Look for `parts_that_failed` in its result in
|
|
513
|
+
`toolTurns`.
|
|
514
|
+
|
|
515
|
+
Most failed calls are the model's own mistakes, which it mends in its next turn. To see trouble on
|
|
516
|
+
your side, such as a store that fails often, log them:
|
|
517
|
+
|
|
518
|
+
```ts
|
|
519
|
+
// result: what askWithFiles or askGemini returned.
|
|
520
|
+
const failed = result.toolTurns.flatMap((turn) => turn.calls).filter((call) => typeof call.result.error === "string");
|
|
521
|
+
for (const call of failed) console.warn(`Tool ${call.name} failed: ${String(call.result.error)}`);
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
## When there is no answer: `answered` and `finishReason`
|
|
525
|
+
|
|
526
|
+
A question can end without an error and without an answer. `answered` is false when the model's
|
|
527
|
+
last turn had no text:
|
|
528
|
+
|
|
529
|
+
- **The provider refused the prompt.** `blockReason` says why: Gemini's `promptFeedback.blockReason`
|
|
530
|
+
(such as "SAFETY"), "refusal" or "refusal: " and its category for Claude, "content_filter" for an
|
|
531
|
+
OpenAI-compatible reply that was filtered with nothing in it. Nothing more is asked after it.
|
|
532
|
+
- **The last reply ended without text**: cut off at the output limit before its first word, stopped
|
|
533
|
+
by a filter, or an answer with no text (empty, or a tool call) after its one second try.
|
|
534
|
+
|
|
535
|
+
`text` may then be empty, hold only a remark the model wrote before a tool call, or the start of a
|
|
536
|
+
reply the provider then refused. Show your own message instead.
|
|
537
|
+
|
|
538
|
+
`finishReason` is the provider's own word for how the last chat reply ended: "STOP", "MAX_TOKENS"
|
|
539
|
+
or "SAFETY" from Gemini, "stop", "length" or "content_filter" from an OpenAI-compatible server,
|
|
540
|
+
"end_turn", "max_tokens" or "refusal" from Claude. An answer can be `answered: true` and still be
|
|
541
|
+
cut off at the output limit. Tell the user, or raise the model's output limit (`maxOutputTokens` in
|
|
542
|
+
Gemini's `generationConfig`, the limit in `body` of `openAiCompatible()`, `maxTokens` of
|
|
543
|
+
`anthropic()`). Claude's `model_context_window_exceeded` means its window filled: shorten the chat
|
|
544
|
+
rather than raise the output limit.
|
|
545
|
+
|
|
546
|
+
```ts
|
|
547
|
+
import type { AskResult } from "llm-large-files";
|
|
548
|
+
|
|
549
|
+
/** The words of the output limit, as each provider says them. */
|
|
550
|
+
const CUT_OFF = new Set(["MAX_TOKENS", "length", "max_tokens"]);
|
|
551
|
+
|
|
552
|
+
export function shownAnswer(result: AskResult): { text: string; note?: string } {
|
|
553
|
+
if (!result.answered) {
|
|
554
|
+
return { text: result.blockReason ? "This question was blocked by the model's safety filters." : "No answer this time. Ask again, or ask more precisely." };
|
|
555
|
+
}
|
|
556
|
+
if (result.finishReason === "model_context_window_exceeded") {
|
|
557
|
+
return { text: result.text, note: "The answer was cut off: the chat filled the model's window." };
|
|
558
|
+
}
|
|
559
|
+
if (result.finishReason !== undefined && CUT_OFF.has(result.finishReason)) {
|
|
560
|
+
return { text: result.text, note: "The answer was cut off at the model's output limit." };
|
|
561
|
+
}
|
|
562
|
+
return { text: result.text };
|
|
563
|
+
}
|
|
564
|
+
```
|
|
565
|
+
|
|
566
|
+
## Keeping what a failed question found
|
|
567
|
+
|
|
568
|
+
`askWithFiles` throws the error as it came, and what the question did until then is not lost.
|
|
569
|
+
`partialResultOf(error)` gives an `AskResult` with `answered: false`: the `steps`, `evidence`,
|
|
570
|
+
`toolTurns`, `usage` and `turns` of the question so far, its `plan` and `budget`, and the `text`
|
|
571
|
+
that was shown. The requests in `usage` were paid for: count them. Keep the tool rounds as you keep
|
|
572
|
+
those of an answered question (see [Conversations](./conversations.md)), so that asking again does
|
|
573
|
+
not search again.
|
|
574
|
+
|
|
575
|
+
It is undefined for an error that did not come from a question under way: `DocumentsNotFoundError`,
|
|
576
|
+
a `DocumentStoreError` while the documents were planned, a budget that cannot work, a last message
|
|
577
|
+
that is not the user's, and an abort whose reason is a string.
|
|
578
|
+
|
|
579
|
+
```ts
|
|
580
|
+
import { askWithFiles, partialResultOf, type ModelAdapter } from "llm-large-files";
|
|
581
|
+
|
|
582
|
+
// recordUsage and keepToolTurns are your app's own: usage per user, tool rounds per chat session.
|
|
583
|
+
export async function askAndRecord(model: ModelAdapter, sessionId: string) {
|
|
584
|
+
try {
|
|
585
|
+
const result = await askWithFiles({ files, model, documentIds, messages, owner });
|
|
586
|
+
await recordUsage(owner, result.usage);
|
|
587
|
+
await keepToolTurns(sessionId, result.toolTurns);
|
|
588
|
+
return result;
|
|
589
|
+
} catch (error) {
|
|
590
|
+
const partial = partialResultOf(error);
|
|
591
|
+
if (partial) {
|
|
592
|
+
await recordUsage(owner, partial.usage);
|
|
593
|
+
await keepToolTurns(sessionId, partial.toolTurns);
|
|
594
|
+
}
|
|
595
|
+
throw error;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
## Errors of uploads and of the store
|
|
601
|
+
|
|
602
|
+
`files.ingest` throws a plain `Error`, with a message written for the user, when it cannot take a
|
|
603
|
+
file: it is empty, larger than `maxUploadBytes` (100 MB by default), has no text, is a gzip or ZIP
|
|
604
|
+
archive, is binary, needs an optional dependency that is not installed (`jszip` for DOCX and PPTX,
|
|
605
|
+
`unpdf` for PDF) or an `unpdf` that runs on this Node, or is a PDF without a text layer (see
|
|
606
|
+
[PDFs](./pdfs.md)). Show its message. A text file is never refused for its encoding: one that is
|
|
607
|
+
not UTF-8 is read in the encoding it was saved in, or as UTF-8 with the characters that are not
|
|
608
|
+
valid counted ([Text encodings](./pdfs.md#text-encodings)).
|
|
609
|
+
|
|
610
|
+
It throws a `TypeError` for an owner of `""`, spaces only or `null`: a mistake of your code, not of
|
|
611
|
+
the file. `createDocumentHandlers` answers it 500 `{ "error": "Upload failed (empty owner)." }`, or
|
|
612
|
+
`{ "error": "Upload failed (owner is not a string)." }` for an owner that is neither a string nor a
|
|
613
|
+
finite number, before it reads the upload ([Storage](./storage.md#how-ownership-works)).
|
|
614
|
+
|
|
615
|
+
A file the parser cannot read (a damaged DOCX, PPTX or PDF) throws the parser's own error (jszip's,
|
|
616
|
+
or pdf.js's `InvalidPDFException`), and an extractor of your own throws its own. Their messages are
|
|
617
|
+
not written for users: show "This file could not be read." for an error whose message you do not
|
|
618
|
+
recognise.
|
|
619
|
+
|
|
620
|
+
A store that fails while it writes throws its own error, as it came: its message may name a path or
|
|
621
|
+
a host, so log it and show a general message. `createDocumentHandlers` answers a file it cannot take
|
|
622
|
+
with 422 and the error's message, and a Node system error of the store (one with a `code` and a
|
|
623
|
+
`syscall`) with 500 and only its code ("Upload failed (ENOSPC)."). Any other store error, one
|
|
624
|
+
without a `status` (or `statusCode`) from 400 to 599, is answered 500 "Upload failed.", without its
|
|
625
|
+
message, and so is a thrown value that is not an `Error`. The handlers log nothing: log the error in
|
|
626
|
+
your store before you throw it. Two paths still answer a store's error 422 with its message, which
|
|
627
|
+
may name a host: an `ingest` of your own that throws a new error in its place, as `ingestInProcess`
|
|
628
|
+
in [Deployment](./deployment.md#uploads-and-ingest) does, and a route of your own, as in
|
|
629
|
+
[Web app](./web-app.md#filesingest-and-its-errors). So a custom store should throw an error with a
|
|
630
|
+
`status` and a message fit for the user (both are sent as they are): every path keeps that status.
|
|
631
|
+
See [the node reference](../reference/node.md#uploadrequest-response).
|
|
632
|
+
|
|
633
|
+
Every read of the store goes through the library: `prepare`, `getMeta`, `getOriginal`, the tools.
|
|
634
|
+
What the store throws there becomes a `DocumentStoreError`, which does not mean the document is
|
|
635
|
+
gone. A store's own `delete` and `sweep` pass on its error as it came. A document that is gone, or
|
|
636
|
+
of another owner, is not an error of the store: `prepare` lists it in `missing`, and `askWithFiles`
|
|
637
|
+
throws `DocumentsNotFoundError` for it. What a store must do is in [Storage](./storage.md).
|
|
638
|
+
|
|
639
|
+
## Putting it together: a chat route
|
|
640
|
+
|
|
641
|
+
A route that answers a question in one JSON response, and turns each error into a status and a
|
|
642
|
+
message. Call `answerChat` from your route once the user is signed in and the body is read: `owner`
|
|
643
|
+
is the user, and `messages` and `documentIds` come from your chat session.
|
|
644
|
+
|
|
645
|
+
```ts
|
|
646
|
+
import type { ServerResponse } from "node:http";
|
|
647
|
+
import { DocumentsNotFoundError, DocumentStoreError, errorKindOf, ModelRequestError, partialResultOf, type ToolTurn } from "llm-large-files";
|
|
648
|
+
import { askGemini, type ChatTurn } from "llm-large-files/gemini";
|
|
649
|
+
|
|
650
|
+
type Failure = { status: number; message: string; retryAfterSeconds?: number };
|
|
651
|
+
|
|
652
|
+
/** What to tell the user about an error of a question, and the HTTP status to answer with. */
|
|
653
|
+
export function toUserError(error: unknown): Failure {
|
|
654
|
+
if (error instanceof DocumentsNotFoundError) {
|
|
655
|
+
return { status: 404, message: "A file of this chat is no longer available. Attach it again." };
|
|
656
|
+
}
|
|
657
|
+
if (error instanceof DocumentStoreError) {
|
|
658
|
+
return { status: 503, message: "Your files could not be read just now. Try again in a moment." };
|
|
659
|
+
}
|
|
660
|
+
switch (errorKindOf(error)) {
|
|
661
|
+
case "context_overflow":
|
|
662
|
+
return { status: 413, message: "This chat is too long for the model. Start a new chat, or ask about fewer files." };
|
|
663
|
+
case "rate_limit": {
|
|
664
|
+
const wait = error instanceof ModelRequestError ? error.retryAfterMs : undefined;
|
|
665
|
+
return { status: 429, message: "The assistant is busy. Try again in a minute.", ...(wait ? { retryAfterSeconds: Math.ceil(wait / 1_000) } : {}) };
|
|
666
|
+
}
|
|
667
|
+
case "quota":
|
|
668
|
+
return { status: 503, message: "The assistant is not available right now." };
|
|
669
|
+
case "timeout":
|
|
670
|
+
return { status: 504, message: "The model took too long to answer. Try again." };
|
|
671
|
+
case "unreachable":
|
|
672
|
+
case "server":
|
|
673
|
+
return { status: 502, message: "The model could not answer just now. Try again." };
|
|
674
|
+
default:
|
|
675
|
+
// auth, invalid, and errors without a kind: your configuration or your code.
|
|
676
|
+
return { status: 500, message: "Something went wrong on our side. Try again later." };
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
export async function answerChat(response: ServerResponse, question: { owner: string; messages: Array<ChatTurn | ToolTurn>; documentIds: string[] }): Promise<void> {
|
|
681
|
+
const send = (status: number, value: unknown, headers: Record<string, string> = {}) => {
|
|
682
|
+
response.writeHead(status, { "Content-Type": "application/json", ...headers }).end(JSON.stringify(value));
|
|
683
|
+
};
|
|
684
|
+
const userLeft = new AbortController();
|
|
685
|
+
response.on("close", () => userLeft.abort());
|
|
686
|
+
const deadline = AbortSignal.timeout(15 * 60_000);
|
|
687
|
+
|
|
688
|
+
try {
|
|
689
|
+
const result = await askGemini({ files, endpoint, ...question, signal: AbortSignal.any([userLeft.signal, deadline]) });
|
|
690
|
+
if (!result.answered) {
|
|
691
|
+
const message = result.blockReason ? "This question was blocked by the model's safety filters." : "No answer this time. Ask again, or ask more precisely.";
|
|
692
|
+
send(200, { answered: false, message });
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
send(200, { answered: true, text: result.text });
|
|
696
|
+
} catch (error) {
|
|
697
|
+
// What a failed question used was paid for: count it with the user's usage.
|
|
698
|
+
const partial = partialResultOf(error);
|
|
699
|
+
if (partial) console.info(`A failed question of ${question.owner} used`, partial.usage);
|
|
700
|
+
if (deadline.aborted) {
|
|
701
|
+
send(504, { error: "The question took too long. Ask again, or ask about less." });
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
if (userLeft.signal.aborted) return; // nobody is waiting for the answer
|
|
705
|
+
// The provider's own message is for your log, not for the user.
|
|
706
|
+
console.error("A question failed", error);
|
|
707
|
+
const failure = toUserError(error);
|
|
708
|
+
send(
|
|
709
|
+
failure.status,
|
|
710
|
+
{ error: failure.message, ...(error instanceof DocumentsNotFoundError ? { missing: error.ids } : {}) },
|
|
711
|
+
failure.retryAfterSeconds ? { "Retry-After": String(failure.retryAfterSeconds) } : {},
|
|
712
|
+
);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
```
|
|
716
|
+
|
|
717
|
+
With a streamed answer (Server-Sent Events), the status 200 is sent before the first word, and an
|
|
718
|
+
error cannot change it. Send the same message in an error event instead, and when
|
|
719
|
+
`partialResultOf(error)?.text` is not empty, say that the answer above it is incomplete. The events,
|
|
720
|
+
progress and cancelling are in [Web app](./web-app.md).
|
|
721
|
+
|
|
722
|
+
To see how your route handles each error without calling a real model, give it an adapter that
|
|
723
|
+
throws them: see [Testing](./testing.md).
|
|
724
|
+
|
|
725
|
+
## Reference
|
|
726
|
+
|
|
727
|
+
- [Errors, retries and streams](../reference/errors-and-retries.md): `ModelRequestError`,
|
|
728
|
+
`ModelErrorKind`, `classifyModelError`, `errorKindOf`, `withRetry`, `RetryOptions`,
|
|
729
|
+
`RetryNotice`, `isRetryableStatus`, `retryAfterMs`, the default waits.
|
|
730
|
+
- [The tool loop](../reference/ask.md): `askWithFiles`, `AskResult`, `partialResultOf`,
|
|
731
|
+
`DocumentsNotFoundError`.
|
|
732
|
+
- [The library](../reference/library.md): `DocumentStoreError`, `ingest`, `prepare`.
|
|
733
|
+
- The adapters and their options: [Gemini](../reference/gemini.md),
|
|
734
|
+
[OpenAI-compatible](../reference/openai.md), [Claude](../reference/anthropic.md).
|
|
735
|
+
- [Troubleshooting](../troubleshooting.md): symptoms, causes and fixes.
|